code stringlengths 81 54k | code_codestyle int64 0 721 | style_context stringlengths 91 41.9k | style_context_codestyle int64 0 699 | label int64 0 1 |
|---|---|---|---|---|
import 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 _lowercase ( self : List[Any] ) -> Optional[int]:
"""simple docstring"""
__magic_name__ = """hf-internal-testing/tiny-random-t5"""
__magic_name__ = AutoTokenizer.from_pretrained(UpperCamelCase__ )
__magic_name__ = AutoModelForSeqaSeqLM.from_pretrained(UpperCamelCase__ )
__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(**UpperCamelCase__ )
__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(UpperCamelCase__ )
__magic_name__ = AutoModelForSeqaSeqLM.from_pretrained(UpperCamelCase__ )
self.assertFalse(
any("""BetterTransformer""" in mod.__class__.__name__ for _, mod in model_reloaded.named_modules() ) )
__magic_name__ = model_reloaded.generate(**UpperCamelCase__ )
self.assertTrue(torch.allclose(UpperCamelCase__ , UpperCamelCase__ ) )
def _lowercase ( self : int ) -> int:
"""simple docstring"""
__magic_name__ = """hf-internal-testing/tiny-random-t5"""
__magic_name__ = AutoModelForSeqaSeqLM.from_pretrained(UpperCamelCase__ )
__magic_name__ = model.to_bettertransformer()
with tempfile.TemporaryDirectory() as tmpdirname:
with self.assertRaises(UpperCamelCase__ ):
model.save_pretrained(UpperCamelCase__ )
__magic_name__ = model.reverse_bettertransformer()
model.save_pretrained(UpperCamelCase__ )
| 709 |
import functools
import operator
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__lowerCAmelCase : Optional[Any] = logging.get_logger(__name__)
__lowerCAmelCase : List[Any] = {
'asapp/sew-d-tiny-100k': 'https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json',
# See all SEW-D models at https://huggingface.co/models?filter=sew-d
}
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = """sew-d"""
def __init__( self : List[str] , UpperCamelCase__ : Tuple=32 , UpperCamelCase__ : Optional[int]=768 , UpperCamelCase__ : Tuple=12 , UpperCamelCase__ : Optional[Any]=12 , UpperCamelCase__ : int=3072 , UpperCamelCase__ : Tuple=2 , UpperCamelCase__ : List[Any]=512 , UpperCamelCase__ : Any=256 , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : Dict=True , UpperCamelCase__ : str=("p2c", "c2p") , UpperCamelCase__ : List[Any]="layer_norm" , UpperCamelCase__ : int="gelu_python" , UpperCamelCase__ : Optional[int]=0.1 , UpperCamelCase__ : Tuple=0.1 , UpperCamelCase__ : List[Any]=0.1 , UpperCamelCase__ : int=0.0 , UpperCamelCase__ : Dict=0.1 , UpperCamelCase__ : List[Any]=0.02 , UpperCamelCase__ : Optional[int]=1E-7 , UpperCamelCase__ : List[Any]=1E-5 , UpperCamelCase__ : List[str]="group" , UpperCamelCase__ : Optional[int]="gelu" , UpperCamelCase__ : Tuple=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , UpperCamelCase__ : str=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , UpperCamelCase__ : Optional[Any]=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , UpperCamelCase__ : Optional[Any]=False , UpperCamelCase__ : Optional[int]=128 , UpperCamelCase__ : Tuple=16 , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : Dict=0.05 , UpperCamelCase__ : str=10 , UpperCamelCase__ : Tuple=2 , UpperCamelCase__ : Dict=0.0 , UpperCamelCase__ : Dict=10 , UpperCamelCase__ : Union[str, Any]=0 , UpperCamelCase__ : List[Any]="mean" , UpperCamelCase__ : int=False , UpperCamelCase__ : Optional[int]=False , UpperCamelCase__ : Optional[int]=256 , UpperCamelCase__ : List[str]=0 , UpperCamelCase__ : Union[str, Any]=1 , UpperCamelCase__ : List[Any]=2 , **UpperCamelCase__ : str , ) -> Dict:
"""simple docstring"""
super().__init__(**UpperCamelCase__ , pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ )
__magic_name__ = hidden_size
__magic_name__ = feat_extract_norm
__magic_name__ = feat_extract_activation
__magic_name__ = list(UpperCamelCase__ )
__magic_name__ = list(UpperCamelCase__ )
__magic_name__ = list(UpperCamelCase__ )
__magic_name__ = conv_bias
__magic_name__ = num_conv_pos_embeddings
__magic_name__ = num_conv_pos_embedding_groups
__magic_name__ = len(self.conv_dim )
__magic_name__ = num_hidden_layers
__magic_name__ = intermediate_size
__magic_name__ = squeeze_factor
__magic_name__ = max_position_embeddings
__magic_name__ = position_buckets
__magic_name__ = share_att_key
__magic_name__ = relative_attention
__magic_name__ = norm_rel_ebd
__magic_name__ = list(UpperCamelCase__ )
__magic_name__ = hidden_act
__magic_name__ = num_attention_heads
__magic_name__ = hidden_dropout
__magic_name__ = attention_dropout
__magic_name__ = activation_dropout
__magic_name__ = feat_proj_dropout
__magic_name__ = final_dropout
__magic_name__ = layer_norm_eps
__magic_name__ = feature_layer_norm_eps
__magic_name__ = initializer_range
__magic_name__ = vocab_size
if (
(len(self.conv_stride ) != self.num_feat_extract_layers)
or (len(self.conv_kernel ) != self.num_feat_extract_layers)
or (len(self.conv_dim ) != self.num_feat_extract_layers)
):
raise ValueError(
"""Configuration for convolutional layers is incorrect."""
"""It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,"""
F'''but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)'''
F'''= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' )
# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
__magic_name__ = apply_spec_augment
__magic_name__ = mask_time_prob
__magic_name__ = mask_time_length
__magic_name__ = mask_time_min_masks
__magic_name__ = mask_feature_prob
__magic_name__ = mask_feature_length
__magic_name__ = mask_feature_min_masks
# ctc loss
__magic_name__ = ctc_loss_reduction
__magic_name__ = ctc_zero_infinity
# sequence classification
__magic_name__ = use_weighted_layer_sum
__magic_name__ = classifier_proj_size
@property
def _lowercase ( self : Union[str, Any] ) -> str:
"""simple docstring"""
return functools.reduce(operator.mul , self.conv_stride , 1 )
| 76 | 0 |
import os
def a__ ( ):
'''simple docstring'''
__magic_name__ = os.path.join(os.path.dirname(A_ ), """num.txt""" )
with open(A_ ) as file_hand:
return str(sum(int(A_ ) for line in file_hand ) )[:10]
if __name__ == "__main__":
print(solution())
| 710 |
import math
import random
def a__ ( A_, A_ = False ):
'''simple docstring'''
if deriv:
return value * (1 - value)
return 1 / (1 + math.exp(-value ))
# Initial Value
__lowerCAmelCase : Union[str, Any] = 0.02
def a__ ( A_, A_ ):
'''simple docstring'''
__magic_name__ = float(2 * (random.randint(1, 100 )) - 1 )
for _ in range(A_ ):
# Forward propagation
__magic_name__ = sigmoid_function(INITIAL_VALUE * weight )
# How much did we miss?
__magic_name__ = (expected / 100) - layer_a
# Error delta
__magic_name__ = layer_1_error * sigmoid_function(A_, A_ )
# Update weight
weight += INITIAL_VALUE * layer_1_delta
return layer_a * 100
if __name__ == "__main__":
import doctest
doctest.testmod()
__lowerCAmelCase : List[Any] = int(input('Expected value: '))
__lowerCAmelCase : Tuple = int(input('Number of propagations: '))
print(forward_propagation(expected, number_propagations))
| 76 | 0 |
def a__ ( A_, A_ ):
'''simple docstring'''
if not (isinstance(A_, A_ ) and isinstance(A_, A_ )):
raise ValueError("""longest_common_substring() takes two strings for inputs""" )
__magic_name__ = len(A_ )
__magic_name__ = len(A_ )
__magic_name__ = [[0] * (texta_length + 1) for _ in range(texta_length + 1 )]
__magic_name__ = 0
__magic_name__ = 0
for i in range(1, texta_length + 1 ):
for j in range(1, texta_length + 1 ):
if texta[i - 1] == texta[j - 1]:
__magic_name__ = 1 + dp[i - 1][j - 1]
if dp[i][j] > ans_length:
__magic_name__ = i
__magic_name__ = dp[i][j]
return texta[ans_index - ans_length : ans_index]
if __name__ == "__main__":
import doctest
doctest.testmod()
| 711 |
import os
import sys
__lowerCAmelCase : Optional[Any] = os.path.join(os.path.dirname(__file__), 'src')
sys.path.append(SRC_DIR)
from transformers import (
AutoConfig,
AutoModel,
AutoModelForCausalLM,
AutoModelForMaskedLM,
AutoModelForQuestionAnswering,
AutoModelForSequenceClassification,
AutoTokenizer,
add_start_docstrings,
)
__lowerCAmelCase : Union[str, Any] = [
'torch',
'numpy',
'tokenizers',
'filelock',
'requests',
'tqdm',
'regex',
'sentencepiece',
'sacremoses',
'importlib_metadata',
'huggingface_hub',
]
@add_start_docstrings(AutoConfig.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoConfig.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoTokenizer.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoTokenizer.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoModel.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoModel.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoModelForCausalLM.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoModelForCausalLM.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoModelForMaskedLM.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoModelForMaskedLM.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoModelForSequenceClassification.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoModelForSequenceClassification.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoModelForQuestionAnswering.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoModelForQuestionAnswering.from_pretrained(*A_, **A_ )
| 76 | 0 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__lowerCAmelCase : Union[str, Any] = logging.get_logger(__name__)
__lowerCAmelCase : List[str] = {
'facebook/s2t-wav2vec2-large-en-de': (
'https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json'
),
# See all Speech2Text models at https://huggingface.co/models?filter=speech2text2
}
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = """speech_to_text_2"""
a__ = ["""past_key_values"""]
a__ = {"""num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model"""}
def __init__( self : Optional[Any] , UpperCamelCase__ : Optional[int]=1_0000 , UpperCamelCase__ : str=6 , UpperCamelCase__ : List[Any]=2048 , UpperCamelCase__ : List[str]=4 , UpperCamelCase__ : Dict=0.0 , UpperCamelCase__ : str=True , UpperCamelCase__ : Optional[int]="relu" , UpperCamelCase__ : str=256 , UpperCamelCase__ : Optional[Any]=0.1 , UpperCamelCase__ : List[Any]=0.0 , UpperCamelCase__ : Dict=0.0 , UpperCamelCase__ : List[str]=0.02 , UpperCamelCase__ : Dict=2 , UpperCamelCase__ : Union[str, Any]=True , UpperCamelCase__ : Union[str, Any]=1 , UpperCamelCase__ : str=0 , UpperCamelCase__ : Optional[Any]=2 , UpperCamelCase__ : Optional[Any]=1024 , **UpperCamelCase__ : str , ) -> int:
"""simple docstring"""
__magic_name__ = vocab_size
__magic_name__ = d_model
__magic_name__ = decoder_ffn_dim
__magic_name__ = decoder_layers
__magic_name__ = decoder_attention_heads
__magic_name__ = dropout
__magic_name__ = attention_dropout
__magic_name__ = activation_dropout
__magic_name__ = activation_function
__magic_name__ = init_std
__magic_name__ = decoder_layerdrop
__magic_name__ = use_cache
__magic_name__ = decoder_layers
__magic_name__ = scale_embedding # scale factor will be sqrt(d_model) if True
__magic_name__ = max_target_positions
super().__init__(
pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , decoder_start_token_id=UpperCamelCase__ , **UpperCamelCase__ , )
| 712 |
from typing import Dict
from .base import GenericTensor, Pipeline
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
def _lowercase ( self : List[Any] , UpperCamelCase__ : List[Any]=None , UpperCamelCase__ : Union[str, Any]=None , UpperCamelCase__ : Any=None , **UpperCamelCase__ : Dict ) -> str:
"""simple docstring"""
if tokenize_kwargs is None:
__magic_name__ = {}
if truncation is not None:
if "truncation" in tokenize_kwargs:
raise ValueError(
"""truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)""" )
__magic_name__ = truncation
__magic_name__ = tokenize_kwargs
__magic_name__ = {}
if return_tensors is not None:
__magic_name__ = return_tensors
return preprocess_params, {}, postprocess_params
def _lowercase ( self : int , UpperCamelCase__ : int , **UpperCamelCase__ : int ) -> Dict[str, GenericTensor]:
"""simple docstring"""
__magic_name__ = self.framework
__magic_name__ = self.tokenizer(UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ )
return model_inputs
def _lowercase ( self : str , UpperCamelCase__ : Dict ) -> str:
"""simple docstring"""
__magic_name__ = self.model(**UpperCamelCase__ )
return model_outputs
def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str]=False ) -> List[str]:
"""simple docstring"""
if return_tensors:
return model_outputs[0]
if self.framework == "pt":
return model_outputs[0].tolist()
elif self.framework == "tf":
return model_outputs[0].numpy().tolist()
def __call__( self : List[str] , *UpperCamelCase__ : List[Any] , **UpperCamelCase__ : List[Any] ) -> Dict:
"""simple docstring"""
return super().__call__(*UpperCamelCase__ , **UpperCamelCase__ )
| 76 | 0 |
import argparse
import datetime
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = {
"""0""": """Sunday""",
"""1""": """Monday""",
"""2""": """Tuesday""",
"""3""": """Wednesday""",
"""4""": """Thursday""",
"""5""": """Friday""",
"""6""": """Saturday""",
}
__magic_name__ = {0: 1, 1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 0}
# Validate
if not 0 < len(A_ ) < 11:
raise ValueError("""Must be 10 characters long""" )
# Get month
__magic_name__ = int(date_input[0] + date_input[1] )
# Validate
if not 0 < m < 13:
raise ValueError("""Month must be between 1 - 12""" )
__magic_name__ = date_input[2]
# Validate
if sep_a not in ["-", "/"]:
raise ValueError("""Date separator must be '-' or '/'""" )
# Get day
__magic_name__ = int(date_input[3] + date_input[4] )
# Validate
if not 0 < d < 32:
raise ValueError("""Date must be between 1 - 31""" )
# Get second separator
__magic_name__ = date_input[5]
# Validate
if sep_a not in ["-", "/"]:
raise ValueError("""Date separator must be '-' or '/'""" )
# Get year
__magic_name__ = int(date_input[6] + date_input[7] + date_input[8] + date_input[9] )
# Arbitrary year range
if not 45 < y < 8500:
raise ValueError(
"""Year out of range. There has to be some sort of limit...right?""" )
# Get datetime obj for validation
__magic_name__ = datetime.date(int(A_ ), int(A_ ), int(A_ ) )
# Start math
if m <= 2:
__magic_name__ = y - 1
__magic_name__ = m + 12
# maths var
__magic_name__ = int(str(A_ )[:2] )
__magic_name__ = int(str(A_ )[2:] )
__magic_name__ = int(2.6 * m - 5.39 )
__magic_name__ = int(c / 4 )
__magic_name__ = int(k / 4 )
__magic_name__ = int(d + k )
__magic_name__ = int(t + u + v + x )
__magic_name__ = int(z - (2 * c) )
__magic_name__ = round(w % 7 )
# End math
# Validate math
if f != convert_datetime_days[dt_ck.weekday()]:
raise AssertionError("""The date was evaluated incorrectly. Contact developer.""" )
# Response
__magic_name__ = f'''Your date {date_input}, is a {days[str(A_ )]}!'''
return response
if __name__ == "__main__":
import doctest
doctest.testmod()
__lowerCAmelCase : List[str] = argparse.ArgumentParser(
description=(
'Find out what day of the week nearly any date is or was. Enter '
'date as a string in the mm-dd-yyyy or mm/dd/yyyy format'
)
)
parser.add_argument(
'date_input', type=str, help='Date as a string (mm-dd-yyyy or mm/dd/yyyy)'
)
__lowerCAmelCase : int = parser.parse_args()
zeller(args.date_input)
| 713 |
import argparse
import math
import os
from copy import deepcopy
import torch
from audio_diffusion.models import DiffusionAttnUnetaD
from diffusion import sampling
from torch import nn
from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel
__lowerCAmelCase : str = {
'gwf-440k': {
'url': 'https://model-server.zqevans2.workers.dev/gwf-440k.ckpt',
'sample_rate': 48000,
'sample_size': 65536,
},
'jmann-small-190k': {
'url': 'https://model-server.zqevans2.workers.dev/jmann-small-190k.ckpt',
'sample_rate': 48000,
'sample_size': 65536,
},
'jmann-large-580k': {
'url': 'https://model-server.zqevans2.workers.dev/jmann-large-580k.ckpt',
'sample_rate': 48000,
'sample_size': 131072,
},
'maestro-uncond-150k': {
'url': 'https://model-server.zqevans2.workers.dev/maestro-uncond-150k.ckpt',
'sample_rate': 16000,
'sample_size': 65536,
},
'unlocked-uncond-250k': {
'url': 'https://model-server.zqevans2.workers.dev/unlocked-uncond-250k.ckpt',
'sample_rate': 16000,
'sample_size': 65536,
},
'honk-140k': {
'url': 'https://model-server.zqevans2.workers.dev/honk-140k.ckpt',
'sample_rate': 16000,
'sample_size': 65536,
},
}
def a__ ( A_, A_ ):
'''simple docstring'''
return torch.atana(A_, A_ ) / math.pi * 2
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = torch.sin(t * math.pi / 2 ) ** 2
__magic_name__ = (1 - sigma**2) ** 0.5
return alpha_sigma_to_t(A_, A_ )
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
pass
class UpperCAmelCase_ ( nn.Module ):
'''simple docstring'''
def __init__( self : Tuple , UpperCamelCase__ : str ) -> Optional[Any]:
"""simple docstring"""
super().__init__()
__magic_name__ = DiffusionAttnUnetaD(UpperCamelCase__ , n_attn_layers=4 )
__magic_name__ = deepcopy(self.diffusion )
__magic_name__ = torch.quasirandom.SobolEngine(1 , scramble=UpperCamelCase__ )
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = MODELS_MAP[model_name]["""url"""]
os.system(f'''wget {url} ./''' )
return f'''./{model_name}.ckpt'''
__lowerCAmelCase : Optional[int] = {
'1': 'resnets.0',
'2': 'attentions.0',
'3': 'resnets.1',
'4': 'attentions.1',
'5': 'resnets.2',
'6': 'attentions.2',
}
__lowerCAmelCase : Optional[Any] = {
'8': 'resnets.0',
'9': 'attentions.0',
'10': 'resnets.1',
'11': 'attentions.1',
'12': 'resnets.2',
'13': 'attentions.2',
}
__lowerCAmelCase : Union[str, Any] = {
'1': 'resnets.0',
'2': 'attentions.0',
'3': 'resnets.1',
'4': 'attentions.1',
'5': 'resnets.2',
'6': 'attentions.2',
'8': 'resnets.3',
'9': 'attentions.3',
'10': 'resnets.4',
'11': 'attentions.4',
'12': 'resnets.5',
'13': 'attentions.5',
}
__lowerCAmelCase : int = {
'0': 'resnets.0',
'1': 'resnets.1',
'2': 'resnets.2',
'4': 'resnets.0',
'5': 'resnets.1',
'6': 'resnets.2',
}
__lowerCAmelCase : List[str] = {
'skip': 'conv_skip',
'main.0': 'conv_1',
'main.1': 'group_norm_1',
'main.3': 'conv_2',
'main.4': 'group_norm_2',
}
__lowerCAmelCase : int = {
'norm': 'group_norm',
'qkv_proj': ['query', 'key', 'value'],
'out_proj': ['proj_attn'],
}
def a__ ( A_ ):
'''simple docstring'''
if name.startswith("""skip""" ):
return name.replace("""skip""", RES_CONV_MAP["""skip"""] )
# name has to be of format main.{digit}
if not name.startswith("""main.""" ):
raise ValueError(f'''ResConvBlock error with {name}''' )
return name.replace(name[:6], RES_CONV_MAP[name[:6]] )
def a__ ( A_ ):
'''simple docstring'''
for key, value in ATTN_MAP.items():
if name.startswith(A_ ) and not isinstance(A_, A_ ):
return name.replace(A_, A_ )
elif name.startswith(A_ ):
return [name.replace(A_, A_ ) for v in value]
raise ValueError(f'''Attn error with {name}''' )
def a__ ( A_, A_=13 ):
'''simple docstring'''
__magic_name__ = input_string
if string.split(""".""" )[0] == "timestep_embed":
return string.replace("""timestep_embed""", """time_proj""" )
__magic_name__ = 0
if string.startswith("""net.3.""" ):
depth += 1
__magic_name__ = string[6:]
elif string.startswith("""net.""" ):
__magic_name__ = string[4:]
while string.startswith("""main.7.""" ):
depth += 1
__magic_name__ = string[7:]
if string.startswith("""main.""" ):
__magic_name__ = string[5:]
# mid block
if string[:2].isdigit():
__magic_name__ = string[:2]
__magic_name__ = string[2:]
else:
__magic_name__ = string[0]
__magic_name__ = string[1:]
if depth == max_depth:
__magic_name__ = MID_NUM_TO_LAYER[layer_num]
__magic_name__ = """mid_block"""
elif depth > 0 and int(A_ ) < 7:
__magic_name__ = DOWN_NUM_TO_LAYER[layer_num]
__magic_name__ = f'''down_blocks.{depth}'''
elif depth > 0 and int(A_ ) > 7:
__magic_name__ = UP_NUM_TO_LAYER[layer_num]
__magic_name__ = f'''up_blocks.{max_depth - depth - 1}'''
elif depth == 0:
__magic_name__ = DEPTH_0_TO_LAYER[layer_num]
__magic_name__ = f'''up_blocks.{max_depth - 1}''' if int(A_ ) > 3 else """down_blocks.0"""
if not string_left.startswith(""".""" ):
raise ValueError(f'''Naming error with {input_string} and string_left: {string_left}.''' )
__magic_name__ = string_left[1:]
if "resnets" in new_layer:
__magic_name__ = convert_resconv_naming(A_ )
elif "attentions" in new_layer:
__magic_name__ = convert_attn_naming(A_ )
__magic_name__ = new_string_left
if not isinstance(A_, A_ ):
__magic_name__ = prefix + """.""" + new_layer + """.""" + string_left
else:
__magic_name__ = [prefix + """.""" + new_layer + """.""" + s for s in string_left]
return new_string
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = {}
for k, v in state_dict.items():
if k.endswith("""kernel""" ):
# up- and downsample layers, don't have trainable weights
continue
__magic_name__ = rename(A_ )
# check if we need to transform from Conv => Linear for attention
if isinstance(A_, A_ ):
__magic_name__ = transform_conv_attns(A_, A_, A_ )
else:
__magic_name__ = v
return new_state_dict
def a__ ( A_, A_, A_ ):
'''simple docstring'''
if len(A_ ) == 1:
if len(v.shape ) == 3:
# weight
__magic_name__ = v[:, :, 0]
else:
# bias
__magic_name__ = v
else:
# qkv matrices
__magic_name__ = v.shape[0]
__magic_name__ = trippled_shape // 3
for i in range(3 ):
if len(v.shape ) == 3:
__magic_name__ = v[i * single_shape : (i + 1) * single_shape, :, 0]
else:
__magic_name__ = v[i * single_shape : (i + 1) * single_shape]
return new_state_dict
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" )
__magic_name__ = args.model_path.split("""/""" )[-1].split(""".""" )[0]
if not os.path.isfile(args.model_path ):
assert (
model_name == args.model_path
), f'''Make sure to provide one of the official model names {MODELS_MAP.keys()}'''
__magic_name__ = download(A_ )
__magic_name__ = MODELS_MAP[model_name]["""sample_rate"""]
__magic_name__ = MODELS_MAP[model_name]["""sample_size"""]
__magic_name__ = Object()
__magic_name__ = sample_size
__magic_name__ = sample_rate
__magic_name__ = 0
__magic_name__ = UNetaDModel(sample_size=A_, sample_rate=A_ )
__magic_name__ = diffusers_model.state_dict()
__magic_name__ = DiffusionUncond(A_ )
orig_model.load_state_dict(torch.load(args.model_path, map_location=A_ )["""state_dict"""] )
__magic_name__ = orig_model.diffusion_ema.eval()
__magic_name__ = orig_model.state_dict()
__magic_name__ = rename_orig_weights(A_ )
__magic_name__ = set(renamed_state_dict.keys() ) - set(diffusers_state_dict.keys() )
__magic_name__ = set(diffusers_state_dict.keys() ) - set(renamed_state_dict.keys() )
assert len(A_ ) == 0, f'''Problem with {renamed_minus_diffusers}'''
assert all(k.endswith("""kernel""" ) for k in list(A_ ) ), f'''Problem with {diffusers_minus_renamed}'''
for key, value in renamed_state_dict.items():
assert (
diffusers_state_dict[key].squeeze().shape == value.squeeze().shape
), f'''Shape for {key} doesn\'t match. Diffusers: {diffusers_state_dict[key].shape} vs. {value.shape}'''
if key == "time_proj.weight":
__magic_name__ = value.squeeze()
__magic_name__ = value
diffusers_model.load_state_dict(A_ )
__magic_name__ = 100
__magic_name__ = 33
__magic_name__ = IPNDMScheduler(num_train_timesteps=A_ )
__magic_name__ = torch.manual_seed(A_ )
__magic_name__ = torch.randn([1, 2, config.sample_size], generator=A_ ).to(A_ )
__magic_name__ = torch.linspace(1, 0, steps + 1, device=A_ )[:-1]
__magic_name__ = get_crash_schedule(A_ )
__magic_name__ = DanceDiffusionPipeline(unet=A_, scheduler=A_ )
__magic_name__ = torch.manual_seed(33 )
__magic_name__ = pipe(num_inference_steps=A_, generator=A_ ).audios
__magic_name__ = sampling.iplms_sample(A_, A_, A_, {} )
__magic_name__ = generated.clamp(-1, 1 )
__magic_name__ = (generated - audio).abs().sum()
__magic_name__ = (generated - audio).abs().max()
if args.save:
pipe.save_pretrained(args.checkpoint_path )
print("""Diff sum""", A_ )
print("""Diff max""", A_ )
assert diff_max < 1e-3, f'''Diff max: {diff_max} is too much :-/'''
print(f'''Conversion for {model_name} successful!''' )
if __name__ == "__main__":
__lowerCAmelCase : Optional[int] = argparse.ArgumentParser()
parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.')
parser.add_argument(
'--save', default=True, type=bool, required=False, help='Whether to save the converted model or not.'
)
parser.add_argument('--checkpoint_path', default=None, type=str, required=True, help='Path to the output model.')
__lowerCAmelCase : Union[str, Any] = parser.parse_args()
main(args)
| 76 | 0 |
import argparse
import json
from pathlib import Path
import requests
import timm
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import DeiTImageProcessor, ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel
from transformers.utils import logging
logging.set_verbosity_info()
__lowerCAmelCase : Any = logging.get_logger(__name__)
def a__ ( A_, A_=False ):
'''simple docstring'''
__magic_name__ = []
for i in range(config.num_hidden_layers ):
# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
rename_keys.append((f'''blocks.{i}.norm1.weight''', f'''vit.encoder.layer.{i}.layernorm_before.weight''') )
rename_keys.append((f'''blocks.{i}.norm1.bias''', f'''vit.encoder.layer.{i}.layernorm_before.bias''') )
rename_keys.append((f'''blocks.{i}.attn.proj.weight''', f'''vit.encoder.layer.{i}.attention.output.dense.weight''') )
rename_keys.append((f'''blocks.{i}.attn.proj.bias''', f'''vit.encoder.layer.{i}.attention.output.dense.bias''') )
rename_keys.append((f'''blocks.{i}.norm2.weight''', f'''vit.encoder.layer.{i}.layernorm_after.weight''') )
rename_keys.append((f'''blocks.{i}.norm2.bias''', f'''vit.encoder.layer.{i}.layernorm_after.bias''') )
rename_keys.append((f'''blocks.{i}.mlp.fc1.weight''', f'''vit.encoder.layer.{i}.intermediate.dense.weight''') )
rename_keys.append((f'''blocks.{i}.mlp.fc1.bias''', f'''vit.encoder.layer.{i}.intermediate.dense.bias''') )
rename_keys.append((f'''blocks.{i}.mlp.fc2.weight''', f'''vit.encoder.layer.{i}.output.dense.weight''') )
rename_keys.append((f'''blocks.{i}.mlp.fc2.bias''', f'''vit.encoder.layer.{i}.output.dense.bias''') )
# projection layer + position embeddings
rename_keys.extend(
[
("""cls_token""", """vit.embeddings.cls_token"""),
("""patch_embed.proj.weight""", """vit.embeddings.patch_embeddings.projection.weight"""),
("""patch_embed.proj.bias""", """vit.embeddings.patch_embeddings.projection.bias"""),
("""pos_embed""", """vit.embeddings.position_embeddings"""),
] )
if base_model:
# layernorm + pooler
rename_keys.extend(
[
("""norm.weight""", """layernorm.weight"""),
("""norm.bias""", """layernorm.bias"""),
("""pre_logits.fc.weight""", """pooler.dense.weight"""),
("""pre_logits.fc.bias""", """pooler.dense.bias"""),
] )
# if just the base model, we should remove "vit" from all keys that start with "vit"
__magic_name__ = [(pair[0], pair[1][4:]) if pair[1].startswith("""vit""" ) else pair for pair in rename_keys]
else:
# layernorm + classification head
rename_keys.extend(
[
("""norm.weight""", """vit.layernorm.weight"""),
("""norm.bias""", """vit.layernorm.bias"""),
("""head.weight""", """classifier.weight"""),
("""head.bias""", """classifier.bias"""),
] )
return rename_keys
def a__ ( A_, A_, A_=False ):
'''simple docstring'''
for i in range(config.num_hidden_layers ):
if base_model:
__magic_name__ = """"""
else:
__magic_name__ = """vit."""
# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
__magic_name__ = state_dict.pop(f'''blocks.{i}.attn.qkv.weight''' )
__magic_name__ = state_dict.pop(f'''blocks.{i}.attn.qkv.bias''' )
# next, add query, keys and values (in that order) to the state dict
__magic_name__ = in_proj_weight[
: config.hidden_size, :
]
__magic_name__ = in_proj_bias[: config.hidden_size]
__magic_name__ = in_proj_weight[
config.hidden_size : config.hidden_size * 2, :
]
__magic_name__ = in_proj_bias[
config.hidden_size : config.hidden_size * 2
]
__magic_name__ = in_proj_weight[
-config.hidden_size :, :
]
__magic_name__ = in_proj_bias[-config.hidden_size :]
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = ["""head.weight""", """head.bias"""]
for k in ignore_keys:
state_dict.pop(A_, A_ )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = dct.pop(A_ )
__magic_name__ = val
def a__ ( ):
'''simple docstring'''
__magic_name__ = """http://images.cocodataset.org/val2017/000000039769.jpg"""
__magic_name__ = Image.open(requests.get(A_, stream=A_ ).raw )
return im
@torch.no_grad()
def a__ ( A_, A_ ):
'''simple docstring'''
__magic_name__ = ViTConfig()
__magic_name__ = False
# dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size
if vit_name[-5:] == "in21k":
__magic_name__ = True
__magic_name__ = int(vit_name[-12:-10] )
__magic_name__ = int(vit_name[-9:-6] )
else:
__magic_name__ = 1000
__magic_name__ = """huggingface/label-files"""
__magic_name__ = """imagenet-1k-id2label.json"""
__magic_name__ = json.load(open(hf_hub_download(A_, A_, repo_type="""dataset""" ), """r""" ) )
__magic_name__ = {int(A_ ): v for k, v in idalabel.items()}
__magic_name__ = idalabel
__magic_name__ = {v: k for k, v in idalabel.items()}
__magic_name__ = int(vit_name[-6:-4] )
__magic_name__ = int(vit_name[-3:] )
# size of the architecture
if "deit" in vit_name:
if vit_name[9:].startswith("""tiny""" ):
__magic_name__ = 192
__magic_name__ = 768
__magic_name__ = 12
__magic_name__ = 3
elif vit_name[9:].startswith("""small""" ):
__magic_name__ = 384
__magic_name__ = 1536
__magic_name__ = 12
__magic_name__ = 6
else:
pass
else:
if vit_name[4:].startswith("""small""" ):
__magic_name__ = 768
__magic_name__ = 2304
__magic_name__ = 8
__magic_name__ = 8
elif vit_name[4:].startswith("""base""" ):
pass
elif vit_name[4:].startswith("""large""" ):
__magic_name__ = 1024
__magic_name__ = 4096
__magic_name__ = 24
__magic_name__ = 16
elif vit_name[4:].startswith("""huge""" ):
__magic_name__ = 1280
__magic_name__ = 5120
__magic_name__ = 32
__magic_name__ = 16
# load original model from timm
__magic_name__ = timm.create_model(A_, pretrained=A_ )
timm_model.eval()
# load state_dict of original model, remove and rename some keys
__magic_name__ = timm_model.state_dict()
if base_model:
remove_classification_head_(A_ )
__magic_name__ = create_rename_keys(A_, A_ )
for src, dest in rename_keys:
rename_key(A_, A_, A_ )
read_in_q_k_v(A_, A_, A_ )
# load HuggingFace model
if vit_name[-5:] == "in21k":
__magic_name__ = ViTModel(A_ ).eval()
else:
__magic_name__ = ViTForImageClassification(A_ ).eval()
model.load_state_dict(A_ )
# Check outputs on an image, prepared by ViTImageProcessor/DeiTImageProcessor
if "deit" in vit_name:
__magic_name__ = DeiTImageProcessor(size=config.image_size )
else:
__magic_name__ = ViTImageProcessor(size=config.image_size )
__magic_name__ = image_processor(images=prepare_img(), return_tensors="""pt""" )
__magic_name__ = encoding["""pixel_values"""]
__magic_name__ = model(A_ )
if base_model:
__magic_name__ = timm_model.forward_features(A_ )
assert timm_pooled_output.shape == outputs.pooler_output.shape
assert torch.allclose(A_, outputs.pooler_output, atol=1e-3 )
else:
__magic_name__ = timm_model(A_ )
assert timm_logits.shape == outputs.logits.shape
assert torch.allclose(A_, outputs.logits, atol=1e-3 )
Path(A_ ).mkdir(exist_ok=A_ )
print(f'''Saving model {vit_name} to {pytorch_dump_folder_path}''' )
model.save_pretrained(A_ )
print(f'''Saving image processor to {pytorch_dump_folder_path}''' )
image_processor.save_pretrained(A_ )
if __name__ == "__main__":
__lowerCAmelCase : List[Any] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--vit_name',
default='vit_base_patch16_224',
type=str,
help='Name of the ViT timm model you\'d like to convert.',
)
parser.add_argument(
'--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.'
)
__lowerCAmelCase : Optional[Any] = parser.parse_args()
convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path)
| 714 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__lowerCAmelCase : Tuple = logging.get_logger(__name__)
__lowerCAmelCase : Tuple = {
'SCUT-DLVCLab/lilt-roberta-en-base': (
'https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json'
),
}
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = """lilt"""
def __init__( self : Dict , UpperCamelCase__ : List[str]=3_0522 , UpperCamelCase__ : Optional[Any]=768 , UpperCamelCase__ : Dict=12 , UpperCamelCase__ : Optional[Any]=12 , UpperCamelCase__ : Dict=3072 , UpperCamelCase__ : Tuple="gelu" , UpperCamelCase__ : int=0.1 , UpperCamelCase__ : Dict=0.1 , UpperCamelCase__ : Union[str, Any]=512 , UpperCamelCase__ : Dict=2 , UpperCamelCase__ : Dict=0.02 , UpperCamelCase__ : Any=1E-12 , UpperCamelCase__ : Optional[int]=0 , UpperCamelCase__ : str="absolute" , UpperCamelCase__ : Any=None , UpperCamelCase__ : Dict=4 , UpperCamelCase__ : Tuple=1024 , **UpperCamelCase__ : Optional[int] , ) -> Dict:
"""simple docstring"""
super().__init__(pad_token_id=UpperCamelCase__ , **UpperCamelCase__ )
__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__ = classifier_dropout
__magic_name__ = channel_shrink_ratio
__magic_name__ = max_ad_position_embeddings
| 76 | 0 |
from __future__ import annotations
from typing import TypedDict
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = 42
a__ = 42
def a__ ( A_ ):
'''simple docstring'''
if not isinstance(A_, A_ ):
raise TypeError("""The parameter s type must be str.""" )
return [s[i:] + s[:i] for i in range(len(A_ ) )]
def a__ ( A_ ):
'''simple docstring'''
if not isinstance(A_, A_ ):
raise TypeError("""The parameter s type must be str.""" )
if not s:
raise ValueError("""The parameter s must not be empty.""" )
__magic_name__ = all_rotations(A_ )
rotations.sort() # sort the list of rotations in alphabetically order
# make a string composed of the last char of each rotation
__magic_name__ = {
"""bwt_string""": """""".join([word[-1] for word in rotations] ),
"""idx_original_string""": rotations.index(A_ ),
}
return response
def a__ ( A_, A_ ):
'''simple docstring'''
if not isinstance(A_, A_ ):
raise TypeError("""The parameter bwt_string type must be str.""" )
if not bwt_string:
raise ValueError("""The parameter bwt_string must not be empty.""" )
try:
__magic_name__ = int(A_ )
except ValueError:
raise TypeError(
"""The parameter idx_original_string type must be int or passive"""
""" of cast to int.""" )
if idx_original_string < 0:
raise ValueError("""The parameter idx_original_string must not be lower than 0.""" )
if idx_original_string >= len(A_ ):
raise ValueError(
"""The parameter idx_original_string must be lower than""" """ len(bwt_string).""" )
__magic_name__ = [""""""] * len(A_ )
for _ in range(len(A_ ) ):
for i in range(len(A_ ) ):
__magic_name__ = bwt_string[i] + ordered_rotations[i]
ordered_rotations.sort()
return ordered_rotations[idx_original_string]
if __name__ == "__main__":
__lowerCAmelCase : Tuple = 'Provide a string that I will generate its BWT transform: '
__lowerCAmelCase : List[Any] = input(entry_msg).strip()
__lowerCAmelCase : List[Any] = bwt_transform(s)
print(
F'''Burrows Wheeler transform for string \'{s}\' results '''
F'''in \'{result["bwt_string"]}\''''
)
__lowerCAmelCase : Optional[Any] = reverse_bwt(result['bwt_string'], result['idx_original_string'])
print(
F'''Reversing Burrows Wheeler transform for entry \'{result["bwt_string"]}\' '''
F'''we get original string \'{original_string}\''''
)
| 715 |
import json
import os
import tempfile
from transformers.testing_utils import check_json_file_has_correct_format
class UpperCAmelCase_ :
'''simple docstring'''
a__ = None
def _lowercase ( self : Optional[int] ) -> str:
"""simple docstring"""
__magic_name__ = self.feature_extraction_class(**self.feat_extract_dict )
__magic_name__ = json.loads(feat_extract.to_json_string() )
for key, value in self.feat_extract_dict.items():
self.assertEqual(obj[key] , UpperCamelCase__ )
def _lowercase ( self : Union[str, Any] ) -> str:
"""simple docstring"""
__magic_name__ = self.feature_extraction_class(**self.feat_extract_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
__magic_name__ = os.path.join(UpperCamelCase__ , """feat_extract.json""" )
feat_extract_first.to_json_file(UpperCamelCase__ )
__magic_name__ = self.feature_extraction_class.from_json_file(UpperCamelCase__ )
self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() )
def _lowercase ( self : str ) -> str:
"""simple docstring"""
__magic_name__ = self.feature_extraction_class(**self.feat_extract_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
__magic_name__ = feat_extract_first.save_pretrained(UpperCamelCase__ )[0]
check_json_file_has_correct_format(UpperCamelCase__ )
__magic_name__ = self.feature_extraction_class.from_pretrained(UpperCamelCase__ )
self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() )
def _lowercase ( self : Optional[int] ) -> Tuple:
"""simple docstring"""
__magic_name__ = self.feature_extraction_class()
self.assertIsNotNone(UpperCamelCase__ )
| 76 | 0 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
__lowerCAmelCase : List[Any] = {
'configuration_swinv2': ['SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Swinv2Config'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowerCAmelCase : str = [
'SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST',
'Swinv2ForImageClassification',
'Swinv2ForMaskedImageModeling',
'Swinv2Model',
'Swinv2PreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_swinva import SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinvaConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_swinva import (
SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST,
SwinvaForImageClassification,
SwinvaForMaskedImageModeling,
SwinvaModel,
SwinvaPreTrainedModel,
)
else:
import sys
__lowerCAmelCase : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 716 |
from ..utils import DummyObject, requires_backends
class UpperCAmelCase_ ( metaclass=_A ):
'''simple docstring'''
a__ = ["""note_seq"""]
def __init__( self : Any , *UpperCamelCase__ : str , **UpperCamelCase__ : List[Any] ) -> Optional[int]:
"""simple docstring"""
requires_backends(self , ["""note_seq"""] )
@classmethod
def _lowercase ( cls : str , *UpperCamelCase__ : Dict , **UpperCamelCase__ : Tuple ) -> Dict:
"""simple docstring"""
requires_backends(cls , ["""note_seq"""] )
@classmethod
def _lowercase ( cls : List[str] , *UpperCamelCase__ : Optional[Any] , **UpperCamelCase__ : Tuple ) -> int:
"""simple docstring"""
requires_backends(cls , ["""note_seq"""] )
| 76 | 0 |
from __future__ import annotations
import unittest
from transformers import FunnelConfig, is_tf_available
from transformers.testing_utils import require_tf
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
TFFunnelBaseModel,
TFFunnelForMaskedLM,
TFFunnelForMultipleChoice,
TFFunnelForPreTraining,
TFFunnelForQuestionAnswering,
TFFunnelForSequenceClassification,
TFFunnelForTokenClassification,
TFFunnelModel,
)
class UpperCAmelCase_ :
'''simple docstring'''
def __init__( self : List[str] , UpperCamelCase__ : int , UpperCamelCase__ : Optional[int]=13 , UpperCamelCase__ : Tuple=7 , UpperCamelCase__ : Any=True , UpperCamelCase__ : int=True , UpperCamelCase__ : List[str]=True , UpperCamelCase__ : Dict=True , UpperCamelCase__ : Dict=99 , UpperCamelCase__ : Union[str, Any]=[1, 1, 2] , UpperCamelCase__ : List[Any]=1 , UpperCamelCase__ : int=32 , UpperCamelCase__ : Union[str, Any]=4 , UpperCamelCase__ : Optional[int]=8 , UpperCamelCase__ : List[Any]=37 , UpperCamelCase__ : str="gelu_new" , UpperCamelCase__ : Optional[Any]=0.1 , UpperCamelCase__ : Optional[Any]=0.1 , UpperCamelCase__ : List[str]=0.0 , UpperCamelCase__ : str=512 , UpperCamelCase__ : Optional[int]=3 , UpperCamelCase__ : str=0.02 , UpperCamelCase__ : List[str]=3 , UpperCamelCase__ : Any=4 , UpperCamelCase__ : List[str]=None , UpperCamelCase__ : Dict=False , ) -> Optional[int]:
"""simple docstring"""
__magic_name__ = parent
__magic_name__ = batch_size
__magic_name__ = seq_length
__magic_name__ = is_training
__magic_name__ = use_input_mask
__magic_name__ = use_token_type_ids
__magic_name__ = use_labels
__magic_name__ = vocab_size
__magic_name__ = block_sizes
__magic_name__ = num_decoder_layers
__magic_name__ = d_model
__magic_name__ = n_head
__magic_name__ = d_head
__magic_name__ = d_inner
__magic_name__ = hidden_act
__magic_name__ = hidden_dropout
__magic_name__ = attention_dropout
__magic_name__ = activation_dropout
__magic_name__ = max_position_embeddings
__magic_name__ = type_vocab_size
__magic_name__ = 2
__magic_name__ = num_labels
__magic_name__ = num_choices
__magic_name__ = scope
__magic_name__ = initializer_std
# Used in the tests to check the size of the first attention layer
__magic_name__ = n_head
# Used in the tests to check the size of the first hidden state
__magic_name__ = self.d_model
# Used in the tests to check the number of output hidden states/attentions
__magic_name__ = sum(self.block_sizes ) + (0 if base else self.num_decoder_layers)
# FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with
# the last hidden state of the first block (which is the first hidden state of the decoder).
if not base:
__magic_name__ = self.num_hidden_layers + 2
def _lowercase ( self : Optional[int] ) -> Dict:
"""simple docstring"""
__magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__magic_name__ = None
if self.use_input_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__ = None
__magic_name__ = None
__magic_name__ = None
if self.use_labels:
__magic_name__ = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
__magic_name__ = ids_tensor([self.batch_size] , self.num_choices )
__magic_name__ = FunnelConfig(
vocab_size=self.vocab_size , block_sizes=self.block_sizes , num_decoder_layers=self.num_decoder_layers , d_model=self.d_model , n_head=self.n_head , d_head=self.d_head , d_inner=self.d_inner , hidden_act=self.hidden_act , hidden_dropout=self.hidden_dropout , attention_dropout=self.attention_dropout , activation_dropout=self.activation_dropout , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_std=self.initializer_std , )
return (
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
)
def _lowercase ( self : str , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : int , UpperCamelCase__ : int , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[Any] , ) -> Optional[Any]:
"""simple docstring"""
__magic_name__ = TFFunnelModel(config=UpperCamelCase__ )
__magic_name__ = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
__magic_name__ = model(UpperCamelCase__ )
__magic_name__ = [input_ids, input_mask]
__magic_name__ = model(UpperCamelCase__ )
__magic_name__ = model(UpperCamelCase__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) )
__magic_name__ = False
__magic_name__ = TFFunnelModel(config=UpperCamelCase__ )
__magic_name__ = model(UpperCamelCase__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) )
__magic_name__ = False
__magic_name__ = TFFunnelModel(config=UpperCamelCase__ )
__magic_name__ = model(UpperCamelCase__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) )
def _lowercase ( self : Dict , UpperCamelCase__ : Dict , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Any , UpperCamelCase__ : Tuple , UpperCamelCase__ : List[Any] , ) -> Dict:
"""simple docstring"""
__magic_name__ = TFFunnelBaseModel(config=UpperCamelCase__ )
__magic_name__ = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
__magic_name__ = model(UpperCamelCase__ )
__magic_name__ = [input_ids, input_mask]
__magic_name__ = model(UpperCamelCase__ )
__magic_name__ = model(UpperCamelCase__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model) )
__magic_name__ = False
__magic_name__ = TFFunnelBaseModel(config=UpperCamelCase__ )
__magic_name__ = model(UpperCamelCase__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 3, self.d_model) )
__magic_name__ = False
__magic_name__ = TFFunnelBaseModel(config=UpperCamelCase__ )
__magic_name__ = model(UpperCamelCase__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model) )
def _lowercase ( self : int , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] , ) -> List[Any]:
"""simple docstring"""
__magic_name__ = TFFunnelForPreTraining(config=UpperCamelCase__ )
__magic_name__ = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
__magic_name__ = model(UpperCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length) )
def _lowercase ( self : List[Any] , UpperCamelCase__ : int , UpperCamelCase__ : Any , UpperCamelCase__ : List[str] , UpperCamelCase__ : Any , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Any , ) -> Optional[Any]:
"""simple docstring"""
__magic_name__ = TFFunnelForMaskedLM(config=UpperCamelCase__ )
__magic_name__ = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
__magic_name__ = model(UpperCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def _lowercase ( self : Optional[int] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : int , UpperCamelCase__ : Any , UpperCamelCase__ : Any , UpperCamelCase__ : List[str] , UpperCamelCase__ : Optional[int] , ) -> List[str]:
"""simple docstring"""
__magic_name__ = self.num_labels
__magic_name__ = TFFunnelForSequenceClassification(config=UpperCamelCase__ )
__magic_name__ = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
__magic_name__ = model(UpperCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def _lowercase ( self : Optional[int] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : Dict , UpperCamelCase__ : str , UpperCamelCase__ : Any , UpperCamelCase__ : str , ) -> Optional[int]:
"""simple docstring"""
__magic_name__ = self.num_choices
__magic_name__ = TFFunnelForMultipleChoice(config=UpperCamelCase__ )
__magic_name__ = tf.tile(tf.expand_dims(UpperCamelCase__ , 1 ) , (1, self.num_choices, 1) )
__magic_name__ = tf.tile(tf.expand_dims(UpperCamelCase__ , 1 ) , (1, self.num_choices, 1) )
__magic_name__ = tf.tile(tf.expand_dims(UpperCamelCase__ , 1 ) , (1, self.num_choices, 1) )
__magic_name__ = {
"""input_ids""": multiple_choice_inputs_ids,
"""attention_mask""": multiple_choice_input_mask,
"""token_type_ids""": multiple_choice_token_type_ids,
}
__magic_name__ = model(UpperCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def _lowercase ( self : List[str] , UpperCamelCase__ : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : List[str] , UpperCamelCase__ : str , UpperCamelCase__ : int , UpperCamelCase__ : Dict , UpperCamelCase__ : Tuple , ) -> Optional[int]:
"""simple docstring"""
__magic_name__ = self.num_labels
__magic_name__ = TFFunnelForTokenClassification(config=UpperCamelCase__ )
__magic_name__ = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
__magic_name__ = model(UpperCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def _lowercase ( self : Optional[int] , UpperCamelCase__ : str , UpperCamelCase__ : List[Any] , UpperCamelCase__ : str , UpperCamelCase__ : List[str] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : int , ) -> str:
"""simple docstring"""
__magic_name__ = TFFunnelForQuestionAnswering(config=UpperCamelCase__ )
__magic_name__ = {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
__magic_name__ = model(UpperCamelCase__ )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def _lowercase ( self : Optional[Any] ) -> int:
"""simple docstring"""
__magic_name__ = self.prepare_config_and_inputs()
(
(
__magic_name__
) , (
__magic_name__
) , (
__magic_name__
) , (
__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""": input_mask}
return config, inputs_dict
@require_tf
class UpperCAmelCase_ ( _A , _A , unittest.TestCase ):
'''simple docstring'''
a__ = (
(
TFFunnelModel,
TFFunnelForMaskedLM,
TFFunnelForPreTraining,
TFFunnelForQuestionAnswering,
TFFunnelForTokenClassification,
)
if is_tf_available()
else ()
)
a__ = (
{
"""feature-extraction""": (TFFunnelBaseModel, TFFunnelModel),
"""fill-mask""": TFFunnelForMaskedLM,
"""question-answering""": TFFunnelForQuestionAnswering,
"""text-classification""": TFFunnelForSequenceClassification,
"""token-classification""": TFFunnelForTokenClassification,
"""zero-shot""": TFFunnelForSequenceClassification,
}
if is_tf_available()
else {}
)
a__ = False
a__ = False
def _lowercase ( self : Optional[int] ) -> str:
"""simple docstring"""
__magic_name__ = TFFunnelModelTester(self )
__magic_name__ = ConfigTester(self , config_class=UpperCamelCase__ )
def _lowercase ( self : Tuple ) -> Any:
"""simple docstring"""
self.config_tester.run_common_tests()
def _lowercase ( self : Any ) -> Union[str, Any]:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*UpperCamelCase__ )
def _lowercase ( self : List[str] ) -> Optional[Any]:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_pretraining(*UpperCamelCase__ )
def _lowercase ( self : Tuple ) -> Union[str, Any]:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase__ )
def _lowercase ( self : Dict ) -> int:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*UpperCamelCase__ )
def _lowercase ( self : Any ) -> Union[str, Any]:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*UpperCamelCase__ )
@require_tf
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = (
(TFFunnelBaseModel, TFFunnelForMultipleChoice, TFFunnelForSequenceClassification) if is_tf_available() else ()
)
a__ = False
a__ = False
def _lowercase ( self : Union[str, Any] ) -> Tuple:
"""simple docstring"""
__magic_name__ = TFFunnelModelTester(self , base=UpperCamelCase__ )
__magic_name__ = ConfigTester(self , config_class=UpperCamelCase__ )
def _lowercase ( self : Dict ) -> Any:
"""simple docstring"""
self.config_tester.run_common_tests()
def _lowercase ( self : Optional[int] ) -> Optional[int]:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_base_model(*UpperCamelCase__ )
def _lowercase ( self : List[str] ) -> Any:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase__ )
def _lowercase ( self : int ) -> Dict:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*UpperCamelCase__ )
| 717 |
def a__ ( A_ ):
'''simple docstring'''
return " ".join(
"""""".join(word[::-1] ) if len(A_ ) > 4 else word for word in sentence.split() )
if __name__ == "__main__":
import doctest
doctest.testmod()
print(reverse_long_words('Hey wollef sroirraw'))
| 76 | 0 |
import pytest
from datasets import Dataset, DatasetDict, Features, NamedSplit, Value
from datasets.io.text import TextDatasetReader
from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases
def a__ ( A_, A_ ):
'''simple docstring'''
assert isinstance(A_, A_ )
assert dataset.num_rows == 4
assert dataset.num_columns == 1
assert dataset.column_names == ["text"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize("""keep_in_memory""", [False, True] )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = tmp_path / """cache"""
__magic_name__ = {"""text""": """string"""}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
__magic_name__ = TextDatasetReader(A_, cache_dir=A_, keep_in_memory=A_ ).read()
_check_text_dataset(A_, A_ )
@pytest.mark.parametrize(
"""features""", [
None,
{"""text""": """string"""},
{"""text""": """int32"""},
{"""text""": """float32"""},
], )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = tmp_path / """cache"""
__magic_name__ = {"""text""": """string"""}
__magic_name__ = features.copy() if features else default_expected_features
__magic_name__ = (
Features({feature: Value(A_ ) for feature, dtype in features.items()} ) if features is not None else None
)
__magic_name__ = TextDatasetReader(A_, features=A_, cache_dir=A_ ).read()
_check_text_dataset(A_, A_ )
@pytest.mark.parametrize("""split""", [None, NamedSplit("""train""" ), """train""", """test"""] )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = tmp_path / """cache"""
__magic_name__ = {"""text""": """string"""}
__magic_name__ = TextDatasetReader(A_, cache_dir=A_, split=A_ ).read()
_check_text_dataset(A_, A_ )
assert dataset.split == split if split else "train"
@pytest.mark.parametrize("""path_type""", [str, list] )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
if issubclass(A_, A_ ):
__magic_name__ = text_path
elif issubclass(A_, A_ ):
__magic_name__ = [text_path]
__magic_name__ = tmp_path / """cache"""
__magic_name__ = {"""text""": """string"""}
__magic_name__ = TextDatasetReader(A_, cache_dir=A_ ).read()
_check_text_dataset(A_, A_ )
def a__ ( A_, A_, A_=("train",) ):
'''simple docstring'''
assert isinstance(A_, A_ )
for split in splits:
__magic_name__ = dataset_dict[split]
assert dataset.num_rows == 4
assert dataset.num_columns == 1
assert dataset.column_names == ["text"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize("""keep_in_memory""", [False, True] )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = tmp_path / """cache"""
__magic_name__ = {"""text""": """string"""}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
__magic_name__ = TextDatasetReader({"""train""": text_path}, cache_dir=A_, keep_in_memory=A_ ).read()
_check_text_datasetdict(A_, A_ )
@pytest.mark.parametrize(
"""features""", [
None,
{"""text""": """string"""},
{"""text""": """int32"""},
{"""text""": """float32"""},
], )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = tmp_path / """cache"""
# CSV file loses col_1 string dtype information: default now is "int64" instead of "string"
__magic_name__ = {"""text""": """string"""}
__magic_name__ = features.copy() if features else default_expected_features
__magic_name__ = (
Features({feature: Value(A_ ) for feature, dtype in features.items()} ) if features is not None else None
)
__magic_name__ = TextDatasetReader({"""train""": text_path}, features=A_, cache_dir=A_ ).read()
_check_text_datasetdict(A_, A_ )
@pytest.mark.parametrize("""split""", [None, NamedSplit("""train""" ), """train""", """test"""] )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
if split:
__magic_name__ = {split: text_path}
else:
__magic_name__ = """train"""
__magic_name__ = {"""train""": text_path, """test""": text_path}
__magic_name__ = tmp_path / """cache"""
__magic_name__ = {"""text""": """string"""}
__magic_name__ = TextDatasetReader(A_, cache_dir=A_ ).read()
_check_text_datasetdict(A_, A_, splits=list(path.keys() ) )
assert all(dataset[split].split == split for split in path.keys() )
| 718 |
import os
import unittest
from transformers import FunnelTokenizer, FunnelTokenizerFast
from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = FunnelTokenizer
a__ = FunnelTokenizerFast
a__ = True
a__ = True
def _lowercase ( self : List[Any] ) -> str:
"""simple docstring"""
super().setUp()
__magic_name__ = [
"""<unk>""",
"""<cls>""",
"""<sep>""",
"""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] ) )
def _lowercase ( self : Dict , **UpperCamelCase__ : Tuple ) -> Union[str, Any]:
"""simple docstring"""
return FunnelTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase__ )
def _lowercase ( self : str , **UpperCamelCase__ : str ) -> List[str]:
"""simple docstring"""
return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **UpperCamelCase__ )
def _lowercase ( self : List[str] , UpperCamelCase__ : str ) -> List[Any]:
"""simple docstring"""
__magic_name__ = """UNwant\u00E9d,running"""
__magic_name__ = """unwanted, running"""
return input_text, output_text
def _lowercase ( self : Union[str, Any] ) -> Tuple:
"""simple docstring"""
__magic_name__ = self.tokenizer_class(self.vocab_file )
__magic_name__ = tokenizer.tokenize("""UNwant\u00E9d,running""" )
self.assertListEqual(UpperCamelCase__ , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) , [7, 4, 5, 10, 8, 9] )
def _lowercase ( self : str ) -> List[Any]:
"""simple docstring"""
__magic_name__ = self.get_tokenizers(do_lower_case=UpperCamelCase__ )
for tokenizer in tokenizers:
__magic_name__ = tokenizer("""UNwant\u00E9d,running""" )
__magic_name__ = len(inputs["""input_ids"""] ) - 1
self.assertListEqual(inputs["""token_type_ids"""] , [2] + [0] * sentence_len )
__magic_name__ = tokenizer("""UNwant\u00E9d,running""" , """UNwant\u00E9d,running""" )
self.assertListEqual(inputs["""token_type_ids"""] , [2] + [0] * sentence_len + [1] * sentence_len )
| 76 | 0 |
import shutil
import tempfile
import unittest
import numpy as np
import pytest
from transformers.testing_utils import require_vision
from transformers.utils import is_vision_available
if is_vision_available():
from PIL import Image
from transformers import AutoProcessor, BlipaProcessor, BlipImageProcessor, GPTaTokenizer, PreTrainedTokenizerFast
@require_vision
class UpperCAmelCase_ ( unittest.TestCase ):
'''simple docstring'''
def _lowercase ( self : int ) -> List[str]:
__magic_name__ = tempfile.mkdtemp()
__magic_name__ = BlipImageProcessor()
__magic_name__ = GPTaTokenizer.from_pretrained("""hf-internal-testing/tiny-random-GPT2Model""" )
__magic_name__ = BlipaProcessor(UpperCamelCase__ , UpperCamelCase__ )
processor.save_pretrained(self.tmpdirname )
def _lowercase ( self : Optional[Any] , **UpperCamelCase__ : int ) -> int:
return AutoProcessor.from_pretrained(self.tmpdirname , **UpperCamelCase__ ).tokenizer
def _lowercase ( self : Dict , **UpperCamelCase__ : List[Any] ) -> List[Any]:
return AutoProcessor.from_pretrained(self.tmpdirname , **UpperCamelCase__ ).image_processor
def _lowercase ( self : Optional[int] ) -> str:
shutil.rmtree(self.tmpdirname )
def _lowercase ( self : Optional[int] ) -> List[Any]:
__magic_name__ = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )]
__magic_name__ = [Image.fromarray(np.moveaxis(UpperCamelCase__ , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def _lowercase ( self : str ) -> List[Any]:
__magic_name__ = BlipaProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
__magic_name__ = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" )
__magic_name__ = self.get_image_processor(do_normalize=UpperCamelCase__ , padding_value=1.0 )
__magic_name__ = BlipaProcessor.from_pretrained(
self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=UpperCamelCase__ , padding_value=1.0 )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() )
self.assertIsInstance(processor.tokenizer , UpperCamelCase__ )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , UpperCamelCase__ )
def _lowercase ( self : str ) -> Dict:
__magic_name__ = self.get_image_processor()
__magic_name__ = self.get_tokenizer()
__magic_name__ = BlipaProcessor(tokenizer=UpperCamelCase__ , image_processor=UpperCamelCase__ )
__magic_name__ = self.prepare_image_inputs()
__magic_name__ = image_processor(UpperCamelCase__ , return_tensors="""np""" )
__magic_name__ = processor(images=UpperCamelCase__ , return_tensors="""np""" )
for key in input_feat_extract.keys():
self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 )
def _lowercase ( self : Dict ) -> int:
__magic_name__ = self.get_image_processor()
__magic_name__ = self.get_tokenizer()
__magic_name__ = BlipaProcessor(tokenizer=UpperCamelCase__ , image_processor=UpperCamelCase__ )
__magic_name__ = """lower newer"""
__magic_name__ = processor(text=UpperCamelCase__ )
__magic_name__ = tokenizer(UpperCamelCase__ , return_token_type_ids=UpperCamelCase__ )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key] )
def _lowercase ( self : Dict ) -> List[str]:
__magic_name__ = self.get_image_processor()
__magic_name__ = self.get_tokenizer()
__magic_name__ = BlipaProcessor(tokenizer=UpperCamelCase__ , image_processor=UpperCamelCase__ )
__magic_name__ = """lower newer"""
__magic_name__ = self.prepare_image_inputs()
__magic_name__ = processor(text=UpperCamelCase__ , images=UpperCamelCase__ )
self.assertListEqual(list(inputs.keys() ) , ["""pixel_values""", """input_ids""", """attention_mask"""] )
# test if it raises when no input is passed
with pytest.raises(UpperCamelCase__ ):
processor()
def _lowercase ( self : Optional[int] ) -> List[str]:
__magic_name__ = self.get_image_processor()
__magic_name__ = self.get_tokenizer()
__magic_name__ = BlipaProcessor(tokenizer=UpperCamelCase__ , image_processor=UpperCamelCase__ )
__magic_name__ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
__magic_name__ = processor.batch_decode(UpperCamelCase__ )
__magic_name__ = tokenizer.batch_decode(UpperCamelCase__ )
self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ )
def _lowercase ( self : List[str] ) -> Union[str, Any]:
__magic_name__ = self.get_image_processor()
__magic_name__ = self.get_tokenizer()
__magic_name__ = BlipaProcessor(tokenizer=UpperCamelCase__ , image_processor=UpperCamelCase__ )
__magic_name__ = """lower newer"""
__magic_name__ = self.prepare_image_inputs()
__magic_name__ = processor(text=UpperCamelCase__ , images=UpperCamelCase__ )
# For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask']
self.assertListEqual(list(inputs.keys() ) , ["""pixel_values""", """input_ids""", """attention_mask"""] )
| 719 |
from collections import deque
from .hash_table import HashTable
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
def __init__( self : int , *UpperCamelCase__ : Union[str, Any] , **UpperCamelCase__ : Optional[Any] ) -> Optional[Any]:
"""simple docstring"""
super().__init__(*UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : Optional[Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Any ) -> Dict:
"""simple docstring"""
__magic_name__ = deque([] ) if self.values[key] is None else self.values[key]
self.values[key].appendleft(UpperCamelCase__ )
__magic_name__ = self.values[key]
def _lowercase ( self : List[str] ) -> int:
"""simple docstring"""
return (
sum(self.charge_factor - len(UpperCamelCase__ ) for slot in self.values )
/ self.size_table
* self.charge_factor
)
def _lowercase ( self : Optional[Any] , UpperCamelCase__ : str , UpperCamelCase__ : Tuple=None ) -> str:
"""simple docstring"""
if not (
len(self.values[key] ) == self.charge_factor and self.values.count(UpperCamelCase__ ) == 0
):
return key
return super()._collision_resolution(UpperCamelCase__ , UpperCamelCase__ )
| 76 | 0 |
from typing import List
import numpy as np
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = {key: len(A_ ) for key, value in gen_kwargs.items() if isinstance(A_, A_ )}
if len(set(lists_lengths.values() ) ) > 1:
raise RuntimeError(
(
"""Sharding is ambiguous for this dataset: """
+ """we found several data sources lists of different lengths, and we don't know over which list we should parallelize:\n"""
+ """\n""".join(f'''\t- key {key} has length {length}''' for key, length in lists_lengths.items() )
+ """\nTo fix this, check the 'gen_kwargs' and make sure to use lists only for data sources, """
+ """and use tuples otherwise. In the end there should only be one single list, or several lists with the same length."""
) )
__magic_name__ = max(lists_lengths.values(), default=0 )
return max(1, A_ )
def a__ ( A_, A_ ):
'''simple docstring'''
__magic_name__ = []
for group_idx in range(A_ ):
__magic_name__ = num_shards // max_num_jobs + (group_idx < (num_shards % max_num_jobs))
if num_shards_to_add == 0:
break
__magic_name__ = shards_indices_per_group[-1].stop if shards_indices_per_group else 0
__magic_name__ = range(A_, start + num_shards_to_add )
shards_indices_per_group.append(A_ )
return shards_indices_per_group
def a__ ( A_, A_ ):
'''simple docstring'''
__magic_name__ = _number_of_shards_in_gen_kwargs(A_ )
if num_shards == 1:
return [dict(A_ )]
else:
__magic_name__ = _distribute_shards(num_shards=A_, max_num_jobs=A_ )
return [
{
key: [value[shard_idx] for shard_idx in shard_indices_per_group[group_idx]]
if isinstance(A_, A_ )
else value
for key, value in gen_kwargs.items()
}
for group_idx in range(len(A_ ) )
]
def a__ ( A_ ):
'''simple docstring'''
return {
key: [value for gen_kwargs in gen_kwargs_list for value in gen_kwargs[key]]
if isinstance(gen_kwargs_list[0][key], A_ )
else gen_kwargs_list[0][key]
for key in gen_kwargs_list[0]
}
def a__ ( A_, A_ ):
'''simple docstring'''
__magic_name__ = {len(A_ ) for value in gen_kwargs.values() if isinstance(A_, A_ )}
__magic_name__ = {}
for size in list_sizes:
__magic_name__ = list(range(A_ ) )
rng.shuffle(indices_per_size[size] )
# Now let's copy the gen_kwargs and shuffle the lists based on their sizes
__magic_name__ = dict(A_ )
for key, value in shuffled_kwargs.items():
if isinstance(A_, A_ ):
__magic_name__ = [value[i] for i in indices_per_size[len(A_ )]]
return shuffled_kwargs
| 720 |
# 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 json
import os
from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES
from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType
from ...utils.imports import is_botoa_available
from .config_args import SageMakerConfig
from .config_utils import (
DYNAMO_BACKENDS,
_ask_field,
_ask_options,
_convert_dynamo_backend,
_convert_mixed_precision,
_convert_sagemaker_distributed_mode,
_convert_yes_no_to_bool,
)
if is_botoa_available():
import botoa # noqa: F401
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = botoa.client("""iam""" )
__magic_name__ = {
"""Version""": """2012-10-17""",
"""Statement""": [
{"""Effect""": """Allow""", """Principal""": {"""Service""": """sagemaker.amazonaws.com"""}, """Action""": """sts:AssumeRole"""}
],
}
try:
# create the role, associated with the chosen trust policy
iam_client.create_role(
RoleName=A_, AssumeRolePolicyDocument=json.dumps(A_, indent=2 ) )
__magic_name__ = {
"""Version""": """2012-10-17""",
"""Statement""": [
{
"""Effect""": """Allow""",
"""Action""": [
"""sagemaker:*""",
"""ecr:GetDownloadUrlForLayer""",
"""ecr:BatchGetImage""",
"""ecr:BatchCheckLayerAvailability""",
"""ecr:GetAuthorizationToken""",
"""cloudwatch:PutMetricData""",
"""cloudwatch:GetMetricData""",
"""cloudwatch:GetMetricStatistics""",
"""cloudwatch:ListMetrics""",
"""logs:CreateLogGroup""",
"""logs:CreateLogStream""",
"""logs:DescribeLogStreams""",
"""logs:PutLogEvents""",
"""logs:GetLogEvents""",
"""s3:CreateBucket""",
"""s3:ListBucket""",
"""s3:GetBucketLocation""",
"""s3:GetObject""",
"""s3:PutObject""",
],
"""Resource""": """*""",
}
],
}
# attach policy to role
iam_client.put_role_policy(
RoleName=A_, PolicyName=f'''{role_name}_policy_permission''', PolicyDocument=json.dumps(A_, indent=2 ), )
except iam_client.exceptions.EntityAlreadyExistsException:
print(f'''role {role_name} already exists. Using existing one''' )
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = botoa.client("""iam""" )
return iam_client.get_role(RoleName=A_ )["Role"]["Arn"]
def a__ ( ):
'''simple docstring'''
__magic_name__ = _ask_options(
"""How do you want to authorize?""", ["""AWS Profile""", """Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) """], A_, )
__magic_name__ = None
if credentials_configuration == 0:
__magic_name__ = _ask_field("""Enter your AWS Profile name: [default] """, default="""default""" )
__magic_name__ = aws_profile
else:
print(
"""Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,"""
"""`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`""" )
__magic_name__ = _ask_field("""AWS Access Key ID: """ )
__magic_name__ = aws_access_key_id
__magic_name__ = _ask_field("""AWS Secret Access Key: """ )
__magic_name__ = aws_secret_access_key
__magic_name__ = _ask_field("""Enter your AWS Region: [us-east-1]""", default="""us-east-1""" )
__magic_name__ = aws_region
__magic_name__ = _ask_options(
"""Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?""", ["""Provide IAM Role name""", """Create new IAM role using credentials"""], A_, )
if role_management == 0:
__magic_name__ = _ask_field("""Enter your IAM role name: """ )
else:
__magic_name__ = """accelerate_sagemaker_execution_role"""
print(f'''Accelerate will create an iam role "{iam_role_name}" using the provided credentials''' )
_create_iam_role_for_sagemaker(A_ )
__magic_name__ = _ask_field(
"""Do you want to use custom Docker image? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
__magic_name__ = None
if is_custom_docker_image:
__magic_name__ = _ask_field("""Enter your Docker image: """, lambda A_ : str(A_ ).lower() )
__magic_name__ = _ask_field(
"""Do you want to provide SageMaker input channels with data locations? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
__magic_name__ = None
if is_sagemaker_inputs_enabled:
__magic_name__ = _ask_field(
"""Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): """, lambda A_ : str(A_ ).lower(), )
__magic_name__ = _ask_field(
"""Do you want to enable SageMaker metrics? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
__magic_name__ = None
if is_sagemaker_metrics_enabled:
__magic_name__ = _ask_field(
"""Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): """, lambda A_ : str(A_ ).lower(), )
__magic_name__ = _ask_options(
"""What is the distributed mode?""", ["""No distributed training""", """Data parallelism"""], _convert_sagemaker_distributed_mode, )
__magic_name__ = {}
__magic_name__ = _ask_field(
"""Do you wish to optimize your script with torch dynamo?[yes/NO]:""", _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
if use_dynamo:
__magic_name__ = """dynamo_"""
__magic_name__ = _ask_options(
"""Which dynamo backend would you like to use?""", [x.lower() for x in DYNAMO_BACKENDS], _convert_dynamo_backend, default=2, )
__magic_name__ = _ask_field(
"""Do you want to customize the defaults sent to torch.compile? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
if use_custom_options:
__magic_name__ = _ask_options(
"""Which mode do you want to use?""", A_, lambda A_ : TORCH_DYNAMO_MODES[int(A_ )], default="""default""", )
__magic_name__ = _ask_field(
"""Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
__magic_name__ = _ask_field(
"""Do you want to enable dynamic shape tracing? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
__magic_name__ = """Which EC2 instance type you want to use for your training?"""
if distributed_type != SageMakerDistributedType.NO:
__magic_name__ = _ask_options(
A_, A_, lambda A_ : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(A_ )] )
else:
eca_instance_query += "? [ml.p3.2xlarge]:"
__magic_name__ = _ask_field(A_, lambda A_ : str(A_ ).lower(), default="""ml.p3.2xlarge""" )
__magic_name__ = 1
if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL):
__magic_name__ = _ask_field(
"""How many machines do you want use? [1]: """, A_, default=1, )
__magic_name__ = _ask_options(
"""Do you wish to use FP16 or BF16 (mixed precision)?""", ["""no""", """fp16""", """bf16""", """fp8"""], _convert_mixed_precision, )
if use_dynamo and mixed_precision == "no":
print(
"""Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.""" )
return SageMakerConfig(
image_uri=A_, compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER, distributed_type=A_, use_cpu=A_, dynamo_config=A_, eca_instance_type=A_, profile=A_, region=A_, iam_role_name=A_, mixed_precision=A_, num_machines=A_, sagemaker_inputs_file=A_, sagemaker_metrics_file=A_, )
| 76 | 0 |
import argparse
import json
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import SegformerImageProcessor, SwinConfig, UperNetConfig, UperNetForSemanticSegmentation
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = 384
__magic_name__ = 7
if "tiny" in model_name:
__magic_name__ = 96
__magic_name__ = (2, 2, 6, 2)
__magic_name__ = (3, 6, 12, 24)
elif "small" in model_name:
__magic_name__ = 96
__magic_name__ = (2, 2, 18, 2)
__magic_name__ = (3, 6, 12, 24)
elif "base" in model_name:
__magic_name__ = 128
__magic_name__ = (2, 2, 18, 2)
__magic_name__ = (4, 8, 16, 32)
__magic_name__ = 12
__magic_name__ = 512
elif "large" in model_name:
__magic_name__ = 192
__magic_name__ = (2, 2, 18, 2)
__magic_name__ = (6, 12, 24, 48)
__magic_name__ = 12
__magic_name__ = 768
# set label information
__magic_name__ = 150
__magic_name__ = """huggingface/label-files"""
__magic_name__ = """ade20k-id2label.json"""
__magic_name__ = json.load(open(hf_hub_download(A_, A_, repo_type="""dataset""" ), """r""" ) )
__magic_name__ = {int(A_ ): v for k, v in idalabel.items()}
__magic_name__ = {v: k for k, v in idalabel.items()}
__magic_name__ = SwinConfig(
embed_dim=A_, depths=A_, num_heads=A_, window_size=A_, out_features=["""stage1""", """stage2""", """stage3""", """stage4"""], )
__magic_name__ = UperNetConfig(
backbone_config=A_, auxiliary_in_channels=A_, num_labels=A_, idalabel=A_, labelaid=A_, )
return config
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = []
# fmt: off
# stem
rename_keys.append(("""backbone.patch_embed.projection.weight""", """backbone.embeddings.patch_embeddings.projection.weight""") )
rename_keys.append(("""backbone.patch_embed.projection.bias""", """backbone.embeddings.patch_embeddings.projection.bias""") )
rename_keys.append(("""backbone.patch_embed.norm.weight""", """backbone.embeddings.norm.weight""") )
rename_keys.append(("""backbone.patch_embed.norm.bias""", """backbone.embeddings.norm.bias""") )
# stages
for i in range(len(config.backbone_config.depths ) ):
for j in range(config.backbone_config.depths[i] ):
rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.norm1.weight''', f'''backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.weight''') )
rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.norm1.bias''', f'''backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.bias''') )
rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.relative_position_bias_table''', f'''backbone.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table''') )
rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.relative_position_index''', f'''backbone.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index''') )
rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.proj.weight''', f'''backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight''') )
rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.proj.bias''', f'''backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias''') )
rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.norm2.weight''', f'''backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.weight''') )
rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.norm2.bias''', f'''backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.bias''') )
rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.ffn.layers.0.0.weight''', f'''backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight''') )
rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.ffn.layers.0.0.bias''', f'''backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias''') )
rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.ffn.layers.1.weight''', f'''backbone.encoder.layers.{i}.blocks.{j}.output.dense.weight''') )
rename_keys.append((f'''backbone.stages.{i}.blocks.{j}.ffn.layers.1.bias''', f'''backbone.encoder.layers.{i}.blocks.{j}.output.dense.bias''') )
if i < 3:
rename_keys.append((f'''backbone.stages.{i}.downsample.reduction.weight''', f'''backbone.encoder.layers.{i}.downsample.reduction.weight''') )
rename_keys.append((f'''backbone.stages.{i}.downsample.norm.weight''', f'''backbone.encoder.layers.{i}.downsample.norm.weight''') )
rename_keys.append((f'''backbone.stages.{i}.downsample.norm.bias''', f'''backbone.encoder.layers.{i}.downsample.norm.bias''') )
rename_keys.append((f'''backbone.norm{i}.weight''', f'''backbone.hidden_states_norms.stage{i+1}.weight''') )
rename_keys.append((f'''backbone.norm{i}.bias''', f'''backbone.hidden_states_norms.stage{i+1}.bias''') )
# decode head
rename_keys.extend(
[
("""decode_head.conv_seg.weight""", """decode_head.classifier.weight"""),
("""decode_head.conv_seg.bias""", """decode_head.classifier.bias"""),
("""auxiliary_head.conv_seg.weight""", """auxiliary_head.classifier.weight"""),
("""auxiliary_head.conv_seg.bias""", """auxiliary_head.classifier.bias"""),
] )
# fmt: on
return rename_keys
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = dct.pop(A_ )
__magic_name__ = val
def a__ ( A_, A_ ):
'''simple docstring'''
__magic_name__ = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )]
for i in range(len(backbone_config.depths ) ):
__magic_name__ = num_features[i]
for j in range(backbone_config.depths[i] ):
# fmt: off
# read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias)
__magic_name__ = state_dict.pop(f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.weight''' )
__magic_name__ = state_dict.pop(f'''backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.bias''' )
# next, add query, keys and values (in that order) to the state dict
__magic_name__ = in_proj_weight[:dim, :]
__magic_name__ = in_proj_bias[: dim]
__magic_name__ = in_proj_weight[
dim : dim * 2, :
]
__magic_name__ = in_proj_bias[
dim : dim * 2
]
__magic_name__ = in_proj_weight[
-dim :, :
]
__magic_name__ = in_proj_bias[-dim :]
# fmt: on
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ , __magic_name__ = x.shape
__magic_name__ = x.reshape(A_, 4, in_channel // 4 )
__magic_name__ = x[:, [0, 2, 1, 3], :].transpose(1, 2 ).reshape(A_, A_ )
return x
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ , __magic_name__ = x.shape
__magic_name__ = x.reshape(A_, in_channel // 4, 4 )
__magic_name__ = x[:, :, [0, 2, 1, 3]].transpose(1, 2 ).reshape(A_, A_ )
return x
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = x.shape[0]
__magic_name__ = x.reshape(4, in_channel // 4 )
__magic_name__ = x[[0, 2, 1, 3], :].transpose(0, 1 ).reshape(A_ )
return x
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = x.shape[0]
__magic_name__ = x.reshape(in_channel // 4, 4 )
__magic_name__ = x[:, [0, 2, 1, 3]].transpose(0, 1 ).reshape(A_ )
return x
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = {
"""upernet-swin-tiny""": """https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K_20210531_112542-e380ad3e.pth""",
"""upernet-swin-small""": """https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_small_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K/upernet_swin_small_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K_20210526_192015-ee2fff1c.pth""",
"""upernet-swin-base""": """https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_base_patch4_window12_512x512_160k_ade20k_pretrain_384x384_22K/upernet_swin_base_patch4_window12_512x512_160k_ade20k_pretrain_384x384_22K_20210531_125459-429057bf.pth""",
"""upernet-swin-large""": """https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_large_patch4_window12_512x512_pretrain_384x384_22K_160k_ade20k/upernet_swin_large_patch4_window12_512x512_pretrain_384x384_22K_160k_ade20k_20220318_091743-9ba68901.pth""",
}
__magic_name__ = model_name_to_url[model_name]
__magic_name__ = torch.hub.load_state_dict_from_url(A_, map_location="""cpu""", file_name=A_ )[
"""state_dict"""
]
for name, param in state_dict.items():
print(A_, param.shape )
__magic_name__ = get_upernet_config(A_ )
__magic_name__ = UperNetForSemanticSegmentation(A_ )
model.eval()
# replace "bn" => "batch_norm"
for key in state_dict.copy().keys():
__magic_name__ = state_dict.pop(A_ )
if "bn" in key:
__magic_name__ = key.replace("""bn""", """batch_norm""" )
__magic_name__ = val
# rename keys
__magic_name__ = create_rename_keys(A_ )
for src, dest in rename_keys:
rename_key(A_, A_, A_ )
read_in_q_k_v(A_, config.backbone_config )
# fix downsample parameters
for key, value in state_dict.items():
if "downsample" in key:
if "reduction" in key:
__magic_name__ = reverse_correct_unfold_reduction_order(A_ )
if "norm" in key:
__magic_name__ = reverse_correct_unfold_norm_order(A_ )
model.load_state_dict(A_ )
# verify on image
__magic_name__ = """https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg"""
__magic_name__ = Image.open(requests.get(A_, stream=A_ ).raw ).convert("""RGB""" )
__magic_name__ = SegformerImageProcessor()
__magic_name__ = processor(A_, return_tensors="""pt""" ).pixel_values
with torch.no_grad():
__magic_name__ = model(A_ )
__magic_name__ = outputs.logits
print(logits.shape )
print("""First values of logits:""", logits[0, 0, :3, :3] )
# assert values
if model_name == "upernet-swin-tiny":
__magic_name__ = torch.tensor(
[[-7.5958, -7.5958, -7.4302], [-7.5958, -7.5958, -7.4302], [-7.4797, -7.4797, -7.3068]] )
elif model_name == "upernet-swin-small":
__magic_name__ = torch.tensor(
[[-7.1921, -7.1921, -6.9532], [-7.1921, -7.1921, -6.9532], [-7.0908, -7.0908, -6.8534]] )
elif model_name == "upernet-swin-base":
__magic_name__ = torch.tensor(
[[-6.5851, -6.5851, -6.4330], [-6.5851, -6.5851, -6.4330], [-6.4763, -6.4763, -6.3254]] )
elif model_name == "upernet-swin-large":
__magic_name__ = torch.tensor(
[[-7.5297, -7.5297, -7.3802], [-7.5297, -7.5297, -7.3802], [-7.4044, -7.4044, -7.2586]] )
print("""Logits:""", outputs.logits[0, 0, :3, :3] )
assert torch.allclose(outputs.logits[0, 0, :3, :3], A_, atol=1e-4 )
print("""Looks ok!""" )
if pytorch_dump_folder_path is not None:
print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' )
model.save_pretrained(A_ )
print(f'''Saving processor to {pytorch_dump_folder_path}''' )
processor.save_pretrained(A_ )
if push_to_hub:
print(f'''Pushing model and processor for {model_name} to hub''' )
model.push_to_hub(f'''openmmlab/{model_name}''' )
processor.push_to_hub(f'''openmmlab/{model_name}''' )
if __name__ == "__main__":
__lowerCAmelCase : Any = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--model_name',
default='upernet-swin-tiny',
type=str,
choices=[F'''upernet-swin-{size}''' for size in ['tiny', 'small', 'base', 'large']],
help='Name of the Swin + UperNet model you\'d like to convert.',
)
parser.add_argument(
'--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.'
)
parser.add_argument(
'--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.'
)
__lowerCAmelCase : Optional[int] = parser.parse_args()
convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
| 721 |
from typing import Dict, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
convert_to_rgb,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
OPENAI_CLIP_MEAN,
OPENAI_CLIP_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
__lowerCAmelCase : Dict = logging.get_logger(__name__)
if is_vision_available():
import PIL
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = ["""pixel_values"""]
def __init__( self : Optional[Any] , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : bool = True , UpperCamelCase__ : Union[int, float] = 1 / 255 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : bool = True , **UpperCamelCase__ : int , ) -> None:
"""simple docstring"""
super().__init__(**UpperCamelCase__ )
__magic_name__ = size if size is not None else {"""shortest_edge""": 224}
__magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ )
__magic_name__ = crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
__magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ , param_name="""crop_size""" )
__magic_name__ = do_resize
__magic_name__ = size
__magic_name__ = resample
__magic_name__ = do_center_crop
__magic_name__ = crop_size
__magic_name__ = do_rescale
__magic_name__ = rescale_factor
__magic_name__ = do_normalize
__magic_name__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
__magic_name__ = image_std if image_std is not None else OPENAI_CLIP_STD
__magic_name__ = do_convert_rgb
def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Tuple , ) -> np.ndarray:
"""simple docstring"""
__magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ )
if "shortest_edge" not in size:
raise ValueError(F'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' )
__magic_name__ = get_resize_output_image_size(UpperCamelCase__ , size=size["""shortest_edge"""] , default_to_square=UpperCamelCase__ )
return resize(UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : Tuple , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Tuple , ) -> np.ndarray:
"""simple docstring"""
__magic_name__ = get_size_dict(UpperCamelCase__ )
if "height" not in size or "width" not in size:
raise ValueError(F'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' )
return center_crop(UpperCamelCase__ , size=(size["""height"""], size["""width"""]) , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : Any , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[int, float] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Optional[Any] , ) -> Optional[int]:
"""simple docstring"""
return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Dict , ) -> np.ndarray:
"""simple docstring"""
return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : List[Any] , UpperCamelCase__ : ImageInput , UpperCamelCase__ : bool = None , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : int = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : float = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , UpperCamelCase__ : Optional[ChannelDimension] = ChannelDimension.FIRST , **UpperCamelCase__ : Dict , ) -> PIL.Image.Image:
"""simple docstring"""
__magic_name__ = do_resize if do_resize is not None else self.do_resize
__magic_name__ = size if size is not None else self.size
__magic_name__ = get_size_dict(UpperCamelCase__ , param_name="""size""" , default_to_square=UpperCamelCase__ )
__magic_name__ = resample if resample is not None else self.resample
__magic_name__ = do_center_crop if do_center_crop is not None else self.do_center_crop
__magic_name__ = crop_size if crop_size is not None else self.crop_size
__magic_name__ = get_size_dict(UpperCamelCase__ , param_name="""crop_size""" , default_to_square=UpperCamelCase__ )
__magic_name__ = do_rescale if do_rescale is not None else self.do_rescale
__magic_name__ = rescale_factor if rescale_factor is not None else self.rescale_factor
__magic_name__ = do_normalize if do_normalize is not None else self.do_normalize
__magic_name__ = image_mean if image_mean is not None else self.image_mean
__magic_name__ = image_std if image_std is not None else self.image_std
__magic_name__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
__magic_name__ = make_list_of_images(UpperCamelCase__ )
if not valid_images(UpperCamelCase__ ):
raise ValueError(
"""Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
"""torch.Tensor, tf.Tensor or jax.ndarray.""" )
if do_resize and size is None:
raise ValueError("""Size must be specified if do_resize is True.""" )
if do_center_crop and crop_size is None:
raise ValueError("""Crop size must be specified if do_center_crop is True.""" )
if do_rescale and rescale_factor is None:
raise ValueError("""Rescale factor must be specified if do_rescale is True.""" )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError("""Image mean and std must be specified if do_normalize is True.""" )
# PIL RGBA images are converted to RGB
if do_convert_rgb:
__magic_name__ = [convert_to_rgb(UpperCamelCase__ ) for image in images]
# All transformations expect numpy arrays.
__magic_name__ = [to_numpy_array(UpperCamelCase__ ) for image in images]
if do_resize:
__magic_name__ = [self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) for image in images]
if do_center_crop:
__magic_name__ = [self.center_crop(image=UpperCamelCase__ , size=UpperCamelCase__ ) for image in images]
if do_rescale:
__magic_name__ = [self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) for image in images]
if do_normalize:
__magic_name__ = [self.normalize(image=UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ ) for image in images]
__magic_name__ = [to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) for image in images]
__magic_name__ = {"""pixel_values""": images}
return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ )
| 76 | 0 |
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 KandinskyPipeline, KandinskyPriorPipeline
else:
from .pipeline_kandinsky import KandinskyPipeline
from .pipeline_kandinsky_imgaimg import KandinskyImgaImgPipeline
from .pipeline_kandinsky_inpaint import KandinskyInpaintPipeline
from .pipeline_kandinsky_prior import KandinskyPriorPipeline, KandinskyPriorPipelineOutput
from .text_encoder import MultilingualCLIP
| 700 |
import unittest
from transformers import AutoTokenizer, NystromformerConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
NystromformerForMaskedLM,
NystromformerForMultipleChoice,
NystromformerForQuestionAnswering,
NystromformerForSequenceClassification,
NystromformerForTokenClassification,
NystromformerModel,
)
from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST
class UpperCAmelCase_ :
'''simple docstring'''
def __init__( self : Any , UpperCamelCase__ : Any , UpperCamelCase__ : Tuple=13 , UpperCamelCase__ : Dict=7 , UpperCamelCase__ : Dict=True , UpperCamelCase__ : List[str]=True , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : int=True , UpperCamelCase__ : Optional[int]=99 , UpperCamelCase__ : List[Any]=32 , UpperCamelCase__ : Any=5 , UpperCamelCase__ : List[Any]=4 , UpperCamelCase__ : str=37 , UpperCamelCase__ : Any="gelu" , UpperCamelCase__ : int=0.1 , UpperCamelCase__ : Tuple=0.1 , UpperCamelCase__ : Dict=512 , UpperCamelCase__ : Union[str, Any]=16 , UpperCamelCase__ : Dict=2 , UpperCamelCase__ : Any=0.02 , UpperCamelCase__ : Any=3 , UpperCamelCase__ : Dict=4 , UpperCamelCase__ : List[Any]=None , ) -> Union[str, Any]:
"""simple docstring"""
__magic_name__ = parent
__magic_name__ = batch_size
__magic_name__ = seq_length
__magic_name__ = is_training
__magic_name__ = use_input_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_labels
__magic_name__ = num_choices
__magic_name__ = scope
def _lowercase ( self : Any ) -> Any:
"""simple docstring"""
__magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__magic_name__ = None
if self.use_input_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__ = None
__magic_name__ = None
__magic_name__ = None
if self.use_labels:
__magic_name__ = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
__magic_name__ = ids_tensor([self.batch_size] , self.num_choices )
__magic_name__ = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def _lowercase ( self : Tuple ) -> Any:
"""simple docstring"""
return NystromformerConfig(
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=UpperCamelCase__ , initializer_range=self.initializer_range , )
def _lowercase ( self : Any , UpperCamelCase__ : Tuple , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : str , UpperCamelCase__ : int , UpperCamelCase__ : str , UpperCamelCase__ : Dict , UpperCamelCase__ : str ) -> Tuple:
"""simple docstring"""
__magic_name__ = NystromformerModel(config=UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
__magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ )
__magic_name__ = model(UpperCamelCase__ , token_type_ids=UpperCamelCase__ )
__magic_name__ = model(UpperCamelCase__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def _lowercase ( self : Optional[int] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : str , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] ) -> str:
"""simple docstring"""
__magic_name__ = NystromformerForMaskedLM(config=UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
__magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def _lowercase ( self : Tuple , UpperCamelCase__ : Any , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Any , UpperCamelCase__ : Any ) -> Optional[Any]:
"""simple docstring"""
__magic_name__ = NystromformerForQuestionAnswering(config=UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
__magic_name__ = model(
UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , start_positions=UpperCamelCase__ , end_positions=UpperCamelCase__ , )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def _lowercase ( self : Optional[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Dict , UpperCamelCase__ : Dict , UpperCamelCase__ : Any ) -> Optional[int]:
"""simple docstring"""
__magic_name__ = self.num_labels
__magic_name__ = NystromformerForSequenceClassification(UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
__magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def _lowercase ( self : Any , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : str , UpperCamelCase__ : Any ) -> Dict:
"""simple docstring"""
__magic_name__ = self.num_labels
__magic_name__ = NystromformerForTokenClassification(config=UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
__magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : int ) -> Optional[Any]:
"""simple docstring"""
__magic_name__ = self.num_choices
__magic_name__ = NystromformerForMultipleChoice(config=UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
__magic_name__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
__magic_name__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
__magic_name__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
__magic_name__ = model(
UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def _lowercase ( self : int ) -> List[Any]:
"""simple docstring"""
__magic_name__ = self.prepare_config_and_inputs()
(
(
__magic_name__
) , (
__magic_name__
) , (
__magic_name__
) , (
__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""": input_mask}
return config, inputs_dict
@require_torch
class UpperCAmelCase_ ( _A , _A , unittest.TestCase ):
'''simple docstring'''
a__ = (
(
NystromformerModel,
NystromformerForMaskedLM,
NystromformerForMultipleChoice,
NystromformerForQuestionAnswering,
NystromformerForSequenceClassification,
NystromformerForTokenClassification,
)
if is_torch_available()
else ()
)
a__ = (
{
"""feature-extraction""": NystromformerModel,
"""fill-mask""": NystromformerForMaskedLM,
"""question-answering""": NystromformerForQuestionAnswering,
"""text-classification""": NystromformerForSequenceClassification,
"""token-classification""": NystromformerForTokenClassification,
"""zero-shot""": NystromformerForSequenceClassification,
}
if is_torch_available()
else {}
)
a__ = False
a__ = False
def _lowercase ( self : Union[str, Any] ) -> Union[str, Any]:
"""simple docstring"""
__magic_name__ = NystromformerModelTester(self )
__magic_name__ = ConfigTester(self , config_class=UpperCamelCase__ , hidden_size=37 )
def _lowercase ( self : Tuple ) -> Any:
"""simple docstring"""
self.config_tester.run_common_tests()
def _lowercase ( self : Optional[Any] ) -> Any:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*UpperCamelCase__ )
def _lowercase ( self : Optional[Any] ) -> int:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
__magic_name__ = type
self.model_tester.create_and_check_model(*UpperCamelCase__ )
def _lowercase ( self : List[Any] ) -> List[Any]:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase__ )
def _lowercase ( self : Union[str, Any] ) -> str:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*UpperCamelCase__ )
def _lowercase ( self : Dict ) -> List[Any]:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*UpperCamelCase__ )
def _lowercase ( self : str ) -> int:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase__ )
def _lowercase ( self : List[Any] ) -> List[str]:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*UpperCamelCase__ )
@slow
def _lowercase ( self : str ) -> Tuple:
"""simple docstring"""
for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__magic_name__ = NystromformerModel.from_pretrained(UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
@require_torch
class UpperCAmelCase_ ( unittest.TestCase ):
'''simple docstring'''
@slow
def _lowercase ( self : Union[str, Any] ) -> Optional[Any]:
"""simple docstring"""
__magic_name__ = NystromformerModel.from_pretrained("""uw-madison/nystromformer-512""" )
__magic_name__ = torch.tensor([[0, 1, 2, 3, 4, 5]] )
with torch.no_grad():
__magic_name__ = model(UpperCamelCase__ )[0]
__magic_name__ = torch.Size((1, 6, 768) )
self.assertEqual(output.shape , UpperCamelCase__ )
__magic_name__ = torch.tensor(
[[[-0.4532, -0.0936, 0.5137], [-0.2676, 0.0628, 0.6186], [-0.3629, -0.1726, 0.4716]]] )
self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCamelCase__ , atol=1E-4 ) )
@slow
def _lowercase ( self : int ) -> str:
"""simple docstring"""
__magic_name__ = """the [MASK] of Belgium is Brussels"""
__magic_name__ = AutoTokenizer.from_pretrained("""uw-madison/nystromformer-512""" )
__magic_name__ = NystromformerForMaskedLM.from_pretrained("""uw-madison/nystromformer-512""" )
__magic_name__ = tokenizer(UpperCamelCase__ , return_tensors="""pt""" )
with torch.no_grad():
__magic_name__ = model(encoding.input_ids ).logits
__magic_name__ = token_logits[:, 2, :].argmax(-1 )[0]
self.assertEqual(tokenizer.decode(UpperCamelCase__ ) , """capital""" )
| 76 | 0 |
from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments
def a__ ( ):
'''simple docstring'''
__magic_name__ = HfArgumentParser(A_ )
__magic_name__ = parser.parse_args_into_dataclasses()[0]
__magic_name__ = TensorFlowBenchmark(args=A_ )
try:
__magic_name__ = parser.parse_args_into_dataclasses()[0]
except ValueError as e:
__magic_name__ = """Arg --no_{0} is no longer used, please use --no-{0} instead."""
__magic_name__ = """ """.join(str(A_ ).split(""" """ )[:-1] )
__magic_name__ = """"""
__magic_name__ = eval(str(A_ ).split(""" """ )[-1] )
__magic_name__ = []
for arg in depreciated_args:
# arg[2:] removes '--'
if arg[2:] in TensorFlowBenchmark.deprecated_args:
# arg[5:] removes '--no_'
full_error_msg += arg_error_msg.format(arg[5:] )
else:
wrong_args.append(A_ )
if len(A_ ) > 0:
__magic_name__ = full_error_msg + begin_error_msg + str(A_ )
raise ValueError(A_ )
benchmark.run()
if __name__ == "__main__":
main()
| 701 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__lowerCAmelCase : Tuple = logging.get_logger(__name__)
__lowerCAmelCase : Union[str, Any] = {
'microsoft/cvt-13': 'https://huggingface.co/microsoft/cvt-13/resolve/main/config.json',
# See all Cvt models at https://huggingface.co/models?filter=cvt
}
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = """cvt"""
def __init__( self : Dict , UpperCamelCase__ : Optional[int]=3 , UpperCamelCase__ : List[Any]=[7, 3, 3] , UpperCamelCase__ : Any=[4, 2, 2] , UpperCamelCase__ : Optional[Any]=[2, 1, 1] , UpperCamelCase__ : Union[str, Any]=[64, 192, 384] , UpperCamelCase__ : Dict=[1, 3, 6] , UpperCamelCase__ : Any=[1, 2, 10] , UpperCamelCase__ : List[str]=[4.0, 4.0, 4.0] , UpperCamelCase__ : Dict=[0.0, 0.0, 0.0] , UpperCamelCase__ : Tuple=[0.0, 0.0, 0.0] , UpperCamelCase__ : Optional[Any]=[0.0, 0.0, 0.1] , UpperCamelCase__ : str=[True, True, True] , UpperCamelCase__ : Optional[Any]=[False, False, True] , UpperCamelCase__ : Union[str, Any]=["dw_bn", "dw_bn", "dw_bn"] , UpperCamelCase__ : List[Any]=[3, 3, 3] , UpperCamelCase__ : Any=[1, 1, 1] , UpperCamelCase__ : Optional[int]=[2, 2, 2] , UpperCamelCase__ : Any=[1, 1, 1] , UpperCamelCase__ : List[str]=[1, 1, 1] , UpperCamelCase__ : int=0.02 , UpperCamelCase__ : int=1E-12 , **UpperCamelCase__ : int , ) -> Dict:
"""simple docstring"""
super().__init__(**UpperCamelCase__ )
__magic_name__ = num_channels
__magic_name__ = patch_sizes
__magic_name__ = patch_stride
__magic_name__ = patch_padding
__magic_name__ = embed_dim
__magic_name__ = num_heads
__magic_name__ = depth
__magic_name__ = mlp_ratio
__magic_name__ = attention_drop_rate
__magic_name__ = drop_rate
__magic_name__ = drop_path_rate
__magic_name__ = qkv_bias
__magic_name__ = cls_token
__magic_name__ = qkv_projection_method
__magic_name__ = kernel_qkv
__magic_name__ = padding_kv
__magic_name__ = stride_kv
__magic_name__ = padding_q
__magic_name__ = stride_q
__magic_name__ = initializer_range
__magic_name__ = layer_norm_eps
| 76 | 0 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__lowerCAmelCase : Tuple = logging.get_logger(__name__)
__lowerCAmelCase : Union[str, Any] = {
'microsoft/cvt-13': 'https://huggingface.co/microsoft/cvt-13/resolve/main/config.json',
# See all Cvt models at https://huggingface.co/models?filter=cvt
}
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = """cvt"""
def __init__( self : Dict , UpperCamelCase__ : Optional[int]=3 , UpperCamelCase__ : List[Any]=[7, 3, 3] , UpperCamelCase__ : Any=[4, 2, 2] , UpperCamelCase__ : Optional[Any]=[2, 1, 1] , UpperCamelCase__ : Union[str, Any]=[64, 192, 384] , UpperCamelCase__ : Dict=[1, 3, 6] , UpperCamelCase__ : Any=[1, 2, 10] , UpperCamelCase__ : List[str]=[4.0, 4.0, 4.0] , UpperCamelCase__ : Dict=[0.0, 0.0, 0.0] , UpperCamelCase__ : Tuple=[0.0, 0.0, 0.0] , UpperCamelCase__ : Optional[Any]=[0.0, 0.0, 0.1] , UpperCamelCase__ : str=[True, True, True] , UpperCamelCase__ : Optional[Any]=[False, False, True] , UpperCamelCase__ : Union[str, Any]=["dw_bn", "dw_bn", "dw_bn"] , UpperCamelCase__ : List[Any]=[3, 3, 3] , UpperCamelCase__ : Any=[1, 1, 1] , UpperCamelCase__ : Optional[int]=[2, 2, 2] , UpperCamelCase__ : Any=[1, 1, 1] , UpperCamelCase__ : List[str]=[1, 1, 1] , UpperCamelCase__ : int=0.02 , UpperCamelCase__ : int=1E-12 , **UpperCamelCase__ : int , ) -> Dict:
"""simple docstring"""
super().__init__(**UpperCamelCase__ )
__magic_name__ = num_channels
__magic_name__ = patch_sizes
__magic_name__ = patch_stride
__magic_name__ = patch_padding
__magic_name__ = embed_dim
__magic_name__ = num_heads
__magic_name__ = depth
__magic_name__ = mlp_ratio
__magic_name__ = attention_drop_rate
__magic_name__ = drop_rate
__magic_name__ = drop_path_rate
__magic_name__ = qkv_bias
__magic_name__ = cls_token
__magic_name__ = qkv_projection_method
__magic_name__ = kernel_qkv
__magic_name__ = padding_kv
__magic_name__ = stride_kv
__magic_name__ = padding_q
__magic_name__ = stride_q
__magic_name__ = initializer_range
__magic_name__ = layer_norm_eps
| 702 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
__lowerCAmelCase : List[str] = {
'configuration_canine': ['CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CanineConfig'],
'tokenization_canine': ['CanineTokenizer'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowerCAmelCase : Optional[Any] = [
'CANINE_PRETRAINED_MODEL_ARCHIVE_LIST',
'CanineForMultipleChoice',
'CanineForQuestionAnswering',
'CanineForSequenceClassification',
'CanineForTokenClassification',
'CanineLayer',
'CanineModel',
'CaninePreTrainedModel',
'load_tf_weights_in_canine',
]
if TYPE_CHECKING:
from .configuration_canine import CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP, CanineConfig
from .tokenization_canine import CanineTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_canine import (
CANINE_PRETRAINED_MODEL_ARCHIVE_LIST,
CanineForMultipleChoice,
CanineForQuestionAnswering,
CanineForSequenceClassification,
CanineForTokenClassification,
CanineLayer,
CanineModel,
CaninePreTrainedModel,
load_tf_weights_in_canine,
)
else:
import sys
__lowerCAmelCase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 76 | 0 |
import os
import sys
__lowerCAmelCase : Optional[Any] = os.path.join(os.path.dirname(__file__), 'src')
sys.path.append(SRC_DIR)
from transformers import (
AutoConfig,
AutoModel,
AutoModelForCausalLM,
AutoModelForMaskedLM,
AutoModelForQuestionAnswering,
AutoModelForSequenceClassification,
AutoTokenizer,
add_start_docstrings,
)
__lowerCAmelCase : Union[str, Any] = [
'torch',
'numpy',
'tokenizers',
'filelock',
'requests',
'tqdm',
'regex',
'sentencepiece',
'sacremoses',
'importlib_metadata',
'huggingface_hub',
]
@add_start_docstrings(AutoConfig.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoConfig.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoTokenizer.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoTokenizer.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoModel.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoModel.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoModelForCausalLM.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoModelForCausalLM.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoModelForMaskedLM.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoModelForMaskedLM.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoModelForSequenceClassification.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoModelForSequenceClassification.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoModelForQuestionAnswering.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoModelForQuestionAnswering.from_pretrained(*A_, **A_ )
| 703 |
import argparse
import torch
from transformers import (
WavaVecaConfig,
WavaVecaFeatureExtractor,
WavaVecaForAudioFrameClassification,
WavaVecaForSequenceClassification,
WavaVecaForXVector,
logging,
)
logging.set_verbosity_info()
__lowerCAmelCase : str = logging.get_logger(__name__)
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = WavaVecaForSequenceClassification.from_pretrained(A_, config=A_ )
__magic_name__ = downstream_dict["""projector.weight"""]
__magic_name__ = downstream_dict["""projector.bias"""]
__magic_name__ = downstream_dict["""model.post_net.linear.weight"""]
__magic_name__ = downstream_dict["""model.post_net.linear.bias"""]
return model
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = WavaVecaForAudioFrameClassification.from_pretrained(A_, config=A_ )
__magic_name__ = downstream_dict["""model.linear.weight"""]
__magic_name__ = downstream_dict["""model.linear.bias"""]
return model
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = WavaVecaForXVector.from_pretrained(A_, config=A_ )
__magic_name__ = downstream_dict["""connector.weight"""]
__magic_name__ = downstream_dict["""connector.bias"""]
for i, kernel_size in enumerate(hf_config.tdnn_kernel ):
__magic_name__ = downstream_dict[
f'''model.framelevel_feature_extractor.module.{i}.kernel.weight'''
]
__magic_name__ = downstream_dict[f'''model.framelevel_feature_extractor.module.{i}.kernel.bias''']
__magic_name__ = downstream_dict["""model.utterancelevel_feature_extractor.linear1.weight"""]
__magic_name__ = downstream_dict["""model.utterancelevel_feature_extractor.linear1.bias"""]
__magic_name__ = downstream_dict["""model.utterancelevel_feature_extractor.linear2.weight"""]
__magic_name__ = downstream_dict["""model.utterancelevel_feature_extractor.linear2.bias"""]
__magic_name__ = downstream_dict["""objective.W"""]
return model
@torch.no_grad()
def a__ ( A_, A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = torch.load(A_, map_location="""cpu""" )
__magic_name__ = checkpoint["""Downstream"""]
__magic_name__ = WavaVecaConfig.from_pretrained(A_ )
__magic_name__ = WavaVecaFeatureExtractor.from_pretrained(
A_, return_attention_mask=A_, do_normalize=A_ )
__magic_name__ = hf_config.architectures[0]
if arch.endswith("""ForSequenceClassification""" ):
__magic_name__ = convert_classification(A_, A_, A_ )
elif arch.endswith("""ForAudioFrameClassification""" ):
__magic_name__ = convert_diarization(A_, A_, A_ )
elif arch.endswith("""ForXVector""" ):
__magic_name__ = convert_xvector(A_, A_, A_ )
else:
raise NotImplementedError(f'''S3PRL weights conversion is not supported for {arch}''' )
if hf_config.use_weighted_layer_sum:
__magic_name__ = checkpoint["""Featurizer"""]["""weights"""]
hf_feature_extractor.save_pretrained(A_ )
hf_model.save_pretrained(A_ )
if __name__ == "__main__":
__lowerCAmelCase : Optional[Any] = argparse.ArgumentParser()
parser.add_argument(
'--base_model_name', default=None, type=str, help='Name of the huggingface pretrained base model.'
)
parser.add_argument('--config_path', default=None, type=str, help='Path to the huggingface classifier config.')
parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to the s3prl checkpoint.')
parser.add_argument('--model_dump_path', default=None, type=str, help='Path to the final converted model.')
__lowerCAmelCase : str = parser.parse_args()
convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
| 76 | 0 |
import unicodedata
from dataclasses import dataclass
from typing import Optional, Union
import numpy as np
from transformers.data.data_collator import DataCollatorMixin
from transformers.file_utils import PaddingStrategy
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
def a__ ( A_, A_, A_, A_ ):
'''simple docstring'''
if isinstance(A_, A_ ):
__magic_name__ = np.full((len(A_ ), sequence_length, 2), A_ )
else:
__magic_name__ = np.full((len(A_ ), sequence_length), A_ )
for i, tensor in enumerate(A_ ):
if padding_side == "right":
if isinstance(A_, A_ ):
__magic_name__ = tensor[:sequence_length]
else:
__magic_name__ = tensor[:sequence_length]
else:
if isinstance(A_, A_ ):
__magic_name__ = tensor[:sequence_length]
else:
__magic_name__ = tensor[:sequence_length]
return out_tensor.tolist()
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = ord(A_ )
if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126):
return True
__magic_name__ = unicodedata.category(A_ )
if cat.startswith("""P""" ):
return True
return False
@dataclass
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = 42
a__ = True
a__ = None
a__ = None
a__ = -1_00
a__ = """pt"""
def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : Tuple ) -> Union[str, Any]:
"""simple docstring"""
import torch
__magic_name__ = """label""" if """label""" in features[0].keys() else """labels"""
__magic_name__ = [feature[label_name] for feature in features] if label_name in features[0].keys() else None
__magic_name__ = self.tokenizer.pad(
UpperCamelCase__ , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="""pt""" if labels is None else None , )
if labels is None:
return batch
__magic_name__ = torch.tensor(batch["""entity_ids"""] ).shape[1]
__magic_name__ = self.tokenizer.padding_side
if padding_side == "right":
__magic_name__ = [
list(UpperCamelCase__ ) + [self.label_pad_token_id] * (sequence_length - len(UpperCamelCase__ )) for label in labels
]
else:
__magic_name__ = [
[self.label_pad_token_id] * (sequence_length - len(UpperCamelCase__ )) + list(UpperCamelCase__ ) for label in labels
]
__magic_name__ = [feature["""ner_tags"""] for feature in features]
__magic_name__ = padding_tensor(UpperCamelCase__ , -1 , UpperCamelCase__ , UpperCamelCase__ )
__magic_name__ = [feature["""original_entity_spans"""] for feature in features]
__magic_name__ = padding_tensor(UpperCamelCase__ , (-1, -1) , UpperCamelCase__ , UpperCamelCase__ )
__magic_name__ = {k: torch.tensor(UpperCamelCase__ , dtype=torch.intaa ) for k, v in batch.items()}
return batch
| 704 |
import pytest
from datasets import Dataset, DatasetDict, Features, NamedSplit, Value
from datasets.io.text import TextDatasetReader
from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases
def a__ ( A_, A_ ):
'''simple docstring'''
assert isinstance(A_, A_ )
assert dataset.num_rows == 4
assert dataset.num_columns == 1
assert dataset.column_names == ["text"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize("""keep_in_memory""", [False, True] )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = tmp_path / """cache"""
__magic_name__ = {"""text""": """string"""}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
__magic_name__ = TextDatasetReader(A_, cache_dir=A_, keep_in_memory=A_ ).read()
_check_text_dataset(A_, A_ )
@pytest.mark.parametrize(
"""features""", [
None,
{"""text""": """string"""},
{"""text""": """int32"""},
{"""text""": """float32"""},
], )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = tmp_path / """cache"""
__magic_name__ = {"""text""": """string"""}
__magic_name__ = features.copy() if features else default_expected_features
__magic_name__ = (
Features({feature: Value(A_ ) for feature, dtype in features.items()} ) if features is not None else None
)
__magic_name__ = TextDatasetReader(A_, features=A_, cache_dir=A_ ).read()
_check_text_dataset(A_, A_ )
@pytest.mark.parametrize("""split""", [None, NamedSplit("""train""" ), """train""", """test"""] )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = tmp_path / """cache"""
__magic_name__ = {"""text""": """string"""}
__magic_name__ = TextDatasetReader(A_, cache_dir=A_, split=A_ ).read()
_check_text_dataset(A_, A_ )
assert dataset.split == split if split else "train"
@pytest.mark.parametrize("""path_type""", [str, list] )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
if issubclass(A_, A_ ):
__magic_name__ = text_path
elif issubclass(A_, A_ ):
__magic_name__ = [text_path]
__magic_name__ = tmp_path / """cache"""
__magic_name__ = {"""text""": """string"""}
__magic_name__ = TextDatasetReader(A_, cache_dir=A_ ).read()
_check_text_dataset(A_, A_ )
def a__ ( A_, A_, A_=("train",) ):
'''simple docstring'''
assert isinstance(A_, A_ )
for split in splits:
__magic_name__ = dataset_dict[split]
assert dataset.num_rows == 4
assert dataset.num_columns == 1
assert dataset.column_names == ["text"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize("""keep_in_memory""", [False, True] )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = tmp_path / """cache"""
__magic_name__ = {"""text""": """string"""}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
__magic_name__ = TextDatasetReader({"""train""": text_path}, cache_dir=A_, keep_in_memory=A_ ).read()
_check_text_datasetdict(A_, A_ )
@pytest.mark.parametrize(
"""features""", [
None,
{"""text""": """string"""},
{"""text""": """int32"""},
{"""text""": """float32"""},
], )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = tmp_path / """cache"""
# CSV file loses col_1 string dtype information: default now is "int64" instead of "string"
__magic_name__ = {"""text""": """string"""}
__magic_name__ = features.copy() if features else default_expected_features
__magic_name__ = (
Features({feature: Value(A_ ) for feature, dtype in features.items()} ) if features is not None else None
)
__magic_name__ = TextDatasetReader({"""train""": text_path}, features=A_, cache_dir=A_ ).read()
_check_text_datasetdict(A_, A_ )
@pytest.mark.parametrize("""split""", [None, NamedSplit("""train""" ), """train""", """test"""] )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
if split:
__magic_name__ = {split: text_path}
else:
__magic_name__ = """train"""
__magic_name__ = {"""train""": text_path, """test""": text_path}
__magic_name__ = tmp_path / """cache"""
__magic_name__ = {"""text""": """string"""}
__magic_name__ = TextDatasetReader(A_, cache_dir=A_ ).read()
_check_text_datasetdict(A_, A_, splits=list(path.keys() ) )
assert all(dataset[split].split == split for split in path.keys() )
| 76 | 0 |
import torch
from transformers import AutoModel
class UpperCAmelCase_ ( torch.nn.Module ):
'''simple docstring'''
def __init__( self : Tuple , UpperCamelCase__ : Any="sayef/fsner-bert-base-uncased" ) -> Optional[int]:
"""simple docstring"""
super(UpperCamelCase__ , self ).__init__()
__magic_name__ = AutoModel.from_pretrained(UpperCamelCase__ , return_dict=UpperCamelCase__ )
__magic_name__ = torch.nn.CosineSimilarity(3 , 1E-08 )
__magic_name__ = torch.nn.Softmax(dim=1 )
def _lowercase ( self : int , **UpperCamelCase__ : Union[str, Any] ) -> Optional[Any]:
"""simple docstring"""
return self.bert(**UpperCamelCase__ ).last_hidden_state
def _lowercase ( self : Any , UpperCamelCase__ : Union[str, Any] ) -> str:
"""simple docstring"""
return token_embeddings.sum(2 , keepdim=UpperCamelCase__ )
def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Tuple , UpperCamelCase__ : int=1 ) -> List[Any]:
"""simple docstring"""
return self.softmax(T * self.cos(UpperCamelCase__ , UpperCamelCase__ ) )
def _lowercase ( self : int , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str] ) -> str:
"""simple docstring"""
__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(**UpperCamelCase__ )
__magic_name__ = self.BERT(**UpperCamelCase__ )
__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(UpperCamelCase__ ):
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
| 705 |
from typing import Dict, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
IMAGENET_STANDARD_MEAN,
IMAGENET_STANDARD_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, logging
__lowerCAmelCase : Union[str, Any] = logging.get_logger(__name__)
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = ["""pixel_values"""]
def __init__( self : str , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Dict[str, int]] = None , UpperCamelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : bool = True , UpperCamelCase__ : Union[int, float] = 1 / 255 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , **UpperCamelCase__ : List[Any] , ) -> None:
"""simple docstring"""
super().__init__(**UpperCamelCase__ )
__magic_name__ = size if size is not None else {"""shortest_edge""": 256}
__magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ )
__magic_name__ = crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
__magic_name__ = get_size_dict(UpperCamelCase__ )
__magic_name__ = do_resize
__magic_name__ = size
__magic_name__ = resample
__magic_name__ = do_center_crop
__magic_name__ = crop_size
__magic_name__ = do_rescale
__magic_name__ = rescale_factor
__magic_name__ = do_normalize
__magic_name__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
__magic_name__ = image_std if image_std is not None else IMAGENET_STANDARD_STD
def _lowercase ( self : Any , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Tuple , ) -> np.ndarray:
"""simple docstring"""
__magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ )
if "shortest_edge" not in size:
raise ValueError(F'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' )
__magic_name__ = get_resize_output_image_size(UpperCamelCase__ , size=size["""shortest_edge"""] , default_to_square=UpperCamelCase__ )
return resize(UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : str , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : str , ) -> np.ndarray:
"""simple docstring"""
__magic_name__ = get_size_dict(UpperCamelCase__ )
return center_crop(UpperCamelCase__ , size=(size["""height"""], size["""width"""]) , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : Tuple , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : float , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Any ) -> np.ndarray:
"""simple docstring"""
return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : List[str] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : str , ) -> np.ndarray:
"""simple docstring"""
return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : Optional[Any] , UpperCamelCase__ : ImageInput , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Optional[float] = None , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , UpperCamelCase__ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **UpperCamelCase__ : int , ) -> Dict:
"""simple docstring"""
__magic_name__ = do_resize if do_resize is not None else self.do_resize
__magic_name__ = size if size is not None else self.size
__magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ )
__magic_name__ = resample if resample is not None else self.resample
__magic_name__ = do_center_crop if do_center_crop is not None else self.do_center_crop
__magic_name__ = crop_size if crop_size is not None else self.crop_size
__magic_name__ = get_size_dict(UpperCamelCase__ )
__magic_name__ = do_rescale if do_rescale is not None else self.do_rescale
__magic_name__ = rescale_factor if rescale_factor is not None else self.rescale_factor
__magic_name__ = do_normalize if do_normalize is not None else self.do_normalize
__magic_name__ = image_mean if image_mean is not None else self.image_mean
__magic_name__ = image_std if image_std is not None else self.image_std
__magic_name__ = make_list_of_images(UpperCamelCase__ )
if not valid_images(UpperCamelCase__ ):
raise ValueError(
"""Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
"""torch.Tensor, tf.Tensor or jax.ndarray.""" )
if do_resize and size is None:
raise ValueError("""Size must be specified if do_resize is True.""" )
if do_center_crop and crop_size is None:
raise ValueError("""Crop size must be specified if do_center_crop is True.""" )
if do_rescale and rescale_factor is None:
raise ValueError("""Rescale factor must be specified if do_rescale is True.""" )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError("""Image mean and std must be specified if do_normalize is True.""" )
# All transformations expect numpy arrays.
__magic_name__ = [to_numpy_array(UpperCamelCase__ ) for image in images]
if do_resize:
__magic_name__ = [self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) for image in images]
if do_center_crop:
__magic_name__ = [self.center_crop(image=UpperCamelCase__ , size=UpperCamelCase__ ) for image in images]
if do_rescale:
__magic_name__ = [self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) for image in images]
if do_normalize:
__magic_name__ = [self.normalize(image=UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ ) for image in images]
__magic_name__ = [to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) for image in images]
__magic_name__ = {"""pixel_values""": images}
return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ )
| 76 | 0 |
from dataclasses import dataclass
from typing import Optional, Tuple
import torch
from torch import nn
from transformers import RobertaPreTrainedModel, XLMRobertaConfig, XLMRobertaModel
from transformers.utils import ModelOutput
@dataclass
class UpperCAmelCase_ ( _A ):
a__ = None
a__ = None
a__ = None
a__ = None
class UpperCAmelCase_ ( _A ):
def __init__( self : Optional[int] , UpperCamelCase__ : List[str]=1 , UpperCamelCase__ : List[str]=0 , UpperCamelCase__ : Any=2 , UpperCamelCase__ : Union[str, Any]=512 , UpperCamelCase__ : Dict="cls" , UpperCamelCase__ : List[Any]=False , UpperCamelCase__ : Optional[int]=True , **UpperCamelCase__ : int , ) -> Optional[Any]:
"""simple docstring"""
super().__init__(pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__ )
__magic_name__ = project_dim
__magic_name__ = pooler_fn
__magic_name__ = learn_encoder
__magic_name__ = use_attention_mask
class UpperCAmelCase_ ( _A ):
a__ = [R"""pooler""", R"""logit_scale"""]
a__ = [R"""position_ids""", R"""predictions.decoder.bias"""]
a__ = """roberta"""
a__ = RobertaSeriesConfig
def __init__( self : str , UpperCamelCase__ : List[str] ) -> List[str]:
"""simple docstring"""
super().__init__(UpperCamelCase__ )
__magic_name__ = XLMRobertaModel(UpperCamelCase__ )
__magic_name__ = nn.Linear(config.hidden_size , config.project_dim )
__magic_name__ = getattr(UpperCamelCase__ , """has_pre_transformation""" , UpperCamelCase__ )
if self.has_pre_transformation:
__magic_name__ = nn.Linear(config.hidden_size , config.project_dim )
__magic_name__ = nn.LayerNorm(config.hidden_size , eps=config.layer_norm_eps )
self.post_init()
def _lowercase ( self : str , UpperCamelCase__ : Optional[torch.Tensor] = None , UpperCamelCase__ : Optional[torch.Tensor] = None , UpperCamelCase__ : Optional[torch.Tensor] = None , UpperCamelCase__ : Optional[torch.Tensor] = None , UpperCamelCase__ : Optional[torch.Tensor] = None , UpperCamelCase__ : Optional[torch.Tensor] = None , UpperCamelCase__ : Optional[torch.Tensor] = None , UpperCamelCase__ : Optional[torch.Tensor] = None , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Optional[bool] = None , ) -> str:
"""simple docstring"""
__magic_name__ = return_dict if return_dict is not None else self.config.use_return_dict
__magic_name__ = self.base_model(
input_ids=UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , position_ids=UpperCamelCase__ , head_mask=UpperCamelCase__ , inputs_embeds=UpperCamelCase__ , encoder_hidden_states=UpperCamelCase__ , encoder_attention_mask=UpperCamelCase__ , output_attentions=UpperCamelCase__ , output_hidden_states=True if self.has_pre_transformation else output_hidden_states , return_dict=UpperCamelCase__ , )
if self.has_pre_transformation:
__magic_name__ = outputs["""hidden_states"""][-2]
__magic_name__ = self.pre_LN(UpperCamelCase__ )
__magic_name__ = self.transformation_pre(UpperCamelCase__ )
return TransformationModelOutput(
projection_state=UpperCamelCase__ , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
else:
__magic_name__ = self.transformation(outputs.last_hidden_state )
return TransformationModelOutput(
projection_state=UpperCamelCase__ , last_hidden_state=outputs.last_hidden_state , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
| 706 |
import math
def a__ ( A_, A_ = 0, A_ = 0 ):
'''simple docstring'''
__magic_name__ = end or len(A_ )
for i in range(A_, A_ ):
__magic_name__ = i
__magic_name__ = array[i]
while temp_index != start and temp_index_value < array[temp_index - 1]:
__magic_name__ = array[temp_index - 1]
temp_index -= 1
__magic_name__ = temp_index_value
return array
def a__ ( A_, A_, A_ ): # Max Heap
'''simple docstring'''
__magic_name__ = index
__magic_name__ = 2 * index + 1 # Left Node
__magic_name__ = 2 * index + 2 # Right Node
if left_index < heap_size and array[largest] < array[left_index]:
__magic_name__ = left_index
if right_index < heap_size and array[largest] < array[right_index]:
__magic_name__ = right_index
if largest != index:
__magic_name__ , __magic_name__ = array[largest], array[index]
heapify(A_, A_, A_ )
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = len(A_ )
for i in range(n // 2, -1, -1 ):
heapify(A_, A_, A_ )
for i in range(n - 1, 0, -1 ):
__magic_name__ , __magic_name__ = array[0], array[i]
heapify(A_, 0, A_ )
return array
def a__ ( A_, A_, A_, A_ ):
'''simple docstring'''
if (array[first_index] > array[middle_index]) != (
array[first_index] > array[last_index]
):
return array[first_index]
elif (array[middle_index] > array[first_index]) != (
array[middle_index] > array[last_index]
):
return array[middle_index]
else:
return array[last_index]
def a__ ( A_, A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = low
__magic_name__ = high
while True:
while array[i] < pivot:
i += 1
j -= 1
while pivot < array[j]:
j -= 1
if i >= j:
return i
__magic_name__ , __magic_name__ = array[j], array[i]
i += 1
def a__ ( A_ ):
'''simple docstring'''
if len(A_ ) == 0:
return array
__magic_name__ = 2 * math.ceil(math.loga(len(A_ ) ) )
__magic_name__ = 16
return intro_sort(A_, 0, len(A_ ), A_, A_ )
def a__ ( A_, A_, A_, A_, A_ ):
'''simple docstring'''
while end - start > size_threshold:
if max_depth == 0:
return heap_sort(A_ )
max_depth -= 1
__magic_name__ = median_of_a(A_, A_, start + ((end - start) // 2) + 1, end - 1 )
__magic_name__ = partition(A_, A_, A_, A_ )
intro_sort(A_, A_, A_, A_, A_ )
__magic_name__ = p
return insertion_sort(A_, A_, A_ )
if __name__ == "__main__":
import doctest
doctest.testmod()
__lowerCAmelCase : str = input('Enter numbers separated by a comma : ').strip()
__lowerCAmelCase : List[Any] = [float(item) for item in user_input.split(',')]
print(sort(unsorted))
| 76 | 0 |
import os
from bleurt import score # From: git+https://github.com/google-research/bleurt.git
import datasets
__lowerCAmelCase : Optional[int] = datasets.logging.get_logger(__name__)
__lowerCAmelCase : Tuple = '\\n@inproceedings{bleurt,\n title={BLEURT: Learning Robust Metrics for Text Generation},\n author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh},\n booktitle={ACL},\n year={2020},\n url={https://arxiv.org/abs/2004.04696}\n}\n'
__lowerCAmelCase : List[str] = '\\nBLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018)\nand then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune\nit for your specific application (the latter is expected to perform better).\n\nSee the project\'s README at https://github.com/google-research/bleurt#readme for more information.\n'
__lowerCAmelCase : Optional[Any] = '\nBLEURT score.\n\nArgs:\n `predictions` (list of str): prediction/candidate sentences\n `references` (list of str): reference sentences\n `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None.\n\nReturns:\n \'scores\': List of scores.\nExamples:\n\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> bleurt = datasets.load_metric("bleurt")\n >>> results = bleurt.compute(predictions=predictions, references=references)\n >>> print([round(v, 2) for v in results["scores"]])\n [1.03, 1.04]\n'
__lowerCAmelCase : Any = {
'bleurt-tiny-128': 'https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip',
'bleurt-tiny-512': 'https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip',
'bleurt-base-128': 'https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip',
'bleurt-base-512': 'https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip',
'bleurt-large-128': 'https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip',
'bleurt-large-512': 'https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip',
'BLEURT-20-D3': 'https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip',
'BLEURT-20-D6': 'https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip',
'BLEURT-20-D12': 'https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip',
'BLEURT-20': 'https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip',
}
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class UpperCAmelCase_ ( datasets.Metric ):
'''simple docstring'''
def _lowercase ( self : Optional[int] ) -> Dict:
"""simple docstring"""
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , homepage="""https://github.com/google-research/bleurt""" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"""predictions""": datasets.Value("""string""" , id="""sequence""" ),
"""references""": datasets.Value("""string""" , id="""sequence""" ),
} ) , codebase_urls=["""https://github.com/google-research/bleurt"""] , reference_urls=["""https://github.com/google-research/bleurt""", """https://arxiv.org/abs/2004.04696"""] , )
def _lowercase ( self : List[str] , UpperCamelCase__ : Optional[Any] ) -> int:
"""simple docstring"""
if self.config_name == "default":
logger.warning(
"""Using default BLEURT-Base checkpoint for sequence maximum length 128. """
"""You can use a bigger model for better results with e.g.: datasets.load_metric('bleurt', 'bleurt-large-512').""" )
__magic_name__ = """bleurt-base-128"""
if self.config_name.lower() in CHECKPOINT_URLS:
__magic_name__ = self.config_name.lower()
elif self.config_name.upper() in CHECKPOINT_URLS:
__magic_name__ = self.config_name.upper()
else:
raise KeyError(
F'''{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}''' )
# download the model checkpoint specified by self.config_name and set up the scorer
__magic_name__ = dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name] )
__magic_name__ = score.BleurtScorer(os.path.join(UpperCamelCase__ , UpperCamelCase__ ) )
def _lowercase ( self : int , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : List[Any] ) -> List[Any]:
"""simple docstring"""
__magic_name__ = self.scorer.score(references=UpperCamelCase__ , candidates=UpperCamelCase__ )
return {"scores": scores}
| 707 |
import argparse
import json
import re
from pathlib import Path
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import (
MobileNetVaConfig,
MobileNetVaForImageClassification,
MobileNetVaImageProcessor,
load_tf_weights_in_mobilenet_va,
)
from transformers.utils import logging
logging.set_verbosity_info()
__lowerCAmelCase : str = logging.get_logger(__name__)
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = MobileNetVaConfig(layer_norm_eps=0.001 )
if "_quant" in model_name:
raise ValueError("""Quantized models are not supported.""" )
__magic_name__ = re.match(R"""^mobilenet_v1_([^_]*)_([^_]*)$""", A_ )
if matches:
__magic_name__ = float(matches[1] )
__magic_name__ = int(matches[2] )
# The TensorFlow version of MobileNetV1 predicts 1001 classes instead of
# the usual 1000. The first class (index 0) is "background".
__magic_name__ = 1001
__magic_name__ = """imagenet-1k-id2label.json"""
__magic_name__ = """huggingface/label-files"""
__magic_name__ = json.load(open(hf_hub_download(A_, A_, repo_type="""dataset""" ), """r""" ) )
__magic_name__ = {int(A_ ) + 1: v for k, v in idalabel.items()}
__magic_name__ = """background"""
__magic_name__ = idalabel
__magic_name__ = {v: k for k, v in idalabel.items()}
return config
def a__ ( ):
'''simple docstring'''
__magic_name__ = """http://images.cocodataset.org/val2017/000000039769.jpg"""
__magic_name__ = Image.open(requests.get(A_, stream=A_ ).raw )
return im
@torch.no_grad()
def a__ ( A_, A_, A_, A_=False ):
'''simple docstring'''
__magic_name__ = get_mobilenet_va_config(A_ )
# Load 🤗 model
__magic_name__ = MobileNetVaForImageClassification(A_ ).eval()
# Load weights from TensorFlow checkpoint
load_tf_weights_in_mobilenet_va(A_, A_, A_ )
# Check outputs on an image, prepared by MobileNetV1ImageProcessor
__magic_name__ = MobileNetVaImageProcessor(
crop_size={"""width""": config.image_size, """height""": config.image_size}, size={"""shortest_edge""": config.image_size + 32}, )
__magic_name__ = image_processor(images=prepare_img(), return_tensors="""pt""" )
__magic_name__ = model(**A_ )
__magic_name__ = outputs.logits
assert logits.shape == (1, 1001)
if model_name == "mobilenet_v1_1.0_224":
__magic_name__ = torch.tensor([-4.1739, -1.1233, 3.1205] )
elif model_name == "mobilenet_v1_0.75_192":
__magic_name__ = torch.tensor([-3.9440, -2.3141, -0.3333] )
else:
__magic_name__ = None
if expected_logits is not None:
assert torch.allclose(logits[0, :3], A_, atol=1e-4 )
Path(A_ ).mkdir(exist_ok=A_ )
print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' )
model.save_pretrained(A_ )
print(f'''Saving image processor to {pytorch_dump_folder_path}''' )
image_processor.save_pretrained(A_ )
if push_to_hub:
print("""Pushing to the hub...""" )
__magic_name__ = """google/""" + model_name
image_processor.push_to_hub(A_ )
model.push_to_hub(A_ )
if __name__ == "__main__":
__lowerCAmelCase : str = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--model_name',
default='mobilenet_v1_1.0_224',
type=str,
help='Name of the MobileNetV1 model you\'d like to convert. Should in the form \'mobilenet_v1_<depth>_<size>\'.',
)
parser.add_argument(
'--checkpoint_path', required=True, type=str, help='Path to the original TensorFlow checkpoint (.ckpt file).'
)
parser.add_argument(
'--pytorch_dump_folder_path', required=True, type=str, help='Path to the output PyTorch model directory.'
)
parser.add_argument(
'--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.'
)
__lowerCAmelCase : str = parser.parse_args()
convert_movilevit_checkpoint(
args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub
)
| 76 | 0 |
import tempfile
import torch
from diffusers import (
DEISMultistepScheduler,
DPMSolverMultistepScheduler,
DPMSolverSinglestepScheduler,
UniPCMultistepScheduler,
)
from .test_schedulers import SchedulerCommonTest
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = (DPMSolverSinglestepScheduler,)
a__ = (("""num_inference_steps""", 25),)
def _lowercase ( self : Optional[Any] , **UpperCamelCase__ : int ) -> Any:
"""simple docstring"""
__magic_name__ = {
"""num_train_timesteps""": 1000,
"""beta_start""": 0.0001,
"""beta_end""": 0.02,
"""beta_schedule""": """linear""",
"""solver_order""": 2,
"""prediction_type""": """epsilon""",
"""thresholding""": False,
"""sample_max_value""": 1.0,
"""algorithm_type""": """dpmsolver++""",
"""solver_type""": """midpoint""",
"""lambda_min_clipped""": -float("""inf""" ),
"""variance_type""": None,
}
config.update(**UpperCamelCase__ )
return config
def _lowercase ( self : List[Any] , UpperCamelCase__ : Any=0 , **UpperCamelCase__ : List[Any] ) -> str:
"""simple docstring"""
__magic_name__ = dict(self.forward_default_kwargs )
__magic_name__ = kwargs.pop("""num_inference_steps""" , UpperCamelCase__ )
__magic_name__ = self.dummy_sample
__magic_name__ = 0.1 * sample
__magic_name__ = [residual + 0.2, residual + 0.15, residual + 0.10]
for scheduler_class in self.scheduler_classes:
__magic_name__ = self.get_scheduler_config(**UpperCamelCase__ )
__magic_name__ = scheduler_class(**UpperCamelCase__ )
scheduler.set_timesteps(UpperCamelCase__ )
# copy over dummy past residuals
__magic_name__ = dummy_past_residuals[: scheduler.config.solver_order]
with tempfile.TemporaryDirectory() as tmpdirname:
scheduler.save_config(UpperCamelCase__ )
__magic_name__ = scheduler_class.from_pretrained(UpperCamelCase__ )
new_scheduler.set_timesteps(UpperCamelCase__ )
# copy over dummy past residuals
__magic_name__ = dummy_past_residuals[: new_scheduler.config.solver_order]
__magic_name__ , __magic_name__ = sample, sample
for t in range(UpperCamelCase__ , time_step + scheduler.config.solver_order + 1 ):
__magic_name__ = scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample
__magic_name__ = new_scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample
assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical"
def _lowercase ( self : Optional[int] ) -> List[Any]:
"""simple docstring"""
pass
def _lowercase ( self : Optional[Any] , UpperCamelCase__ : Dict=0 , **UpperCamelCase__ : Any ) -> Any:
"""simple docstring"""
__magic_name__ = dict(self.forward_default_kwargs )
__magic_name__ = kwargs.pop("""num_inference_steps""" , UpperCamelCase__ )
__magic_name__ = self.dummy_sample
__magic_name__ = 0.1 * sample
__magic_name__ = [residual + 0.2, residual + 0.15, residual + 0.10]
for scheduler_class in self.scheduler_classes:
__magic_name__ = self.get_scheduler_config()
__magic_name__ = scheduler_class(**UpperCamelCase__ )
scheduler.set_timesteps(UpperCamelCase__ )
# copy over dummy past residuals (must be after setting timesteps)
__magic_name__ = dummy_past_residuals[: scheduler.config.solver_order]
with tempfile.TemporaryDirectory() as tmpdirname:
scheduler.save_config(UpperCamelCase__ )
__magic_name__ = scheduler_class.from_pretrained(UpperCamelCase__ )
# copy over dummy past residuals
new_scheduler.set_timesteps(UpperCamelCase__ )
# copy over dummy past residual (must be after setting timesteps)
__magic_name__ = dummy_past_residuals[: new_scheduler.config.solver_order]
__magic_name__ = scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample
__magic_name__ = new_scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ).prev_sample
assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical"
def _lowercase ( self : List[str] , UpperCamelCase__ : List[Any]=None , **UpperCamelCase__ : List[str] ) -> Any:
"""simple docstring"""
if scheduler is None:
__magic_name__ = self.scheduler_classes[0]
__magic_name__ = self.get_scheduler_config(**UpperCamelCase__ )
__magic_name__ = scheduler_class(**UpperCamelCase__ )
__magic_name__ = self.scheduler_classes[0]
__magic_name__ = self.get_scheduler_config(**UpperCamelCase__ )
__magic_name__ = scheduler_class(**UpperCamelCase__ )
__magic_name__ = 10
__magic_name__ = self.dummy_model()
__magic_name__ = self.dummy_sample_deter
scheduler.set_timesteps(UpperCamelCase__ )
for i, t in enumerate(scheduler.timesteps ):
__magic_name__ = model(UpperCamelCase__ , UpperCamelCase__ )
__magic_name__ = scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ).prev_sample
return sample
def _lowercase ( self : Optional[Any] ) -> int:
"""simple docstring"""
__magic_name__ = DPMSolverSinglestepScheduler(**self.get_scheduler_config() )
__magic_name__ = 50
__magic_name__ = self.dummy_model()
__magic_name__ = self.dummy_sample_deter
scheduler.set_timesteps(UpperCamelCase__ )
# make sure that the first t is uneven
for i, t in enumerate(scheduler.timesteps[3:] ):
__magic_name__ = model(UpperCamelCase__ , UpperCamelCase__ )
__magic_name__ = scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ).prev_sample
__magic_name__ = torch.mean(torch.abs(UpperCamelCase__ ) )
assert abs(result_mean.item() - 0.2574 ) < 1E-3
def _lowercase ( self : str ) -> str:
"""simple docstring"""
for timesteps in [25, 50, 100, 999, 1000]:
self.check_over_configs(num_train_timesteps=UpperCamelCase__ )
def _lowercase ( self : List[Any] ) -> Optional[Any]:
"""simple docstring"""
__magic_name__ = DPMSolverSinglestepScheduler(**self.get_scheduler_config() )
__magic_name__ = self.full_loop(scheduler=UpperCamelCase__ )
__magic_name__ = torch.mean(torch.abs(UpperCamelCase__ ) )
assert abs(result_mean.item() - 0.2791 ) < 1E-3
__magic_name__ = DEISMultistepScheduler.from_config(scheduler.config )
__magic_name__ = DPMSolverMultistepScheduler.from_config(scheduler.config )
__magic_name__ = UniPCMultistepScheduler.from_config(scheduler.config )
__magic_name__ = DPMSolverSinglestepScheduler.from_config(scheduler.config )
__magic_name__ = self.full_loop(scheduler=UpperCamelCase__ )
__magic_name__ = torch.mean(torch.abs(UpperCamelCase__ ) )
assert abs(result_mean.item() - 0.2791 ) < 1E-3
def _lowercase ( self : Optional[int] ) -> List[str]:
"""simple docstring"""
self.check_over_configs(thresholding=UpperCamelCase__ )
for order in [1, 2, 3]:
for solver_type in ["midpoint", "heun"]:
for threshold in [0.5, 1.0, 2.0]:
for prediction_type in ["epsilon", "sample"]:
self.check_over_configs(
thresholding=UpperCamelCase__ , prediction_type=UpperCamelCase__ , sample_max_value=UpperCamelCase__ , algorithm_type="""dpmsolver++""" , solver_order=UpperCamelCase__ , solver_type=UpperCamelCase__ , )
def _lowercase ( self : Dict ) -> Optional[Any]:
"""simple docstring"""
for prediction_type in ["epsilon", "v_prediction"]:
self.check_over_configs(prediction_type=UpperCamelCase__ )
def _lowercase ( self : List[Any] ) -> Any:
"""simple docstring"""
for algorithm_type in ["dpmsolver", "dpmsolver++"]:
for solver_type in ["midpoint", "heun"]:
for order in [1, 2, 3]:
for prediction_type in ["epsilon", "sample"]:
self.check_over_configs(
solver_order=UpperCamelCase__ , solver_type=UpperCamelCase__ , prediction_type=UpperCamelCase__ , algorithm_type=UpperCamelCase__ , )
__magic_name__ = self.full_loop(
solver_order=UpperCamelCase__ , solver_type=UpperCamelCase__ , prediction_type=UpperCamelCase__ , algorithm_type=UpperCamelCase__ , )
assert not torch.isnan(UpperCamelCase__ ).any(), "Samples have nan numbers"
def _lowercase ( self : List[Any] ) -> str:
"""simple docstring"""
self.check_over_configs(lower_order_final=UpperCamelCase__ )
self.check_over_configs(lower_order_final=UpperCamelCase__ )
def _lowercase ( self : str ) -> Union[str, Any]:
"""simple docstring"""
self.check_over_configs(lambda_min_clipped=-float("""inf""" ) )
self.check_over_configs(lambda_min_clipped=-5.1 )
def _lowercase ( self : List[str] ) -> List[str]:
"""simple docstring"""
self.check_over_configs(variance_type=UpperCamelCase__ )
self.check_over_configs(variance_type="""learned_range""" )
def _lowercase ( self : List[str] ) -> Optional[int]:
"""simple docstring"""
for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]:
self.check_over_forward(num_inference_steps=UpperCamelCase__ , time_step=0 )
def _lowercase ( self : str ) -> Any:
"""simple docstring"""
__magic_name__ = self.full_loop()
__magic_name__ = torch.mean(torch.abs(UpperCamelCase__ ) )
assert abs(result_mean.item() - 0.2791 ) < 1E-3
def _lowercase ( self : Optional[Any] ) -> Any:
"""simple docstring"""
__magic_name__ = self.full_loop(use_karras_sigmas=UpperCamelCase__ )
__magic_name__ = torch.mean(torch.abs(UpperCamelCase__ ) )
assert abs(result_mean.item() - 0.2248 ) < 1E-3
def _lowercase ( self : Optional[int] ) -> List[str]:
"""simple docstring"""
__magic_name__ = self.full_loop(prediction_type="""v_prediction""" )
__magic_name__ = torch.mean(torch.abs(UpperCamelCase__ ) )
assert abs(result_mean.item() - 0.1453 ) < 1E-3
def _lowercase ( self : Union[str, Any] ) -> str:
"""simple docstring"""
__magic_name__ = self.full_loop(prediction_type="""v_prediction""" , use_karras_sigmas=UpperCamelCase__ )
__magic_name__ = torch.mean(torch.abs(UpperCamelCase__ ) )
assert abs(result_mean.item() - 0.0649 ) < 1E-3
def _lowercase ( self : List[Any] ) -> Any:
"""simple docstring"""
__magic_name__ = self.scheduler_classes[0]
__magic_name__ = self.get_scheduler_config(thresholding=UpperCamelCase__ , dynamic_thresholding_ratio=0 )
__magic_name__ = scheduler_class(**UpperCamelCase__ )
__magic_name__ = 10
__magic_name__ = self.dummy_model()
__magic_name__ = self.dummy_sample_deter.half()
scheduler.set_timesteps(UpperCamelCase__ )
for i, t in enumerate(scheduler.timesteps ):
__magic_name__ = model(UpperCamelCase__ , UpperCamelCase__ )
__magic_name__ = scheduler.step(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ).prev_sample
assert sample.dtype == torch.floataa
| 708 |
import collections
import importlib.util
import os
import re
from pathlib import Path
__lowerCAmelCase : int = 'src/transformers'
# Matches is_xxx_available()
__lowerCAmelCase : Optional[int] = re.compile(R'is\_([a-z_]*)_available()')
# Catches a one-line _import_struct = {xxx}
__lowerCAmelCase : Dict = re.compile(R'^_import_structure\s+=\s+\{([^\}]+)\}')
# Catches a line with a key-values pattern: "bla": ["foo", "bar"]
__lowerCAmelCase : int = re.compile(R'\s+"\S*":\s+\[([^\]]*)\]')
# Catches a line if not is_foo_available
__lowerCAmelCase : Optional[Any] = re.compile(R'^\s*if\s+not\s+is\_[a-z_]*\_available\(\)')
# Catches a line _import_struct["bla"].append("foo")
__lowerCAmelCase : Optional[Any] = re.compile(R'^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)')
# Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"]
__lowerCAmelCase : Dict = re.compile(R'^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]')
# Catches a line with an object between quotes and a comma: "MyModel",
__lowerCAmelCase : List[str] = re.compile('^\s+"([^"]+)",')
# Catches a line with objects between brackets only: ["foo", "bar"],
__lowerCAmelCase : Optional[int] = re.compile('^\s+\[([^\]]+)\]')
# Catches a line with from foo import bar, bla, boo
__lowerCAmelCase : List[str] = re.compile(R'\s+from\s+\S*\s+import\s+([^\(\s].*)\n')
# Catches a line with try:
__lowerCAmelCase : int = re.compile(R'^\s*try:')
# Catches a line with else:
__lowerCAmelCase : Tuple = re.compile(R'^\s*else:')
def a__ ( A_ ):
'''simple docstring'''
if _re_test_backend.search(A_ ) is None:
return None
__magic_name__ = [b[0] for b in _re_backend.findall(A_ )]
backends.sort()
return "_and_".join(A_ )
def a__ ( A_ ):
'''simple docstring'''
with open(A_, """r""", encoding="""utf-8""", newline="""\n""" ) as f:
__magic_name__ = f.readlines()
__magic_name__ = 0
while line_index < len(A_ ) and not lines[line_index].startswith("""_import_structure = {""" ):
line_index += 1
# If this is a traditional init, just return.
if line_index >= len(A_ ):
return None
# First grab the objects without a specific backend in _import_structure
__magic_name__ = []
while not lines[line_index].startswith("""if TYPE_CHECKING""" ) and find_backend(lines[line_index] ) is None:
__magic_name__ = lines[line_index]
# If we have everything on a single line, let's deal with it.
if _re_one_line_import_struct.search(A_ ):
__magic_name__ = _re_one_line_import_struct.search(A_ ).groups()[0]
__magic_name__ = re.findall("""\[([^\]]+)\]""", A_ )
for imp in imports:
objects.extend([obj[1:-1] for obj in imp.split(""", """ )] )
line_index += 1
continue
__magic_name__ = _re_import_struct_key_value.search(A_ )
if single_line_import_search is not None:
__magic_name__ = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(""", """ ) if len(A_ ) > 0]
objects.extend(A_ )
elif line.startswith(""" """ * 8 + """\"""" ):
objects.append(line[9:-3] )
line_index += 1
__magic_name__ = {"""none""": objects}
# Let's continue with backend-specific objects in _import_structure
while not lines[line_index].startswith("""if TYPE_CHECKING""" ):
# If the line is an if not is_backend_available, we grab all objects associated.
__magic_name__ = find_backend(lines[line_index] )
# Check if the backend declaration is inside a try block:
if _re_try.search(lines[line_index - 1] ) is None:
__magic_name__ = None
if backend is not None:
line_index += 1
# Scroll until we hit the else block of try-except-else
while _re_else.search(lines[line_index] ) is None:
line_index += 1
line_index += 1
__magic_name__ = []
# Until we unindent, add backend objects to the list
while len(lines[line_index] ) <= 1 or lines[line_index].startswith(""" """ * 4 ):
__magic_name__ = lines[line_index]
if _re_import_struct_add_one.search(A_ ) is not None:
objects.append(_re_import_struct_add_one.search(A_ ).groups()[0] )
elif _re_import_struct_add_many.search(A_ ) is not None:
__magic_name__ = _re_import_struct_add_many.search(A_ ).groups()[0].split(""", """ )
__magic_name__ = [obj[1:-1] for obj in imports if len(A_ ) > 0]
objects.extend(A_ )
elif _re_between_brackets.search(A_ ) is not None:
__magic_name__ = _re_between_brackets.search(A_ ).groups()[0].split(""", """ )
__magic_name__ = [obj[1:-1] for obj in imports if len(A_ ) > 0]
objects.extend(A_ )
elif _re_quote_object.search(A_ ) is not None:
objects.append(_re_quote_object.search(A_ ).groups()[0] )
elif line.startswith(""" """ * 8 + """\"""" ):
objects.append(line[9:-3] )
elif line.startswith(""" """ * 12 + """\"""" ):
objects.append(line[13:-3] )
line_index += 1
__magic_name__ = objects
else:
line_index += 1
# At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend
__magic_name__ = []
while (
line_index < len(A_ )
and find_backend(lines[line_index] ) is None
and not lines[line_index].startswith("""else""" )
):
__magic_name__ = lines[line_index]
__magic_name__ = _re_import.search(A_ )
if single_line_import_search is not None:
objects.extend(single_line_import_search.groups()[0].split(""", """ ) )
elif line.startswith(""" """ * 8 ):
objects.append(line[8:-2] )
line_index += 1
__magic_name__ = {"""none""": objects}
# Let's continue with backend-specific objects
while line_index < len(A_ ):
# If the line is an if is_backend_available, we grab all objects associated.
__magic_name__ = find_backend(lines[line_index] )
# Check if the backend declaration is inside a try block:
if _re_try.search(lines[line_index - 1] ) is None:
__magic_name__ = None
if backend is not None:
line_index += 1
# Scroll until we hit the else block of try-except-else
while _re_else.search(lines[line_index] ) is None:
line_index += 1
line_index += 1
__magic_name__ = []
# Until we unindent, add backend objects to the list
while len(lines[line_index] ) <= 1 or lines[line_index].startswith(""" """ * 8 ):
__magic_name__ = lines[line_index]
__magic_name__ = _re_import.search(A_ )
if single_line_import_search is not None:
objects.extend(single_line_import_search.groups()[0].split(""", """ ) )
elif line.startswith(""" """ * 12 ):
objects.append(line[12:-2] )
line_index += 1
__magic_name__ = objects
else:
line_index += 1
return import_dict_objects, type_hint_objects
def a__ ( A_, A_ ):
'''simple docstring'''
def find_duplicates(A_ ):
return [k for k, v in collections.Counter(A_ ).items() if v > 1]
if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ):
return ["Both sides of the init do not have the same backends!"]
__magic_name__ = []
for key in import_dict_objects.keys():
__magic_name__ = find_duplicates(import_dict_objects[key] )
if duplicate_imports:
errors.append(f'''Duplicate _import_structure definitions for: {duplicate_imports}''' )
__magic_name__ = find_duplicates(type_hint_objects[key] )
if duplicate_type_hints:
errors.append(f'''Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}''' )
if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ):
__magic_name__ = """base imports""" if key == """none""" else f'''{key} backend'''
errors.append(f'''Differences for {name}:''' )
for a in type_hint_objects[key]:
if a not in import_dict_objects[key]:
errors.append(f''' {a} in TYPE_HINT but not in _import_structure.''' )
for a in import_dict_objects[key]:
if a not in type_hint_objects[key]:
errors.append(f''' {a} in _import_structure but not in TYPE_HINT.''' )
return errors
def a__ ( ):
'''simple docstring'''
__magic_name__ = []
for root, _, files in os.walk(A_ ):
if "__init__.py" in files:
__magic_name__ = os.path.join(A_, """__init__.py""" )
__magic_name__ = parse_init(A_ )
if objects is not None:
__magic_name__ = analyze_results(*A_ )
if len(A_ ) > 0:
__magic_name__ = f'''Problem in {fname}, both halves do not define the same objects.\n{errors[0]}'''
failures.append("""\n""".join(A_ ) )
if len(A_ ) > 0:
raise ValueError("""\n\n""".join(A_ ) )
def a__ ( ):
'''simple docstring'''
__magic_name__ = []
for path, directories, files in os.walk(A_ ):
for folder in directories:
# Ignore private modules
if folder.startswith("""_""" ):
directories.remove(A_ )
continue
# Ignore leftovers from branches (empty folders apart from pycache)
if len(list((Path(A_ ) / folder).glob("""*.py""" ) ) ) == 0:
continue
__magic_name__ = str((Path(A_ ) / folder).relative_to(A_ ) )
__magic_name__ = short_path.replace(os.path.sep, """.""" )
submodules.append(A_ )
for fname in files:
if fname == "__init__.py":
continue
__magic_name__ = str((Path(A_ ) / fname).relative_to(A_ ) )
__magic_name__ = short_path.replace(""".py""", """""" ).replace(os.path.sep, """.""" )
if len(submodule.split(""".""" ) ) == 1:
submodules.append(A_ )
return submodules
__lowerCAmelCase : Dict = [
'convert_pytorch_checkpoint_to_tf2',
'modeling_flax_pytorch_utils',
]
def a__ ( ):
'''simple docstring'''
__magic_name__ = importlib.util.spec_from_file_location(
"""transformers""", os.path.join(A_, """__init__.py""" ), submodule_search_locations=[PATH_TO_TRANSFORMERS], )
__magic_name__ = spec.loader.load_module()
__magic_name__ = [
module
for module in get_transformers_submodules()
if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys()
]
if len(A_ ) > 0:
__magic_name__ = """\n""".join(f'''- {module}''' for module in module_not_registered )
raise ValueError(
"""The following submodules are not properly registered in the main init of Transformers:\n"""
f'''{list_of_modules}\n'''
"""Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.""" )
if __name__ == "__main__":
check_all_inits()
check_submodules()
| 76 | 0 |
class UpperCAmelCase_ :
'''simple docstring'''
def __init__( self : str , UpperCamelCase__ : int , UpperCamelCase__ : List[Any] ) -> int:
"""simple docstring"""
__magic_name__ = name
__magic_name__ = val
def __str__( self : str ) -> Union[str, Any]:
"""simple docstring"""
return F'''{self.__class__.__name__}({self.name}, {self.val})'''
def __lt__( self : List[str] , UpperCamelCase__ : Any ) -> int:
"""simple docstring"""
return self.val < other.val
class UpperCAmelCase_ :
'''simple docstring'''
def __init__( self : List[str] , UpperCamelCase__ : Any ) -> Any:
"""simple docstring"""
__magic_name__ = {}
__magic_name__ = {}
__magic_name__ = self.build_heap(UpperCamelCase__ )
def __getitem__( self : Union[str, Any] , UpperCamelCase__ : Optional[int] ) -> Optional[int]:
"""simple docstring"""
return self.get_value(UpperCamelCase__ )
def _lowercase ( self : str , UpperCamelCase__ : Optional[int] ) -> Optional[Any]:
"""simple docstring"""
return (idx - 1) // 2
def _lowercase ( self : Dict , UpperCamelCase__ : Tuple ) -> Any:
"""simple docstring"""
return idx * 2 + 1
def _lowercase ( self : Dict , UpperCamelCase__ : Any ) -> str:
"""simple docstring"""
return idx * 2 + 2
def _lowercase ( self : Any , UpperCamelCase__ : List[Any] ) -> Union[str, Any]:
"""simple docstring"""
return self.heap_dict[key]
def _lowercase ( self : List[str] , UpperCamelCase__ : int ) -> Optional[Any]:
"""simple docstring"""
__magic_name__ = len(UpperCamelCase__ ) - 1
__magic_name__ = self.get_parent_idx(UpperCamelCase__ )
for idx, i in enumerate(UpperCamelCase__ ):
__magic_name__ = idx
__magic_name__ = i.val
for i in range(UpperCamelCase__ , -1 , -1 ):
self.sift_down(UpperCamelCase__ , UpperCamelCase__ )
return array
def _lowercase ( self : Tuple , UpperCamelCase__ : str , UpperCamelCase__ : Union[str, Any] ) -> Optional[int]:
"""simple docstring"""
while True:
__magic_name__ = self.get_left_child_idx(UpperCamelCase__ ) # noqa: E741
__magic_name__ = self.get_right_child_idx(UpperCamelCase__ )
__magic_name__ = idx
if l < len(UpperCamelCase__ ) and array[l] < array[idx]:
__magic_name__ = l
if r < len(UpperCamelCase__ ) and array[r] < array[smallest]:
__magic_name__ = r
if smallest != idx:
__magic_name__ , __magic_name__ = array[smallest], array[idx]
(
(
__magic_name__
) , (
__magic_name__
) ,
) = (
self.idx_of_element[array[smallest]],
self.idx_of_element[array[idx]],
)
__magic_name__ = smallest
else:
break
def _lowercase ( self : str , UpperCamelCase__ : str ) -> str:
"""simple docstring"""
__magic_name__ = self.get_parent_idx(UpperCamelCase__ )
while p >= 0 and self.heap[p] > self.heap[idx]:
__magic_name__ , __magic_name__ = self.heap[idx], self.heap[p]
__magic_name__ , __magic_name__ = (
self.idx_of_element[self.heap[idx]],
self.idx_of_element[self.heap[p]],
)
__magic_name__ = p
__magic_name__ = self.get_parent_idx(UpperCamelCase__ )
def _lowercase ( self : int ) -> Tuple:
"""simple docstring"""
return self.heap[0]
def _lowercase ( self : Tuple ) -> List[str]:
"""simple docstring"""
__magic_name__ , __magic_name__ = self.heap[-1], self.heap[0]
__magic_name__ , __magic_name__ = (
self.idx_of_element[self.heap[-1]],
self.idx_of_element[self.heap[0]],
)
__magic_name__ = self.heap.pop()
del self.idx_of_element[x]
self.sift_down(0 , self.heap )
return x
def _lowercase ( self : List[str] , UpperCamelCase__ : int ) -> Union[str, Any]:
"""simple docstring"""
self.heap.append(UpperCamelCase__ )
__magic_name__ = len(self.heap ) - 1
__magic_name__ = node.val
self.sift_up(len(self.heap ) - 1 )
def _lowercase ( self : Optional[Any] ) -> str:
"""simple docstring"""
return len(self.heap ) == 0
def _lowercase ( self : List[Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Tuple ) -> List[str]:
"""simple docstring"""
assert (
self.heap[self.idx_of_element[node]].val > new_value
), "newValue must be less that current value"
__magic_name__ = new_value
__magic_name__ = new_value
self.sift_up(self.idx_of_element[node] )
__lowerCAmelCase : Union[str, Any] = Node('R', -1)
__lowerCAmelCase : Tuple = Node('B', 6)
__lowerCAmelCase : int = Node('A', 3)
__lowerCAmelCase : Union[str, Any] = Node('X', 1)
__lowerCAmelCase : List[Any] = Node('E', 4)
# Use one of these two ways to generate Min-Heap
# Generating Min-Heap from array
__lowerCAmelCase : Tuple = MinHeap([r, b, a, x, e])
# Generating Min-Heap by Insert method
# myMinHeap.insert(a)
# myMinHeap.insert(b)
# myMinHeap.insert(x)
# myMinHeap.insert(r)
# myMinHeap.insert(e)
# Before
print('Min Heap - before decrease key')
for i in my_min_heap.heap:
print(i)
print('Min Heap - After decrease key of node [B -> -17]')
my_min_heap.decrease_key(b, -17)
# After
for i in my_min_heap.heap:
print(i)
if __name__ == "__main__":
import doctest
doctest.testmod()
| 709 |
import functools
import operator
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__lowerCAmelCase : Optional[Any] = logging.get_logger(__name__)
__lowerCAmelCase : List[Any] = {
'asapp/sew-d-tiny-100k': 'https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json',
# See all SEW-D models at https://huggingface.co/models?filter=sew-d
}
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = """sew-d"""
def __init__( self : List[str] , UpperCamelCase__ : Tuple=32 , UpperCamelCase__ : Optional[int]=768 , UpperCamelCase__ : Tuple=12 , UpperCamelCase__ : Optional[Any]=12 , UpperCamelCase__ : int=3072 , UpperCamelCase__ : Tuple=2 , UpperCamelCase__ : List[Any]=512 , UpperCamelCase__ : Any=256 , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : Dict=True , UpperCamelCase__ : str=("p2c", "c2p") , UpperCamelCase__ : List[Any]="layer_norm" , UpperCamelCase__ : int="gelu_python" , UpperCamelCase__ : Optional[int]=0.1 , UpperCamelCase__ : Tuple=0.1 , UpperCamelCase__ : List[Any]=0.1 , UpperCamelCase__ : int=0.0 , UpperCamelCase__ : Dict=0.1 , UpperCamelCase__ : List[Any]=0.02 , UpperCamelCase__ : Optional[int]=1E-7 , UpperCamelCase__ : List[Any]=1E-5 , UpperCamelCase__ : List[str]="group" , UpperCamelCase__ : Optional[int]="gelu" , UpperCamelCase__ : Tuple=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , UpperCamelCase__ : str=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , UpperCamelCase__ : Optional[Any]=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , UpperCamelCase__ : Optional[Any]=False , UpperCamelCase__ : Optional[int]=128 , UpperCamelCase__ : Tuple=16 , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : Dict=0.05 , UpperCamelCase__ : str=10 , UpperCamelCase__ : Tuple=2 , UpperCamelCase__ : Dict=0.0 , UpperCamelCase__ : Dict=10 , UpperCamelCase__ : Union[str, Any]=0 , UpperCamelCase__ : List[Any]="mean" , UpperCamelCase__ : int=False , UpperCamelCase__ : Optional[int]=False , UpperCamelCase__ : Optional[int]=256 , UpperCamelCase__ : List[str]=0 , UpperCamelCase__ : Union[str, Any]=1 , UpperCamelCase__ : List[Any]=2 , **UpperCamelCase__ : str , ) -> Dict:
"""simple docstring"""
super().__init__(**UpperCamelCase__ , pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ )
__magic_name__ = hidden_size
__magic_name__ = feat_extract_norm
__magic_name__ = feat_extract_activation
__magic_name__ = list(UpperCamelCase__ )
__magic_name__ = list(UpperCamelCase__ )
__magic_name__ = list(UpperCamelCase__ )
__magic_name__ = conv_bias
__magic_name__ = num_conv_pos_embeddings
__magic_name__ = num_conv_pos_embedding_groups
__magic_name__ = len(self.conv_dim )
__magic_name__ = num_hidden_layers
__magic_name__ = intermediate_size
__magic_name__ = squeeze_factor
__magic_name__ = max_position_embeddings
__magic_name__ = position_buckets
__magic_name__ = share_att_key
__magic_name__ = relative_attention
__magic_name__ = norm_rel_ebd
__magic_name__ = list(UpperCamelCase__ )
__magic_name__ = hidden_act
__magic_name__ = num_attention_heads
__magic_name__ = hidden_dropout
__magic_name__ = attention_dropout
__magic_name__ = activation_dropout
__magic_name__ = feat_proj_dropout
__magic_name__ = final_dropout
__magic_name__ = layer_norm_eps
__magic_name__ = feature_layer_norm_eps
__magic_name__ = initializer_range
__magic_name__ = vocab_size
if (
(len(self.conv_stride ) != self.num_feat_extract_layers)
or (len(self.conv_kernel ) != self.num_feat_extract_layers)
or (len(self.conv_dim ) != self.num_feat_extract_layers)
):
raise ValueError(
"""Configuration for convolutional layers is incorrect."""
"""It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,"""
F'''but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)'''
F'''= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' )
# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
__magic_name__ = apply_spec_augment
__magic_name__ = mask_time_prob
__magic_name__ = mask_time_length
__magic_name__ = mask_time_min_masks
__magic_name__ = mask_feature_prob
__magic_name__ = mask_feature_length
__magic_name__ = mask_feature_min_masks
# ctc loss
__magic_name__ = ctc_loss_reduction
__magic_name__ = ctc_zero_infinity
# sequence classification
__magic_name__ = use_weighted_layer_sum
__magic_name__ = classifier_proj_size
@property
def _lowercase ( self : Union[str, Any] ) -> str:
"""simple docstring"""
return functools.reduce(operator.mul , self.conv_stride , 1 )
| 76 | 0 |
import copy
import os
from typing import Union
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__lowerCAmelCase : int = logging.get_logger(__name__)
__lowerCAmelCase : List[Any] = {
'BAAI/AltCLIP': 'https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json',
# See all AltCLIP models at https://huggingface.co/models?filter=altclip
}
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = """altclip_text_model"""
def __init__( self : Tuple , UpperCamelCase__ : Union[str, Any]=25_0002 , UpperCamelCase__ : Optional[int]=1024 , UpperCamelCase__ : str=24 , UpperCamelCase__ : Dict=16 , UpperCamelCase__ : List[Any]=4096 , UpperCamelCase__ : List[str]="gelu" , UpperCamelCase__ : Optional[Any]=0.1 , UpperCamelCase__ : Optional[int]=0.1 , UpperCamelCase__ : Tuple=514 , UpperCamelCase__ : Tuple=1 , UpperCamelCase__ : int=0.02 , UpperCamelCase__ : Any=0.02 , UpperCamelCase__ : int=1E-05 , UpperCamelCase__ : Union[str, Any]=1 , UpperCamelCase__ : Any=0 , UpperCamelCase__ : Any=2 , UpperCamelCase__ : Optional[Any]="absolute" , UpperCamelCase__ : int=True , UpperCamelCase__ : Optional[Any]=768 , **UpperCamelCase__ : List[str] , ) -> List[Any]:
"""simple docstring"""
super().__init__(pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , **UpperCamelCase__ )
__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__ = initializer_factor
__magic_name__ = layer_norm_eps
__magic_name__ = position_embedding_type
__magic_name__ = use_cache
__magic_name__ = project_dim
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = """altclip_vision_model"""
def __init__( self : Optional[int] , UpperCamelCase__ : Optional[Any]=768 , UpperCamelCase__ : Union[str, Any]=3072 , UpperCamelCase__ : List[Any]=512 , UpperCamelCase__ : Optional[int]=12 , UpperCamelCase__ : Optional[Any]=12 , UpperCamelCase__ : Optional[Any]=3 , UpperCamelCase__ : Optional[int]=224 , UpperCamelCase__ : int=32 , UpperCamelCase__ : Union[str, Any]="quick_gelu" , UpperCamelCase__ : Tuple=1E-5 , UpperCamelCase__ : Tuple=0.0 , UpperCamelCase__ : Dict=0.02 , UpperCamelCase__ : Union[str, Any]=1.0 , **UpperCamelCase__ : List[Any] , ) -> Tuple:
"""simple docstring"""
super().__init__(**UpperCamelCase__ )
__magic_name__ = hidden_size
__magic_name__ = intermediate_size
__magic_name__ = projection_dim
__magic_name__ = num_hidden_layers
__magic_name__ = num_attention_heads
__magic_name__ = num_channels
__magic_name__ = patch_size
__magic_name__ = image_size
__magic_name__ = initializer_range
__magic_name__ = initializer_factor
__magic_name__ = attention_dropout
__magic_name__ = layer_norm_eps
__magic_name__ = hidden_act
@classmethod
def _lowercase ( cls : List[str] , UpperCamelCase__ : Union[str, os.PathLike] , **UpperCamelCase__ : List[Any] ) -> "PretrainedConfig":
"""simple docstring"""
cls._set_token_in_kwargs(UpperCamelCase__ )
__magic_name__ , __magic_name__ = cls.get_config_dict(UpperCamelCase__ , **UpperCamelCase__ )
# get the vision config dict if we are loading from AltCLIPConfig
if config_dict.get("""model_type""" ) == "altclip":
__magic_name__ = config_dict["""vision_config"""]
if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type:
logger.warning(
F'''You are using a model of type {config_dict['model_type']} to instantiate a model of type '''
F'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' )
return cls.from_dict(UpperCamelCase__ , **UpperCamelCase__ )
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = """altclip"""
a__ = True
def __init__( self : int , UpperCamelCase__ : Dict=None , UpperCamelCase__ : Tuple=None , UpperCamelCase__ : int=768 , UpperCamelCase__ : int=2.6592 , **UpperCamelCase__ : int ) -> List[Any]:
"""simple docstring"""
__magic_name__ = kwargs.pop("""text_config_dict""" , UpperCamelCase__ )
__magic_name__ = kwargs.pop("""vision_config_dict""" , UpperCamelCase__ )
super().__init__(**UpperCamelCase__ )
# Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
# `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
# cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
if text_config_dict is not None:
if text_config is None:
__magic_name__ = {}
# This is the complete result when using `text_config_dict`.
__magic_name__ = AltCLIPTextConfig(**UpperCamelCase__ ).to_dict()
# Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
for key, value in _text_config_dict.items():
if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
# If specified in `text_config_dict`
if key in text_config_dict:
__magic_name__ = (
F'''`{key}` is found in both `text_config_dict` and `text_config` but with different values. '''
F'''The value `text_config_dict["{key}"]` will be used instead.'''
)
# If inferred from default argument values (just to be super careful)
else:
__magic_name__ = (
F'''`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The '''
F'''value `text_config["{key}"]` will be overriden.'''
)
logger.warning(UpperCamelCase__ )
# Update all values in `text_config` with the ones in `_text_config_dict`.
text_config.update(_text_config_dict )
if vision_config_dict is not None:
if vision_config is None:
__magic_name__ = {}
# This is the complete result when using `vision_config_dict`.
__magic_name__ = AltCLIPVisionConfig(**UpperCamelCase__ ).to_dict()
# convert keys to string instead of integer
if "id2label" in _vision_config_dict:
__magic_name__ = {
str(UpperCamelCase__ ): value for key, value in _vision_config_dict["""id2label"""].items()
}
# Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
for key, value in _vision_config_dict.items():
if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
# If specified in `vision_config_dict`
if key in vision_config_dict:
__magic_name__ = (
F'''`{key}` is found in both `vision_config_dict` and `vision_config` but with different '''
F'''values. The value `vision_config_dict["{key}"]` will be used instead.'''
)
# If inferred from default argument values (just to be super careful)
else:
__magic_name__ = (
F'''`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. '''
F'''The value `vision_config["{key}"]` will be overriden.'''
)
logger.warning(UpperCamelCase__ )
# Update all values in `vision_config` with the ones in `_vision_config_dict`.
vision_config.update(_vision_config_dict )
if text_config is None:
__magic_name__ = {}
logger.info("""`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values.""" )
if vision_config is None:
__magic_name__ = {}
logger.info("""`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values.""" )
__magic_name__ = AltCLIPTextConfig(**UpperCamelCase__ )
__magic_name__ = AltCLIPVisionConfig(**UpperCamelCase__ )
__magic_name__ = projection_dim
__magic_name__ = logit_scale_init_value
__magic_name__ = 1.0
@classmethod
def _lowercase ( cls : str , UpperCamelCase__ : AltCLIPTextConfig , UpperCamelCase__ : AltCLIPVisionConfig , **UpperCamelCase__ : Any ) -> Tuple:
"""simple docstring"""
return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **UpperCamelCase__ )
def _lowercase ( self : List[str] ) -> str:
"""simple docstring"""
__magic_name__ = copy.deepcopy(self.__dict__ )
__magic_name__ = self.text_config.to_dict()
__magic_name__ = self.vision_config.to_dict()
__magic_name__ = self.__class__.model_type
return output
| 710 |
import math
import random
def a__ ( A_, A_ = False ):
'''simple docstring'''
if deriv:
return value * (1 - value)
return 1 / (1 + math.exp(-value ))
# Initial Value
__lowerCAmelCase : Union[str, Any] = 0.02
def a__ ( A_, A_ ):
'''simple docstring'''
__magic_name__ = float(2 * (random.randint(1, 100 )) - 1 )
for _ in range(A_ ):
# Forward propagation
__magic_name__ = sigmoid_function(INITIAL_VALUE * weight )
# How much did we miss?
__magic_name__ = (expected / 100) - layer_a
# Error delta
__magic_name__ = layer_1_error * sigmoid_function(A_, A_ )
# Update weight
weight += INITIAL_VALUE * layer_1_delta
return layer_a * 100
if __name__ == "__main__":
import doctest
doctest.testmod()
__lowerCAmelCase : List[Any] = int(input('Expected value: '))
__lowerCAmelCase : Tuple = int(input('Number of propagations: '))
print(forward_propagation(expected, number_propagations))
| 76 | 0 |
import argparse
import json
import os
import fairseq
import torch
from fairseq.data import Dictionary
from transformers import (
HubertConfig,
HubertForCTC,
HubertModel,
WavaVecaCTCTokenizer,
WavaVecaFeatureExtractor,
WavaVecaProcessor,
logging,
)
logging.set_verbosity_info()
__lowerCAmelCase : int = logging.get_logger(__name__)
__lowerCAmelCase : Dict = {
'post_extract_proj': 'feature_projection.projection',
'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv',
'self_attn.k_proj': 'encoder.layers.*.attention.k_proj',
'self_attn.v_proj': 'encoder.layers.*.attention.v_proj',
'self_attn.q_proj': 'encoder.layers.*.attention.q_proj',
'self_attn.out_proj': 'encoder.layers.*.attention.out_proj',
'self_attn_layer_norm': 'encoder.layers.*.layer_norm',
'fc1': 'encoder.layers.*.feed_forward.intermediate_dense',
'fc2': 'encoder.layers.*.feed_forward.output_dense',
'final_layer_norm': 'encoder.layers.*.final_layer_norm',
'encoder.layer_norm': 'encoder.layer_norm',
'w2v_model.layer_norm': 'feature_projection.layer_norm',
'w2v_encoder.proj': 'lm_head',
'mask_emb': 'masked_spec_embed',
}
def a__ ( A_, A_, A_, A_, A_ ):
'''simple docstring'''
for attribute in key.split(""".""" ):
__magic_name__ = getattr(A_, A_ )
if weight_type is not None:
__magic_name__ = getattr(A_, A_ ).shape
else:
__magic_name__ = hf_pointer.shape
assert hf_shape == value.shape, (
f'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be'''
f''' {value.shape} for {full_name}'''
)
if weight_type == "weight":
__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
else:
__magic_name__ = value
logger.info(f'''{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}.''' )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = []
__magic_name__ = fairseq_model.state_dict()
__magic_name__ = hf_model.hubert.feature_extractor if is_finetuned else hf_model.feature_extractor
for name, value in fairseq_dict.items():
__magic_name__ = False
if "conv_layers" in name:
load_conv_layer(
A_, A_, A_, A_, hf_model.config.feat_extract_norm == """group""", )
__magic_name__ = True
else:
for key, mapped_key in MAPPING.items():
__magic_name__ = """hubert.""" + mapped_key if (is_finetuned and mapped_key != """lm_head""") else mapped_key
if key in name or (key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0] and not is_finetuned):
__magic_name__ = True
if "*" in mapped_key:
__magic_name__ = name.split(A_ )[0].split(""".""" )[-2]
__magic_name__ = mapped_key.replace("""*""", A_ )
if "weight_g" in name:
__magic_name__ = """weight_g"""
elif "weight_v" in name:
__magic_name__ = """weight_v"""
elif "weight" in name:
__magic_name__ = """weight"""
elif "bias" in name:
__magic_name__ = """bias"""
else:
__magic_name__ = None
set_recursively(A_, A_, A_, A_, A_ )
continue
if not is_used:
unused_weights.append(A_ )
logger.warning(f'''Unused weights: {unused_weights}''' )
def a__ ( A_, A_, A_, A_, A_ ):
'''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:
assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
f'''{full_name} has size {value.shape}, but'''
f''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.'''
)
__magic_name__ = value
logger.info(f'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' )
elif "weight" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
f'''{full_name} has size {value.shape}, but'''
f''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.'''
)
__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:
assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
f'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was'''
" found."
)
__magic_name__ = value
logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' )
elif "weight" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
f'''{full_name} has size {value.shape}, but'''
f''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.'''
)
__magic_name__ = value
logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' )
else:
unused_weights.append(A_ )
@torch.no_grad()
def a__ ( A_, A_, A_=None, A_=None, A_=True ):
'''simple docstring'''
if config_path is not None:
__magic_name__ = HubertConfig.from_pretrained(A_ )
else:
__magic_name__ = HubertConfig()
if is_finetuned:
if dict_path:
__magic_name__ = Dictionary.load(A_ )
# important change bos & pad token id since CTC symbol is <pad> and
# not <s> as in fairseq
__magic_name__ = target_dict.pad_index
__magic_name__ = target_dict.bos_index
__magic_name__ = target_dict.eos_index
__magic_name__ = len(target_dict.symbols )
__magic_name__ = os.path.join(A_, """vocab.json""" )
if not os.path.isdir(A_ ):
logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(A_ ) )
return
os.makedirs(A_, exist_ok=A_ )
with open(A_, """w""", encoding="""utf-8""" ) as vocab_handle:
json.dump(target_dict.indices, A_ )
__magic_name__ = WavaVecaCTCTokenizer(
A_, unk_token=target_dict.unk_word, pad_token=target_dict.pad_word, bos_token=target_dict.bos_word, eos_token=target_dict.eos_word, word_delimiter_token="""|""", do_lower_case=A_, )
__magic_name__ = True if config.feat_extract_norm == """layer""" else False
__magic_name__ = WavaVecaFeatureExtractor(
feature_size=1, sampling_rate=16000, padding_value=0, do_normalize=A_, return_attention_mask=A_, )
__magic_name__ = WavaVecaProcessor(feature_extractor=A_, tokenizer=A_ )
processor.save_pretrained(A_ )
__magic_name__ = HubertForCTC(A_ )
else:
__magic_name__ = HubertModel(A_ )
if is_finetuned:
__magic_name__ , __magic_name__ , __magic_name__ = fairseq.checkpoint_utils.load_model_ensemble_and_task(
[checkpoint_path], arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} )
else:
__magic_name__ , __magic_name__ , __magic_name__ = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] )
__magic_name__ = model[0].eval()
recursively_load_weights(A_, A_, A_ )
hf_wavavec.save_pretrained(A_ )
if __name__ == "__main__":
__lowerCAmelCase : Union[str, Any] = argparse.ArgumentParser()
parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint')
parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model')
parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert')
parser.add_argument(
'--not_finetuned', action='store_true', help='Whether the model to convert is a fine-tuned model or not'
)
__lowerCAmelCase : Dict = parser.parse_args()
convert_hubert_checkpoint(
args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
)
| 711 |
import os
import sys
__lowerCAmelCase : Optional[Any] = os.path.join(os.path.dirname(__file__), 'src')
sys.path.append(SRC_DIR)
from transformers import (
AutoConfig,
AutoModel,
AutoModelForCausalLM,
AutoModelForMaskedLM,
AutoModelForQuestionAnswering,
AutoModelForSequenceClassification,
AutoTokenizer,
add_start_docstrings,
)
__lowerCAmelCase : Union[str, Any] = [
'torch',
'numpy',
'tokenizers',
'filelock',
'requests',
'tqdm',
'regex',
'sentencepiece',
'sacremoses',
'importlib_metadata',
'huggingface_hub',
]
@add_start_docstrings(AutoConfig.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoConfig.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoTokenizer.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoTokenizer.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoModel.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoModel.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoModelForCausalLM.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoModelForCausalLM.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoModelForMaskedLM.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoModelForMaskedLM.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoModelForSequenceClassification.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoModelForSequenceClassification.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoModelForQuestionAnswering.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoModelForQuestionAnswering.from_pretrained(*A_, **A_ )
| 76 | 0 |
'''simple docstring'''
import os
import pytest
import yaml
from datasets.features.features import Features, Value
from datasets.info import DatasetInfo, DatasetInfosDict
@pytest.mark.parametrize(
"""files""", [
["""full:README.md""", """dataset_infos.json"""],
["""empty:README.md""", """dataset_infos.json"""],
["""dataset_infos.json"""],
["""full:README.md"""],
], )
def a__ ( A_, A_ ):
'''simple docstring'''
__magic_name__ = tmp_path_factory.mktemp("""dset_infos_dir""" )
if "full:README.md" in files:
with open(dataset_infos_dir / """README.md""", """w""" ) as f:
f.write("""---\ndataset_info:\n dataset_size: 42\n---""" )
if "empty:README.md" in files:
with open(dataset_infos_dir / """README.md""", """w""" ) as f:
f.write("""""" )
# we want to support dataset_infos.json for backward compatibility
if "dataset_infos.json" in files:
with open(dataset_infos_dir / """dataset_infos.json""", """w""" ) as f:
f.write("""{\"default\": {\"dataset_size\": 42}}""" )
__magic_name__ = DatasetInfosDict.from_directory(A_ )
assert dataset_infos
assert dataset_infos["default"].dataset_size == 42
@pytest.mark.parametrize(
"""dataset_info""", [
DatasetInfo(),
DatasetInfo(
description="""foo""", features=Features({"""a""": Value("""int32""" )} ), builder_name="""builder""", config_name="""config""", version="""1.0.0""", splits=[{"""name""": """train"""}], download_size=42, ),
], )
def a__ ( A_, A_ ):
'''simple docstring'''
__magic_name__ = str(A_ )
dataset_info.write_to_directory(A_ )
__magic_name__ = DatasetInfo.from_directory(A_ )
assert dataset_info == reloaded
assert os.path.exists(os.path.join(A_, """dataset_info.json""" ) )
def a__ ( ):
'''simple docstring'''
__magic_name__ = DatasetInfo(
description="""foo""", citation="""bar""", homepage="""https://foo.bar""", license="""CC0""", features=Features({"""a""": Value("""int32""" )} ), post_processed={}, supervised_keys=(), task_templates=[], builder_name="""builder""", config_name="""config""", version="""1.0.0""", splits=[{"""name""": """train""", """num_examples""": 42}], download_checksums={}, download_size=1337, post_processing_size=442, dataset_size=1234, size_in_bytes=1337 + 442 + 1234, )
__magic_name__ = dataset_info._to_yaml_dict()
assert sorted(A_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML )
for key in DatasetInfo._INCLUDED_INFO_IN_YAML:
assert key in dataset_info_yaml_dict
assert isinstance(dataset_info_yaml_dict[key], (list, dict, int, str) )
__magic_name__ = yaml.safe_dump(A_ )
__magic_name__ = yaml.safe_load(A_ )
assert dataset_info_yaml_dict == reloaded
def a__ ( ):
'''simple docstring'''
__magic_name__ = DatasetInfo()
__magic_name__ = dataset_info._to_yaml_dict()
assert dataset_info_yaml_dict == {}
@pytest.mark.parametrize(
"""dataset_infos_dict""", [
DatasetInfosDict(),
DatasetInfosDict({"""default""": DatasetInfo()} ),
DatasetInfosDict({"""my_config_name""": DatasetInfo()} ),
DatasetInfosDict(
{
"""default""": DatasetInfo(
description="""foo""", features=Features({"""a""": Value("""int32""" )} ), builder_name="""builder""", config_name="""config""", version="""1.0.0""", splits=[{"""name""": """train"""}], download_size=42, )
} ),
DatasetInfosDict(
{
"""v1""": DatasetInfo(dataset_size=42 ),
"""v2""": DatasetInfo(dataset_size=1337 ),
} ),
], )
def a__ ( A_, A_ ):
'''simple docstring'''
__magic_name__ = str(A_ )
dataset_infos_dict.write_to_directory(A_ )
__magic_name__ = DatasetInfosDict.from_directory(A_ )
# the config_name of the dataset_infos_dict take over the attribute
for config_name, dataset_info in dataset_infos_dict.items():
__magic_name__ = config_name
# the yaml representation doesn't include fields like description or citation
# so we just test that we can recover what we can from the yaml
__magic_name__ = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() )
assert dataset_infos_dict == reloaded
if dataset_infos_dict:
assert os.path.exists(os.path.join(A_, """README.md""" ) )
| 712 |
from typing import Dict
from .base import GenericTensor, Pipeline
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
def _lowercase ( self : List[Any] , UpperCamelCase__ : List[Any]=None , UpperCamelCase__ : Union[str, Any]=None , UpperCamelCase__ : Any=None , **UpperCamelCase__ : Dict ) -> str:
"""simple docstring"""
if tokenize_kwargs is None:
__magic_name__ = {}
if truncation is not None:
if "truncation" in tokenize_kwargs:
raise ValueError(
"""truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)""" )
__magic_name__ = truncation
__magic_name__ = tokenize_kwargs
__magic_name__ = {}
if return_tensors is not None:
__magic_name__ = return_tensors
return preprocess_params, {}, postprocess_params
def _lowercase ( self : int , UpperCamelCase__ : int , **UpperCamelCase__ : int ) -> Dict[str, GenericTensor]:
"""simple docstring"""
__magic_name__ = self.framework
__magic_name__ = self.tokenizer(UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ )
return model_inputs
def _lowercase ( self : str , UpperCamelCase__ : Dict ) -> str:
"""simple docstring"""
__magic_name__ = self.model(**UpperCamelCase__ )
return model_outputs
def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str]=False ) -> List[str]:
"""simple docstring"""
if return_tensors:
return model_outputs[0]
if self.framework == "pt":
return model_outputs[0].tolist()
elif self.framework == "tf":
return model_outputs[0].numpy().tolist()
def __call__( self : List[str] , *UpperCamelCase__ : List[Any] , **UpperCamelCase__ : List[Any] ) -> Dict:
"""simple docstring"""
return super().__call__(*UpperCamelCase__ , **UpperCamelCase__ )
| 76 | 0 |
import copy
from dataclasses import dataclass, field
from typing import ClassVar, Dict
from ..features import ClassLabel, Features, Value
from .base import TaskTemplate
@dataclass(frozen=_A )
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = field(default="""text-classification""" , metadata={"""include_in_asdict_even_if_is_default""": True} )
a__ = Features({"""text""": Value("""string""" )} )
a__ = Features({"""labels""": ClassLabel} )
a__ = """text"""
a__ = """labels"""
def _lowercase ( self : Dict , UpperCamelCase__ : Tuple ) -> str:
"""simple docstring"""
if self.label_column not in features:
raise ValueError(F'''Column {self.label_column} is not present in features.''' )
if not isinstance(features[self.label_column] , UpperCamelCase__ ):
raise ValueError(F'''Column {self.label_column} is not a ClassLabel.''' )
__magic_name__ = copy.deepcopy(self )
__magic_name__ = self.label_schema.copy()
__magic_name__ = features[self.label_column]
__magic_name__ = label_schema
return task_template
@property
def _lowercase ( self : Optional[int] ) -> Dict[str, str]:
"""simple docstring"""
return {
self.text_column: "text",
self.label_column: "labels",
}
| 713 |
import argparse
import math
import os
from copy import deepcopy
import torch
from audio_diffusion.models import DiffusionAttnUnetaD
from diffusion import sampling
from torch import nn
from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel
__lowerCAmelCase : str = {
'gwf-440k': {
'url': 'https://model-server.zqevans2.workers.dev/gwf-440k.ckpt',
'sample_rate': 48000,
'sample_size': 65536,
},
'jmann-small-190k': {
'url': 'https://model-server.zqevans2.workers.dev/jmann-small-190k.ckpt',
'sample_rate': 48000,
'sample_size': 65536,
},
'jmann-large-580k': {
'url': 'https://model-server.zqevans2.workers.dev/jmann-large-580k.ckpt',
'sample_rate': 48000,
'sample_size': 131072,
},
'maestro-uncond-150k': {
'url': 'https://model-server.zqevans2.workers.dev/maestro-uncond-150k.ckpt',
'sample_rate': 16000,
'sample_size': 65536,
},
'unlocked-uncond-250k': {
'url': 'https://model-server.zqevans2.workers.dev/unlocked-uncond-250k.ckpt',
'sample_rate': 16000,
'sample_size': 65536,
},
'honk-140k': {
'url': 'https://model-server.zqevans2.workers.dev/honk-140k.ckpt',
'sample_rate': 16000,
'sample_size': 65536,
},
}
def a__ ( A_, A_ ):
'''simple docstring'''
return torch.atana(A_, A_ ) / math.pi * 2
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = torch.sin(t * math.pi / 2 ) ** 2
__magic_name__ = (1 - sigma**2) ** 0.5
return alpha_sigma_to_t(A_, A_ )
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
pass
class UpperCAmelCase_ ( nn.Module ):
'''simple docstring'''
def __init__( self : Tuple , UpperCamelCase__ : str ) -> Optional[Any]:
"""simple docstring"""
super().__init__()
__magic_name__ = DiffusionAttnUnetaD(UpperCamelCase__ , n_attn_layers=4 )
__magic_name__ = deepcopy(self.diffusion )
__magic_name__ = torch.quasirandom.SobolEngine(1 , scramble=UpperCamelCase__ )
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = MODELS_MAP[model_name]["""url"""]
os.system(f'''wget {url} ./''' )
return f'''./{model_name}.ckpt'''
__lowerCAmelCase : Optional[int] = {
'1': 'resnets.0',
'2': 'attentions.0',
'3': 'resnets.1',
'4': 'attentions.1',
'5': 'resnets.2',
'6': 'attentions.2',
}
__lowerCAmelCase : Optional[Any] = {
'8': 'resnets.0',
'9': 'attentions.0',
'10': 'resnets.1',
'11': 'attentions.1',
'12': 'resnets.2',
'13': 'attentions.2',
}
__lowerCAmelCase : Union[str, Any] = {
'1': 'resnets.0',
'2': 'attentions.0',
'3': 'resnets.1',
'4': 'attentions.1',
'5': 'resnets.2',
'6': 'attentions.2',
'8': 'resnets.3',
'9': 'attentions.3',
'10': 'resnets.4',
'11': 'attentions.4',
'12': 'resnets.5',
'13': 'attentions.5',
}
__lowerCAmelCase : int = {
'0': 'resnets.0',
'1': 'resnets.1',
'2': 'resnets.2',
'4': 'resnets.0',
'5': 'resnets.1',
'6': 'resnets.2',
}
__lowerCAmelCase : List[str] = {
'skip': 'conv_skip',
'main.0': 'conv_1',
'main.1': 'group_norm_1',
'main.3': 'conv_2',
'main.4': 'group_norm_2',
}
__lowerCAmelCase : int = {
'norm': 'group_norm',
'qkv_proj': ['query', 'key', 'value'],
'out_proj': ['proj_attn'],
}
def a__ ( A_ ):
'''simple docstring'''
if name.startswith("""skip""" ):
return name.replace("""skip""", RES_CONV_MAP["""skip"""] )
# name has to be of format main.{digit}
if not name.startswith("""main.""" ):
raise ValueError(f'''ResConvBlock error with {name}''' )
return name.replace(name[:6], RES_CONV_MAP[name[:6]] )
def a__ ( A_ ):
'''simple docstring'''
for key, value in ATTN_MAP.items():
if name.startswith(A_ ) and not isinstance(A_, A_ ):
return name.replace(A_, A_ )
elif name.startswith(A_ ):
return [name.replace(A_, A_ ) for v in value]
raise ValueError(f'''Attn error with {name}''' )
def a__ ( A_, A_=13 ):
'''simple docstring'''
__magic_name__ = input_string
if string.split(""".""" )[0] == "timestep_embed":
return string.replace("""timestep_embed""", """time_proj""" )
__magic_name__ = 0
if string.startswith("""net.3.""" ):
depth += 1
__magic_name__ = string[6:]
elif string.startswith("""net.""" ):
__magic_name__ = string[4:]
while string.startswith("""main.7.""" ):
depth += 1
__magic_name__ = string[7:]
if string.startswith("""main.""" ):
__magic_name__ = string[5:]
# mid block
if string[:2].isdigit():
__magic_name__ = string[:2]
__magic_name__ = string[2:]
else:
__magic_name__ = string[0]
__magic_name__ = string[1:]
if depth == max_depth:
__magic_name__ = MID_NUM_TO_LAYER[layer_num]
__magic_name__ = """mid_block"""
elif depth > 0 and int(A_ ) < 7:
__magic_name__ = DOWN_NUM_TO_LAYER[layer_num]
__magic_name__ = f'''down_blocks.{depth}'''
elif depth > 0 and int(A_ ) > 7:
__magic_name__ = UP_NUM_TO_LAYER[layer_num]
__magic_name__ = f'''up_blocks.{max_depth - depth - 1}'''
elif depth == 0:
__magic_name__ = DEPTH_0_TO_LAYER[layer_num]
__magic_name__ = f'''up_blocks.{max_depth - 1}''' if int(A_ ) > 3 else """down_blocks.0"""
if not string_left.startswith(""".""" ):
raise ValueError(f'''Naming error with {input_string} and string_left: {string_left}.''' )
__magic_name__ = string_left[1:]
if "resnets" in new_layer:
__magic_name__ = convert_resconv_naming(A_ )
elif "attentions" in new_layer:
__magic_name__ = convert_attn_naming(A_ )
__magic_name__ = new_string_left
if not isinstance(A_, A_ ):
__magic_name__ = prefix + """.""" + new_layer + """.""" + string_left
else:
__magic_name__ = [prefix + """.""" + new_layer + """.""" + s for s in string_left]
return new_string
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = {}
for k, v in state_dict.items():
if k.endswith("""kernel""" ):
# up- and downsample layers, don't have trainable weights
continue
__magic_name__ = rename(A_ )
# check if we need to transform from Conv => Linear for attention
if isinstance(A_, A_ ):
__magic_name__ = transform_conv_attns(A_, A_, A_ )
else:
__magic_name__ = v
return new_state_dict
def a__ ( A_, A_, A_ ):
'''simple docstring'''
if len(A_ ) == 1:
if len(v.shape ) == 3:
# weight
__magic_name__ = v[:, :, 0]
else:
# bias
__magic_name__ = v
else:
# qkv matrices
__magic_name__ = v.shape[0]
__magic_name__ = trippled_shape // 3
for i in range(3 ):
if len(v.shape ) == 3:
__magic_name__ = v[i * single_shape : (i + 1) * single_shape, :, 0]
else:
__magic_name__ = v[i * single_shape : (i + 1) * single_shape]
return new_state_dict
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" )
__magic_name__ = args.model_path.split("""/""" )[-1].split(""".""" )[0]
if not os.path.isfile(args.model_path ):
assert (
model_name == args.model_path
), f'''Make sure to provide one of the official model names {MODELS_MAP.keys()}'''
__magic_name__ = download(A_ )
__magic_name__ = MODELS_MAP[model_name]["""sample_rate"""]
__magic_name__ = MODELS_MAP[model_name]["""sample_size"""]
__magic_name__ = Object()
__magic_name__ = sample_size
__magic_name__ = sample_rate
__magic_name__ = 0
__magic_name__ = UNetaDModel(sample_size=A_, sample_rate=A_ )
__magic_name__ = diffusers_model.state_dict()
__magic_name__ = DiffusionUncond(A_ )
orig_model.load_state_dict(torch.load(args.model_path, map_location=A_ )["""state_dict"""] )
__magic_name__ = orig_model.diffusion_ema.eval()
__magic_name__ = orig_model.state_dict()
__magic_name__ = rename_orig_weights(A_ )
__magic_name__ = set(renamed_state_dict.keys() ) - set(diffusers_state_dict.keys() )
__magic_name__ = set(diffusers_state_dict.keys() ) - set(renamed_state_dict.keys() )
assert len(A_ ) == 0, f'''Problem with {renamed_minus_diffusers}'''
assert all(k.endswith("""kernel""" ) for k in list(A_ ) ), f'''Problem with {diffusers_minus_renamed}'''
for key, value in renamed_state_dict.items():
assert (
diffusers_state_dict[key].squeeze().shape == value.squeeze().shape
), f'''Shape for {key} doesn\'t match. Diffusers: {diffusers_state_dict[key].shape} vs. {value.shape}'''
if key == "time_proj.weight":
__magic_name__ = value.squeeze()
__magic_name__ = value
diffusers_model.load_state_dict(A_ )
__magic_name__ = 100
__magic_name__ = 33
__magic_name__ = IPNDMScheduler(num_train_timesteps=A_ )
__magic_name__ = torch.manual_seed(A_ )
__magic_name__ = torch.randn([1, 2, config.sample_size], generator=A_ ).to(A_ )
__magic_name__ = torch.linspace(1, 0, steps + 1, device=A_ )[:-1]
__magic_name__ = get_crash_schedule(A_ )
__magic_name__ = DanceDiffusionPipeline(unet=A_, scheduler=A_ )
__magic_name__ = torch.manual_seed(33 )
__magic_name__ = pipe(num_inference_steps=A_, generator=A_ ).audios
__magic_name__ = sampling.iplms_sample(A_, A_, A_, {} )
__magic_name__ = generated.clamp(-1, 1 )
__magic_name__ = (generated - audio).abs().sum()
__magic_name__ = (generated - audio).abs().max()
if args.save:
pipe.save_pretrained(args.checkpoint_path )
print("""Diff sum""", A_ )
print("""Diff max""", A_ )
assert diff_max < 1e-3, f'''Diff max: {diff_max} is too much :-/'''
print(f'''Conversion for {model_name} successful!''' )
if __name__ == "__main__":
__lowerCAmelCase : Optional[int] = argparse.ArgumentParser()
parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.')
parser.add_argument(
'--save', default=True, type=bool, required=False, help='Whether to save the converted model or not.'
)
parser.add_argument('--checkpoint_path', default=None, type=str, required=True, help='Path to the output model.')
__lowerCAmelCase : Union[str, Any] = parser.parse_args()
main(args)
| 76 | 0 |
from typing import Dict
from .base import GenericTensor, Pipeline
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
def _lowercase ( self : List[Any] , UpperCamelCase__ : List[Any]=None , UpperCamelCase__ : Union[str, Any]=None , UpperCamelCase__ : Any=None , **UpperCamelCase__ : Dict ) -> str:
"""simple docstring"""
if tokenize_kwargs is None:
__magic_name__ = {}
if truncation is not None:
if "truncation" in tokenize_kwargs:
raise ValueError(
"""truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)""" )
__magic_name__ = truncation
__magic_name__ = tokenize_kwargs
__magic_name__ = {}
if return_tensors is not None:
__magic_name__ = return_tensors
return preprocess_params, {}, postprocess_params
def _lowercase ( self : int , UpperCamelCase__ : int , **UpperCamelCase__ : int ) -> Dict[str, GenericTensor]:
"""simple docstring"""
__magic_name__ = self.framework
__magic_name__ = self.tokenizer(UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ )
return model_inputs
def _lowercase ( self : str , UpperCamelCase__ : Dict ) -> str:
"""simple docstring"""
__magic_name__ = self.model(**UpperCamelCase__ )
return model_outputs
def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str]=False ) -> List[str]:
"""simple docstring"""
if return_tensors:
return model_outputs[0]
if self.framework == "pt":
return model_outputs[0].tolist()
elif self.framework == "tf":
return model_outputs[0].numpy().tolist()
def __call__( self : List[str] , *UpperCamelCase__ : List[Any] , **UpperCamelCase__ : List[Any] ) -> Dict:
"""simple docstring"""
return super().__call__(*UpperCamelCase__ , **UpperCamelCase__ )
| 714 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__lowerCAmelCase : Tuple = logging.get_logger(__name__)
__lowerCAmelCase : Tuple = {
'SCUT-DLVCLab/lilt-roberta-en-base': (
'https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json'
),
}
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = """lilt"""
def __init__( self : Dict , UpperCamelCase__ : List[str]=3_0522 , UpperCamelCase__ : Optional[Any]=768 , UpperCamelCase__ : Dict=12 , UpperCamelCase__ : Optional[Any]=12 , UpperCamelCase__ : Dict=3072 , UpperCamelCase__ : Tuple="gelu" , UpperCamelCase__ : int=0.1 , UpperCamelCase__ : Dict=0.1 , UpperCamelCase__ : Union[str, Any]=512 , UpperCamelCase__ : Dict=2 , UpperCamelCase__ : Dict=0.02 , UpperCamelCase__ : Any=1E-12 , UpperCamelCase__ : Optional[int]=0 , UpperCamelCase__ : str="absolute" , UpperCamelCase__ : Any=None , UpperCamelCase__ : Dict=4 , UpperCamelCase__ : Tuple=1024 , **UpperCamelCase__ : Optional[int] , ) -> Dict:
"""simple docstring"""
super().__init__(pad_token_id=UpperCamelCase__ , **UpperCamelCase__ )
__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__ = classifier_dropout
__magic_name__ = channel_shrink_ratio
__magic_name__ = max_ad_position_embeddings
| 76 | 0 |
from __future__ import annotations
from typing import Any
class UpperCAmelCase_ :
'''simple docstring'''
def __init__( self : Optional[int] , UpperCamelCase__ : int = 6 ) -> None:
"""simple docstring"""
__magic_name__ = None
__magic_name__ = None
self.create_linked_list(UpperCamelCase__ )
def _lowercase ( self : Optional[int] , UpperCamelCase__ : int ) -> None:
"""simple docstring"""
__magic_name__ = Node()
__magic_name__ = current_node
__magic_name__ = current_node
__magic_name__ = current_node
for _ in range(1 , UpperCamelCase__ ):
__magic_name__ = Node()
__magic_name__ = current_node
__magic_name__ = previous_node
__magic_name__ = current_node
__magic_name__ = self.front
__magic_name__ = previous_node
def _lowercase ( self : Optional[int] ) -> bool:
"""simple docstring"""
return (
self.front == self.rear
and self.front is not None
and self.front.data is None
)
def _lowercase ( self : Optional[int] ) -> Any | None:
"""simple docstring"""
self.check_can_perform_operation()
return self.front.data if self.front else None
def _lowercase ( self : List[Any] , UpperCamelCase__ : Any ) -> None:
"""simple docstring"""
if self.rear is None:
return
self.check_is_full()
if not self.is_empty():
__magic_name__ = self.rear.next
if self.rear:
__magic_name__ = data
def _lowercase ( self : Optional[Any] ) -> Any:
"""simple docstring"""
self.check_can_perform_operation()
if self.rear is None or self.front is None:
return None
if self.front == self.rear:
__magic_name__ = self.front.data
__magic_name__ = None
return data
__magic_name__ = self.front
__magic_name__ = old_front.next
__magic_name__ = old_front.data
__magic_name__ = None
return data
def _lowercase ( self : Optional[Any] ) -> None:
"""simple docstring"""
if self.is_empty():
raise Exception("""Empty Queue""" )
def _lowercase ( self : str ) -> None:
"""simple docstring"""
if self.rear and self.rear.next == self.front:
raise Exception("""Full Queue""" )
class UpperCAmelCase_ :
'''simple docstring'''
def __init__( self : int ) -> None:
"""simple docstring"""
__magic_name__ = None
__magic_name__ = None
__magic_name__ = None
if __name__ == "__main__":
import doctest
doctest.testmod()
| 715 |
import json
import os
import tempfile
from transformers.testing_utils import check_json_file_has_correct_format
class UpperCAmelCase_ :
'''simple docstring'''
a__ = None
def _lowercase ( self : Optional[int] ) -> str:
"""simple docstring"""
__magic_name__ = self.feature_extraction_class(**self.feat_extract_dict )
__magic_name__ = json.loads(feat_extract.to_json_string() )
for key, value in self.feat_extract_dict.items():
self.assertEqual(obj[key] , UpperCamelCase__ )
def _lowercase ( self : Union[str, Any] ) -> str:
"""simple docstring"""
__magic_name__ = self.feature_extraction_class(**self.feat_extract_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
__magic_name__ = os.path.join(UpperCamelCase__ , """feat_extract.json""" )
feat_extract_first.to_json_file(UpperCamelCase__ )
__magic_name__ = self.feature_extraction_class.from_json_file(UpperCamelCase__ )
self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() )
def _lowercase ( self : str ) -> str:
"""simple docstring"""
__magic_name__ = self.feature_extraction_class(**self.feat_extract_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
__magic_name__ = feat_extract_first.save_pretrained(UpperCamelCase__ )[0]
check_json_file_has_correct_format(UpperCamelCase__ )
__magic_name__ = self.feature_extraction_class.from_pretrained(UpperCamelCase__ )
self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() )
def _lowercase ( self : Optional[int] ) -> Tuple:
"""simple docstring"""
__magic_name__ = self.feature_extraction_class()
self.assertIsNotNone(UpperCamelCase__ )
| 76 | 0 |
import warnings
from pathlib import Path
from typing import List, Tuple, Union
import fire
from torch import nn
from transformers import AutoModelForSeqaSeqLM, AutoTokenizer, PreTrainedModel
from transformers.utils import logging
__lowerCAmelCase : List[str] = logging.get_logger(__name__)
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = nn.ModuleList([src_layers[i] for i in layers_to_copy] )
assert len(A_ ) == len(A_ ), f'''{len(A_ )} != {len(A_ )}'''
dest_layers.load_state_dict(layers_to_copy.state_dict() )
__lowerCAmelCase : int = {
# maps num layers in teacher -> num_layers in student -> which teacher layers to copy.
# 12: bart, 16: pegasus, 6: marian/Helsinki-NLP
12: {
1: [0], # This says that if the teacher has 12 layers and the student has 1, copy layer 0 of the teacher
2: [0, 6],
3: [0, 6, 11],
4: [0, 4, 8, 11],
6: [0, 2, 4, 7, 9, 11],
9: [0, 1, 2, 4, 5, 7, 9, 10, 11],
12: list(range(12)),
},
16: { # maps num layers in student -> which teacher layers to copy
1: [0],
2: [0, 15],
3: [0, 8, 15],
4: [0, 5, 10, 15],
6: [0, 3, 6, 9, 12, 15],
8: [0, 2, 4, 6, 8, 10, 12, 15],
9: [0, 1, 3, 5, 7, 9, 11, 13, 15],
12: [0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15],
16: list(range(16)),
},
6: {1: [0], 2: [0, 5], 3: [0, 2, 5], 4: [0, 1, 3, 5], 6: list(range(6))},
}
__lowerCAmelCase : List[str] = {
# maps num layers in student -> which teacher layers to copy.
6: {1: [5], 2: [3, 5], 3: [1, 4, 5], 4: [1, 2, 4, 5]},
12: {1: [11], 2: [5, 11], 3: [3, 7, 11], 6: [1, 3, 5, 8, 10, 11]},
16: {1: [15], 4: [4, 9, 12, 15], 8: [1, 3, 5, 7, 9, 11, 13, 15]},
}
def a__ ( A_, A_ ):
'''simple docstring'''
try:
__magic_name__ = LAYERS_TO_COPY[n_teacher][n_student]
return val
except KeyError:
if n_student != n_teacher:
warnings.warn(
f'''no hardcoded layers to copy for teacher {n_teacher} -> student {n_student}, defaulting to first'''
f''' {n_student}''' )
return list(range(A_ ) )
def a__ ( A_, A_ ):
'''simple docstring'''
if n_student > n_teacher:
raise ValueError(f'''Cannot perform intermediate supervision for student {n_student} > teacher {n_teacher}''' )
elif n_teacher == n_student:
return list(range(A_ ) )
elif n_student == 1:
return [n_teacher - 1]
else:
return LAYERS_TO_SUPERVISE[n_teacher][n_student]
def a__ ( A_, A_ = "student", A_ = None, A_ = None, A_=False, A_=None, A_=None, **A_, ):
'''simple docstring'''
__magic_name__ = """encoder_layers and decoder_layers cannot be both None-- you would just have an identical teacher."""
assert (e is not None) or (d is not None), _msg
if isinstance(A_, A_ ):
AutoTokenizer.from_pretrained(A_ ).save_pretrained(A_ ) # purely for convenience
__magic_name__ = AutoModelForSeqaSeqLM.from_pretrained(A_ ).eval()
else:
assert isinstance(A_, A_ ), f'''teacher must be a model or string got type {type(A_ )}'''
__magic_name__ = teacher.config.to_diff_dict()
try:
__magic_name__ , __magic_name__ = teacher.config.encoder_layers, teacher.config.decoder_layers
if e is None:
__magic_name__ = teacher_e
if d is None:
__magic_name__ = teacher_d
init_kwargs.update({"""encoder_layers""": e, """decoder_layers""": d} )
except AttributeError: # T5
if hasattr(teacher.config, """num_encoder_layers""" ):
__magic_name__ , __magic_name__ = teacher.config.num_encoder_layers, teacher.config.num_decoder_layers
else:
__magic_name__ , __magic_name__ = teacher.config.num_layers, teacher.config.num_decoder_layers
if e is None:
__magic_name__ = teacher_e
if d is None:
__magic_name__ = teacher_d
if hasattr(teacher.config, """num_encoder_layers""" ):
init_kwargs.update({"""num_encoder_layers""": e, """num_decoder_layers""": d} )
else:
init_kwargs.update({"""num_layers""": e, """num_decoder_layers""": d} )
# Kwargs to instantiate student: teacher kwargs with updated layer numbers + **extra_config_kwargs
init_kwargs.update(A_ )
# Copy weights
__magic_name__ = teacher.config_class(**A_ )
__magic_name__ = AutoModelForSeqaSeqLM.from_config(A_ )
# Start by copying the full teacher state dict this will copy the first N teacher layers to the student.
__magic_name__ = student.load_state_dict(teacher.state_dict(), strict=A_ )
assert info.missing_keys == [], info.missing_keys # every student key should have a teacher keys.
if copy_first_teacher_layers: # Our copying is done. We just log and save
__magic_name__ , __magic_name__ = list(range(A_ ) ), list(range(A_ ) )
logger.info(
f'''Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to'''
f''' {save_path}''' )
student.save_pretrained(A_ )
return student, e_layers_to_copy, d_layers_to_copy
# Decide which layers of the teacher to copy. Not exactly alternating -- we try to keep first and last layer.
if e_layers_to_copy is None:
__magic_name__ = pick_layers_to_copy(A_, A_ )
if d_layers_to_copy is None:
__magic_name__ = pick_layers_to_copy(A_, A_ )
try:
if hasattr(
A_, """prophetnet""" ): # For ProphetNet, student.model.encoder.layers is called student.prophetnet.encoder.layers
copy_layers(teacher.prophetnet.encoder.layers, student.prophetnet.encoder.layers, A_ )
copy_layers(teacher.prophetnet.decoder.layers, student.prophetnet.decoder.layers, A_ )
else:
copy_layers(teacher.model.encoder.layers, student.model.encoder.layers, A_ )
copy_layers(teacher.model.decoder.layers, student.model.decoder.layers, A_ )
except AttributeError: # For t5, student.model.encoder.layers is called student.encoder.block
copy_layers(teacher.encoder.block, student.encoder.block, A_ )
copy_layers(teacher.decoder.block, student.decoder.block, A_ )
logger.info(
f'''Copied encoder layers {e_layers_to_copy} and decoder layers {d_layers_to_copy}. Saving them to {save_path}''' )
__magic_name__ = {
"""teacher_type""": teacher.config.model_type,
"""copied_encoder_layers""": e_layers_to_copy,
"""copied_decoder_layers""": d_layers_to_copy,
}
student.save_pretrained(A_ )
# Save information about copying for easier reproducibility
return student, e_layers_to_copy, d_layers_to_copy
if __name__ == "__main__":
fire.Fire(create_student_by_copying_alternating_layers)
| 716 |
from ..utils import DummyObject, requires_backends
class UpperCAmelCase_ ( metaclass=_A ):
'''simple docstring'''
a__ = ["""note_seq"""]
def __init__( self : Any , *UpperCamelCase__ : str , **UpperCamelCase__ : List[Any] ) -> Optional[int]:
"""simple docstring"""
requires_backends(self , ["""note_seq"""] )
@classmethod
def _lowercase ( cls : str , *UpperCamelCase__ : Dict , **UpperCamelCase__ : Tuple ) -> Dict:
"""simple docstring"""
requires_backends(cls , ["""note_seq"""] )
@classmethod
def _lowercase ( cls : List[str] , *UpperCamelCase__ : Optional[Any] , **UpperCamelCase__ : Tuple ) -> int:
"""simple docstring"""
requires_backends(cls , ["""note_seq"""] )
| 76 | 0 |
import os
import unittest
from transformers import FunnelTokenizer, FunnelTokenizerFast
from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = FunnelTokenizer
a__ = FunnelTokenizerFast
a__ = True
a__ = True
def _lowercase ( self : List[Any] ) -> str:
"""simple docstring"""
super().setUp()
__magic_name__ = [
"""<unk>""",
"""<cls>""",
"""<sep>""",
"""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] ) )
def _lowercase ( self : Dict , **UpperCamelCase__ : Tuple ) -> Union[str, Any]:
"""simple docstring"""
return FunnelTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase__ )
def _lowercase ( self : str , **UpperCamelCase__ : str ) -> List[str]:
"""simple docstring"""
return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **UpperCamelCase__ )
def _lowercase ( self : List[str] , UpperCamelCase__ : str ) -> List[Any]:
"""simple docstring"""
__magic_name__ = """UNwant\u00E9d,running"""
__magic_name__ = """unwanted, running"""
return input_text, output_text
def _lowercase ( self : Union[str, Any] ) -> Tuple:
"""simple docstring"""
__magic_name__ = self.tokenizer_class(self.vocab_file )
__magic_name__ = tokenizer.tokenize("""UNwant\u00E9d,running""" )
self.assertListEqual(UpperCamelCase__ , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) , [7, 4, 5, 10, 8, 9] )
def _lowercase ( self : str ) -> List[Any]:
"""simple docstring"""
__magic_name__ = self.get_tokenizers(do_lower_case=UpperCamelCase__ )
for tokenizer in tokenizers:
__magic_name__ = tokenizer("""UNwant\u00E9d,running""" )
__magic_name__ = len(inputs["""input_ids"""] ) - 1
self.assertListEqual(inputs["""token_type_ids"""] , [2] + [0] * sentence_len )
__magic_name__ = tokenizer("""UNwant\u00E9d,running""" , """UNwant\u00E9d,running""" )
self.assertListEqual(inputs["""token_type_ids"""] , [2] + [0] * sentence_len + [1] * sentence_len )
| 717 |
def a__ ( A_ ):
'''simple docstring'''
return " ".join(
"""""".join(word[::-1] ) if len(A_ ) > 4 else word for word in sentence.split() )
if __name__ == "__main__":
import doctest
doctest.testmod()
print(reverse_long_words('Hey wollef sroirraw'))
| 76 | 0 |
import fire
from utils import calculate_rouge, save_json
def a__ ( A_, A_, A_=None, **A_ ):
'''simple docstring'''
__magic_name__ = [x.strip() for x in open(A_ ).readlines()]
__magic_name__ = [x.strip() for x in open(A_ ).readlines()][: len(A_ )]
__magic_name__ = calculate_rouge(A_, A_, **A_ )
if save_path is not None:
save_json(A_, A_, indent=A_ )
return metrics # these print nicely
if __name__ == "__main__":
fire.Fire(calculate_rouge_path)
| 718 |
import os
import unittest
from transformers import FunnelTokenizer, FunnelTokenizerFast
from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = FunnelTokenizer
a__ = FunnelTokenizerFast
a__ = True
a__ = True
def _lowercase ( self : List[Any] ) -> str:
"""simple docstring"""
super().setUp()
__magic_name__ = [
"""<unk>""",
"""<cls>""",
"""<sep>""",
"""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] ) )
def _lowercase ( self : Dict , **UpperCamelCase__ : Tuple ) -> Union[str, Any]:
"""simple docstring"""
return FunnelTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase__ )
def _lowercase ( self : str , **UpperCamelCase__ : str ) -> List[str]:
"""simple docstring"""
return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **UpperCamelCase__ )
def _lowercase ( self : List[str] , UpperCamelCase__ : str ) -> List[Any]:
"""simple docstring"""
__magic_name__ = """UNwant\u00E9d,running"""
__magic_name__ = """unwanted, running"""
return input_text, output_text
def _lowercase ( self : Union[str, Any] ) -> Tuple:
"""simple docstring"""
__magic_name__ = self.tokenizer_class(self.vocab_file )
__magic_name__ = tokenizer.tokenize("""UNwant\u00E9d,running""" )
self.assertListEqual(UpperCamelCase__ , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) , [7, 4, 5, 10, 8, 9] )
def _lowercase ( self : str ) -> List[Any]:
"""simple docstring"""
__magic_name__ = self.get_tokenizers(do_lower_case=UpperCamelCase__ )
for tokenizer in tokenizers:
__magic_name__ = tokenizer("""UNwant\u00E9d,running""" )
__magic_name__ = len(inputs["""input_ids"""] ) - 1
self.assertListEqual(inputs["""token_type_ids"""] , [2] + [0] * sentence_len )
__magic_name__ = tokenizer("""UNwant\u00E9d,running""" , """UNwant\u00E9d,running""" )
self.assertListEqual(inputs["""token_type_ids"""] , [2] + [0] * sentence_len + [1] * sentence_len )
| 76 | 0 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_torch_available,
)
__lowerCAmelCase : str = {
'configuration_speecht5': [
'SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP',
'SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP',
'SpeechT5Config',
'SpeechT5HifiGanConfig',
],
'feature_extraction_speecht5': ['SpeechT5FeatureExtractor'],
'processing_speecht5': ['SpeechT5Processor'],
}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowerCAmelCase : Dict = ['SpeechT5Tokenizer']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowerCAmelCase : int = [
'SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST',
'SpeechT5ForSpeechToText',
'SpeechT5ForSpeechToSpeech',
'SpeechT5ForTextToSpeech',
'SpeechT5Model',
'SpeechT5PreTrainedModel',
'SpeechT5HifiGan',
]
if TYPE_CHECKING:
from .configuration_speechta import (
SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP,
SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP,
SpeechTaConfig,
SpeechTaHifiGanConfig,
)
from .feature_extraction_speechta import SpeechTaFeatureExtractor
from .processing_speechta import SpeechTaProcessor
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_speechta import SpeechTaTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_speechta import (
SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST,
SpeechTaForSpeechToSpeech,
SpeechTaForSpeechToText,
SpeechTaForTextToSpeech,
SpeechTaHifiGan,
SpeechTaModel,
SpeechTaPreTrainedModel,
)
else:
import sys
__lowerCAmelCase : Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 719 |
from collections import deque
from .hash_table import HashTable
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
def __init__( self : int , *UpperCamelCase__ : Union[str, Any] , **UpperCamelCase__ : Optional[Any] ) -> Optional[Any]:
"""simple docstring"""
super().__init__(*UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : Optional[Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Any ) -> Dict:
"""simple docstring"""
__magic_name__ = deque([] ) if self.values[key] is None else self.values[key]
self.values[key].appendleft(UpperCamelCase__ )
__magic_name__ = self.values[key]
def _lowercase ( self : List[str] ) -> int:
"""simple docstring"""
return (
sum(self.charge_factor - len(UpperCamelCase__ ) for slot in self.values )
/ self.size_table
* self.charge_factor
)
def _lowercase ( self : Optional[Any] , UpperCamelCase__ : str , UpperCamelCase__ : Tuple=None ) -> str:
"""simple docstring"""
if not (
len(self.values[key] ) == self.charge_factor and self.values.count(UpperCamelCase__ ) == 0
):
return key
return super()._collision_resolution(UpperCamelCase__ , UpperCamelCase__ )
| 76 | 0 |
from ...utils import is_torch_available, is_transformers_available
if is_transformers_available() and is_torch_available():
from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
| 720 |
# 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 json
import os
from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES
from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType
from ...utils.imports import is_botoa_available
from .config_args import SageMakerConfig
from .config_utils import (
DYNAMO_BACKENDS,
_ask_field,
_ask_options,
_convert_dynamo_backend,
_convert_mixed_precision,
_convert_sagemaker_distributed_mode,
_convert_yes_no_to_bool,
)
if is_botoa_available():
import botoa # noqa: F401
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = botoa.client("""iam""" )
__magic_name__ = {
"""Version""": """2012-10-17""",
"""Statement""": [
{"""Effect""": """Allow""", """Principal""": {"""Service""": """sagemaker.amazonaws.com"""}, """Action""": """sts:AssumeRole"""}
],
}
try:
# create the role, associated with the chosen trust policy
iam_client.create_role(
RoleName=A_, AssumeRolePolicyDocument=json.dumps(A_, indent=2 ) )
__magic_name__ = {
"""Version""": """2012-10-17""",
"""Statement""": [
{
"""Effect""": """Allow""",
"""Action""": [
"""sagemaker:*""",
"""ecr:GetDownloadUrlForLayer""",
"""ecr:BatchGetImage""",
"""ecr:BatchCheckLayerAvailability""",
"""ecr:GetAuthorizationToken""",
"""cloudwatch:PutMetricData""",
"""cloudwatch:GetMetricData""",
"""cloudwatch:GetMetricStatistics""",
"""cloudwatch:ListMetrics""",
"""logs:CreateLogGroup""",
"""logs:CreateLogStream""",
"""logs:DescribeLogStreams""",
"""logs:PutLogEvents""",
"""logs:GetLogEvents""",
"""s3:CreateBucket""",
"""s3:ListBucket""",
"""s3:GetBucketLocation""",
"""s3:GetObject""",
"""s3:PutObject""",
],
"""Resource""": """*""",
}
],
}
# attach policy to role
iam_client.put_role_policy(
RoleName=A_, PolicyName=f'''{role_name}_policy_permission''', PolicyDocument=json.dumps(A_, indent=2 ), )
except iam_client.exceptions.EntityAlreadyExistsException:
print(f'''role {role_name} already exists. Using existing one''' )
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = botoa.client("""iam""" )
return iam_client.get_role(RoleName=A_ )["Role"]["Arn"]
def a__ ( ):
'''simple docstring'''
__magic_name__ = _ask_options(
"""How do you want to authorize?""", ["""AWS Profile""", """Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) """], A_, )
__magic_name__ = None
if credentials_configuration == 0:
__magic_name__ = _ask_field("""Enter your AWS Profile name: [default] """, default="""default""" )
__magic_name__ = aws_profile
else:
print(
"""Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,"""
"""`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`""" )
__magic_name__ = _ask_field("""AWS Access Key ID: """ )
__magic_name__ = aws_access_key_id
__magic_name__ = _ask_field("""AWS Secret Access Key: """ )
__magic_name__ = aws_secret_access_key
__magic_name__ = _ask_field("""Enter your AWS Region: [us-east-1]""", default="""us-east-1""" )
__magic_name__ = aws_region
__magic_name__ = _ask_options(
"""Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?""", ["""Provide IAM Role name""", """Create new IAM role using credentials"""], A_, )
if role_management == 0:
__magic_name__ = _ask_field("""Enter your IAM role name: """ )
else:
__magic_name__ = """accelerate_sagemaker_execution_role"""
print(f'''Accelerate will create an iam role "{iam_role_name}" using the provided credentials''' )
_create_iam_role_for_sagemaker(A_ )
__magic_name__ = _ask_field(
"""Do you want to use custom Docker image? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
__magic_name__ = None
if is_custom_docker_image:
__magic_name__ = _ask_field("""Enter your Docker image: """, lambda A_ : str(A_ ).lower() )
__magic_name__ = _ask_field(
"""Do you want to provide SageMaker input channels with data locations? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
__magic_name__ = None
if is_sagemaker_inputs_enabled:
__magic_name__ = _ask_field(
"""Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): """, lambda A_ : str(A_ ).lower(), )
__magic_name__ = _ask_field(
"""Do you want to enable SageMaker metrics? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
__magic_name__ = None
if is_sagemaker_metrics_enabled:
__magic_name__ = _ask_field(
"""Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): """, lambda A_ : str(A_ ).lower(), )
__magic_name__ = _ask_options(
"""What is the distributed mode?""", ["""No distributed training""", """Data parallelism"""], _convert_sagemaker_distributed_mode, )
__magic_name__ = {}
__magic_name__ = _ask_field(
"""Do you wish to optimize your script with torch dynamo?[yes/NO]:""", _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
if use_dynamo:
__magic_name__ = """dynamo_"""
__magic_name__ = _ask_options(
"""Which dynamo backend would you like to use?""", [x.lower() for x in DYNAMO_BACKENDS], _convert_dynamo_backend, default=2, )
__magic_name__ = _ask_field(
"""Do you want to customize the defaults sent to torch.compile? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
if use_custom_options:
__magic_name__ = _ask_options(
"""Which mode do you want to use?""", A_, lambda A_ : TORCH_DYNAMO_MODES[int(A_ )], default="""default""", )
__magic_name__ = _ask_field(
"""Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
__magic_name__ = _ask_field(
"""Do you want to enable dynamic shape tracing? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
__magic_name__ = """Which EC2 instance type you want to use for your training?"""
if distributed_type != SageMakerDistributedType.NO:
__magic_name__ = _ask_options(
A_, A_, lambda A_ : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(A_ )] )
else:
eca_instance_query += "? [ml.p3.2xlarge]:"
__magic_name__ = _ask_field(A_, lambda A_ : str(A_ ).lower(), default="""ml.p3.2xlarge""" )
__magic_name__ = 1
if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL):
__magic_name__ = _ask_field(
"""How many machines do you want use? [1]: """, A_, default=1, )
__magic_name__ = _ask_options(
"""Do you wish to use FP16 or BF16 (mixed precision)?""", ["""no""", """fp16""", """bf16""", """fp8"""], _convert_mixed_precision, )
if use_dynamo and mixed_precision == "no":
print(
"""Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.""" )
return SageMakerConfig(
image_uri=A_, compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER, distributed_type=A_, use_cpu=A_, dynamo_config=A_, eca_instance_type=A_, profile=A_, region=A_, iam_role_name=A_, mixed_precision=A_, num_machines=A_, sagemaker_inputs_file=A_, sagemaker_metrics_file=A_, )
| 76 | 0 |
# tests directory-specific settings - this file is run automatically
# by pytest before any tests are run
import sys
import warnings
from os.path import abspath, dirname, join
# allow having multiple repository checkouts and not needing to remember to rerun
# 'pip install -e .[dev]' when switching between checkouts and running tests.
__lowerCAmelCase : Union[str, Any] = abspath(join(dirname(dirname(__file__)), 'src'))
sys.path.insert(1, git_repo_path)
# silence FutureWarning warnings in tests since often we can't act on them until
# they become normal warnings - i.e. the tests still need to test the current functionality
warnings.simplefilter(action='ignore', category=FutureWarning)
def a__ ( A_ ):
'''simple docstring'''
from diffusers.utils.testing_utils import pytest_addoption_shared
pytest_addoption_shared(A_ )
def a__ ( A_ ):
'''simple docstring'''
from diffusers.utils.testing_utils import pytest_terminal_summary_main
__magic_name__ = terminalreporter.config.getoption("""--make-reports""" )
if make_reports:
pytest_terminal_summary_main(A_, id=A_ )
| 721 |
from typing import Dict, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
convert_to_rgb,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
OPENAI_CLIP_MEAN,
OPENAI_CLIP_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
__lowerCAmelCase : Dict = logging.get_logger(__name__)
if is_vision_available():
import PIL
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = ["""pixel_values"""]
def __init__( self : Optional[Any] , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : bool = True , UpperCamelCase__ : Union[int, float] = 1 / 255 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : bool = True , **UpperCamelCase__ : int , ) -> None:
"""simple docstring"""
super().__init__(**UpperCamelCase__ )
__magic_name__ = size if size is not None else {"""shortest_edge""": 224}
__magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ )
__magic_name__ = crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
__magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ , param_name="""crop_size""" )
__magic_name__ = do_resize
__magic_name__ = size
__magic_name__ = resample
__magic_name__ = do_center_crop
__magic_name__ = crop_size
__magic_name__ = do_rescale
__magic_name__ = rescale_factor
__magic_name__ = do_normalize
__magic_name__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
__magic_name__ = image_std if image_std is not None else OPENAI_CLIP_STD
__magic_name__ = do_convert_rgb
def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Tuple , ) -> np.ndarray:
"""simple docstring"""
__magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ )
if "shortest_edge" not in size:
raise ValueError(F'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' )
__magic_name__ = get_resize_output_image_size(UpperCamelCase__ , size=size["""shortest_edge"""] , default_to_square=UpperCamelCase__ )
return resize(UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : Tuple , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Tuple , ) -> np.ndarray:
"""simple docstring"""
__magic_name__ = get_size_dict(UpperCamelCase__ )
if "height" not in size or "width" not in size:
raise ValueError(F'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' )
return center_crop(UpperCamelCase__ , size=(size["""height"""], size["""width"""]) , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : Any , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[int, float] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Optional[Any] , ) -> Optional[int]:
"""simple docstring"""
return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Dict , ) -> np.ndarray:
"""simple docstring"""
return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : List[Any] , UpperCamelCase__ : ImageInput , UpperCamelCase__ : bool = None , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : int = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : float = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , UpperCamelCase__ : Optional[ChannelDimension] = ChannelDimension.FIRST , **UpperCamelCase__ : Dict , ) -> PIL.Image.Image:
"""simple docstring"""
__magic_name__ = do_resize if do_resize is not None else self.do_resize
__magic_name__ = size if size is not None else self.size
__magic_name__ = get_size_dict(UpperCamelCase__ , param_name="""size""" , default_to_square=UpperCamelCase__ )
__magic_name__ = resample if resample is not None else self.resample
__magic_name__ = do_center_crop if do_center_crop is not None else self.do_center_crop
__magic_name__ = crop_size if crop_size is not None else self.crop_size
__magic_name__ = get_size_dict(UpperCamelCase__ , param_name="""crop_size""" , default_to_square=UpperCamelCase__ )
__magic_name__ = do_rescale if do_rescale is not None else self.do_rescale
__magic_name__ = rescale_factor if rescale_factor is not None else self.rescale_factor
__magic_name__ = do_normalize if do_normalize is not None else self.do_normalize
__magic_name__ = image_mean if image_mean is not None else self.image_mean
__magic_name__ = image_std if image_std is not None else self.image_std
__magic_name__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
__magic_name__ = make_list_of_images(UpperCamelCase__ )
if not valid_images(UpperCamelCase__ ):
raise ValueError(
"""Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
"""torch.Tensor, tf.Tensor or jax.ndarray.""" )
if do_resize and size is None:
raise ValueError("""Size must be specified if do_resize is True.""" )
if do_center_crop and crop_size is None:
raise ValueError("""Crop size must be specified if do_center_crop is True.""" )
if do_rescale and rescale_factor is None:
raise ValueError("""Rescale factor must be specified if do_rescale is True.""" )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError("""Image mean and std must be specified if do_normalize is True.""" )
# PIL RGBA images are converted to RGB
if do_convert_rgb:
__magic_name__ = [convert_to_rgb(UpperCamelCase__ ) for image in images]
# All transformations expect numpy arrays.
__magic_name__ = [to_numpy_array(UpperCamelCase__ ) for image in images]
if do_resize:
__magic_name__ = [self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) for image in images]
if do_center_crop:
__magic_name__ = [self.center_crop(image=UpperCamelCase__ , size=UpperCamelCase__ ) for image in images]
if do_rescale:
__magic_name__ = [self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) for image in images]
if do_normalize:
__magic_name__ = [self.normalize(image=UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ ) for image in images]
__magic_name__ = [to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) for image in images]
__magic_name__ = {"""pixel_values""": images}
return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ )
| 76 | 0 |
import math
def a__ ( A_ ):
'''simple docstring'''
if 1 < number < 4:
# 2 and 3 are primes
return True
elif number < 2 or number % 2 == 0 or number % 3 == 0:
# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
return False
# All primes number are in format of 6k +/- 1
for i in range(5, int(math.sqrt(A_ ) + 1 ), 6 ):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def a__ ( A_ = 10001 ):
'''simple docstring'''
try:
__magic_name__ = int(A_ )
except (TypeError, ValueError):
raise TypeError("""Parameter nth must be int or castable to int.""" ) from None
if nth <= 0:
raise ValueError("""Parameter nth must be greater than or equal to one.""" )
__magic_name__ = []
__magic_name__ = 2
while len(A_ ) < nth:
if is_prime(A_ ):
primes.append(A_ )
num += 1
else:
num += 1
return primes[len(A_ ) - 1]
if __name__ == "__main__":
print(F'''{solution() = }''')
| 700 |
import unittest
from transformers import AutoTokenizer, NystromformerConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
NystromformerForMaskedLM,
NystromformerForMultipleChoice,
NystromformerForQuestionAnswering,
NystromformerForSequenceClassification,
NystromformerForTokenClassification,
NystromformerModel,
)
from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST
class UpperCAmelCase_ :
'''simple docstring'''
def __init__( self : Any , UpperCamelCase__ : Any , UpperCamelCase__ : Tuple=13 , UpperCamelCase__ : Dict=7 , UpperCamelCase__ : Dict=True , UpperCamelCase__ : List[str]=True , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : int=True , UpperCamelCase__ : Optional[int]=99 , UpperCamelCase__ : List[Any]=32 , UpperCamelCase__ : Any=5 , UpperCamelCase__ : List[Any]=4 , UpperCamelCase__ : str=37 , UpperCamelCase__ : Any="gelu" , UpperCamelCase__ : int=0.1 , UpperCamelCase__ : Tuple=0.1 , UpperCamelCase__ : Dict=512 , UpperCamelCase__ : Union[str, Any]=16 , UpperCamelCase__ : Dict=2 , UpperCamelCase__ : Any=0.02 , UpperCamelCase__ : Any=3 , UpperCamelCase__ : Dict=4 , UpperCamelCase__ : List[Any]=None , ) -> Union[str, Any]:
"""simple docstring"""
__magic_name__ = parent
__magic_name__ = batch_size
__magic_name__ = seq_length
__magic_name__ = is_training
__magic_name__ = use_input_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_labels
__magic_name__ = num_choices
__magic_name__ = scope
def _lowercase ( self : Any ) -> Any:
"""simple docstring"""
__magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__magic_name__ = None
if self.use_input_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__ = None
__magic_name__ = None
__magic_name__ = None
if self.use_labels:
__magic_name__ = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
__magic_name__ = ids_tensor([self.batch_size] , self.num_choices )
__magic_name__ = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def _lowercase ( self : Tuple ) -> Any:
"""simple docstring"""
return NystromformerConfig(
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=UpperCamelCase__ , initializer_range=self.initializer_range , )
def _lowercase ( self : Any , UpperCamelCase__ : Tuple , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : str , UpperCamelCase__ : int , UpperCamelCase__ : str , UpperCamelCase__ : Dict , UpperCamelCase__ : str ) -> Tuple:
"""simple docstring"""
__magic_name__ = NystromformerModel(config=UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
__magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ )
__magic_name__ = model(UpperCamelCase__ , token_type_ids=UpperCamelCase__ )
__magic_name__ = model(UpperCamelCase__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def _lowercase ( self : Optional[int] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : str , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] ) -> str:
"""simple docstring"""
__magic_name__ = NystromformerForMaskedLM(config=UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
__magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def _lowercase ( self : Tuple , UpperCamelCase__ : Any , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Any , UpperCamelCase__ : Any ) -> Optional[Any]:
"""simple docstring"""
__magic_name__ = NystromformerForQuestionAnswering(config=UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
__magic_name__ = model(
UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , start_positions=UpperCamelCase__ , end_positions=UpperCamelCase__ , )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def _lowercase ( self : Optional[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Dict , UpperCamelCase__ : Dict , UpperCamelCase__ : Any ) -> Optional[int]:
"""simple docstring"""
__magic_name__ = self.num_labels
__magic_name__ = NystromformerForSequenceClassification(UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
__magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def _lowercase ( self : Any , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : str , UpperCamelCase__ : Any ) -> Dict:
"""simple docstring"""
__magic_name__ = self.num_labels
__magic_name__ = NystromformerForTokenClassification(config=UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
__magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : int ) -> Optional[Any]:
"""simple docstring"""
__magic_name__ = self.num_choices
__magic_name__ = NystromformerForMultipleChoice(config=UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
__magic_name__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
__magic_name__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
__magic_name__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
__magic_name__ = model(
UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def _lowercase ( self : int ) -> List[Any]:
"""simple docstring"""
__magic_name__ = self.prepare_config_and_inputs()
(
(
__magic_name__
) , (
__magic_name__
) , (
__magic_name__
) , (
__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""": input_mask}
return config, inputs_dict
@require_torch
class UpperCAmelCase_ ( _A , _A , unittest.TestCase ):
'''simple docstring'''
a__ = (
(
NystromformerModel,
NystromformerForMaskedLM,
NystromformerForMultipleChoice,
NystromformerForQuestionAnswering,
NystromformerForSequenceClassification,
NystromformerForTokenClassification,
)
if is_torch_available()
else ()
)
a__ = (
{
"""feature-extraction""": NystromformerModel,
"""fill-mask""": NystromformerForMaskedLM,
"""question-answering""": NystromformerForQuestionAnswering,
"""text-classification""": NystromformerForSequenceClassification,
"""token-classification""": NystromformerForTokenClassification,
"""zero-shot""": NystromformerForSequenceClassification,
}
if is_torch_available()
else {}
)
a__ = False
a__ = False
def _lowercase ( self : Union[str, Any] ) -> Union[str, Any]:
"""simple docstring"""
__magic_name__ = NystromformerModelTester(self )
__magic_name__ = ConfigTester(self , config_class=UpperCamelCase__ , hidden_size=37 )
def _lowercase ( self : Tuple ) -> Any:
"""simple docstring"""
self.config_tester.run_common_tests()
def _lowercase ( self : Optional[Any] ) -> Any:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*UpperCamelCase__ )
def _lowercase ( self : Optional[Any] ) -> int:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
__magic_name__ = type
self.model_tester.create_and_check_model(*UpperCamelCase__ )
def _lowercase ( self : List[Any] ) -> List[Any]:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase__ )
def _lowercase ( self : Union[str, Any] ) -> str:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*UpperCamelCase__ )
def _lowercase ( self : Dict ) -> List[Any]:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*UpperCamelCase__ )
def _lowercase ( self : str ) -> int:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase__ )
def _lowercase ( self : List[Any] ) -> List[str]:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*UpperCamelCase__ )
@slow
def _lowercase ( self : str ) -> Tuple:
"""simple docstring"""
for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__magic_name__ = NystromformerModel.from_pretrained(UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
@require_torch
class UpperCAmelCase_ ( unittest.TestCase ):
'''simple docstring'''
@slow
def _lowercase ( self : Union[str, Any] ) -> Optional[Any]:
"""simple docstring"""
__magic_name__ = NystromformerModel.from_pretrained("""uw-madison/nystromformer-512""" )
__magic_name__ = torch.tensor([[0, 1, 2, 3, 4, 5]] )
with torch.no_grad():
__magic_name__ = model(UpperCamelCase__ )[0]
__magic_name__ = torch.Size((1, 6, 768) )
self.assertEqual(output.shape , UpperCamelCase__ )
__magic_name__ = torch.tensor(
[[[-0.4532, -0.0936, 0.5137], [-0.2676, 0.0628, 0.6186], [-0.3629, -0.1726, 0.4716]]] )
self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCamelCase__ , atol=1E-4 ) )
@slow
def _lowercase ( self : int ) -> str:
"""simple docstring"""
__magic_name__ = """the [MASK] of Belgium is Brussels"""
__magic_name__ = AutoTokenizer.from_pretrained("""uw-madison/nystromformer-512""" )
__magic_name__ = NystromformerForMaskedLM.from_pretrained("""uw-madison/nystromformer-512""" )
__magic_name__ = tokenizer(UpperCamelCase__ , return_tensors="""pt""" )
with torch.no_grad():
__magic_name__ = model(encoding.input_ids ).logits
__magic_name__ = token_logits[:, 2, :].argmax(-1 )[0]
self.assertEqual(tokenizer.decode(UpperCamelCase__ ) , """capital""" )
| 76 | 0 |
import baseaa
def a__ ( A_ ):
'''simple docstring'''
return baseaa.aaaencode(string.encode("""utf-8""" ) )
def a__ ( A_ ):
'''simple docstring'''
return baseaa.aaadecode(A_ ).decode("""utf-8""" )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 701 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__lowerCAmelCase : Tuple = logging.get_logger(__name__)
__lowerCAmelCase : Union[str, Any] = {
'microsoft/cvt-13': 'https://huggingface.co/microsoft/cvt-13/resolve/main/config.json',
# See all Cvt models at https://huggingface.co/models?filter=cvt
}
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = """cvt"""
def __init__( self : Dict , UpperCamelCase__ : Optional[int]=3 , UpperCamelCase__ : List[Any]=[7, 3, 3] , UpperCamelCase__ : Any=[4, 2, 2] , UpperCamelCase__ : Optional[Any]=[2, 1, 1] , UpperCamelCase__ : Union[str, Any]=[64, 192, 384] , UpperCamelCase__ : Dict=[1, 3, 6] , UpperCamelCase__ : Any=[1, 2, 10] , UpperCamelCase__ : List[str]=[4.0, 4.0, 4.0] , UpperCamelCase__ : Dict=[0.0, 0.0, 0.0] , UpperCamelCase__ : Tuple=[0.0, 0.0, 0.0] , UpperCamelCase__ : Optional[Any]=[0.0, 0.0, 0.1] , UpperCamelCase__ : str=[True, True, True] , UpperCamelCase__ : Optional[Any]=[False, False, True] , UpperCamelCase__ : Union[str, Any]=["dw_bn", "dw_bn", "dw_bn"] , UpperCamelCase__ : List[Any]=[3, 3, 3] , UpperCamelCase__ : Any=[1, 1, 1] , UpperCamelCase__ : Optional[int]=[2, 2, 2] , UpperCamelCase__ : Any=[1, 1, 1] , UpperCamelCase__ : List[str]=[1, 1, 1] , UpperCamelCase__ : int=0.02 , UpperCamelCase__ : int=1E-12 , **UpperCamelCase__ : int , ) -> Dict:
"""simple docstring"""
super().__init__(**UpperCamelCase__ )
__magic_name__ = num_channels
__magic_name__ = patch_sizes
__magic_name__ = patch_stride
__magic_name__ = patch_padding
__magic_name__ = embed_dim
__magic_name__ = num_heads
__magic_name__ = depth
__magic_name__ = mlp_ratio
__magic_name__ = attention_drop_rate
__magic_name__ = drop_rate
__magic_name__ = drop_path_rate
__magic_name__ = qkv_bias
__magic_name__ = cls_token
__magic_name__ = qkv_projection_method
__magic_name__ = kernel_qkv
__magic_name__ = padding_kv
__magic_name__ = stride_kv
__magic_name__ = padding_q
__magic_name__ = stride_q
__magic_name__ = initializer_range
__magic_name__ = layer_norm_eps
| 76 | 0 |
import gc
import threading
import time
import psutil
import torch
class UpperCAmelCase_ :
'''simple docstring'''
def __init__( self : Tuple ) -> Dict:
"""simple docstring"""
__magic_name__ = psutil.Process()
__magic_name__ = False
def _lowercase ( self : int ) -> Tuple:
"""simple docstring"""
__magic_name__ = -1
while True:
__magic_name__ = max(self.process.memory_info().rss , self.cpu_memory_peak )
# can't sleep or will not catch the peak right (this comment is here on purpose)
if not self.peak_monitoring:
break
def _lowercase ( self : List[Any] ) -> Tuple:
"""simple docstring"""
__magic_name__ = True
__magic_name__ = threading.Thread(target=self.peak_monitor )
__magic_name__ = True
self.thread.start()
def _lowercase ( self : Optional[int] ) -> Optional[int]:
"""simple docstring"""
__magic_name__ = False
self.thread.join()
return self.cpu_memory_peak
__lowerCAmelCase : int = PeakCPUMemory()
def a__ ( ):
'''simple docstring'''
__magic_name__ = {"""time""": time.time()}
gc.collect()
torch.cuda.empty_cache()
# CPU mem
__magic_name__ = psutil.Process().memory_info().rss
cpu_peak_tracker.start()
# GPU mem
for i in range(torch.cuda.device_count() ):
__magic_name__ = torch.cuda.memory_allocated(A_ )
torch.cuda.reset_peak_memory_stats()
return measures
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = {"""time""": time.time() - start_measures["""time"""]}
gc.collect()
torch.cuda.empty_cache()
# CPU mem
__magic_name__ = (psutil.Process().memory_info().rss - start_measures["""cpu"""]) / 2**20
__magic_name__ = (cpu_peak_tracker.stop() - start_measures["""cpu"""]) / 2**20
# GPU mem
for i in range(torch.cuda.device_count() ):
__magic_name__ = (torch.cuda.memory_allocated(A_ ) - start_measures[str(A_ )]) / 2**20
__magic_name__ = (torch.cuda.max_memory_allocated(A_ ) - start_measures[str(A_ )]) / 2**20
return measures
def a__ ( A_, A_ ):
'''simple docstring'''
print(f'''{description}:''' )
print(f'''- Time: {measures['time']:.2f}s''' )
for i in range(torch.cuda.device_count() ):
print(f'''- GPU {i} allocated: {measures[str(A_ )]:.2f}MiB''' )
__magic_name__ = measures[f'''{i}-peak''']
print(f'''- GPU {i} peak: {peak:.2f}MiB''' )
print(f'''- CPU RAM allocated: {measures['cpu']:.2f}MiB''' )
print(f'''- CPU RAM peak: {measures['cpu-peak']:.2f}MiB''' )
| 702 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
__lowerCAmelCase : List[str] = {
'configuration_canine': ['CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CanineConfig'],
'tokenization_canine': ['CanineTokenizer'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowerCAmelCase : Optional[Any] = [
'CANINE_PRETRAINED_MODEL_ARCHIVE_LIST',
'CanineForMultipleChoice',
'CanineForQuestionAnswering',
'CanineForSequenceClassification',
'CanineForTokenClassification',
'CanineLayer',
'CanineModel',
'CaninePreTrainedModel',
'load_tf_weights_in_canine',
]
if TYPE_CHECKING:
from .configuration_canine import CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP, CanineConfig
from .tokenization_canine import CanineTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_canine import (
CANINE_PRETRAINED_MODEL_ARCHIVE_LIST,
CanineForMultipleChoice,
CanineForQuestionAnswering,
CanineForSequenceClassification,
CanineForTokenClassification,
CanineLayer,
CanineModel,
CaninePreTrainedModel,
load_tf_weights_in_canine,
)
else:
import sys
__lowerCAmelCase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 76 | 0 |
from sympy import diff, lambdify, symbols
from sympy.functions import * # noqa: F403
def a__ ( A_, A_, A_ = "x", A_ = 10**-10, A_ = 1, ):
'''simple docstring'''
__magic_name__ = symbols(A_ )
__magic_name__ = lambdify(A_, A_ )
__magic_name__ = lambdify(A_, diff(A_, A_ ) )
__magic_name__ = starting_point
while True:
if diff_function(A_ ) != 0:
__magic_name__ = prev_guess - multiplicity * func(A_ ) / diff_function(
A_ )
else:
raise ZeroDivisionError("""Could not find root""" ) from None
# Precision is checked by comparing the difference of consecutive guesses
if abs(next_guess - prev_guess ) < precision:
return next_guess
__magic_name__ = next_guess
# Let's Execute
if __name__ == "__main__":
# Find root of trigonometric function
# Find value of pi
print(F'''The root of sin(x) = 0 is {newton_raphson("sin(x)", 2)}''')
# Find root of polynomial
# Find fourth Root of 5
print(F'''The root of x**4 - 5 = 0 is {newton_raphson("x**4 -5", 0.4 +5j)}''')
# Find value of e
print(
'The root of log(y) - 1 = 0 is ',
F'''{newton_raphson("log(y) - 1", 2, variable="y")}''',
)
# Exponential Roots
print(
'The root of exp(x) - 1 = 0 is',
F'''{newton_raphson("exp(x) - 1", 10, precision=0.005)}''',
)
# Find root of cos(x)
print(F'''The root of cos(x) = 0 is {newton_raphson("cos(x)", 0)}''')
| 703 |
import argparse
import torch
from transformers import (
WavaVecaConfig,
WavaVecaFeatureExtractor,
WavaVecaForAudioFrameClassification,
WavaVecaForSequenceClassification,
WavaVecaForXVector,
logging,
)
logging.set_verbosity_info()
__lowerCAmelCase : str = logging.get_logger(__name__)
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = WavaVecaForSequenceClassification.from_pretrained(A_, config=A_ )
__magic_name__ = downstream_dict["""projector.weight"""]
__magic_name__ = downstream_dict["""projector.bias"""]
__magic_name__ = downstream_dict["""model.post_net.linear.weight"""]
__magic_name__ = downstream_dict["""model.post_net.linear.bias"""]
return model
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = WavaVecaForAudioFrameClassification.from_pretrained(A_, config=A_ )
__magic_name__ = downstream_dict["""model.linear.weight"""]
__magic_name__ = downstream_dict["""model.linear.bias"""]
return model
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = WavaVecaForXVector.from_pretrained(A_, config=A_ )
__magic_name__ = downstream_dict["""connector.weight"""]
__magic_name__ = downstream_dict["""connector.bias"""]
for i, kernel_size in enumerate(hf_config.tdnn_kernel ):
__magic_name__ = downstream_dict[
f'''model.framelevel_feature_extractor.module.{i}.kernel.weight'''
]
__magic_name__ = downstream_dict[f'''model.framelevel_feature_extractor.module.{i}.kernel.bias''']
__magic_name__ = downstream_dict["""model.utterancelevel_feature_extractor.linear1.weight"""]
__magic_name__ = downstream_dict["""model.utterancelevel_feature_extractor.linear1.bias"""]
__magic_name__ = downstream_dict["""model.utterancelevel_feature_extractor.linear2.weight"""]
__magic_name__ = downstream_dict["""model.utterancelevel_feature_extractor.linear2.bias"""]
__magic_name__ = downstream_dict["""objective.W"""]
return model
@torch.no_grad()
def a__ ( A_, A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = torch.load(A_, map_location="""cpu""" )
__magic_name__ = checkpoint["""Downstream"""]
__magic_name__ = WavaVecaConfig.from_pretrained(A_ )
__magic_name__ = WavaVecaFeatureExtractor.from_pretrained(
A_, return_attention_mask=A_, do_normalize=A_ )
__magic_name__ = hf_config.architectures[0]
if arch.endswith("""ForSequenceClassification""" ):
__magic_name__ = convert_classification(A_, A_, A_ )
elif arch.endswith("""ForAudioFrameClassification""" ):
__magic_name__ = convert_diarization(A_, A_, A_ )
elif arch.endswith("""ForXVector""" ):
__magic_name__ = convert_xvector(A_, A_, A_ )
else:
raise NotImplementedError(f'''S3PRL weights conversion is not supported for {arch}''' )
if hf_config.use_weighted_layer_sum:
__magic_name__ = checkpoint["""Featurizer"""]["""weights"""]
hf_feature_extractor.save_pretrained(A_ )
hf_model.save_pretrained(A_ )
if __name__ == "__main__":
__lowerCAmelCase : Optional[Any] = argparse.ArgumentParser()
parser.add_argument(
'--base_model_name', default=None, type=str, help='Name of the huggingface pretrained base model.'
)
parser.add_argument('--config_path', default=None, type=str, help='Path to the huggingface classifier config.')
parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to the s3prl checkpoint.')
parser.add_argument('--model_dump_path', default=None, type=str, help='Path to the final converted model.')
__lowerCAmelCase : str = parser.parse_args()
convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
| 76 | 0 |
import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_convbert import ConvBertTokenizer
__lowerCAmelCase : List[str] = logging.get_logger(__name__)
__lowerCAmelCase : Union[str, Any] = {'vocab_file': 'vocab.txt'}
__lowerCAmelCase : str = {
'vocab_file': {
'YituTech/conv-bert-base': 'https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt',
'YituTech/conv-bert-medium-small': (
'https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt'
),
'YituTech/conv-bert-small': 'https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt',
}
}
__lowerCAmelCase : List[str] = {
'YituTech/conv-bert-base': 512,
'YituTech/conv-bert-medium-small': 512,
'YituTech/conv-bert-small': 512,
}
__lowerCAmelCase : Tuple = {
'YituTech/conv-bert-base': {'do_lower_case': True},
'YituTech/conv-bert-medium-small': {'do_lower_case': True},
'YituTech/conv-bert-small': {'do_lower_case': True},
}
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = VOCAB_FILES_NAMES
a__ = PRETRAINED_VOCAB_FILES_MAP
a__ = PRETRAINED_INIT_CONFIGURATION
a__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
a__ = ConvBertTokenizer
def __init__( self : str , UpperCamelCase__ : Optional[int]=None , UpperCamelCase__ : List[Any]=None , UpperCamelCase__ : Dict=True , UpperCamelCase__ : Optional[Any]="[UNK]" , UpperCamelCase__ : Optional[Any]="[SEP]" , UpperCamelCase__ : Tuple="[PAD]" , UpperCamelCase__ : Any="[CLS]" , UpperCamelCase__ : int="[MASK]" , UpperCamelCase__ : Any=True , UpperCamelCase__ : Optional[Any]=None , **UpperCamelCase__ : Dict , ) -> List[Any]:
"""simple docstring"""
super().__init__(
UpperCamelCase__ , tokenizer_file=UpperCamelCase__ , do_lower_case=UpperCamelCase__ , unk_token=UpperCamelCase__ , sep_token=UpperCamelCase__ , pad_token=UpperCamelCase__ , cls_token=UpperCamelCase__ , mask_token=UpperCamelCase__ , tokenize_chinese_chars=UpperCamelCase__ , strip_accents=UpperCamelCase__ , **UpperCamelCase__ , )
__magic_name__ = json.loads(self.backend_tokenizer.normalizer.__getstate__() )
if (
normalizer_state.get("""lowercase""" , UpperCamelCase__ ) != do_lower_case
or normalizer_state.get("""strip_accents""" , UpperCamelCase__ ) != strip_accents
or normalizer_state.get("""handle_chinese_chars""" , UpperCamelCase__ ) != tokenize_chinese_chars
):
__magic_name__ = getattr(UpperCamelCase__ , normalizer_state.pop("""type""" ) )
__magic_name__ = do_lower_case
__magic_name__ = strip_accents
__magic_name__ = tokenize_chinese_chars
__magic_name__ = normalizer_class(**UpperCamelCase__ )
__magic_name__ = do_lower_case
def _lowercase ( self : int , UpperCamelCase__ : int , UpperCamelCase__ : str=None ) -> Optional[int]:
"""simple docstring"""
__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 _lowercase ( self : List[Any] , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None ) -> List[int]:
"""simple docstring"""
__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 _lowercase ( self : Tuple , UpperCamelCase__ : str , UpperCamelCase__ : Optional[str] = None ) -> Tuple[str]:
"""simple docstring"""
__magic_name__ = self._tokenizer.model.save(UpperCamelCase__ , name=UpperCamelCase__ )
return tuple(UpperCamelCase__ )
| 704 |
import pytest
from datasets import Dataset, DatasetDict, Features, NamedSplit, Value
from datasets.io.text import TextDatasetReader
from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases
def a__ ( A_, A_ ):
'''simple docstring'''
assert isinstance(A_, A_ )
assert dataset.num_rows == 4
assert dataset.num_columns == 1
assert dataset.column_names == ["text"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize("""keep_in_memory""", [False, True] )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = tmp_path / """cache"""
__magic_name__ = {"""text""": """string"""}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
__magic_name__ = TextDatasetReader(A_, cache_dir=A_, keep_in_memory=A_ ).read()
_check_text_dataset(A_, A_ )
@pytest.mark.parametrize(
"""features""", [
None,
{"""text""": """string"""},
{"""text""": """int32"""},
{"""text""": """float32"""},
], )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = tmp_path / """cache"""
__magic_name__ = {"""text""": """string"""}
__magic_name__ = features.copy() if features else default_expected_features
__magic_name__ = (
Features({feature: Value(A_ ) for feature, dtype in features.items()} ) if features is not None else None
)
__magic_name__ = TextDatasetReader(A_, features=A_, cache_dir=A_ ).read()
_check_text_dataset(A_, A_ )
@pytest.mark.parametrize("""split""", [None, NamedSplit("""train""" ), """train""", """test"""] )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = tmp_path / """cache"""
__magic_name__ = {"""text""": """string"""}
__magic_name__ = TextDatasetReader(A_, cache_dir=A_, split=A_ ).read()
_check_text_dataset(A_, A_ )
assert dataset.split == split if split else "train"
@pytest.mark.parametrize("""path_type""", [str, list] )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
if issubclass(A_, A_ ):
__magic_name__ = text_path
elif issubclass(A_, A_ ):
__magic_name__ = [text_path]
__magic_name__ = tmp_path / """cache"""
__magic_name__ = {"""text""": """string"""}
__magic_name__ = TextDatasetReader(A_, cache_dir=A_ ).read()
_check_text_dataset(A_, A_ )
def a__ ( A_, A_, A_=("train",) ):
'''simple docstring'''
assert isinstance(A_, A_ )
for split in splits:
__magic_name__ = dataset_dict[split]
assert dataset.num_rows == 4
assert dataset.num_columns == 1
assert dataset.column_names == ["text"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize("""keep_in_memory""", [False, True] )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = tmp_path / """cache"""
__magic_name__ = {"""text""": """string"""}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
__magic_name__ = TextDatasetReader({"""train""": text_path}, cache_dir=A_, keep_in_memory=A_ ).read()
_check_text_datasetdict(A_, A_ )
@pytest.mark.parametrize(
"""features""", [
None,
{"""text""": """string"""},
{"""text""": """int32"""},
{"""text""": """float32"""},
], )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = tmp_path / """cache"""
# CSV file loses col_1 string dtype information: default now is "int64" instead of "string"
__magic_name__ = {"""text""": """string"""}
__magic_name__ = features.copy() if features else default_expected_features
__magic_name__ = (
Features({feature: Value(A_ ) for feature, dtype in features.items()} ) if features is not None else None
)
__magic_name__ = TextDatasetReader({"""train""": text_path}, features=A_, cache_dir=A_ ).read()
_check_text_datasetdict(A_, A_ )
@pytest.mark.parametrize("""split""", [None, NamedSplit("""train""" ), """train""", """test"""] )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
if split:
__magic_name__ = {split: text_path}
else:
__magic_name__ = """train"""
__magic_name__ = {"""train""": text_path, """test""": text_path}
__magic_name__ = tmp_path / """cache"""
__magic_name__ = {"""text""": """string"""}
__magic_name__ = TextDatasetReader(A_, cache_dir=A_ ).read()
_check_text_datasetdict(A_, A_, splits=list(path.keys() ) )
assert all(dataset[split].split == split for split in path.keys() )
| 76 | 0 |
def a__ ( A_ = 10**12 ):
'''simple docstring'''
__magic_name__ = 1
__magic_name__ = 0
__magic_name__ = 1
__magic_name__ = 1
while numerator <= 2 * min_total - 1:
prev_numerator += 2 * numerator
numerator += 2 * prev_numerator
prev_denominator += 2 * denominator
denominator += 2 * prev_denominator
return (denominator + 1) // 2
if __name__ == "__main__":
print(F'''{solution() = }''')
| 705 |
from typing import Dict, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
IMAGENET_STANDARD_MEAN,
IMAGENET_STANDARD_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, logging
__lowerCAmelCase : Union[str, Any] = logging.get_logger(__name__)
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = ["""pixel_values"""]
def __init__( self : str , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Dict[str, int]] = None , UpperCamelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : bool = True , UpperCamelCase__ : Union[int, float] = 1 / 255 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , **UpperCamelCase__ : List[Any] , ) -> None:
"""simple docstring"""
super().__init__(**UpperCamelCase__ )
__magic_name__ = size if size is not None else {"""shortest_edge""": 256}
__magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ )
__magic_name__ = crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
__magic_name__ = get_size_dict(UpperCamelCase__ )
__magic_name__ = do_resize
__magic_name__ = size
__magic_name__ = resample
__magic_name__ = do_center_crop
__magic_name__ = crop_size
__magic_name__ = do_rescale
__magic_name__ = rescale_factor
__magic_name__ = do_normalize
__magic_name__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
__magic_name__ = image_std if image_std is not None else IMAGENET_STANDARD_STD
def _lowercase ( self : Any , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Tuple , ) -> np.ndarray:
"""simple docstring"""
__magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ )
if "shortest_edge" not in size:
raise ValueError(F'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' )
__magic_name__ = get_resize_output_image_size(UpperCamelCase__ , size=size["""shortest_edge"""] , default_to_square=UpperCamelCase__ )
return resize(UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : str , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : str , ) -> np.ndarray:
"""simple docstring"""
__magic_name__ = get_size_dict(UpperCamelCase__ )
return center_crop(UpperCamelCase__ , size=(size["""height"""], size["""width"""]) , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : Tuple , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : float , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Any ) -> np.ndarray:
"""simple docstring"""
return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : List[str] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : str , ) -> np.ndarray:
"""simple docstring"""
return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : Optional[Any] , UpperCamelCase__ : ImageInput , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Optional[float] = None , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , UpperCamelCase__ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **UpperCamelCase__ : int , ) -> Dict:
"""simple docstring"""
__magic_name__ = do_resize if do_resize is not None else self.do_resize
__magic_name__ = size if size is not None else self.size
__magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ )
__magic_name__ = resample if resample is not None else self.resample
__magic_name__ = do_center_crop if do_center_crop is not None else self.do_center_crop
__magic_name__ = crop_size if crop_size is not None else self.crop_size
__magic_name__ = get_size_dict(UpperCamelCase__ )
__magic_name__ = do_rescale if do_rescale is not None else self.do_rescale
__magic_name__ = rescale_factor if rescale_factor is not None else self.rescale_factor
__magic_name__ = do_normalize if do_normalize is not None else self.do_normalize
__magic_name__ = image_mean if image_mean is not None else self.image_mean
__magic_name__ = image_std if image_std is not None else self.image_std
__magic_name__ = make_list_of_images(UpperCamelCase__ )
if not valid_images(UpperCamelCase__ ):
raise ValueError(
"""Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
"""torch.Tensor, tf.Tensor or jax.ndarray.""" )
if do_resize and size is None:
raise ValueError("""Size must be specified if do_resize is True.""" )
if do_center_crop and crop_size is None:
raise ValueError("""Crop size must be specified if do_center_crop is True.""" )
if do_rescale and rescale_factor is None:
raise ValueError("""Rescale factor must be specified if do_rescale is True.""" )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError("""Image mean and std must be specified if do_normalize is True.""" )
# All transformations expect numpy arrays.
__magic_name__ = [to_numpy_array(UpperCamelCase__ ) for image in images]
if do_resize:
__magic_name__ = [self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) for image in images]
if do_center_crop:
__magic_name__ = [self.center_crop(image=UpperCamelCase__ , size=UpperCamelCase__ ) for image in images]
if do_rescale:
__magic_name__ = [self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) for image in images]
if do_normalize:
__magic_name__ = [self.normalize(image=UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ ) for image in images]
__magic_name__ = [to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) for image in images]
__magic_name__ = {"""pixel_values""": images}
return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ )
| 76 | 0 |
from __future__ import annotations
def a__ ( A_ ):
'''simple docstring'''
if not nums:
raise ValueError("""List is empty""" )
return sum(A_ ) / len(A_ )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 706 |
import math
def a__ ( A_, A_ = 0, A_ = 0 ):
'''simple docstring'''
__magic_name__ = end or len(A_ )
for i in range(A_, A_ ):
__magic_name__ = i
__magic_name__ = array[i]
while temp_index != start and temp_index_value < array[temp_index - 1]:
__magic_name__ = array[temp_index - 1]
temp_index -= 1
__magic_name__ = temp_index_value
return array
def a__ ( A_, A_, A_ ): # Max Heap
'''simple docstring'''
__magic_name__ = index
__magic_name__ = 2 * index + 1 # Left Node
__magic_name__ = 2 * index + 2 # Right Node
if left_index < heap_size and array[largest] < array[left_index]:
__magic_name__ = left_index
if right_index < heap_size and array[largest] < array[right_index]:
__magic_name__ = right_index
if largest != index:
__magic_name__ , __magic_name__ = array[largest], array[index]
heapify(A_, A_, A_ )
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = len(A_ )
for i in range(n // 2, -1, -1 ):
heapify(A_, A_, A_ )
for i in range(n - 1, 0, -1 ):
__magic_name__ , __magic_name__ = array[0], array[i]
heapify(A_, 0, A_ )
return array
def a__ ( A_, A_, A_, A_ ):
'''simple docstring'''
if (array[first_index] > array[middle_index]) != (
array[first_index] > array[last_index]
):
return array[first_index]
elif (array[middle_index] > array[first_index]) != (
array[middle_index] > array[last_index]
):
return array[middle_index]
else:
return array[last_index]
def a__ ( A_, A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = low
__magic_name__ = high
while True:
while array[i] < pivot:
i += 1
j -= 1
while pivot < array[j]:
j -= 1
if i >= j:
return i
__magic_name__ , __magic_name__ = array[j], array[i]
i += 1
def a__ ( A_ ):
'''simple docstring'''
if len(A_ ) == 0:
return array
__magic_name__ = 2 * math.ceil(math.loga(len(A_ ) ) )
__magic_name__ = 16
return intro_sort(A_, 0, len(A_ ), A_, A_ )
def a__ ( A_, A_, A_, A_, A_ ):
'''simple docstring'''
while end - start > size_threshold:
if max_depth == 0:
return heap_sort(A_ )
max_depth -= 1
__magic_name__ = median_of_a(A_, A_, start + ((end - start) // 2) + 1, end - 1 )
__magic_name__ = partition(A_, A_, A_, A_ )
intro_sort(A_, A_, A_, A_, A_ )
__magic_name__ = p
return insertion_sort(A_, A_, A_ )
if __name__ == "__main__":
import doctest
doctest.testmod()
__lowerCAmelCase : str = input('Enter numbers separated by a comma : ').strip()
__lowerCAmelCase : List[Any] = [float(item) for item in user_input.split(',')]
print(sort(unsorted))
| 76 | 0 |
from __future__ import annotations
def a__ ( A_, A_, A_, A_ ): # noqa: E741
'''simple docstring'''
while r - l > 1:
__magic_name__ = (l + r) // 2
if v[m] >= key:
__magic_name__ = m
else:
__magic_name__ = m # noqa: E741
return r
def a__ ( A_ ):
'''simple docstring'''
if len(A_ ) == 0:
return 0
__magic_name__ = [0] * len(A_ )
__magic_name__ = 1
__magic_name__ = v[0]
for i in range(1, len(A_ ) ):
if v[i] < tail[0]:
__magic_name__ = v[i]
elif v[i] > tail[length - 1]:
__magic_name__ = v[i]
length += 1
else:
__magic_name__ = v[i]
return length
if __name__ == "__main__":
import doctest
doctest.testmod()
| 707 |
import argparse
import json
import re
from pathlib import Path
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import (
MobileNetVaConfig,
MobileNetVaForImageClassification,
MobileNetVaImageProcessor,
load_tf_weights_in_mobilenet_va,
)
from transformers.utils import logging
logging.set_verbosity_info()
__lowerCAmelCase : str = logging.get_logger(__name__)
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = MobileNetVaConfig(layer_norm_eps=0.001 )
if "_quant" in model_name:
raise ValueError("""Quantized models are not supported.""" )
__magic_name__ = re.match(R"""^mobilenet_v1_([^_]*)_([^_]*)$""", A_ )
if matches:
__magic_name__ = float(matches[1] )
__magic_name__ = int(matches[2] )
# The TensorFlow version of MobileNetV1 predicts 1001 classes instead of
# the usual 1000. The first class (index 0) is "background".
__magic_name__ = 1001
__magic_name__ = """imagenet-1k-id2label.json"""
__magic_name__ = """huggingface/label-files"""
__magic_name__ = json.load(open(hf_hub_download(A_, A_, repo_type="""dataset""" ), """r""" ) )
__magic_name__ = {int(A_ ) + 1: v for k, v in idalabel.items()}
__magic_name__ = """background"""
__magic_name__ = idalabel
__magic_name__ = {v: k for k, v in idalabel.items()}
return config
def a__ ( ):
'''simple docstring'''
__magic_name__ = """http://images.cocodataset.org/val2017/000000039769.jpg"""
__magic_name__ = Image.open(requests.get(A_, stream=A_ ).raw )
return im
@torch.no_grad()
def a__ ( A_, A_, A_, A_=False ):
'''simple docstring'''
__magic_name__ = get_mobilenet_va_config(A_ )
# Load 🤗 model
__magic_name__ = MobileNetVaForImageClassification(A_ ).eval()
# Load weights from TensorFlow checkpoint
load_tf_weights_in_mobilenet_va(A_, A_, A_ )
# Check outputs on an image, prepared by MobileNetV1ImageProcessor
__magic_name__ = MobileNetVaImageProcessor(
crop_size={"""width""": config.image_size, """height""": config.image_size}, size={"""shortest_edge""": config.image_size + 32}, )
__magic_name__ = image_processor(images=prepare_img(), return_tensors="""pt""" )
__magic_name__ = model(**A_ )
__magic_name__ = outputs.logits
assert logits.shape == (1, 1001)
if model_name == "mobilenet_v1_1.0_224":
__magic_name__ = torch.tensor([-4.1739, -1.1233, 3.1205] )
elif model_name == "mobilenet_v1_0.75_192":
__magic_name__ = torch.tensor([-3.9440, -2.3141, -0.3333] )
else:
__magic_name__ = None
if expected_logits is not None:
assert torch.allclose(logits[0, :3], A_, atol=1e-4 )
Path(A_ ).mkdir(exist_ok=A_ )
print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' )
model.save_pretrained(A_ )
print(f'''Saving image processor to {pytorch_dump_folder_path}''' )
image_processor.save_pretrained(A_ )
if push_to_hub:
print("""Pushing to the hub...""" )
__magic_name__ = """google/""" + model_name
image_processor.push_to_hub(A_ )
model.push_to_hub(A_ )
if __name__ == "__main__":
__lowerCAmelCase : str = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--model_name',
default='mobilenet_v1_1.0_224',
type=str,
help='Name of the MobileNetV1 model you\'d like to convert. Should in the form \'mobilenet_v1_<depth>_<size>\'.',
)
parser.add_argument(
'--checkpoint_path', required=True, type=str, help='Path to the original TensorFlow checkpoint (.ckpt file).'
)
parser.add_argument(
'--pytorch_dump_folder_path', required=True, type=str, help='Path to the output PyTorch model directory.'
)
parser.add_argument(
'--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.'
)
__lowerCAmelCase : str = parser.parse_args()
convert_movilevit_checkpoint(
args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub
)
| 76 | 0 |
import math
import random
def a__ ( A_, A_ = False ):
'''simple docstring'''
if deriv:
return value * (1 - value)
return 1 / (1 + math.exp(-value ))
# Initial Value
__lowerCAmelCase : Union[str, Any] = 0.02
def a__ ( A_, A_ ):
'''simple docstring'''
__magic_name__ = float(2 * (random.randint(1, 100 )) - 1 )
for _ in range(A_ ):
# Forward propagation
__magic_name__ = sigmoid_function(INITIAL_VALUE * weight )
# How much did we miss?
__magic_name__ = (expected / 100) - layer_a
# Error delta
__magic_name__ = layer_1_error * sigmoid_function(A_, A_ )
# Update weight
weight += INITIAL_VALUE * layer_1_delta
return layer_a * 100
if __name__ == "__main__":
import doctest
doctest.testmod()
__lowerCAmelCase : List[Any] = int(input('Expected value: '))
__lowerCAmelCase : Tuple = int(input('Number of propagations: '))
print(forward_propagation(expected, number_propagations))
| 708 |
import collections
import importlib.util
import os
import re
from pathlib import Path
__lowerCAmelCase : int = 'src/transformers'
# Matches is_xxx_available()
__lowerCAmelCase : Optional[int] = re.compile(R'is\_([a-z_]*)_available()')
# Catches a one-line _import_struct = {xxx}
__lowerCAmelCase : Dict = re.compile(R'^_import_structure\s+=\s+\{([^\}]+)\}')
# Catches a line with a key-values pattern: "bla": ["foo", "bar"]
__lowerCAmelCase : int = re.compile(R'\s+"\S*":\s+\[([^\]]*)\]')
# Catches a line if not is_foo_available
__lowerCAmelCase : Optional[Any] = re.compile(R'^\s*if\s+not\s+is\_[a-z_]*\_available\(\)')
# Catches a line _import_struct["bla"].append("foo")
__lowerCAmelCase : Optional[Any] = re.compile(R'^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)')
# Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"]
__lowerCAmelCase : Dict = re.compile(R'^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]')
# Catches a line with an object between quotes and a comma: "MyModel",
__lowerCAmelCase : List[str] = re.compile('^\s+"([^"]+)",')
# Catches a line with objects between brackets only: ["foo", "bar"],
__lowerCAmelCase : Optional[int] = re.compile('^\s+\[([^\]]+)\]')
# Catches a line with from foo import bar, bla, boo
__lowerCAmelCase : List[str] = re.compile(R'\s+from\s+\S*\s+import\s+([^\(\s].*)\n')
# Catches a line with try:
__lowerCAmelCase : int = re.compile(R'^\s*try:')
# Catches a line with else:
__lowerCAmelCase : Tuple = re.compile(R'^\s*else:')
def a__ ( A_ ):
'''simple docstring'''
if _re_test_backend.search(A_ ) is None:
return None
__magic_name__ = [b[0] for b in _re_backend.findall(A_ )]
backends.sort()
return "_and_".join(A_ )
def a__ ( A_ ):
'''simple docstring'''
with open(A_, """r""", encoding="""utf-8""", newline="""\n""" ) as f:
__magic_name__ = f.readlines()
__magic_name__ = 0
while line_index < len(A_ ) and not lines[line_index].startswith("""_import_structure = {""" ):
line_index += 1
# If this is a traditional init, just return.
if line_index >= len(A_ ):
return None
# First grab the objects without a specific backend in _import_structure
__magic_name__ = []
while not lines[line_index].startswith("""if TYPE_CHECKING""" ) and find_backend(lines[line_index] ) is None:
__magic_name__ = lines[line_index]
# If we have everything on a single line, let's deal with it.
if _re_one_line_import_struct.search(A_ ):
__magic_name__ = _re_one_line_import_struct.search(A_ ).groups()[0]
__magic_name__ = re.findall("""\[([^\]]+)\]""", A_ )
for imp in imports:
objects.extend([obj[1:-1] for obj in imp.split(""", """ )] )
line_index += 1
continue
__magic_name__ = _re_import_struct_key_value.search(A_ )
if single_line_import_search is not None:
__magic_name__ = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(""", """ ) if len(A_ ) > 0]
objects.extend(A_ )
elif line.startswith(""" """ * 8 + """\"""" ):
objects.append(line[9:-3] )
line_index += 1
__magic_name__ = {"""none""": objects}
# Let's continue with backend-specific objects in _import_structure
while not lines[line_index].startswith("""if TYPE_CHECKING""" ):
# If the line is an if not is_backend_available, we grab all objects associated.
__magic_name__ = find_backend(lines[line_index] )
# Check if the backend declaration is inside a try block:
if _re_try.search(lines[line_index - 1] ) is None:
__magic_name__ = None
if backend is not None:
line_index += 1
# Scroll until we hit the else block of try-except-else
while _re_else.search(lines[line_index] ) is None:
line_index += 1
line_index += 1
__magic_name__ = []
# Until we unindent, add backend objects to the list
while len(lines[line_index] ) <= 1 or lines[line_index].startswith(""" """ * 4 ):
__magic_name__ = lines[line_index]
if _re_import_struct_add_one.search(A_ ) is not None:
objects.append(_re_import_struct_add_one.search(A_ ).groups()[0] )
elif _re_import_struct_add_many.search(A_ ) is not None:
__magic_name__ = _re_import_struct_add_many.search(A_ ).groups()[0].split(""", """ )
__magic_name__ = [obj[1:-1] for obj in imports if len(A_ ) > 0]
objects.extend(A_ )
elif _re_between_brackets.search(A_ ) is not None:
__magic_name__ = _re_between_brackets.search(A_ ).groups()[0].split(""", """ )
__magic_name__ = [obj[1:-1] for obj in imports if len(A_ ) > 0]
objects.extend(A_ )
elif _re_quote_object.search(A_ ) is not None:
objects.append(_re_quote_object.search(A_ ).groups()[0] )
elif line.startswith(""" """ * 8 + """\"""" ):
objects.append(line[9:-3] )
elif line.startswith(""" """ * 12 + """\"""" ):
objects.append(line[13:-3] )
line_index += 1
__magic_name__ = objects
else:
line_index += 1
# At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend
__magic_name__ = []
while (
line_index < len(A_ )
and find_backend(lines[line_index] ) is None
and not lines[line_index].startswith("""else""" )
):
__magic_name__ = lines[line_index]
__magic_name__ = _re_import.search(A_ )
if single_line_import_search is not None:
objects.extend(single_line_import_search.groups()[0].split(""", """ ) )
elif line.startswith(""" """ * 8 ):
objects.append(line[8:-2] )
line_index += 1
__magic_name__ = {"""none""": objects}
# Let's continue with backend-specific objects
while line_index < len(A_ ):
# If the line is an if is_backend_available, we grab all objects associated.
__magic_name__ = find_backend(lines[line_index] )
# Check if the backend declaration is inside a try block:
if _re_try.search(lines[line_index - 1] ) is None:
__magic_name__ = None
if backend is not None:
line_index += 1
# Scroll until we hit the else block of try-except-else
while _re_else.search(lines[line_index] ) is None:
line_index += 1
line_index += 1
__magic_name__ = []
# Until we unindent, add backend objects to the list
while len(lines[line_index] ) <= 1 or lines[line_index].startswith(""" """ * 8 ):
__magic_name__ = lines[line_index]
__magic_name__ = _re_import.search(A_ )
if single_line_import_search is not None:
objects.extend(single_line_import_search.groups()[0].split(""", """ ) )
elif line.startswith(""" """ * 12 ):
objects.append(line[12:-2] )
line_index += 1
__magic_name__ = objects
else:
line_index += 1
return import_dict_objects, type_hint_objects
def a__ ( A_, A_ ):
'''simple docstring'''
def find_duplicates(A_ ):
return [k for k, v in collections.Counter(A_ ).items() if v > 1]
if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ):
return ["Both sides of the init do not have the same backends!"]
__magic_name__ = []
for key in import_dict_objects.keys():
__magic_name__ = find_duplicates(import_dict_objects[key] )
if duplicate_imports:
errors.append(f'''Duplicate _import_structure definitions for: {duplicate_imports}''' )
__magic_name__ = find_duplicates(type_hint_objects[key] )
if duplicate_type_hints:
errors.append(f'''Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}''' )
if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ):
__magic_name__ = """base imports""" if key == """none""" else f'''{key} backend'''
errors.append(f'''Differences for {name}:''' )
for a in type_hint_objects[key]:
if a not in import_dict_objects[key]:
errors.append(f''' {a} in TYPE_HINT but not in _import_structure.''' )
for a in import_dict_objects[key]:
if a not in type_hint_objects[key]:
errors.append(f''' {a} in _import_structure but not in TYPE_HINT.''' )
return errors
def a__ ( ):
'''simple docstring'''
__magic_name__ = []
for root, _, files in os.walk(A_ ):
if "__init__.py" in files:
__magic_name__ = os.path.join(A_, """__init__.py""" )
__magic_name__ = parse_init(A_ )
if objects is not None:
__magic_name__ = analyze_results(*A_ )
if len(A_ ) > 0:
__magic_name__ = f'''Problem in {fname}, both halves do not define the same objects.\n{errors[0]}'''
failures.append("""\n""".join(A_ ) )
if len(A_ ) > 0:
raise ValueError("""\n\n""".join(A_ ) )
def a__ ( ):
'''simple docstring'''
__magic_name__ = []
for path, directories, files in os.walk(A_ ):
for folder in directories:
# Ignore private modules
if folder.startswith("""_""" ):
directories.remove(A_ )
continue
# Ignore leftovers from branches (empty folders apart from pycache)
if len(list((Path(A_ ) / folder).glob("""*.py""" ) ) ) == 0:
continue
__magic_name__ = str((Path(A_ ) / folder).relative_to(A_ ) )
__magic_name__ = short_path.replace(os.path.sep, """.""" )
submodules.append(A_ )
for fname in files:
if fname == "__init__.py":
continue
__magic_name__ = str((Path(A_ ) / fname).relative_to(A_ ) )
__magic_name__ = short_path.replace(""".py""", """""" ).replace(os.path.sep, """.""" )
if len(submodule.split(""".""" ) ) == 1:
submodules.append(A_ )
return submodules
__lowerCAmelCase : Dict = [
'convert_pytorch_checkpoint_to_tf2',
'modeling_flax_pytorch_utils',
]
def a__ ( ):
'''simple docstring'''
__magic_name__ = importlib.util.spec_from_file_location(
"""transformers""", os.path.join(A_, """__init__.py""" ), submodule_search_locations=[PATH_TO_TRANSFORMERS], )
__magic_name__ = spec.loader.load_module()
__magic_name__ = [
module
for module in get_transformers_submodules()
if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys()
]
if len(A_ ) > 0:
__magic_name__ = """\n""".join(f'''- {module}''' for module in module_not_registered )
raise ValueError(
"""The following submodules are not properly registered in the main init of Transformers:\n"""
f'''{list_of_modules}\n'''
"""Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.""" )
if __name__ == "__main__":
check_all_inits()
check_submodules()
| 76 | 0 |
import unittest
from diffusers.models.unet_ad_blocks import * # noqa F403
from diffusers.utils import torch_device
from .test_unet_blocks_common import UNetBlockTesterMixin
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = DownBlockaD # noqa F405
a__ = """down"""
def _lowercase ( self : List[str] ) -> Union[str, Any]:
"""simple docstring"""
__magic_name__ = [-0.0232, -0.9869, 0.8054, -0.0637, -0.1688, -1.4264, 0.4470, -1.3394, 0.0904]
super().test_output(UpperCamelCase__ )
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = ResnetDownsampleBlockaD # noqa F405
a__ = """down"""
def _lowercase ( self : Tuple ) -> Union[str, Any]:
"""simple docstring"""
__magic_name__ = [0.0710, 0.2410, -0.7320, -1.0757, -1.1343, 0.3540, -0.0133, -0.2576, 0.0948]
super().test_output(UpperCamelCase__ )
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = AttnDownBlockaD # noqa F405
a__ = """down"""
def _lowercase ( self : Optional[int] ) -> Optional[int]:
"""simple docstring"""
__magic_name__ = [0.0636, 0.8964, -0.6234, -1.0131, 0.0844, 0.4935, 0.3437, 0.0911, -0.2957]
super().test_output(UpperCamelCase__ )
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = CrossAttnDownBlockaD # noqa F405
a__ = """down"""
def _lowercase ( self : List[Any] ) -> Tuple:
"""simple docstring"""
__magic_name__ , __magic_name__ = super().prepare_init_args_and_inputs_for_common()
__magic_name__ = 32
return init_dict, inputs_dict
def _lowercase ( self : List[Any] ) -> Tuple:
"""simple docstring"""
__magic_name__ = [0.2238, -0.7396, -0.2255, -0.3829, 0.1925, 1.1665, 0.0603, -0.7295, 0.1983]
super().test_output(UpperCamelCase__ )
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = SimpleCrossAttnDownBlockaD # noqa F405
a__ = """down"""
@property
def _lowercase ( self : Dict ) -> Any:
"""simple docstring"""
return super().get_dummy_input(include_encoder_hidden_states=UpperCamelCase__ )
def _lowercase ( self : str ) -> Union[str, Any]:
"""simple docstring"""
__magic_name__ , __magic_name__ = super().prepare_init_args_and_inputs_for_common()
__magic_name__ = 32
return init_dict, inputs_dict
@unittest.skipIf(torch_device == """mps""" , """MPS result is not consistent""" )
def _lowercase ( self : Any ) -> List[Any]:
"""simple docstring"""
__magic_name__ = [0.7921, -0.0992, -0.1962, -0.7695, -0.4242, 0.7804, 0.4737, 0.2765, 0.3338]
super().test_output(UpperCamelCase__ )
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = SkipDownBlockaD # noqa F405
a__ = """down"""
@property
def _lowercase ( self : List[Any] ) -> str:
"""simple docstring"""
return super().get_dummy_input(include_skip_sample=UpperCamelCase__ )
def _lowercase ( self : Dict ) -> str:
"""simple docstring"""
__magic_name__ = [-0.0845, -0.2087, -0.2465, 0.0971, 0.1900, -0.0484, 0.2664, 0.4179, 0.5069]
super().test_output(UpperCamelCase__ )
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = AttnSkipDownBlockaD # noqa F405
a__ = """down"""
@property
def _lowercase ( self : Optional[Any] ) -> Optional[Any]:
"""simple docstring"""
return super().get_dummy_input(include_skip_sample=UpperCamelCase__ )
def _lowercase ( self : List[Any] ) -> Optional[int]:
"""simple docstring"""
__magic_name__ = [0.5539, 0.1609, 0.4924, 0.0537, -0.1995, 0.4050, 0.0979, -0.2721, -0.0642]
super().test_output(UpperCamelCase__ )
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = DownEncoderBlockaD # noqa F405
a__ = """down"""
@property
def _lowercase ( self : Any ) -> List[Any]:
"""simple docstring"""
return super().get_dummy_input(include_temb=UpperCamelCase__ )
def _lowercase ( self : Optional[int] ) -> List[str]:
"""simple docstring"""
__magic_name__ = {
"""in_channels""": 32,
"""out_channels""": 32,
}
__magic_name__ = self.dummy_input
return init_dict, inputs_dict
def _lowercase ( self : Optional[Any] ) -> Optional[Any]:
"""simple docstring"""
__magic_name__ = [1.1102, 0.5302, 0.4872, -0.0023, -0.8042, 0.0483, -0.3489, -0.5632, 0.7626]
super().test_output(UpperCamelCase__ )
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = AttnDownEncoderBlockaD # noqa F405
a__ = """down"""
@property
def _lowercase ( self : List[str] ) -> str:
"""simple docstring"""
return super().get_dummy_input(include_temb=UpperCamelCase__ )
def _lowercase ( self : Union[str, Any] ) -> str:
"""simple docstring"""
__magic_name__ = {
"""in_channels""": 32,
"""out_channels""": 32,
}
__magic_name__ = self.dummy_input
return init_dict, inputs_dict
def _lowercase ( self : Optional[Any] ) -> Any:
"""simple docstring"""
__magic_name__ = [0.8966, -0.1486, 0.8568, 0.8141, -0.9046, -0.1342, -0.0972, -0.7417, 0.1538]
super().test_output(UpperCamelCase__ )
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = UNetMidBlockaD # noqa F405
a__ = """mid"""
def _lowercase ( self : Union[str, Any] ) -> Optional[int]:
"""simple docstring"""
__magic_name__ = {
"""in_channels""": 32,
"""temb_channels""": 128,
}
__magic_name__ = self.dummy_input
return init_dict, inputs_dict
def _lowercase ( self : int ) -> Any:
"""simple docstring"""
__magic_name__ = [-0.1062, 1.7248, 0.3494, 1.4569, -0.0910, -1.2421, -0.9984, 0.6736, 1.0028]
super().test_output(UpperCamelCase__ )
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = UNetMidBlockaDCrossAttn # noqa F405
a__ = """mid"""
def _lowercase ( self : Any ) -> Any:
"""simple docstring"""
__magic_name__ , __magic_name__ = super().prepare_init_args_and_inputs_for_common()
__magic_name__ = 32
return init_dict, inputs_dict
def _lowercase ( self : Any ) -> List[str]:
"""simple docstring"""
__magic_name__ = [0.0187, 2.4220, 0.4484, 1.1203, -0.6121, -1.5122, -0.8270, 0.7851, 1.8335]
super().test_output(UpperCamelCase__ )
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = UNetMidBlockaDSimpleCrossAttn # noqa F405
a__ = """mid"""
@property
def _lowercase ( self : List[str] ) -> Tuple:
"""simple docstring"""
return super().get_dummy_input(include_encoder_hidden_states=UpperCamelCase__ )
def _lowercase ( self : Optional[int] ) -> int:
"""simple docstring"""
__magic_name__ , __magic_name__ = super().prepare_init_args_and_inputs_for_common()
__magic_name__ = 32
return init_dict, inputs_dict
def _lowercase ( self : List[str] ) -> Optional[Any]:
"""simple docstring"""
__magic_name__ = [0.7143, 1.9974, 0.5448, 1.3977, 0.1282, -1.1237, -1.4238, 0.5530, 0.8880]
super().test_output(UpperCamelCase__ )
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = UpBlockaD # noqa F405
a__ = """up"""
@property
def _lowercase ( self : int ) -> List[Any]:
"""simple docstring"""
return super().get_dummy_input(include_res_hidden_states_tuple=UpperCamelCase__ )
def _lowercase ( self : Tuple ) -> int:
"""simple docstring"""
__magic_name__ = [-0.2041, -0.4165, -0.3022, 0.0041, -0.6628, -0.7053, 0.1928, -0.0325, 0.0523]
super().test_output(UpperCamelCase__ )
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = ResnetUpsampleBlockaD # noqa F405
a__ = """up"""
@property
def _lowercase ( self : Optional[int] ) -> List[Any]:
"""simple docstring"""
return super().get_dummy_input(include_res_hidden_states_tuple=UpperCamelCase__ )
def _lowercase ( self : str ) -> Optional[int]:
"""simple docstring"""
__magic_name__ = [0.2287, 0.3549, -0.1346, 0.4797, -0.1715, -0.9649, 0.7305, -0.5864, -0.6244]
super().test_output(UpperCamelCase__ )
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = CrossAttnUpBlockaD # noqa F405
a__ = """up"""
@property
def _lowercase ( self : Any ) -> List[Any]:
"""simple docstring"""
return super().get_dummy_input(include_res_hidden_states_tuple=UpperCamelCase__ )
def _lowercase ( self : Dict ) -> Any:
"""simple docstring"""
__magic_name__ , __magic_name__ = super().prepare_init_args_and_inputs_for_common()
__magic_name__ = 32
return init_dict, inputs_dict
def _lowercase ( self : Union[str, Any] ) -> Union[str, Any]:
"""simple docstring"""
__magic_name__ = [-0.1403, -0.3515, -0.0420, -0.1425, 0.3167, 0.5094, -0.2181, 0.5931, 0.5582]
super().test_output(UpperCamelCase__ )
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = SimpleCrossAttnUpBlockaD # noqa F405
a__ = """up"""
@property
def _lowercase ( self : List[str] ) -> Union[str, Any]:
"""simple docstring"""
return super().get_dummy_input(include_res_hidden_states_tuple=UpperCamelCase__ , include_encoder_hidden_states=UpperCamelCase__ )
def _lowercase ( self : Dict ) -> List[Any]:
"""simple docstring"""
__magic_name__ , __magic_name__ = super().prepare_init_args_and_inputs_for_common()
__magic_name__ = 32
return init_dict, inputs_dict
def _lowercase ( self : Union[str, Any] ) -> List[Any]:
"""simple docstring"""
__magic_name__ = [0.2645, 0.1480, 0.0909, 0.8044, -0.9758, -0.9083, 0.0994, -1.1453, -0.7402]
super().test_output(UpperCamelCase__ )
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = AttnUpBlockaD # noqa F405
a__ = """up"""
@property
def _lowercase ( self : Any ) -> Optional[int]:
"""simple docstring"""
return super().get_dummy_input(include_res_hidden_states_tuple=UpperCamelCase__ )
@unittest.skipIf(torch_device == """mps""" , """MPS result is not consistent""" )
def _lowercase ( self : Dict ) -> str:
"""simple docstring"""
__magic_name__ = [0.0979, 0.1326, 0.0021, 0.0659, 0.2249, 0.0059, 0.1132, 0.5952, 0.1033]
super().test_output(UpperCamelCase__ )
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = SkipUpBlockaD # noqa F405
a__ = """up"""
@property
def _lowercase ( self : Dict ) -> List[Any]:
"""simple docstring"""
return super().get_dummy_input(include_res_hidden_states_tuple=UpperCamelCase__ )
def _lowercase ( self : Union[str, Any] ) -> Dict:
"""simple docstring"""
__magic_name__ = [-0.0893, -0.1234, -0.1506, -0.0332, 0.0123, -0.0211, 0.0566, 0.0143, 0.0362]
super().test_output(UpperCamelCase__ )
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = AttnSkipUpBlockaD # noqa F405
a__ = """up"""
@property
def _lowercase ( self : Any ) -> List[Any]:
"""simple docstring"""
return super().get_dummy_input(include_res_hidden_states_tuple=UpperCamelCase__ )
def _lowercase ( self : Optional[int] ) -> Optional[Any]:
"""simple docstring"""
__magic_name__ = [0.0361, 0.0617, 0.2787, -0.0350, 0.0342, 0.3421, -0.0843, 0.0913, 0.3015]
super().test_output(UpperCamelCase__ )
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = UpDecoderBlockaD # noqa F405
a__ = """up"""
@property
def _lowercase ( self : str ) -> List[Any]:
"""simple docstring"""
return super().get_dummy_input(include_temb=UpperCamelCase__ )
def _lowercase ( self : Dict ) -> List[Any]:
"""simple docstring"""
__magic_name__ = {"""in_channels""": 32, """out_channels""": 32}
__magic_name__ = self.dummy_input
return init_dict, inputs_dict
def _lowercase ( self : Optional[int] ) -> Tuple:
"""simple docstring"""
__magic_name__ = [0.4404, 0.1998, -0.9886, -0.3320, -0.3128, -0.7034, -0.6955, -0.2338, -0.3137]
super().test_output(UpperCamelCase__ )
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = AttnUpDecoderBlockaD # noqa F405
a__ = """up"""
@property
def _lowercase ( self : Tuple ) -> Tuple:
"""simple docstring"""
return super().get_dummy_input(include_temb=UpperCamelCase__ )
def _lowercase ( self : Any ) -> Union[str, Any]:
"""simple docstring"""
__magic_name__ = {"""in_channels""": 32, """out_channels""": 32}
__magic_name__ = self.dummy_input
return init_dict, inputs_dict
def _lowercase ( self : Any ) -> List[str]:
"""simple docstring"""
__magic_name__ = [0.6738, 0.4491, 0.1055, 1.0710, 0.7316, 0.3339, 0.3352, 0.1023, 0.3568]
super().test_output(UpperCamelCase__ )
| 709 |
import functools
import operator
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__lowerCAmelCase : Optional[Any] = logging.get_logger(__name__)
__lowerCAmelCase : List[Any] = {
'asapp/sew-d-tiny-100k': 'https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json',
# See all SEW-D models at https://huggingface.co/models?filter=sew-d
}
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = """sew-d"""
def __init__( self : List[str] , UpperCamelCase__ : Tuple=32 , UpperCamelCase__ : Optional[int]=768 , UpperCamelCase__ : Tuple=12 , UpperCamelCase__ : Optional[Any]=12 , UpperCamelCase__ : int=3072 , UpperCamelCase__ : Tuple=2 , UpperCamelCase__ : List[Any]=512 , UpperCamelCase__ : Any=256 , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : Dict=True , UpperCamelCase__ : str=("p2c", "c2p") , UpperCamelCase__ : List[Any]="layer_norm" , UpperCamelCase__ : int="gelu_python" , UpperCamelCase__ : Optional[int]=0.1 , UpperCamelCase__ : Tuple=0.1 , UpperCamelCase__ : List[Any]=0.1 , UpperCamelCase__ : int=0.0 , UpperCamelCase__ : Dict=0.1 , UpperCamelCase__ : List[Any]=0.02 , UpperCamelCase__ : Optional[int]=1E-7 , UpperCamelCase__ : List[Any]=1E-5 , UpperCamelCase__ : List[str]="group" , UpperCamelCase__ : Optional[int]="gelu" , UpperCamelCase__ : Tuple=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , UpperCamelCase__ : str=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , UpperCamelCase__ : Optional[Any]=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , UpperCamelCase__ : Optional[Any]=False , UpperCamelCase__ : Optional[int]=128 , UpperCamelCase__ : Tuple=16 , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : Dict=0.05 , UpperCamelCase__ : str=10 , UpperCamelCase__ : Tuple=2 , UpperCamelCase__ : Dict=0.0 , UpperCamelCase__ : Dict=10 , UpperCamelCase__ : Union[str, Any]=0 , UpperCamelCase__ : List[Any]="mean" , UpperCamelCase__ : int=False , UpperCamelCase__ : Optional[int]=False , UpperCamelCase__ : Optional[int]=256 , UpperCamelCase__ : List[str]=0 , UpperCamelCase__ : Union[str, Any]=1 , UpperCamelCase__ : List[Any]=2 , **UpperCamelCase__ : str , ) -> Dict:
"""simple docstring"""
super().__init__(**UpperCamelCase__ , pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ )
__magic_name__ = hidden_size
__magic_name__ = feat_extract_norm
__magic_name__ = feat_extract_activation
__magic_name__ = list(UpperCamelCase__ )
__magic_name__ = list(UpperCamelCase__ )
__magic_name__ = list(UpperCamelCase__ )
__magic_name__ = conv_bias
__magic_name__ = num_conv_pos_embeddings
__magic_name__ = num_conv_pos_embedding_groups
__magic_name__ = len(self.conv_dim )
__magic_name__ = num_hidden_layers
__magic_name__ = intermediate_size
__magic_name__ = squeeze_factor
__magic_name__ = max_position_embeddings
__magic_name__ = position_buckets
__magic_name__ = share_att_key
__magic_name__ = relative_attention
__magic_name__ = norm_rel_ebd
__magic_name__ = list(UpperCamelCase__ )
__magic_name__ = hidden_act
__magic_name__ = num_attention_heads
__magic_name__ = hidden_dropout
__magic_name__ = attention_dropout
__magic_name__ = activation_dropout
__magic_name__ = feat_proj_dropout
__magic_name__ = final_dropout
__magic_name__ = layer_norm_eps
__magic_name__ = feature_layer_norm_eps
__magic_name__ = initializer_range
__magic_name__ = vocab_size
if (
(len(self.conv_stride ) != self.num_feat_extract_layers)
or (len(self.conv_kernel ) != self.num_feat_extract_layers)
or (len(self.conv_dim ) != self.num_feat_extract_layers)
):
raise ValueError(
"""Configuration for convolutional layers is incorrect."""
"""It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,"""
F'''but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)'''
F'''= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' )
# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
__magic_name__ = apply_spec_augment
__magic_name__ = mask_time_prob
__magic_name__ = mask_time_length
__magic_name__ = mask_time_min_masks
__magic_name__ = mask_feature_prob
__magic_name__ = mask_feature_length
__magic_name__ = mask_feature_min_masks
# ctc loss
__magic_name__ = ctc_loss_reduction
__magic_name__ = ctc_zero_infinity
# sequence classification
__magic_name__ = use_weighted_layer_sum
__magic_name__ = classifier_proj_size
@property
def _lowercase ( self : Union[str, Any] ) -> str:
"""simple docstring"""
return functools.reduce(operator.mul , self.conv_stride , 1 )
| 76 | 0 |
from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels
from .squad import SquadExample, SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features
from .utils import DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor
from .xnli import xnli_output_modes, xnli_processors, xnli_tasks_num_labels
| 710 |
import math
import random
def a__ ( A_, A_ = False ):
'''simple docstring'''
if deriv:
return value * (1 - value)
return 1 / (1 + math.exp(-value ))
# Initial Value
__lowerCAmelCase : Union[str, Any] = 0.02
def a__ ( A_, A_ ):
'''simple docstring'''
__magic_name__ = float(2 * (random.randint(1, 100 )) - 1 )
for _ in range(A_ ):
# Forward propagation
__magic_name__ = sigmoid_function(INITIAL_VALUE * weight )
# How much did we miss?
__magic_name__ = (expected / 100) - layer_a
# Error delta
__magic_name__ = layer_1_error * sigmoid_function(A_, A_ )
# Update weight
weight += INITIAL_VALUE * layer_1_delta
return layer_a * 100
if __name__ == "__main__":
import doctest
doctest.testmod()
__lowerCAmelCase : List[Any] = int(input('Expected value: '))
__lowerCAmelCase : Tuple = int(input('Number of propagations: '))
print(forward_propagation(expected, number_propagations))
| 76 | 0 |
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = 0
for ch in input_str:
__magic_name__ = ord(A_ )
__magic_name__ = pow(2, A_ )
# If we already turned on bit for current character's unicode
if bitmap >> ch_unicode & 1 == 1:
return False
bitmap |= ch_bit_index_on
return True
if __name__ == "__main__":
import doctest
doctest.testmod()
| 711 |
import os
import sys
__lowerCAmelCase : Optional[Any] = os.path.join(os.path.dirname(__file__), 'src')
sys.path.append(SRC_DIR)
from transformers import (
AutoConfig,
AutoModel,
AutoModelForCausalLM,
AutoModelForMaskedLM,
AutoModelForQuestionAnswering,
AutoModelForSequenceClassification,
AutoTokenizer,
add_start_docstrings,
)
__lowerCAmelCase : Union[str, Any] = [
'torch',
'numpy',
'tokenizers',
'filelock',
'requests',
'tqdm',
'regex',
'sentencepiece',
'sacremoses',
'importlib_metadata',
'huggingface_hub',
]
@add_start_docstrings(AutoConfig.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoConfig.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoTokenizer.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoTokenizer.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoModel.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoModel.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoModelForCausalLM.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoModelForCausalLM.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoModelForMaskedLM.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoModelForMaskedLM.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoModelForSequenceClassification.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoModelForSequenceClassification.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoModelForQuestionAnswering.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoModelForQuestionAnswering.from_pretrained(*A_, **A_ )
| 76 | 0 |
'''simple docstring'''
from __future__ import annotations
__lowerCAmelCase : Tuple = [True] * 1000001
__lowerCAmelCase : int = 2
while i * i <= 1000000:
if seive[i]:
for j in range(i * i, 1000001, i):
__lowerCAmelCase : Union[str, Any] = False
i += 1
def a__ ( A_ ):
'''simple docstring'''
return seive[n]
def a__ ( A_ ):
'''simple docstring'''
return any(digit in """02468""" for digit in str(A_ ) )
def a__ ( A_ = 1000000 ):
'''simple docstring'''
__magic_name__ = [2] # result already includes the number 2.
for num in range(3, limit + 1, 2 ):
if is_prime(A_ ) and not contains_an_even_digit(A_ ):
__magic_name__ = str(A_ )
__magic_name__ = [int(str_num[j:] + str_num[:j] ) for j in range(len(A_ ) )]
if all(is_prime(A_ ) for i in list_nums ):
result.append(A_ )
return result
def a__ ( ):
'''simple docstring'''
return len(find_circular_primes() )
if __name__ == "__main__":
print(F'''{len(find_circular_primes()) = }''')
| 712 |
from typing import Dict
from .base import GenericTensor, Pipeline
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
def _lowercase ( self : List[Any] , UpperCamelCase__ : List[Any]=None , UpperCamelCase__ : Union[str, Any]=None , UpperCamelCase__ : Any=None , **UpperCamelCase__ : Dict ) -> str:
"""simple docstring"""
if tokenize_kwargs is None:
__magic_name__ = {}
if truncation is not None:
if "truncation" in tokenize_kwargs:
raise ValueError(
"""truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)""" )
__magic_name__ = truncation
__magic_name__ = tokenize_kwargs
__magic_name__ = {}
if return_tensors is not None:
__magic_name__ = return_tensors
return preprocess_params, {}, postprocess_params
def _lowercase ( self : int , UpperCamelCase__ : int , **UpperCamelCase__ : int ) -> Dict[str, GenericTensor]:
"""simple docstring"""
__magic_name__ = self.framework
__magic_name__ = self.tokenizer(UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ )
return model_inputs
def _lowercase ( self : str , UpperCamelCase__ : Dict ) -> str:
"""simple docstring"""
__magic_name__ = self.model(**UpperCamelCase__ )
return model_outputs
def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str]=False ) -> List[str]:
"""simple docstring"""
if return_tensors:
return model_outputs[0]
if self.framework == "pt":
return model_outputs[0].tolist()
elif self.framework == "tf":
return model_outputs[0].numpy().tolist()
def __call__( self : List[str] , *UpperCamelCase__ : List[Any] , **UpperCamelCase__ : List[Any] ) -> Dict:
"""simple docstring"""
return super().__call__(*UpperCamelCase__ , **UpperCamelCase__ )
| 76 | 0 |
from __future__ import annotations
def a__ ( A_ ):
'''simple docstring'''
if len(A_ ) < 2:
raise ValueError("""Monogons and Digons are not polygons in the Euclidean space""" )
if any(i <= 0 for i in nums ):
raise ValueError("""All values must be greater than 0""" )
__magic_name__ = nums.copy()
copy_nums.sort()
return copy_nums[-1] < sum(copy_nums[:-1] )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 713 |
import argparse
import math
import os
from copy import deepcopy
import torch
from audio_diffusion.models import DiffusionAttnUnetaD
from diffusion import sampling
from torch import nn
from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel
__lowerCAmelCase : str = {
'gwf-440k': {
'url': 'https://model-server.zqevans2.workers.dev/gwf-440k.ckpt',
'sample_rate': 48000,
'sample_size': 65536,
},
'jmann-small-190k': {
'url': 'https://model-server.zqevans2.workers.dev/jmann-small-190k.ckpt',
'sample_rate': 48000,
'sample_size': 65536,
},
'jmann-large-580k': {
'url': 'https://model-server.zqevans2.workers.dev/jmann-large-580k.ckpt',
'sample_rate': 48000,
'sample_size': 131072,
},
'maestro-uncond-150k': {
'url': 'https://model-server.zqevans2.workers.dev/maestro-uncond-150k.ckpt',
'sample_rate': 16000,
'sample_size': 65536,
},
'unlocked-uncond-250k': {
'url': 'https://model-server.zqevans2.workers.dev/unlocked-uncond-250k.ckpt',
'sample_rate': 16000,
'sample_size': 65536,
},
'honk-140k': {
'url': 'https://model-server.zqevans2.workers.dev/honk-140k.ckpt',
'sample_rate': 16000,
'sample_size': 65536,
},
}
def a__ ( A_, A_ ):
'''simple docstring'''
return torch.atana(A_, A_ ) / math.pi * 2
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = torch.sin(t * math.pi / 2 ) ** 2
__magic_name__ = (1 - sigma**2) ** 0.5
return alpha_sigma_to_t(A_, A_ )
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
pass
class UpperCAmelCase_ ( nn.Module ):
'''simple docstring'''
def __init__( self : Tuple , UpperCamelCase__ : str ) -> Optional[Any]:
"""simple docstring"""
super().__init__()
__magic_name__ = DiffusionAttnUnetaD(UpperCamelCase__ , n_attn_layers=4 )
__magic_name__ = deepcopy(self.diffusion )
__magic_name__ = torch.quasirandom.SobolEngine(1 , scramble=UpperCamelCase__ )
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = MODELS_MAP[model_name]["""url"""]
os.system(f'''wget {url} ./''' )
return f'''./{model_name}.ckpt'''
__lowerCAmelCase : Optional[int] = {
'1': 'resnets.0',
'2': 'attentions.0',
'3': 'resnets.1',
'4': 'attentions.1',
'5': 'resnets.2',
'6': 'attentions.2',
}
__lowerCAmelCase : Optional[Any] = {
'8': 'resnets.0',
'9': 'attentions.0',
'10': 'resnets.1',
'11': 'attentions.1',
'12': 'resnets.2',
'13': 'attentions.2',
}
__lowerCAmelCase : Union[str, Any] = {
'1': 'resnets.0',
'2': 'attentions.0',
'3': 'resnets.1',
'4': 'attentions.1',
'5': 'resnets.2',
'6': 'attentions.2',
'8': 'resnets.3',
'9': 'attentions.3',
'10': 'resnets.4',
'11': 'attentions.4',
'12': 'resnets.5',
'13': 'attentions.5',
}
__lowerCAmelCase : int = {
'0': 'resnets.0',
'1': 'resnets.1',
'2': 'resnets.2',
'4': 'resnets.0',
'5': 'resnets.1',
'6': 'resnets.2',
}
__lowerCAmelCase : List[str] = {
'skip': 'conv_skip',
'main.0': 'conv_1',
'main.1': 'group_norm_1',
'main.3': 'conv_2',
'main.4': 'group_norm_2',
}
__lowerCAmelCase : int = {
'norm': 'group_norm',
'qkv_proj': ['query', 'key', 'value'],
'out_proj': ['proj_attn'],
}
def a__ ( A_ ):
'''simple docstring'''
if name.startswith("""skip""" ):
return name.replace("""skip""", RES_CONV_MAP["""skip"""] )
# name has to be of format main.{digit}
if not name.startswith("""main.""" ):
raise ValueError(f'''ResConvBlock error with {name}''' )
return name.replace(name[:6], RES_CONV_MAP[name[:6]] )
def a__ ( A_ ):
'''simple docstring'''
for key, value in ATTN_MAP.items():
if name.startswith(A_ ) and not isinstance(A_, A_ ):
return name.replace(A_, A_ )
elif name.startswith(A_ ):
return [name.replace(A_, A_ ) for v in value]
raise ValueError(f'''Attn error with {name}''' )
def a__ ( A_, A_=13 ):
'''simple docstring'''
__magic_name__ = input_string
if string.split(""".""" )[0] == "timestep_embed":
return string.replace("""timestep_embed""", """time_proj""" )
__magic_name__ = 0
if string.startswith("""net.3.""" ):
depth += 1
__magic_name__ = string[6:]
elif string.startswith("""net.""" ):
__magic_name__ = string[4:]
while string.startswith("""main.7.""" ):
depth += 1
__magic_name__ = string[7:]
if string.startswith("""main.""" ):
__magic_name__ = string[5:]
# mid block
if string[:2].isdigit():
__magic_name__ = string[:2]
__magic_name__ = string[2:]
else:
__magic_name__ = string[0]
__magic_name__ = string[1:]
if depth == max_depth:
__magic_name__ = MID_NUM_TO_LAYER[layer_num]
__magic_name__ = """mid_block"""
elif depth > 0 and int(A_ ) < 7:
__magic_name__ = DOWN_NUM_TO_LAYER[layer_num]
__magic_name__ = f'''down_blocks.{depth}'''
elif depth > 0 and int(A_ ) > 7:
__magic_name__ = UP_NUM_TO_LAYER[layer_num]
__magic_name__ = f'''up_blocks.{max_depth - depth - 1}'''
elif depth == 0:
__magic_name__ = DEPTH_0_TO_LAYER[layer_num]
__magic_name__ = f'''up_blocks.{max_depth - 1}''' if int(A_ ) > 3 else """down_blocks.0"""
if not string_left.startswith(""".""" ):
raise ValueError(f'''Naming error with {input_string} and string_left: {string_left}.''' )
__magic_name__ = string_left[1:]
if "resnets" in new_layer:
__magic_name__ = convert_resconv_naming(A_ )
elif "attentions" in new_layer:
__magic_name__ = convert_attn_naming(A_ )
__magic_name__ = new_string_left
if not isinstance(A_, A_ ):
__magic_name__ = prefix + """.""" + new_layer + """.""" + string_left
else:
__magic_name__ = [prefix + """.""" + new_layer + """.""" + s for s in string_left]
return new_string
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = {}
for k, v in state_dict.items():
if k.endswith("""kernel""" ):
# up- and downsample layers, don't have trainable weights
continue
__magic_name__ = rename(A_ )
# check if we need to transform from Conv => Linear for attention
if isinstance(A_, A_ ):
__magic_name__ = transform_conv_attns(A_, A_, A_ )
else:
__magic_name__ = v
return new_state_dict
def a__ ( A_, A_, A_ ):
'''simple docstring'''
if len(A_ ) == 1:
if len(v.shape ) == 3:
# weight
__magic_name__ = v[:, :, 0]
else:
# bias
__magic_name__ = v
else:
# qkv matrices
__magic_name__ = v.shape[0]
__magic_name__ = trippled_shape // 3
for i in range(3 ):
if len(v.shape ) == 3:
__magic_name__ = v[i * single_shape : (i + 1) * single_shape, :, 0]
else:
__magic_name__ = v[i * single_shape : (i + 1) * single_shape]
return new_state_dict
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" )
__magic_name__ = args.model_path.split("""/""" )[-1].split(""".""" )[0]
if not os.path.isfile(args.model_path ):
assert (
model_name == args.model_path
), f'''Make sure to provide one of the official model names {MODELS_MAP.keys()}'''
__magic_name__ = download(A_ )
__magic_name__ = MODELS_MAP[model_name]["""sample_rate"""]
__magic_name__ = MODELS_MAP[model_name]["""sample_size"""]
__magic_name__ = Object()
__magic_name__ = sample_size
__magic_name__ = sample_rate
__magic_name__ = 0
__magic_name__ = UNetaDModel(sample_size=A_, sample_rate=A_ )
__magic_name__ = diffusers_model.state_dict()
__magic_name__ = DiffusionUncond(A_ )
orig_model.load_state_dict(torch.load(args.model_path, map_location=A_ )["""state_dict"""] )
__magic_name__ = orig_model.diffusion_ema.eval()
__magic_name__ = orig_model.state_dict()
__magic_name__ = rename_orig_weights(A_ )
__magic_name__ = set(renamed_state_dict.keys() ) - set(diffusers_state_dict.keys() )
__magic_name__ = set(diffusers_state_dict.keys() ) - set(renamed_state_dict.keys() )
assert len(A_ ) == 0, f'''Problem with {renamed_minus_diffusers}'''
assert all(k.endswith("""kernel""" ) for k in list(A_ ) ), f'''Problem with {diffusers_minus_renamed}'''
for key, value in renamed_state_dict.items():
assert (
diffusers_state_dict[key].squeeze().shape == value.squeeze().shape
), f'''Shape for {key} doesn\'t match. Diffusers: {diffusers_state_dict[key].shape} vs. {value.shape}'''
if key == "time_proj.weight":
__magic_name__ = value.squeeze()
__magic_name__ = value
diffusers_model.load_state_dict(A_ )
__magic_name__ = 100
__magic_name__ = 33
__magic_name__ = IPNDMScheduler(num_train_timesteps=A_ )
__magic_name__ = torch.manual_seed(A_ )
__magic_name__ = torch.randn([1, 2, config.sample_size], generator=A_ ).to(A_ )
__magic_name__ = torch.linspace(1, 0, steps + 1, device=A_ )[:-1]
__magic_name__ = get_crash_schedule(A_ )
__magic_name__ = DanceDiffusionPipeline(unet=A_, scheduler=A_ )
__magic_name__ = torch.manual_seed(33 )
__magic_name__ = pipe(num_inference_steps=A_, generator=A_ ).audios
__magic_name__ = sampling.iplms_sample(A_, A_, A_, {} )
__magic_name__ = generated.clamp(-1, 1 )
__magic_name__ = (generated - audio).abs().sum()
__magic_name__ = (generated - audio).abs().max()
if args.save:
pipe.save_pretrained(args.checkpoint_path )
print("""Diff sum""", A_ )
print("""Diff max""", A_ )
assert diff_max < 1e-3, f'''Diff max: {diff_max} is too much :-/'''
print(f'''Conversion for {model_name} successful!''' )
if __name__ == "__main__":
__lowerCAmelCase : Optional[int] = argparse.ArgumentParser()
parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.')
parser.add_argument(
'--save', default=True, type=bool, required=False, help='Whether to save the converted model or not.'
)
parser.add_argument('--checkpoint_path', default=None, type=str, required=True, help='Path to the output model.')
__lowerCAmelCase : Union[str, Any] = parser.parse_args()
main(args)
| 76 | 0 |
import unittest
import numpy as np
from transformers.testing_utils import is_flaky, require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import DonutImageProcessor
class UpperCAmelCase_ ( unittest.TestCase ):
'''simple docstring'''
def __init__( self : List[str] , UpperCamelCase__ : Tuple , UpperCamelCase__ : int=7 , UpperCamelCase__ : int=3 , UpperCamelCase__ : Tuple=18 , UpperCamelCase__ : str=30 , UpperCamelCase__ : List[str]=400 , UpperCamelCase__ : Optional[Any]=True , UpperCamelCase__ : Optional[int]=None , UpperCamelCase__ : str=True , UpperCamelCase__ : Union[str, Any]=False , UpperCamelCase__ : List[str]=True , UpperCamelCase__ : Any=True , UpperCamelCase__ : List[str]=[0.5, 0.5, 0.5] , UpperCamelCase__ : List[str]=[0.5, 0.5, 0.5] , ) -> List[Any]:
"""simple docstring"""
__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 if size is not None else {"""height""": 18, """width""": 20}
__magic_name__ = do_thumbnail
__magic_name__ = do_align_axis
__magic_name__ = do_pad
__magic_name__ = do_normalize
__magic_name__ = image_mean
__magic_name__ = image_std
def _lowercase ( self : Union[str, Any] ) -> Tuple:
"""simple docstring"""
return {
"do_resize": self.do_resize,
"size": self.size,
"do_thumbnail": self.do_thumbnail,
"do_align_long_axis": self.do_align_axis,
"do_pad": self.do_pad,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
}
@require_torch
@require_vision
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = DonutImageProcessor if is_vision_available() else None
def _lowercase ( self : Optional[Any] ) -> Optional[int]:
"""simple docstring"""
__magic_name__ = DonutImageProcessingTester(self )
@property
def _lowercase ( self : Dict ) -> List[str]:
"""simple docstring"""
return self.image_processor_tester.prepare_image_processor_dict()
def _lowercase ( self : List[str] ) -> List[str]:
"""simple docstring"""
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(UpperCamelCase__ , """do_resize""" ) )
self.assertTrue(hasattr(UpperCamelCase__ , """size""" ) )
self.assertTrue(hasattr(UpperCamelCase__ , """do_thumbnail""" ) )
self.assertTrue(hasattr(UpperCamelCase__ , """do_align_long_axis""" ) )
self.assertTrue(hasattr(UpperCamelCase__ , """do_pad""" ) )
self.assertTrue(hasattr(UpperCamelCase__ , """do_normalize""" ) )
self.assertTrue(hasattr(UpperCamelCase__ , """image_mean""" ) )
self.assertTrue(hasattr(UpperCamelCase__ , """image_std""" ) )
def _lowercase ( self : Optional[int] ) -> Any:
"""simple docstring"""
__magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {"""height""": 18, """width""": 20} )
__magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 )
self.assertEqual(image_processor.size , {"""height""": 42, """width""": 42} )
# Previous config had dimensions in (width, height) order
__magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict , size=(42, 84) )
self.assertEqual(image_processor.size , {"""height""": 84, """width""": 42} )
def _lowercase ( self : List[Any] ) -> Tuple:
"""simple docstring"""
pass
@is_flaky()
def _lowercase ( self : Union[str, Any] ) -> Optional[int]:
"""simple docstring"""
__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=UpperCamelCase__ )
for image in image_inputs:
self.assertIsInstance(UpperCamelCase__ , 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(UpperCamelCase__ , return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["""height"""],
self.image_processor_tester.size["""width"""],
) , )
@is_flaky()
def _lowercase ( self : str ) -> List[Any]:
"""simple docstring"""
__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=UpperCamelCase__ , numpify=UpperCamelCase__ )
for image in image_inputs:
self.assertIsInstance(UpperCamelCase__ , 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(UpperCamelCase__ , return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["""height"""],
self.image_processor_tester.size["""width"""],
) , )
@is_flaky()
def _lowercase ( self : Optional[int] ) -> str:
"""simple docstring"""
__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=UpperCamelCase__ , torchify=UpperCamelCase__ )
for image in image_inputs:
self.assertIsInstance(UpperCamelCase__ , 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(UpperCamelCase__ , return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.size["""height"""],
self.image_processor_tester.size["""width"""],
) , )
| 714 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__lowerCAmelCase : Tuple = logging.get_logger(__name__)
__lowerCAmelCase : Tuple = {
'SCUT-DLVCLab/lilt-roberta-en-base': (
'https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json'
),
}
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = """lilt"""
def __init__( self : Dict , UpperCamelCase__ : List[str]=3_0522 , UpperCamelCase__ : Optional[Any]=768 , UpperCamelCase__ : Dict=12 , UpperCamelCase__ : Optional[Any]=12 , UpperCamelCase__ : Dict=3072 , UpperCamelCase__ : Tuple="gelu" , UpperCamelCase__ : int=0.1 , UpperCamelCase__ : Dict=0.1 , UpperCamelCase__ : Union[str, Any]=512 , UpperCamelCase__ : Dict=2 , UpperCamelCase__ : Dict=0.02 , UpperCamelCase__ : Any=1E-12 , UpperCamelCase__ : Optional[int]=0 , UpperCamelCase__ : str="absolute" , UpperCamelCase__ : Any=None , UpperCamelCase__ : Dict=4 , UpperCamelCase__ : Tuple=1024 , **UpperCamelCase__ : Optional[int] , ) -> Dict:
"""simple docstring"""
super().__init__(pad_token_id=UpperCamelCase__ , **UpperCamelCase__ )
__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__ = classifier_dropout
__magic_name__ = channel_shrink_ratio
__magic_name__ = max_ad_position_embeddings
| 76 | 0 |
__lowerCAmelCase : Union[str, Any] = '\n# Installazione di Transformers\n! pip install transformers datasets\n# Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e\n# rimuovi la modalità commento al comando seguente.\n# ! pip install git+https://github.com/huggingface/transformers.git\n'
__lowerCAmelCase : Dict = [{'type': 'code', 'content': INSTALL_CONTENT}]
__lowerCAmelCase : Optional[Any] = {
'{processor_class}': 'FakeProcessorClass',
'{model_class}': 'FakeModelClass',
'{object_class}': 'FakeObjectClass',
}
| 715 |
import json
import os
import tempfile
from transformers.testing_utils import check_json_file_has_correct_format
class UpperCAmelCase_ :
'''simple docstring'''
a__ = None
def _lowercase ( self : Optional[int] ) -> str:
"""simple docstring"""
__magic_name__ = self.feature_extraction_class(**self.feat_extract_dict )
__magic_name__ = json.loads(feat_extract.to_json_string() )
for key, value in self.feat_extract_dict.items():
self.assertEqual(obj[key] , UpperCamelCase__ )
def _lowercase ( self : Union[str, Any] ) -> str:
"""simple docstring"""
__magic_name__ = self.feature_extraction_class(**self.feat_extract_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
__magic_name__ = os.path.join(UpperCamelCase__ , """feat_extract.json""" )
feat_extract_first.to_json_file(UpperCamelCase__ )
__magic_name__ = self.feature_extraction_class.from_json_file(UpperCamelCase__ )
self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() )
def _lowercase ( self : str ) -> str:
"""simple docstring"""
__magic_name__ = self.feature_extraction_class(**self.feat_extract_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
__magic_name__ = feat_extract_first.save_pretrained(UpperCamelCase__ )[0]
check_json_file_has_correct_format(UpperCamelCase__ )
__magic_name__ = self.feature_extraction_class.from_pretrained(UpperCamelCase__ )
self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() )
def _lowercase ( self : Optional[int] ) -> Tuple:
"""simple docstring"""
__magic_name__ = self.feature_extraction_class()
self.assertIsNotNone(UpperCamelCase__ )
| 76 | 0 |
import math
def a__ ( A_ = 100 ):
'''simple docstring'''
__magic_name__ = sum(i * i for i in range(1, n + 1 ) )
__magic_name__ = int(math.pow(sum(range(1, n + 1 ) ), 2 ) )
return square_of_sum - sum_of_squares
if __name__ == "__main__":
print(F'''{solution() = }''')
| 716 |
from ..utils import DummyObject, requires_backends
class UpperCAmelCase_ ( metaclass=_A ):
'''simple docstring'''
a__ = ["""note_seq"""]
def __init__( self : Any , *UpperCamelCase__ : str , **UpperCamelCase__ : List[Any] ) -> Optional[int]:
"""simple docstring"""
requires_backends(self , ["""note_seq"""] )
@classmethod
def _lowercase ( cls : str , *UpperCamelCase__ : Dict , **UpperCamelCase__ : Tuple ) -> Dict:
"""simple docstring"""
requires_backends(cls , ["""note_seq"""] )
@classmethod
def _lowercase ( cls : List[str] , *UpperCamelCase__ : Optional[Any] , **UpperCamelCase__ : Tuple ) -> int:
"""simple docstring"""
requires_backends(cls , ["""note_seq"""] )
| 76 | 0 |
import json
import os
from typing import Optional, Tuple
import regex as re
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
__lowerCAmelCase : Optional[int] = logging.get_logger(__name__)
__lowerCAmelCase : List[str] = {
'vocab_file': 'vocab.json',
'merges_file': 'merges.txt',
}
__lowerCAmelCase : Dict = {
'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'},
}
__lowerCAmelCase : Tuple = {
'ctrl': 256,
}
__lowerCAmelCase : Any = {
'Pregnancy': 168629,
'Christianity': 7675,
'Explain': 106423,
'Fitness': 63440,
'Saving': 63163,
'Ask': 27171,
'Ass': 95985,
'Joke': 163509,
'Questions': 45622,
'Thoughts': 49605,
'Retail': 52342,
'Feminism': 164338,
'Writing': 11992,
'Atheism': 192263,
'Netflix': 48616,
'Computing': 39639,
'Opinion': 43213,
'Alone': 44967,
'Funny': 58917,
'Gaming': 40358,
'Human': 4088,
'India': 1331,
'Joker': 77138,
'Diet': 36206,
'Legal': 11859,
'Norman': 4939,
'Tip': 72689,
'Weight': 52343,
'Movies': 46273,
'Running': 23425,
'Science': 2090,
'Horror': 37793,
'Confession': 60572,
'Finance': 12250,
'Politics': 16360,
'Scary': 191985,
'Support': 12654,
'Technologies': 32516,
'Teenage': 66160,
'Event': 32769,
'Learned': 67460,
'Notion': 182770,
'Wikipedia': 37583,
'Books': 6665,
'Extract': 76050,
'Confessions': 102701,
'Conspiracy': 75932,
'Links': 63674,
'Narcissus': 150425,
'Relationship': 54766,
'Relationships': 134796,
'Reviews': 41671,
'News': 4256,
'Translation': 26820,
'multilingual': 128406,
}
def a__ ( A_ ) -> Tuple:
'''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(A_ )
return pairs
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = VOCAB_FILES_NAMES
a__ = PRETRAINED_VOCAB_FILES_MAP
a__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
a__ = CONTROL_CODES
def __init__( self : int , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Any="<unk>" , **UpperCamelCase__ : Dict ) -> List[Any]:
"""simple docstring"""
super().__init__(unk_token=UpperCamelCase__ , **UpperCamelCase__ )
with open(UpperCamelCase__ , encoding="""utf-8""" ) as vocab_handle:
__magic_name__ = json.load(UpperCamelCase__ )
__magic_name__ = {v: k for k, v in self.encoder.items()}
with open(UpperCamelCase__ , 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(UpperCamelCase__ , range(len(UpperCamelCase__ ) ) ) )
__magic_name__ = {}
@property
def _lowercase ( self : Optional[int] ) -> int:
"""simple docstring"""
return len(self.encoder )
def _lowercase ( self : Tuple ) -> Optional[int]:
"""simple docstring"""
return dict(self.encoder , **self.added_tokens_encoder )
def _lowercase ( self : str , UpperCamelCase__ : List[Any] ) -> Any:
"""simple docstring"""
if token in self.cache:
return self.cache[token]
__magic_name__ = tuple(UpperCamelCase__ )
__magic_name__ = tuple(list(word[:-1] ) + [word[-1] + """</w>"""] )
__magic_name__ = get_pairs(UpperCamelCase__ )
if not pairs:
return token
while True:
__magic_name__ = min(UpperCamelCase__ , key=lambda UpperCamelCase__ : self.bpe_ranks.get(UpperCamelCase__ , float("""inf""" ) ) )
if bigram not in self.bpe_ranks:
break
__magic_name__ , __magic_name__ = bigram
__magic_name__ = []
__magic_name__ = 0
while i < len(UpperCamelCase__ ):
try:
__magic_name__ = word.index(UpperCamelCase__ , UpperCamelCase__ )
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(UpperCamelCase__ ) - 1 and word[i + 1] == second:
new_word.append(first + second )
i += 2
else:
new_word.append(word[i] )
i += 1
__magic_name__ = tuple(UpperCamelCase__ )
__magic_name__ = new_word
if len(UpperCamelCase__ ) == 1:
break
else:
__magic_name__ = get_pairs(UpperCamelCase__ )
__magic_name__ = """@@ """.join(UpperCamelCase__ )
__magic_name__ = word[:-4]
__magic_name__ = word
return word
def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : Tuple ) -> Any:
"""simple docstring"""
__magic_name__ = []
__magic_name__ = re.findall(R"""\S+\n?""" , UpperCamelCase__ )
for token in words:
split_tokens.extend(list(self.bpe(UpperCamelCase__ ).split(""" """ ) ) )
return split_tokens
def _lowercase ( self : int , UpperCamelCase__ : str ) -> Dict:
"""simple docstring"""
return self.encoder.get(UpperCamelCase__ , self.encoder.get(self.unk_token ) )
def _lowercase ( self : Optional[int] , UpperCamelCase__ : List[Any] ) -> Optional[Any]:
"""simple docstring"""
return self.decoder.get(UpperCamelCase__ , self.unk_token )
def _lowercase ( self : Optional[Any] , UpperCamelCase__ : Tuple ) -> Dict:
"""simple docstring"""
__magic_name__ = """ """.join(UpperCamelCase__ ).replace("""@@ """ , """""" ).strip()
return out_string
def _lowercase ( self : Optional[int] , UpperCamelCase__ : str , UpperCamelCase__ : Optional[str] = None ) -> Tuple[str]:
"""simple docstring"""
if not os.path.isdir(UpperCamelCase__ ):
logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' )
return
__magic_name__ = os.path.join(
UpperCamelCase__ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] )
__magic_name__ = os.path.join(
UpperCamelCase__ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""] )
with open(UpperCamelCase__ , """w""" , encoding="""utf-8""" ) as f:
f.write(json.dumps(self.encoder , indent=2 , sort_keys=UpperCamelCase__ , ensure_ascii=UpperCamelCase__ ) + """\n""" )
__magic_name__ = 0
with open(UpperCamelCase__ , """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 UpperCamelCase__ : 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(UpperCamelCase__ ) + """\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)
| 717 |
def a__ ( A_ ):
'''simple docstring'''
return " ".join(
"""""".join(word[::-1] ) if len(A_ ) > 4 else word for word in sentence.split() )
if __name__ == "__main__":
import doctest
doctest.testmod()
print(reverse_long_words('Hey wollef sroirraw'))
| 76 | 0 |
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor
from .base import PipelineTool
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = """openai/whisper-base"""
a__ = (
"""This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the """
"""transcribed text."""
)
a__ = """transcriber"""
a__ = WhisperProcessor
a__ = WhisperForConditionalGeneration
a__ = ["""audio"""]
a__ = ["""text"""]
def _lowercase ( self : int , UpperCamelCase__ : Optional[int] ) -> Any:
"""simple docstring"""
return self.pre_processor(UpperCamelCase__ , return_tensors="""pt""" ).input_features
def _lowercase ( self : Dict , UpperCamelCase__ : int ) -> Union[str, Any]:
"""simple docstring"""
return self.model.generate(inputs=UpperCamelCase__ )
def _lowercase ( self : List[str] , UpperCamelCase__ : Union[str, Any] ) -> Optional[int]:
"""simple docstring"""
return self.pre_processor.batch_decode(UpperCamelCase__ , skip_special_tokens=UpperCamelCase__ )[0]
| 718 |
import os
import unittest
from transformers import FunnelTokenizer, FunnelTokenizerFast
from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = FunnelTokenizer
a__ = FunnelTokenizerFast
a__ = True
a__ = True
def _lowercase ( self : List[Any] ) -> str:
"""simple docstring"""
super().setUp()
__magic_name__ = [
"""<unk>""",
"""<cls>""",
"""<sep>""",
"""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] ) )
def _lowercase ( self : Dict , **UpperCamelCase__ : Tuple ) -> Union[str, Any]:
"""simple docstring"""
return FunnelTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase__ )
def _lowercase ( self : str , **UpperCamelCase__ : str ) -> List[str]:
"""simple docstring"""
return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **UpperCamelCase__ )
def _lowercase ( self : List[str] , UpperCamelCase__ : str ) -> List[Any]:
"""simple docstring"""
__magic_name__ = """UNwant\u00E9d,running"""
__magic_name__ = """unwanted, running"""
return input_text, output_text
def _lowercase ( self : Union[str, Any] ) -> Tuple:
"""simple docstring"""
__magic_name__ = self.tokenizer_class(self.vocab_file )
__magic_name__ = tokenizer.tokenize("""UNwant\u00E9d,running""" )
self.assertListEqual(UpperCamelCase__ , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) , [7, 4, 5, 10, 8, 9] )
def _lowercase ( self : str ) -> List[Any]:
"""simple docstring"""
__magic_name__ = self.get_tokenizers(do_lower_case=UpperCamelCase__ )
for tokenizer in tokenizers:
__magic_name__ = tokenizer("""UNwant\u00E9d,running""" )
__magic_name__ = len(inputs["""input_ids"""] ) - 1
self.assertListEqual(inputs["""token_type_ids"""] , [2] + [0] * sentence_len )
__magic_name__ = tokenizer("""UNwant\u00E9d,running""" , """UNwant\u00E9d,running""" )
self.assertListEqual(inputs["""token_type_ids"""] , [2] + [0] * sentence_len + [1] * sentence_len )
| 76 | 0 |
#
# This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or
# many nodes) can talk to each other via nccl and allocate gpu memory.
#
# To run first adjust the number of processes and nodes:
#
# python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
#
# You may need to add --master_addr $MASTER_ADDR --master_port $MASTER_PORT if using a custom addr:port
#
# You can also use the rdzv API: --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_backend c10d
#
# use torch.distributed.launch instead of torch.distributed.run for torch < 1.9
#
# If you get a hanging in `barrier` calls you have some network issues, you may try to debug this with:
#
# NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
#
# which should tell you what's going on behind the scenes.
#
#
# This script can be run via `srun` in the SLURM environment as well. Here is a SLURM script that
# runs on 2 nodes of 4 gpus per node:
#
# #SBATCH --job-name=test-nodes # name
# #SBATCH --nodes=2 # nodes
# #SBATCH --ntasks-per-node=1 # crucial - only 1 task per dist per node!
# #SBATCH --cpus-per-task=10 # number of cores per tasks
# #SBATCH --gres=gpu:4 # number of gpus
# #SBATCH --time 0:05:00 # maximum execution time (HH:MM:SS)
# #SBATCH --output=%x-%j.out # output file name
#
# GPUS_PER_NODE=4
# MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1)
# MASTER_PORT=6000
#
# srun --jobid $SLURM_JOBID bash -c 'python -m torch.distributed.run \
# --nproc_per_node $GPUS_PER_NODE --nnodes $SLURM_NNODES --node_rank $SLURM_PROCID \
# --master_addr $MASTER_ADDR --master_port $MASTER_PORT \
# torch-distributed-gpu-test.py'
#
import fcntl
import os
import socket
import torch
import torch.distributed as dist
def a__ ( *A_ ):
'''simple docstring'''
with open(A_, """r""" ) as fh:
fcntl.flock(A_, fcntl.LOCK_EX )
try:
print(*A_ )
finally:
fcntl.flock(A_, fcntl.LOCK_UN )
__lowerCAmelCase : Tuple = int(os.environ['LOCAL_RANK'])
torch.cuda.set_device(local_rank)
__lowerCAmelCase : str = torch.device('cuda', local_rank)
__lowerCAmelCase : int = socket.gethostname()
__lowerCAmelCase : Union[str, Any] = F'''[{hostname}-{local_rank}]'''
try:
# test distributed
dist.init_process_group('nccl')
dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM)
dist.barrier()
# test cuda is available and can allocate memory
torch.cuda.is_available()
torch.ones(1).cuda(local_rank)
# global rank
__lowerCAmelCase : Optional[Any] = dist.get_rank()
__lowerCAmelCase : Union[str, Any] = dist.get_world_size()
printflock(F'''{gpu} is OK (global rank: {rank}/{world_size})''')
dist.barrier()
if rank == 0:
printflock(F'''pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}''')
except Exception:
printflock(F'''{gpu} is broken''')
raise
| 719 |
from collections import deque
from .hash_table import HashTable
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
def __init__( self : int , *UpperCamelCase__ : Union[str, Any] , **UpperCamelCase__ : Optional[Any] ) -> Optional[Any]:
"""simple docstring"""
super().__init__(*UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : Optional[Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Any ) -> Dict:
"""simple docstring"""
__magic_name__ = deque([] ) if self.values[key] is None else self.values[key]
self.values[key].appendleft(UpperCamelCase__ )
__magic_name__ = self.values[key]
def _lowercase ( self : List[str] ) -> int:
"""simple docstring"""
return (
sum(self.charge_factor - len(UpperCamelCase__ ) for slot in self.values )
/ self.size_table
* self.charge_factor
)
def _lowercase ( self : Optional[Any] , UpperCamelCase__ : str , UpperCamelCase__ : Tuple=None ) -> str:
"""simple docstring"""
if not (
len(self.values[key] ) == self.charge_factor and self.values.count(UpperCamelCase__ ) == 0
):
return key
return super()._collision_resolution(UpperCamelCase__ , UpperCamelCase__ )
| 76 | 0 |
import importlib.metadata
from typing import Union
from packaging.version import Version, parse
from .constants import STR_OPERATION_TO_FUNC
__lowerCAmelCase : Any = parse(importlib.metadata.version('torch'))
def a__ ( A_, A_, A_ ):
'''simple docstring'''
if operation not in STR_OPERATION_TO_FUNC.keys():
raise ValueError(f'''`operation` must be one of {list(STR_OPERATION_TO_FUNC.keys() )}, received {operation}''' )
__magic_name__ = STR_OPERATION_TO_FUNC[operation]
if isinstance(A_, A_ ):
__magic_name__ = parse(importlib.metadata.version(A_ ) )
return operation(A_, parse(A_ ) )
def a__ ( A_, A_ ):
'''simple docstring'''
return compare_versions(A_, A_, A_ )
| 720 |
# 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 json
import os
from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES
from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType
from ...utils.imports import is_botoa_available
from .config_args import SageMakerConfig
from .config_utils import (
DYNAMO_BACKENDS,
_ask_field,
_ask_options,
_convert_dynamo_backend,
_convert_mixed_precision,
_convert_sagemaker_distributed_mode,
_convert_yes_no_to_bool,
)
if is_botoa_available():
import botoa # noqa: F401
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = botoa.client("""iam""" )
__magic_name__ = {
"""Version""": """2012-10-17""",
"""Statement""": [
{"""Effect""": """Allow""", """Principal""": {"""Service""": """sagemaker.amazonaws.com"""}, """Action""": """sts:AssumeRole"""}
],
}
try:
# create the role, associated with the chosen trust policy
iam_client.create_role(
RoleName=A_, AssumeRolePolicyDocument=json.dumps(A_, indent=2 ) )
__magic_name__ = {
"""Version""": """2012-10-17""",
"""Statement""": [
{
"""Effect""": """Allow""",
"""Action""": [
"""sagemaker:*""",
"""ecr:GetDownloadUrlForLayer""",
"""ecr:BatchGetImage""",
"""ecr:BatchCheckLayerAvailability""",
"""ecr:GetAuthorizationToken""",
"""cloudwatch:PutMetricData""",
"""cloudwatch:GetMetricData""",
"""cloudwatch:GetMetricStatistics""",
"""cloudwatch:ListMetrics""",
"""logs:CreateLogGroup""",
"""logs:CreateLogStream""",
"""logs:DescribeLogStreams""",
"""logs:PutLogEvents""",
"""logs:GetLogEvents""",
"""s3:CreateBucket""",
"""s3:ListBucket""",
"""s3:GetBucketLocation""",
"""s3:GetObject""",
"""s3:PutObject""",
],
"""Resource""": """*""",
}
],
}
# attach policy to role
iam_client.put_role_policy(
RoleName=A_, PolicyName=f'''{role_name}_policy_permission''', PolicyDocument=json.dumps(A_, indent=2 ), )
except iam_client.exceptions.EntityAlreadyExistsException:
print(f'''role {role_name} already exists. Using existing one''' )
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = botoa.client("""iam""" )
return iam_client.get_role(RoleName=A_ )["Role"]["Arn"]
def a__ ( ):
'''simple docstring'''
__magic_name__ = _ask_options(
"""How do you want to authorize?""", ["""AWS Profile""", """Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) """], A_, )
__magic_name__ = None
if credentials_configuration == 0:
__magic_name__ = _ask_field("""Enter your AWS Profile name: [default] """, default="""default""" )
__magic_name__ = aws_profile
else:
print(
"""Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,"""
"""`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`""" )
__magic_name__ = _ask_field("""AWS Access Key ID: """ )
__magic_name__ = aws_access_key_id
__magic_name__ = _ask_field("""AWS Secret Access Key: """ )
__magic_name__ = aws_secret_access_key
__magic_name__ = _ask_field("""Enter your AWS Region: [us-east-1]""", default="""us-east-1""" )
__magic_name__ = aws_region
__magic_name__ = _ask_options(
"""Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?""", ["""Provide IAM Role name""", """Create new IAM role using credentials"""], A_, )
if role_management == 0:
__magic_name__ = _ask_field("""Enter your IAM role name: """ )
else:
__magic_name__ = """accelerate_sagemaker_execution_role"""
print(f'''Accelerate will create an iam role "{iam_role_name}" using the provided credentials''' )
_create_iam_role_for_sagemaker(A_ )
__magic_name__ = _ask_field(
"""Do you want to use custom Docker image? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
__magic_name__ = None
if is_custom_docker_image:
__magic_name__ = _ask_field("""Enter your Docker image: """, lambda A_ : str(A_ ).lower() )
__magic_name__ = _ask_field(
"""Do you want to provide SageMaker input channels with data locations? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
__magic_name__ = None
if is_sagemaker_inputs_enabled:
__magic_name__ = _ask_field(
"""Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): """, lambda A_ : str(A_ ).lower(), )
__magic_name__ = _ask_field(
"""Do you want to enable SageMaker metrics? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
__magic_name__ = None
if is_sagemaker_metrics_enabled:
__magic_name__ = _ask_field(
"""Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): """, lambda A_ : str(A_ ).lower(), )
__magic_name__ = _ask_options(
"""What is the distributed mode?""", ["""No distributed training""", """Data parallelism"""], _convert_sagemaker_distributed_mode, )
__magic_name__ = {}
__magic_name__ = _ask_field(
"""Do you wish to optimize your script with torch dynamo?[yes/NO]:""", _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
if use_dynamo:
__magic_name__ = """dynamo_"""
__magic_name__ = _ask_options(
"""Which dynamo backend would you like to use?""", [x.lower() for x in DYNAMO_BACKENDS], _convert_dynamo_backend, default=2, )
__magic_name__ = _ask_field(
"""Do you want to customize the defaults sent to torch.compile? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
if use_custom_options:
__magic_name__ = _ask_options(
"""Which mode do you want to use?""", A_, lambda A_ : TORCH_DYNAMO_MODES[int(A_ )], default="""default""", )
__magic_name__ = _ask_field(
"""Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
__magic_name__ = _ask_field(
"""Do you want to enable dynamic shape tracing? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
__magic_name__ = """Which EC2 instance type you want to use for your training?"""
if distributed_type != SageMakerDistributedType.NO:
__magic_name__ = _ask_options(
A_, A_, lambda A_ : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(A_ )] )
else:
eca_instance_query += "? [ml.p3.2xlarge]:"
__magic_name__ = _ask_field(A_, lambda A_ : str(A_ ).lower(), default="""ml.p3.2xlarge""" )
__magic_name__ = 1
if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL):
__magic_name__ = _ask_field(
"""How many machines do you want use? [1]: """, A_, default=1, )
__magic_name__ = _ask_options(
"""Do you wish to use FP16 or BF16 (mixed precision)?""", ["""no""", """fp16""", """bf16""", """fp8"""], _convert_mixed_precision, )
if use_dynamo and mixed_precision == "no":
print(
"""Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.""" )
return SageMakerConfig(
image_uri=A_, compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER, distributed_type=A_, use_cpu=A_, dynamo_config=A_, eca_instance_type=A_, profile=A_, region=A_, iam_role_name=A_, mixed_precision=A_, num_machines=A_, sagemaker_inputs_file=A_, sagemaker_metrics_file=A_, )
| 76 | 0 |
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] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : int=13 , UpperCamelCase__ : List[str]=7 , UpperCamelCase__ : Optional[Any]=True , UpperCamelCase__ : Tuple=True , UpperCamelCase__ : Dict=True , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : Optional[Any]=99 , UpperCamelCase__ : Optional[int]=32 , UpperCamelCase__ : Optional[int]=5 , UpperCamelCase__ : int=4 , UpperCamelCase__ : List[Any]=37 , UpperCamelCase__ : Dict="gelu" , UpperCamelCase__ : int=0.1 , UpperCamelCase__ : List[str]=0.1 , UpperCamelCase__ : List[Any]=512 , UpperCamelCase__ : List[Any]=16 , UpperCamelCase__ : str=2 , UpperCamelCase__ : int=0.02 , UpperCamelCase__ : Dict=4 , ) -> Dict:
"""simple docstring"""
__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 _lowercase ( self : List[str] ) -> List[str]:
"""simple docstring"""
__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=UpperCamelCase__ , initializer_range=self.initializer_range , )
return config, input_ids, token_type_ids, attention_mask
def _lowercase ( self : Tuple ) -> List[Any]:
"""simple docstring"""
__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'''
a__ = (
(
FlaxAlbertModel,
FlaxAlbertForPreTraining,
FlaxAlbertForMaskedLM,
FlaxAlbertForMultipleChoice,
FlaxAlbertForQuestionAnswering,
FlaxAlbertForSequenceClassification,
FlaxAlbertForTokenClassification,
FlaxAlbertForQuestionAnswering,
)
if is_flax_available()
else ()
)
def _lowercase ( self : Optional[int] ) -> List[Any]:
"""simple docstring"""
__magic_name__ = FlaxAlbertModelTester(self )
@slow
def _lowercase ( self : List[str] ) -> Any:
"""simple docstring"""
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(UpperCamelCase__ )
@require_flax
class UpperCAmelCase_ ( unittest.TestCase ):
'''simple docstring'''
@slow
def _lowercase ( self : Optional[int] ) -> Optional[Any]:
"""simple docstring"""
__magic_name__ = FlaxAlbertModel.from_pretrained("""albert-base-v2""" )
__magic_name__ = np.array([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] )
__magic_name__ = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] )
__magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ )[0]
__magic_name__ = (1, 11, 768)
self.assertEqual(output.shape , UpperCamelCase__ )
__magic_name__ = np.array(
[[[-0.6513, 1.5035, -0.2766], [-0.6515, 1.5046, -0.2780], [-0.6512, 1.5049, -0.2784]]] )
self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] , UpperCamelCase__ , atol=1E-4 ) )
| 721 |
from typing import Dict, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
convert_to_rgb,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
OPENAI_CLIP_MEAN,
OPENAI_CLIP_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
__lowerCAmelCase : Dict = logging.get_logger(__name__)
if is_vision_available():
import PIL
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = ["""pixel_values"""]
def __init__( self : Optional[Any] , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : bool = True , UpperCamelCase__ : Union[int, float] = 1 / 255 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : bool = True , **UpperCamelCase__ : int , ) -> None:
"""simple docstring"""
super().__init__(**UpperCamelCase__ )
__magic_name__ = size if size is not None else {"""shortest_edge""": 224}
__magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ )
__magic_name__ = crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
__magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ , param_name="""crop_size""" )
__magic_name__ = do_resize
__magic_name__ = size
__magic_name__ = resample
__magic_name__ = do_center_crop
__magic_name__ = crop_size
__magic_name__ = do_rescale
__magic_name__ = rescale_factor
__magic_name__ = do_normalize
__magic_name__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
__magic_name__ = image_std if image_std is not None else OPENAI_CLIP_STD
__magic_name__ = do_convert_rgb
def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Tuple , ) -> np.ndarray:
"""simple docstring"""
__magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ )
if "shortest_edge" not in size:
raise ValueError(F'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' )
__magic_name__ = get_resize_output_image_size(UpperCamelCase__ , size=size["""shortest_edge"""] , default_to_square=UpperCamelCase__ )
return resize(UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : Tuple , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Tuple , ) -> np.ndarray:
"""simple docstring"""
__magic_name__ = get_size_dict(UpperCamelCase__ )
if "height" not in size or "width" not in size:
raise ValueError(F'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' )
return center_crop(UpperCamelCase__ , size=(size["""height"""], size["""width"""]) , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : Any , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[int, float] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Optional[Any] , ) -> Optional[int]:
"""simple docstring"""
return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Dict , ) -> np.ndarray:
"""simple docstring"""
return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : List[Any] , UpperCamelCase__ : ImageInput , UpperCamelCase__ : bool = None , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : int = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : float = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , UpperCamelCase__ : Optional[ChannelDimension] = ChannelDimension.FIRST , **UpperCamelCase__ : Dict , ) -> PIL.Image.Image:
"""simple docstring"""
__magic_name__ = do_resize if do_resize is not None else self.do_resize
__magic_name__ = size if size is not None else self.size
__magic_name__ = get_size_dict(UpperCamelCase__ , param_name="""size""" , default_to_square=UpperCamelCase__ )
__magic_name__ = resample if resample is not None else self.resample
__magic_name__ = do_center_crop if do_center_crop is not None else self.do_center_crop
__magic_name__ = crop_size if crop_size is not None else self.crop_size
__magic_name__ = get_size_dict(UpperCamelCase__ , param_name="""crop_size""" , default_to_square=UpperCamelCase__ )
__magic_name__ = do_rescale if do_rescale is not None else self.do_rescale
__magic_name__ = rescale_factor if rescale_factor is not None else self.rescale_factor
__magic_name__ = do_normalize if do_normalize is not None else self.do_normalize
__magic_name__ = image_mean if image_mean is not None else self.image_mean
__magic_name__ = image_std if image_std is not None else self.image_std
__magic_name__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
__magic_name__ = make_list_of_images(UpperCamelCase__ )
if not valid_images(UpperCamelCase__ ):
raise ValueError(
"""Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
"""torch.Tensor, tf.Tensor or jax.ndarray.""" )
if do_resize and size is None:
raise ValueError("""Size must be specified if do_resize is True.""" )
if do_center_crop and crop_size is None:
raise ValueError("""Crop size must be specified if do_center_crop is True.""" )
if do_rescale and rescale_factor is None:
raise ValueError("""Rescale factor must be specified if do_rescale is True.""" )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError("""Image mean and std must be specified if do_normalize is True.""" )
# PIL RGBA images are converted to RGB
if do_convert_rgb:
__magic_name__ = [convert_to_rgb(UpperCamelCase__ ) for image in images]
# All transformations expect numpy arrays.
__magic_name__ = [to_numpy_array(UpperCamelCase__ ) for image in images]
if do_resize:
__magic_name__ = [self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) for image in images]
if do_center_crop:
__magic_name__ = [self.center_crop(image=UpperCamelCase__ , size=UpperCamelCase__ ) for image in images]
if do_rescale:
__magic_name__ = [self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) for image in images]
if do_normalize:
__magic_name__ = [self.normalize(image=UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ ) for image in images]
__magic_name__ = [to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) for image in images]
__magic_name__ = {"""pixel_values""": images}
return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ )
| 76 | 0 |
from collections.abc import Callable
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = a
__magic_name__ = b
if function(A_ ) == 0: # one of the a or b is a root for the function
return a
elif function(A_ ) == 0:
return b
elif (
function(A_ ) * function(A_ ) > 0
): # if none of these are root and they are both positive or negative,
# then this algorithm can't find the root
raise ValueError("""could not find root in given interval.""" )
else:
__magic_name__ = start + (end - start) / 2.0
while abs(start - mid ) > 10**-7: # until precisely equals to 10^-7
if function(A_ ) == 0:
return mid
elif function(A_ ) * function(A_ ) < 0:
__magic_name__ = mid
else:
__magic_name__ = mid
__magic_name__ = start + (end - start) / 2.0
return mid
def a__ ( A_ ):
'''simple docstring'''
return x**3 - 2 * x - 5
if __name__ == "__main__":
print(bisection(f, 1, 1000))
import doctest
doctest.testmod()
| 700 |
import unittest
from transformers import AutoTokenizer, NystromformerConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
NystromformerForMaskedLM,
NystromformerForMultipleChoice,
NystromformerForQuestionAnswering,
NystromformerForSequenceClassification,
NystromformerForTokenClassification,
NystromformerModel,
)
from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST
class UpperCAmelCase_ :
'''simple docstring'''
def __init__( self : Any , UpperCamelCase__ : Any , UpperCamelCase__ : Tuple=13 , UpperCamelCase__ : Dict=7 , UpperCamelCase__ : Dict=True , UpperCamelCase__ : List[str]=True , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : int=True , UpperCamelCase__ : Optional[int]=99 , UpperCamelCase__ : List[Any]=32 , UpperCamelCase__ : Any=5 , UpperCamelCase__ : List[Any]=4 , UpperCamelCase__ : str=37 , UpperCamelCase__ : Any="gelu" , UpperCamelCase__ : int=0.1 , UpperCamelCase__ : Tuple=0.1 , UpperCamelCase__ : Dict=512 , UpperCamelCase__ : Union[str, Any]=16 , UpperCamelCase__ : Dict=2 , UpperCamelCase__ : Any=0.02 , UpperCamelCase__ : Any=3 , UpperCamelCase__ : Dict=4 , UpperCamelCase__ : List[Any]=None , ) -> Union[str, Any]:
"""simple docstring"""
__magic_name__ = parent
__magic_name__ = batch_size
__magic_name__ = seq_length
__magic_name__ = is_training
__magic_name__ = use_input_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_labels
__magic_name__ = num_choices
__magic_name__ = scope
def _lowercase ( self : Any ) -> Any:
"""simple docstring"""
__magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__magic_name__ = None
if self.use_input_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__ = None
__magic_name__ = None
__magic_name__ = None
if self.use_labels:
__magic_name__ = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
__magic_name__ = ids_tensor([self.batch_size] , self.num_choices )
__magic_name__ = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def _lowercase ( self : Tuple ) -> Any:
"""simple docstring"""
return NystromformerConfig(
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=UpperCamelCase__ , initializer_range=self.initializer_range , )
def _lowercase ( self : Any , UpperCamelCase__ : Tuple , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : str , UpperCamelCase__ : int , UpperCamelCase__ : str , UpperCamelCase__ : Dict , UpperCamelCase__ : str ) -> Tuple:
"""simple docstring"""
__magic_name__ = NystromformerModel(config=UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
__magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ )
__magic_name__ = model(UpperCamelCase__ , token_type_ids=UpperCamelCase__ )
__magic_name__ = model(UpperCamelCase__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def _lowercase ( self : Optional[int] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : str , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] ) -> str:
"""simple docstring"""
__magic_name__ = NystromformerForMaskedLM(config=UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
__magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def _lowercase ( self : Tuple , UpperCamelCase__ : Any , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Any , UpperCamelCase__ : Any ) -> Optional[Any]:
"""simple docstring"""
__magic_name__ = NystromformerForQuestionAnswering(config=UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
__magic_name__ = model(
UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , start_positions=UpperCamelCase__ , end_positions=UpperCamelCase__ , )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def _lowercase ( self : Optional[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Dict , UpperCamelCase__ : Dict , UpperCamelCase__ : Any ) -> Optional[int]:
"""simple docstring"""
__magic_name__ = self.num_labels
__magic_name__ = NystromformerForSequenceClassification(UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
__magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def _lowercase ( self : Any , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : str , UpperCamelCase__ : Any ) -> Dict:
"""simple docstring"""
__magic_name__ = self.num_labels
__magic_name__ = NystromformerForTokenClassification(config=UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
__magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : int , UpperCamelCase__ : int ) -> Optional[Any]:
"""simple docstring"""
__magic_name__ = self.num_choices
__magic_name__ = NystromformerForMultipleChoice(config=UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
__magic_name__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
__magic_name__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
__magic_name__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous()
__magic_name__ = model(
UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def _lowercase ( self : int ) -> List[Any]:
"""simple docstring"""
__magic_name__ = self.prepare_config_and_inputs()
(
(
__magic_name__
) , (
__magic_name__
) , (
__magic_name__
) , (
__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""": input_mask}
return config, inputs_dict
@require_torch
class UpperCAmelCase_ ( _A , _A , unittest.TestCase ):
'''simple docstring'''
a__ = (
(
NystromformerModel,
NystromformerForMaskedLM,
NystromformerForMultipleChoice,
NystromformerForQuestionAnswering,
NystromformerForSequenceClassification,
NystromformerForTokenClassification,
)
if is_torch_available()
else ()
)
a__ = (
{
"""feature-extraction""": NystromformerModel,
"""fill-mask""": NystromformerForMaskedLM,
"""question-answering""": NystromformerForQuestionAnswering,
"""text-classification""": NystromformerForSequenceClassification,
"""token-classification""": NystromformerForTokenClassification,
"""zero-shot""": NystromformerForSequenceClassification,
}
if is_torch_available()
else {}
)
a__ = False
a__ = False
def _lowercase ( self : Union[str, Any] ) -> Union[str, Any]:
"""simple docstring"""
__magic_name__ = NystromformerModelTester(self )
__magic_name__ = ConfigTester(self , config_class=UpperCamelCase__ , hidden_size=37 )
def _lowercase ( self : Tuple ) -> Any:
"""simple docstring"""
self.config_tester.run_common_tests()
def _lowercase ( self : Optional[Any] ) -> Any:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*UpperCamelCase__ )
def _lowercase ( self : Optional[Any] ) -> int:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
__magic_name__ = type
self.model_tester.create_and_check_model(*UpperCamelCase__ )
def _lowercase ( self : List[Any] ) -> List[Any]:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*UpperCamelCase__ )
def _lowercase ( self : Union[str, Any] ) -> str:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*UpperCamelCase__ )
def _lowercase ( self : Dict ) -> List[Any]:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*UpperCamelCase__ )
def _lowercase ( self : str ) -> int:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase__ )
def _lowercase ( self : List[Any] ) -> List[str]:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*UpperCamelCase__ )
@slow
def _lowercase ( self : str ) -> Tuple:
"""simple docstring"""
for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__magic_name__ = NystromformerModel.from_pretrained(UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
@require_torch
class UpperCAmelCase_ ( unittest.TestCase ):
'''simple docstring'''
@slow
def _lowercase ( self : Union[str, Any] ) -> Optional[Any]:
"""simple docstring"""
__magic_name__ = NystromformerModel.from_pretrained("""uw-madison/nystromformer-512""" )
__magic_name__ = torch.tensor([[0, 1, 2, 3, 4, 5]] )
with torch.no_grad():
__magic_name__ = model(UpperCamelCase__ )[0]
__magic_name__ = torch.Size((1, 6, 768) )
self.assertEqual(output.shape , UpperCamelCase__ )
__magic_name__ = torch.tensor(
[[[-0.4532, -0.0936, 0.5137], [-0.2676, 0.0628, 0.6186], [-0.3629, -0.1726, 0.4716]]] )
self.assertTrue(torch.allclose(output[:, :3, :3] , UpperCamelCase__ , atol=1E-4 ) )
@slow
def _lowercase ( self : int ) -> str:
"""simple docstring"""
__magic_name__ = """the [MASK] of Belgium is Brussels"""
__magic_name__ = AutoTokenizer.from_pretrained("""uw-madison/nystromformer-512""" )
__magic_name__ = NystromformerForMaskedLM.from_pretrained("""uw-madison/nystromformer-512""" )
__magic_name__ = tokenizer(UpperCamelCase__ , return_tensors="""pt""" )
with torch.no_grad():
__magic_name__ = model(encoding.input_ids ).logits
__magic_name__ = token_logits[:, 2, :].argmax(-1 )[0]
self.assertEqual(tokenizer.decode(UpperCamelCase__ ) , """capital""" )
| 76 | 0 |
from typing import TYPE_CHECKING
from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available
from ...utils import OptionalDependencyNotAvailable
__lowerCAmelCase : Tuple = {'configuration_gpt_neox': ['GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GPTNeoXConfig']}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowerCAmelCase : str = ['GPTNeoXTokenizerFast']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowerCAmelCase : Union[str, Any] = [
'GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST',
'GPTNeoXForCausalLM',
'GPTNeoXForQuestionAnswering',
'GPTNeoXForSequenceClassification',
'GPTNeoXForTokenClassification',
'GPTNeoXLayer',
'GPTNeoXModel',
'GPTNeoXPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_gpt_neox import GPT_NEOX_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXConfig
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_gpt_neox_fast import GPTNeoXTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_gpt_neox import (
GPT_NEOX_PRETRAINED_MODEL_ARCHIVE_LIST,
GPTNeoXForCausalLM,
GPTNeoXForQuestionAnswering,
GPTNeoXForSequenceClassification,
GPTNeoXForTokenClassification,
GPTNeoXLayer,
GPTNeoXModel,
GPTNeoXPreTrainedModel,
)
else:
import sys
__lowerCAmelCase : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 701 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__lowerCAmelCase : Tuple = logging.get_logger(__name__)
__lowerCAmelCase : Union[str, Any] = {
'microsoft/cvt-13': 'https://huggingface.co/microsoft/cvt-13/resolve/main/config.json',
# See all Cvt models at https://huggingface.co/models?filter=cvt
}
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = """cvt"""
def __init__( self : Dict , UpperCamelCase__ : Optional[int]=3 , UpperCamelCase__ : List[Any]=[7, 3, 3] , UpperCamelCase__ : Any=[4, 2, 2] , UpperCamelCase__ : Optional[Any]=[2, 1, 1] , UpperCamelCase__ : Union[str, Any]=[64, 192, 384] , UpperCamelCase__ : Dict=[1, 3, 6] , UpperCamelCase__ : Any=[1, 2, 10] , UpperCamelCase__ : List[str]=[4.0, 4.0, 4.0] , UpperCamelCase__ : Dict=[0.0, 0.0, 0.0] , UpperCamelCase__ : Tuple=[0.0, 0.0, 0.0] , UpperCamelCase__ : Optional[Any]=[0.0, 0.0, 0.1] , UpperCamelCase__ : str=[True, True, True] , UpperCamelCase__ : Optional[Any]=[False, False, True] , UpperCamelCase__ : Union[str, Any]=["dw_bn", "dw_bn", "dw_bn"] , UpperCamelCase__ : List[Any]=[3, 3, 3] , UpperCamelCase__ : Any=[1, 1, 1] , UpperCamelCase__ : Optional[int]=[2, 2, 2] , UpperCamelCase__ : Any=[1, 1, 1] , UpperCamelCase__ : List[str]=[1, 1, 1] , UpperCamelCase__ : int=0.02 , UpperCamelCase__ : int=1E-12 , **UpperCamelCase__ : int , ) -> Dict:
"""simple docstring"""
super().__init__(**UpperCamelCase__ )
__magic_name__ = num_channels
__magic_name__ = patch_sizes
__magic_name__ = patch_stride
__magic_name__ = patch_padding
__magic_name__ = embed_dim
__magic_name__ = num_heads
__magic_name__ = depth
__magic_name__ = mlp_ratio
__magic_name__ = attention_drop_rate
__magic_name__ = drop_rate
__magic_name__ = drop_path_rate
__magic_name__ = qkv_bias
__magic_name__ = cls_token
__magic_name__ = qkv_projection_method
__magic_name__ = kernel_qkv
__magic_name__ = padding_kv
__magic_name__ = stride_kv
__magic_name__ = padding_q
__magic_name__ = stride_q
__magic_name__ = initializer_range
__magic_name__ = layer_norm_eps
| 76 | 0 |
from __future__ import annotations
import random
import unittest
from transformers import TransfoXLConfig, is_tf_available
from transformers.testing_utils import require_tf, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
TFTransfoXLForSequenceClassification,
TFTransfoXLLMHeadModel,
TFTransfoXLModel,
)
class UpperCAmelCase_ :
'''simple docstring'''
def __init__( self : Tuple , UpperCamelCase__ : Dict , ) -> List[Any]:
"""simple docstring"""
__magic_name__ = parent
__magic_name__ = 13
__magic_name__ = 7
__magic_name__ = 30
__magic_name__ = self.seq_length + self.mem_len
__magic_name__ = 15
__magic_name__ = True
__magic_name__ = True
__magic_name__ = 99
__magic_name__ = [10, 50, 80]
__magic_name__ = 32
__magic_name__ = 32
__magic_name__ = 4
__magic_name__ = 8
__magic_name__ = 128
__magic_name__ = 2
__magic_name__ = 2
__magic_name__ = None
__magic_name__ = 1
__magic_name__ = 0
__magic_name__ = 3
__magic_name__ = self.vocab_size - 1
__magic_name__ = 0.01
def _lowercase ( self : Any ) -> Tuple:
"""simple docstring"""
__magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__magic_name__ = None
if self.use_labels:
__magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__magic_name__ = TransfoXLConfig(
vocab_size=self.vocab_size , mem_len=self.mem_len , clamp_len=self.clamp_len , cutoffs=self.cutoffs , d_model=self.hidden_size , d_embed=self.d_embed , n_head=self.num_attention_heads , d_head=self.d_head , d_inner=self.d_inner , div_val=self.div_val , n_layer=self.num_hidden_layers , eos_token_id=self.eos_token_id , pad_token_id=self.vocab_size - 1 , init_range=self.init_range , num_labels=self.num_labels , )
return (config, input_ids_a, input_ids_a, lm_labels)
def _lowercase ( self : Any ) -> Tuple:
"""simple docstring"""
random.seed(self.seed )
tf.random.set_seed(self.seed )
def _lowercase ( self : List[str] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : str , UpperCamelCase__ : int , UpperCamelCase__ : str ) -> Optional[int]:
"""simple docstring"""
__magic_name__ = TFTransfoXLModel(UpperCamelCase__ )
__magic_name__ , __magic_name__ = model(UpperCamelCase__ ).to_tuple()
__magic_name__ = {"""input_ids""": input_ids_a, """mems""": mems_a}
__magic_name__ , __magic_name__ = model(UpperCamelCase__ ).to_tuple()
self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size) )
self.parent.assertEqual(hidden_states_a.shape , (self.batch_size, self.seq_length, self.hidden_size) )
self.parent.assertListEqual(
[mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , )
self.parent.assertListEqual(
[mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , )
def _lowercase ( self : Tuple , UpperCamelCase__ : Dict , UpperCamelCase__ : str , UpperCamelCase__ : Any , UpperCamelCase__ : Optional[Any] ) -> str:
"""simple docstring"""
__magic_name__ = TFTransfoXLLMHeadModel(UpperCamelCase__ )
__magic_name__ , __magic_name__ = model(UpperCamelCase__ ).to_tuple()
__magic_name__ = {"""input_ids""": input_ids_a, """labels""": lm_labels}
__magic_name__ , __magic_name__ = model(UpperCamelCase__ ).to_tuple()
__magic_name__ , __magic_name__ = model([input_ids_a, mems_a] ).to_tuple()
__magic_name__ = {"""input_ids""": input_ids_a, """mems""": mems_a, """labels""": lm_labels}
__magic_name__ , __magic_name__ = model(UpperCamelCase__ ).to_tuple()
self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size) )
self.parent.assertListEqual(
[mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , )
self.parent.assertEqual(lm_logits_a.shape , (self.batch_size, self.seq_length, self.vocab_size) )
self.parent.assertListEqual(
[mem.shape for mem in mems_a] , [(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers , )
def _lowercase ( self : str , UpperCamelCase__ : Tuple , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[str] ) -> str:
"""simple docstring"""
__magic_name__ = TFTransfoXLForSequenceClassification(UpperCamelCase__ )
__magic_name__ = model(UpperCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def _lowercase ( self : List[Any] ) -> int:
"""simple docstring"""
__magic_name__ = self.prepare_config_and_inputs()
((__magic_name__) , (__magic_name__) , (__magic_name__) , (__magic_name__)) = config_and_inputs
__magic_name__ = {"""input_ids""": input_ids_a}
return config, inputs_dict
@require_tf
class UpperCAmelCase_ ( _A , _A , unittest.TestCase ):
'''simple docstring'''
a__ = (
(TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else ()
)
a__ = () if is_tf_available() else ()
a__ = (
{
"""feature-extraction""": TFTransfoXLModel,
"""text-classification""": TFTransfoXLForSequenceClassification,
"""text-generation""": TFTransfoXLLMHeadModel,
"""zero-shot""": TFTransfoXLForSequenceClassification,
}
if is_tf_available()
else {}
)
# TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented
a__ = False
a__ = False
a__ = False
a__ = False
def _lowercase ( self : Optional[int] , UpperCamelCase__ : Any , UpperCamelCase__ : str , UpperCamelCase__ : Tuple , UpperCamelCase__ : str , UpperCamelCase__ : Union[str, Any] ) -> List[Any]:
"""simple docstring"""
if pipeline_test_casse_name == "TextGenerationPipelineTests":
# Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`.
# `TransfoXLConfig` was never used in pipeline tests: cannot create a simple
# tokenizer.
return True
return False
def _lowercase ( self : List[Any] ) -> Any:
"""simple docstring"""
__magic_name__ = TFTransfoXLModelTester(self )
__magic_name__ = ConfigTester(self , config_class=UpperCamelCase__ , d_embed=37 )
def _lowercase ( self : Dict ) -> Tuple:
"""simple docstring"""
self.config_tester.run_common_tests()
def _lowercase ( self : List[Any] ) -> Tuple:
"""simple docstring"""
self.model_tester.set_seed()
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_transfo_xl_model(*UpperCamelCase__ )
def _lowercase ( self : Any ) -> Optional[int]:
"""simple docstring"""
self.model_tester.set_seed()
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_transfo_xl_lm_head(*UpperCamelCase__ )
def _lowercase ( self : Any ) -> Optional[Any]:
"""simple docstring"""
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*UpperCamelCase__ )
def _lowercase ( self : Any ) -> Tuple:
"""simple docstring"""
__magic_name__ , __magic_name__ = self.model_tester.prepare_config_and_inputs_for_common()
__magic_name__ = [TFTransfoXLForSequenceClassification]
for model_class in self.all_model_classes:
__magic_name__ = model_class(UpperCamelCase__ )
assert isinstance(model.get_input_embeddings() , tf.keras.layers.Layer )
if model_class in list_other_models_with_output_ebd:
__magic_name__ = model.get_output_embeddings()
assert isinstance(UpperCamelCase__ , tf.keras.layers.Layer )
__magic_name__ = model.get_bias()
assert name is None
else:
__magic_name__ = model.get_output_embeddings()
assert x is None
__magic_name__ = model.get_bias()
assert name is None
def _lowercase ( self : Tuple ) -> Optional[Any]:
"""simple docstring"""
pass
@slow
def _lowercase ( self : Dict ) -> int:
"""simple docstring"""
for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__magic_name__ = TFTransfoXLModel.from_pretrained(UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
@unittest.skip(reason="""This model doesn't play well with fit() due to not returning a single loss.""" )
def _lowercase ( self : Union[str, Any] ) -> Tuple:
"""simple docstring"""
pass
@require_tf
class UpperCAmelCase_ ( unittest.TestCase ):
'''simple docstring'''
@unittest.skip("""Skip test until #12651 is resolved.""" )
@slow
def _lowercase ( self : str ) -> List[Any]:
"""simple docstring"""
__magic_name__ = TFTransfoXLLMHeadModel.from_pretrained("""transfo-xl-wt103""" )
# fmt: off
__magic_name__ = tf.convert_to_tensor([[33,1297,2,1,1009,4,1109,1_1739,4762,358,5,25,245,22,1706,17,2_0098,5,3215,21,37,1110,3,13,1041,4,24,603,490,2,7_1477,2_0098,10_4447,2,2_0961,1,2604,4,1,329,3,6224,831,1_6002,2,8,603,7_8967,2_9546,23,803,20,25,416,5,8,232,4,277,6,1855,4601,3,2_9546,54,8,3609,5,5_7211,49,4,1,277,18,8,1755,1_5691,3,341,25,416,693,4_2573,71,17,401,94,31,1_7919,2,2_9546,7873,18,1,435,23,1_1011,755,5,5167,3,7983,98,84,2,2_9546,3267,8,3609,4,1,4865,1075,2,6087,71,6,346,8,5854,3,2_9546,824,1400,1868,2,19,160,2,311,8,5496,2,2_0920,17,25,1_5097,3,24,24,0]] , dtype=tf.intaa ) # noqa: E231
# fmt: on
# In 1991 , the remains of Russian Tsar Nicholas II and his family
# ( except for Alexei and Maria ) are discovered .
# The voice of Nicholas's young son , Tsarevich Alexei Nikolaevich , narrates the
# remainder of the story . 1883 Western Siberia ,
# a young Grigori Rasputin is asked by his father and a group of men to perform magic .
# Rasputin has a vision and denounces one of the men as a horse thief . Although his
# father initially slaps him for making such an accusation , Rasputin watches as the
# man is chased outside and beaten . Twenty years later , Rasputin sees a vision of
# the Virgin Mary , prompting him to become a priest . Rasputin quickly becomes famous ,
# with people , even a bishop , begging for his blessing . <eod> </s> <eos>
# fmt: off
__magic_name__ = [33,1297,2,1,1009,4,1109,1_1739,4762,358,5,25,245,22,1706,17,2_0098,5,3215,21,37,1110,3,13,1041,4,24,603,490,2,7_1477,2_0098,10_4447,2,2_0961,1,2604,4,1,329,3,6224,831,1_6002,2,8,603,7_8967,2_9546,23,803,20,25,416,5,8,232,4,277,6,1855,4601,3,2_9546,54,8,3609,5,5_7211,49,4,1,277,18,8,1755,1_5691,3,341,25,416,693,4_2573,71,17,401,94,31,1_7919,2,2_9546,7873,18,1,435,23,1_1011,755,5,5167,3,7983,98,84,2,2_9546,3267,8,3609,4,1,4865,1075,2,6087,71,6,346,8,5854,3,2_9546,824,1400,1868,2,19,160,2,311,8,5496,2,2_0920,17,25,1_5097,3,24,24,0,33,1,1857,2,1,1009,4,1109,1_1739,4762,358,5,25,245,28,1110,3,13,1041,4,24,603,490,2,7_1477,2_0098,10_4447,2,2_0961,1,2604,4,1,329,3,0] # noqa: E231
# fmt: on
# In 1991, the remains of Russian Tsar Nicholas II and his family (
# except for Alexei and Maria ) are discovered. The voice of young son,
# Tsarevich Alexei Nikolaevich, narrates the remainder of the story.
# 1883 Western Siberia, a young Grigori Rasputin is asked by his father
# and a group of men to perform magic. Rasputin has a vision and
# denounces one of the men as a horse thief. Although his father initially
# slaps him for making such an accusation, Rasputin watches as the man
# is chased outside and beaten. Twenty years later, Rasputin sees a vision
# of the Virgin Mary, prompting him to become a priest.
# Rasputin quickly becomes famous, with people, even a bishop, begging for
# his blessing. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar
# Nicholas II and his family were discovered. The voice of <unk> young son,
# Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos>
__magic_name__ = model.generate(UpperCamelCase__ , max_length=200 , do_sample=UpperCamelCase__ )
self.assertListEqual(output_ids[0].numpy().tolist() , UpperCamelCase__ )
| 702 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
__lowerCAmelCase : List[str] = {
'configuration_canine': ['CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP', 'CanineConfig'],
'tokenization_canine': ['CanineTokenizer'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__lowerCAmelCase : Optional[Any] = [
'CANINE_PRETRAINED_MODEL_ARCHIVE_LIST',
'CanineForMultipleChoice',
'CanineForQuestionAnswering',
'CanineForSequenceClassification',
'CanineForTokenClassification',
'CanineLayer',
'CanineModel',
'CaninePreTrainedModel',
'load_tf_weights_in_canine',
]
if TYPE_CHECKING:
from .configuration_canine import CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP, CanineConfig
from .tokenization_canine import CanineTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_canine import (
CANINE_PRETRAINED_MODEL_ARCHIVE_LIST,
CanineForMultipleChoice,
CanineForQuestionAnswering,
CanineForSequenceClassification,
CanineForTokenClassification,
CanineLayer,
CanineModel,
CaninePreTrainedModel,
load_tf_weights_in_canine,
)
else:
import sys
__lowerCAmelCase : int = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 76 | 0 |
import functools
import operator
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__lowerCAmelCase : int = logging.get_logger(__name__)
__lowerCAmelCase : str = {
'asapp/sew-tiny-100k': 'https://huggingface.co/asapp/sew-tiny-100k/resolve/main/config.json',
# See all SEW models at https://huggingface.co/models?filter=sew
}
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = """sew"""
def __init__( self : Optional[Any] , UpperCamelCase__ : int=32 , UpperCamelCase__ : List[str]=768 , UpperCamelCase__ : Optional[int]=12 , UpperCamelCase__ : Any=12 , UpperCamelCase__ : Optional[Any]=3072 , UpperCamelCase__ : Optional[int]=2 , UpperCamelCase__ : int="gelu" , UpperCamelCase__ : List[str]=0.1 , UpperCamelCase__ : Union[str, Any]=0.1 , UpperCamelCase__ : List[str]=0.1 , UpperCamelCase__ : List[str]=0.0 , UpperCamelCase__ : Union[str, Any]=0.1 , UpperCamelCase__ : Tuple=0.1 , UpperCamelCase__ : Dict=0.02 , UpperCamelCase__ : Union[str, Any]=1E-5 , UpperCamelCase__ : Optional[int]="group" , UpperCamelCase__ : Optional[Any]="gelu" , UpperCamelCase__ : Dict=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , UpperCamelCase__ : List[Any]=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , UpperCamelCase__ : Any=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , UpperCamelCase__ : Union[str, Any]=False , UpperCamelCase__ : str=128 , UpperCamelCase__ : List[Any]=16 , UpperCamelCase__ : int=True , UpperCamelCase__ : str=0.05 , UpperCamelCase__ : Any=10 , UpperCamelCase__ : List[Any]=2 , UpperCamelCase__ : Any=0.0 , UpperCamelCase__ : Any=10 , UpperCamelCase__ : Optional[int]=0 , UpperCamelCase__ : Union[str, Any]="mean" , UpperCamelCase__ : Union[str, Any]=False , UpperCamelCase__ : Any=False , UpperCamelCase__ : Optional[Any]=256 , UpperCamelCase__ : str=0 , UpperCamelCase__ : Dict=1 , UpperCamelCase__ : Tuple=2 , **UpperCamelCase__ : str , ) -> Dict:
"""simple docstring"""
super().__init__(**UpperCamelCase__ , pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ )
__magic_name__ = hidden_size
__magic_name__ = feat_extract_norm
__magic_name__ = feat_extract_activation
__magic_name__ = list(UpperCamelCase__ )
__magic_name__ = list(UpperCamelCase__ )
__magic_name__ = list(UpperCamelCase__ )
__magic_name__ = conv_bias
__magic_name__ = num_conv_pos_embeddings
__magic_name__ = num_conv_pos_embedding_groups
__magic_name__ = len(self.conv_dim )
__magic_name__ = num_hidden_layers
__magic_name__ = intermediate_size
__magic_name__ = squeeze_factor
__magic_name__ = hidden_act
__magic_name__ = num_attention_heads
__magic_name__ = hidden_dropout
__magic_name__ = attention_dropout
__magic_name__ = activation_dropout
__magic_name__ = feat_proj_dropout
__magic_name__ = final_dropout
__magic_name__ = layerdrop
__magic_name__ = layer_norm_eps
__magic_name__ = initializer_range
__magic_name__ = vocab_size
if (
(len(self.conv_stride ) != self.num_feat_extract_layers)
or (len(self.conv_kernel ) != self.num_feat_extract_layers)
or (len(self.conv_dim ) != self.num_feat_extract_layers)
):
raise ValueError(
"""Configuration for convolutional layers is incorrect."""
"""It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,"""
F'''but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)'''
F'''= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' )
# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
__magic_name__ = apply_spec_augment
__magic_name__ = mask_time_prob
__magic_name__ = mask_time_length
__magic_name__ = mask_time_min_masks
__magic_name__ = mask_feature_prob
__magic_name__ = mask_feature_length
__magic_name__ = mask_feature_min_masks
# ctc loss
__magic_name__ = ctc_loss_reduction
__magic_name__ = ctc_zero_infinity
# sequence classification
__magic_name__ = use_weighted_layer_sum
__magic_name__ = classifier_proj_size
@property
def _lowercase ( self : int ) -> Dict:
"""simple docstring"""
return functools.reduce(operator.mul , self.conv_stride , 1 )
| 703 |
import argparse
import torch
from transformers import (
WavaVecaConfig,
WavaVecaFeatureExtractor,
WavaVecaForAudioFrameClassification,
WavaVecaForSequenceClassification,
WavaVecaForXVector,
logging,
)
logging.set_verbosity_info()
__lowerCAmelCase : str = logging.get_logger(__name__)
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = WavaVecaForSequenceClassification.from_pretrained(A_, config=A_ )
__magic_name__ = downstream_dict["""projector.weight"""]
__magic_name__ = downstream_dict["""projector.bias"""]
__magic_name__ = downstream_dict["""model.post_net.linear.weight"""]
__magic_name__ = downstream_dict["""model.post_net.linear.bias"""]
return model
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = WavaVecaForAudioFrameClassification.from_pretrained(A_, config=A_ )
__magic_name__ = downstream_dict["""model.linear.weight"""]
__magic_name__ = downstream_dict["""model.linear.bias"""]
return model
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = WavaVecaForXVector.from_pretrained(A_, config=A_ )
__magic_name__ = downstream_dict["""connector.weight"""]
__magic_name__ = downstream_dict["""connector.bias"""]
for i, kernel_size in enumerate(hf_config.tdnn_kernel ):
__magic_name__ = downstream_dict[
f'''model.framelevel_feature_extractor.module.{i}.kernel.weight'''
]
__magic_name__ = downstream_dict[f'''model.framelevel_feature_extractor.module.{i}.kernel.bias''']
__magic_name__ = downstream_dict["""model.utterancelevel_feature_extractor.linear1.weight"""]
__magic_name__ = downstream_dict["""model.utterancelevel_feature_extractor.linear1.bias"""]
__magic_name__ = downstream_dict["""model.utterancelevel_feature_extractor.linear2.weight"""]
__magic_name__ = downstream_dict["""model.utterancelevel_feature_extractor.linear2.bias"""]
__magic_name__ = downstream_dict["""objective.W"""]
return model
@torch.no_grad()
def a__ ( A_, A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = torch.load(A_, map_location="""cpu""" )
__magic_name__ = checkpoint["""Downstream"""]
__magic_name__ = WavaVecaConfig.from_pretrained(A_ )
__magic_name__ = WavaVecaFeatureExtractor.from_pretrained(
A_, return_attention_mask=A_, do_normalize=A_ )
__magic_name__ = hf_config.architectures[0]
if arch.endswith("""ForSequenceClassification""" ):
__magic_name__ = convert_classification(A_, A_, A_ )
elif arch.endswith("""ForAudioFrameClassification""" ):
__magic_name__ = convert_diarization(A_, A_, A_ )
elif arch.endswith("""ForXVector""" ):
__magic_name__ = convert_xvector(A_, A_, A_ )
else:
raise NotImplementedError(f'''S3PRL weights conversion is not supported for {arch}''' )
if hf_config.use_weighted_layer_sum:
__magic_name__ = checkpoint["""Featurizer"""]["""weights"""]
hf_feature_extractor.save_pretrained(A_ )
hf_model.save_pretrained(A_ )
if __name__ == "__main__":
__lowerCAmelCase : Optional[Any] = argparse.ArgumentParser()
parser.add_argument(
'--base_model_name', default=None, type=str, help='Name of the huggingface pretrained base model.'
)
parser.add_argument('--config_path', default=None, type=str, help='Path to the huggingface classifier config.')
parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to the s3prl checkpoint.')
parser.add_argument('--model_dump_path', default=None, type=str, help='Path to the final converted model.')
__lowerCAmelCase : str = parser.parse_args()
convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)
| 76 | 0 |
import argparse
import json
import math
import os
import time
import traceback
import zipfile
from collections import Counter
import requests
def a__ ( A_, A_=None ):
'''simple docstring'''
__magic_name__ = None
if token is not None:
__magic_name__ = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''}
__magic_name__ = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100'''
__magic_name__ = requests.get(A_, headers=A_ ).json()
__magic_name__ = {}
try:
job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} )
__magic_name__ = math.ceil((result["""total_count"""] - 100) / 100 )
for i in range(A_ ):
__magic_name__ = requests.get(url + f'''&page={i + 2}''', headers=A_ ).json()
job_links.update({job["""name"""]: job["""html_url"""] for job in result["""jobs"""]} )
return job_links
except Exception:
print(f'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' )
return {}
def a__ ( A_, A_=None ):
'''simple docstring'''
__magic_name__ = None
if token is not None:
__magic_name__ = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''}
__magic_name__ = f'''https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100'''
__magic_name__ = requests.get(A_, headers=A_ ).json()
__magic_name__ = {}
try:
artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} )
__magic_name__ = math.ceil((result["""total_count"""] - 100) / 100 )
for i in range(A_ ):
__magic_name__ = requests.get(url + f'''&page={i + 2}''', headers=A_ ).json()
artifacts.update({artifact["""name"""]: artifact["""archive_download_url"""] for artifact in result["""artifacts"""]} )
return artifacts
except Exception:
print(f'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' )
return {}
def a__ ( A_, A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = None
if token is not None:
__magic_name__ = {"""Accept""": """application/vnd.github+json""", """Authorization""": f'''Bearer {token}'''}
__magic_name__ = requests.get(A_, headers=A_, allow_redirects=A_ )
__magic_name__ = result.headers["""Location"""]
__magic_name__ = requests.get(A_, allow_redirects=A_ )
__magic_name__ = os.path.join(A_, f'''{artifact_name}.zip''' )
with open(A_, """wb""" ) as fp:
fp.write(response.content )
def a__ ( A_, A_=None ):
'''simple docstring'''
__magic_name__ = []
__magic_name__ = []
__magic_name__ = None
with zipfile.ZipFile(A_ ) as z:
for filename in z.namelist():
if not os.path.isdir(A_ ):
# read the file
if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]:
with z.open(A_ ) as f:
for line in f:
__magic_name__ = line.decode("""UTF-8""" ).strip()
if filename == "failures_line.txt":
try:
# `error_line` is the place where `error` occurs
__magic_name__ = line[: line.index(""": """ )]
__magic_name__ = line[line.index(""": """ ) + len(""": """ ) :]
errors.append([error_line, error] )
except Exception:
# skip un-related lines
pass
elif filename == "summary_short.txt" and line.startswith("""FAILED """ ):
# `test` is the test method that failed
__magic_name__ = line[len("""FAILED """ ) :]
failed_tests.append(A_ )
elif filename == "job_name.txt":
__magic_name__ = line
if len(A_ ) != len(A_ ):
raise ValueError(
f'''`errors` and `failed_tests` should have the same number of elements. Got {len(A_ )} for `errors` '''
f'''and {len(A_ )} for `failed_tests` instead. The test reports in {artifact_zip_path} have some'''
""" problem.""" )
__magic_name__ = None
if job_name and job_links:
__magic_name__ = job_links.get(A_, A_ )
# A list with elements of the form (line of error, error, failed test)
__magic_name__ = [x + [y] + [job_link] for x, y in zip(A_, A_ )]
return result
def a__ ( A_, A_=None ):
'''simple docstring'''
__magic_name__ = []
__magic_name__ = [os.path.join(A_, A_ ) for p in os.listdir(A_ ) if p.endswith(""".zip""" )]
for p in paths:
errors.extend(get_errors_from_single_artifact(A_, job_links=A_ ) )
return errors
def a__ ( A_, A_=None ):
'''simple docstring'''
__magic_name__ = Counter()
counter.update([x[1] for x in logs] )
__magic_name__ = counter.most_common()
__magic_name__ = {}
for error, count in counts:
if error_filter is None or error not in error_filter:
__magic_name__ = {"""count""": count, """failed_tests""": [(x[2], x[0]) for x in logs if x[1] == error]}
__magic_name__ = dict(sorted(r.items(), key=lambda A_ : item[1]["count"], reverse=A_ ) )
return r
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = test.split("""::""" )[0]
if test.startswith("""tests/models/""" ):
__magic_name__ = test.split("""/""" )[2]
else:
__magic_name__ = None
return test
def a__ ( A_, A_=None ):
'''simple docstring'''
__magic_name__ = [(x[0], x[1], get_model(x[2] )) for x in logs]
__magic_name__ = [x for x in logs if x[2] is not None]
__magic_name__ = {x[2] for x in logs}
__magic_name__ = {}
for test in tests:
__magic_name__ = Counter()
# count by errors in `test`
counter.update([x[1] for x in logs if x[2] == test] )
__magic_name__ = counter.most_common()
__magic_name__ = {error: count for error, count in counts if (error_filter is None or error not in error_filter)}
__magic_name__ = sum(error_counts.values() )
if n_errors > 0:
__magic_name__ = {"""count""": n_errors, """errors""": error_counts}
__magic_name__ = dict(sorted(r.items(), key=lambda A_ : item[1]["count"], reverse=A_ ) )
return r
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = """| no. | error | status |"""
__magic_name__ = """|-:|:-|:-|"""
__magic_name__ = [header, sep]
for error in reduced_by_error:
__magic_name__ = reduced_by_error[error]["""count"""]
__magic_name__ = f'''| {count} | {error[:100]} | |'''
lines.append(A_ )
return "\n".join(A_ )
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = """| model | no. of errors | major error | count |"""
__magic_name__ = """|-:|-:|-:|-:|"""
__magic_name__ = [header, sep]
for model in reduced_by_model:
__magic_name__ = reduced_by_model[model]["""count"""]
__magic_name__ , __magic_name__ = list(reduced_by_model[model]["""errors"""].items() )[0]
__magic_name__ = f'''| {model} | {count} | {error[:60]} | {_count} |'''
lines.append(A_ )
return "\n".join(A_ )
if __name__ == "__main__":
__lowerCAmelCase : List[str] = argparse.ArgumentParser()
# Required parameters
parser.add_argument('--workflow_run_id', type=str, required=True, help='A GitHub Actions workflow run id.')
parser.add_argument(
'--output_dir',
type=str,
required=True,
help='Where to store the downloaded artifacts and other result files.',
)
parser.add_argument('--token', default=None, type=str, help='A token that has actions:read permission.')
__lowerCAmelCase : Dict = parser.parse_args()
os.makedirs(args.output_dir, exist_ok=True)
__lowerCAmelCase : List[str] = get_job_links(args.workflow_run_id, token=args.token)
__lowerCAmelCase : Dict = {}
# To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee.
# For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`.
if _job_links:
for k, v in _job_links.items():
# This is how GitHub actions combine job names.
if " / " in k:
__lowerCAmelCase : Optional[int] = k.find(' / ')
__lowerCAmelCase : List[str] = k[index + len(' / ') :]
__lowerCAmelCase : Dict = v
with open(os.path.join(args.output_dir, 'job_links.json'), 'w', encoding='UTF-8') as fp:
json.dump(job_links, fp, ensure_ascii=False, indent=4)
__lowerCAmelCase : Tuple = get_artifacts_links(args.workflow_run_id, token=args.token)
with open(os.path.join(args.output_dir, 'artifacts.json'), 'w', encoding='UTF-8') as fp:
json.dump(artifacts, fp, ensure_ascii=False, indent=4)
for idx, (name, url) in enumerate(artifacts.items()):
download_artifact(name, url, args.output_dir, args.token)
# Be gentle to GitHub
time.sleep(1)
__lowerCAmelCase : List[str] = get_all_errors(args.output_dir, job_links=job_links)
# `e[1]` is the error
__lowerCAmelCase : str = Counter()
counter.update([e[1] for e in errors])
# print the top 30 most common test errors
__lowerCAmelCase : str = counter.most_common(30)
for item in most_common:
print(item)
with open(os.path.join(args.output_dir, 'errors.json'), 'w', encoding='UTF-8') as fp:
json.dump(errors, fp, ensure_ascii=False, indent=4)
__lowerCAmelCase : Optional[Any] = reduce_by_error(errors)
__lowerCAmelCase : Optional[int] = reduce_by_model(errors)
__lowerCAmelCase : Dict = make_github_table(reduced_by_error)
__lowerCAmelCase : Optional[int] = make_github_table_per_model(reduced_by_model)
with open(os.path.join(args.output_dir, 'reduced_by_error.txt'), 'w', encoding='UTF-8') as fp:
fp.write(sa)
with open(os.path.join(args.output_dir, 'reduced_by_model.txt'), 'w', encoding='UTF-8') as fp:
fp.write(sa)
| 704 |
import pytest
from datasets import Dataset, DatasetDict, Features, NamedSplit, Value
from datasets.io.text import TextDatasetReader
from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases
def a__ ( A_, A_ ):
'''simple docstring'''
assert isinstance(A_, A_ )
assert dataset.num_rows == 4
assert dataset.num_columns == 1
assert dataset.column_names == ["text"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize("""keep_in_memory""", [False, True] )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = tmp_path / """cache"""
__magic_name__ = {"""text""": """string"""}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
__magic_name__ = TextDatasetReader(A_, cache_dir=A_, keep_in_memory=A_ ).read()
_check_text_dataset(A_, A_ )
@pytest.mark.parametrize(
"""features""", [
None,
{"""text""": """string"""},
{"""text""": """int32"""},
{"""text""": """float32"""},
], )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = tmp_path / """cache"""
__magic_name__ = {"""text""": """string"""}
__magic_name__ = features.copy() if features else default_expected_features
__magic_name__ = (
Features({feature: Value(A_ ) for feature, dtype in features.items()} ) if features is not None else None
)
__magic_name__ = TextDatasetReader(A_, features=A_, cache_dir=A_ ).read()
_check_text_dataset(A_, A_ )
@pytest.mark.parametrize("""split""", [None, NamedSplit("""train""" ), """train""", """test"""] )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = tmp_path / """cache"""
__magic_name__ = {"""text""": """string"""}
__magic_name__ = TextDatasetReader(A_, cache_dir=A_, split=A_ ).read()
_check_text_dataset(A_, A_ )
assert dataset.split == split if split else "train"
@pytest.mark.parametrize("""path_type""", [str, list] )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
if issubclass(A_, A_ ):
__magic_name__ = text_path
elif issubclass(A_, A_ ):
__magic_name__ = [text_path]
__magic_name__ = tmp_path / """cache"""
__magic_name__ = {"""text""": """string"""}
__magic_name__ = TextDatasetReader(A_, cache_dir=A_ ).read()
_check_text_dataset(A_, A_ )
def a__ ( A_, A_, A_=("train",) ):
'''simple docstring'''
assert isinstance(A_, A_ )
for split in splits:
__magic_name__ = dataset_dict[split]
assert dataset.num_rows == 4
assert dataset.num_columns == 1
assert dataset.column_names == ["text"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize("""keep_in_memory""", [False, True] )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = tmp_path / """cache"""
__magic_name__ = {"""text""": """string"""}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
__magic_name__ = TextDatasetReader({"""train""": text_path}, cache_dir=A_, keep_in_memory=A_ ).read()
_check_text_datasetdict(A_, A_ )
@pytest.mark.parametrize(
"""features""", [
None,
{"""text""": """string"""},
{"""text""": """int32"""},
{"""text""": """float32"""},
], )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = tmp_path / """cache"""
# CSV file loses col_1 string dtype information: default now is "int64" instead of "string"
__magic_name__ = {"""text""": """string"""}
__magic_name__ = features.copy() if features else default_expected_features
__magic_name__ = (
Features({feature: Value(A_ ) for feature, dtype in features.items()} ) if features is not None else None
)
__magic_name__ = TextDatasetReader({"""train""": text_path}, features=A_, cache_dir=A_ ).read()
_check_text_datasetdict(A_, A_ )
@pytest.mark.parametrize("""split""", [None, NamedSplit("""train""" ), """train""", """test"""] )
def a__ ( A_, A_, A_ ):
'''simple docstring'''
if split:
__magic_name__ = {split: text_path}
else:
__magic_name__ = """train"""
__magic_name__ = {"""train""": text_path, """test""": text_path}
__magic_name__ = tmp_path / """cache"""
__magic_name__ = {"""text""": """string"""}
__magic_name__ = TextDatasetReader(A_, cache_dir=A_ ).read()
_check_text_datasetdict(A_, A_, splits=list(path.keys() ) )
assert all(dataset[split].split == split for split in path.keys() )
| 76 | 0 |
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.layers import LSTM, Dense
from tensorflow.keras.models import Sequential
if __name__ == "__main__":
__lowerCAmelCase : int = pd.read_csv('sample_data.csv', header=None)
__lowerCAmelCase : str = df.shape[:1][0]
# If you're using some other dataset input the target column
__lowerCAmelCase : Tuple = df.iloc[:, 1:2]
__lowerCAmelCase : List[Any] = actual_data.values.reshape(len_data, 1)
__lowerCAmelCase : Union[str, Any] = MinMaxScaler().fit_transform(actual_data)
__lowerCAmelCase : int = 10
__lowerCAmelCase : Dict = 5
__lowerCAmelCase : Tuple = 20
__lowerCAmelCase : int = len_data - periods * look_back
__lowerCAmelCase : str = actual_data[:division]
__lowerCAmelCase : int = actual_data[division - look_back :]
__lowerCAmelCase : Optional[int] = [], []
__lowerCAmelCase : Dict = [], []
for i in range(0, len(train_data) - forward_days - look_back + 1):
train_x.append(train_data[i : i + look_back])
train_y.append(train_data[i + look_back : i + look_back + forward_days])
for i in range(0, len(test_data) - forward_days - look_back + 1):
test_x.append(test_data[i : i + look_back])
test_y.append(test_data[i + look_back : i + look_back + forward_days])
__lowerCAmelCase : Any = np.array(train_x)
__lowerCAmelCase : int = np.array(test_x)
__lowerCAmelCase : Optional[int] = np.array([list(i.ravel()) for i in train_y])
__lowerCAmelCase : Dict = np.array([list(i.ravel()) for i in test_y])
__lowerCAmelCase : Optional[int] = Sequential()
model.add(LSTM(128, input_shape=(look_back, 1), return_sequences=True))
model.add(LSTM(64, input_shape=(128, 1)))
model.add(Dense(forward_days))
model.compile(loss='mean_squared_error', optimizer='adam')
__lowerCAmelCase : str = model.fit(
x_train, y_train, epochs=150, verbose=1, shuffle=True, batch_size=4
)
__lowerCAmelCase : Optional[int] = model.predict(x_test)
| 705 |
from typing import Dict, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
IMAGENET_STANDARD_MEAN,
IMAGENET_STANDARD_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, logging
__lowerCAmelCase : Union[str, Any] = logging.get_logger(__name__)
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = ["""pixel_values"""]
def __init__( self : str , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Dict[str, int]] = None , UpperCamelCase__ : PILImageResampling = PILImageResampling.BILINEAR , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : bool = True , UpperCamelCase__ : Union[int, float] = 1 / 255 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , **UpperCamelCase__ : List[Any] , ) -> None:
"""simple docstring"""
super().__init__(**UpperCamelCase__ )
__magic_name__ = size if size is not None else {"""shortest_edge""": 256}
__magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ )
__magic_name__ = crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
__magic_name__ = get_size_dict(UpperCamelCase__ )
__magic_name__ = do_resize
__magic_name__ = size
__magic_name__ = resample
__magic_name__ = do_center_crop
__magic_name__ = crop_size
__magic_name__ = do_rescale
__magic_name__ = rescale_factor
__magic_name__ = do_normalize
__magic_name__ = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
__magic_name__ = image_std if image_std is not None else IMAGENET_STANDARD_STD
def _lowercase ( self : Any , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Tuple , ) -> np.ndarray:
"""simple docstring"""
__magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ )
if "shortest_edge" not in size:
raise ValueError(F'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' )
__magic_name__ = get_resize_output_image_size(UpperCamelCase__ , size=size["""shortest_edge"""] , default_to_square=UpperCamelCase__ )
return resize(UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : str , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : str , ) -> np.ndarray:
"""simple docstring"""
__magic_name__ = get_size_dict(UpperCamelCase__ )
return center_crop(UpperCamelCase__ , size=(size["""height"""], size["""width"""]) , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : Tuple , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : float , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Any ) -> np.ndarray:
"""simple docstring"""
return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : List[str] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : str , ) -> np.ndarray:
"""simple docstring"""
return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : Optional[Any] , UpperCamelCase__ : ImageInput , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Optional[float] = None , UpperCamelCase__ : Optional[bool] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , UpperCamelCase__ : Union[str, ChannelDimension] = ChannelDimension.FIRST , **UpperCamelCase__ : int , ) -> Dict:
"""simple docstring"""
__magic_name__ = do_resize if do_resize is not None else self.do_resize
__magic_name__ = size if size is not None else self.size
__magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ )
__magic_name__ = resample if resample is not None else self.resample
__magic_name__ = do_center_crop if do_center_crop is not None else self.do_center_crop
__magic_name__ = crop_size if crop_size is not None else self.crop_size
__magic_name__ = get_size_dict(UpperCamelCase__ )
__magic_name__ = do_rescale if do_rescale is not None else self.do_rescale
__magic_name__ = rescale_factor if rescale_factor is not None else self.rescale_factor
__magic_name__ = do_normalize if do_normalize is not None else self.do_normalize
__magic_name__ = image_mean if image_mean is not None else self.image_mean
__magic_name__ = image_std if image_std is not None else self.image_std
__magic_name__ = make_list_of_images(UpperCamelCase__ )
if not valid_images(UpperCamelCase__ ):
raise ValueError(
"""Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
"""torch.Tensor, tf.Tensor or jax.ndarray.""" )
if do_resize and size is None:
raise ValueError("""Size must be specified if do_resize is True.""" )
if do_center_crop and crop_size is None:
raise ValueError("""Crop size must be specified if do_center_crop is True.""" )
if do_rescale and rescale_factor is None:
raise ValueError("""Rescale factor must be specified if do_rescale is True.""" )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError("""Image mean and std must be specified if do_normalize is True.""" )
# All transformations expect numpy arrays.
__magic_name__ = [to_numpy_array(UpperCamelCase__ ) for image in images]
if do_resize:
__magic_name__ = [self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) for image in images]
if do_center_crop:
__magic_name__ = [self.center_crop(image=UpperCamelCase__ , size=UpperCamelCase__ ) for image in images]
if do_rescale:
__magic_name__ = [self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) for image in images]
if do_normalize:
__magic_name__ = [self.normalize(image=UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ ) for image in images]
__magic_name__ = [to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) for image in images]
__magic_name__ = {"""pixel_values""": images}
return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ )
| 76 | 0 |
import argparse
import re
from flax.traverse_util import flatten_dict, unflatten_dict
from tax import checkpoints
from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration
from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model
from transformers.utils import logging
logging.set_verbosity_info()
# should not include what is already done by the `from_pt` argument
__lowerCAmelCase : Union[str, Any] = {
'/attention/': '/0/SelfAttention/',
'/self_attention/': '/0/SelfAttention/',
'/encoder_decoder_attention/': '/1/EncDecAttention/',
'value': 'v',
'query': 'q',
'key': 'k',
'out': 'o',
'pre_self_attention_layer_norm': '0/layer_norm',
'pre_cross_attention_layer_norm': '1/layer_norm',
'pre_attention_layer_norm': '0/layer_norm', # previously 1, but seems wrong
'token_embedder': 'shared',
'encoder_norm': 'final_layer_norm',
'decoder_norm': 'final_layer_norm',
'relpos_bias/rel_embedding': 'block/0/layer/0/SelfAttention/relative_attention_bias/weight',
'router/router_weights/w/': 'router/classifier/',
'roer/roer_weights/w/': 'router/classifier/',
'logits_dense': 'lm_head',
}
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = list(s_dict.keys() )
for key in keys:
__magic_name__ = R""".*/layers_(\d+)"""
__magic_name__ = key
if re.match(A_, A_ ):
__magic_name__ = re.sub(R"""layers_(\d+)""", R"""block/\1/layer""", A_ )
__magic_name__ = R"""(encoder|decoder)\/"""
if re.match(A_, A_ ):
__magic_name__ = re.match(A_, A_ ).groups()
if groups[0] == "encoder":
__magic_name__ = re.sub(R"""/mlp/""", R"""/1/mlp/""", A_ )
__magic_name__ = re.sub(R"""/pre_mlp_layer_norm/""", R"""/1/layer_norm/""", A_ )
elif groups[0] == "decoder":
__magic_name__ = re.sub(R"""/mlp/""", R"""/2/mlp/""", A_ )
__magic_name__ = re.sub(R"""/pre_mlp_layer_norm/""", R"""/2/layer_norm/""", A_ )
# 2. Convert other classic mappings
for old_key, temp_key in MOE_LAYER_NAME_MAPPING.items():
if old_key in new_key:
__magic_name__ = new_key.replace(A_, A_ )
print(f'''{key} -> {new_key}''' )
__magic_name__ = s_dict.pop(A_ )
if "encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict:
__magic_name__ = s_dict[
"""encoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight"""
].T
if "decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight" in s_dict:
__magic_name__ = s_dict[
"""decoder/block/0/layer/0/SelfAttention/relative_attention_bias/weight"""
].T
# 3. Take extra care of the EXPERTS layer
for key in list(s_dict.keys() ):
if "expert" in key:
__magic_name__ = s_dict[key].shape[0]
__magic_name__ = s_dict[key]
for idx in range(A_ ):
__magic_name__ = expert_weihts[idx]
print(f'''{key} -> {key.replace('expert/', 'nested fstring' )}''' )
s_dict.pop(A_ )
return s_dict
__lowerCAmelCase : Dict = {
'NUM_ENCODER_LAYERS': 'num_layers',
'NUM_DECODER_LAYERS': 'num_decoder_layers',
'NUM_HEADS': 'num_heads',
'HEAD_DIM': 'd_kv',
'EMBED_DIM': 'd_model',
'MLP_DIM': 'd_ff',
'NUM_SELECTED_EXPERTS': 'num_selected_experts',
'NUM_ENCODER_SPARSE_LAYERS': 'num_sparse_encoder_layers',
'NUM_DECODER_SPARSE_LAYERS': 'num_sparse_decoder_layers',
'dense.MlpBlock.activations': 'feed_forward_proj',
}
def a__ ( A_, A_ ):
'''simple docstring'''
import regex as re
with open(A_, """r""" ) as f:
__magic_name__ = f.read()
__magic_name__ = re.findall(R"""(.*) = ([0-9.]*)""", A_ )
__magic_name__ = {}
for param, value in regex_match:
if param in GIN_TO_CONFIG_MAPPING and value != "":
__magic_name__ = float(A_ ) if """.""" in value else int(A_ )
__magic_name__ = re.findall(R"""(.*activations) = \(\'(.*)\',\)""", A_ )[0]
__magic_name__ = str(activation[1] )
__magic_name__ = num_experts
__magic_name__ = SwitchTransformersConfig(**A_ )
return config
def a__ ( A_, A_, A_=None, A_="./", A_=8 ):
'''simple docstring'''
print(f'''Loading flax weights from : {flax_checkpoint_path}''' )
__magic_name__ = checkpoints.load_tax_checkpoint(A_ )
if gin_file is not None:
__magic_name__ = convert_gin_to_config(A_, A_ )
else:
__magic_name__ = SwitchTransformersConfig.from_pretrained(A_ )
__magic_name__ = SwitchTransformersForConditionalGeneration(A_ )
__magic_name__ = flax_params["""target"""]
__magic_name__ = flatten_dict(A_, sep="""/""" )
__magic_name__ = rename_keys(A_ )
__magic_name__ = unflatten_dict(A_, sep="""/""" )
# Load the flax params in the PT model
load_flax_weights_in_pytorch_model(A_, A_ )
print(f'''Save PyTorch model to {pytorch_dump_path}''' )
pt_model.save_pretrained(A_ )
if __name__ == "__main__":
__lowerCAmelCase : Tuple = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--switch_t5x_checkpoint_path',
default=None,
type=str,
required=True,
help=(
'The config json file corresponding to the pre-trained SwitchTransformers model. \nThis specifies the'
' model architecture. If not provided, a `gin_file` has to be provided.'
),
)
parser.add_argument(
'--gin_file',
default=None,
type=str,
required=False,
help='Path to the gin config file. If not provided, a `config_file` has to be passed ',
)
parser.add_argument(
'--config_name', default=None, type=str, required=False, help='Config name of SwitchTransformers model.'
)
parser.add_argument(
'--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output pytorch model.'
)
parser.add_argument('--num_experts', default=8, type=int, required=False, help='Number of experts')
__lowerCAmelCase : Dict = parser.parse_args()
convert_flax_checkpoint_to_pytorch(
args.switch_tax_checkpoint_path,
args.config_name,
args.gin_file,
args.pytorch_dump_folder_path,
args.num_experts,
)
| 706 |
import math
def a__ ( A_, A_ = 0, A_ = 0 ):
'''simple docstring'''
__magic_name__ = end or len(A_ )
for i in range(A_, A_ ):
__magic_name__ = i
__magic_name__ = array[i]
while temp_index != start and temp_index_value < array[temp_index - 1]:
__magic_name__ = array[temp_index - 1]
temp_index -= 1
__magic_name__ = temp_index_value
return array
def a__ ( A_, A_, A_ ): # Max Heap
'''simple docstring'''
__magic_name__ = index
__magic_name__ = 2 * index + 1 # Left Node
__magic_name__ = 2 * index + 2 # Right Node
if left_index < heap_size and array[largest] < array[left_index]:
__magic_name__ = left_index
if right_index < heap_size and array[largest] < array[right_index]:
__magic_name__ = right_index
if largest != index:
__magic_name__ , __magic_name__ = array[largest], array[index]
heapify(A_, A_, A_ )
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = len(A_ )
for i in range(n // 2, -1, -1 ):
heapify(A_, A_, A_ )
for i in range(n - 1, 0, -1 ):
__magic_name__ , __magic_name__ = array[0], array[i]
heapify(A_, 0, A_ )
return array
def a__ ( A_, A_, A_, A_ ):
'''simple docstring'''
if (array[first_index] > array[middle_index]) != (
array[first_index] > array[last_index]
):
return array[first_index]
elif (array[middle_index] > array[first_index]) != (
array[middle_index] > array[last_index]
):
return array[middle_index]
else:
return array[last_index]
def a__ ( A_, A_, A_, A_ ):
'''simple docstring'''
__magic_name__ = low
__magic_name__ = high
while True:
while array[i] < pivot:
i += 1
j -= 1
while pivot < array[j]:
j -= 1
if i >= j:
return i
__magic_name__ , __magic_name__ = array[j], array[i]
i += 1
def a__ ( A_ ):
'''simple docstring'''
if len(A_ ) == 0:
return array
__magic_name__ = 2 * math.ceil(math.loga(len(A_ ) ) )
__magic_name__ = 16
return intro_sort(A_, 0, len(A_ ), A_, A_ )
def a__ ( A_, A_, A_, A_, A_ ):
'''simple docstring'''
while end - start > size_threshold:
if max_depth == 0:
return heap_sort(A_ )
max_depth -= 1
__magic_name__ = median_of_a(A_, A_, start + ((end - start) // 2) + 1, end - 1 )
__magic_name__ = partition(A_, A_, A_, A_ )
intro_sort(A_, A_, A_, A_, A_ )
__magic_name__ = p
return insertion_sort(A_, A_, A_ )
if __name__ == "__main__":
import doctest
doctest.testmod()
__lowerCAmelCase : str = input('Enter numbers separated by a comma : ').strip()
__lowerCAmelCase : List[Any] = [float(item) for item in user_input.split(',')]
print(sort(unsorted))
| 76 | 0 |
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = set()
# To detect a back edge, keep track of vertices currently in the recursion stack
__magic_name__ = set()
return any(
node not in visited and depth_first_search(A_, A_, A_, A_ )
for node in graph )
def a__ ( A_, A_, A_, A_ ):
'''simple docstring'''
visited.add(A_ )
rec_stk.add(A_ )
for node in graph[vertex]:
if node not in visited:
if depth_first_search(A_, A_, A_, A_ ):
return True
elif node in rec_stk:
return True
# The node needs to be removed from recursion stack before function ends
rec_stk.remove(A_ )
return False
if __name__ == "__main__":
from doctest import testmod
testmod()
| 707 |
import argparse
import json
import re
from pathlib import Path
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import (
MobileNetVaConfig,
MobileNetVaForImageClassification,
MobileNetVaImageProcessor,
load_tf_weights_in_mobilenet_va,
)
from transformers.utils import logging
logging.set_verbosity_info()
__lowerCAmelCase : str = logging.get_logger(__name__)
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = MobileNetVaConfig(layer_norm_eps=0.001 )
if "_quant" in model_name:
raise ValueError("""Quantized models are not supported.""" )
__magic_name__ = re.match(R"""^mobilenet_v1_([^_]*)_([^_]*)$""", A_ )
if matches:
__magic_name__ = float(matches[1] )
__magic_name__ = int(matches[2] )
# The TensorFlow version of MobileNetV1 predicts 1001 classes instead of
# the usual 1000. The first class (index 0) is "background".
__magic_name__ = 1001
__magic_name__ = """imagenet-1k-id2label.json"""
__magic_name__ = """huggingface/label-files"""
__magic_name__ = json.load(open(hf_hub_download(A_, A_, repo_type="""dataset""" ), """r""" ) )
__magic_name__ = {int(A_ ) + 1: v for k, v in idalabel.items()}
__magic_name__ = """background"""
__magic_name__ = idalabel
__magic_name__ = {v: k for k, v in idalabel.items()}
return config
def a__ ( ):
'''simple docstring'''
__magic_name__ = """http://images.cocodataset.org/val2017/000000039769.jpg"""
__magic_name__ = Image.open(requests.get(A_, stream=A_ ).raw )
return im
@torch.no_grad()
def a__ ( A_, A_, A_, A_=False ):
'''simple docstring'''
__magic_name__ = get_mobilenet_va_config(A_ )
# Load 🤗 model
__magic_name__ = MobileNetVaForImageClassification(A_ ).eval()
# Load weights from TensorFlow checkpoint
load_tf_weights_in_mobilenet_va(A_, A_, A_ )
# Check outputs on an image, prepared by MobileNetV1ImageProcessor
__magic_name__ = MobileNetVaImageProcessor(
crop_size={"""width""": config.image_size, """height""": config.image_size}, size={"""shortest_edge""": config.image_size + 32}, )
__magic_name__ = image_processor(images=prepare_img(), return_tensors="""pt""" )
__magic_name__ = model(**A_ )
__magic_name__ = outputs.logits
assert logits.shape == (1, 1001)
if model_name == "mobilenet_v1_1.0_224":
__magic_name__ = torch.tensor([-4.1739, -1.1233, 3.1205] )
elif model_name == "mobilenet_v1_0.75_192":
__magic_name__ = torch.tensor([-3.9440, -2.3141, -0.3333] )
else:
__magic_name__ = None
if expected_logits is not None:
assert torch.allclose(logits[0, :3], A_, atol=1e-4 )
Path(A_ ).mkdir(exist_ok=A_ )
print(f'''Saving model {model_name} to {pytorch_dump_folder_path}''' )
model.save_pretrained(A_ )
print(f'''Saving image processor to {pytorch_dump_folder_path}''' )
image_processor.save_pretrained(A_ )
if push_to_hub:
print("""Pushing to the hub...""" )
__magic_name__ = """google/""" + model_name
image_processor.push_to_hub(A_ )
model.push_to_hub(A_ )
if __name__ == "__main__":
__lowerCAmelCase : str = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--model_name',
default='mobilenet_v1_1.0_224',
type=str,
help='Name of the MobileNetV1 model you\'d like to convert. Should in the form \'mobilenet_v1_<depth>_<size>\'.',
)
parser.add_argument(
'--checkpoint_path', required=True, type=str, help='Path to the original TensorFlow checkpoint (.ckpt file).'
)
parser.add_argument(
'--pytorch_dump_folder_path', required=True, type=str, help='Path to the output PyTorch model directory.'
)
parser.add_argument(
'--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.'
)
__lowerCAmelCase : str = parser.parse_args()
convert_movilevit_checkpoint(
args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub
)
| 76 | 0 |
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
__lowerCAmelCase : Any = logging.get_logger(__name__)
@dataclass
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = [
"""no_inference""",
"""no_cuda""",
"""no_tpu""",
"""no_speed""",
"""no_memory""",
"""no_env_print""",
"""no_multi_process""",
]
def __init__( self : Optional[Any] , **UpperCamelCase__ : Tuple ) -> int:
"""simple docstring"""
for deprecated_arg in self.deprecated_args:
if deprecated_arg in kwargs:
__magic_name__ = deprecated_arg[3:]
__magic_name__ = not kwargs.pop(UpperCamelCase__ )
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__(**UpperCamelCase__ )
a__ = field(
default=_A , metadata={"""help""": """Name of TPU"""} , )
a__ = field(
default=0 , metadata={"""help""": """CPU / GPU device index. Defaults to 0."""} , )
a__ = field(default=_A , metadata={"""help""": """Benchmark models in eager model."""} )
a__ = field(
default=_A , metadata={
"""help""": """Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`."""
} , )
@cached_property
def _lowercase ( self : List[Any] ) -> Tuple["tf.distribute.cluster_resolver.TPUClusterResolver"]:
"""simple docstring"""
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 _lowercase ( self : int ) -> Tuple["tf.distribute.Strategy", "tf.distribute.cluster_resolver.TPUClusterResolver"]:
"""simple docstring"""
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 _lowercase ( self : Union[str, Any] ) -> bool:
"""simple docstring"""
requires_backends(self , ["""tf"""] )
return self._setup_tpu is not None
@property
def _lowercase ( self : int ) -> "tf.distribute.Strategy":
"""simple docstring"""
requires_backends(self , ["""tf"""] )
return self._setup_strategy
@property
def _lowercase ( self : Optional[Any] ) -> List[str]:
"""simple docstring"""
requires_backends(self , ["""tf"""] )
return tf.config.list_physical_devices("""GPU""" )
@property
def _lowercase ( self : int ) -> int:
"""simple docstring"""
requires_backends(self , ["""tf"""] )
if self.cuda:
return len(self.gpu_list )
return 0
@property
def _lowercase ( self : Dict ) -> bool:
"""simple docstring"""
return self.n_gpu > 0
| 708 |
import collections
import importlib.util
import os
import re
from pathlib import Path
__lowerCAmelCase : int = 'src/transformers'
# Matches is_xxx_available()
__lowerCAmelCase : Optional[int] = re.compile(R'is\_([a-z_]*)_available()')
# Catches a one-line _import_struct = {xxx}
__lowerCAmelCase : Dict = re.compile(R'^_import_structure\s+=\s+\{([^\}]+)\}')
# Catches a line with a key-values pattern: "bla": ["foo", "bar"]
__lowerCAmelCase : int = re.compile(R'\s+"\S*":\s+\[([^\]]*)\]')
# Catches a line if not is_foo_available
__lowerCAmelCase : Optional[Any] = re.compile(R'^\s*if\s+not\s+is\_[a-z_]*\_available\(\)')
# Catches a line _import_struct["bla"].append("foo")
__lowerCAmelCase : Optional[Any] = re.compile(R'^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)')
# Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"]
__lowerCAmelCase : Dict = re.compile(R'^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]')
# Catches a line with an object between quotes and a comma: "MyModel",
__lowerCAmelCase : List[str] = re.compile('^\s+"([^"]+)",')
# Catches a line with objects between brackets only: ["foo", "bar"],
__lowerCAmelCase : Optional[int] = re.compile('^\s+\[([^\]]+)\]')
# Catches a line with from foo import bar, bla, boo
__lowerCAmelCase : List[str] = re.compile(R'\s+from\s+\S*\s+import\s+([^\(\s].*)\n')
# Catches a line with try:
__lowerCAmelCase : int = re.compile(R'^\s*try:')
# Catches a line with else:
__lowerCAmelCase : Tuple = re.compile(R'^\s*else:')
def a__ ( A_ ):
'''simple docstring'''
if _re_test_backend.search(A_ ) is None:
return None
__magic_name__ = [b[0] for b in _re_backend.findall(A_ )]
backends.sort()
return "_and_".join(A_ )
def a__ ( A_ ):
'''simple docstring'''
with open(A_, """r""", encoding="""utf-8""", newline="""\n""" ) as f:
__magic_name__ = f.readlines()
__magic_name__ = 0
while line_index < len(A_ ) and not lines[line_index].startswith("""_import_structure = {""" ):
line_index += 1
# If this is a traditional init, just return.
if line_index >= len(A_ ):
return None
# First grab the objects without a specific backend in _import_structure
__magic_name__ = []
while not lines[line_index].startswith("""if TYPE_CHECKING""" ) and find_backend(lines[line_index] ) is None:
__magic_name__ = lines[line_index]
# If we have everything on a single line, let's deal with it.
if _re_one_line_import_struct.search(A_ ):
__magic_name__ = _re_one_line_import_struct.search(A_ ).groups()[0]
__magic_name__ = re.findall("""\[([^\]]+)\]""", A_ )
for imp in imports:
objects.extend([obj[1:-1] for obj in imp.split(""", """ )] )
line_index += 1
continue
__magic_name__ = _re_import_struct_key_value.search(A_ )
if single_line_import_search is not None:
__magic_name__ = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(""", """ ) if len(A_ ) > 0]
objects.extend(A_ )
elif line.startswith(""" """ * 8 + """\"""" ):
objects.append(line[9:-3] )
line_index += 1
__magic_name__ = {"""none""": objects}
# Let's continue with backend-specific objects in _import_structure
while not lines[line_index].startswith("""if TYPE_CHECKING""" ):
# If the line is an if not is_backend_available, we grab all objects associated.
__magic_name__ = find_backend(lines[line_index] )
# Check if the backend declaration is inside a try block:
if _re_try.search(lines[line_index - 1] ) is None:
__magic_name__ = None
if backend is not None:
line_index += 1
# Scroll until we hit the else block of try-except-else
while _re_else.search(lines[line_index] ) is None:
line_index += 1
line_index += 1
__magic_name__ = []
# Until we unindent, add backend objects to the list
while len(lines[line_index] ) <= 1 or lines[line_index].startswith(""" """ * 4 ):
__magic_name__ = lines[line_index]
if _re_import_struct_add_one.search(A_ ) is not None:
objects.append(_re_import_struct_add_one.search(A_ ).groups()[0] )
elif _re_import_struct_add_many.search(A_ ) is not None:
__magic_name__ = _re_import_struct_add_many.search(A_ ).groups()[0].split(""", """ )
__magic_name__ = [obj[1:-1] for obj in imports if len(A_ ) > 0]
objects.extend(A_ )
elif _re_between_brackets.search(A_ ) is not None:
__magic_name__ = _re_between_brackets.search(A_ ).groups()[0].split(""", """ )
__magic_name__ = [obj[1:-1] for obj in imports if len(A_ ) > 0]
objects.extend(A_ )
elif _re_quote_object.search(A_ ) is not None:
objects.append(_re_quote_object.search(A_ ).groups()[0] )
elif line.startswith(""" """ * 8 + """\"""" ):
objects.append(line[9:-3] )
elif line.startswith(""" """ * 12 + """\"""" ):
objects.append(line[13:-3] )
line_index += 1
__magic_name__ = objects
else:
line_index += 1
# At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend
__magic_name__ = []
while (
line_index < len(A_ )
and find_backend(lines[line_index] ) is None
and not lines[line_index].startswith("""else""" )
):
__magic_name__ = lines[line_index]
__magic_name__ = _re_import.search(A_ )
if single_line_import_search is not None:
objects.extend(single_line_import_search.groups()[0].split(""", """ ) )
elif line.startswith(""" """ * 8 ):
objects.append(line[8:-2] )
line_index += 1
__magic_name__ = {"""none""": objects}
# Let's continue with backend-specific objects
while line_index < len(A_ ):
# If the line is an if is_backend_available, we grab all objects associated.
__magic_name__ = find_backend(lines[line_index] )
# Check if the backend declaration is inside a try block:
if _re_try.search(lines[line_index - 1] ) is None:
__magic_name__ = None
if backend is not None:
line_index += 1
# Scroll until we hit the else block of try-except-else
while _re_else.search(lines[line_index] ) is None:
line_index += 1
line_index += 1
__magic_name__ = []
# Until we unindent, add backend objects to the list
while len(lines[line_index] ) <= 1 or lines[line_index].startswith(""" """ * 8 ):
__magic_name__ = lines[line_index]
__magic_name__ = _re_import.search(A_ )
if single_line_import_search is not None:
objects.extend(single_line_import_search.groups()[0].split(""", """ ) )
elif line.startswith(""" """ * 12 ):
objects.append(line[12:-2] )
line_index += 1
__magic_name__ = objects
else:
line_index += 1
return import_dict_objects, type_hint_objects
def a__ ( A_, A_ ):
'''simple docstring'''
def find_duplicates(A_ ):
return [k for k, v in collections.Counter(A_ ).items() if v > 1]
if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ):
return ["Both sides of the init do not have the same backends!"]
__magic_name__ = []
for key in import_dict_objects.keys():
__magic_name__ = find_duplicates(import_dict_objects[key] )
if duplicate_imports:
errors.append(f'''Duplicate _import_structure definitions for: {duplicate_imports}''' )
__magic_name__ = find_duplicates(type_hint_objects[key] )
if duplicate_type_hints:
errors.append(f'''Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}''' )
if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ):
__magic_name__ = """base imports""" if key == """none""" else f'''{key} backend'''
errors.append(f'''Differences for {name}:''' )
for a in type_hint_objects[key]:
if a not in import_dict_objects[key]:
errors.append(f''' {a} in TYPE_HINT but not in _import_structure.''' )
for a in import_dict_objects[key]:
if a not in type_hint_objects[key]:
errors.append(f''' {a} in _import_structure but not in TYPE_HINT.''' )
return errors
def a__ ( ):
'''simple docstring'''
__magic_name__ = []
for root, _, files in os.walk(A_ ):
if "__init__.py" in files:
__magic_name__ = os.path.join(A_, """__init__.py""" )
__magic_name__ = parse_init(A_ )
if objects is not None:
__magic_name__ = analyze_results(*A_ )
if len(A_ ) > 0:
__magic_name__ = f'''Problem in {fname}, both halves do not define the same objects.\n{errors[0]}'''
failures.append("""\n""".join(A_ ) )
if len(A_ ) > 0:
raise ValueError("""\n\n""".join(A_ ) )
def a__ ( ):
'''simple docstring'''
__magic_name__ = []
for path, directories, files in os.walk(A_ ):
for folder in directories:
# Ignore private modules
if folder.startswith("""_""" ):
directories.remove(A_ )
continue
# Ignore leftovers from branches (empty folders apart from pycache)
if len(list((Path(A_ ) / folder).glob("""*.py""" ) ) ) == 0:
continue
__magic_name__ = str((Path(A_ ) / folder).relative_to(A_ ) )
__magic_name__ = short_path.replace(os.path.sep, """.""" )
submodules.append(A_ )
for fname in files:
if fname == "__init__.py":
continue
__magic_name__ = str((Path(A_ ) / fname).relative_to(A_ ) )
__magic_name__ = short_path.replace(""".py""", """""" ).replace(os.path.sep, """.""" )
if len(submodule.split(""".""" ) ) == 1:
submodules.append(A_ )
return submodules
__lowerCAmelCase : Dict = [
'convert_pytorch_checkpoint_to_tf2',
'modeling_flax_pytorch_utils',
]
def a__ ( ):
'''simple docstring'''
__magic_name__ = importlib.util.spec_from_file_location(
"""transformers""", os.path.join(A_, """__init__.py""" ), submodule_search_locations=[PATH_TO_TRANSFORMERS], )
__magic_name__ = spec.loader.load_module()
__magic_name__ = [
module
for module in get_transformers_submodules()
if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys()
]
if len(A_ ) > 0:
__magic_name__ = """\n""".join(f'''- {module}''' for module in module_not_registered )
raise ValueError(
"""The following submodules are not properly registered in the main init of Transformers:\n"""
f'''{list_of_modules}\n'''
"""Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.""" )
if __name__ == "__main__":
check_all_inits()
check_submodules()
| 76 | 0 |
from __future__ import annotations
from math import gcd
def a__ ( A_, A_ = 2, A_ = 1, A_ = 3, ):
'''simple docstring'''
if num < 2:
raise ValueError("""The input value cannot be less than 2""" )
# Because of the relationship between ``f(f(x))`` and ``f(x)``, this
# algorithm struggles to find factors that are divisible by two.
# As a workaround, we specifically check for two and even inputs.
# See: https://math.stackexchange.com/a/2856214/165820
if num > 2 and num % 2 == 0:
return 2
# Pollard's Rho algorithm requires a function that returns pseudorandom
# values between 0 <= X < ``num``. It doesn't need to be random in the
# sense that the output value is cryptographically secure or difficult
# to calculate, it only needs to be random in the sense that all output
# values should be equally likely to appear.
# For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num``
# However, the success of Pollard's algorithm isn't guaranteed and is
# determined in part by the initial seed and the chosen random function.
# To make retries easier, we will instead use ``f(x) = (x**2 + C) % num``
# where ``C`` is a value that we can modify between each attempt.
def rand_fn(A_, A_, A_ ) -> int:
return (pow(A_, 2 ) + step) % modulus
for _ in range(A_ ):
# These track the position within the cycle detection logic.
__magic_name__ = seed
__magic_name__ = seed
while True:
# At each iteration, the tortoise moves one step and the hare moves two.
__magic_name__ = rand_fn(A_, A_, A_ )
__magic_name__ = rand_fn(A_, A_, A_ )
__magic_name__ = rand_fn(A_, A_, A_ )
# At some point both the tortoise and the hare will enter a cycle whose
# length ``p`` is a divisor of ``num``. Once in that cycle, at some point
# the tortoise and hare will end up on the same value modulo ``p``.
# We can detect when this happens because the position difference between
# the tortoise and the hare will share a common divisor with ``num``.
__magic_name__ = gcd(hare - tortoise, A_ )
if divisor == 1:
# No common divisor yet, just keep searching.
continue
else:
# We found a common divisor!
if divisor == num:
# Unfortunately, the divisor is ``num`` itself and is useless.
break
else:
# The divisor is a nontrivial factor of ``num``!
return divisor
# If we made it here, then this attempt failed.
# We need to pick a new starting seed for the tortoise and hare
# in addition to a new step value for the random function.
# To keep this example implementation deterministic, the
# new values will be generated based on currently available
# values instead of using something like ``random.randint``.
# We can use the hare's position as the new seed.
# This is actually what Richard Brent's the "optimized" variant does.
__magic_name__ = hare
# The new step value for the random function can just be incremented.
# At first the results will be similar to what the old function would
# have produced, but the value will quickly diverge after a bit.
step += 1
# We haven't found a divisor within the requested number of attempts.
# We were unlucky or ``num`` itself is actually prime.
return None
if __name__ == "__main__":
import argparse
__lowerCAmelCase : str = argparse.ArgumentParser()
parser.add_argument(
'num',
type=int,
help='The value to find a divisor of',
)
parser.add_argument(
'--attempts',
type=int,
default=3,
help='The number of attempts before giving up',
)
__lowerCAmelCase : Dict = parser.parse_args()
__lowerCAmelCase : List[Any] = pollard_rho(args.num, attempts=args.attempts)
if divisor is None:
print(F'''{args.num} is probably prime''')
else:
__lowerCAmelCase : Tuple = args.num // divisor
print(F'''{args.num} = {divisor} * {quotient}''')
| 709 |
import functools
import operator
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__lowerCAmelCase : Optional[Any] = logging.get_logger(__name__)
__lowerCAmelCase : List[Any] = {
'asapp/sew-d-tiny-100k': 'https://huggingface.co/asapp/sew-d-tiny-100k/resolve/main/config.json',
# See all SEW-D models at https://huggingface.co/models?filter=sew-d
}
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = """sew-d"""
def __init__( self : List[str] , UpperCamelCase__ : Tuple=32 , UpperCamelCase__ : Optional[int]=768 , UpperCamelCase__ : Tuple=12 , UpperCamelCase__ : Optional[Any]=12 , UpperCamelCase__ : int=3072 , UpperCamelCase__ : Tuple=2 , UpperCamelCase__ : List[Any]=512 , UpperCamelCase__ : Any=256 , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : Dict=True , UpperCamelCase__ : str=("p2c", "c2p") , UpperCamelCase__ : List[Any]="layer_norm" , UpperCamelCase__ : int="gelu_python" , UpperCamelCase__ : Optional[int]=0.1 , UpperCamelCase__ : Tuple=0.1 , UpperCamelCase__ : List[Any]=0.1 , UpperCamelCase__ : int=0.0 , UpperCamelCase__ : Dict=0.1 , UpperCamelCase__ : List[Any]=0.02 , UpperCamelCase__ : Optional[int]=1E-7 , UpperCamelCase__ : List[Any]=1E-5 , UpperCamelCase__ : List[str]="group" , UpperCamelCase__ : Optional[int]="gelu" , UpperCamelCase__ : Tuple=(64, 128, 128, 128, 128, 256, 256, 256, 256, 512, 512, 512, 512) , UpperCamelCase__ : str=(5, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1) , UpperCamelCase__ : Optional[Any]=(10, 3, 1, 3, 1, 3, 1, 3, 1, 2, 1, 2, 1) , UpperCamelCase__ : Optional[Any]=False , UpperCamelCase__ : Optional[int]=128 , UpperCamelCase__ : Tuple=16 , UpperCamelCase__ : Optional[int]=True , UpperCamelCase__ : Dict=0.05 , UpperCamelCase__ : str=10 , UpperCamelCase__ : Tuple=2 , UpperCamelCase__ : Dict=0.0 , UpperCamelCase__ : Dict=10 , UpperCamelCase__ : Union[str, Any]=0 , UpperCamelCase__ : List[Any]="mean" , UpperCamelCase__ : int=False , UpperCamelCase__ : Optional[int]=False , UpperCamelCase__ : Optional[int]=256 , UpperCamelCase__ : List[str]=0 , UpperCamelCase__ : Union[str, Any]=1 , UpperCamelCase__ : List[Any]=2 , **UpperCamelCase__ : str , ) -> Dict:
"""simple docstring"""
super().__init__(**UpperCamelCase__ , pad_token_id=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ )
__magic_name__ = hidden_size
__magic_name__ = feat_extract_norm
__magic_name__ = feat_extract_activation
__magic_name__ = list(UpperCamelCase__ )
__magic_name__ = list(UpperCamelCase__ )
__magic_name__ = list(UpperCamelCase__ )
__magic_name__ = conv_bias
__magic_name__ = num_conv_pos_embeddings
__magic_name__ = num_conv_pos_embedding_groups
__magic_name__ = len(self.conv_dim )
__magic_name__ = num_hidden_layers
__magic_name__ = intermediate_size
__magic_name__ = squeeze_factor
__magic_name__ = max_position_embeddings
__magic_name__ = position_buckets
__magic_name__ = share_att_key
__magic_name__ = relative_attention
__magic_name__ = norm_rel_ebd
__magic_name__ = list(UpperCamelCase__ )
__magic_name__ = hidden_act
__magic_name__ = num_attention_heads
__magic_name__ = hidden_dropout
__magic_name__ = attention_dropout
__magic_name__ = activation_dropout
__magic_name__ = feat_proj_dropout
__magic_name__ = final_dropout
__magic_name__ = layer_norm_eps
__magic_name__ = feature_layer_norm_eps
__magic_name__ = initializer_range
__magic_name__ = vocab_size
if (
(len(self.conv_stride ) != self.num_feat_extract_layers)
or (len(self.conv_kernel ) != self.num_feat_extract_layers)
or (len(self.conv_dim ) != self.num_feat_extract_layers)
):
raise ValueError(
"""Configuration for convolutional layers is incorrect."""
"""It is required that `len(config.conv_dim)` == `len(config.conv_stride)` == `len(config.conv_kernel)`,"""
F'''but is `len(config.conv_dim) = {len(self.conv_dim )}`, `len(config.conv_stride)'''
F'''= {len(self.conv_stride )}`, `len(config.conv_kernel) = {len(self.conv_kernel )}`.''' )
# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
__magic_name__ = apply_spec_augment
__magic_name__ = mask_time_prob
__magic_name__ = mask_time_length
__magic_name__ = mask_time_min_masks
__magic_name__ = mask_feature_prob
__magic_name__ = mask_feature_length
__magic_name__ = mask_feature_min_masks
# ctc loss
__magic_name__ = ctc_loss_reduction
__magic_name__ = ctc_zero_infinity
# sequence classification
__magic_name__ = use_weighted_layer_sum
__magic_name__ = classifier_proj_size
@property
def _lowercase ( self : Union[str, Any] ) -> str:
"""simple docstring"""
return functools.reduce(operator.mul , self.conv_stride , 1 )
| 76 | 0 |
import os
from collections import namedtuple
import pytest
from datasets import ClassLabel, Features, Sequence, Value
from datasets.commands.test import TestCommand
from datasets.info import DatasetInfo, DatasetInfosDict
__lowerCAmelCase : str = namedtuple(
'_TestCommandArgs',
[
'dataset',
'name',
'cache_dir',
'data_dir',
'all_configs',
'save_infos',
'ignore_verifications',
'force_redownload',
'clear_cache',
],
defaults=[None, None, None, False, False, False, False, False],
)
def a__ ( A_, A_ ):
'''simple docstring'''
return (abs(source - target ) / target) < 0.01
@pytest.mark.integration
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = _TestCommandArgs(dataset=A_, all_configs=A_, save_infos=A_ )
__magic_name__ = TestCommand(*A_ )
test_command.run()
__magic_name__ = os.path.join(A_, """README.md""" )
assert os.path.exists(A_ )
__magic_name__ = DatasetInfosDict.from_directory(A_ )
__magic_name__ = DatasetInfosDict(
{
"""default""": DatasetInfo(
features=Features(
{
"""tokens""": Sequence(Value("""string""" ) ),
"""ner_tags""": Sequence(
ClassLabel(names=["""O""", """B-PER""", """I-PER""", """B-ORG""", """I-ORG""", """B-LOC""", """I-LOC"""] ) ),
"""langs""": Sequence(Value("""string""" ) ),
"""spans""": Sequence(Value("""string""" ) ),
} ), splits=[
{
"""name""": """train""",
"""num_bytes""": 2351563,
"""num_examples""": 10000,
},
{
"""name""": """validation""",
"""num_bytes""": 238418,
"""num_examples""": 1000,
},
], download_size=3940680, dataset_size=2589981, )
} )
assert dataset_infos.keys() == expected_dataset_infos.keys()
for key in DatasetInfo._INCLUDED_INFO_IN_YAML:
__magic_name__ , __magic_name__ = getattr(dataset_infos["""default"""], A_ ), getattr(expected_dataset_infos["""default"""], A_ )
if key == "num_bytes":
assert is_apercent_close(A_, A_ )
elif key == "splits":
assert list(A_ ) == list(A_ )
for split in result:
assert result[split].name == expected[split].name
assert result[split].num_examples == expected[split].num_examples
assert is_apercent_close(result[split].num_bytes, expected[split].num_bytes )
else:
result == expected
| 710 |
import math
import random
def a__ ( A_, A_ = False ):
'''simple docstring'''
if deriv:
return value * (1 - value)
return 1 / (1 + math.exp(-value ))
# Initial Value
__lowerCAmelCase : Union[str, Any] = 0.02
def a__ ( A_, A_ ):
'''simple docstring'''
__magic_name__ = float(2 * (random.randint(1, 100 )) - 1 )
for _ in range(A_ ):
# Forward propagation
__magic_name__ = sigmoid_function(INITIAL_VALUE * weight )
# How much did we miss?
__magic_name__ = (expected / 100) - layer_a
# Error delta
__magic_name__ = layer_1_error * sigmoid_function(A_, A_ )
# Update weight
weight += INITIAL_VALUE * layer_1_delta
return layer_a * 100
if __name__ == "__main__":
import doctest
doctest.testmod()
__lowerCAmelCase : List[Any] = int(input('Expected value: '))
__lowerCAmelCase : Tuple = int(input('Number of propagations: '))
print(forward_propagation(expected, number_propagations))
| 76 | 0 |
import json
import re
from typing import TYPE_CHECKING, List, Optional, Tuple, Union
import numpy as np
from ...utils import is_tf_available, is_torch_available, logging
if TYPE_CHECKING:
if is_torch_available():
import torch
if is_tf_available():
import tensorflow as tf
from tokenizers import pre_tokenizers
from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from .tokenization_codegen import CodeGenTokenizer
__lowerCAmelCase : Dict = logging.get_logger(__name__)
__lowerCAmelCase : List[Any] = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'}
__lowerCAmelCase : Dict = {
'vocab_file': {
'Salesforce/codegen-350M-mono': 'https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/vocab.json',
},
'merges_file': {
'Salesforce/codegen-350M-mono': 'https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/merges.txt',
},
'tokenizer_file': {
'Salesforce/codegen-350M-mono': (
'https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/tokenizer.json'
),
},
}
__lowerCAmelCase : Optional[int] = {
'Salesforce/codegen-350M-mono': 2048,
}
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = VOCAB_FILES_NAMES
a__ = PRETRAINED_VOCAB_FILES_MAP
a__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
a__ = ["""input_ids""", """attention_mask"""]
a__ = CodeGenTokenizer
def __init__( self : Tuple , UpperCamelCase__ : Optional[int]=None , UpperCamelCase__ : Any=None , UpperCamelCase__ : Tuple=None , UpperCamelCase__ : List[Any]="<|endoftext|>" , UpperCamelCase__ : str="<|endoftext|>" , UpperCamelCase__ : List[Any]="<|endoftext|>" , UpperCamelCase__ : Tuple=False , **UpperCamelCase__ : Union[str, Any] , ) -> Tuple:
"""simple docstring"""
super().__init__(
UpperCamelCase__ , UpperCamelCase__ , tokenizer_file=UpperCamelCase__ , unk_token=UpperCamelCase__ , bos_token=UpperCamelCase__ , eos_token=UpperCamelCase__ , add_prefix_space=UpperCamelCase__ , **UpperCamelCase__ , )
if kwargs.pop("""add_bos_token""" , UpperCamelCase__ ):
__magic_name__ = kwargs.pop("""name_or_path""" , """""" )
raise ValueError(
"""Currenty GPT2's fast tokenizer does NOT support adding a BOS token."""
"""Instead you should use GPT2's slow tokenizer class `CodeGenTokenizer` as follows: \n"""
F'''`CodeGenTokenizer.from_pretrained(\'{model_id}\')`\nor\n'''
F'''`AutoTokenizer.from_pretrained(\'{model_id}\', use_fast=False)`\n'''
"""This issue will be fixed soon, see: https://github.com/huggingface/tokenizers/pull/1005."""
""" so that the fast tokenizer works correctly.""" )
__magic_name__ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() )
if pre_tok_state.get("""add_prefix_space""" , UpperCamelCase__ ) != add_prefix_space:
__magic_name__ = getattr(UpperCamelCase__ , pre_tok_state.pop("""type""" ) )
__magic_name__ = add_prefix_space
__magic_name__ = pre_tok_class(**UpperCamelCase__ )
__magic_name__ = add_prefix_space
def _lowercase ( self : Optional[Any] , *UpperCamelCase__ : Optional[int] , **UpperCamelCase__ : Optional[int] ) -> BatchEncoding:
"""simple docstring"""
__magic_name__ = kwargs.get("""is_split_into_words""" , UpperCamelCase__ )
assert self.add_prefix_space or not is_split_into_words, (
F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True '''
"to use it with pretokenized inputs."
)
return super()._batch_encode_plus(*UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : Optional[int] , *UpperCamelCase__ : List[Any] , **UpperCamelCase__ : List[Any] ) -> BatchEncoding:
"""simple docstring"""
__magic_name__ = kwargs.get("""is_split_into_words""" , UpperCamelCase__ )
assert self.add_prefix_space or not is_split_into_words, (
F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True '''
"to use it with pretokenized inputs."
)
return super()._encode_plus(*UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : List[Any] , UpperCamelCase__ : str , UpperCamelCase__ : Optional[str] = None ) -> Tuple[str]:
"""simple docstring"""
__magic_name__ = self._tokenizer.model.save(UpperCamelCase__ , name=UpperCamelCase__ )
return tuple(UpperCamelCase__ )
def _lowercase ( self : str , UpperCamelCase__ : Union[int, List[int], "np.ndarray", "torch.Tensor", "tf.Tensor"] , UpperCamelCase__ : bool = False , UpperCamelCase__ : bool = None , UpperCamelCase__ : Optional[List[str]] = None , **UpperCamelCase__ : Optional[Any] , ) -> str:
"""simple docstring"""
__magic_name__ = super().decode(
token_ids=UpperCamelCase__ , skip_special_tokens=UpperCamelCase__ , clean_up_tokenization_spaces=UpperCamelCase__ , **UpperCamelCase__ , )
if truncate_before_pattern is not None and len(UpperCamelCase__ ) > 0:
__magic_name__ = self.truncate(UpperCamelCase__ , UpperCamelCase__ )
return decoded_text
def _lowercase ( self : int , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[Any] ) -> List[str]:
"""simple docstring"""
def find_re(UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[Any] ):
__magic_name__ = pattern.search(UpperCamelCase__ , UpperCamelCase__ )
return m.start() if m else -1
__magic_name__ = [re.compile(UpperCamelCase__ , re.MULTILINE ) for pattern in truncate_before_pattern]
__magic_name__ = list(re.finditer("""^print""" , UpperCamelCase__ , re.MULTILINE ) )
if len(UpperCamelCase__ ) > 1:
__magic_name__ = completion[: prints[1].start()]
__magic_name__ = list(re.finditer("""^def""" , UpperCamelCase__ , re.MULTILINE ) )
if len(UpperCamelCase__ ) > 1:
__magic_name__ = completion[: defs[1].start()]
__magic_name__ = 0
__magic_name__ = [
pos for pos in [find_re(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) for terminal in terminals] if pos != -1
]
if len(UpperCamelCase__ ) > 0:
return completion[: min(UpperCamelCase__ )]
else:
return completion
| 711 |
import os
import sys
__lowerCAmelCase : Optional[Any] = os.path.join(os.path.dirname(__file__), 'src')
sys.path.append(SRC_DIR)
from transformers import (
AutoConfig,
AutoModel,
AutoModelForCausalLM,
AutoModelForMaskedLM,
AutoModelForQuestionAnswering,
AutoModelForSequenceClassification,
AutoTokenizer,
add_start_docstrings,
)
__lowerCAmelCase : Union[str, Any] = [
'torch',
'numpy',
'tokenizers',
'filelock',
'requests',
'tqdm',
'regex',
'sentencepiece',
'sacremoses',
'importlib_metadata',
'huggingface_hub',
]
@add_start_docstrings(AutoConfig.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoConfig.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoTokenizer.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoTokenizer.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoModel.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoModel.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoModelForCausalLM.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoModelForCausalLM.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoModelForMaskedLM.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoModelForMaskedLM.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoModelForSequenceClassification.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoModelForSequenceClassification.from_pretrained(*A_, **A_ )
@add_start_docstrings(AutoModelForQuestionAnswering.__doc__ )
def a__ ( *A_, **A_ ):
'''simple docstring'''
return AutoModelForQuestionAnswering.from_pretrained(*A_, **A_ )
| 76 | 0 |
'''simple docstring'''
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union
import pyarrow as pa
if TYPE_CHECKING:
from .features import FeatureType
@dataclass
class UpperCAmelCase_ :
'''simple docstring'''
a__ = 42
a__ = None
# Automatically constructed
a__ = """dict"""
a__ = None
a__ = field(default="""Translation""" , init=_A , repr=_A )
def __call__( self : Union[str, Any] ) -> Optional[int]:
"""simple docstring"""
return pa.struct({lang: pa.string() for lang in sorted(self.languages )} )
def _lowercase ( self : Optional[int] ) -> Union["FeatureType", Dict[str, "FeatureType"]]:
"""simple docstring"""
from .features import Value
return {k: Value("""string""" ) for k in sorted(self.languages )}
@dataclass
class UpperCAmelCase_ :
'''simple docstring'''
a__ = None
a__ = None
a__ = None
# Automatically constructed
a__ = """dict"""
a__ = None
a__ = field(default="""TranslationVariableLanguages""" , init=_A , repr=_A )
def _lowercase ( self : Union[str, Any] ) -> List[Any]:
"""simple docstring"""
__magic_name__ = sorted(set(self.languages ) ) if self.languages else None
__magic_name__ = len(self.languages ) if self.languages else None
def __call__( self : List[str] ) -> Dict:
"""simple docstring"""
return pa.struct({"""language""": pa.list_(pa.string() ), """translation""": pa.list_(pa.string() )} )
def _lowercase ( self : Optional[int] , UpperCamelCase__ : Optional[int] ) -> List[Any]:
"""simple docstring"""
__magic_name__ = set(self.languages )
if self.languages and set(UpperCamelCase__ ) - lang_set:
raise ValueError(
F'''Some languages in example ({', '.join(sorted(set(UpperCamelCase__ ) - lang_set ) )}) are not in valid set ({', '.join(UpperCamelCase__ )}).''' )
# Convert dictionary into tuples, splitting out cases where there are
# multiple translations for a single language.
__magic_name__ = []
for lang, text in translation_dict.items():
if isinstance(UpperCamelCase__ , UpperCamelCase__ ):
translation_tuples.append((lang, text) )
else:
translation_tuples.extend([(lang, el) for el in text] )
# Ensure translations are in ascending order by language code.
__magic_name__ , __magic_name__ = zip(*sorted(UpperCamelCase__ ) )
return {"language": languages, "translation": translations}
def _lowercase ( self : List[str] ) -> Union["FeatureType", Dict[str, "FeatureType"]]:
"""simple docstring"""
from .features import Sequence, Value
return {
"language": Sequence(Value("""string""" ) ),
"translation": Sequence(Value("""string""" ) ),
}
| 712 |
from typing import Dict
from .base import GenericTensor, Pipeline
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
def _lowercase ( self : List[Any] , UpperCamelCase__ : List[Any]=None , UpperCamelCase__ : Union[str, Any]=None , UpperCamelCase__ : Any=None , **UpperCamelCase__ : Dict ) -> str:
"""simple docstring"""
if tokenize_kwargs is None:
__magic_name__ = {}
if truncation is not None:
if "truncation" in tokenize_kwargs:
raise ValueError(
"""truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)""" )
__magic_name__ = truncation
__magic_name__ = tokenize_kwargs
__magic_name__ = {}
if return_tensors is not None:
__magic_name__ = return_tensors
return preprocess_params, {}, postprocess_params
def _lowercase ( self : int , UpperCamelCase__ : int , **UpperCamelCase__ : int ) -> Dict[str, GenericTensor]:
"""simple docstring"""
__magic_name__ = self.framework
__magic_name__ = self.tokenizer(UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ )
return model_inputs
def _lowercase ( self : str , UpperCamelCase__ : Dict ) -> str:
"""simple docstring"""
__magic_name__ = self.model(**UpperCamelCase__ )
return model_outputs
def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : List[str]=False ) -> List[str]:
"""simple docstring"""
if return_tensors:
return model_outputs[0]
if self.framework == "pt":
return model_outputs[0].tolist()
elif self.framework == "tf":
return model_outputs[0].numpy().tolist()
def __call__( self : List[str] , *UpperCamelCase__ : List[Any] , **UpperCamelCase__ : List[Any] ) -> Dict:
"""simple docstring"""
return super().__call__(*UpperCamelCase__ , **UpperCamelCase__ )
| 76 | 0 |
import numpy as np
def a__ ( A_, A_ ):
'''simple docstring'''
return np.where(vector > 0, A_, (alpha * (np.exp(A_ ) - 1)) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 713 |
import argparse
import math
import os
from copy import deepcopy
import torch
from audio_diffusion.models import DiffusionAttnUnetaD
from diffusion import sampling
from torch import nn
from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNetaDModel
__lowerCAmelCase : str = {
'gwf-440k': {
'url': 'https://model-server.zqevans2.workers.dev/gwf-440k.ckpt',
'sample_rate': 48000,
'sample_size': 65536,
},
'jmann-small-190k': {
'url': 'https://model-server.zqevans2.workers.dev/jmann-small-190k.ckpt',
'sample_rate': 48000,
'sample_size': 65536,
},
'jmann-large-580k': {
'url': 'https://model-server.zqevans2.workers.dev/jmann-large-580k.ckpt',
'sample_rate': 48000,
'sample_size': 131072,
},
'maestro-uncond-150k': {
'url': 'https://model-server.zqevans2.workers.dev/maestro-uncond-150k.ckpt',
'sample_rate': 16000,
'sample_size': 65536,
},
'unlocked-uncond-250k': {
'url': 'https://model-server.zqevans2.workers.dev/unlocked-uncond-250k.ckpt',
'sample_rate': 16000,
'sample_size': 65536,
},
'honk-140k': {
'url': 'https://model-server.zqevans2.workers.dev/honk-140k.ckpt',
'sample_rate': 16000,
'sample_size': 65536,
},
}
def a__ ( A_, A_ ):
'''simple docstring'''
return torch.atana(A_, A_ ) / math.pi * 2
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = torch.sin(t * math.pi / 2 ) ** 2
__magic_name__ = (1 - sigma**2) ** 0.5
return alpha_sigma_to_t(A_, A_ )
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
pass
class UpperCAmelCase_ ( nn.Module ):
'''simple docstring'''
def __init__( self : Tuple , UpperCamelCase__ : str ) -> Optional[Any]:
"""simple docstring"""
super().__init__()
__magic_name__ = DiffusionAttnUnetaD(UpperCamelCase__ , n_attn_layers=4 )
__magic_name__ = deepcopy(self.diffusion )
__magic_name__ = torch.quasirandom.SobolEngine(1 , scramble=UpperCamelCase__ )
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = MODELS_MAP[model_name]["""url"""]
os.system(f'''wget {url} ./''' )
return f'''./{model_name}.ckpt'''
__lowerCAmelCase : Optional[int] = {
'1': 'resnets.0',
'2': 'attentions.0',
'3': 'resnets.1',
'4': 'attentions.1',
'5': 'resnets.2',
'6': 'attentions.2',
}
__lowerCAmelCase : Optional[Any] = {
'8': 'resnets.0',
'9': 'attentions.0',
'10': 'resnets.1',
'11': 'attentions.1',
'12': 'resnets.2',
'13': 'attentions.2',
}
__lowerCAmelCase : Union[str, Any] = {
'1': 'resnets.0',
'2': 'attentions.0',
'3': 'resnets.1',
'4': 'attentions.1',
'5': 'resnets.2',
'6': 'attentions.2',
'8': 'resnets.3',
'9': 'attentions.3',
'10': 'resnets.4',
'11': 'attentions.4',
'12': 'resnets.5',
'13': 'attentions.5',
}
__lowerCAmelCase : int = {
'0': 'resnets.0',
'1': 'resnets.1',
'2': 'resnets.2',
'4': 'resnets.0',
'5': 'resnets.1',
'6': 'resnets.2',
}
__lowerCAmelCase : List[str] = {
'skip': 'conv_skip',
'main.0': 'conv_1',
'main.1': 'group_norm_1',
'main.3': 'conv_2',
'main.4': 'group_norm_2',
}
__lowerCAmelCase : int = {
'norm': 'group_norm',
'qkv_proj': ['query', 'key', 'value'],
'out_proj': ['proj_attn'],
}
def a__ ( A_ ):
'''simple docstring'''
if name.startswith("""skip""" ):
return name.replace("""skip""", RES_CONV_MAP["""skip"""] )
# name has to be of format main.{digit}
if not name.startswith("""main.""" ):
raise ValueError(f'''ResConvBlock error with {name}''' )
return name.replace(name[:6], RES_CONV_MAP[name[:6]] )
def a__ ( A_ ):
'''simple docstring'''
for key, value in ATTN_MAP.items():
if name.startswith(A_ ) and not isinstance(A_, A_ ):
return name.replace(A_, A_ )
elif name.startswith(A_ ):
return [name.replace(A_, A_ ) for v in value]
raise ValueError(f'''Attn error with {name}''' )
def a__ ( A_, A_=13 ):
'''simple docstring'''
__magic_name__ = input_string
if string.split(""".""" )[0] == "timestep_embed":
return string.replace("""timestep_embed""", """time_proj""" )
__magic_name__ = 0
if string.startswith("""net.3.""" ):
depth += 1
__magic_name__ = string[6:]
elif string.startswith("""net.""" ):
__magic_name__ = string[4:]
while string.startswith("""main.7.""" ):
depth += 1
__magic_name__ = string[7:]
if string.startswith("""main.""" ):
__magic_name__ = string[5:]
# mid block
if string[:2].isdigit():
__magic_name__ = string[:2]
__magic_name__ = string[2:]
else:
__magic_name__ = string[0]
__magic_name__ = string[1:]
if depth == max_depth:
__magic_name__ = MID_NUM_TO_LAYER[layer_num]
__magic_name__ = """mid_block"""
elif depth > 0 and int(A_ ) < 7:
__magic_name__ = DOWN_NUM_TO_LAYER[layer_num]
__magic_name__ = f'''down_blocks.{depth}'''
elif depth > 0 and int(A_ ) > 7:
__magic_name__ = UP_NUM_TO_LAYER[layer_num]
__magic_name__ = f'''up_blocks.{max_depth - depth - 1}'''
elif depth == 0:
__magic_name__ = DEPTH_0_TO_LAYER[layer_num]
__magic_name__ = f'''up_blocks.{max_depth - 1}''' if int(A_ ) > 3 else """down_blocks.0"""
if not string_left.startswith(""".""" ):
raise ValueError(f'''Naming error with {input_string} and string_left: {string_left}.''' )
__magic_name__ = string_left[1:]
if "resnets" in new_layer:
__magic_name__ = convert_resconv_naming(A_ )
elif "attentions" in new_layer:
__magic_name__ = convert_attn_naming(A_ )
__magic_name__ = new_string_left
if not isinstance(A_, A_ ):
__magic_name__ = prefix + """.""" + new_layer + """.""" + string_left
else:
__magic_name__ = [prefix + """.""" + new_layer + """.""" + s for s in string_left]
return new_string
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = {}
for k, v in state_dict.items():
if k.endswith("""kernel""" ):
# up- and downsample layers, don't have trainable weights
continue
__magic_name__ = rename(A_ )
# check if we need to transform from Conv => Linear for attention
if isinstance(A_, A_ ):
__magic_name__ = transform_conv_attns(A_, A_, A_ )
else:
__magic_name__ = v
return new_state_dict
def a__ ( A_, A_, A_ ):
'''simple docstring'''
if len(A_ ) == 1:
if len(v.shape ) == 3:
# weight
__magic_name__ = v[:, :, 0]
else:
# bias
__magic_name__ = v
else:
# qkv matrices
__magic_name__ = v.shape[0]
__magic_name__ = trippled_shape // 3
for i in range(3 ):
if len(v.shape ) == 3:
__magic_name__ = v[i * single_shape : (i + 1) * single_shape, :, 0]
else:
__magic_name__ = v[i * single_shape : (i + 1) * single_shape]
return new_state_dict
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" )
__magic_name__ = args.model_path.split("""/""" )[-1].split(""".""" )[0]
if not os.path.isfile(args.model_path ):
assert (
model_name == args.model_path
), f'''Make sure to provide one of the official model names {MODELS_MAP.keys()}'''
__magic_name__ = download(A_ )
__magic_name__ = MODELS_MAP[model_name]["""sample_rate"""]
__magic_name__ = MODELS_MAP[model_name]["""sample_size"""]
__magic_name__ = Object()
__magic_name__ = sample_size
__magic_name__ = sample_rate
__magic_name__ = 0
__magic_name__ = UNetaDModel(sample_size=A_, sample_rate=A_ )
__magic_name__ = diffusers_model.state_dict()
__magic_name__ = DiffusionUncond(A_ )
orig_model.load_state_dict(torch.load(args.model_path, map_location=A_ )["""state_dict"""] )
__magic_name__ = orig_model.diffusion_ema.eval()
__magic_name__ = orig_model.state_dict()
__magic_name__ = rename_orig_weights(A_ )
__magic_name__ = set(renamed_state_dict.keys() ) - set(diffusers_state_dict.keys() )
__magic_name__ = set(diffusers_state_dict.keys() ) - set(renamed_state_dict.keys() )
assert len(A_ ) == 0, f'''Problem with {renamed_minus_diffusers}'''
assert all(k.endswith("""kernel""" ) for k in list(A_ ) ), f'''Problem with {diffusers_minus_renamed}'''
for key, value in renamed_state_dict.items():
assert (
diffusers_state_dict[key].squeeze().shape == value.squeeze().shape
), f'''Shape for {key} doesn\'t match. Diffusers: {diffusers_state_dict[key].shape} vs. {value.shape}'''
if key == "time_proj.weight":
__magic_name__ = value.squeeze()
__magic_name__ = value
diffusers_model.load_state_dict(A_ )
__magic_name__ = 100
__magic_name__ = 33
__magic_name__ = IPNDMScheduler(num_train_timesteps=A_ )
__magic_name__ = torch.manual_seed(A_ )
__magic_name__ = torch.randn([1, 2, config.sample_size], generator=A_ ).to(A_ )
__magic_name__ = torch.linspace(1, 0, steps + 1, device=A_ )[:-1]
__magic_name__ = get_crash_schedule(A_ )
__magic_name__ = DanceDiffusionPipeline(unet=A_, scheduler=A_ )
__magic_name__ = torch.manual_seed(33 )
__magic_name__ = pipe(num_inference_steps=A_, generator=A_ ).audios
__magic_name__ = sampling.iplms_sample(A_, A_, A_, {} )
__magic_name__ = generated.clamp(-1, 1 )
__magic_name__ = (generated - audio).abs().sum()
__magic_name__ = (generated - audio).abs().max()
if args.save:
pipe.save_pretrained(args.checkpoint_path )
print("""Diff sum""", A_ )
print("""Diff max""", A_ )
assert diff_max < 1e-3, f'''Diff max: {diff_max} is too much :-/'''
print(f'''Conversion for {model_name} successful!''' )
if __name__ == "__main__":
__lowerCAmelCase : Optional[int] = argparse.ArgumentParser()
parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.')
parser.add_argument(
'--save', default=True, type=bool, required=False, help='Whether to save the converted model or not.'
)
parser.add_argument('--checkpoint_path', default=None, type=str, required=True, help='Path to the output model.')
__lowerCAmelCase : Union[str, Any] = parser.parse_args()
main(args)
| 76 | 0 |
import math
import tensorflow as tf
from packaging import version
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = tf.convert_to_tensor(A_ )
__magic_name__ = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0 ), x.dtype ) ))
return x * cdf
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = tf.convert_to_tensor(A_ )
__magic_name__ = tf.cast(math.pi, x.dtype )
__magic_name__ = tf.cast(0.044715, x.dtype )
__magic_name__ = 0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi ) * (x + coeff * tf.pow(A_, 3 )) ))
return x * cdf
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = tf.convert_to_tensor(A_ )
return x * tf.tanh(tf.math.softplus(A_ ) )
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = tf.convert_to_tensor(A_ )
__magic_name__ = tf.cast(0.044715, x.dtype )
__magic_name__ = tf.cast(0.7978845608, x.dtype )
return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x) ))
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = tf.convert_to_tensor(A_ )
__magic_name__ = tf.cast(1.702, x.dtype )
return x * tf.math.sigmoid(coeff * x )
def a__ ( A_ ):
'''simple docstring'''
return tf.clip_by_value(_gelu(A_ ), -10, 10 )
def a__ ( A_, A_=-1 ):
'''simple docstring'''
__magic_name__ , __magic_name__ = tf.split(A_, 2, axis=A_ )
return a * tf.math.sigmoid(A_ )
if version.parse(tf.version.VERSION) >= version.parse('2.4'):
def a__ ( A_ ):
'''simple docstring'''
return tf.keras.activations.gelu(A_, approximate=A_ )
__lowerCAmelCase : List[str] = tf.keras.activations.gelu
__lowerCAmelCase : str = approximate_gelu_wrap
else:
__lowerCAmelCase : Dict = _gelu
__lowerCAmelCase : List[Any] = _gelu_new
__lowerCAmelCase : Optional[int] = {
'gelu': gelu,
'gelu_10': gelu_aa,
'gelu_fast': gelu_fast,
'gelu_new': gelu_new,
'glu': glu,
'mish': mish,
'quick_gelu': quick_gelu,
'relu': tf.keras.activations.relu,
'sigmoid': tf.keras.activations.sigmoid,
'silu': tf.keras.activations.swish,
'swish': tf.keras.activations.swish,
'tanh': tf.keras.activations.tanh,
}
def a__ ( A_ ):
'''simple docstring'''
if activation_string in ACTaFN:
return ACTaFN[activation_string]
else:
raise KeyError(f'''function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}''' )
| 714 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__lowerCAmelCase : Tuple = logging.get_logger(__name__)
__lowerCAmelCase : Tuple = {
'SCUT-DLVCLab/lilt-roberta-en-base': (
'https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json'
),
}
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = """lilt"""
def __init__( self : Dict , UpperCamelCase__ : List[str]=3_0522 , UpperCamelCase__ : Optional[Any]=768 , UpperCamelCase__ : Dict=12 , UpperCamelCase__ : Optional[Any]=12 , UpperCamelCase__ : Dict=3072 , UpperCamelCase__ : Tuple="gelu" , UpperCamelCase__ : int=0.1 , UpperCamelCase__ : Dict=0.1 , UpperCamelCase__ : Union[str, Any]=512 , UpperCamelCase__ : Dict=2 , UpperCamelCase__ : Dict=0.02 , UpperCamelCase__ : Any=1E-12 , UpperCamelCase__ : Optional[int]=0 , UpperCamelCase__ : str="absolute" , UpperCamelCase__ : Any=None , UpperCamelCase__ : Dict=4 , UpperCamelCase__ : Tuple=1024 , **UpperCamelCase__ : Optional[int] , ) -> Dict:
"""simple docstring"""
super().__init__(pad_token_id=UpperCamelCase__ , **UpperCamelCase__ )
__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__ = classifier_dropout
__magic_name__ = channel_shrink_ratio
__magic_name__ = max_ad_position_embeddings
| 76 | 0 |
import unittest
from typing import Dict, List, Optional, Union
import numpy as np
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import BridgeTowerImageProcessor
class UpperCAmelCase_ ( unittest.TestCase ):
'''simple docstring'''
def __init__( self : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : int = 32 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Union[int, float] = 1 / 255 , UpperCamelCase__ : bool = True , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Union[float, List[float]]] = [0.48145466, 0.4578275, 0.40821073] , UpperCamelCase__ : Optional[Union[float, List[float]]] = [0.26862954, 0.26130258, 0.27577711] , UpperCamelCase__ : bool = True , UpperCamelCase__ : Any=7 , UpperCamelCase__ : List[Any]=30 , UpperCamelCase__ : int=400 , UpperCamelCase__ : List[Any]=3 , ) -> str:
"""simple docstring"""
__magic_name__ = parent
__magic_name__ = do_resize
__magic_name__ = size if size is not None else {"""shortest_edge""": 288}
__magic_name__ = size_divisor
__magic_name__ = do_rescale
__magic_name__ = rescale_factor
__magic_name__ = do_normalize
__magic_name__ = do_center_crop
__magic_name__ = image_mean
__magic_name__ = image_std
__magic_name__ = do_pad
__magic_name__ = batch_size
__magic_name__ = num_channels
__magic_name__ = min_resolution
__magic_name__ = max_resolution
def _lowercase ( self : List[Any] ) -> Optional[int]:
"""simple docstring"""
return {
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_normalize": self.do_normalize,
"do_resize": self.do_resize,
"size": self.size,
"size_divisor": self.size_divisor,
}
def _lowercase ( self : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : str=False ) -> Any:
"""simple docstring"""
if not batched:
__magic_name__ = self.size["""shortest_edge"""]
__magic_name__ = image_inputs[0]
if isinstance(UpperCamelCase__ , Image.Image ):
__magic_name__ , __magic_name__ = image.size
else:
__magic_name__ , __magic_name__ = image.shape[1], image.shape[2]
__magic_name__ = size / min(UpperCamelCase__ , UpperCamelCase__ )
if h < w:
__magic_name__ , __magic_name__ = size, scale * w
else:
__magic_name__ , __magic_name__ = scale * h, size
__magic_name__ = int((1333 / 800) * size )
if max(UpperCamelCase__ , UpperCamelCase__ ) > max_size:
__magic_name__ = max_size / max(UpperCamelCase__ , UpperCamelCase__ )
__magic_name__ = newh * scale
__magic_name__ = neww * scale
__magic_name__ , __magic_name__ = int(newh + 0.5 ), int(neww + 0.5 )
__magic_name__ , __magic_name__ = (
newh // self.size_divisor * self.size_divisor,
neww // self.size_divisor * self.size_divisor,
)
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(UpperCamelCase__ , key=lambda UpperCamelCase__ : item[0] )[0]
__magic_name__ = max(UpperCamelCase__ , key=lambda UpperCamelCase__ : item[1] )[1]
return expected_height, expected_width
@require_torch
@require_vision
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = BridgeTowerImageProcessor if is_vision_available() else None
def _lowercase ( self : str ) -> Dict:
"""simple docstring"""
__magic_name__ = BridgeTowerImageProcessingTester(self )
@property
def _lowercase ( self : List[str] ) -> Optional[Any]:
"""simple docstring"""
return self.image_processor_tester.prepare_image_processor_dict()
def _lowercase ( self : Tuple ) -> Dict:
"""simple docstring"""
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(UpperCamelCase__ , """image_mean""" ) )
self.assertTrue(hasattr(UpperCamelCase__ , """image_std""" ) )
self.assertTrue(hasattr(UpperCamelCase__ , """do_normalize""" ) )
self.assertTrue(hasattr(UpperCamelCase__ , """do_resize""" ) )
self.assertTrue(hasattr(UpperCamelCase__ , """size""" ) )
self.assertTrue(hasattr(UpperCamelCase__ , """size_divisor""" ) )
def _lowercase ( self : Union[str, Any] ) -> int:
"""simple docstring"""
pass
def _lowercase ( self : Optional[int] ) -> Tuple:
"""simple docstring"""
__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=UpperCamelCase__ )
for image in image_inputs:
self.assertIsInstance(UpperCamelCase__ , 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(UpperCamelCase__ )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__magic_name__ = image_processing(UpperCamelCase__ , return_tensors="""pt""" ).pixel_values
__magic_name__ , __magic_name__ = self.image_processor_tester.get_expected_values(UpperCamelCase__ , batched=UpperCamelCase__ )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def _lowercase ( self : str ) -> str:
"""simple docstring"""
__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=UpperCamelCase__ , numpify=UpperCamelCase__ )
for image in image_inputs:
self.assertIsInstance(UpperCamelCase__ , 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(UpperCamelCase__ )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__magic_name__ = image_processing(UpperCamelCase__ , return_tensors="""pt""" ).pixel_values
__magic_name__ , __magic_name__ = self.image_processor_tester.get_expected_values(UpperCamelCase__ , batched=UpperCamelCase__ )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def _lowercase ( self : Tuple ) -> Union[str, Any]:
"""simple docstring"""
__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=UpperCamelCase__ , torchify=UpperCamelCase__ )
for image in image_inputs:
self.assertIsInstance(UpperCamelCase__ , 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(UpperCamelCase__ )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__magic_name__ = image_processing(UpperCamelCase__ , return_tensors="""pt""" ).pixel_values
__magic_name__ , __magic_name__ = self.image_processor_tester.get_expected_values(UpperCamelCase__ , batched=UpperCamelCase__ )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
| 715 |
import json
import os
import tempfile
from transformers.testing_utils import check_json_file_has_correct_format
class UpperCAmelCase_ :
'''simple docstring'''
a__ = None
def _lowercase ( self : Optional[int] ) -> str:
"""simple docstring"""
__magic_name__ = self.feature_extraction_class(**self.feat_extract_dict )
__magic_name__ = json.loads(feat_extract.to_json_string() )
for key, value in self.feat_extract_dict.items():
self.assertEqual(obj[key] , UpperCamelCase__ )
def _lowercase ( self : Union[str, Any] ) -> str:
"""simple docstring"""
__magic_name__ = self.feature_extraction_class(**self.feat_extract_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
__magic_name__ = os.path.join(UpperCamelCase__ , """feat_extract.json""" )
feat_extract_first.to_json_file(UpperCamelCase__ )
__magic_name__ = self.feature_extraction_class.from_json_file(UpperCamelCase__ )
self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() )
def _lowercase ( self : str ) -> str:
"""simple docstring"""
__magic_name__ = self.feature_extraction_class(**self.feat_extract_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
__magic_name__ = feat_extract_first.save_pretrained(UpperCamelCase__ )[0]
check_json_file_has_correct_format(UpperCamelCase__ )
__magic_name__ = self.feature_extraction_class.from_pretrained(UpperCamelCase__ )
self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() )
def _lowercase ( self : Optional[int] ) -> Tuple:
"""simple docstring"""
__magic_name__ = self.feature_extraction_class()
self.assertIsNotNone(UpperCamelCase__ )
| 76 | 0 |
import argparse
import os
import re
import numpy as np
import PIL
import torch
from timm import create_model
from torch.optim.lr_scheduler import OneCycleLR
from torch.utils.data import DataLoader, Dataset
from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor
from accelerate import Accelerator
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = fname.split(os.path.sep )[-1]
return re.search(R"""^(.*)_\d+\.jpg$""", A_ ).groups()[0]
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
def __init__( self : List[str] , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[Any]=None , UpperCamelCase__ : Optional[Any]=None ) -> str:
"""simple docstring"""
__magic_name__ = file_names
__magic_name__ = image_transform
__magic_name__ = label_to_id
def __len__( self : str ) -> Tuple:
"""simple docstring"""
return len(self.file_names )
def __getitem__( self : Optional[Any] , UpperCamelCase__ : Any ) -> Tuple:
"""simple docstring"""
__magic_name__ = self.file_names[idx]
__magic_name__ = PIL.Image.open(UpperCamelCase__ )
__magic_name__ = raw_image.convert("""RGB""" )
if self.image_transform is not None:
__magic_name__ = self.image_transform(UpperCamelCase__ )
__magic_name__ = extract_label(UpperCamelCase__ )
if self.label_to_id is not None:
__magic_name__ = self.label_to_id[label]
return {"image": image, "label": label}
def a__ ( A_, A_ ):
'''simple docstring'''
if args.with_tracking:
__magic_name__ = Accelerator(
cpu=args.cpu, mixed_precision=args.mixed_precision, log_with="""all""", project_dir=args.project_dir )
else:
__magic_name__ = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision )
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
__magic_name__ = config["""lr"""]
__magic_name__ = int(config["""num_epochs"""] )
__magic_name__ = int(config["""seed"""] )
__magic_name__ = int(config["""batch_size"""] )
__magic_name__ = config["""image_size"""]
if not isinstance(A_, (list, tuple) ):
__magic_name__ = (image_size, image_size)
# Parse out whether we are saving every epoch or after a certain number of batches
if hasattr(args.checkpointing_steps, """isdigit""" ):
if args.checkpointing_steps == "epoch":
__magic_name__ = args.checkpointing_steps
elif args.checkpointing_steps.isdigit():
__magic_name__ = int(args.checkpointing_steps )
else:
raise ValueError(
f'''Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed.''' )
else:
__magic_name__ = None
# We need to initialize the trackers we use, and also store our configuration
if args.with_tracking:
__magic_name__ = os.path.split(A_ )[-1].split(""".""" )[0]
accelerator.init_trackers(A_, A_ )
# Grab all the image filenames
__magic_name__ = [os.path.join(args.data_dir, A_ ) for fname in os.listdir(args.data_dir ) if fname.endswith(""".jpg""" )]
# Build the label correspondences
__magic_name__ = [extract_label(A_ ) for fname in file_names]
__magic_name__ = list(set(A_ ) )
id_to_label.sort()
__magic_name__ = {lbl: i for i, lbl in enumerate(A_ )}
# Set the seed before splitting the data.
np.random.seed(A_ )
torch.manual_seed(A_ )
torch.cuda.manual_seed_all(A_ )
# Split our filenames between train and validation
__magic_name__ = np.random.permutation(len(A_ ) )
__magic_name__ = int(0.8 * len(A_ ) )
__magic_name__ = random_perm[:cut]
__magic_name__ = random_perm[cut:]
# For training we use a simple RandomResizedCrop
__magic_name__ = Compose([RandomResizedCrop(A_, scale=(0.5, 1.0) ), ToTensor()] )
__magic_name__ = PetsDataset(
[file_names[i] for i in train_split], image_transform=A_, label_to_id=A_ )
# For evaluation, we use a deterministic Resize
__magic_name__ = Compose([Resize(A_ ), ToTensor()] )
__magic_name__ = PetsDataset([file_names[i] for i in eval_split], image_transform=A_, label_to_id=A_ )
# Instantiate dataloaders.
__magic_name__ = DataLoader(A_, shuffle=A_, batch_size=A_, num_workers=4 )
__magic_name__ = DataLoader(A_, shuffle=A_, batch_size=A_, num_workers=4 )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
__magic_name__ = create_model("""resnet50d""", pretrained=A_, num_classes=len(A_ ) )
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
__magic_name__ = model.to(accelerator.device )
# Freezing the base model
for param in model.parameters():
__magic_name__ = False
for param in model.get_classifier().parameters():
__magic_name__ = True
# We normalize the batches of images to be a bit faster.
__magic_name__ = torch.tensor(model.default_cfg["""mean"""] )[None, :, None, None].to(accelerator.device )
__magic_name__ = torch.tensor(model.default_cfg["""std"""] )[None, :, None, None].to(accelerator.device )
# Instantiate optimizer
__magic_name__ = torch.optim.Adam(params=model.parameters(), lr=lr / 25 )
# Instantiate learning rate scheduler
__magic_name__ = OneCycleLR(optimizer=A_, max_lr=A_, epochs=A_, steps_per_epoch=len(A_ ) )
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
__magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__ = accelerator.prepare(
A_, A_, A_, A_, A_ )
# We need to keep track of how many total steps we have iterated over
__magic_name__ = 0
# We also need to keep track of the starting epoch so files are named properly
__magic_name__ = 0
# Potentially load in the weights and states from a previous save
if args.resume_from_checkpoint:
if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
accelerator.print(f'''Resumed from checkpoint: {args.resume_from_checkpoint}''' )
accelerator.load_state(args.resume_from_checkpoint )
__magic_name__ = os.path.basename(args.resume_from_checkpoint )
else:
# Get the most recent checkpoint
__magic_name__ = [f.name for f in os.scandir(os.getcwd() ) if f.is_dir()]
dirs.sort(key=os.path.getctime )
__magic_name__ = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
# Extract `epoch_{i}` or `step_{i}`
__magic_name__ = os.path.splitext(A_ )[0]
if "epoch" in training_difference:
__magic_name__ = int(training_difference.replace("""epoch_""", """""" ) ) + 1
__magic_name__ = None
else:
__magic_name__ = int(training_difference.replace("""step_""", """""" ) )
__magic_name__ = resume_step // len(A_ )
resume_step -= starting_epoch * len(A_ )
# Now we train the model
for epoch in range(A_, A_ ):
model.train()
if args.with_tracking:
__magic_name__ = 0
if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
# We need to skip steps until we reach the resumed step
__magic_name__ = accelerator.skip_first_batches(A_, A_ )
overall_step += resume_step
else:
# After the first iteration though, we need to go back to the original dataloader
__magic_name__ = train_dataloader
for batch in active_dataloader:
# We could avoid this line since we set the accelerator with `device_placement=True`.
__magic_name__ = {k: v.to(accelerator.device ) for k, v in batch.items()}
__magic_name__ = (batch["""image"""] - mean) / std
__magic_name__ = model(A_ )
__magic_name__ = torch.nn.functional.cross_entropy(A_, batch["""label"""] )
# We keep track of the loss at each epoch
if args.with_tracking:
total_loss += loss.detach().float()
accelerator.backward(A_ )
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
overall_step += 1
if isinstance(A_, A_ ):
__magic_name__ = f'''step_{overall_step}'''
if overall_step % checkpointing_steps == 0:
if args.output_dir is not None:
__magic_name__ = os.path.join(args.output_dir, A_ )
accelerator.save_state(A_ )
model.eval()
__magic_name__ = 0
__magic_name__ = 0
for step, batch in enumerate(A_ ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
__magic_name__ = {k: v.to(accelerator.device ) for k, v in batch.items()}
__magic_name__ = (batch["""image"""] - mean) / std
with torch.no_grad():
__magic_name__ = model(A_ )
__magic_name__ = outputs.argmax(dim=-1 )
__magic_name__ , __magic_name__ = accelerator.gather_for_metrics((predictions, batch["""label"""]) )
__magic_name__ = predictions == references
num_elems += accurate_preds.shape[0]
accurate += accurate_preds.long().sum()
__magic_name__ = accurate.item() / num_elems
# Use accelerator.print to print only on the main process.
accelerator.print(f'''epoch {epoch}: {100 * eval_metric:.2f}''' )
if args.with_tracking:
accelerator.log(
{
"""accuracy""": 100 * eval_metric,
"""train_loss""": total_loss.item() / len(A_ ),
"""epoch""": epoch,
}, step=A_, )
if checkpointing_steps == "epoch":
__magic_name__ = f'''epoch_{epoch}'''
if args.output_dir is not None:
__magic_name__ = os.path.join(args.output_dir, A_ )
accelerator.save_state(A_ )
if args.with_tracking:
accelerator.end_training()
def a__ ( ):
'''simple docstring'''
__magic_name__ = argparse.ArgumentParser(description="""Simple example of training script.""" )
parser.add_argument("""--data_dir""", required=A_, help="""The data folder on disk.""" )
parser.add_argument("""--fp16""", action="""store_true""", help="""If passed, will use FP16 training.""" )
parser.add_argument(
"""--mixed_precision""", type=A_, default=A_, choices=["""no""", """fp16""", """bf16""", """fp8"""], help="""Whether to use mixed precision. Choose"""
"""between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."""
"""and an Nvidia Ampere GPU.""", )
parser.add_argument("""--cpu""", action="""store_true""", help="""If passed, will train on the CPU.""" )
parser.add_argument(
"""--checkpointing_steps""", type=A_, default=A_, help="""Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.""", )
parser.add_argument(
"""--output_dir""", type=A_, default=""".""", help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""", )
parser.add_argument(
"""--resume_from_checkpoint""", type=A_, default=A_, help="""If the training should continue from a checkpoint folder.""", )
parser.add_argument(
"""--with_tracking""", action="""store_true""", help="""Whether to load in all available experiment trackers from the environment and use them for logging.""", )
parser.add_argument(
"""--project_dir""", type=A_, default="""logs""", help="""Location on where to store experiment tracking logs` and relevent project information""", )
__magic_name__ = parser.parse_args()
__magic_name__ = {"""lr""": 3e-2, """num_epochs""": 3, """seed""": 42, """batch_size""": 64, """image_size""": 224}
training_function(A_, A_ )
if __name__ == "__main__":
main()
| 716 |
from ..utils import DummyObject, requires_backends
class UpperCAmelCase_ ( metaclass=_A ):
'''simple docstring'''
a__ = ["""note_seq"""]
def __init__( self : Any , *UpperCamelCase__ : str , **UpperCamelCase__ : List[Any] ) -> Optional[int]:
"""simple docstring"""
requires_backends(self , ["""note_seq"""] )
@classmethod
def _lowercase ( cls : str , *UpperCamelCase__ : Dict , **UpperCamelCase__ : Tuple ) -> Dict:
"""simple docstring"""
requires_backends(cls , ["""note_seq"""] )
@classmethod
def _lowercase ( cls : List[str] , *UpperCamelCase__ : Optional[Any] , **UpperCamelCase__ : Tuple ) -> int:
"""simple docstring"""
requires_backends(cls , ["""note_seq"""] )
| 76 | 0 |
from math import ceil
from typing import List, Optional, Union
import numpy as np
from ...audio_utils import mel_filter_bank, spectrogram, window_function
from ...feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor
from ...utils import TensorType, logging
__lowerCAmelCase : List[str] = logging.get_logger(__name__)
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = ["""audio_values""", """audio_mask"""]
def __init__( self : List[str] , UpperCamelCase__ : Union[str, Any]=2048 , UpperCamelCase__ : Optional[Any]=1 , UpperCamelCase__ : Tuple=[16, 16] , UpperCamelCase__ : List[str]=128 , UpperCamelCase__ : Union[str, Any]=4_4100 , UpperCamelCase__ : List[str]=86 , UpperCamelCase__ : str=2048 , UpperCamelCase__ : Optional[Any]=0.0 , **UpperCamelCase__ : List[Any] , ) -> List[str]:
"""simple docstring"""
super().__init__(
feature_size=UpperCamelCase__ , sampling_rate=UpperCamelCase__ , padding_value=UpperCamelCase__ , **UpperCamelCase__ , )
__magic_name__ = spectrogram_length
__magic_name__ = num_channels
__magic_name__ = patch_size
__magic_name__ = feature_size // self.patch_size[1]
__magic_name__ = n_fft
__magic_name__ = sampling_rate // hop_length_to_sampling_rate
__magic_name__ = sampling_rate
__magic_name__ = padding_value
__magic_name__ = mel_filter_bank(
num_frequency_bins=1 + n_fft // 2 , num_mel_filters=UpperCamelCase__ , min_frequency=0.0 , max_frequency=22050.0 , sampling_rate=UpperCamelCase__ , norm="""slaney""" , mel_scale="""slaney""" , ).T
def _lowercase ( self : List[str] , UpperCamelCase__ : np.array ) -> np.ndarray:
"""simple docstring"""
__magic_name__ = spectrogram(
UpperCamelCase__ , window_function(self.n_fft , """hann""" ) , frame_length=self.n_fft , hop_length=self.hop_length , power=2.0 , mel_filters=self.mel_filters.T , log_mel="""dB""" , db_range=80.0 , )
__magic_name__ = log_spec[:, :-1]
__magic_name__ = log_spec - 20.0
__magic_name__ = np.clip(log_spec / 40.0 , -2.0 , 0.0 ) + 1.0
return log_spec
def __call__( self : Union[str, Any] , UpperCamelCase__ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , UpperCamelCase__ : Optional[bool] = True , UpperCamelCase__ : Optional[int] = None , UpperCamelCase__ : bool = False , UpperCamelCase__ : bool = False , **UpperCamelCase__ : Dict , ) -> BatchFeature:
"""simple docstring"""
if sampling_rate is not None:
if sampling_rate != self.sampling_rate:
raise ValueError(
"""This feature extractor is set to support sampling rate"""
F''' of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled'''
F''' 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(UpperCamelCase__ , 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(UpperCamelCase__ , (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(UpperCamelCase__ , np.ndarray ):
__magic_name__ = np.asarray(UpperCamelCase__ , dtype=np.floataa )
elif isinstance(UpperCamelCase__ , 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]
# Convert audio signals to log mel spectrograms, truncate by time axis
__magic_name__ = [
self._np_extract_fbank_features(waveform.squeeze() ).T[: self.spectrogram_length] for waveform in raw_speech
]
if isinstance(audio_features[0] , UpperCamelCase__ ):
__magic_name__ = [np.asarray(UpperCamelCase__ , dtype=np.floataa ) for feature in audio_features]
# Create audio attention mask
__magic_name__ = max(
[ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len for feature in audio_features] ) # The maximum number of audio patches in a batch
if return_attention_mask:
__magic_name__ = [
(ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [1]
+ (max_patch_len - ceil(feature.shape[0] / self.patch_size[0] ) * self.freq_len) * [0]
for feature in audio_features
]
__magic_name__ = np.array(UpperCamelCase__ ).astype(np.floataa )
# convert into correct format for padding
__magic_name__ = max_patch_len // self.freq_len * self.patch_size[0] # The maximum audio size in a batch
__magic_name__ = np.ones([len(UpperCamelCase__ ), 1, max_time_len, self.feature_size] ).astype(np.floataa )
__magic_name__ = padded_audio_features * self.padding_value
for i in range(len(UpperCamelCase__ ) ):
__magic_name__ = audio_features[i]
__magic_name__ = feature
# return as BatchFeature
if return_attention_mask:
__magic_name__ = {"""audio_values""": padded_audio_features, """audio_mask""": audio_mask}
else:
__magic_name__ = {"""audio_values""": padded_audio_features}
__magic_name__ = BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ )
return encoded_inputs
| 717 |
def a__ ( A_ ):
'''simple docstring'''
return " ".join(
"""""".join(word[::-1] ) if len(A_ ) > 4 else word for word in sentence.split() )
if __name__ == "__main__":
import doctest
doctest.testmod()
print(reverse_long_words('Hey wollef sroirraw'))
| 76 | 0 |
import os
import re
import sys
import traceback
import warnings
from pathlib import Path
from typing import Dict, Optional, Union
from uuid import uuida
from huggingface_hub import HfFolder, ModelCard, ModelCardData, hf_hub_download, whoami
from huggingface_hub.file_download import REGEX_COMMIT_HASH
from huggingface_hub.utils import (
EntryNotFoundError,
RepositoryNotFoundError,
RevisionNotFoundError,
is_jinja_available,
)
from packaging import version
from requests import HTTPError
from .. import __version__
from .constants import (
DEPRECATED_REVISION_ARGS,
DIFFUSERS_CACHE,
HUGGINGFACE_CO_RESOLVE_ENDPOINT,
SAFETENSORS_WEIGHTS_NAME,
WEIGHTS_NAME,
)
from .import_utils import (
ENV_VARS_TRUE_VALUES,
_flax_version,
_jax_version,
_onnxruntime_version,
_torch_version,
is_flax_available,
is_onnx_available,
is_torch_available,
)
from .logging import get_logger
__lowerCAmelCase : Dict = get_logger(__name__)
__lowerCAmelCase : Union[str, Any] = Path(__file__).parent / 'model_card_template.md'
__lowerCAmelCase : Optional[int] = uuida().hex
__lowerCAmelCase : str = os.getenv('HF_HUB_OFFLINE', '').upper() in ENV_VARS_TRUE_VALUES
__lowerCAmelCase : Dict = os.getenv('DISABLE_TELEMETRY', '').upper() in ENV_VARS_TRUE_VALUES
__lowerCAmelCase : Any = HUGGINGFACE_CO_RESOLVE_ENDPOINT + '/api/telemetry/'
def a__ ( A_ = None ):
'''simple docstring'''
__magic_name__ = f'''diffusers/{__version__}; python/{sys.version.split()[0]}; session_id/{SESSION_ID}'''
if DISABLE_TELEMETRY or HF_HUB_OFFLINE:
return ua + "; telemetry/off"
if is_torch_available():
ua += f'''; torch/{_torch_version}'''
if is_flax_available():
ua += f'''; jax/{_jax_version}'''
ua += f'''; flax/{_flax_version}'''
if is_onnx_available():
ua += f'''; onnxruntime/{_onnxruntime_version}'''
# CI will set this value to True
if os.environ.get("""DIFFUSERS_IS_CI""", """""" ).upper() in ENV_VARS_TRUE_VALUES:
ua += "; is_ci/true"
if isinstance(A_, A_ ):
ua += "; " + "; ".join(f'''{k}/{v}''' for k, v in user_agent.items() )
elif isinstance(A_, A_ ):
ua += "; " + user_agent
return ua
def a__ ( A_, A_ = None, A_ = None ):
'''simple docstring'''
if token is None:
__magic_name__ = HfFolder.get_token()
if organization is None:
__magic_name__ = whoami(A_ )["""name"""]
return f'''{username}/{model_id}'''
else:
return f'''{organization}/{model_id}'''
def a__ ( A_, A_ ):
'''simple docstring'''
if not is_jinja_available():
raise ValueError(
"""Modelcard rendering is based on Jinja templates."""
""" Please make sure to have `jinja` installed before using `create_model_card`."""
""" To install it, please run `pip install Jinja2`.""" )
if hasattr(A_, """local_rank""" ) and args.local_rank not in [-1, 0]:
return
__magic_name__ = args.hub_token if hasattr(A_, """hub_token""" ) else None
__magic_name__ = get_full_repo_name(A_, token=A_ )
__magic_name__ = ModelCard.from_template(
card_data=ModelCardData( # Card metadata object that will be converted to YAML block
language="""en""", license="""apache-2.0""", library_name="""diffusers""", tags=[], datasets=args.dataset_name, metrics=[], ), template_path=A_, model_name=A_, repo_name=A_, dataset_name=args.dataset_name if hasattr(A_, """dataset_name""" ) else None, learning_rate=args.learning_rate, train_batch_size=args.train_batch_size, eval_batch_size=args.eval_batch_size, gradient_accumulation_steps=(
args.gradient_accumulation_steps if hasattr(A_, """gradient_accumulation_steps""" ) else None
), adam_betaa=args.adam_betaa if hasattr(A_, """adam_beta1""" ) else None, adam_betaa=args.adam_betaa if hasattr(A_, """adam_beta2""" ) else None, adam_weight_decay=args.adam_weight_decay if hasattr(A_, """adam_weight_decay""" ) else None, adam_epsilon=args.adam_epsilon if hasattr(A_, """adam_epsilon""" ) else None, lr_scheduler=args.lr_scheduler if hasattr(A_, """lr_scheduler""" ) else None, lr_warmup_steps=args.lr_warmup_steps if hasattr(A_, """lr_warmup_steps""" ) else None, ema_inv_gamma=args.ema_inv_gamma if hasattr(A_, """ema_inv_gamma""" ) else None, ema_power=args.ema_power if hasattr(A_, """ema_power""" ) else None, ema_max_decay=args.ema_max_decay if hasattr(A_, """ema_max_decay""" ) else None, mixed_precision=args.mixed_precision, )
__magic_name__ = os.path.join(args.output_dir, """README.md""" )
model_card.save(A_ )
def a__ ( A_, A_ = None ):
'''simple docstring'''
if resolved_file is None or commit_hash is not None:
return commit_hash
__magic_name__ = str(Path(A_ ).as_posix() )
__magic_name__ = re.search(R"""snapshots/([^/]+)/""", A_ )
if search is None:
return None
__magic_name__ = search.groups()[0]
return commit_hash if REGEX_COMMIT_HASH.match(A_ ) else None
# Old default cache path, potentially to be migrated.
# This logic was more or less taken from `transformers`, with the following differences:
# - Diffusers doesn't use custom environment variables to specify the cache path.
# - There is no need to migrate the cache format, just move the files to the new location.
__lowerCAmelCase : List[str] = os.path.expanduser(
os.getenv('HF_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'huggingface'))
)
__lowerCAmelCase : str = os.path.join(hf_cache_home, 'diffusers')
def a__ ( A_ = None, A_ = None ):
'''simple docstring'''
if new_cache_dir is None:
__magic_name__ = DIFFUSERS_CACHE
if old_cache_dir is None:
__magic_name__ = old_diffusers_cache
__magic_name__ = Path(A_ ).expanduser()
__magic_name__ = Path(A_ ).expanduser()
for old_blob_path in old_cache_dir.glob("""**/blobs/*""" ):
if old_blob_path.is_file() and not old_blob_path.is_symlink():
__magic_name__ = new_cache_dir / old_blob_path.relative_to(A_ )
new_blob_path.parent.mkdir(parents=A_, exist_ok=A_ )
os.replace(A_, A_ )
try:
os.symlink(A_, A_ )
except OSError:
logger.warning(
"""Could not create symlink between old cache and new cache. If you use an older version of diffusers again, files will be re-downloaded.""" )
# At this point, old_cache_dir contains symlinks to the new cache (it can still be used).
__lowerCAmelCase : Optional[int] = os.path.join(DIFFUSERS_CACHE, 'version_diffusers_cache.txt')
if not os.path.isfile(cache_version_file):
__lowerCAmelCase : Optional[int] = 0
else:
with open(cache_version_file) as f:
try:
__lowerCAmelCase : Optional[int] = int(f.read())
except ValueError:
__lowerCAmelCase : Optional[int] = 0
if cache_version < 1:
__lowerCAmelCase : Dict = os.path.isdir(old_diffusers_cache) and len(os.listdir(old_diffusers_cache)) > 0
if old_cache_is_not_empty:
logger.warning(
'The cache for model files in Diffusers v0.14.0 has moved to a new location. Moving your '
'existing cached models. This is a one-time operation, you can interrupt it or run it '
'later by calling `diffusers.utils.hub_utils.move_cache()`.'
)
try:
move_cache()
except Exception as e:
__lowerCAmelCase : Union[str, Any] = '\n'.join(traceback.format_tb(e.__traceback__))
logger.error(
F'''There was a problem when trying to move your cache:\n\n{trace}\n{e.__class__.__name__}: {e}\n\nPlease '''
'file an issue at https://github.com/huggingface/diffusers/issues/new/choose, copy paste this whole '
'message and we will do our best to help.'
)
if cache_version < 1:
try:
os.makedirs(DIFFUSERS_CACHE, exist_ok=True)
with open(cache_version_file, 'w') as f:
f.write('1')
except Exception:
logger.warning(
F'''There was a problem when trying to write in your cache folder ({DIFFUSERS_CACHE}). Please, ensure '''
'the directory exists and can be written to.'
)
def a__ ( A_, A_ = None ):
'''simple docstring'''
if variant is not None:
__magic_name__ = weights_name.split(""".""" )
__magic_name__ = splits[:-1] + [variant] + splits[-1:]
__magic_name__ = """.""".join(A_ )
return weights_name
def a__ ( A_, *,
A_, A_, A_, A_, A_, A_, A_, A_, A_, A_, A_=None, ):
'''simple docstring'''
__magic_name__ = str(A_ )
if os.path.isfile(A_ ):
return pretrained_model_name_or_path
elif os.path.isdir(A_ ):
if os.path.isfile(os.path.join(A_, A_ ) ):
# Load from a PyTorch checkpoint
__magic_name__ = os.path.join(A_, A_ )
return model_file
elif subfolder is not None and os.path.isfile(
os.path.join(A_, A_, A_ ) ):
__magic_name__ = os.path.join(A_, A_, A_ )
return model_file
else:
raise EnvironmentError(
f'''Error no file named {weights_name} found in directory {pretrained_model_name_or_path}.''' )
else:
# 1. First check if deprecated way of loading from branches is used
if (
revision in DEPRECATED_REVISION_ARGS
and (weights_name == WEIGHTS_NAME or weights_name == SAFETENSORS_WEIGHTS_NAME)
and version.parse(version.parse(A_ ).base_version ) >= version.parse("""0.20.0""" )
):
try:
__magic_name__ = hf_hub_download(
A_, filename=_add_variant(A_, A_ ), cache_dir=A_, force_download=A_, proxies=A_, resume_download=A_, local_files_only=A_, use_auth_token=A_, user_agent=A_, subfolder=A_, revision=revision or commit_hash, )
warnings.warn(
f'''Loading the variant {revision} from {pretrained_model_name_or_path} via `revision=\'{revision}\'` is deprecated. Loading instead from `revision=\'main\'` with `variant={revision}`. Loading model variants via `revision=\'{revision}\'` will be removed in diffusers v1. Please use `variant=\'{revision}\'` instead.''', A_, )
return model_file
except: # noqa: E722
warnings.warn(
f'''You are loading the variant {revision} from {pretrained_model_name_or_path} via `revision=\'{revision}\'`. This behavior is deprecated and will be removed in diffusers v1. One should use `variant=\'{revision}\'` instead. However, it appears that {pretrained_model_name_or_path} currently does not have a {_add_variant(A_, A_ )} file in the \'main\' branch of {pretrained_model_name_or_path}. \n The Diffusers team and community would be very grateful if you could open an issue: https://github.com/huggingface/diffusers/issues/new with the title \'{pretrained_model_name_or_path} is missing {_add_variant(A_, A_ )}\' so that the correct variant file can be added.''', A_, )
try:
# 2. Load model file as usual
__magic_name__ = hf_hub_download(
A_, filename=A_, cache_dir=A_, force_download=A_, proxies=A_, resume_download=A_, local_files_only=A_, use_auth_token=A_, user_agent=A_, subfolder=A_, revision=revision or commit_hash, )
return model_file
except RepositoryNotFoundError:
raise EnvironmentError(
f'''{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier '''
"""listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a """
"""token having permission to this repo with `use_auth_token` or log in with `huggingface-cli """
"""login`.""" )
except RevisionNotFoundError:
raise EnvironmentError(
f'''{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for '''
"""this model name. Check the model page at """
f'''\'https://huggingface.co/{pretrained_model_name_or_path}\' for available revisions.''' )
except EntryNotFoundError:
raise EnvironmentError(
f'''{pretrained_model_name_or_path} does not appear to have a file named {weights_name}.''' )
except HTTPError as err:
raise EnvironmentError(
f'''There was a specific connection error when trying to load {pretrained_model_name_or_path}:\n{err}''' )
except ValueError:
raise EnvironmentError(
f'''We couldn\'t connect to \'{HUGGINGFACE_CO_RESOLVE_ENDPOINT}\' to load this model, couldn\'t find it'''
f''' in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a'''
f''' directory containing a file named {weights_name} or'''
""" \nCheckout your internet connection or see how to run the library in"""
""" offline mode at 'https://huggingface.co/docs/diffusers/installation#offline-mode'.""" )
except EnvironmentError:
raise EnvironmentError(
f'''Can\'t load the model for \'{pretrained_model_name_or_path}\'. If you were trying to load it from '''
"""'https://huggingface.co/models', make sure you don't have a local directory with the same name. """
f'''Otherwise, make sure \'{pretrained_model_name_or_path}\' is the correct path to a directory '''
f'''containing a file named {weights_name}''' )
| 718 |
import os
import unittest
from transformers import FunnelTokenizer, FunnelTokenizerFast
from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class UpperCAmelCase_ ( _A , unittest.TestCase ):
'''simple docstring'''
a__ = FunnelTokenizer
a__ = FunnelTokenizerFast
a__ = True
a__ = True
def _lowercase ( self : List[Any] ) -> str:
"""simple docstring"""
super().setUp()
__magic_name__ = [
"""<unk>""",
"""<cls>""",
"""<sep>""",
"""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] ) )
def _lowercase ( self : Dict , **UpperCamelCase__ : Tuple ) -> Union[str, Any]:
"""simple docstring"""
return FunnelTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase__ )
def _lowercase ( self : str , **UpperCamelCase__ : str ) -> List[str]:
"""simple docstring"""
return FunnelTokenizerFast.from_pretrained(self.tmpdirname , **UpperCamelCase__ )
def _lowercase ( self : List[str] , UpperCamelCase__ : str ) -> List[Any]:
"""simple docstring"""
__magic_name__ = """UNwant\u00E9d,running"""
__magic_name__ = """unwanted, running"""
return input_text, output_text
def _lowercase ( self : Union[str, Any] ) -> Tuple:
"""simple docstring"""
__magic_name__ = self.tokenizer_class(self.vocab_file )
__magic_name__ = tokenizer.tokenize("""UNwant\u00E9d,running""" )
self.assertListEqual(UpperCamelCase__ , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase__ ) , [7, 4, 5, 10, 8, 9] )
def _lowercase ( self : str ) -> List[Any]:
"""simple docstring"""
__magic_name__ = self.get_tokenizers(do_lower_case=UpperCamelCase__ )
for tokenizer in tokenizers:
__magic_name__ = tokenizer("""UNwant\u00E9d,running""" )
__magic_name__ = len(inputs["""input_ids"""] ) - 1
self.assertListEqual(inputs["""token_type_ids"""] , [2] + [0] * sentence_len )
__magic_name__ = tokenizer("""UNwant\u00E9d,running""" , """UNwant\u00E9d,running""" )
self.assertListEqual(inputs["""token_type_ids"""] , [2] + [0] * sentence_len + [1] * sentence_len )
| 76 | 0 |
from functools import lru_cache
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = 2
__magic_name__ = set()
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.add(A_ )
if n > 1:
factors.add(A_ )
return factors
@lru_cache
def a__ ( A_ ):
'''simple docstring'''
return len(unique_prime_factors(A_ ) )
def a__ ( A_ ):
'''simple docstring'''
return len(set(A_ ) ) in (0, 1)
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = 2
while True:
# Increment each value of a generated range
__magic_name__ = [base + i for i in range(A_ )]
# Run elements through out unique_prime_factors function
# Append our target number to the end.
__magic_name__ = [upf_len(A_ ) for x in group]
checker.append(A_ )
# If all numbers in the list are equal, return the group variable.
if equality(A_ ):
return group
# Increment our base variable by 1
base += 1
def a__ ( A_ = 4 ):
'''simple docstring'''
__magic_name__ = run(A_ )
return results[0] if len(A_ ) else None
if __name__ == "__main__":
print(solution())
| 719 |
from collections import deque
from .hash_table import HashTable
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
def __init__( self : int , *UpperCamelCase__ : Union[str, Any] , **UpperCamelCase__ : Optional[Any] ) -> Optional[Any]:
"""simple docstring"""
super().__init__(*UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : Optional[Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Any ) -> Dict:
"""simple docstring"""
__magic_name__ = deque([] ) if self.values[key] is None else self.values[key]
self.values[key].appendleft(UpperCamelCase__ )
__magic_name__ = self.values[key]
def _lowercase ( self : List[str] ) -> int:
"""simple docstring"""
return (
sum(self.charge_factor - len(UpperCamelCase__ ) for slot in self.values )
/ self.size_table
* self.charge_factor
)
def _lowercase ( self : Optional[Any] , UpperCamelCase__ : str , UpperCamelCase__ : Tuple=None ) -> str:
"""simple docstring"""
if not (
len(self.values[key] ) == self.charge_factor and self.values.count(UpperCamelCase__ ) == 0
):
return key
return super()._collision_resolution(UpperCamelCase__ , UpperCamelCase__ )
| 76 | 0 |
import argparse
import os
import re
import torch
from flax.traverse_util import flatten_dict
from tax import checkpoints
from transformers import (
AutoTokenizer,
PixaStructConfig,
PixaStructForConditionalGeneration,
PixaStructImageProcessor,
PixaStructProcessor,
PixaStructTextConfig,
PixaStructVisionConfig,
)
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = checkpoints.load_tax_checkpoint(A_ )
__magic_name__ = flatten_dict(A_ )
return flax_params
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = {}
__magic_name__ = {
"""token_embedder""": """embeddings""",
"""encoder_norm""": """layernorm""",
"""kernel""": """weight""",
""".out""": """.output""",
"""scale""": """weight""",
"""embedders_0.pos_embedding""": """row_embedder.weight""",
"""embedders_1.pos_embedding""": """column_embedder.weight""",
}
__magic_name__ = {
"""query""": """attention.query""",
"""key""": """attention.key""",
"""value""": """attention.value""",
"""output.dense""": """output""",
"""encoder_decoder_attention.o""": """encoder_decoder_attention.attention.o""",
"""pre_self_attention_layer_norm""": """self_attention.layer_norm""",
"""pre_cross_attention_layer_norm""": """encoder_decoder_attention.layer_norm""",
"""mlp.""": """mlp.DenseReluDense.""",
"""pre_mlp_layer_norm""": """mlp.layer_norm""",
"""self_attention.o""": """self_attention.attention.o""",
"""decoder.embeddings.embedding""": """decoder.embed_tokens.weight""",
"""decoder.relpos_bias.rel_embedding""": """decoder.layer.0.self_attention.attention.relative_attention_bias.weight""",
"""decoder.decoder_norm.weight""": """decoder.final_layer_norm.weight""",
"""decoder.logits_dense.weight""": """decoder.lm_head.weight""",
}
for key in flax_dict.keys():
if "target" in key:
# remove the first prefix from the key
__magic_name__ = """.""".join(key[1:] )
# rename the key
for old, new in CONVERSION_MAPPING.items():
__magic_name__ = new_key.replace(A_, A_ )
if "decoder" in new_key:
for old, new in DECODER_CONVERSION_MAPPING.items():
__magic_name__ = new_key.replace(A_, A_ )
if "layers" in new_key and "decoder" not in new_key:
# use regex to replace the layer number
__magic_name__ = re.sub(R"""layers_(\d+)""", R"""layer.\1""", A_ )
__magic_name__ = new_key.replace("""encoder""", """encoder.encoder""" )
elif "layers" in new_key and "decoder" in new_key:
# use regex to replace the layer number
__magic_name__ = re.sub(R"""layers_(\d+)""", R"""layer.\1""", A_ )
__magic_name__ = flax_dict[key]
__magic_name__ = {}
# convert converted_dict into torch format
for key in converted_dict.keys():
if ("embed_tokens" not in key) and ("embedder" not in key):
__magic_name__ = torch.from_numpy(converted_dict[key].T )
else:
__magic_name__ = torch.from_numpy(converted_dict[key] )
return converted_torch_dict
def a__ ( A_, A_, A_=False, A_=False ):
'''simple docstring'''
__magic_name__ = get_flax_param(A_ )
if not use_large:
__magic_name__ = PixaStructVisionConfig()
__magic_name__ = PixaStructTextConfig()
else:
__magic_name__ = PixaStructVisionConfig(
hidden_size=1536, d_ff=3968, num_attention_heads=24, num_hidden_layers=18 )
__magic_name__ = PixaStructTextConfig(hidden_size=1536, d_ff=3968, num_heads=24, num_layers=18 )
__magic_name__ = PixaStructConfig(
vision_config=encoder_config.to_dict(), text_config=decoder_config.to_dict(), is_vqa=A_ )
__magic_name__ = PixaStructForConditionalGeneration(A_ )
__magic_name__ = rename_and_convert_flax_params(A_ )
model.load_state_dict(A_ )
__magic_name__ = AutoTokenizer.from_pretrained("""ybelkada/test-pix2struct-tokenizer""" )
__magic_name__ = PixaStructImageProcessor()
__magic_name__ = PixaStructProcessor(image_processor=A_, tokenizer=A_ )
if use_large:
__magic_name__ = 4096
__magic_name__ = True
# mkdir if needed
os.makedirs(A_, exist_ok=A_ )
model.save_pretrained(A_ )
processor.save_pretrained(A_ )
print("""Model saved in {}""".format(A_ ) )
if __name__ == "__main__":
__lowerCAmelCase : Union[str, Any] = argparse.ArgumentParser()
parser.add_argument('--t5x_checkpoint_path', default=None, type=str, help='Path to the original T5x checkpoint.')
parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.')
parser.add_argument('--use_large', action='store_true', help='Use large model.')
parser.add_argument('--is_vqa', action='store_true', help='Use large model.')
__lowerCAmelCase : Optional[int] = parser.parse_args()
convert_pixastruct_original_pytorch_checkpoint_to_hf(
args.tax_checkpoint_path, args.pytorch_dump_folder_path, args.use_large
)
| 720 |
# 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 json
import os
from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES
from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType
from ...utils.imports import is_botoa_available
from .config_args import SageMakerConfig
from .config_utils import (
DYNAMO_BACKENDS,
_ask_field,
_ask_options,
_convert_dynamo_backend,
_convert_mixed_precision,
_convert_sagemaker_distributed_mode,
_convert_yes_no_to_bool,
)
if is_botoa_available():
import botoa # noqa: F401
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = botoa.client("""iam""" )
__magic_name__ = {
"""Version""": """2012-10-17""",
"""Statement""": [
{"""Effect""": """Allow""", """Principal""": {"""Service""": """sagemaker.amazonaws.com"""}, """Action""": """sts:AssumeRole"""}
],
}
try:
# create the role, associated with the chosen trust policy
iam_client.create_role(
RoleName=A_, AssumeRolePolicyDocument=json.dumps(A_, indent=2 ) )
__magic_name__ = {
"""Version""": """2012-10-17""",
"""Statement""": [
{
"""Effect""": """Allow""",
"""Action""": [
"""sagemaker:*""",
"""ecr:GetDownloadUrlForLayer""",
"""ecr:BatchGetImage""",
"""ecr:BatchCheckLayerAvailability""",
"""ecr:GetAuthorizationToken""",
"""cloudwatch:PutMetricData""",
"""cloudwatch:GetMetricData""",
"""cloudwatch:GetMetricStatistics""",
"""cloudwatch:ListMetrics""",
"""logs:CreateLogGroup""",
"""logs:CreateLogStream""",
"""logs:DescribeLogStreams""",
"""logs:PutLogEvents""",
"""logs:GetLogEvents""",
"""s3:CreateBucket""",
"""s3:ListBucket""",
"""s3:GetBucketLocation""",
"""s3:GetObject""",
"""s3:PutObject""",
],
"""Resource""": """*""",
}
],
}
# attach policy to role
iam_client.put_role_policy(
RoleName=A_, PolicyName=f'''{role_name}_policy_permission''', PolicyDocument=json.dumps(A_, indent=2 ), )
except iam_client.exceptions.EntityAlreadyExistsException:
print(f'''role {role_name} already exists. Using existing one''' )
def a__ ( A_ ):
'''simple docstring'''
__magic_name__ = botoa.client("""iam""" )
return iam_client.get_role(RoleName=A_ )["Role"]["Arn"]
def a__ ( ):
'''simple docstring'''
__magic_name__ = _ask_options(
"""How do you want to authorize?""", ["""AWS Profile""", """Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) """], A_, )
__magic_name__ = None
if credentials_configuration == 0:
__magic_name__ = _ask_field("""Enter your AWS Profile name: [default] """, default="""default""" )
__magic_name__ = aws_profile
else:
print(
"""Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,"""
"""`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`""" )
__magic_name__ = _ask_field("""AWS Access Key ID: """ )
__magic_name__ = aws_access_key_id
__magic_name__ = _ask_field("""AWS Secret Access Key: """ )
__magic_name__ = aws_secret_access_key
__magic_name__ = _ask_field("""Enter your AWS Region: [us-east-1]""", default="""us-east-1""" )
__magic_name__ = aws_region
__magic_name__ = _ask_options(
"""Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?""", ["""Provide IAM Role name""", """Create new IAM role using credentials"""], A_, )
if role_management == 0:
__magic_name__ = _ask_field("""Enter your IAM role name: """ )
else:
__magic_name__ = """accelerate_sagemaker_execution_role"""
print(f'''Accelerate will create an iam role "{iam_role_name}" using the provided credentials''' )
_create_iam_role_for_sagemaker(A_ )
__magic_name__ = _ask_field(
"""Do you want to use custom Docker image? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
__magic_name__ = None
if is_custom_docker_image:
__magic_name__ = _ask_field("""Enter your Docker image: """, lambda A_ : str(A_ ).lower() )
__magic_name__ = _ask_field(
"""Do you want to provide SageMaker input channels with data locations? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
__magic_name__ = None
if is_sagemaker_inputs_enabled:
__magic_name__ = _ask_field(
"""Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): """, lambda A_ : str(A_ ).lower(), )
__magic_name__ = _ask_field(
"""Do you want to enable SageMaker metrics? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
__magic_name__ = None
if is_sagemaker_metrics_enabled:
__magic_name__ = _ask_field(
"""Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): """, lambda A_ : str(A_ ).lower(), )
__magic_name__ = _ask_options(
"""What is the distributed mode?""", ["""No distributed training""", """Data parallelism"""], _convert_sagemaker_distributed_mode, )
__magic_name__ = {}
__magic_name__ = _ask_field(
"""Do you wish to optimize your script with torch dynamo?[yes/NO]:""", _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
if use_dynamo:
__magic_name__ = """dynamo_"""
__magic_name__ = _ask_options(
"""Which dynamo backend would you like to use?""", [x.lower() for x in DYNAMO_BACKENDS], _convert_dynamo_backend, default=2, )
__magic_name__ = _ask_field(
"""Do you want to customize the defaults sent to torch.compile? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
if use_custom_options:
__magic_name__ = _ask_options(
"""Which mode do you want to use?""", A_, lambda A_ : TORCH_DYNAMO_MODES[int(A_ )], default="""default""", )
__magic_name__ = _ask_field(
"""Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
__magic_name__ = _ask_field(
"""Do you want to enable dynamic shape tracing? [yes/NO]: """, _convert_yes_no_to_bool, default=A_, error_message="""Please enter yes or no.""", )
__magic_name__ = """Which EC2 instance type you want to use for your training?"""
if distributed_type != SageMakerDistributedType.NO:
__magic_name__ = _ask_options(
A_, A_, lambda A_ : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(A_ )] )
else:
eca_instance_query += "? [ml.p3.2xlarge]:"
__magic_name__ = _ask_field(A_, lambda A_ : str(A_ ).lower(), default="""ml.p3.2xlarge""" )
__magic_name__ = 1
if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL):
__magic_name__ = _ask_field(
"""How many machines do you want use? [1]: """, A_, default=1, )
__magic_name__ = _ask_options(
"""Do you wish to use FP16 or BF16 (mixed precision)?""", ["""no""", """fp16""", """bf16""", """fp8"""], _convert_mixed_precision, )
if use_dynamo and mixed_precision == "no":
print(
"""Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.""" )
return SageMakerConfig(
image_uri=A_, compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER, distributed_type=A_, use_cpu=A_, dynamo_config=A_, eca_instance_type=A_, profile=A_, region=A_, iam_role_name=A_, mixed_precision=A_, num_machines=A_, sagemaker_inputs_file=A_, sagemaker_metrics_file=A_, )
| 76 | 0 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__lowerCAmelCase : str = logging.get_logger(__name__)
__lowerCAmelCase : Dict = {}
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = """llama"""
a__ = ["""past_key_values"""]
def __init__( self : Dict , UpperCamelCase__ : Dict=3_2000 , UpperCamelCase__ : List[str]=4096 , UpperCamelCase__ : Optional[Any]=1_1008 , UpperCamelCase__ : str=32 , UpperCamelCase__ : int=32 , UpperCamelCase__ : int=None , UpperCamelCase__ : Tuple="silu" , UpperCamelCase__ : List[Any]=2048 , UpperCamelCase__ : List[str]=0.02 , UpperCamelCase__ : Optional[int]=1E-6 , UpperCamelCase__ : Tuple=True , UpperCamelCase__ : Union[str, Any]=0 , UpperCamelCase__ : Dict=1 , UpperCamelCase__ : Any=2 , UpperCamelCase__ : List[Any]=1 , UpperCamelCase__ : Any=False , UpperCamelCase__ : Any=None , **UpperCamelCase__ : str , ) -> str:
"""simple docstring"""
__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=UpperCamelCase__ , bos_token_id=UpperCamelCase__ , eos_token_id=UpperCamelCase__ , tie_word_embeddings=UpperCamelCase__ , **UpperCamelCase__ , )
def _lowercase ( self : Any ) -> int:
"""simple docstring"""
if self.rope_scaling is None:
return
if not isinstance(self.rope_scaling , UpperCamelCase__ ) 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""" , UpperCamelCase__ )
__magic_name__ = self.rope_scaling.get("""factor""" , UpperCamelCase__ )
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(UpperCamelCase__ , UpperCamelCase__ ) or rope_scaling_factor <= 1.0:
raise ValueError(F'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
| 721 |
from typing import Dict, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
convert_to_rgb,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
OPENAI_CLIP_MEAN,
OPENAI_CLIP_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
__lowerCAmelCase : Dict = logging.get_logger(__name__)
if is_vision_available():
import PIL
class UpperCAmelCase_ ( _A ):
'''simple docstring'''
a__ = ["""pixel_values"""]
def __init__( self : Optional[Any] , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : bool = True , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : bool = True , UpperCamelCase__ : Union[int, float] = 1 / 255 , UpperCamelCase__ : bool = True , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : bool = True , **UpperCamelCase__ : int , ) -> None:
"""simple docstring"""
super().__init__(**UpperCamelCase__ )
__magic_name__ = size if size is not None else {"""shortest_edge""": 224}
__magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ )
__magic_name__ = crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
__magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ , param_name="""crop_size""" )
__magic_name__ = do_resize
__magic_name__ = size
__magic_name__ = resample
__magic_name__ = do_center_crop
__magic_name__ = crop_size
__magic_name__ = do_rescale
__magic_name__ = rescale_factor
__magic_name__ = do_normalize
__magic_name__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
__magic_name__ = image_std if image_std is not None else OPENAI_CLIP_STD
__magic_name__ = do_convert_rgb
def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : PILImageResampling = PILImageResampling.BICUBIC , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Tuple , ) -> np.ndarray:
"""simple docstring"""
__magic_name__ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ )
if "shortest_edge" not in size:
raise ValueError(F'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' )
__magic_name__ = get_resize_output_image_size(UpperCamelCase__ , size=size["""shortest_edge"""] , default_to_square=UpperCamelCase__ )
return resize(UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : Tuple , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Dict[str, int] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Tuple , ) -> np.ndarray:
"""simple docstring"""
__magic_name__ = get_size_dict(UpperCamelCase__ )
if "height" not in size or "width" not in size:
raise ValueError(F'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' )
return center_crop(UpperCamelCase__ , size=(size["""height"""], size["""width"""]) , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : Any , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[int, float] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Optional[Any] , ) -> Optional[int]:
"""simple docstring"""
return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : np.ndarray , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Union[float, List[float]] , UpperCamelCase__ : Optional[Union[str, ChannelDimension]] = None , **UpperCamelCase__ : Dict , ) -> np.ndarray:
"""simple docstring"""
return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ )
def _lowercase ( self : List[Any] , UpperCamelCase__ : ImageInput , UpperCamelCase__ : bool = None , UpperCamelCase__ : Dict[str, int] = None , UpperCamelCase__ : PILImageResampling = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : int = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : float = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : Optional[Union[float, List[float]]] = None , UpperCamelCase__ : bool = None , UpperCamelCase__ : Optional[Union[str, TensorType]] = None , UpperCamelCase__ : Optional[ChannelDimension] = ChannelDimension.FIRST , **UpperCamelCase__ : Dict , ) -> PIL.Image.Image:
"""simple docstring"""
__magic_name__ = do_resize if do_resize is not None else self.do_resize
__magic_name__ = size if size is not None else self.size
__magic_name__ = get_size_dict(UpperCamelCase__ , param_name="""size""" , default_to_square=UpperCamelCase__ )
__magic_name__ = resample if resample is not None else self.resample
__magic_name__ = do_center_crop if do_center_crop is not None else self.do_center_crop
__magic_name__ = crop_size if crop_size is not None else self.crop_size
__magic_name__ = get_size_dict(UpperCamelCase__ , param_name="""crop_size""" , default_to_square=UpperCamelCase__ )
__magic_name__ = do_rescale if do_rescale is not None else self.do_rescale
__magic_name__ = rescale_factor if rescale_factor is not None else self.rescale_factor
__magic_name__ = do_normalize if do_normalize is not None else self.do_normalize
__magic_name__ = image_mean if image_mean is not None else self.image_mean
__magic_name__ = image_std if image_std is not None else self.image_std
__magic_name__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
__magic_name__ = make_list_of_images(UpperCamelCase__ )
if not valid_images(UpperCamelCase__ ):
raise ValueError(
"""Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
"""torch.Tensor, tf.Tensor or jax.ndarray.""" )
if do_resize and size is None:
raise ValueError("""Size must be specified if do_resize is True.""" )
if do_center_crop and crop_size is None:
raise ValueError("""Crop size must be specified if do_center_crop is True.""" )
if do_rescale and rescale_factor is None:
raise ValueError("""Rescale factor must be specified if do_rescale is True.""" )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError("""Image mean and std must be specified if do_normalize is True.""" )
# PIL RGBA images are converted to RGB
if do_convert_rgb:
__magic_name__ = [convert_to_rgb(UpperCamelCase__ ) for image in images]
# All transformations expect numpy arrays.
__magic_name__ = [to_numpy_array(UpperCamelCase__ ) for image in images]
if do_resize:
__magic_name__ = [self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) for image in images]
if do_center_crop:
__magic_name__ = [self.center_crop(image=UpperCamelCase__ , size=UpperCamelCase__ ) for image in images]
if do_rescale:
__magic_name__ = [self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) for image in images]
if do_normalize:
__magic_name__ = [self.normalize(image=UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ ) for image in images]
__magic_name__ = [to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) for image in images]
__magic_name__ = {"""pixel_values""": images}
return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ )
| 76 | 0 |
def _SCREAMING_SNAKE_CASE ( a , a ) -> float:
if digit_amount > 0:
return round(number - int(a ) , a )
return number - int(a )
if __name__ == "__main__":
print(decimal_isolate(1.53, 0))
print(decimal_isolate(35.345, 1))
print(decimal_isolate(35.345, 2))
print(decimal_isolate(35.345, 3))
print(decimal_isolate(-14.789, 3))
print(decimal_isolate(0, 2))
print(decimal_isolate(-14.123, 1))
print(decimal_isolate(-14.123, 2))
print(decimal_isolate(-14.123, 3))
| 77 |
# 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 warnings
from typing import List
from unittest.mock import Mock
import torch
from torch.utils.data import DataLoader, IterableDataset, TensorDataset
from accelerate.accelerator import Accelerator
from accelerate.utils.dataclasses import DistributedType
class _A( snake_case__ ):
"""simple docstring"""
def __init__( self , _A ):
__A : Any = data
def __iter__( self ):
for element in self.data:
yield element
def _SCREAMING_SNAKE_CASE ( a=True ) -> Any:
__A : List[Any] = Accelerator(even_batches=a )
assert accelerator.num_processes == 2, "this script expects that two GPUs are available"
return accelerator
def _SCREAMING_SNAKE_CASE ( a , a , a , a = False ) -> str:
if iterable:
__A : int = DummyIterableDataset(torch.as_tensor(range(a ) ) )
else:
__A : Optional[Any] = TensorDataset(torch.as_tensor(range(a ) ) )
__A : Optional[Any] = DataLoader(a , batch_size=a )
__A : Optional[int] = accelerator.prepare(a )
return dl
def _SCREAMING_SNAKE_CASE ( a , a , a , a , a , ) -> Union[str, Any]:
__A : Optional[int] = create_dataloader(accelerator=a , dataset_size=a , batch_size=a )
__A : Tuple = [len(batch[0] ) for batch in dl]
if accelerator.process_index == 0:
assert batch_sizes == process_0_expected_batch_sizes
elif accelerator.process_index == 1:
assert batch_sizes == process_1_expected_batch_sizes
def _SCREAMING_SNAKE_CASE ( ) -> List[Any]:
__A : int = create_accelerator()
# without padding, we would expect a different number of batches
verify_dataloader_batch_sizes(
a , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1, 1] , )
# without padding, we would expect the same number of batches, but different sizes
verify_dataloader_batch_sizes(
a , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 2] , )
def _SCREAMING_SNAKE_CASE ( ) -> List[Any]:
__A : str = create_accelerator(even_batches=a )
verify_dataloader_batch_sizes(
a , dataset_size=3 , batch_size=1 , process_0_expected_batch_sizes=[1, 1] , process_1_expected_batch_sizes=[1] , )
verify_dataloader_batch_sizes(
a , dataset_size=7 , batch_size=2 , process_0_expected_batch_sizes=[2, 2] , process_1_expected_batch_sizes=[2, 1] , )
def _SCREAMING_SNAKE_CASE ( ) -> str:
__A : Optional[Any] = create_accelerator(even_batches=a )
__A : str = torch.nn.Linear(1 , 1 )
__A : Optional[int] = accelerator.prepare(a )
__A : Optional[int] = create_dataloader(a , dataset_size=3 , batch_size=1 )
__A : str = []
with accelerator.join_uneven_inputs([ddp_model] ):
for batch_idx, batch in enumerate(a ):
__A : Dict = ddp_model(batch[0].float() )
__A : List[str] = output.sum()
loss.backward()
batch_idxs.append(a )
accelerator.wait_for_everyone()
if accelerator.process_index == 0:
assert batch_idxs == [0, 1]
elif accelerator.process_index == 1:
assert batch_idxs == [0]
def _SCREAMING_SNAKE_CASE ( a ) -> List[Any]:
with warnings.catch_warnings(record=a ) as w:
with accelerator.join_uneven_inputs([Mock()] ):
pass
assert issubclass(w[-1].category , a )
assert "only supported for multi-GPU" in str(w[-1].message )
def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]:
__A : int = True
__A : Union[str, Any] = False
__A : Optional[int] = create_accelerator(even_batches=a )
__A : int = torch.nn.Linear(1 , 1 )
__A : List[Any] = accelerator.prepare(a )
__A : int = create_dataloader(a , dataset_size=3 , batch_size=1 )
__A : Optional[int] = create_dataloader(a , dataset_size=3 , batch_size=1 )
with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ):
__A : List[str] = train_dl.batch_sampler.even_batches
__A : Dict = valid_dl.batch_sampler.even_batches
assert train_dl_overridden_value == overridden_even_batches
assert valid_dl_overridden_value == overridden_even_batches
assert train_dl.batch_sampler.even_batches == default_even_batches
assert valid_dl.batch_sampler.even_batches == default_even_batches
def _SCREAMING_SNAKE_CASE ( ) -> List[Any]:
__A : Any = True
__A : List[Any] = False
__A : Tuple = create_accelerator(even_batches=a )
__A : List[str] = torch.nn.Linear(1 , 1 )
__A : Optional[Any] = accelerator.prepare(a )
create_dataloader(a , dataset_size=3 , batch_size=1 , iterable=a )
__A : int = create_dataloader(a , dataset_size=3 , batch_size=1 )
with warnings.catch_warnings():
warnings.filterwarnings('ignore' )
try:
with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ):
__A : Tuple = batch_dl.batch_sampler.even_batches
except AttributeError:
# ensure attribute error is not raised when processing iterable dl
raise AssertionError
assert batch_dl_overridden_value == overridden_even_batches
assert batch_dl.batch_sampler.even_batches == default_even_batches
def _SCREAMING_SNAKE_CASE ( ) -> Dict:
__A : Any = create_accelerator()
__A : Union[str, Any] = torch.nn.Linear(1 , 1 )
__A : str = accelerator.prepare(a )
create_dataloader(a , dataset_size=3 , batch_size=1 , iterable=a )
with warnings.catch_warnings(record=a ) as w:
with accelerator.join_uneven_inputs([ddp_model] , even_batches=a ):
pass
assert issubclass(w[-1].category , a )
assert "only supported for map-style datasets" in str(w[-1].message )
def _SCREAMING_SNAKE_CASE ( ) -> List[str]:
__A : str = create_accelerator()
accelerator.print('Test that even_batches variable ensures uniform batches across processes' )
test_default_ensures_even_batch_sizes()
accelerator.print('Run tests with even_batches disabled' )
test_can_disable_even_batches()
accelerator.print('Test joining uneven inputs' )
test_can_join_uneven_inputs()
accelerator.print('Test overriding even_batches when joining uneven inputs' )
test_join_can_override_even_batches()
accelerator.print('Test overriding even_batches for mixed dataloader types' )
test_join_can_override_for_mixed_type_dataloaders()
accelerator.print('Test overriding even_batches raises a warning for iterable dataloaders' )
test_join_raises_warning_for_iterable_when_overriding_even_batches()
accelerator.print('Test join with non DDP distributed raises warning' )
__A : int = accelerator.state.distributed_type
__A : Tuple = DistributedType.FSDP
test_join_raises_warning_for_non_ddp_distributed(a )
__A : str = original_state
if __name__ == "__main__":
main()
| 77 | 1 |
import torch
from diffusers import DiffusionPipeline
class _A( snake_case__ ):
"""simple docstring"""
def __init__( self , _A , _A ):
super().__init__()
self.register_modules(unet=_A , scheduler=_A )
def __call__( self ):
__A : Union[str, Any] = torch.randn(
(1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , )
__A : List[str] = 1
__A : int = self.unet(_A , _A ).sample
__A : Union[str, Any] = self.scheduler.step(_A , _A , _A ).prev_sample
__A : List[str] = scheduler_output - scheduler_output + torch.ones_like(_A )
return result
| 77 |
from collections import OrderedDict
from typing import Any, List, Mapping, Optional
from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import logging
UpperCAmelCase : Dict = logging.get_logger(__name__)
UpperCAmelCase : str = {
'''Salesforce/codegen-350M-nl''': '''https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json''',
'''Salesforce/codegen-350M-multi''': '''https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json''',
'''Salesforce/codegen-350M-mono''': '''https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json''',
'''Salesforce/codegen-2B-nl''': '''https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json''',
'''Salesforce/codegen-2B-multi''': '''https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json''',
'''Salesforce/codegen-2B-mono''': '''https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json''',
'''Salesforce/codegen-6B-nl''': '''https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json''',
'''Salesforce/codegen-6B-multi''': '''https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json''',
'''Salesforce/codegen-6B-mono''': '''https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json''',
'''Salesforce/codegen-16B-nl''': '''https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json''',
'''Salesforce/codegen-16B-multi''': '''https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json''',
'''Salesforce/codegen-16B-mono''': '''https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json''',
}
class _A( snake_case__ ):
"""simple docstring"""
UpperCamelCase : List[str] = '''codegen'''
UpperCamelCase : List[str] = {
'''max_position_embeddings''': '''n_positions''',
'''hidden_size''': '''n_embd''',
'''num_attention_heads''': '''n_head''',
'''num_hidden_layers''': '''n_layer''',
}
def __init__( self , _A=50400 , _A=2048 , _A=2048 , _A=4096 , _A=28 , _A=16 , _A=64 , _A=None , _A="gelu_new" , _A=0.0 , _A=0.0 , _A=0.0 , _A=1e-5 , _A=0.0_2 , _A=True , _A=50256 , _A=50256 , _A=False , **_A , ):
__A : Any = vocab_size
__A : Tuple = n_ctx
__A : Union[str, Any] = n_positions
__A : Optional[Any] = n_embd
__A : Any = n_layer
__A : Dict = n_head
__A : Union[str, Any] = n_inner
__A : List[Any] = rotary_dim
__A : str = activation_function
__A : Any = resid_pdrop
__A : Tuple = embd_pdrop
__A : Tuple = attn_pdrop
__A : Union[str, Any] = layer_norm_epsilon
__A : str = initializer_range
__A : Optional[Any] = use_cache
__A : Union[str, Any] = bos_token_id
__A : Tuple = eos_token_id
super().__init__(
bos_token_id=_A , eos_token_id=_A , tie_word_embeddings=_A , **_A )
class _A( snake_case__ ):
"""simple docstring"""
def __init__( self , _A , _A = "default" , _A = None , _A = False , ):
super().__init__(_A , task=_A , patching_specs=_A , use_past=_A )
if not getattr(self._config , 'pad_token_id' , _A ):
# TODO: how to do that better?
__A : Dict = 0
@property
def UpperCAmelCase_ ( self ):
__A : List[str] = OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}} )
if self.use_past:
self.fill_with_past_key_values_(_A , direction='inputs' )
__A : Tuple = {0: 'batch', 1: 'past_sequence + sequence'}
else:
__A : int = {0: 'batch', 1: 'sequence'}
return common_inputs
@property
def UpperCAmelCase_ ( self ):
return self._config.n_layer
@property
def UpperCAmelCase_ ( self ):
return self._config.n_head
def UpperCAmelCase_ ( self , _A , _A = -1 , _A = -1 , _A = False , _A = None , ):
__A : Any = super(_A , self ).generate_dummy_inputs(
_A , batch_size=_A , seq_length=_A , is_pair=_A , framework=_A )
# We need to order the input in the way they appears in the forward()
__A : str = 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
__A , __A : Any = common_inputs['input_ids'].shape
# Not using the same length for past_key_values
__A : Any = seqlen + 2
__A : List[str] = (
batch,
self.num_attention_heads,
past_key_values_length,
self._config.hidden_size // self.num_attention_heads,
)
__A : Optional[Any] = [
(torch.zeros(_A ), torch.zeros(_A )) for _ in range(self.num_layers )
]
__A : Tuple = common_inputs['attention_mask']
if self.use_past:
__A : str = ordered_inputs['attention_mask'].dtype
__A : List[Any] = torch.cat(
[ordered_inputs['attention_mask'], torch.ones(_A , _A , dtype=_A )] , dim=1 )
return ordered_inputs
@property
def UpperCAmelCase_ ( self ):
return 13
| 77 | 1 |
from __future__ import annotations
from random import random
class _A:
"""simple docstring"""
def __init__( self , _A = None ):
__A : List[Any] = value
__A : Any = random()
__A : Node | None = None
__A : Node | None = None
def __repr__( self ):
from pprint import pformat
if self.left is None and self.right is None:
return F"""'{self.value}: {self.prior:.5}'"""
else:
return pformat(
{F"""{self.value}: {self.prior:.5}""": (self.left, self.right)} , indent=1 )
def __str__( self ):
__A : Union[str, Any] = str(self.value ) + ' '
__A : Tuple = str(self.left or '' )
__A : List[Any] = str(self.right or '' )
return value + left + right
def _SCREAMING_SNAKE_CASE ( a , a ) -> tuple[Node | None, Node | None]:
if root is None: # None tree is split into 2 Nones
return None, None
elif root.value is None:
return None, None
else:
if value < root.value:
__A , __A : Optional[Any] = split(root.left , a )
return left, root
else:
__A , __A : List[Any] = split(root.right , a )
return root, right
def _SCREAMING_SNAKE_CASE ( a , a ) -> Node | None:
if (not left) or (not right): # If one node is None, return the other
return left or right
elif left.prior < right.prior:
__A : List[Any] = merge(left.right , a )
return left
else:
__A : Any = merge(a , right.left )
return right
def _SCREAMING_SNAKE_CASE ( a , a ) -> Node | None:
__A : Tuple = Node(a )
__A , __A : Optional[Any] = split(a , a )
return merge(merge(a , a ) , a )
def _SCREAMING_SNAKE_CASE ( a , a ) -> Node | None:
__A , __A : Union[str, Any] = split(a , value - 1 )
__A , __A : Dict = split(a , a )
return merge(a , a )
def _SCREAMING_SNAKE_CASE ( a ) -> None:
if not root: # None
return
else:
inorder(root.left )
print(root.value , end=',' )
inorder(root.right )
def _SCREAMING_SNAKE_CASE ( a , a ) -> Node | None:
for arg in args.split():
if arg[0] == "+":
__A : Tuple = insert(a , int(arg[1:] ) )
elif arg[0] == "-":
__A : Union[str, Any] = erase(a , int(arg[1:] ) )
else:
print('Unknown command' )
return root
def _SCREAMING_SNAKE_CASE ( ) -> None:
__A : Union[str, Any] = None
print(
'enter numbers to create a tree, + value to add value into treap, '
'- value to erase all nodes with value. \'q\' to quit. ' )
__A : Tuple = input()
while args != "q":
__A : str = interact_treap(a , a )
print(a )
__A : Dict = input()
print('good by!' )
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| 77 |
import warnings
from ...utils import logging
from .image_processing_mobilevit import MobileViTImageProcessor
UpperCAmelCase : List[Any] = logging.get_logger(__name__)
class _A( snake_case__ ):
"""simple docstring"""
def __init__( self , *_A , **_A ):
warnings.warn(
'The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.'
' Please use MobileViTImageProcessor instead.' , _A , )
super().__init__(*_A , **_A )
| 77 | 1 |
def _SCREAMING_SNAKE_CASE ( a ) -> int:
__A : list[list[int]] = [[0 for _ in range(a )] for _ in range(m + 1 )]
for i in range(m + 1 ):
__A : Optional[int] = 1
for n in range(m + 1 ):
for k in range(1 , a ):
memo[n][k] += memo[n][k - 1]
if n - k > 0:
memo[n][k] += memo[n - k - 1][k]
return memo[m][m - 1]
if __name__ == "__main__":
import sys
if len(sys.argv) == 1:
try:
UpperCAmelCase : str = int(input('''Enter a number: ''').strip())
print(partition(n))
except ValueError:
print('''Please enter a number.''')
else:
try:
UpperCAmelCase : str = int(sys.argv[1])
print(partition(n))
except ValueError:
print('''Please pass a number.''')
| 77 |
import glob
import os
import random
from string import ascii_lowercase, digits
import cva
UpperCAmelCase : Dict = ''''''
UpperCAmelCase : Union[str, Any] = ''''''
UpperCAmelCase : Optional[int] = ''''''
UpperCAmelCase : Union[str, Any] = 1 # (0 is vertical, 1 is horizontal)
def _SCREAMING_SNAKE_CASE ( ) -> None:
__A , __A : List[Any] = get_dataset(a , a )
print('Processing...' )
__A , __A , __A : Optional[Any] = update_image_and_anno(a , a , a )
for index, image in enumerate(a ):
# Get random string code: '7b7ad245cdff75241935e4dd860f3bad'
__A : Optional[int] = random_chars(32 )
__A : Dict = paths[index].split(os.sep )[-1].rsplit('.' , 1 )[0]
__A : Dict = F"""{OUTPUT_DIR}/{file_name}_FLIP_{letter_code}"""
cva.imwrite(F"""/{file_root}.jpg""" , a , [cva.IMWRITE_JPEG_QUALITY, 85] )
print(F"""Success {index+1}/{len(a )} with {file_name}""" )
__A : int = []
for anno in new_annos[index]:
__A : Any = F"""{anno[0]} {anno[1]} {anno[2]} {anno[3]} {anno[4]}"""
annos_list.append(a )
with open(F"""/{file_root}.txt""" , 'w' ) as outfile:
outfile.write('\n'.join(line for line in annos_list ) )
def _SCREAMING_SNAKE_CASE ( a , a ) -> tuple[list, list]:
__A : int = []
__A : List[Any] = []
for label_file in glob.glob(os.path.join(a , '*.txt' ) ):
__A : List[str] = label_file.split(os.sep )[-1].rsplit('.' , 1 )[0]
with open(a ) as in_file:
__A : Tuple = in_file.readlines()
__A : Dict = os.path.join(a , F"""{label_name}.jpg""" )
__A : Dict = []
for obj_list in obj_lists:
__A : int = 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(a )
labels.append(a )
return img_paths, labels
def _SCREAMING_SNAKE_CASE ( a , a , a = 1 ) -> tuple[list, list, list]:
__A : int = []
__A : Optional[Any] = []
__A : Dict = []
for idx in range(len(a ) ):
__A : Dict = []
__A : Optional[Any] = img_list[idx]
path_list.append(a )
__A : Union[str, Any] = anno_list[idx]
__A : Optional[Any] = cva.imread(a )
if flip_type == 1:
__A : Any = cva.flip(a , a )
for bbox in img_annos:
__A : Dict = 1 - bbox[1]
new_annos.append([bbox[0], x_center_new, bbox[2], bbox[3], bbox[4]] )
elif flip_type == 0:
__A : Union[str, Any] = cva.flip(a , a )
for bbox in img_annos:
__A : Optional[Any] = 1 - bbox[2]
new_annos.append([bbox[0], bbox[1], y_center_new, bbox[3], bbox[4]] )
new_annos_lists.append(a )
new_imgs_list.append(a )
return new_imgs_list, new_annos_lists, path_list
def _SCREAMING_SNAKE_CASE ( a = 32 ) -> str:
assert number_char > 1, "The number of character should greater than 1"
__A : List[Any] = ascii_lowercase + digits
return "".join(random.choice(a ) for _ in range(a ) )
if __name__ == "__main__":
main()
print('''DONE ✅''')
| 77 | 1 |
import os
import sys
import unittest
UpperCAmelCase : int = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, '''utils'''))
import check_dummies # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402
# Align TRANSFORMERS_PATH in check_dummies with the current path
UpperCAmelCase : Optional[Any] = os.path.join(git_repo_path, '''src''', '''transformers''')
UpperCAmelCase : Optional[int] = '''
{0} = None
'''
UpperCAmelCase : Optional[int] = '''
class {0}(metaclass=DummyObject):
_backends = {1}
def __init__(self, *args, **kwargs):
requires_backends(self, {1})
'''
UpperCAmelCase : int = '''
def {0}(*args, **kwargs):
requires_backends({0}, {1})
'''
class _A( unittest.TestCase ):
"""simple docstring"""
def UpperCAmelCase_ ( self ):
__A : Union[str, Any] = find_backend(' _import_structure["models.albert"].append("AlbertTokenizerFast")' )
self.assertIsNone(_A )
__A : Optional[int] = find_backend(' if not is_tokenizers_available():' )
self.assertEqual(_A , 'tokenizers' )
__A : int = find_backend(' if not is_tensorflow_text_available():' )
self.assertEqual(_A , 'tensorflow_text' )
__A : str = find_backend(' if not (is_sentencepiece_available() and is_tokenizers_available()):' )
self.assertEqual(_A , 'sentencepiece_and_tokenizers' )
__A : Optional[Any] = find_backend(
' if not (is_sentencepiece_available() and is_tensorflow_text_available()):' )
self.assertEqual(_A , 'sentencepiece_and_tensorflow_text' )
__A : Tuple = find_backend(
' if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):' )
self.assertEqual(_A , 'sentencepiece_and_tokenizers_and_vision' )
def UpperCAmelCase_ ( self ):
__A : Dict = read_init()
# We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
self.assertIn('torch' , _A )
self.assertIn('tensorflow_text' , _A )
self.assertIn('sentencepiece_and_tokenizers' , _A )
# Likewise, we can't assert on the exact content of a key
self.assertIn('BertModel' , objects['torch'] )
self.assertIn('TFBertModel' , objects['tf'] )
self.assertIn('FlaxBertModel' , objects['flax'] )
self.assertIn('BertModel' , objects['torch'] )
self.assertIn('TFBertTokenizer' , objects['tensorflow_text'] )
self.assertIn('convert_slow_tokenizer' , objects['sentencepiece_and_tokenizers'] )
def UpperCAmelCase_ ( self ):
__A : Optional[int] = create_dummy_object('CONSTANT' , '\'torch\'' )
self.assertEqual(_A , '\nCONSTANT = None\n' )
__A : Optional[int] = create_dummy_object('function' , '\'torch\'' )
self.assertEqual(
_A , '\ndef function(*args, **kwargs):\n requires_backends(function, \'torch\')\n' )
__A : List[Any] = '\nclass FakeClass(metaclass=DummyObject):\n _backends = \'torch\'\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, \'torch\')\n'
__A : Any = create_dummy_object('FakeClass' , '\'torch\'' )
self.assertEqual(_A , _A )
def UpperCAmelCase_ ( self ):
__A : Tuple = '# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n requires_backends(function, ["torch"])\n\n\nclass FakeClass(metaclass=DummyObject):\n _backends = ["torch"]\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, ["torch"])\n'
__A : List[str] = create_dummy_files({'torch': ['CONSTANT', 'function', 'FakeClass']} )
self.assertEqual(dummy_files['torch'] , _A )
| 77 |
import unittest
from parameterized import parameterized
from transformers import LlamaConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, slow, torch_device
from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer
class _A:
"""simple docstring"""
def __init__( self , _A , _A=13 , _A=7 , _A=True , _A=True , _A=False , _A=True , _A=99 , _A=32 , _A=5 , _A=4 , _A=37 , _A="gelu" , _A=0.1 , _A=0.1 , _A=512 , _A=16 , _A=2 , _A=0.0_2 , _A=3 , _A=4 , _A=None , ):
__A : Union[str, Any] = parent
__A : List[str] = batch_size
__A : Optional[int] = seq_length
__A : List[Any] = is_training
__A : Optional[Any] = use_input_mask
__A : List[Any] = use_token_type_ids
__A : Optional[Any] = use_labels
__A : List[str] = vocab_size
__A : Optional[int] = hidden_size
__A : List[Any] = num_hidden_layers
__A : int = num_attention_heads
__A : Dict = intermediate_size
__A : Any = hidden_act
__A : Union[str, Any] = hidden_dropout_prob
__A : Union[str, Any] = attention_probs_dropout_prob
__A : Optional[int] = max_position_embeddings
__A : Dict = type_vocab_size
__A : Any = type_sequence_label_size
__A : Dict = initializer_range
__A : str = num_labels
__A : Union[str, Any] = num_choices
__A : str = scope
def UpperCAmelCase_ ( self ):
__A : str = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__A : Optional[Any] = None
if self.use_input_mask:
__A : Tuple = random_attention_mask([self.batch_size, self.seq_length] )
__A : Dict = None
if self.use_token_type_ids:
__A : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
__A : Dict = None
__A : List[Any] = None
__A : List[Any] = None
if self.use_labels:
__A : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__A : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
__A : List[Any] = ids_tensor([self.batch_size] , self.num_choices )
__A : Optional[int] = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def UpperCAmelCase_ ( self ):
return LlamaConfig(
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=_A , initializer_range=self.initializer_range , )
def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A ):
__A : List[str] = LlamaModel(config=_A )
model.to(_A )
model.eval()
__A : Any = model(_A , attention_mask=_A )
__A : Any = model(_A )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ):
__A : Dict = True
__A : int = LlamaModel(_A )
model.to(_A )
model.eval()
__A : str = model(
_A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , )
__A : int = model(
_A , attention_mask=_A , encoder_hidden_states=_A , )
__A : List[Any] = model(_A , attention_mask=_A )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ):
__A : Optional[Any] = LlamaForCausalLM(config=_A )
model.to(_A )
model.eval()
__A : List[Any] = model(_A , attention_mask=_A , labels=_A )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def UpperCAmelCase_ ( self , _A , _A , _A , _A , _A , _A , _A , _A , _A , ):
__A : int = True
__A : List[Any] = True
__A : List[Any] = LlamaForCausalLM(config=_A )
model.to(_A )
model.eval()
# first forward pass
__A : Optional[Any] = model(
_A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , use_cache=_A , )
__A : Optional[int] = outputs.past_key_values
# create hypothetical multiple next token and extent to next_input_ids
__A : int = ids_tensor((self.batch_size, 3) , config.vocab_size )
__A : str = ids_tensor((self.batch_size, 3) , vocab_size=2 )
# append to next input_ids and
__A : Tuple = torch.cat([input_ids, next_tokens] , dim=-1 )
__A : str = torch.cat([input_mask, next_mask] , dim=-1 )
__A : Tuple = model(
_A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , output_hidden_states=_A , )['hidden_states'][0]
__A : Union[str, Any] = model(
_A , attention_mask=_A , encoder_hidden_states=_A , encoder_attention_mask=_A , past_key_values=_A , output_hidden_states=_A , )['hidden_states'][0]
# select random slice
__A : Optional[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item()
__A : List[str] = output_from_no_past[:, -3:, random_slice_idx].detach()
__A : Tuple = output_from_past[:, :, random_slice_idx].detach()
self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] )
# test that outputs are equal for slice
self.parent.assertTrue(torch.allclose(_A , _A , atol=1e-3 ) )
def UpperCAmelCase_ ( self ):
__A : Tuple = self.prepare_config_and_inputs()
(
(
__A
) , (
__A
) , (
__A
) , (
__A
) , (
__A
) , (
__A
) , (
__A
) ,
) : Tuple = config_and_inputs
__A : List[str] = {'input_ids': input_ids, 'attention_mask': input_mask}
return config, inputs_dict
@require_torch
class _A( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ):
"""simple docstring"""
UpperCamelCase : Optional[Any] = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else ()
UpperCamelCase : Optional[Any] = (LlamaForCausalLM,) if is_torch_available() else ()
UpperCamelCase : Optional[Any] = (
{
'''feature-extraction''': LlamaModel,
'''text-classification''': LlamaForSequenceClassification,
'''text-generation''': LlamaForCausalLM,
'''zero-shot''': LlamaForSequenceClassification,
}
if is_torch_available()
else {}
)
UpperCamelCase : int = False
UpperCamelCase : Dict = False
def UpperCAmelCase_ ( self ):
__A : List[Any] = LlamaModelTester(self )
__A : Optional[int] = ConfigTester(self , config_class=_A , hidden_size=37 )
def UpperCAmelCase_ ( self ):
self.config_tester.run_common_tests()
def UpperCAmelCase_ ( self ):
__A : Optional[int] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_A )
def UpperCAmelCase_ ( self ):
__A : Optional[Any] = self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
__A : int = type
self.model_tester.create_and_check_model(*_A )
def UpperCAmelCase_ ( self ):
__A , __A : int = self.model_tester.prepare_config_and_inputs_for_common()
__A : str = 3
__A : Optional[int] = input_dict['input_ids']
__A : int = input_ids.ne(1 ).to(_A )
__A : List[str] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size )
__A : Optional[Any] = LlamaForSequenceClassification(_A )
model.to(_A )
model.eval()
__A : List[Any] = model(_A , attention_mask=_A , labels=_A )
self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) )
def UpperCAmelCase_ ( self ):
__A , __A : str = self.model_tester.prepare_config_and_inputs_for_common()
__A : Union[str, Any] = 3
__A : Tuple = 'single_label_classification'
__A : Union[str, Any] = input_dict['input_ids']
__A : List[str] = input_ids.ne(1 ).to(_A )
__A : Any = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size )
__A : Optional[int] = LlamaForSequenceClassification(_A )
model.to(_A )
model.eval()
__A : Tuple = model(_A , attention_mask=_A , labels=_A )
self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) )
def UpperCAmelCase_ ( self ):
__A , __A : str = self.model_tester.prepare_config_and_inputs_for_common()
__A : Any = 3
__A : int = 'multi_label_classification'
__A : int = input_dict['input_ids']
__A : List[str] = input_ids.ne(1 ).to(_A )
__A : List[Any] = ids_tensor(
[self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float )
__A : List[Any] = LlamaForSequenceClassification(_A )
model.to(_A )
model.eval()
__A : Tuple = model(_A , attention_mask=_A , labels=_A )
self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) )
@unittest.skip('LLaMA buffers include complex numbers, which breaks this test' )
def UpperCAmelCase_ ( self ):
pass
@parameterized.expand([('linear',), ('dynamic',)] )
def UpperCAmelCase_ ( self , _A ):
__A , __A : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common()
__A : Dict = ids_tensor([1, 10] , config.vocab_size )
__A : Union[str, Any] = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size )
set_seed(42 ) # Fixed seed at init time so the two models get the same random weights
__A : List[Any] = LlamaModel(_A )
original_model.to(_A )
original_model.eval()
__A : Dict = original_model(_A ).last_hidden_state
__A : int = original_model(_A ).last_hidden_state
set_seed(42 ) # Fixed seed at init time so the two models get the same random weights
__A : int = {'type': scaling_type, 'factor': 1_0.0}
__A : str = LlamaModel(_A )
scaled_model.to(_A )
scaled_model.eval()
__A : Dict = scaled_model(_A ).last_hidden_state
__A : str = scaled_model(_A ).last_hidden_state
# Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
# maximum sequence length, so the outputs for the short input should match.
if scaling_type == "dynamic":
self.assertTrue(torch.allclose(_A , _A , atol=1e-5 ) )
else:
self.assertFalse(torch.allclose(_A , _A , atol=1e-5 ) )
# The output should be different for long inputs
self.assertFalse(torch.allclose(_A , _A , atol=1e-5 ) )
@require_torch
class _A( unittest.TestCase ):
"""simple docstring"""
@unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' )
@slow
def UpperCAmelCase_ ( self ):
__A : Tuple = [1, 306, 4658, 278, 6593, 310, 2834, 338]
__A : Tuple = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-7b-hf' , device_map='auto' )
__A : Union[str, Any] = model(torch.tensor([input_ids] ) )
# Expected mean on dim = -1
__A : Optional[int] = torch.tensor([[-6.6_5_5_0, -4.1_2_2_7, -4.9_8_5_9, -3.2_4_0_6, 0.8_2_6_2, -3.0_0_3_3, 1.2_9_6_4, -3.3_6_9_9]] )
torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 )
# slicing logits[0, 0, 0:30]
# fmt: off
__A : str = torch.tensor([-1_2.8_2_8_1, -7.4_4_5_3, -0.4_6_3_9, -8.0_6_2_5, -7.2_5_0_0, -8.0_0_0_0, -6.4_8_8_3, -7.7_6_9_5, -7.8_4_3_8, -7.0_3_1_2, -6.2_1_8_8, -7.1_3_2_8, -1.8_4_9_6, 1.9_9_6_1, -8.6_2_5_0, -6.7_2_2_7, -1_2.8_2_8_1, -6.9_4_9_2, -7.0_7_4_2, -7.7_8_5_2, -7.5_8_2_0, -7.9_0_6_2, -6.9_3_7_5, -7.9_8_0_5, -8.3_4_3_8, -8.1_5_6_2, -8.0_4_6_9, -7.6_2_5_0, -7.7_4_2_2, -7.3_3_9_8,] )
# fmt: on
torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 )
@unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' )
@slow
def UpperCAmelCase_ ( self ):
__A : int = [1, 306, 4658, 278, 6593, 310, 2834, 338]
__A : List[str] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-hf' , device_map='auto' )
__A : int = model(torch.tensor(_A ) )
# Expected mean on dim = -1
__A : List[str] = torch.tensor([[-2.0_6_2_2, -1.2_7_9_4, -1.1_6_3_8, -0.9_7_8_8, -1.4_6_0_3, -1.0_2_3_8, -1.7_8_9_3, -1.4_4_1_1]] )
torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 )
# slicing logits[0, 0, 0:30]
# fmt: off
__A : List[str] = torch.tensor([-8.1_4_0_6, -8.0_5_4_7, 2.7_4_6_1, -1.2_3_4_4, -0.1_4_4_8, -1.8_2_6_2, -1.0_0_2_0, -1.8_1_5_4, -1.6_8_9_5, -1.8_5_1_6, -2.3_5_7_4, -0.9_2_7_7, 3.7_5_9_8, 6.5_7_4_2, -1.2_9_9_8, -0.1_1_7_7, -8.1_4_0_6, -2.9_6_8_8, -2.9_1_9_9, -3.1_6_9_9, -3.5_2_5_4, -2.3_5_5_5, -2.7_9_8_8, -3.4_1_4_1, -2.8_2_6_2, -4.5_1_9_5, -3.3_3_7_9, -3.3_1_6_4, -2.7_8_3_2, -3.0_2_7_3] )
# fmt: on
torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 )
@unittest.skip('Logits are not exactly the same, once we fix the instabalities somehow, will update!' )
@slow
def UpperCAmelCase_ ( self ):
__A : str = [1, 306, 4658, 278, 6593, 310, 2834, 338]
__A : Tuple = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-13b-chat-hf' , device_map='auto' )
__A : Optional[int] = model(torch.tensor(_A ) )
# Expected mean on dim = -1
__A : List[str] = torch.tensor([[-0.8_5_6_2, -1.8_5_2_0, -0.7_5_5_1, -0.4_1_6_2, -1.5_1_6_1, -1.2_0_3_8, -2.4_8_2_3, -2.3_2_5_4]] )
torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 )
# slicing logits[0, 0, 0:30]
# fmt: off
__A : Optional[Any] = torch.tensor([-2.2_2_2_7, 4.8_8_2_8, 0.9_0_2_3, -0.4_5_7_8, -0.7_8_7_1, -0.1_0_3_3, -0.6_2_2_1, -0.5_7_8_6, -0.7_8_0_3, -1.0_6_7_4, -1.2_9_2_0, -0.1_5_7_0, 0.8_0_0_8, 2.0_7_2_3, -0.9_4_9_7, 0.2_7_7_1, -2.2_2_2_7, -0.7_6_1_2, -1.4_3_4_6, -1.2_0_6_1, -1.6_4_2_6, -0.3_0_0_0, -0.7_1_3_9, -1.1_9_3_4, -1.8_6_9_1, -1.6_9_7_3, -1.5_9_4_7, -1.2_7_0_5, -0.3_5_2_3, -0.5_5_1_3] )
# fmt: on
torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 )
@unittest.skip(
'Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test' )
@slow
def UpperCAmelCase_ ( self ):
__A : str = [1, 306, 4658, 278, 6593, 310, 2834, 338]
__A : List[Any] = LlamaForCausalLM.from_pretrained('meta-llama/Llama-2-70b-hf' , device_map='auto' )
__A : List[Any] = model(torch.tensor(_A ) )
__A : Tuple = torch.tensor(
[[-4.2_3_2_7, -3.3_3_6_0, -4.6_6_6_5, -4.7_6_3_1, -1.8_1_8_0, -3.4_1_7_0, -1.4_2_1_1, -3.1_8_1_0]] , dtype=torch.floataa )
torch.testing.assert_close(out.mean(-1 ) , _A , atol=1e-2 , rtol=1e-2 )
# fmt: off
__A : Optional[int] = torch.tensor([-9.4_9_2_2, -3.9_5_5_1, 1.7_9_9_8, -5.6_7_5_8, -5.1_0_5_5, -5.8_9_8_4, -4.8_3_2_0, -6.8_0_8_6, -6.5_3_9_1, -5.6_1_7_2, -5.5_8_2_0, -5.5_3_5_2, 1.7_8_8_1, 3.6_2_8_9, -6.5_1_1_7, -3.4_7_8_5, -9.5_0_0_0, -6.0_3_5_2, -6.8_1_2_5, -6.0_1_9_5, -6.6_8_3_6, -5.4_7_2_7, -6.2_8_1_2, -6.0_3_9_1, -7.3_3_9_8, -7.4_2_9_7, -7.4_8_4_4, -6.5_8_2_0, -5.8_7_8_9, -5.5_3_1_2] )
# fmt: on
torch.testing.assert_close(out[0, 0, :30] , _A , atol=1e-5 , rtol=1e-5 )
@unittest.skip('Model is curently gated' )
@slow
def UpperCAmelCase_ ( self ):
__A : Tuple = 'Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi'
__A : List[str] = 'Simply put, the theory of relativity states that '
__A : Union[str, Any] = LlamaTokenizer.from_pretrained('meta-llama/Llama-2-13b-chat-hf' )
__A : List[str] = tokenizer.encode(_A , return_tensors='pt' )
__A : Tuple = LlamaForCausalLM.from_pretrained(
'meta-llama/Llama-2-13b-chat-hf' , device_map='sequential' , use_safetensors=_A )
# greedy generation outputs
__A : Union[str, Any] = model.generate(_A , max_new_tokens=64 , top_p=_A , temperature=1 , do_sample=_A )
__A : List[str] = tokenizer.decode(generated_ids[0] , skip_special_tokens=_A )
self.assertEqual(_A , _A )
| 77 | 1 |
import os
import random
import sys
from . import cryptomath_module as cryptoMath # noqa: N812
from . import rabin_miller as rabinMiller # noqa: N812
def _SCREAMING_SNAKE_CASE ( ) -> None:
print('Making key files...' )
make_key_files('rsa' , 10_24 )
print('Key files generation successful.' )
def _SCREAMING_SNAKE_CASE ( a ) -> tuple[tuple[int, int], tuple[int, int]]:
print('Generating prime p...' )
__A : Optional[Any] = rabinMiller.generate_large_prime(a )
print('Generating prime q...' )
__A : Union[str, Any] = rabinMiller.generate_large_prime(a )
__A : Tuple = p * q
print('Generating e that is relatively prime to (p - 1) * (q - 1)...' )
while True:
__A : Dict = random.randrange(2 ** (key_size - 1) , 2 ** (key_size) )
if cryptoMath.gcd(a , (p - 1) * (q - 1) ) == 1:
break
print('Calculating d that is mod inverse of e...' )
__A : Any = cryptoMath.find_mod_inverse(a , (p - 1) * (q - 1) )
__A : Dict = (n, e)
__A : Dict = (n, d)
return (public_key, private_key)
def _SCREAMING_SNAKE_CASE ( a , a ) -> None:
if os.path.exists(F"""{name}_pubkey.txt""" ) or os.path.exists(F"""{name}_privkey.txt""" ):
print('\nWARNING:' )
print(
F"""\"{name}_pubkey.txt\" or \"{name}_privkey.txt\" already exists. \n"""
'Use a different name or delete these files and re-run this program.' )
sys.exit()
__A , __A : Optional[int] = generate_key(a )
print(F"""\nWriting public key to file {name}_pubkey.txt...""" )
with open(F"""{name}_pubkey.txt""" , 'w' ) as out_file:
out_file.write(F"""{key_size},{public_key[0]},{public_key[1]}""" )
print(F"""Writing private key to file {name}_privkey.txt...""" )
with open(F"""{name}_privkey.txt""" , 'w' ) as out_file:
out_file.write(F"""{key_size},{private_key[0]},{private_key[1]}""" )
if __name__ == "__main__":
main()
| 77 |
import random
import torch
from huggingface_hub import HfApi
from diffusers import UNetaDModel
UpperCAmelCase : str = HfApi()
UpperCAmelCase : List[str] = {}
# fmt: off
UpperCAmelCase : Optional[Any] = torch.tensor([
-0.7515, -1.6883, 0.2420, 0.0300, 0.6347, 1.3433, -1.1743, -3.7467,
1.2342, -2.2485, 0.4636, 0.8076, -0.7991, 0.3969, 0.8498, 0.9189,
-1.8887, -3.3522, 0.7639, 0.2040, 0.6271, -2.7148, -1.6316, 3.0839,
0.3186, 0.2721, -0.9759, -1.2461, 2.6257, 1.3557
])
UpperCAmelCase : Dict = torch.tensor([
-2.3639, -2.5344, 0.0054, -0.6674, 1.5990, 1.0158, 0.3124, -2.1436,
1.8795, -2.5429, -0.1566, -0.3973, 1.2490, 2.6447, 1.2283, -0.5208,
-2.8154, -3.5119, 2.3838, 1.2033, 1.7201, -2.1256, -1.4576, 2.7948,
2.4204, -0.9752, -1.2546, 0.8027, 3.2758, 3.1365
])
UpperCAmelCase : Union[str, Any] = torch.tensor([
-0.6531, -0.6891, -0.3172, -0.5375, -0.9140, -0.5367, -0.1175, -0.7869,
-0.3808, -0.4513, -0.2098, -0.0083, 0.3183, 0.5140, 0.2247, -0.1304,
-0.1302, -0.2802, -0.2084, -0.2025, -0.4967, -0.4873, -0.0861, 0.6925,
0.0250, 0.1290, -0.1543, 0.6316, 1.0460, 1.4943
])
UpperCAmelCase : str = torch.tensor([
0.0911, 0.1107, 0.0182, 0.0435, -0.0805, -0.0608, 0.0381, 0.2172,
-0.0280, 0.1327, -0.0299, -0.0255, -0.0050, -0.1170, -0.1046, 0.0309,
0.1367, 0.1728, -0.0533, -0.0748, -0.0534, 0.1624, 0.0384, -0.1805,
-0.0707, 0.0642, 0.0220, -0.0134, -0.1333, -0.1505
])
UpperCAmelCase : Optional[Any] = torch.tensor([
0.1321, 0.1337, 0.0440, 0.0622, -0.0591, -0.0370, 0.0503, 0.2133,
-0.0177, 0.1415, -0.0116, -0.0112, 0.0044, -0.0980, -0.0789, 0.0395,
0.1502, 0.1785, -0.0488, -0.0514, -0.0404, 0.1539, 0.0454, -0.1559,
-0.0665, 0.0659, 0.0383, -0.0005, -0.1266, -0.1386
])
UpperCAmelCase : List[Any] = torch.tensor([
0.1154, 0.1218, 0.0307, 0.0526, -0.0711, -0.0541, 0.0366, 0.2078,
-0.0267, 0.1317, -0.0226, -0.0193, -0.0014, -0.1055, -0.0902, 0.0330,
0.1391, 0.1709, -0.0562, -0.0693, -0.0560, 0.1482, 0.0381, -0.1683,
-0.0681, 0.0661, 0.0331, -0.0046, -0.1268, -0.1431
])
UpperCAmelCase : Optional[int] = torch.tensor([
0.1192, 0.1240, 0.0414, 0.0606, -0.0557, -0.0412, 0.0430, 0.2042,
-0.0200, 0.1385, -0.0115, -0.0132, 0.0017, -0.0965, -0.0802, 0.0398,
0.1433, 0.1747, -0.0458, -0.0533, -0.0407, 0.1545, 0.0419, -0.1574,
-0.0645, 0.0626, 0.0341, -0.0010, -0.1199, -0.1390
])
UpperCAmelCase : Tuple = torch.tensor([
0.1075, 0.1074, 0.0205, 0.0431, -0.0774, -0.0607, 0.0298, 0.2042,
-0.0320, 0.1267, -0.0281, -0.0250, -0.0064, -0.1091, -0.0946, 0.0290,
0.1328, 0.1650, -0.0580, -0.0738, -0.0586, 0.1440, 0.0337, -0.1746,
-0.0712, 0.0605, 0.0250, -0.0099, -0.1316, -0.1473
])
UpperCAmelCase : Any = torch.tensor([
-1.4572, -2.0481, -0.0414, -0.6005, 1.4136, 0.5848, 0.4028, -2.7330,
1.2212, -2.1228, 0.2155, 0.4039, 0.7662, 2.0535, 0.7477, -0.3243,
-2.1758, -2.7648, 1.6947, 0.7026, 1.2338, -1.6078, -0.8682, 2.2810,
1.8574, -0.5718, -0.5586, -0.0186, 2.3415, 2.1251])
UpperCAmelCase : Union[str, Any] = torch.tensor([
-1.3690, -1.9720, -0.4090, -0.6966, 1.4660, 0.9938, -0.1385, -2.7324,
0.7736, -1.8917, 0.2923, 0.4293, 0.1693, 1.4112, 1.1887, -0.3181,
-2.2160, -2.6381, 1.3170, 0.8163, 0.9240, -1.6544, -0.6099, 2.5259,
1.6430, -0.9090, -0.9392, -0.0126, 2.4268, 2.3266
])
UpperCAmelCase : Tuple = torch.tensor([
-1.3525, -1.9628, -0.3956, -0.6860, 1.4664, 1.0014, -0.1259, -2.7212,
0.7772, -1.8811, 0.2996, 0.4388, 0.1704, 1.4029, 1.1701, -0.3027,
-2.2053, -2.6287, 1.3350, 0.8131, 0.9274, -1.6292, -0.6098, 2.5131,
1.6505, -0.8958, -0.9298, -0.0151, 2.4257, 2.3355
])
UpperCAmelCase : Dict = torch.tensor([
-2.0585, -2.7897, -0.2850, -0.8940, 1.9052, 0.5702, 0.6345, -3.8959,
1.5932, -3.2319, 0.1974, 0.0287, 1.7566, 2.6543, 0.8387, -0.5351,
-3.2736, -4.3375, 2.9029, 1.6390, 1.4640, -2.1701, -1.9013, 2.9341,
3.4981, -0.6255, -1.1644, -0.1591, 3.7097, 3.2066
])
UpperCAmelCase : Tuple = torch.tensor([
-2.3139, -2.5594, -0.0197, -0.6785, 1.7001, 1.1606, 0.3075, -2.1740,
1.8071, -2.5630, -0.0926, -0.3811, 1.2116, 2.6246, 1.2731, -0.5398,
-2.8153, -3.6140, 2.3893, 1.3262, 1.6258, -2.1856, -1.3267, 2.8395,
2.3779, -1.0623, -1.2468, 0.8959, 3.3367, 3.2243
])
UpperCAmelCase : List[str] = torch.tensor([
-2.0628, -2.7667, -0.2089, -0.8263, 2.0539, 0.5992, 0.6495, -3.8336,
1.6025, -3.2817, 0.1721, -0.0633, 1.7516, 2.7039, 0.8100, -0.5908,
-3.2113, -4.4343, 2.9257, 1.3632, 1.5562, -2.1489, -1.9894, 3.0560,
3.3396, -0.7328, -1.0417, 0.0383, 3.7093, 3.2343
])
UpperCAmelCase : Union[str, Any] = torch.tensor([
-1.4574, -2.0569, -0.0473, -0.6117, 1.4018, 0.5769, 0.4129, -2.7344,
1.2241, -2.1397, 0.2000, 0.3937, 0.7616, 2.0453, 0.7324, -0.3391,
-2.1746, -2.7744, 1.6963, 0.6921, 1.2187, -1.6172, -0.8877, 2.2439,
1.8471, -0.5839, -0.5605, -0.0464, 2.3250, 2.1219
])
# fmt: on
UpperCAmelCase : Any = api.list_models(filter='''diffusers''')
for mod in models:
if "google" in mod.author or mod.modelId == "CompVis/ldm-celebahq-256":
UpperCAmelCase : Union[str, Any] = '''/home/patrick/google_checkpoints/''' + mod.modelId.split('''/''')[-1]
print(F"""Started running {mod.modelId}!!!""")
if mod.modelId.startswith('''CompVis'''):
UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint, subfolder='''unet''')
else:
UpperCAmelCase : List[str] = UNetaDModel.from_pretrained(local_checkpoint)
torch.manual_seed(0)
random.seed(0)
UpperCAmelCase : int = torch.randn(1, model.config.in_channels, model.config.sample_size, model.config.sample_size)
UpperCAmelCase : Optional[int] = torch.tensor([10] * noise.shape[0])
with torch.no_grad():
UpperCAmelCase : Any = model(noise, time_step).sample
assert torch.allclose(
logits[0, 0, 0, :30], results['''_'''.join('''_'''.join(mod.modelId.split('''/''')).split('''-'''))], atol=1E-3
)
print(F"""{mod.modelId} has passed successfully!!!""")
| 77 | 1 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
UpperCAmelCase : Any = {
'''configuration_clap''': [
'''CLAP_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''ClapAudioConfig''',
'''ClapConfig''',
'''ClapTextConfig''',
],
'''processing_clap''': ['''ClapProcessor'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase : int = [
'''CLAP_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''ClapModel''',
'''ClapPreTrainedModel''',
'''ClapTextModel''',
'''ClapTextModelWithProjection''',
'''ClapAudioModel''',
'''ClapAudioModelWithProjection''',
]
UpperCAmelCase : Optional[int] = ['''ClapFeatureExtractor''']
if TYPE_CHECKING:
from .configuration_clap import (
CLAP_PRETRAINED_MODEL_ARCHIVE_LIST,
ClapAudioConfig,
ClapConfig,
ClapTextConfig,
)
from .processing_clap import ClapProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_clap import ClapFeatureExtractor
from .modeling_clap import (
CLAP_PRETRAINED_MODEL_ARCHIVE_LIST,
ClapAudioModel,
ClapAudioModelWithProjection,
ClapModel,
ClapPreTrainedModel,
ClapTextModel,
ClapTextModelWithProjection,
)
else:
import sys
UpperCAmelCase : Optional[Any] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 77 |
import numpy as np
from PIL import Image
def _SCREAMING_SNAKE_CASE ( a , a , a ) -> np.ndarray:
__A : Union[str, Any] = np.array(a )
if arr.shape[0] != arr.shape[1]:
raise ValueError('The input array is not a square matrix' )
__A : List[Any] = 0
__A : Optional[Any] = 0
__A : List[Any] = 0
__A : Dict = 0
# compute the shape of the output matrix
__A : List[Any] = (arr.shape[0] - size) // stride + 1
# initialize the output matrix with zeros of shape maxpool_shape
__A : Optional[int] = np.zeros((maxpool_shape, maxpool_shape) )
while i < arr.shape[0]:
if i + size > arr.shape[0]:
# if the end of the matrix is reached, break
break
while j < arr.shape[1]:
# if the end of the matrix is reached, break
if j + size > arr.shape[1]:
break
# compute the maximum of the pooling matrix
__A : Tuple = np.max(arr[i : i + size, j : j + size] )
# shift the pooling matrix by stride of column pixels
j += stride
mat_j += 1
# shift the pooling matrix by stride of row pixels
i += stride
mat_i += 1
# reset the column index to 0
__A : List[str] = 0
__A : Union[str, Any] = 0
return updated_arr
def _SCREAMING_SNAKE_CASE ( a , a , a ) -> np.ndarray:
__A : List[Any] = np.array(a )
if arr.shape[0] != arr.shape[1]:
raise ValueError('The input array is not a square matrix' )
__A : Dict = 0
__A : str = 0
__A : Tuple = 0
__A : Optional[int] = 0
# compute the shape of the output matrix
__A : List[Any] = (arr.shape[0] - size) // stride + 1
# initialize the output matrix with zeros of shape avgpool_shape
__A : Any = np.zeros((avgpool_shape, avgpool_shape) )
while i < arr.shape[0]:
# if the end of the matrix is reached, break
if i + size > arr.shape[0]:
break
while j < arr.shape[1]:
# if the end of the matrix is reached, break
if j + size > arr.shape[1]:
break
# compute the average of the pooling matrix
__A : Tuple = int(np.average(arr[i : i + size, j : j + size] ) )
# shift the pooling matrix by stride of column pixels
j += stride
mat_j += 1
# shift the pooling matrix by stride of row pixels
i += stride
mat_i += 1
# reset the column index to 0
__A : Dict = 0
__A : int = 0
return updated_arr
# Main Function
if __name__ == "__main__":
from doctest import testmod
testmod(name='''avgpooling''', verbose=True)
# Loading the image
UpperCAmelCase : int = Image.open('''path_to_image''')
# Converting the image to numpy array and maxpooling, displaying the result
# Ensure that the image is a square matrix
Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show()
# Converting the image to numpy array and averagepooling, displaying the result
# Ensure that the image is a square matrix
Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
| 77 | 1 |
import os
import re
import shutil
import sys
import tempfile
import unittest
import black
UpperCAmelCase : Union[str, Any] = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, '''utils'''))
import check_copies # noqa: E402
# This is the reference code that will be used in the tests.
# If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated.
UpperCAmelCase : Union[str, Any] = ''' def __init__(self, config):
super().__init__()
self.transform = BertPredictionHeadTransform(config)
# The output weights are the same as the input embeddings, but there is
# an output-only bias for each token.
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
# Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
self.decoder.bias = self.bias
def forward(self, hidden_states):
hidden_states = self.transform(hidden_states)
hidden_states = self.decoder(hidden_states)
return hidden_states
'''
class _A( unittest.TestCase ):
"""simple docstring"""
def UpperCAmelCase_ ( self ):
__A : Any = tempfile.mkdtemp()
os.makedirs(os.path.join(self.transformer_dir , 'models/bert/' ) )
__A : List[str] = self.transformer_dir
shutil.copy(
os.path.join(_A , 'src/transformers/models/bert/modeling_bert.py' ) , os.path.join(self.transformer_dir , 'models/bert/modeling_bert.py' ) , )
def UpperCAmelCase_ ( self ):
__A : List[str] = 'src/transformers'
shutil.rmtree(self.transformer_dir )
def UpperCAmelCase_ ( self , _A , _A , _A , _A=None ):
__A : int = comment + F"""\nclass {class_name}(nn.Module):\n""" + class_code
if overwrite_result is not None:
__A : Dict = comment + F"""\nclass {class_name}(nn.Module):\n""" + overwrite_result
__A : List[Any] = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 )
__A : List[str] = black.format_str(_A , mode=_A )
__A : List[Any] = os.path.join(self.transformer_dir , 'new_code.py' )
with open(_A , 'w' , newline='\n' ) as f:
f.write(_A )
if overwrite_result is None:
self.assertTrue(len(check_copies.is_copy_consistent(_A ) ) == 0 )
else:
check_copies.is_copy_consistent(f.name , overwrite=_A )
with open(_A , 'r' ) as f:
self.assertTrue(f.read() , _A )
def UpperCAmelCase_ ( self ):
__A : Optional[int] = check_copies.find_code_in_transformers('models.bert.modeling_bert.BertLMPredictionHead' )
self.assertEqual(_A , _A )
def UpperCAmelCase_ ( self ):
# Base copy consistency
self.check_copy_consistency(
'# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead' , 'BertLMPredictionHead' , REFERENCE_CODE + '\n' , )
# With no empty line at the end
self.check_copy_consistency(
'# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead' , 'BertLMPredictionHead' , _A , )
# Copy consistency with rename
self.check_copy_consistency(
'# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel' , 'TestModelLMPredictionHead' , re.sub('Bert' , 'TestModel' , _A ) , )
# Copy consistency with a really long name
__A : Any = 'TestModelWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason'
self.check_copy_consistency(
F"""# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->{long_class_name}""" , F"""{long_class_name}LMPredictionHead""" , re.sub('Bert' , _A , _A ) , )
# Copy consistency with overwrite
self.check_copy_consistency(
'# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->TestModel' , 'TestModelLMPredictionHead' , _A , overwrite_result=re.sub('Bert' , 'TestModel' , _A ) , )
def UpperCAmelCase_ ( self ):
__A : Union[str, Any] = check_copies.LOCALIZED_READMES['README_zh-hans.md']
__A : Union[str, Any] = (
'1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the'
' Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for'
' Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong'
' Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1.'
' **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace),'
' released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and'
' lighter](https://arxiv.org/abs/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same'
' method has been applied to compress GPT2 into'
' [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into'
' [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),'
' Multilingual BERT into'
' [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German'
' version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**'
' (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders'
' as discriminators rather than generators](https://arxiv.org/abs/2003.10555) by Kevin Clark, Minh-Thang'
' Luong, Quoc V. Le, Christopher D. Manning.'
)
__A : Optional[Any] = (
'1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the'
' Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of'
' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian'
' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n'
)
__A : Optional[int] = (
'1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the'
' Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of'
' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian'
' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1.'
' **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文'
' [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and'
' lighter](https://arxiv.org/abs/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same'
' method has been applied to compress GPT2 into'
' [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into'
' [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation),'
' Multilingual BERT into'
' [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German'
' version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自'
' Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather'
' than generators](https://arxiv.org/abs/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le,'
' Christopher D. Manning 发布。\n'
)
__A , __A : Union[str, Any] = check_copies.convert_to_localized_md(
_A , _A , localized_readme['format_model_list'] )
self.assertFalse(_A )
self.assertEqual(_A , _A )
__A , __A : Any = check_copies.convert_to_localized_md(
_A , _A , localized_readme['format_model_list'] )
# Check whether the number of models is equal to README.md after conversion.
self.assertTrue(_A )
__A : int = (
'1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the'
' Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for'
' Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942), by Zhenzhong'
' Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.'
)
__A : int = (
'1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and'
' the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of'
' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian'
' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n'
)
__A : Tuple = (
'1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the'
' Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of'
' Language Representations](https://arxiv.org/abs/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian'
' Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n'
)
__A , __A : Union[str, Any] = check_copies.convert_to_localized_md(
_A , _A , localized_readme['format_model_list'] )
# Check if the model link is synchronized.
self.assertEqual(_A , _A )
| 77 |
from __future__ import annotations
from collections.abc import Callable
def _SCREAMING_SNAKE_CASE ( a , a , a , a = 1_00 , ) -> float:
__A : Any = x_start
__A : List[str] = fnc(a )
__A : Optional[Any] = 0.0
for _ in range(a ):
# Approximates small segments of curve as linear and solve
# for trapezoidal area
__A : Any = (x_end - x_start) / steps + xa
__A : List[str] = fnc(a )
area += abs(fxa + fxa ) * (xa - xa) / 2
# Increment step
__A : Any = xa
__A : Dict = fxa
return area
if __name__ == "__main__":
def _SCREAMING_SNAKE_CASE ( a ) -> int:
return x**3 + x**2
print('''f(x) = x^3 + x^2''')
print('''The area between the curve, x = -5, x = 5 and the x axis is:''')
UpperCAmelCase : Tuple = 10
while i <= 10_00_00:
print(F"""with {i} steps: {trapezoidal_area(f, -5, 5, i)}""")
i *= 10
| 77 | 1 |
import argparse
import os
import re
UpperCAmelCase : Optional[Any] = '''src/transformers'''
# Pattern that looks at the indentation in a line.
UpperCAmelCase : List[str] = re.compile(r'''^(\s*)\S''')
# Pattern that matches `"key":" and puts `key` in group 0.
UpperCAmelCase : Optional[int] = re.compile(r'''^\s*"([^"]+)":''')
# Pattern that matches `_import_structure["key"]` and puts `key` in group 0.
UpperCAmelCase : List[Any] = re.compile(r'''^\s*_import_structure\["([^"]+)"\]''')
# Pattern that matches `"key",` and puts `key` in group 0.
UpperCAmelCase : List[Any] = re.compile(r'''^\s*"([^"]+)",\s*$''')
# Pattern that matches any `[stuff]` and puts `stuff` in group 0.
UpperCAmelCase : Optional[Any] = re.compile(r'''\[([^\]]+)\]''')
def _SCREAMING_SNAKE_CASE ( a ) -> str:
__A : List[Any] = _re_indent.search(a )
return "" if search is None else search.groups()[0]
def _SCREAMING_SNAKE_CASE ( a , a="" , a=None , a=None ) -> Any:
__A : Any = 0
__A : Optional[Any] = code.split('\n' )
if start_prompt is not None:
while not lines[index].startswith(a ):
index += 1
__A : Tuple = ['\n'.join(lines[:index] )]
else:
__A : Tuple = []
# We split into blocks until we get to the `end_prompt` (or the end of the block).
__A : int = [lines[index]]
index += 1
while index < len(a ) and (end_prompt is None or not lines[index].startswith(a )):
if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level:
if len(a ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + ' ' ):
current_block.append(lines[index] )
blocks.append('\n'.join(a ) )
if index < len(a ) - 1:
__A : List[str] = [lines[index + 1]]
index += 1
else:
__A : int = []
else:
blocks.append('\n'.join(a ) )
__A : Optional[Any] = [lines[index]]
else:
current_block.append(lines[index] )
index += 1
# Adds current block if it's nonempty.
if len(a ) > 0:
blocks.append('\n'.join(a ) )
# Add final block after end_prompt if provided.
if end_prompt is not None and index < len(a ):
blocks.append('\n'.join(lines[index:] ) )
return blocks
def _SCREAMING_SNAKE_CASE ( a ) -> List[Any]:
def _inner(a ):
return key(a ).lower().replace('_' , '' )
return _inner
def _SCREAMING_SNAKE_CASE ( a , a=None ) -> Optional[Any]:
# If no key is provided, we use a noop.
def noop(a ):
return x
if key is None:
__A : Optional[int] = noop
# Constants are all uppercase, they go first.
__A : str = [obj for obj in objects if key(a ).isupper()]
# Classes are not all uppercase but start with a capital, they go second.
__A : Tuple = [obj for obj in objects if key(a )[0].isupper() and not key(a ).isupper()]
# Functions begin with a lowercase, they go last.
__A : Tuple = [obj for obj in objects if not key(a )[0].isupper()]
__A : Union[str, Any] = ignore_underscore(a )
return sorted(a , key=a ) + sorted(a , key=a ) + sorted(a , key=a )
def _SCREAMING_SNAKE_CASE ( a ) -> int:
# This inner function sort imports between [ ].
def _replace(a ):
__A : Optional[Any] = match.groups()[0]
if "," not in imports:
return F"""[{imports}]"""
__A : str = [part.strip().replace('"' , '' ) for part in imports.split(',' )]
# We will have a final empty element if the line finished with a comma.
if len(keys[-1] ) == 0:
__A : Optional[Any] = keys[:-1]
return "[" + ", ".join([F"""\"{k}\"""" for k in sort_objects(a )] ) + "]"
__A : Any = import_statement.split('\n' )
if len(a ) > 3:
# Here we have to sort internal imports that are on several lines (one per name):
# key: [
# "object1",
# "object2",
# ...
# ]
# We may have to ignore one or two lines on each side.
__A : Any = 2 if lines[1].strip() == '[' else 1
__A : str = [(i, _re_strip_line.search(a ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )]
__A : Tuple = sort_objects(a , key=lambda a : x[1] )
__A : int = [lines[x[0] + idx] for x in sorted_indices]
return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] )
elif len(a ) == 3:
# Here we have to sort internal imports that are on one separate line:
# key: [
# "object1", "object2", ...
# ]
if _re_bracket_content.search(lines[1] ) is not None:
__A : List[Any] = _re_bracket_content.sub(_replace , lines[1] )
else:
__A : List[str] = [part.strip().replace('"' , '' ) for part in lines[1].split(',' )]
# We will have a final empty element if the line finished with a comma.
if len(keys[-1] ) == 0:
__A : Union[str, Any] = keys[:-1]
__A : Any = get_indent(lines[1] ) + ', '.join([F"""\"{k}\"""" for k in sort_objects(a )] )
return "\n".join(a )
else:
# Finally we have to deal with imports fitting on one line
__A : Dict = _re_bracket_content.sub(_replace , a )
return import_statement
def _SCREAMING_SNAKE_CASE ( a , a=True ) -> Any:
with open(a , encoding='utf-8' ) as f:
__A : List[str] = f.read()
if "_import_structure" not in code:
return
# Blocks of indent level 0
__A : Dict = split_code_in_indented_blocks(
a , start_prompt='_import_structure = {' , end_prompt='if TYPE_CHECKING:' )
# We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt).
for block_idx in range(1 , len(a ) - 1 ):
# Check if the block contains some `_import_structure`s thingy to sort.
__A : Dict = main_blocks[block_idx]
__A : int = block.split('\n' )
# Get to the start of the imports.
__A : Optional[int] = 0
while line_idx < len(a ) and "_import_structure" not in block_lines[line_idx]:
# Skip dummy import blocks
if "import dummy" in block_lines[line_idx]:
__A : Any = len(a )
else:
line_idx += 1
if line_idx >= len(a ):
continue
# Ignore beginning and last line: they don't contain anything.
__A : Any = '\n'.join(block_lines[line_idx:-1] )
__A : List[str] = get_indent(block_lines[1] )
# Slit the internal block into blocks of indent level 1.
__A : Tuple = split_code_in_indented_blocks(a , indent_level=a )
# We have two categories of import key: list or _import_structure[key].append/extend
__A : Optional[int] = _re_direct_key if '_import_structure = {' in block_lines[0] else _re_indirect_key
# Grab the keys, but there is a trap: some lines are empty or just comments.
__A : Dict = [(pattern.search(a ).groups()[0] if pattern.search(a ) is not None else None) for b in internal_blocks]
# We only sort the lines with a key.
__A : Optional[int] = [(i, key) for i, key in enumerate(a ) if key is not None]
__A : Any = [x[0] for x in sorted(a , key=lambda a : x[1] )]
# We reorder the blocks by leaving empty lines/comments as they were and reorder the rest.
__A : Tuple = 0
__A : List[Any] = []
for i in range(len(a ) ):
if keys[i] is None:
reorderded_blocks.append(internal_blocks[i] )
else:
__A : Dict = sort_objects_in_import(internal_blocks[sorted_indices[count]] )
reorderded_blocks.append(a )
count += 1
# And we put our main block back together with its first and last line.
__A : Dict = '\n'.join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] )
if code != "\n".join(a ):
if check_only:
return True
else:
print(F"""Overwriting {file}.""" )
with open(a , 'w' , encoding='utf-8' ) as f:
f.write('\n'.join(a ) )
def _SCREAMING_SNAKE_CASE ( a=True ) -> Dict:
__A : Union[str, Any] = []
for root, _, files in os.walk(a ):
if "__init__.py" in files:
__A : str = sort_imports(os.path.join(a , '__init__.py' ) , check_only=a )
if result:
__A : Optional[int] = [os.path.join(a , '__init__.py' )]
if len(a ) > 0:
raise ValueError(F"""Would overwrite {len(a )} files, run `make style`.""" )
if __name__ == "__main__":
UpperCAmelCase : Dict = argparse.ArgumentParser()
parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''')
UpperCAmelCase : Dict = parser.parse_args()
sort_imports_in_all_inits(check_only=args.check_only)
| 77 |
import os
import random
import sys
from . import cryptomath_module as cryptoMath # noqa: N812
from . import rabin_miller as rabinMiller # noqa: N812
def _SCREAMING_SNAKE_CASE ( ) -> None:
print('Making key files...' )
make_key_files('rsa' , 10_24 )
print('Key files generation successful.' )
def _SCREAMING_SNAKE_CASE ( a ) -> tuple[tuple[int, int], tuple[int, int]]:
print('Generating prime p...' )
__A : Optional[Any] = rabinMiller.generate_large_prime(a )
print('Generating prime q...' )
__A : Union[str, Any] = rabinMiller.generate_large_prime(a )
__A : Tuple = p * q
print('Generating e that is relatively prime to (p - 1) * (q - 1)...' )
while True:
__A : Dict = random.randrange(2 ** (key_size - 1) , 2 ** (key_size) )
if cryptoMath.gcd(a , (p - 1) * (q - 1) ) == 1:
break
print('Calculating d that is mod inverse of e...' )
__A : Any = cryptoMath.find_mod_inverse(a , (p - 1) * (q - 1) )
__A : Dict = (n, e)
__A : Dict = (n, d)
return (public_key, private_key)
def _SCREAMING_SNAKE_CASE ( a , a ) -> None:
if os.path.exists(F"""{name}_pubkey.txt""" ) or os.path.exists(F"""{name}_privkey.txt""" ):
print('\nWARNING:' )
print(
F"""\"{name}_pubkey.txt\" or \"{name}_privkey.txt\" already exists. \n"""
'Use a different name or delete these files and re-run this program.' )
sys.exit()
__A , __A : Optional[int] = generate_key(a )
print(F"""\nWriting public key to file {name}_pubkey.txt...""" )
with open(F"""{name}_pubkey.txt""" , 'w' ) as out_file:
out_file.write(F"""{key_size},{public_key[0]},{public_key[1]}""" )
print(F"""Writing private key to file {name}_privkey.txt...""" )
with open(F"""{name}_privkey.txt""" , 'w' ) as out_file:
out_file.write(F"""{key_size},{private_key[0]},{private_key[1]}""" )
if __name__ == "__main__":
main()
| 77 | 1 |
import unittest
from transformers import is_vision_available
from transformers.pipelines import pipeline
from transformers.testing_utils import (
is_pipeline_test,
nested_simplify,
require_tf,
require_torch,
require_vision,
slow,
)
from .test_pipelines_common import ANY
if is_vision_available():
from PIL import Image
else:
class _A:
"""simple docstring"""
@staticmethod
def UpperCAmelCase_ ( *_A , **_A ):
pass
@is_pipeline_test
@require_vision
class _A( unittest.TestCase ):
"""simple docstring"""
@require_torch
def UpperCAmelCase_ ( self ):
__A : Dict = pipeline(
model='hf-internal-testing/tiny-random-clip-zero-shot-image-classification' , )
__A : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
__A : Tuple = image_classifier(_A , candidate_labels=['a', 'b', 'c'] )
# The floating scores are so close, we enter floating error approximation and the order is not guaranteed across
# python and torch versions.
self.assertIn(
nested_simplify(_A ) , [
[{'score': 0.3_3_3, 'label': 'a'}, {'score': 0.3_3_3, 'label': 'b'}, {'score': 0.3_3_3, 'label': 'c'}],
[{'score': 0.3_3_3, 'label': 'a'}, {'score': 0.3_3_3, 'label': 'c'}, {'score': 0.3_3_3, 'label': 'b'}],
] , )
__A : Optional[int] = image_classifier([image] * 5 , candidate_labels=['A', 'B', 'C'] , batch_size=2 )
self.assertEqual(
nested_simplify(_A ) , [
[
{'score': 0.3_3_3, 'label': ANY(_A )},
{'score': 0.3_3_3, 'label': ANY(_A )},
{'score': 0.3_3_3, 'label': ANY(_A )},
],
[
{'score': 0.3_3_3, 'label': ANY(_A )},
{'score': 0.3_3_3, 'label': ANY(_A )},
{'score': 0.3_3_3, 'label': ANY(_A )},
],
[
{'score': 0.3_3_3, 'label': ANY(_A )},
{'score': 0.3_3_3, 'label': ANY(_A )},
{'score': 0.3_3_3, 'label': ANY(_A )},
],
[
{'score': 0.3_3_3, 'label': ANY(_A )},
{'score': 0.3_3_3, 'label': ANY(_A )},
{'score': 0.3_3_3, 'label': ANY(_A )},
],
[
{'score': 0.3_3_3, 'label': ANY(_A )},
{'score': 0.3_3_3, 'label': ANY(_A )},
{'score': 0.3_3_3, 'label': ANY(_A )},
],
] , )
@require_tf
def UpperCAmelCase_ ( self ):
__A : Any = pipeline(
model='hf-internal-testing/tiny-random-clip-zero-shot-image-classification' , framework='tf' )
__A : List[str] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
__A : int = image_classifier(_A , candidate_labels=['a', 'b', 'c'] )
self.assertEqual(
nested_simplify(_A ) , [{'score': 0.3_3_3, 'label': 'a'}, {'score': 0.3_3_3, 'label': 'b'}, {'score': 0.3_3_3, 'label': 'c'}] , )
__A : Optional[int] = image_classifier([image] * 5 , candidate_labels=['A', 'B', 'C'] , batch_size=2 )
self.assertEqual(
nested_simplify(_A ) , [
[
{'score': 0.3_3_3, 'label': ANY(_A )},
{'score': 0.3_3_3, 'label': ANY(_A )},
{'score': 0.3_3_3, 'label': ANY(_A )},
],
[
{'score': 0.3_3_3, 'label': ANY(_A )},
{'score': 0.3_3_3, 'label': ANY(_A )},
{'score': 0.3_3_3, 'label': ANY(_A )},
],
[
{'score': 0.3_3_3, 'label': ANY(_A )},
{'score': 0.3_3_3, 'label': ANY(_A )},
{'score': 0.3_3_3, 'label': ANY(_A )},
],
[
{'score': 0.3_3_3, 'label': ANY(_A )},
{'score': 0.3_3_3, 'label': ANY(_A )},
{'score': 0.3_3_3, 'label': ANY(_A )},
],
[
{'score': 0.3_3_3, 'label': ANY(_A )},
{'score': 0.3_3_3, 'label': ANY(_A )},
{'score': 0.3_3_3, 'label': ANY(_A )},
],
] , )
@slow
@require_torch
def UpperCAmelCase_ ( self ):
__A : Union[str, Any] = pipeline(
task='zero-shot-image-classification' , model='openai/clip-vit-base-patch32' , )
# This is an image of 2 cats with remotes and no planes
__A : Tuple = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
__A : Dict = image_classifier(_A , candidate_labels=['cat', 'plane', 'remote'] )
self.assertEqual(
nested_simplify(_A ) , [
{'score': 0.5_1_1, 'label': 'remote'},
{'score': 0.4_8_5, 'label': 'cat'},
{'score': 0.0_0_4, 'label': 'plane'},
] , )
__A : Optional[int] = image_classifier([image] * 5 , candidate_labels=['cat', 'plane', 'remote'] , batch_size=2 )
self.assertEqual(
nested_simplify(_A ) , [
[
{'score': 0.5_1_1, 'label': 'remote'},
{'score': 0.4_8_5, 'label': 'cat'},
{'score': 0.0_0_4, 'label': 'plane'},
],
]
* 5 , )
@slow
@require_tf
def UpperCAmelCase_ ( self ):
__A : str = pipeline(
task='zero-shot-image-classification' , model='openai/clip-vit-base-patch32' , framework='tf' )
# This is an image of 2 cats with remotes and no planes
__A : Dict = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
__A : Optional[int] = image_classifier(_A , candidate_labels=['cat', 'plane', 'remote'] )
self.assertEqual(
nested_simplify(_A ) , [
{'score': 0.5_1_1, 'label': 'remote'},
{'score': 0.4_8_5, 'label': 'cat'},
{'score': 0.0_0_4, 'label': 'plane'},
] , )
__A : str = image_classifier([image] * 5 , candidate_labels=['cat', 'plane', 'remote'] , batch_size=2 )
self.assertEqual(
nested_simplify(_A ) , [
[
{'score': 0.5_1_1, 'label': 'remote'},
{'score': 0.4_8_5, 'label': 'cat'},
{'score': 0.0_0_4, 'label': 'plane'},
],
]
* 5 , )
| 77 |
import os
import unittest
from transformers import BatchEncoding
from transformers.models.bert.tokenization_bert import (
BasicTokenizer,
WordpieceTokenizer,
_is_control,
_is_punctuation,
_is_whitespace,
)
from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer
from transformers.testing_utils import require_torch, slow
from ...test_tokenization_common import TokenizerTesterMixin
class _A( snake_case__ , unittest.TestCase ):
"""simple docstring"""
UpperCamelCase : Tuple = ProphetNetTokenizer
UpperCamelCase : Tuple = False
def UpperCAmelCase_ ( self ):
super().setUp()
__A : Any = [
'[UNK]',
'[CLS]',
'[SEP]',
'[PAD]',
'[MASK]',
'want',
'##want',
'##ed',
'wa',
'un',
'runn',
'##ing',
',',
'low',
'lowest',
]
__A : int = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] )
with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer:
vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) )
def UpperCAmelCase_ ( self , _A ):
__A : List[Any] = 'UNwant\u00E9d,running'
__A : List[str] = 'unwanted, running'
return input_text, output_text
def UpperCAmelCase_ ( self ):
__A : Tuple = self.tokenizer_class(self.vocab_file )
__A : List[Any] = tokenizer.tokenize('UNwant\u00E9d,running' )
self.assertListEqual(_A , ['un', '##want', '##ed', ',', 'runn', '##ing'] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(_A ) , [9, 6, 7, 12, 10, 11] )
def UpperCAmelCase_ ( self ):
__A : int = BasicTokenizer()
self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] )
def UpperCAmelCase_ ( self ):
__A : Union[str, Any] = BasicTokenizer(do_lower_case=_A )
self.assertListEqual(
tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] )
self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] )
def UpperCAmelCase_ ( self ):
__A : Optional[Any] = BasicTokenizer(do_lower_case=_A , strip_accents=_A )
self.assertListEqual(
tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] )
self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] )
def UpperCAmelCase_ ( self ):
__A : List[str] = BasicTokenizer(do_lower_case=_A , strip_accents=_A )
self.assertListEqual(
tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] )
self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] )
def UpperCAmelCase_ ( self ):
__A : Optional[int] = BasicTokenizer(do_lower_case=_A )
self.assertListEqual(
tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] )
self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] )
def UpperCAmelCase_ ( self ):
__A : Tuple = BasicTokenizer(do_lower_case=_A )
self.assertListEqual(
tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] )
def UpperCAmelCase_ ( self ):
__A : Tuple = BasicTokenizer(do_lower_case=_A , strip_accents=_A )
self.assertListEqual(
tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] )
def UpperCAmelCase_ ( self ):
__A : Dict = BasicTokenizer(do_lower_case=_A , strip_accents=_A )
self.assertListEqual(
tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] )
def UpperCAmelCase_ ( self ):
__A : List[Any] = BasicTokenizer(do_lower_case=_A , never_split=['[UNK]'] )
self.assertListEqual(
tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] )
def UpperCAmelCase_ ( self ):
__A : Optional[int] = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing']
__A : Optional[int] = {}
for i, token in enumerate(_A ):
__A : Tuple = i
__A : Tuple = WordpieceTokenizer(vocab=_A , unk_token='[UNK]' )
self.assertListEqual(tokenizer.tokenize('' ) , [] )
self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] )
self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] )
@require_torch
def UpperCAmelCase_ ( self ):
__A : int = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' )
__A : Optional[Any] = ['A long paragraph for summarization.', 'Another paragraph for summarization.']
__A : str = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102]
__A : str = tokenizer(_A , padding=_A , return_tensors='pt' )
self.assertIsInstance(_A , _A )
__A : List[str] = list(batch.input_ids.numpy()[0] )
self.assertListEqual(_A , _A )
self.assertEqual((2, 9) , batch.input_ids.shape )
self.assertEqual((2, 9) , batch.attention_mask.shape )
def UpperCAmelCase_ ( self ):
self.assertTrue(_is_whitespace(' ' ) )
self.assertTrue(_is_whitespace('\t' ) )
self.assertTrue(_is_whitespace('\r' ) )
self.assertTrue(_is_whitespace('\n' ) )
self.assertTrue(_is_whitespace('\u00A0' ) )
self.assertFalse(_is_whitespace('A' ) )
self.assertFalse(_is_whitespace('-' ) )
def UpperCAmelCase_ ( self ):
self.assertTrue(_is_control('\u0005' ) )
self.assertFalse(_is_control('A' ) )
self.assertFalse(_is_control(' ' ) )
self.assertFalse(_is_control('\t' ) )
self.assertFalse(_is_control('\r' ) )
def UpperCAmelCase_ ( self ):
self.assertTrue(_is_punctuation('-' ) )
self.assertTrue(_is_punctuation('$' ) )
self.assertTrue(_is_punctuation('`' ) )
self.assertTrue(_is_punctuation('.' ) )
self.assertFalse(_is_punctuation('A' ) )
self.assertFalse(_is_punctuation(' ' ) )
@slow
def UpperCAmelCase_ ( self ):
__A : Union[str, Any] = self.tokenizer_class.from_pretrained('microsoft/prophetnet-large-uncased' )
__A : Any = tokenizer.encode('sequence builders' , add_special_tokens=_A )
__A : List[Any] = tokenizer.encode('multi-sequence build' , add_special_tokens=_A )
__A : str = tokenizer.build_inputs_with_special_tokens(_A )
__A : Optional[Any] = tokenizer.build_inputs_with_special_tokens(_A , _A )
assert encoded_sentence == text + [102]
assert encoded_pair == text + [102] + text_a + [102]
| 77 | 1 |
from string import ascii_lowercase, ascii_uppercase
def _SCREAMING_SNAKE_CASE ( a ) -> str:
if not sentence:
return ""
__A : Union[str, Any] = dict(zip(a , a ) )
return lower_to_upper.get(sentence[0] , sentence[0] ) + sentence[1:]
if __name__ == "__main__":
from doctest import testmod
testmod()
| 77 |
import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_bert import BertTokenizer
UpperCAmelCase : List[str] = logging.get_logger(__name__)
UpperCAmelCase : int = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''}
UpperCAmelCase : Any = {
'''vocab_file''': {
'''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt''',
'''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt''',
'''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/vocab.txt''',
'''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/vocab.txt''',
'''bert-base-multilingual-uncased''': (
'''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt'''
),
'''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt''',
'''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt''',
'''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt''',
'''bert-large-uncased-whole-word-masking''': (
'''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt'''
),
'''bert-large-cased-whole-word-masking''': (
'''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt'''
),
'''bert-large-uncased-whole-word-masking-finetuned-squad''': (
'''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt'''
),
'''bert-large-cased-whole-word-masking-finetuned-squad''': (
'''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt'''
),
'''bert-base-cased-finetuned-mrpc''': (
'''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt'''
),
'''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt''',
'''bert-base-german-dbmdz-uncased''': (
'''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt'''
),
'''TurkuNLP/bert-base-finnish-cased-v1''': (
'''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt'''
),
'''TurkuNLP/bert-base-finnish-uncased-v1''': (
'''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt'''
),
'''wietsedv/bert-base-dutch-cased''': (
'''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt'''
),
},
'''tokenizer_file''': {
'''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json''',
'''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json''',
'''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json''',
'''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json''',
'''bert-base-multilingual-uncased''': (
'''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json'''
),
'''bert-base-multilingual-cased''': (
'''https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json'''
),
'''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json''',
'''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json''',
'''bert-large-uncased-whole-word-masking''': (
'''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json'''
),
'''bert-large-cased-whole-word-masking''': (
'''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json'''
),
'''bert-large-uncased-whole-word-masking-finetuned-squad''': (
'''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json'''
),
'''bert-large-cased-whole-word-masking-finetuned-squad''': (
'''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json'''
),
'''bert-base-cased-finetuned-mrpc''': (
'''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json'''
),
'''bert-base-german-dbmdz-cased''': (
'''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json'''
),
'''bert-base-german-dbmdz-uncased''': (
'''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json'''
),
'''TurkuNLP/bert-base-finnish-cased-v1''': (
'''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json'''
),
'''TurkuNLP/bert-base-finnish-uncased-v1''': (
'''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json'''
),
'''wietsedv/bert-base-dutch-cased''': (
'''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json'''
),
},
}
UpperCAmelCase : Optional[int] = {
'''bert-base-uncased''': 5_12,
'''bert-large-uncased''': 5_12,
'''bert-base-cased''': 5_12,
'''bert-large-cased''': 5_12,
'''bert-base-multilingual-uncased''': 5_12,
'''bert-base-multilingual-cased''': 5_12,
'''bert-base-chinese''': 5_12,
'''bert-base-german-cased''': 5_12,
'''bert-large-uncased-whole-word-masking''': 5_12,
'''bert-large-cased-whole-word-masking''': 5_12,
'''bert-large-uncased-whole-word-masking-finetuned-squad''': 5_12,
'''bert-large-cased-whole-word-masking-finetuned-squad''': 5_12,
'''bert-base-cased-finetuned-mrpc''': 5_12,
'''bert-base-german-dbmdz-cased''': 5_12,
'''bert-base-german-dbmdz-uncased''': 5_12,
'''TurkuNLP/bert-base-finnish-cased-v1''': 5_12,
'''TurkuNLP/bert-base-finnish-uncased-v1''': 5_12,
'''wietsedv/bert-base-dutch-cased''': 5_12,
}
UpperCAmelCase : List[Any] = {
'''bert-base-uncased''': {'''do_lower_case''': True},
'''bert-large-uncased''': {'''do_lower_case''': True},
'''bert-base-cased''': {'''do_lower_case''': False},
'''bert-large-cased''': {'''do_lower_case''': False},
'''bert-base-multilingual-uncased''': {'''do_lower_case''': True},
'''bert-base-multilingual-cased''': {'''do_lower_case''': False},
'''bert-base-chinese''': {'''do_lower_case''': False},
'''bert-base-german-cased''': {'''do_lower_case''': False},
'''bert-large-uncased-whole-word-masking''': {'''do_lower_case''': True},
'''bert-large-cased-whole-word-masking''': {'''do_lower_case''': False},
'''bert-large-uncased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': True},
'''bert-large-cased-whole-word-masking-finetuned-squad''': {'''do_lower_case''': False},
'''bert-base-cased-finetuned-mrpc''': {'''do_lower_case''': False},
'''bert-base-german-dbmdz-cased''': {'''do_lower_case''': False},
'''bert-base-german-dbmdz-uncased''': {'''do_lower_case''': True},
'''TurkuNLP/bert-base-finnish-cased-v1''': {'''do_lower_case''': False},
'''TurkuNLP/bert-base-finnish-uncased-v1''': {'''do_lower_case''': True},
'''wietsedv/bert-base-dutch-cased''': {'''do_lower_case''': False},
}
class _A( snake_case__ ):
"""simple docstring"""
UpperCamelCase : List[str] = VOCAB_FILES_NAMES
UpperCamelCase : Any = PRETRAINED_VOCAB_FILES_MAP
UpperCamelCase : Dict = PRETRAINED_INIT_CONFIGURATION
UpperCamelCase : List[str] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
UpperCamelCase : List[str] = BertTokenizer
def __init__( self , _A=None , _A=None , _A=True , _A="[UNK]" , _A="[SEP]" , _A="[PAD]" , _A="[CLS]" , _A="[MASK]" , _A=True , _A=None , **_A , ):
super().__init__(
_A , tokenizer_file=_A , do_lower_case=_A , unk_token=_A , sep_token=_A , pad_token=_A , cls_token=_A , mask_token=_A , tokenize_chinese_chars=_A , strip_accents=_A , **_A , )
__A : Optional[int] = json.loads(self.backend_tokenizer.normalizer.__getstate__() )
if (
normalizer_state.get('lowercase' , _A ) != do_lower_case
or normalizer_state.get('strip_accents' , _A ) != strip_accents
or normalizer_state.get('handle_chinese_chars' , _A ) != tokenize_chinese_chars
):
__A : Any = getattr(_A , normalizer_state.pop('type' ) )
__A : Union[str, Any] = do_lower_case
__A : Optional[int] = strip_accents
__A : List[Any] = tokenize_chinese_chars
__A : int = normalizer_class(**_A )
__A : Union[str, Any] = do_lower_case
def UpperCAmelCase_ ( self , _A , _A=None ):
__A : Tuple = [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 UpperCAmelCase_ ( self , _A , _A = None ):
__A : Optional[Any] = [self.sep_token_id]
__A : Optional[int] = [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 UpperCAmelCase_ ( self , _A , _A = None ):
__A : int = self._tokenizer.model.save(_A , name=_A )
return tuple(_A )
| 77 | 1 |
import timeit
import numpy as np
import datasets
from datasets.arrow_writer import ArrowWriter
from datasets.features.features import _ArrayXD
def _SCREAMING_SNAKE_CASE ( a ) -> Union[str, Any]:
def wrapper(*a , **a ):
__A : Dict = timeit.default_timer()
__A : Dict = func(*a , **a )
__A : str = timeit.default_timer() - starttime
return delta
__A : int = func.__name__
return wrapper
def _SCREAMING_SNAKE_CASE ( a , a=1_00 , a=None ) -> List[str]:
__A : Dict = []
__A : Dict = seq_shapes or {}
for i in range(a ):
__A : Union[str, Any] = {}
for col_id, (k, v) in enumerate(features.items() ):
if isinstance(a , _ArrayXD ):
__A : str = np.random.rand(*v.shape ).astype(v.dtype )
elif isinstance(a , datasets.Value ):
if v.dtype == "string":
__A : int = 'The small grey turtle was surprisingly fast when challenged.'
else:
__A : Optional[Any] = np.random.randint(10 , size=1 ).astype(v.dtype ).item()
elif isinstance(a , datasets.Sequence ):
while isinstance(a , datasets.Sequence ):
__A : Union[str, Any] = v.feature
__A : List[Any] = seq_shapes[k]
__A : List[str] = np.random.rand(*a ).astype(v.dtype )
__A : Optional[Any] = data
dummy_data.append((i, example) )
return dummy_data
def _SCREAMING_SNAKE_CASE ( a , a , a=1_00 , a=None ) -> List[str]:
__A : Optional[Any] = generate_examples(a , num_examples=a , seq_shapes=a )
with ArrowWriter(features=a , path=a ) as writer:
for key, record in dummy_data:
__A : Tuple = features.encode_example(a )
writer.write(a )
__A , __A : Optional[Any] = writer.finalize()
if not num_final_examples == num_examples:
raise ValueError(
F"""Error writing the dataset, wrote {num_final_examples} examples but should have written {num_examples}.""" )
__A : int = datasets.Dataset.from_file(filename=a , info=datasets.DatasetInfo(features=a ) )
return dataset
| 77 |
import unittest
from accelerate import debug_launcher
from accelerate.test_utils import require_cpu, test_ops, test_script
@require_cpu
class _A( unittest.TestCase ):
"""simple docstring"""
def UpperCAmelCase_ ( self ):
debug_launcher(test_script.main )
def UpperCAmelCase_ ( self ):
debug_launcher(test_ops.main )
| 77 | 1 |
def _SCREAMING_SNAKE_CASE ( a = 60_08_51_47_51_43 ) -> int:
try:
__A : List[Any] = int(a )
except (TypeError, ValueError):
raise TypeError('Parameter n must be int or castable to int.' )
if n <= 0:
raise ValueError('Parameter n must be greater than or equal to one.' )
__A : Dict = 1
__A : List[str] = 2
while i * i <= n:
while n % i == 0:
__A : Dict = i
n //= i
i += 1
if n > 1:
__A : int = n
return int(a )
if __name__ == "__main__":
print(F"""{solution() = }""")
| 77 |
import json
import os
import shutil
import tempfile
import unittest
import numpy as np
import pytest
from transformers import CLIPTokenizer, CLIPTokenizerFast
from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available
if is_vision_available():
from PIL import Image
from transformers import OwlViTImageProcessor, OwlViTProcessor
@require_vision
class _A( unittest.TestCase ):
"""simple docstring"""
def UpperCAmelCase_ ( self ):
__A : Tuple = tempfile.mkdtemp()
# fmt: off
__A : Union[str, Any] = ['', 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', 'lo', 'l</w>', 'w</w>', 'r</w>', 't</w>', 'low</w>', 'er</w>', 'lowest</w>', 'newer</w>', 'wider', '<unk>', '<|startoftext|>', '<|endoftext|>']
# fmt: on
__A : Dict = dict(zip(_A , range(len(_A ) ) ) )
__A : int = ['#version: 0.2', 'l o', 'lo w</w>', 'e r</w>', '']
__A : Optional[Any] = {'unk_token': '<unk>'}
__A : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] )
__A : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['merges_file'] )
with open(self.vocab_file , 'w' , encoding='utf-8' ) as fp:
fp.write(json.dumps(_A ) + '\n' )
with open(self.merges_file , 'w' , encoding='utf-8' ) as fp:
fp.write('\n'.join(_A ) )
__A : Union[str, Any] = {
'do_resize': True,
'size': 20,
'do_center_crop': True,
'crop_size': 18,
'do_normalize': True,
'image_mean': [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3],
'image_std': [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1],
}
__A : List[str] = os.path.join(self.tmpdirname , _A )
with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp:
json.dump(_A , _A )
def UpperCAmelCase_ ( self , **_A ):
return CLIPTokenizer.from_pretrained(self.tmpdirname , pad_token='!' , **_A )
def UpperCAmelCase_ ( self , **_A ):
return CLIPTokenizerFast.from_pretrained(self.tmpdirname , pad_token='!' , **_A )
def UpperCAmelCase_ ( self , **_A ):
return OwlViTImageProcessor.from_pretrained(self.tmpdirname , **_A )
def UpperCAmelCase_ ( self ):
shutil.rmtree(self.tmpdirname )
def UpperCAmelCase_ ( self ):
__A : List[Any] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )]
__A : Optional[int] = [Image.fromarray(np.moveaxis(_A , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def UpperCAmelCase_ ( self ):
__A : List[str] = self.get_tokenizer()
__A : Dict = self.get_rust_tokenizer()
__A : Optional[Any] = self.get_image_processor()
__A : Dict = OwlViTProcessor(tokenizer=_A , image_processor=_A )
processor_slow.save_pretrained(self.tmpdirname )
__A : Optional[int] = OwlViTProcessor.from_pretrained(self.tmpdirname , use_fast=_A )
__A : Any = OwlViTProcessor(tokenizer=_A , image_processor=_A )
processor_fast.save_pretrained(self.tmpdirname )
__A : Optional[int] = OwlViTProcessor.from_pretrained(self.tmpdirname )
self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() )
self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() )
self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() )
self.assertIsInstance(processor_slow.tokenizer , _A )
self.assertIsInstance(processor_fast.tokenizer , _A )
self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() )
self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() )
self.assertIsInstance(processor_slow.image_processor , _A )
self.assertIsInstance(processor_fast.image_processor , _A )
def UpperCAmelCase_ ( self ):
__A : Tuple = OwlViTProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
__A : str = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' )
__A : int = self.get_image_processor(do_normalize=_A )
__A : int = OwlViTProcessor.from_pretrained(
self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_A )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() )
self.assertIsInstance(processor.tokenizer , _A )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , _A )
def UpperCAmelCase_ ( self ):
__A : List[str] = self.get_image_processor()
__A : Optional[Any] = self.get_tokenizer()
__A : Union[str, Any] = OwlViTProcessor(tokenizer=_A , image_processor=_A )
__A : List[Any] = self.prepare_image_inputs()
__A : Any = image_processor(_A , return_tensors='np' )
__A : Tuple = processor(images=_A , return_tensors='np' )
for key in input_image_proc.keys():
self.assertAlmostEqual(input_image_proc[key].sum() , input_processor[key].sum() , delta=1e-2 )
def UpperCAmelCase_ ( self ):
__A : Tuple = self.get_image_processor()
__A : int = self.get_tokenizer()
__A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A )
__A : Union[str, Any] = 'lower newer'
__A : Any = processor(text=_A , return_tensors='np' )
__A : Dict = tokenizer(_A , return_tensors='np' )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key][0].tolist() , encoded_processor[key][0].tolist() )
def UpperCAmelCase_ ( self ):
__A : Optional[int] = self.get_image_processor()
__A : List[str] = self.get_tokenizer()
__A : Tuple = OwlViTProcessor(tokenizer=_A , image_processor=_A )
__A : Tuple = 'lower newer'
__A : Union[str, Any] = self.prepare_image_inputs()
__A : List[Any] = processor(text=_A , images=_A )
self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask', 'pixel_values'] )
# test if it raises when no input is passed
with pytest.raises(_A ):
processor()
def UpperCAmelCase_ ( self ):
__A : Optional[int] = 'google/owlvit-base-patch32'
__A : str = OwlViTProcessor.from_pretrained(_A )
__A : Any = ['cat', 'nasa badge']
__A : List[Any] = processor(text=_A )
__A : Dict = 16
self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] )
self.assertEqual(inputs['input_ids'].shape , (2, seq_length) )
# test if it raises when no input is passed
with pytest.raises(_A ):
processor()
def UpperCAmelCase_ ( self ):
__A : Tuple = 'google/owlvit-base-patch32'
__A : Any = OwlViTProcessor.from_pretrained(_A )
__A : int = [['cat', 'nasa badge'], ['person']]
__A : str = processor(text=_A )
__A : int = 16
__A : Optional[int] = len(_A )
__A : int = max([len(_A ) for texts in input_texts] )
self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] )
self.assertEqual(inputs['input_ids'].shape , (batch_size * num_max_text_queries, seq_length) )
# test if it raises when no input is passed
with pytest.raises(_A ):
processor()
def UpperCAmelCase_ ( self ):
__A : int = 'google/owlvit-base-patch32'
__A : List[str] = OwlViTProcessor.from_pretrained(_A )
__A : Tuple = ['cat', 'nasa badge']
__A : Dict = processor(text=_A )
__A : Tuple = 16
__A : str = inputs['input_ids']
__A : str = [
[49406, 2368, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[49406, 6841, 11301, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
]
self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'attention_mask'] )
self.assertEqual(inputs['input_ids'].shape , (2, seq_length) )
self.assertListEqual(list(input_ids[0] ) , predicted_ids[0] )
self.assertListEqual(list(input_ids[1] ) , predicted_ids[1] )
def UpperCAmelCase_ ( self ):
__A : Dict = self.get_image_processor()
__A : Optional[int] = self.get_tokenizer()
__A : Dict = OwlViTProcessor(tokenizer=_A , image_processor=_A )
__A : Any = self.prepare_image_inputs()
__A : Tuple = self.prepare_image_inputs()
__A : Any = processor(images=_A , query_images=_A )
self.assertListEqual(list(inputs.keys() ) , ['query_pixel_values', 'pixel_values'] )
# test if it raises when no input is passed
with pytest.raises(_A ):
processor()
def UpperCAmelCase_ ( self ):
__A : Optional[Any] = self.get_image_processor()
__A : Union[str, Any] = self.get_tokenizer()
__A : Optional[int] = OwlViTProcessor(tokenizer=_A , image_processor=_A )
__A : int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
__A : Any = processor.batch_decode(_A )
__A : Union[str, Any] = tokenizer.batch_decode(_A )
self.assertListEqual(_A , _A )
| 77 | 1 |
import os
import sys
import unittest
UpperCAmelCase : str = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, '''utils'''))
import get_test_info # noqa: E402
from get_test_info import ( # noqa: E402
get_model_to_test_mapping,
get_model_to_tester_mapping,
get_test_to_tester_mapping,
)
UpperCAmelCase : Union[str, Any] = os.path.join('''tests''', '''models''', '''bert''', '''test_modeling_bert.py''')
UpperCAmelCase : Dict = os.path.join('''tests''', '''models''', '''blip''', '''test_modeling_blip.py''')
class _A( unittest.TestCase ):
"""simple docstring"""
def UpperCAmelCase_ ( self ):
__A : List[str] = get_test_to_tester_mapping(_A )
__A : Tuple = get_test_to_tester_mapping(_A )
__A : List[Any] = {'BertModelTest': 'BertModelTester'}
__A : Optional[Any] = {
'BlipModelTest': 'BlipModelTester',
'BlipTextImageModelTest': 'BlipTextImageModelsModelTester',
'BlipTextModelTest': 'BlipTextModelTester',
'BlipTextRetrievalModelTest': 'BlipTextRetrievalModelTester',
'BlipVQAModelTest': 'BlipVQAModelTester',
'BlipVisionModelTest': 'BlipVisionModelTester',
}
self.assertEqual(get_test_info.to_json(_A ) , _A )
self.assertEqual(get_test_info.to_json(_A ) , _A )
def UpperCAmelCase_ ( self ):
__A : Any = get_model_to_test_mapping(_A )
__A : str = get_model_to_test_mapping(_A )
__A : Dict = {
'BertForMaskedLM': ['BertModelTest'],
'BertForMultipleChoice': ['BertModelTest'],
'BertForNextSentencePrediction': ['BertModelTest'],
'BertForPreTraining': ['BertModelTest'],
'BertForQuestionAnswering': ['BertModelTest'],
'BertForSequenceClassification': ['BertModelTest'],
'BertForTokenClassification': ['BertModelTest'],
'BertLMHeadModel': ['BertModelTest'],
'BertModel': ['BertModelTest'],
}
__A : Optional[int] = {
'BlipForConditionalGeneration': ['BlipTextImageModelTest'],
'BlipForImageTextRetrieval': ['BlipTextRetrievalModelTest'],
'BlipForQuestionAnswering': ['BlipVQAModelTest'],
'BlipModel': ['BlipModelTest'],
'BlipTextModel': ['BlipTextModelTest'],
'BlipVisionModel': ['BlipVisionModelTest'],
}
self.assertEqual(get_test_info.to_json(_A ) , _A )
self.assertEqual(get_test_info.to_json(_A ) , _A )
def UpperCAmelCase_ ( self ):
__A : str = get_model_to_tester_mapping(_A )
__A : Optional[Any] = get_model_to_tester_mapping(_A )
__A : Optional[int] = {
'BertForMaskedLM': ['BertModelTester'],
'BertForMultipleChoice': ['BertModelTester'],
'BertForNextSentencePrediction': ['BertModelTester'],
'BertForPreTraining': ['BertModelTester'],
'BertForQuestionAnswering': ['BertModelTester'],
'BertForSequenceClassification': ['BertModelTester'],
'BertForTokenClassification': ['BertModelTester'],
'BertLMHeadModel': ['BertModelTester'],
'BertModel': ['BertModelTester'],
}
__A : str = {
'BlipForConditionalGeneration': ['BlipTextImageModelsModelTester'],
'BlipForImageTextRetrieval': ['BlipTextRetrievalModelTester'],
'BlipForQuestionAnswering': ['BlipVQAModelTester'],
'BlipModel': ['BlipModelTester'],
'BlipTextModel': ['BlipTextModelTester'],
'BlipVisionModel': ['BlipVisionModelTester'],
}
self.assertEqual(get_test_info.to_json(_A ) , _A )
self.assertEqual(get_test_info.to_json(_A ) , _A )
| 77 |
import argparse
import json
import os
import fairseq
import torch
from fairseq.data import Dictionary
from transformers import (
WavaVecaConformerConfig,
WavaVecaConformerForCTC,
WavaVecaConformerForPreTraining,
WavaVecaCTCTokenizer,
WavaVecaFeatureExtractor,
WavaVecaProcessor,
logging,
)
logging.set_verbosity_info()
UpperCAmelCase : Optional[Any] = logging.get_logger(__name__)
UpperCAmelCase : Optional[Any] = {
'''post_extract_proj''': '''feature_projection.projection''',
'''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''',
'''self_attn.linear_k''': '''encoder.layers.*.self_attn.linear_k''',
'''self_attn.linear_v''': '''encoder.layers.*.self_attn.linear_v''',
'''self_attn.linear_q''': '''encoder.layers.*.self_attn.linear_q''',
'''self_attn.pos_bias_u''': '''encoder.layers.*.self_attn.pos_bias_u''',
'''self_attn.pos_bias_v''': '''encoder.layers.*.self_attn.pos_bias_v''',
'''self_attn.linear_out''': '''encoder.layers.*.self_attn.linear_out''',
'''self_attn.linear_pos''': '''encoder.layers.*.self_attn.linear_pos''',
'''self_attn.rotary_emb''': '''encoder.embed_positions''',
'''self_attn_layer_norm''': '''encoder.layers.*.self_attn_layer_norm''',
'''conv_module.pointwise_conv1''': '''encoder.layers.*.conv_module.pointwise_conv1''',
'''conv_module.pointwise_conv2''': '''encoder.layers.*.conv_module.pointwise_conv2''',
'''conv_module.depthwise_conv''': '''encoder.layers.*.conv_module.depthwise_conv''',
'''conv_module.batch_norm''': '''encoder.layers.*.conv_module.batch_norm''',
'''conv_module.layer_norm''': '''encoder.layers.*.conv_module.layer_norm''',
'''ffn1.w_1''': '''encoder.layers.*.ffn1.intermediate_dense''',
'''ffn1.w_2''': '''encoder.layers.*.ffn1.output_dense''',
'''ffn1.layer_norm''': '''encoder.layers.*.ffn1_layer_norm''',
'''ffn2.w_1''': '''encoder.layers.*.ffn2.intermediate_dense''',
'''ffn2.w_2''': '''encoder.layers.*.ffn2.output_dense''',
'''ffn2.layer_norm''': '''encoder.layers.*.ffn2_layer_norm''',
'''final_layer_norm''': '''encoder.layers.*.final_layer_norm''',
'''encoder.layer_norm''': '''encoder.layer_norm''',
'''w2v_model.layer_norm''': '''feature_projection.layer_norm''',
'''quantizer.weight_proj''': '''quantizer.weight_proj''',
'''quantizer.vars''': '''quantizer.codevectors''',
'''project_q''': '''project_q''',
'''final_proj''': '''project_hid''',
'''w2v_encoder.proj''': '''lm_head''',
'''mask_emb''': '''masked_spec_embed''',
}
UpperCAmelCase : Union[str, Any] = [
'''lm_head''',
'''quantizer.weight_proj''',
'''quantizer.codevectors''',
'''project_q''',
'''project_hid''',
]
def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> Tuple:
for attribute in key.split('.' ):
__A : Dict = getattr(a , a )
if weight_type is not None:
__A : Any = getattr(a , a ).shape
else:
__A : Any = hf_pointer.shape
if hf_shape != value.shape:
raise ValueError(
F"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be"""
F""" {value.shape} for {full_name}""" )
if weight_type == "weight":
__A : Union[str, Any] = value
elif weight_type == "weight_g":
__A : Dict = value
elif weight_type == "weight_v":
__A : Optional[int] = value
elif weight_type == "bias":
__A : int = value
elif weight_type == "running_mean":
__A : Union[str, Any] = value
elif weight_type == "running_var":
__A : Union[str, Any] = value
elif weight_type == "num_batches_tracked":
__A : Any = value
elif weight_type == "inv_freq":
__A : Optional[Any] = value
else:
__A : int = value
logger.info(F"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" )
def _SCREAMING_SNAKE_CASE ( a , a , a ) -> Union[str, Any]:
__A : Any = []
__A : Optional[int] = fairseq_model.state_dict()
__A : Union[str, Any] = hf_model.wavaveca_conformer.feature_extractor
for name, value in fairseq_dict.items():
__A : int = False
if "conv_layers" in name:
load_conv_layer(
a , a , a , a , hf_model.config.feat_extract_norm == 'group' , )
__A : Optional[int] = True
else:
for key, mapped_key in MAPPING.items():
__A : Any = 'wav2vec2_conformer.' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key
if key in name or key.split('w2v_model.' )[-1] == name.split('.' )[0]:
__A : Optional[Any] = True
if "*" in mapped_key:
__A : str = name.split(a )[0].split('.' )[-2]
__A : int = mapped_key.replace('*' , a )
if "pos_bias_u" in name:
__A : Optional[int] = None
elif "pos_bias_v" in name:
__A : Dict = None
elif "weight_g" in name:
__A : Optional[Any] = 'weight_g'
elif "weight_v" in name:
__A : Dict = 'weight_v'
elif "bias" in name:
__A : Tuple = 'bias'
elif "weight" in name:
# TODO: don't match quantizer.weight_proj
__A : int = 'weight'
elif "running_mean" in name:
__A : str = 'running_mean'
elif "inv_freq" in name:
__A : List[Any] = 'inv_freq'
elif "running_var" in name:
__A : Union[str, Any] = 'running_var'
elif "num_batches_tracked" in name:
__A : Optional[Any] = 'num_batches_tracked'
else:
__A : List[str] = None
set_recursively(a , a , a , a , a )
continue
if not is_used:
unused_weights.append(a )
logger.warning(F"""Unused weights: {unused_weights}""" )
def _SCREAMING_SNAKE_CASE ( a , a , a , a , a ) -> Any:
__A : str = full_name.split('conv_layers.' )[-1]
__A : str = name.split('.' )
__A : Dict = int(items[0] )
__A : Any = 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.""" )
__A : int = 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.""" )
__A : int = 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.""" )
__A : Any = value
logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" )
elif "weight" in name:
if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape:
raise ValueError(
F"""{full_name} has size {value.shape}, but"""
F""" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found.""" )
__A : List[str] = value
logger.info(F"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" )
else:
unused_weights.append(a )
@torch.no_grad()
def _SCREAMING_SNAKE_CASE ( a , a , a=None , a=None , a=True ) -> Any:
if config_path is not None:
__A : Tuple = WavaVecaConformerConfig.from_pretrained(a , hidden_act='swish' )
else:
__A : Optional[Any] = WavaVecaConformerConfig()
if "rope" in checkpoint_path:
__A : Dict = 'rotary'
if is_finetuned:
if dict_path:
__A : Dict = Dictionary.load(a )
# important change bos & pad token id since CTC symbol is <pad> and
# not <s> as in fairseq
__A : int = target_dict.pad_index
__A : List[Any] = target_dict.bos_index
__A : Any = target_dict.eos_index
__A : Dict = len(target_dict.symbols )
__A : Optional[Any] = os.path.join(a , 'vocab.json' )
if not os.path.isdir(a ):
logger.error('--pytorch_dump_folder_path ({}) should be a directory'.format(a ) )
return
os.makedirs(a , exist_ok=a )
__A : List[str] = target_dict.indices
# fairseq has the <pad> and <s> switched
__A : int = 0
__A : Optional[Any] = 1
with open(a , 'w' , encoding='utf-8' ) as vocab_handle:
json.dump(a , a )
__A : Optional[Any] = WavaVecaCTCTokenizer(
a , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token='|' , do_lower_case=a , )
__A : Tuple = True if config.feat_extract_norm == 'layer' else False
__A : Any = WavaVecaFeatureExtractor(
feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=a , return_attention_mask=a , )
__A : Optional[int] = WavaVecaProcessor(feature_extractor=a , tokenizer=a )
processor.save_pretrained(a )
__A : List[Any] = WavaVecaConformerForCTC(a )
else:
__A : List[Any] = WavaVecaConformerForPreTraining(a )
if is_finetuned:
__A , __A , __A : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task(
[checkpoint_path] , arg_overrides={'data': '/'.join(dict_path.split('/' )[:-1] )} )
else:
__A : Optional[Any] = argparse.Namespace(task='audio_pretraining' )
__A : str = fairseq.tasks.setup_task(a )
__A , __A , __A : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=a )
__A : Tuple = model[0].eval()
recursively_load_weights(a , a , not is_finetuned )
hf_wavavec.save_pretrained(a )
if __name__ == "__main__":
UpperCAmelCase : int = argparse.ArgumentParser()
parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''')
parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''')
parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''')
parser.add_argument(
'''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not'''
)
UpperCAmelCase : List[str] = parser.parse_args()
convert_wavaveca_conformer_checkpoint(
args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned
)
| 77 | 1 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_speech_available,
is_torch_available,
)
UpperCAmelCase : Optional[Any] = {
'''configuration_trocr''': ['''TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''TrOCRConfig'''],
'''processing_trocr''': ['''TrOCRProcessor'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase : int = [
'''TROCR_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''TrOCRForCausalLM''',
'''TrOCRPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig
from .processing_trocr import TrOCRProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel
else:
import sys
UpperCAmelCase : Optional[int] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 77 |
from abc import ABC, abstractmethod
from argparse import ArgumentParser
class _A( snake_case__ ):
"""simple docstring"""
@staticmethod
@abstractmethod
def UpperCAmelCase_ ( _A ):
raise NotImplementedError()
@abstractmethod
def UpperCAmelCase_ ( self ):
raise NotImplementedError()
| 77 | 1 |
import random
import unittest
import numpy as np
from diffusers import (
DPMSolverMultistepScheduler,
EulerAncestralDiscreteScheduler,
EulerDiscreteScheduler,
LMSDiscreteScheduler,
OnnxStableDiffusionImgaImgPipeline,
PNDMScheduler,
)
from diffusers.utils import floats_tensor
from diffusers.utils.testing_utils import (
is_onnx_available,
load_image,
nightly,
require_onnxruntime,
require_torch_gpu,
)
from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin
if is_onnx_available():
import onnxruntime as ort
class _A( snake_case__ , unittest.TestCase ):
"""simple docstring"""
UpperCamelCase : int = '''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline'''
def UpperCAmelCase_ ( self , _A=0 ):
__A : List[str] = floats_tensor((1, 3, 128, 128) , rng=random.Random(_A ) )
__A : Optional[Any] = np.random.RandomState(_A )
__A : List[Any] = {
'prompt': 'A painting of a squirrel eating a burger',
'image': image,
'generator': generator,
'num_inference_steps': 3,
'strength': 0.7_5,
'guidance_scale': 7.5,
'output_type': 'numpy',
}
return inputs
def UpperCAmelCase_ ( self ):
__A : List[Any] = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' )
pipe.set_progress_bar_config(disable=_A )
__A : Tuple = self.get_dummy_inputs()
__A : List[str] = pipe(**_A ).images
__A : int = image[0, -3:, -3:, -1].flatten()
assert image.shape == (1, 128, 128, 3)
__A : Any = np.array([0.6_9_6_4_3, 0.5_8_4_8_4, 0.5_0_3_1_4, 0.5_8_7_6_0, 0.5_5_3_6_8, 0.5_9_6_4_3, 0.5_1_5_2_9, 0.4_1_2_1_7, 0.4_9_0_8_7] )
assert np.abs(image_slice - expected_slice ).max() < 1e-1
def UpperCAmelCase_ ( self ):
__A : Dict = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' )
__A : Optional[int] = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=_A )
pipe.set_progress_bar_config(disable=_A )
__A : Optional[Any] = self.get_dummy_inputs()
__A : Optional[int] = pipe(**_A ).images
__A : Union[str, Any] = image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
__A : Optional[int] = np.array([0.6_1_7_3_7, 0.5_4_6_4_2, 0.5_3_1_8_3, 0.5_4_4_6_5, 0.5_2_7_4_2, 0.6_0_5_2_5, 0.4_9_9_6_9, 0.4_0_6_5_5, 0.4_8_1_5_4] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
def UpperCAmelCase_ ( self ):
__A : Tuple = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' )
__A : Union[str, Any] = LMSDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=_A )
# warmup pass to apply optimizations
__A : str = pipe(**self.get_dummy_inputs() )
__A : Optional[int] = self.get_dummy_inputs()
__A : List[Any] = pipe(**_A ).images
__A : str = image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
__A : Dict = np.array([0.5_2_7_6_1, 0.5_9_9_7_7, 0.4_9_0_3_3, 0.4_9_6_1_9, 0.5_4_2_8_2, 0.5_0_3_1_1, 0.4_7_6_0_0, 0.4_0_9_1_8, 0.4_5_2_0_3] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
def UpperCAmelCase_ ( self ):
__A : Any = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' )
__A : Optional[Any] = EulerDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=_A )
__A : Tuple = self.get_dummy_inputs()
__A : Any = pipe(**_A ).images
__A : str = image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
__A : Union[str, Any] = np.array([0.5_2_9_1_1, 0.6_0_0_0_4, 0.4_9_2_2_9, 0.4_9_8_0_5, 0.5_4_5_0_2, 0.5_0_6_8_0, 0.4_7_7_7_7, 0.4_1_0_2_8, 0.4_5_3_0_4] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
def UpperCAmelCase_ ( self ):
__A : Optional[int] = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' )
__A : Tuple = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=_A )
__A : List[str] = self.get_dummy_inputs()
__A : int = pipe(**_A ).images
__A : Optional[Any] = image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
__A : List[str] = np.array([0.5_2_9_1_1, 0.6_0_0_0_4, 0.4_9_2_2_9, 0.4_9_8_0_5, 0.5_4_5_0_2, 0.5_0_6_8_0, 0.4_7_7_7_7, 0.4_1_0_2_8, 0.4_5_3_0_4] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
def UpperCAmelCase_ ( self ):
__A : str = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' )
__A : Dict = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=_A )
__A : Optional[Any] = self.get_dummy_inputs()
__A : List[str] = pipe(**_A ).images
__A : Optional[Any] = image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
__A : int = np.array([0.6_5_3_3_1, 0.5_8_2_7_7, 0.4_8_2_0_4, 0.5_6_0_5_9, 0.5_3_6_6_5, 0.5_6_2_3_5, 0.5_0_9_6_9, 0.4_0_0_0_9, 0.4_6_5_5_2] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
@nightly
@require_onnxruntime
@require_torch_gpu
class _A( unittest.TestCase ):
"""simple docstring"""
@property
def UpperCAmelCase_ ( self ):
return (
"CUDAExecutionProvider",
{
"gpu_mem_limit": "15000000000", # 15GB
"arena_extend_strategy": "kSameAsRequested",
},
)
@property
def UpperCAmelCase_ ( self ):
__A : int = ort.SessionOptions()
__A : List[Any] = False
return options
def UpperCAmelCase_ ( self ):
__A : Any = load_image(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
'/img2img/sketch-mountains-input.jpg' )
__A : Optional[int] = init_image.resize((768, 512) )
# using the PNDM scheduler by default
__A : Union[str, Any] = OnnxStableDiffusionImgaImgPipeline.from_pretrained(
'CompVis/stable-diffusion-v1-4' , revision='onnx' , safety_checker=_A , feature_extractor=_A , provider=self.gpu_provider , sess_options=self.gpu_options , )
pipe.set_progress_bar_config(disable=_A )
__A : int = 'A fantasy landscape, trending on artstation'
__A : List[str] = np.random.RandomState(0 )
__A : Optional[Any] = pipe(
prompt=_A , image=_A , strength=0.7_5 , guidance_scale=7.5 , num_inference_steps=10 , generator=_A , output_type='np' , )
__A : int = output.images
__A : Dict = images[0, 255:258, 383:386, -1]
assert images.shape == (1, 512, 768, 3)
__A : List[str] = np.array([0.4_9_0_9, 0.5_0_5_9, 0.5_3_7_2, 0.4_6_2_3, 0.4_8_7_6, 0.5_0_4_9, 0.4_8_2_0, 0.4_9_5_6, 0.5_0_1_9] )
# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues
assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
def UpperCAmelCase_ ( self ):
__A : Optional[Any] = load_image(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
'/img2img/sketch-mountains-input.jpg' )
__A : str = init_image.resize((768, 512) )
__A : Tuple = LMSDiscreteScheduler.from_pretrained(
'runwayml/stable-diffusion-v1-5' , subfolder='scheduler' , revision='onnx' )
__A : Any = OnnxStableDiffusionImgaImgPipeline.from_pretrained(
'runwayml/stable-diffusion-v1-5' , revision='onnx' , scheduler=_A , safety_checker=_A , feature_extractor=_A , provider=self.gpu_provider , sess_options=self.gpu_options , )
pipe.set_progress_bar_config(disable=_A )
__A : Optional[int] = 'A fantasy landscape, trending on artstation'
__A : Tuple = np.random.RandomState(0 )
__A : int = pipe(
prompt=_A , image=_A , strength=0.7_5 , guidance_scale=7.5 , num_inference_steps=20 , generator=_A , output_type='np' , )
__A : Tuple = output.images
__A : Optional[int] = images[0, 255:258, 383:386, -1]
assert images.shape == (1, 512, 768, 3)
__A : Tuple = np.array([0.8_0_4_3, 0.9_2_6, 0.9_5_8_1, 0.8_1_1_9, 0.8_9_5_4, 0.9_1_3, 0.7_2_0_9, 0.7_4_6_3, 0.7_4_3_1] )
# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues
assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
| 77 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_torch_available,
)
UpperCAmelCase : Optional[int] = {'''configuration_unispeech''': ['''UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''UniSpeechConfig''']}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCAmelCase : Optional[Any] = [
'''UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''UniSpeechForCTC''',
'''UniSpeechForPreTraining''',
'''UniSpeechForSequenceClassification''',
'''UniSpeechModel''',
'''UniSpeechPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_unispeech import UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP, UniSpeechConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_unispeech import (
UNISPEECH_PRETRAINED_MODEL_ARCHIVE_LIST,
UniSpeechForCTC,
UniSpeechForPreTraining,
UniSpeechForSequenceClassification,
UniSpeechModel,
UniSpeechPreTrainedModel,
)
else:
import sys
UpperCAmelCase : Any = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 77 | 1 |
import inspect
import unittest
from transformers import RegNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor
if is_flax_available():
import jax
import jax.numpy as jnp
from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel
if is_vision_available():
from PIL import Image
from transformers import AutoImageProcessor
class _A( unittest.TestCase ):
"""simple docstring"""
def __init__( self , _A , _A=3 , _A=32 , _A=3 , _A=10 , _A=[10, 20, 30, 40] , _A=[1, 1, 2, 1] , _A=True , _A=True , _A="relu" , _A=3 , _A=None , ):
__A : int = parent
__A : Tuple = batch_size
__A : Optional[int] = image_size
__A : Optional[int] = num_channels
__A : int = embeddings_size
__A : List[str] = hidden_sizes
__A : Union[str, Any] = depths
__A : Optional[Any] = is_training
__A : str = use_labels
__A : Optional[Any] = hidden_act
__A : str = num_labels
__A : List[str] = scope
__A : int = len(_A )
def UpperCAmelCase_ ( self ):
__A : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
__A : List[str] = self.get_config()
return config, pixel_values
def UpperCAmelCase_ ( self ):
return RegNetConfig(
num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , )
def UpperCAmelCase_ ( self , _A , _A ):
__A : int = FlaxRegNetModel(config=_A )
__A : Tuple = model(_A )
# Output shape (b, c, h, w)
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , )
def UpperCAmelCase_ ( self , _A , _A ):
__A : Dict = self.num_labels
__A : List[str] = FlaxRegNetForImageClassification(config=_A )
__A : Dict = model(_A )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def UpperCAmelCase_ ( self ):
__A : Dict = self.prepare_config_and_inputs()
__A , __A : Dict = config_and_inputs
__A : Dict = {'pixel_values': pixel_values}
return config, inputs_dict
@require_flax
class _A( snake_case__ , unittest.TestCase ):
"""simple docstring"""
UpperCamelCase : List[str] = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()
UpperCamelCase : List[str] = False
UpperCamelCase : Optional[int] = False
UpperCamelCase : List[str] = False
def UpperCAmelCase_ ( self ):
__A : str = FlaxRegNetModelTester(self )
__A : Any = ConfigTester(self , config_class=_A , has_text_modality=_A )
def UpperCAmelCase_ ( self ):
self.create_and_test_config_common_properties()
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_with_num_labels()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
def UpperCAmelCase_ ( self ):
return
def UpperCAmelCase_ ( self ):
__A : Tuple = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_A )
def UpperCAmelCase_ ( self ):
__A : List[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*_A )
@unittest.skip(reason='RegNet does not use inputs_embeds' )
def UpperCAmelCase_ ( self ):
pass
@unittest.skip(reason='RegNet does not support input and output embeddings' )
def UpperCAmelCase_ ( self ):
pass
def UpperCAmelCase_ ( self ):
__A , __A : List[str] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__A : int = model_class(_A )
__A : List[Any] = inspect.signature(model.__call__ )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__A : Dict = [*signature.parameters.keys()]
__A : List[str] = ['pixel_values']
self.assertListEqual(arg_names[:1] , _A )
def UpperCAmelCase_ ( self ):
def check_hidden_states_output(_A , _A , _A ):
__A : int = model_class(_A )
__A : str = model(**self._prepare_for_class(_A , _A ) )
__A : Dict = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
__A : int = self.model_tester.num_stages
self.assertEqual(len(_A ) , expected_num_stages + 1 )
__A , __A : List[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__A : Optional[int] = True
check_hidden_states_output(_A , _A , _A )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
__A : int = True
check_hidden_states_output(_A , _A , _A )
def UpperCAmelCase_ ( self ):
__A , __A : List[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
with self.subTest(model_class.__name__ ):
__A : int = self._prepare_for_class(_A , _A )
__A : Tuple = model_class(_A )
@jax.jit
def model_jitted(_A , **_A ):
return model(pixel_values=_A , **_A )
with self.subTest('JIT Enabled' ):
__A : str = model_jitted(**_A ).to_tuple()
with self.subTest('JIT Disabled' ):
with jax.disable_jit():
__A : Optional[int] = model_jitted(**_A ).to_tuple()
self.assertEqual(len(_A ) , len(_A ) )
for jitted_output, output in zip(_A , _A ):
self.assertEqual(jitted_output.shape , output.shape )
def _SCREAMING_SNAKE_CASE ( ) -> Optional[Any]:
__A : Union[str, Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
return image
@require_flax
class _A( unittest.TestCase ):
"""simple docstring"""
@cached_property
def UpperCAmelCase_ ( self ):
return AutoImageProcessor.from_pretrained('facebook/regnet-y-040' ) if is_vision_available() else None
@slow
def UpperCAmelCase_ ( self ):
__A : str = FlaxRegNetForImageClassification.from_pretrained('facebook/regnet-y-040' )
__A : List[str] = self.default_image_processor
__A : str = prepare_img()
__A : Any = image_processor(images=_A , return_tensors='np' )
__A : Dict = model(**_A )
# verify the logits
__A : Tuple = (1, 1000)
self.assertEqual(outputs.logits.shape , _A )
__A : Tuple = jnp.array([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6] )
self.assertTrue(jnp.allclose(outputs.logits[0, :3] , _A , atol=1e-4 ) )
| 77 |
import gc
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer
from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import load_numpy, slow
from diffusers.utils.testing_utils import require_torch_gpu, torch_device
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
class _A( snake_case__ , unittest.TestCase ):
"""simple docstring"""
UpperCamelCase : Any = ShapEPipeline
UpperCamelCase : str = ['''prompt''']
UpperCamelCase : Tuple = ['''prompt''']
UpperCamelCase : Optional[int] = [
'''num_images_per_prompt''',
'''num_inference_steps''',
'''generator''',
'''latents''',
'''guidance_scale''',
'''frame_size''',
'''output_type''',
'''return_dict''',
]
UpperCamelCase : int = False
@property
def UpperCAmelCase_ ( self ):
return 32
@property
def UpperCAmelCase_ ( self ):
return 32
@property
def UpperCAmelCase_ ( self ):
return self.time_input_dim * 4
@property
def UpperCAmelCase_ ( self ):
return 8
@property
def UpperCAmelCase_ ( self ):
__A : List[Any] = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )
return tokenizer
@property
def UpperCAmelCase_ ( self ):
torch.manual_seed(0 )
__A : Optional[int] = CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , )
return CLIPTextModelWithProjection(_A )
@property
def UpperCAmelCase_ ( self ):
torch.manual_seed(0 )
__A : int = {
'num_attention_heads': 2,
'attention_head_dim': 16,
'embedding_dim': self.time_input_dim,
'num_embeddings': 32,
'embedding_proj_dim': self.text_embedder_hidden_size,
'time_embed_dim': self.time_embed_dim,
'num_layers': 1,
'clip_embed_dim': self.time_input_dim * 2,
'additional_embeddings': 0,
'time_embed_act_fn': 'gelu',
'norm_in_type': 'layer',
'encoder_hid_proj_type': None,
'added_emb_type': None,
}
__A : Optional[Any] = PriorTransformer(**_A )
return model
@property
def UpperCAmelCase_ ( self ):
torch.manual_seed(0 )
__A : List[str] = {
'param_shapes': (
(self.renderer_dim, 93),
(self.renderer_dim, 8),
(self.renderer_dim, 8),
(self.renderer_dim, 8),
),
'd_latent': self.time_input_dim,
'd_hidden': self.renderer_dim,
'n_output': 12,
'background': (
0.1,
0.1,
0.1,
),
}
__A : List[Any] = ShapERenderer(**_A )
return model
def UpperCAmelCase_ ( self ):
__A : List[str] = self.dummy_prior
__A : Optional[int] = self.dummy_text_encoder
__A : List[Any] = self.dummy_tokenizer
__A : str = self.dummy_renderer
__A : List[Any] = HeunDiscreteScheduler(
beta_schedule='exp' , num_train_timesteps=1024 , prediction_type='sample' , use_karras_sigmas=_A , clip_sample=_A , clip_sample_range=1.0 , )
__A : Any = {
'prior': prior,
'text_encoder': text_encoder,
'tokenizer': tokenizer,
'renderer': renderer,
'scheduler': scheduler,
}
return components
def UpperCAmelCase_ ( self , _A , _A=0 ):
if str(_A ).startswith('mps' ):
__A : List[Any] = torch.manual_seed(_A )
else:
__A : Dict = torch.Generator(device=_A ).manual_seed(_A )
__A : int = {
'prompt': 'horse',
'generator': generator,
'num_inference_steps': 1,
'frame_size': 32,
'output_type': 'np',
}
return inputs
def UpperCAmelCase_ ( self ):
__A : Tuple = 'cpu'
__A : Any = self.get_dummy_components()
__A : Tuple = self.pipeline_class(**_A )
__A : List[str] = pipe.to(_A )
pipe.set_progress_bar_config(disable=_A )
__A : Tuple = pipe(**self.get_dummy_inputs(_A ) )
__A : int = output.images[0]
__A : str = image[0, -3:, -3:, -1]
assert image.shape == (20, 32, 32, 3)
__A : Any = np.array(
[
0.0_0_0_3_9_2_1_6,
0.0_0_0_3_9_2_1_6,
0.0_0_0_3_9_2_1_6,
0.0_0_0_3_9_2_1_6,
0.0_0_0_3_9_2_1_6,
0.0_0_0_3_9_2_1_6,
0.0_0_0_3_9_2_1_6,
0.0_0_0_3_9_2_1_6,
0.0_0_0_3_9_2_1_6,
] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def UpperCAmelCase_ ( self ):
# NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
self._test_inference_batch_consistent(batch_sizes=[1, 2] )
def UpperCAmelCase_ ( self ):
__A : List[str] = torch_device == 'cpu'
__A : Any = True
self._test_inference_batch_single_identical(
batch_size=2 , test_max_difference=_A , relax_max_difference=_A , )
def UpperCAmelCase_ ( self ):
__A : Any = self.get_dummy_components()
__A : Any = self.pipeline_class(**_A )
__A : Dict = pipe.to(_A )
pipe.set_progress_bar_config(disable=_A )
__A : Any = 1
__A : Dict = 2
__A : Tuple = self.get_dummy_inputs(_A )
for key in inputs.keys():
if key in self.batch_params:
__A : Optional[int] = batch_size * [inputs[key]]
__A : Optional[int] = pipe(**_A , num_images_per_prompt=_A )[0]
assert images.shape[0] == batch_size * num_images_per_prompt
@slow
@require_torch_gpu
class _A( unittest.TestCase ):
"""simple docstring"""
def UpperCAmelCase_ ( self ):
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def UpperCAmelCase_ ( self ):
__A : List[str] = load_numpy(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
'/shap_e/test_shap_e_np_out.npy' )
__A : Dict = ShapEPipeline.from_pretrained('openai/shap-e' )
__A : int = pipe.to(_A )
pipe.set_progress_bar_config(disable=_A )
__A : str = torch.Generator(device=_A ).manual_seed(0 )
__A : Tuple = pipe(
'a shark' , generator=_A , guidance_scale=1_5.0 , num_inference_steps=64 , frame_size=64 , output_type='np' , ).images[0]
assert images.shape == (20, 64, 64, 3)
assert_mean_pixel_difference(_A , _A )
| 77 | 1 |
import warnings
from ...utils import logging
from .image_processing_mobilevit import MobileViTImageProcessor
UpperCAmelCase : List[Any] = logging.get_logger(__name__)
class _A( snake_case__ ):
"""simple docstring"""
def __init__( self , *_A , **_A ):
warnings.warn(
'The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.'
' Please use MobileViTImageProcessor instead.' , _A , )
super().__init__(*_A , **_A )
| 77 |
from __future__ import annotations
import math
def _SCREAMING_SNAKE_CASE ( a , a ) -> list:
if len(a ) != 2 or len(a[0] ) != 2 or len(a ) != 2 or len(b[0] ) != 2:
raise Exception('Matrices are not 2x2' )
__A : Optional[int] = [
[a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]],
[a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]],
]
return new_matrix
def _SCREAMING_SNAKE_CASE ( a , a ) -> str:
return [
[matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row] ) )]
for row in range(len(a ) )
]
def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[int]:
return [
[matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row] ) )]
for row in range(len(a ) )
]
def _SCREAMING_SNAKE_CASE ( a ) -> tuple[list, list, list, list]:
if len(a ) % 2 != 0 or len(a[0] ) % 2 != 0:
raise Exception('Odd matrices are not supported!' )
__A : str = len(a )
__A : List[Any] = matrix_length // 2
__A : List[str] = [[a[i][j] for j in range(a , a )] for i in range(a )]
__A : Dict = [
[a[i][j] for j in range(a , a )] for i in range(a , a )
]
__A : int = [[a[i][j] for j in range(a )] for i in range(a )]
__A : Any = [[a[i][j] for j in range(a )] for i in range(a , a )]
return top_left, top_right, bot_left, bot_right
def _SCREAMING_SNAKE_CASE ( a ) -> tuple[int, int]:
return len(a ), len(matrix[0] )
def _SCREAMING_SNAKE_CASE ( a ) -> None:
print('\n'.join(str(a ) for line in matrix ) )
def _SCREAMING_SNAKE_CASE ( a , a ) -> list:
if matrix_dimensions(a ) == (2, 2):
return default_matrix_multiplication(a , a )
__A , __A , __A , __A : str = split_matrix(a )
__A , __A , __A , __A : List[Any] = split_matrix(a )
__A : Any = actual_strassen(a , matrix_subtraction(a , a ) )
__A : Tuple = actual_strassen(matrix_addition(a , a ) , a )
__A : List[str] = actual_strassen(matrix_addition(a , a ) , a )
__A : Optional[int] = actual_strassen(a , matrix_subtraction(a , a ) )
__A : Any = actual_strassen(matrix_addition(a , a ) , matrix_addition(a , a ) )
__A : Any = actual_strassen(matrix_subtraction(a , a ) , matrix_addition(a , a ) )
__A : List[Any] = actual_strassen(matrix_subtraction(a , a ) , matrix_addition(a , a ) )
__A : List[Any] = matrix_addition(matrix_subtraction(matrix_addition(a , a ) , a ) , a )
__A : Union[str, Any] = matrix_addition(a , a )
__A : str = matrix_addition(a , a )
__A : Dict = matrix_subtraction(matrix_subtraction(matrix_addition(a , a ) , a ) , a )
# construct the new matrix from our 4 quadrants
__A : List[Any] = []
for i in range(len(a ) ):
new_matrix.append(top_left[i] + top_right[i] )
for i in range(len(a ) ):
new_matrix.append(bot_left[i] + bot_right[i] )
return new_matrix
def _SCREAMING_SNAKE_CASE ( a , a ) -> list:
if matrix_dimensions(a )[1] != matrix_dimensions(a )[0]:
__A : Dict = (
'Unable to multiply these matrices, please check the dimensions.\n'
F"""Matrix A: {matrixa}\n"""
F"""Matrix B: {matrixa}"""
)
raise Exception(a )
__A : int = matrix_dimensions(a )
__A : Any = matrix_dimensions(a )
if dimensiona[0] == dimensiona[1] and dimensiona[0] == dimensiona[1]:
return [matrixa, matrixa]
__A : List[Any] = max(*a , *a )
__A : Optional[Any] = int(math.pow(2 , math.ceil(math.loga(a ) ) ) )
__A : Union[str, Any] = matrixa
__A : Optional[int] = matrixa
# Adding zeros to the matrices so that the arrays dimensions are the same and also
# power of 2
for i in range(0 , a ):
if i < dimensiona[0]:
for _ in range(dimensiona[1] , a ):
new_matrixa[i].append(0 )
else:
new_matrixa.append([0] * maxim )
if i < dimensiona[0]:
for _ in range(dimensiona[1] , a ):
new_matrixa[i].append(0 )
else:
new_matrixa.append([0] * maxim )
__A : str = actual_strassen(a , a )
# Removing the additional zeros
for i in range(0 , a ):
if i < dimensiona[0]:
for _ in range(dimensiona[1] , a ):
final_matrix[i].pop()
else:
final_matrix.pop()
return final_matrix
if __name__ == "__main__":
UpperCAmelCase : Union[str, Any] = [
[2, 3, 4, 5],
[6, 4, 3, 1],
[2, 3, 6, 7],
[3, 1, 2, 4],
[2, 3, 4, 5],
[6, 4, 3, 1],
[2, 3, 6, 7],
[3, 1, 2, 4],
[2, 3, 4, 5],
[6, 2, 3, 1],
]
UpperCAmelCase : Optional[Any] = [[0, 2, 1, 1], [16, 2, 3, 3], [2, 2, 7, 7], [13, 11, 22, 4]]
print(strassen(matrixa, matrixa))
| 77 | 1 |
from __future__ import annotations
import time
import numpy as np
UpperCAmelCase : Optional[Any] = [8, 5, 9, 7]
UpperCAmelCase : List[str] = [
[2, 0, 1, 1],
[0, 1, 2, 1],
[4, 0, 0, 3],
[0, 2, 1, 0],
[1, 0, 3, 0],
]
UpperCAmelCase : Any = [
[3, 2, 1, 4],
[0, 2, 5, 2],
[5, 1, 0, 5],
[1, 5, 3, 0],
[3, 0, 3, 3],
]
class _A:
"""simple docstring"""
def __init__( self , _A , _A , _A , ):
__A : List[Any] = claim_vector
__A : List[str] = allocated_resources_table
__A : Any = maximum_claim_table
def UpperCAmelCase_ ( self ):
return [
sum(p_item[i] for p_item in self.__allocated_resources_table )
for i in range(len(self.__allocated_resources_table[0] ) )
]
def UpperCAmelCase_ ( self ):
return np.array(self.__claim_vector ) - np.array(
self.__processes_resource_summation() )
def UpperCAmelCase_ ( self ):
return [
list(np.array(self.__maximum_claim_table[i] ) - np.array(_A ) )
for i, allocated_resource in enumerate(self.__allocated_resources_table )
]
def UpperCAmelCase_ ( self ):
return {self.__need().index(_A ): i for i in self.__need()}
def UpperCAmelCase_ ( self , **_A ):
__A : Any = self.__need()
__A : Union[str, Any] = self.__allocated_resources_table
__A : Optional[Any] = self.__available_resources()
__A : Union[str, Any] = self.__need_index_manager()
for kw, val in kwargs.items():
if kw and val is True:
self.__pretty_data()
print('_' * 50 + '\n' )
while need_list:
__A : int = False
for each_need in need_list:
__A : Optional[int] = True
for index, need in enumerate(_A ):
if need > available_resources[index]:
__A : Optional[Any] = False
break
if execution:
__A : List[str] = True
# get the original index of the process from ind_ctrl db
for original_need_index, need_clone in need_index_manager.items():
if each_need == need_clone:
__A : str = original_need_index
print(F"""Process {process_number + 1} is executing.""" )
# remove the process run from stack
need_list.remove(_A )
# update available/freed resources stack
__A : Any = np.array(_A ) + np.array(
alloc_resources_table[process_number] )
print(
'Updated available resource stack for processes: '
+ ' '.join([str(_A ) for x in available_resources] ) )
break
if safe:
print('The process is in a safe state.\n' )
else:
print('System in unsafe state. Aborting...\n' )
break
def UpperCAmelCase_ ( self ):
print(' ' * 9 + 'Allocated Resource Table' )
for item in self.__allocated_resources_table:
print(
F"""P{self.__allocated_resources_table.index(_A ) + 1}"""
+ ' '.join(F"""{it:>8}""" for it in item )
+ '\n' )
print(' ' * 9 + 'System Resource Table' )
for item in self.__maximum_claim_table:
print(
F"""P{self.__maximum_claim_table.index(_A ) + 1}"""
+ ' '.join(F"""{it:>8}""" for it in item )
+ '\n' )
print(
'Current Usage by Active Processes: '
+ ' '.join(str(_A ) for x in self.__claim_vector ) )
print(
'Initial Available Resources: '
+ ' '.join(str(_A ) for x in self.__available_resources() ) )
time.sleep(1 )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 77 |
def _SCREAMING_SNAKE_CASE ( a ) -> int:
__A : List[str] = []
__A : Tuple = []
__A : Union[str, Any] = {
'^': 3,
'*': 2,
'/': 2,
'%': 2,
'+': 1,
'-': 1,
} # Priority of each operator
__A : List[str] = len(a ) if (len(a ) > 7) else 7
# Print table header for output
print(
'Symbol'.center(8 ) , 'Stack'.center(a ) , 'Postfix'.center(a ) , sep=' | ' , )
print('-' * (print_width * 3 + 7) )
for x in infix:
if x.isalpha() or x.isdigit():
post_fix.append(a ) # if x is Alphabet / Digit, add it to Postfix
elif x == "(":
stack.append(a ) # if x is "(" push to Stack
elif x == ")": # if x is ")" pop stack until "(" is encountered
while stack[-1] != "(":
post_fix.append(stack.pop() ) # Pop stack & add the content to Postfix
stack.pop()
else:
if len(a ) == 0:
stack.append(a ) # If stack is empty, push x to stack
else: # while priority of x is not > priority of element in the stack
while len(a ) > 0 and priority[x] <= priority[stack[-1]]:
post_fix.append(stack.pop() ) # pop stack & add to Postfix
stack.append(a ) # push x to stack
print(
x.center(8 ) , (''.join(a )).ljust(a ) , (''.join(a )).ljust(a ) , sep=' | ' , ) # Output in tabular format
while len(a ) > 0: # while stack is not empty
post_fix.append(stack.pop() ) # pop stack & add to Postfix
print(
' '.center(8 ) , (''.join(a )).ljust(a ) , (''.join(a )).ljust(a ) , sep=' | ' , ) # Output in tabular format
return "".join(a ) # return Postfix as str
def _SCREAMING_SNAKE_CASE ( a ) -> List[str]:
__A : List[Any] = list(infix[::-1] ) # reverse the infix equation
for i in range(len(a ) ):
if infix[i] == "(":
__A : List[str] = ')' # change "(" to ")"
elif infix[i] == ")":
__A : Any = '(' # change ")" to "("
return (infix_2_postfix(''.join(a ) ))[
::-1
] # call infix_2_postfix on Infix, return reverse of Postfix
if __name__ == "__main__":
UpperCAmelCase : List[str] = input('''\nEnter an Infix Equation = ''') # Input an Infix equation
UpperCAmelCase : Union[str, Any] = ''''''.join(Infix.split()) # Remove spaces from the input
print('''\n\t''', Infix, '''(Infix) -> ''', infix_2_prefix(Infix), '''(Prefix)''')
| 77 | 1 |
import inspect
import jax
import jax.lax as lax
import jax.numpy as jnp
from ..utils import add_start_docstrings
from ..utils.logging import get_logger
UpperCAmelCase : int = get_logger(__name__)
UpperCAmelCase : List[Any] = r'''
Args:
input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`):
Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam
search or log softmax for each vocabulary token when using beam search
kwargs (`Dict[str, Any]`, *optional*):
Additional logits processor specific kwargs.
Return:
`jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.
'''
class _A:
"""simple docstring"""
@add_start_docstrings(_A )
def __call__( self , _A , _A ):
raise NotImplementedError(
F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" )
class _A:
"""simple docstring"""
@add_start_docstrings(_A )
def __call__( self , _A , _A ):
raise NotImplementedError(
F"""{self.__class__} is an abstract class. Only classes inheriting this class can be called.""" )
class _A( snake_case__ ):
"""simple docstring"""
@add_start_docstrings(_A )
def __call__( self , _A , _A , _A , **_A ):
for processor in self:
__A : str = inspect.signature(processor.__call__ ).parameters
if len(_A ) > 3:
if not all(arg in kwargs for arg in list(function_args.keys() )[2:] ):
raise ValueError(
F"""Make sure that all the required parameters: {list(function_args.keys() )} for """
F"""{processor.__class__} are passed to the logits processor.""" )
__A : Any = processor(_A , _A , _A , **_A )
else:
__A : Union[str, Any] = processor(_A , _A , _A )
return scores
class _A( snake_case__ ):
"""simple docstring"""
def __init__( self , _A ):
if not isinstance(_A , _A ) or not (temperature > 0):
raise ValueError(F"""`temperature` has to be a strictly positive float, but is {temperature}""" )
__A : Optional[int] = temperature
def __call__( self , _A , _A , _A ):
__A : Dict = scores / self.temperature
return scores
class _A( snake_case__ ):
"""simple docstring"""
def __init__( self , _A , _A = -float('Inf' ) , _A = 1 ):
if not isinstance(_A , _A ) or (top_p < 0 or top_p > 1.0):
raise ValueError(F"""`top_p` has to be a float > 0 and < 1, but is {top_p}""" )
if not isinstance(_A , _A ) or (min_tokens_to_keep < 1):
raise ValueError(F"""`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}""" )
__A : Optional[Any] = top_p
__A : Optional[Any] = filter_value
__A : List[str] = min_tokens_to_keep
def __call__( self , _A , _A , _A ):
__A , __A : Union[str, Any] = lax.top_k(_A , scores.shape[-1] )
__A : Union[str, Any] = jnp.full_like(_A , self.filter_value )
__A : int = jax.nn.softmax(_A , axis=-1 ).cumsum(axis=-1 )
__A : Union[str, Any] = cumulative_probs < self.top_p
# include the token that is higher than top_p as well
__A : List[Any] = jnp.roll(_A , 1 )
score_mask |= score_mask.at[:, 0].set(_A )
# min tokens to keep
__A : int = score_mask.at[:, : self.min_tokens_to_keep].set(_A )
__A : Tuple = jnp.where(_A , _A , _A )
__A : List[str] = jax.lax.sort_key_val(_A , _A )[-1]
return next_scores
class _A( snake_case__ ):
"""simple docstring"""
def __init__( self , _A , _A = -float('Inf' ) , _A = 1 ):
if not isinstance(_A , _A ) or top_k <= 0:
raise ValueError(F"""`top_k` has to be a strictly positive integer, but is {top_k}""" )
__A : Dict = max(_A , _A )
__A : Tuple = filter_value
def __call__( self , _A , _A , _A ):
__A , __A : Tuple = scores.shape
__A : List[Any] = jnp.full(batch_size * vocab_size , self.filter_value )
__A : Optional[int] = min(self.top_k , scores.shape[-1] ) # Safety check
__A , __A : Dict = lax.top_k(_A , _A )
__A : Optional[Any] = jnp.broadcast_to((jnp.arange(_A ) * vocab_size)[:, None] , (batch_size, topk) ).flatten()
__A : Union[str, Any] = topk_scores.flatten()
__A : List[Any] = topk_indices.flatten() + shift
__A : Dict = next_scores_flat.at[topk_indices_flat].set(_A )
__A : Optional[Any] = next_scores_flat.reshape(_A , _A )
return next_scores
class _A( snake_case__ ):
"""simple docstring"""
def __init__( self , _A ):
__A : Optional[int] = bos_token_id
def __call__( self , _A , _A , _A ):
__A : Optional[Any] = jnp.full(scores.shape , -float('inf' ) )
__A : List[Any] = 1 - jnp.bool_(cur_len - 1 )
__A : Union[str, Any] = jnp.where(_A , new_scores.at[:, self.bos_token_id].set(0 ) , _A )
return scores
class _A( snake_case__ ):
"""simple docstring"""
def __init__( self , _A , _A ):
__A : Union[str, Any] = max_length
__A : Union[str, Any] = eos_token_id
def __call__( self , _A , _A , _A ):
__A : Optional[int] = jnp.full(scores.shape , -float('inf' ) )
__A : str = 1 - jnp.bool_(cur_len - self.max_length + 1 )
__A : Optional[Any] = jnp.where(_A , new_scores.at[:, self.eos_token_id].set(0 ) , _A )
return scores
class _A( snake_case__ ):
"""simple docstring"""
def __init__( self , _A , _A ):
if not isinstance(_A , _A ) or min_length < 0:
raise ValueError(F"""`min_length` has to be a positive integer, but is {min_length}""" )
if not isinstance(_A , _A ) or eos_token_id < 0:
raise ValueError(F"""`eos_token_id` has to be a positive integer, but is {eos_token_id}""" )
__A : Tuple = min_length
__A : List[Any] = eos_token_id
def __call__( self , _A , _A , _A ):
# create boolean flag to decide if min length penalty should be applied
__A : Optional[Any] = 1 - jnp.clip(cur_len - self.min_length , 0 , 1 )
__A : Union[str, Any] = jnp.where(_A , scores.at[:, self.eos_token_id].set(-float('inf' ) ) , _A )
return scores
class _A( snake_case__ ):
"""simple docstring"""
def __init__( self , _A , _A ):
__A : List[str] = list(_A )
__A : List[Any] = begin_index
def __call__( self , _A , _A , _A ):
__A : Optional[Any] = 1 - jnp.bool_(cur_len - self.begin_index )
__A : Tuple = jnp.where(_A , scores.at[:, self.begin_suppress_tokens].set(-float('inf' ) ) , _A )
return scores
class _A( snake_case__ ):
"""simple docstring"""
def __init__( self , _A ):
__A : List[str] = list(_A )
def __call__( self , _A , _A , _A ):
__A : Tuple = scores.at[..., self.suppress_tokens].set(-float('inf' ) )
return scores
class _A( snake_case__ ):
"""simple docstring"""
def __init__( self , _A ):
__A : Dict = dict(_A )
# Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the
# index of the array corresponds to the index of the token to be forced, for XLA compatibility.
# Indexes without forced tokens will have a negative value.
__A : Optional[Any] = jnp.ones((max(force_token_map.keys() ) + 1) , dtype=jnp.intaa ) * -1
for index, token in force_token_map.items():
if token is not None:
__A : Tuple = force_token_array.at[index].set(_A )
__A : Union[str, Any] = jnp.intaa(_A )
def __call__( self , _A , _A , _A ):
def _force_token(_A ):
__A : int = scores.shape[0]
__A : int = self.force_token_array[generation_idx]
__A : Tuple = jnp.ones_like(_A , dtype=scores.dtype ) * -float('inf' )
__A : Tuple = jnp.zeros((batch_size, 1) , dtype=scores.dtype )
__A : str = lax.dynamic_update_slice(_A , _A , (0, current_token) )
return new_scores
__A : int = lax.cond(
cur_len >= self.force_token_array.shape[0] , lambda: scores , lambda: lax.cond(
self.force_token_array[cur_len] >= 0 , lambda: _force_token(_A ) , lambda: scores , ) , )
return scores
class _A( snake_case__ ):
"""simple docstring"""
def __init__( self , _A , _A , _A ):
__A : str = generate_config.eos_token_id
__A : Any = generate_config.no_timestamps_token_id
__A : List[str] = generate_config.no_timestamps_token_id + 1
__A : List[Any] = decoder_input_length + 1
if generate_config.is_multilingual:
# room for language token and task token
self.begin_index += 2
if hasattr(_A , 'max_initial_timestamp_index' ):
__A : List[Any] = generate_config.max_initial_timestamp_index
else:
__A : Tuple = model_config.vocab_size
if self.max_initial_timestamp_index is None:
__A : Tuple = model_config.vocab_size
def __call__( self , _A , _A , _A ):
# suppress <|notimestamps|> which is handled by without_timestamps
__A : Any = scores.at[:, self.no_timestamps_token_id].set(-float('inf' ) )
def handle_pairs(_A , _A ):
__A : Tuple = jnp.where((cur_len - self.begin_index) >= 1 , _A , _A )
__A : str = jnp.where(
input_ids_k[cur_len - 1] >= self.timestamp_begin , True and last_was_timestamp , _A , )
__A : List[str] = jnp.where((cur_len - self.begin_index) < 2 , _A , _A )
__A : int = jnp.where(
input_ids_k[cur_len - 2] >= self.timestamp_begin , _A , _A , )
return jnp.where(
_A , jnp.where(
penultimate_was_timestamp > 0 , scores_k.at[self.timestamp_begin :].set(-float('inf' ) ) , scores_k.at[: self.eos_token_id].set(-float('inf' ) ) , ) , _A , )
__A : Tuple = jax.vmap(_A )(_A , _A )
__A : List[Any] = jnp.where(cur_len == self.begin_index , _A , _A )
__A : str = jnp.where(
self.max_initial_timestamp_index is not None , True and apply_max_initial_timestamp , _A , )
__A : Any = self.timestamp_begin + self.max_initial_timestamp_index
__A : Tuple = jnp.where(
_A , scores.at[:, last_allowed + 1 :].set(-float('inf' ) ) , _A , )
# if sum of probability over timestamps is above any other token, sample timestamp
__A : Optional[int] = jax.nn.log_softmax(_A , axis=-1 )
def handle_cumulative_probs(_A , _A ):
__A : Any = jax.nn.logsumexp(logprobs_k[self.timestamp_begin :] , axis=-1 )
__A : Optional[Any] = jnp.max(logprobs_k[: self.timestamp_begin] )
return jnp.where(
timestamp_logprob > max_text_token_logprob , scores_k.at[: self.timestamp_begin].set(-float('inf' ) ) , _A , )
__A : Union[str, Any] = jax.vmap(_A )(_A , _A )
return scores
| 77 |
import copy
from typing import Dict, List, Optional
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING
UpperCAmelCase : Tuple = {
'''facebook/mask2former-swin-small-coco-instance''': (
'''https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json'''
)
# See all Mask2Former models at https://huggingface.co/models?filter=mask2former
}
UpperCAmelCase : int = logging.get_logger(__name__)
class _A( snake_case__ ):
"""simple docstring"""
UpperCamelCase : Union[str, Any] = '''mask2former'''
UpperCamelCase : Any = ['''swin''']
UpperCamelCase : Union[str, Any] = {'''hidden_size''': '''hidden_dim'''}
def __init__( self , _A = None , _A = 256 , _A = 256 , _A = 256 , _A = 1024 , _A = "relu" , _A = 6 , _A = 10 , _A = 8 , _A = 0.0 , _A = 2048 , _A = False , _A = False , _A = 4 , _A = 255 , _A = 100 , _A = 0.1 , _A = 2.0 , _A = 5.0 , _A = 5.0 , _A = 12544 , _A = 3.0 , _A = 0.7_5 , _A = 0.0_2 , _A = 1.0 , _A = True , _A = [4, 8, 16, 32] , _A = None , **_A , ):
if backbone_config is None:
logger.info('`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.' )
__A : Optional[int] = CONFIG_MAPPING['swin'](
image_size=224 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=_A , out_features=['stage1', 'stage2', 'stage3', 'stage4'] , )
if isinstance(_A , _A ):
__A : Dict = backbone_config.pop('model_type' )
__A : Union[str, Any] = CONFIG_MAPPING[backbone_model_type]
__A : List[str] = config_class.from_dict(_A )
# verify that the backbone is supported
if backbone_config.model_type not in self.backbones_supported:
logger.warning_once(
F"""Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. """
F"""Supported model types: {",".join(self.backbones_supported )}""" )
__A : Optional[int] = backbone_config
__A : Optional[Any] = feature_size
__A : Any = mask_feature_size
__A : Optional[Any] = hidden_dim
__A : Union[str, Any] = encoder_feedforward_dim
__A : Optional[Any] = activation_function
__A : List[Any] = encoder_layers
__A : Union[str, Any] = decoder_layers
__A : Dict = num_attention_heads
__A : Tuple = dropout
__A : Dict = dim_feedforward
__A : Tuple = pre_norm
__A : Dict = enforce_input_projection
__A : Optional[int] = common_stride
__A : Optional[Any] = ignore_value
__A : str = num_queries
__A : List[Any] = no_object_weight
__A : List[str] = class_weight
__A : List[Any] = mask_weight
__A : List[Any] = dice_weight
__A : Tuple = train_num_points
__A : Optional[Any] = oversample_ratio
__A : Union[str, Any] = importance_sample_ratio
__A : Union[str, Any] = init_std
__A : int = init_xavier_std
__A : Union[str, Any] = use_auxiliary_loss
__A : Union[str, Any] = feature_strides
__A : List[Any] = output_auxiliary_logits
__A : Optional[Any] = decoder_layers
super().__init__(**_A )
@classmethod
def UpperCAmelCase_ ( cls , _A , **_A ):
return cls(
backbone_config=_A , **_A , )
def UpperCAmelCase_ ( self ):
__A : Union[str, Any] = copy.deepcopy(self.__dict__ )
__A : List[Any] = self.backbone_config.to_dict()
__A : Union[str, Any] = self.__class__.model_type
return output
| 77 | 1 |
from typing import Any, Dict, List, Union
from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
from .base import PIPELINE_INIT_ARGS, Pipeline
if is_vision_available():
from ..image_utils import load_image
if is_torch_available():
import torch
from ..models.auto.modeling_auto import MODEL_FOR_OBJECT_DETECTION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING
UpperCAmelCase : Optional[int] = logging.get_logger(__name__)
UpperCAmelCase : Optional[Any] = Dict[str, Any]
UpperCAmelCase : int = List[Prediction]
@add_end_docstrings(snake_case__ )
class _A( snake_case__ ):
"""simple docstring"""
def __init__( self , *_A , **_A ):
super().__init__(*_A , **_A )
if self.framework == "tf":
raise ValueError(F"""The {self.__class__} is only available in PyTorch.""" )
requires_backends(self , 'vision' )
self.check_model_type(
dict(MODEL_FOR_OBJECT_DETECTION_MAPPING.items() + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.items() ) )
def UpperCAmelCase_ ( self , **_A ):
__A : Tuple = {}
if "threshold" in kwargs:
__A : List[Any] = kwargs['threshold']
return {}, {}, postprocess_kwargs
def __call__( self , *_A , **_A ):
return super().__call__(*_A , **_A )
def UpperCAmelCase_ ( self , _A ):
__A : List[str] = load_image(_A )
__A : Any = torch.IntTensor([[image.height, image.width]] )
__A : Optional[int] = self.image_processor(images=[image] , return_tensors='pt' )
if self.tokenizer is not None:
__A : str = self.tokenizer(text=inputs['words'] , boxes=inputs['boxes'] , return_tensors='pt' )
__A : Any = target_size
return inputs
def UpperCAmelCase_ ( self , _A ):
__A : Any = model_inputs.pop('target_size' )
__A : Tuple = self.model(**_A )
__A : Optional[Any] = outputs.__class__({'target_size': target_size, **outputs} )
if self.tokenizer is not None:
__A : List[str] = model_inputs['bbox']
return model_outputs
def UpperCAmelCase_ ( self , _A , _A=0.9 ):
__A : str = model_outputs['target_size']
if self.tokenizer is not None:
# This is a LayoutLMForTokenClassification variant.
# The OCR got the boxes and the model classified the words.
__A , __A : List[Any] = target_size[0].tolist()
def unnormalize(_A ):
return self._get_bounding_box(
torch.Tensor(
[
(width * bbox[0] / 1000),
(height * bbox[1] / 1000),
(width * bbox[2] / 1000),
(height * bbox[3] / 1000),
] ) )
__A , __A : Union[str, Any] = model_outputs['logits'].squeeze(0 ).softmax(dim=-1 ).max(dim=-1 )
__A : List[str] = [self.model.config.idalabel[prediction] for prediction in classes.tolist()]
__A : Optional[Any] = [unnormalize(_A ) for bbox in model_outputs['bbox'].squeeze(0 )]
__A : Union[str, Any] = ['score', 'label', 'box']
__A : str = [dict(zip(_A , _A ) ) for vals in zip(scores.tolist() , _A , _A ) if vals[0] > threshold]
else:
# This is a regular ForObjectDetectionModel
__A : List[Any] = self.image_processor.post_process_object_detection(_A , _A , _A )
__A : Tuple = raw_annotations[0]
__A : int = raw_annotation['scores']
__A : Optional[int] = raw_annotation['labels']
__A : Union[str, Any] = raw_annotation['boxes']
__A : Optional[int] = scores.tolist()
__A : str = [self.model.config.idalabel[label.item()] for label in labels]
__A : str = [self._get_bounding_box(_A ) for box in boxes]
# {"scores": [...], ...} --> [{"score":x, ...}, ...]
__A : Tuple = ['score', 'label', 'box']
__A : str = [
dict(zip(_A , _A ) )
for vals in zip(raw_annotation['scores'] , raw_annotation['labels'] , raw_annotation['boxes'] )
]
return annotation
def UpperCAmelCase_ ( self , _A ):
if self.framework != "pt":
raise ValueError('The ObjectDetectionPipeline is only available in PyTorch.' )
__A , __A , __A , __A : Union[str, Any] = box.int().tolist()
__A : Union[str, Any] = {
'xmin': xmin,
'ymin': ymin,
'xmax': xmax,
'ymax': ymax,
}
return bbox
| 77 |
import copy
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING
UpperCAmelCase : List[str] = logging.get_logger(__name__)
UpperCAmelCase : Optional[int] = {
'''microsoft/conditional-detr-resnet-50''': (
'''https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json'''
),
}
class _A( snake_case__ ):
"""simple docstring"""
UpperCamelCase : str = '''conditional_detr'''
UpperCamelCase : int = ['''past_key_values''']
UpperCamelCase : Tuple = {
'''hidden_size''': '''d_model''',
'''num_attention_heads''': '''encoder_attention_heads''',
}
def __init__( self , _A=True , _A=None , _A=3 , _A=300 , _A=6 , _A=2048 , _A=8 , _A=6 , _A=2048 , _A=8 , _A=0.0 , _A=0.0 , _A=True , _A="relu" , _A=256 , _A=0.1 , _A=0.0 , _A=0.0 , _A=0.0_2 , _A=1.0 , _A=False , _A="sine" , _A="resnet50" , _A=True , _A=False , _A=2 , _A=5 , _A=2 , _A=1 , _A=1 , _A=2 , _A=5 , _A=2 , _A=0.2_5 , **_A , ):
if backbone_config is not None and use_timm_backbone:
raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.' )
if not use_timm_backbone:
if backbone_config is None:
logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' )
__A : List[str] = CONFIG_MAPPING['resnet'](out_features=['stage4'] )
elif isinstance(_A , _A ):
__A : Tuple = backbone_config.get('model_type' )
__A : Union[str, Any] = CONFIG_MAPPING[backbone_model_type]
__A : List[Any] = config_class.from_dict(_A )
__A : Tuple = use_timm_backbone
__A : List[str] = backbone_config
__A : Dict = num_channels
__A : int = num_queries
__A : int = d_model
__A : str = encoder_ffn_dim
__A : List[str] = encoder_layers
__A : Optional[Any] = encoder_attention_heads
__A : Union[str, Any] = decoder_ffn_dim
__A : List[Any] = decoder_layers
__A : Optional[Any] = decoder_attention_heads
__A : Any = dropout
__A : Any = attention_dropout
__A : int = activation_dropout
__A : Optional[int] = activation_function
__A : Union[str, Any] = init_std
__A : Union[str, Any] = init_xavier_std
__A : Optional[Any] = encoder_layerdrop
__A : int = decoder_layerdrop
__A : List[str] = encoder_layers
__A : str = auxiliary_loss
__A : Union[str, Any] = position_embedding_type
__A : Optional[int] = backbone
__A : List[str] = use_pretrained_backbone
__A : List[Any] = dilation
# Hungarian matcher
__A : List[str] = class_cost
__A : Optional[int] = bbox_cost
__A : Dict = giou_cost
# Loss coefficients
__A : Optional[int] = mask_loss_coefficient
__A : Union[str, Any] = dice_loss_coefficient
__A : List[Any] = cls_loss_coefficient
__A : Dict = bbox_loss_coefficient
__A : Tuple = giou_loss_coefficient
__A : Tuple = focal_alpha
super().__init__(is_encoder_decoder=_A , **_A )
@property
def UpperCAmelCase_ ( self ):
return self.encoder_attention_heads
@property
def UpperCAmelCase_ ( self ):
return self.d_model
def UpperCAmelCase_ ( self ):
__A : str = copy.deepcopy(self.__dict__ )
if self.backbone_config is not None:
__A : Dict = self.backbone_config.to_dict()
__A : Union[str, Any] = self.__class__.model_type
return output
class _A( snake_case__ ):
"""simple docstring"""
UpperCamelCase : List[str] = version.parse('''1.11''' )
@property
def UpperCAmelCase_ ( self ):
return OrderedDict(
[
('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
('pixel_mask', {0: 'batch'}),
] )
@property
def UpperCAmelCase_ ( self ):
return 1e-5
@property
def UpperCAmelCase_ ( self ):
return 12
| 77 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.