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 |
|---|---|---|---|---|
"""simple docstring"""
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, is_vision_available, logging
if is_vision_available():
import PIL
_a = logging.get_logger(__name__)
class _UpperCAmelCase( UpperCamelCase_ ):
lowercase__ = ['pixel_values']
def __init__( self , __a = True , __a = None , __a = None , __a = PILImageResampling.BILINEAR , __a = True , __a = 1 / 2_55 , __a = True , __a = None , __a = None , **__a , ) -> None:
'''simple docstring'''
super().__init__(**__a)
_UpperCamelCase = size if size is not None else {'shortest_edge': 3_84}
_UpperCamelCase = get_size_dict(__a , default_to_square=__a)
_UpperCamelCase = do_resize
_UpperCamelCase = size
# Default value set here for backwards compatibility where the value in config is None
_UpperCamelCase = crop_pct if crop_pct is not None else 2_24 / 2_56
_UpperCamelCase = resample
_UpperCamelCase = do_rescale
_UpperCamelCase = rescale_factor
_UpperCamelCase = do_normalize
_UpperCamelCase = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
_UpperCamelCase = image_std if image_std is not None else IMAGENET_STANDARD_STD
def UpperCAmelCase ( self , __a , __a , __a , __a = PILImageResampling.BICUBIC , __a = None , **__a , ) -> np.ndarray:
'''simple docstring'''
_UpperCamelCase = get_size_dict(__a , default_to_square=__a)
if "shortest_edge" not in size:
raise ValueError(F'''Size dictionary must contain \'shortest_edge\' key. Got {size.keys()}''')
_UpperCamelCase = size['shortest_edge']
if shortest_edge < 3_84:
# maintain same ratio, resizing shortest edge to shortest_edge/crop_pct
_UpperCamelCase = int(shortest_edge / crop_pct)
_UpperCamelCase = get_resize_output_image_size(__a , size=__a , default_to_square=__a)
_UpperCamelCase = resize(image=__a , size=__a , resample=__a , data_format=__a , **__a)
# then crop to (shortest_edge, shortest_edge)
return center_crop(image=__a , size=(shortest_edge, shortest_edge) , data_format=__a , **__a)
else:
# warping (no cropping) when evaluated at 384 or larger
return resize(
__a , size=(shortest_edge, shortest_edge) , resample=__a , data_format=__a , **__a)
def UpperCAmelCase ( self , __a , __a , __a = None , **__a , ) -> Any:
'''simple docstring'''
return rescale(__a , scale=__a , data_format=__a , **__a)
def UpperCAmelCase ( self , __a , __a , __a , __a = None , **__a , ) -> np.ndarray:
'''simple docstring'''
return normalize(__a , mean=__a , std=__a , data_format=__a , **__a)
def UpperCAmelCase ( self , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = ChannelDimension.FIRST , **__a , ) -> PIL.Image.Image:
'''simple docstring'''
_UpperCamelCase = do_resize if do_resize is not None else self.do_resize
_UpperCamelCase = crop_pct if crop_pct is not None else self.crop_pct
_UpperCamelCase = resample if resample is not None else self.resample
_UpperCamelCase = do_rescale if do_rescale is not None else self.do_rescale
_UpperCamelCase = rescale_factor if rescale_factor is not None else self.rescale_factor
_UpperCamelCase = do_normalize if do_normalize is not None else self.do_normalize
_UpperCamelCase = image_mean if image_mean is not None else self.image_mean
_UpperCamelCase = image_std if image_std is not None else self.image_std
_UpperCamelCase = size if size is not None else self.size
_UpperCamelCase = get_size_dict(__a , default_to_square=__a)
_UpperCamelCase = make_list_of_images(__a)
if not valid_images(__a):
raise ValueError(
'''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
'''torch.Tensor, tf.Tensor or jax.ndarray.''')
if do_resize and size is None or resample is None:
raise ValueError('''Size and resample must be specified if do_resize is True.''')
if do_resize and size["shortest_edge"] < 3_84 and crop_pct is None:
raise ValueError('''crop_pct must be specified if size < 384.''')
if do_rescale and rescale_factor is None:
raise ValueError('''Rescale factor must be specified if do_rescale is True.''')
if do_normalize and (image_mean is None or image_std is None):
raise ValueError('''Image mean and std must be specified if do_normalize is True.''')
# All transformations expect numpy arrays.
_UpperCamelCase = [to_numpy_array(__a) for image in images]
if do_resize:
_UpperCamelCase = [self.resize(image=__a , size=__a , crop_pct=__a , resample=__a) for image in images]
if do_rescale:
_UpperCamelCase = [self.rescale(image=__a , scale=__a) for image in images]
if do_normalize:
_UpperCamelCase = [self.normalize(image=__a , mean=__a , std=__a) for image in images]
_UpperCamelCase = [to_channel_dimension_format(__a , __a) for image in images]
_UpperCamelCase = {'pixel_values': images}
return BatchFeature(data=__a , tensor_type=__a)
| 717 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tokenizers_available,
is_torch_available,
is_vision_available,
)
_a = {
"""configuration_perceiver""": ["""PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """PerceiverConfig""", """PerceiverOnnxConfig"""],
"""tokenization_perceiver""": ["""PerceiverTokenizer"""],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_a = ["""PerceiverFeatureExtractor"""]
_a = ["""PerceiverImageProcessor"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_a = [
"""PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""PerceiverForImageClassificationConvProcessing""",
"""PerceiverForImageClassificationFourier""",
"""PerceiverForImageClassificationLearned""",
"""PerceiverForMaskedLM""",
"""PerceiverForMultimodalAutoencoding""",
"""PerceiverForOpticalFlow""",
"""PerceiverForSequenceClassification""",
"""PerceiverLayer""",
"""PerceiverModel""",
"""PerceiverPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_perceiver import PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP, PerceiverConfig, PerceiverOnnxConfig
from .tokenization_perceiver import PerceiverTokenizer
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_perceiver import PerceiverFeatureExtractor
from .image_processing_perceiver import PerceiverImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_perceiver import (
PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST,
PerceiverForImageClassificationConvProcessing,
PerceiverForImageClassificationFourier,
PerceiverForImageClassificationLearned,
PerceiverForMaskedLM,
PerceiverForMultimodalAutoencoding,
PerceiverForOpticalFlow,
PerceiverForSequenceClassification,
PerceiverLayer,
PerceiverModel,
PerceiverPreTrainedModel,
)
else:
import sys
_a = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 78 | 0 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tensorflow_text_available, is_torch_available
_a = {
"""configuration_ernie""": ["""ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ErnieConfig""", """ErnieOnnxConfig"""],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_a = [
"""ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""ErnieForCausalLM""",
"""ErnieForMaskedLM""",
"""ErnieForMultipleChoice""",
"""ErnieForNextSentencePrediction""",
"""ErnieForPreTraining""",
"""ErnieForQuestionAnswering""",
"""ErnieForSequenceClassification""",
"""ErnieForTokenClassification""",
"""ErnieModel""",
"""ErniePreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_ernie import ERNIE_PRETRAINED_CONFIG_ARCHIVE_MAP, ErnieConfig, ErnieOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_ernie import (
ERNIE_PRETRAINED_MODEL_ARCHIVE_LIST,
ErnieForCausalLM,
ErnieForMaskedLM,
ErnieForMultipleChoice,
ErnieForNextSentencePrediction,
ErnieForPreTraining,
ErnieForQuestionAnswering,
ErnieForSequenceClassification,
ErnieForTokenClassification,
ErnieModel,
ErniePreTrainedModel,
)
else:
import sys
_a = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 718 |
"""simple docstring"""
import inspect
import unittest
from huggingface_hub import hf_hub_download
from transformers import ASTConfig
from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_torchaudio_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import ASTForAudioClassification, ASTModel
from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import (
AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
)
if is_torchaudio_available():
import torchaudio
from transformers import ASTFeatureExtractor
class _UpperCAmelCase:
def __init__( self , __a , __a=13 , __a=2 , __a=24 , __a=16 , __a=True , __a=True , __a=32 , __a=5 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=10 , __a=0.02 , __a=None , __a=2 , __a=2 , ) -> List[str]:
'''simple docstring'''
_UpperCamelCase = parent
_UpperCamelCase = batch_size
_UpperCamelCase = patch_size
_UpperCamelCase = max_length
_UpperCamelCase = num_mel_bins
_UpperCamelCase = is_training
_UpperCamelCase = use_labels
_UpperCamelCase = hidden_size
_UpperCamelCase = num_hidden_layers
_UpperCamelCase = num_attention_heads
_UpperCamelCase = intermediate_size
_UpperCamelCase = hidden_act
_UpperCamelCase = hidden_dropout_prob
_UpperCamelCase = attention_probs_dropout_prob
_UpperCamelCase = type_sequence_label_size
_UpperCamelCase = initializer_range
_UpperCamelCase = scope
_UpperCamelCase = frequency_stride
_UpperCamelCase = time_stride
# in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
_UpperCamelCase = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1
_UpperCamelCase = (self.max_length - self.patch_size) // self.time_stride + 1
_UpperCamelCase = frequency_out_dimension * time_out_dimension
_UpperCamelCase = num_patches + 2
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins])
_UpperCamelCase = None
if self.use_labels:
_UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size)
_UpperCamelCase = self.get_config()
return config, input_values, labels
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
return ASTConfig(
patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__a , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , )
def UpperCAmelCase ( self , __a , __a , __a) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = ASTModel(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a)
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.prepare_config_and_inputs()
(
(
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) ,
) = config_and_inputs
_UpperCamelCase = {'''input_values''': input_values}
return config, inputs_dict
@require_torch
class _UpperCAmelCase( lowerCamelCase , lowerCamelCase , unittest.TestCase ):
lowercase__ = (
(
ASTModel,
ASTForAudioClassification,
)
if is_torch_available()
else ()
)
lowercase__ = (
{'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel}
if is_torch_available()
else {}
)
lowercase__ = False
lowercase__ = False
lowercase__ = False
lowercase__ = False
def UpperCAmelCase ( self , __a , __a , __a , __a , __a) -> Optional[Any]:
'''simple docstring'''
if pipeline_test_casse_name == "AudioClassificationPipelineTests":
return True
return False
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
_UpperCamelCase = ASTModelTester(self)
_UpperCamelCase = ConfigTester(self , config_class=__a , has_text_modality=__a , hidden_size=37)
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
self.config_tester.run_common_tests()
@unittest.skip(reason='''AST does not use inputs_embeds''')
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
pass
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_UpperCamelCase = model_class(__a)
self.assertIsInstance(model.get_input_embeddings() , (nn.Module))
_UpperCamelCase = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(__a , nn.Linear))
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_UpperCamelCase = model_class(__a)
_UpperCamelCase = inspect.signature(model.forward)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
_UpperCamelCase = [*signature.parameters.keys()]
_UpperCamelCase = ['''input_values''']
self.assertListEqual(arg_names[:1] , __a)
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__a)
@slow
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_UpperCamelCase = ASTModel.from_pretrained(__a)
self.assertIsNotNone(__a)
def lowerCamelCase__ ( ) -> List[str]:
"""simple docstring"""
_UpperCamelCase = hf_hub_download(
repo_id='''nielsr/audio-spectogram-transformer-checkpoint''', filename='''sample_audio.flac''', repo_type='''dataset''' )
_UpperCamelCase , _UpperCamelCase = torchaudio.load(__snake_case )
return audio, sampling_rate
@require_torch
@require_torchaudio
class _UpperCAmelCase( unittest.TestCase ):
@cached_property
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
return (
ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''')
if is_torchaudio_available()
else None
)
@slow
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.default_feature_extractor
_UpperCamelCase = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''').to(__a)
_UpperCamelCase = self.default_feature_extractor
_UpperCamelCase , _UpperCamelCase = prepare_audio()
_UpperCamelCase = audio.squeeze().numpy()
_UpperCamelCase = feature_extractor(__a , sampling_rate=__a , return_tensors='''pt''').to(__a)
# forward pass
with torch.no_grad():
_UpperCamelCase = model(**__a)
# verify the logits
_UpperCamelCase = torch.Size((1, 5_27))
self.assertEqual(outputs.logits.shape , __a)
_UpperCamelCase = torch.tensor([-0.8760, -7.0042, -8.6602]).to(__a)
self.assertTrue(torch.allclose(outputs.logits[0, :3] , __a , atol=1e-4))
| 78 | 0 |
"""simple docstring"""
import warnings
from ...utils import logging
from .image_processing_yolos import YolosImageProcessor
_a = logging.get_logger(__name__)
class _UpperCAmelCase( __snake_case ):
def __init__( self , *__a , **__a) -> Optional[Any]:
'''simple docstring'''
warnings.warn(
'''The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please'''
''' use YolosImageProcessor instead.''' , _lowercase , )
super().__init__(*_lowercase , **_lowercase)
| 719 |
"""simple docstring"""
def lowerCamelCase__ ( ) -> list[list[int]]:
"""simple docstring"""
return [list(range(10_00 - i, -10_00 - i, -1 ) ) for i in range(10_00 )]
_a = generate_large_matrix()
_a = (
[[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]],
[[3, 2], [1, 0]],
[[7, 7, 6]],
[[7, 7, 6], [-1, -2, -3]],
grid,
)
def lowerCamelCase__ ( __snake_case ) -> None:
"""simple docstring"""
assert all(row == sorted(__snake_case, reverse=__snake_case ) for row in grid )
assert all(list(__snake_case ) == sorted(__snake_case, reverse=__snake_case ) for col in zip(*__snake_case ) )
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = 0
_UpperCamelCase = len(__snake_case ) - 1
# Edge cases such as no values or all numbers are negative.
if not array or array[0] < 0:
return 0
while right + 1 > left:
_UpperCamelCase = (left + right) // 2
_UpperCamelCase = array[mid]
# Num must be negative and the index must be greater than or equal to 0.
if num < 0 and array[mid - 1] >= 0:
return mid
if num >= 0:
_UpperCamelCase = mid + 1
else:
_UpperCamelCase = mid - 1
# No negative numbers so return the last index of the array + 1 which is the length.
return len(__snake_case )
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = 0
_UpperCamelCase = len(grid[0] )
for i in range(len(__snake_case ) ):
_UpperCamelCase = find_negative_index(grid[i][:bound] )
total += bound
return (len(__snake_case ) * len(grid[0] )) - total
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
return len([number for row in grid for number in row if number < 0] )
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = 0
for row in grid:
for i, number in enumerate(__snake_case ):
if number < 0:
total += len(__snake_case ) - i
break
return total
def lowerCamelCase__ ( ) -> None:
"""simple docstring"""
from timeit import timeit
print('''Running benchmarks''' )
_UpperCamelCase = (
'''from __main__ import count_negatives_binary_search, '''
'''count_negatives_brute_force, count_negatives_brute_force_with_break, grid'''
)
for func in (
"count_negatives_binary_search", # took 0.7727 seconds
"count_negatives_brute_force_with_break", # took 4.6505 seconds
"count_negatives_brute_force", # took 12.8160 seconds
):
_UpperCamelCase = timeit(F'''{func}(grid=grid)''', setup=__snake_case, number=5_00 )
print(F'''{func}() took {time:0.4f} seconds''' )
if __name__ == "__main__":
import doctest
doctest.testmod()
benchmark()
| 78 | 0 |
"""simple docstring"""
def lowerCamelCase__ ( __snake_case ) -> bool:
return number & 1 == 0
if __name__ == "__main__":
import doctest
doctest.testmod()
| 720 |
"""simple docstring"""
import copy
import re
class _UpperCAmelCase:
lowercase__ = 'hp'
lowercase__ = {}
lowercase__ = None
@classmethod
def UpperCAmelCase ( cls , __a , __a) -> Dict:
'''simple docstring'''
_UpperCamelCase = prefix
_UpperCamelCase = defaults
cls.build_naming_info()
@staticmethod
def UpperCAmelCase ( __a , __a) -> Union[str, Any]:
'''simple docstring'''
if len(__a) == 0:
return ""
_UpperCamelCase = None
if any(char.isdigit() for char in word):
raise Exception(F'''Parameters should not contain numbers: \'{word}\' contains a number''')
if word in info["short_word"]:
return info["short_word"][word]
for prefix_len in range(1 , len(__a) + 1):
_UpperCamelCase = word[:prefix_len]
if prefix in info["reverse_short_word"]:
continue
else:
_UpperCamelCase = prefix
break
if short_word is None:
# Paranoid fallback
def int_to_alphabetic(__a):
_UpperCamelCase = ''''''
while integer != 0:
_UpperCamelCase = chr(ord('''A''') + integer % 10) + s
integer //= 10
return s
_UpperCamelCase = 0
while True:
_UpperCamelCase = word + '''#''' + int_to_alphabetic(__a)
if sword in info["reverse_short_word"]:
continue
else:
_UpperCamelCase = sword
break
_UpperCamelCase = short_word
_UpperCamelCase = word
return short_word
@staticmethod
def UpperCAmelCase ( __a , __a) -> Any:
'''simple docstring'''
_UpperCamelCase = param_name.split('''_''')
_UpperCamelCase = [TrialShortNamer.shortname_for_word(__a , __a) for word in words]
# We try to create a separatorless short name, but if there is a collision we have to fallback
# to a separated short name
_UpperCamelCase = ['''''', '''_''']
for separator in separators:
_UpperCamelCase = separator.join(__a)
if shortname not in info["reverse_short_param"]:
_UpperCamelCase = shortname
_UpperCamelCase = param_name
return shortname
return param_name
@staticmethod
def UpperCAmelCase ( __a , __a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = TrialShortNamer.shortname_for_key(__a , __a)
_UpperCamelCase = short_name
_UpperCamelCase = param_name
@classmethod
def UpperCAmelCase ( cls) -> Any:
'''simple docstring'''
if cls.NAMING_INFO is not None:
return
_UpperCamelCase = {
'''short_word''': {},
'''reverse_short_word''': {},
'''short_param''': {},
'''reverse_short_param''': {},
}
_UpperCamelCase = list(cls.DEFAULTS.keys())
for k in field_keys:
cls.add_new_param_name(__a , __a)
_UpperCamelCase = info
@classmethod
def UpperCAmelCase ( cls , __a) -> Optional[Any]:
'''simple docstring'''
cls.build_naming_info()
assert cls.PREFIX is not None
_UpperCamelCase = [copy.copy(cls.PREFIX)]
for k, v in params.items():
if k not in cls.DEFAULTS:
raise Exception(F'''You should provide a default value for the param name {k} with value {v}''')
if v == cls.DEFAULTS[k]:
# The default value is not added to the name
continue
_UpperCamelCase = cls.NAMING_INFO['''short_param'''][k]
if isinstance(__a , __a):
_UpperCamelCase = 1 if v else 0
_UpperCamelCase = '''''' if isinstance(__a , (int, float)) else '''-'''
_UpperCamelCase = F'''{key}{sep}{v}'''
name.append(__a)
return "_".join(__a)
@classmethod
def UpperCAmelCase ( cls , __a) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = repr[len(cls.PREFIX) + 1 :]
if repr == "":
_UpperCamelCase = []
else:
_UpperCamelCase = repr.split('''_''')
_UpperCamelCase = {}
for value in values:
if "-" in value:
_UpperCamelCase , _UpperCamelCase = value.split('''-''')
else:
_UpperCamelCase = re.sub('''[0-9.]''' , '''''' , __a)
_UpperCamelCase = float(re.sub('''[^0-9.]''' , '''''' , __a))
_UpperCamelCase = cls.NAMING_INFO['''reverse_short_param'''][p_k]
_UpperCamelCase = p_v
for k in cls.DEFAULTS:
if k not in parameters:
_UpperCamelCase = cls.DEFAULTS[k]
return parameters
| 78 | 0 |
"""simple docstring"""
import unittest
import numpy as np
from diffusers import LMSDiscreteScheduler, OnnxStableDiffusionInpaintPipeline
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 _UpperCAmelCase( __SCREAMING_SNAKE_CASE , unittest.TestCase ):
pass
@nightly
@require_onnxruntime
@require_torch_gpu
class _UpperCAmelCase( unittest.TestCase ):
@property
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
return (
"CUDAExecutionProvider",
{
"gpu_mem_limit": "15000000000", # 15GB
"arena_extend_strategy": "kSameAsRequested",
},
)
@property
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = ort.SessionOptions()
_UpperCamelCase = False
return options
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/in_paint/overture-creations-5sI6fQgYIuo.png''')
_UpperCamelCase = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/in_paint/overture-creations-5sI6fQgYIuo_mask.png''')
_UpperCamelCase = OnnxStableDiffusionInpaintPipeline.from_pretrained(
'''runwayml/stable-diffusion-inpainting''' , revision='''onnx''' , safety_checker=_a , feature_extractor=_a , provider=self.gpu_provider , sess_options=self.gpu_options , )
pipe.set_progress_bar_config(disable=_a)
_UpperCamelCase = '''A red cat sitting on a park bench'''
_UpperCamelCase = np.random.RandomState(0)
_UpperCamelCase = pipe(
prompt=_a , image=_a , mask_image=_a , guidance_scale=7.5 , num_inference_steps=10 , generator=_a , output_type='''np''' , )
_UpperCamelCase = output.images
_UpperCamelCase = images[0, 2_55:2_58, 2_55:2_58, -1]
assert images.shape == (1, 5_12, 5_12, 3)
_UpperCamelCase = np.array([0.2514, 0.3007, 0.3517, 0.1790, 0.2382, 0.3167, 0.1944, 0.2273, 0.2464])
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/in_paint/overture-creations-5sI6fQgYIuo.png''')
_UpperCamelCase = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/in_paint/overture-creations-5sI6fQgYIuo_mask.png''')
_UpperCamelCase = LMSDiscreteScheduler.from_pretrained(
'''runwayml/stable-diffusion-inpainting''' , subfolder='''scheduler''' , revision='''onnx''')
_UpperCamelCase = OnnxStableDiffusionInpaintPipeline.from_pretrained(
'''runwayml/stable-diffusion-inpainting''' , 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)
_UpperCamelCase = '''A red cat sitting on a park bench'''
_UpperCamelCase = np.random.RandomState(0)
_UpperCamelCase = pipe(
prompt=_a , image=_a , mask_image=_a , guidance_scale=7.5 , num_inference_steps=20 , generator=_a , output_type='''np''' , )
_UpperCamelCase = output.images
_UpperCamelCase = images[0, 2_55:2_58, 2_55:2_58, -1]
assert images.shape == (1, 5_12, 5_12, 3)
_UpperCamelCase = np.array([0.0086, 0.0077, 0.0083, 0.0093, 0.0107, 0.0139, 0.0094, 0.0097, 0.0125])
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
| 721 |
"""simple docstring"""
import os
import time
import pytest
from datasets.utils.filelock import FileLock, Timeout
def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]:
"""simple docstring"""
_UpperCamelCase = FileLock(str(tmpdir / '''foo.lock''' ) )
_UpperCamelCase = FileLock(str(tmpdir / '''foo.lock''' ) )
_UpperCamelCase = 0.01
with locka.acquire():
with pytest.raises(__snake_case ):
_UpperCamelCase = time.time()
locka.acquire(__snake_case )
assert time.time() - _start > timeout
def lowerCamelCase__ ( __snake_case ) -> List[Any]:
"""simple docstring"""
_UpperCamelCase = '''a''' * 10_00 + '''.lock'''
_UpperCamelCase = FileLock(str(tmpdir / filename ) )
assert locka._lock_file.endswith('''.lock''' )
assert not locka._lock_file.endswith(__snake_case )
assert len(os.path.basename(locka._lock_file ) ) <= 2_55
_UpperCamelCase = FileLock(tmpdir / filename )
with locka.acquire():
with pytest.raises(__snake_case ):
locka.acquire(0 )
| 78 | 0 |
"""simple docstring"""
import math
from dataclasses import dataclass
from typing import List, Optional, Tuple, Union
import numpy as np
import torch
from diffusers.configuration_utils import ConfigMixin, register_to_config
from diffusers.schedulers.scheduling_utils import SchedulerMixin
from diffusers.utils import BaseOutput, deprecate
@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = 42
lowercase__ = None
def lowerCamelCase__ ( __snake_case, __snake_case=0.999, __snake_case="cosine", ):
"""simple docstring"""
if alpha_transform_type == "cosine":
def alpha_bar_fn(__snake_case ):
return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2
elif alpha_transform_type == "exp":
def alpha_bar_fn(__snake_case ):
return math.exp(t * -12.0 )
else:
raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}''' )
_UpperCamelCase = []
for i in range(_lowerCamelCase ):
_UpperCamelCase = i / num_diffusion_timesteps
_UpperCamelCase = (i + 1) / num_diffusion_timesteps
betas.append(min(1 - alpha_bar_fn(_lowerCamelCase ) / alpha_bar_fn(_lowerCamelCase ), _lowerCamelCase ) )
return torch.tensor(_lowerCamelCase, dtype=torch.floataa )
class _UpperCAmelCase( lowerCamelCase , lowerCamelCase ):
lowercase__ = 1
@register_to_config
def __init__( self , __a = 10_00 , __a = 0.0001 , __a = 0.02 , __a = "linear" , __a = None , __a = True , __a = True , __a = 0 , __a = "epsilon" , __a = 1.0 , **__a , ) -> int:
'''simple docstring'''
if kwargs.get('''set_alpha_to_one''' , UpperCamelCase__) is not None:
_UpperCamelCase = (
'''The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.'''
)
deprecate('''set_alpha_to_one''' , '''1.0.0''' , UpperCamelCase__ , standard_warn=UpperCamelCase__)
_UpperCamelCase = kwargs['''set_alpha_to_one''']
if trained_betas is not None:
_UpperCamelCase = torch.tensor(UpperCamelCase__ , dtype=torch.floataa)
elif beta_schedule == "linear":
_UpperCamelCase = torch.linspace(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , dtype=torch.floataa)
elif beta_schedule == "scaled_linear":
# this schedule is very specific to the latent diffusion model.
_UpperCamelCase = (
torch.linspace(beta_start**0.5 , beta_end**0.5 , UpperCamelCase__ , dtype=torch.floataa) ** 2
)
elif beta_schedule == "squaredcos_cap_v2":
# Glide cosine schedule
_UpperCamelCase = betas_for_alpha_bar(UpperCamelCase__)
else:
raise NotImplementedError(F'''{beta_schedule} does is not implemented for {self.__class__}''')
_UpperCamelCase = 1.0 - self.betas
_UpperCamelCase = torch.cumprod(self.alphas , dim=0)
# At every step in inverted ddim, we are looking into the next alphas_cumprod
# For the final step, there is no next alphas_cumprod, and the index is out of bounds
# `set_alpha_to_zero` decides whether we set this parameter simply to zero
# in this case, self.step() just output the predicted noise
# or whether we use the final alpha of the "non-previous" one.
_UpperCamelCase = torch.tensor(0.0) if set_alpha_to_zero else self.alphas_cumprod[-1]
# standard deviation of the initial noise distribution
_UpperCamelCase = 1.0
# setable values
_UpperCamelCase = None
_UpperCamelCase = torch.from_numpy(np.arange(0 , UpperCamelCase__).copy().astype(np.intaa))
def UpperCAmelCase ( self , __a , __a = None) -> torch.FloatTensor:
'''simple docstring'''
return sample
def UpperCAmelCase ( self , __a , __a = None) -> List[str]:
'''simple docstring'''
if num_inference_steps > self.config.num_train_timesteps:
raise ValueError(
F'''`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:'''
F''' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle'''
F''' maximal {self.config.num_train_timesteps} timesteps.''')
_UpperCamelCase = num_inference_steps
_UpperCamelCase = self.config.num_train_timesteps // self.num_inference_steps
# creates integer timesteps by multiplying by ratio
# casting to int to avoid issues when num_inference_step is power of 3
_UpperCamelCase = (np.arange(0 , UpperCamelCase__) * step_ratio).round().copy().astype(np.intaa)
_UpperCamelCase = torch.from_numpy(UpperCamelCase__).to(UpperCamelCase__)
self.timesteps += self.config.steps_offset
def UpperCAmelCase ( self , __a , __a , __a , __a = 0.0 , __a = False , __a = None , __a = True , ) -> Union[DDIMSchedulerOutput, Tuple]:
'''simple docstring'''
_UpperCamelCase = timestep + self.config.num_train_timesteps // self.num_inference_steps
# 2. compute alphas, betas
# change original implementation to exactly match noise levels for analogous forward process
_UpperCamelCase = self.alphas_cumprod[timestep]
_UpperCamelCase = (
self.alphas_cumprod[prev_timestep]
if prev_timestep < self.config.num_train_timesteps
else self.final_alpha_cumprod
)
_UpperCamelCase = 1 - alpha_prod_t
# 3. compute predicted original sample from predicted noise also called
# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
if self.config.prediction_type == "epsilon":
_UpperCamelCase = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
_UpperCamelCase = model_output
elif self.config.prediction_type == "sample":
_UpperCamelCase = model_output
_UpperCamelCase = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5
elif self.config.prediction_type == "v_prediction":
_UpperCamelCase = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output
_UpperCamelCase = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample
else:
raise ValueError(
F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or'''
''' `v_prediction`''')
# 4. Clip or threshold "predicted x_0"
if self.config.clip_sample:
_UpperCamelCase = pred_original_sample.clamp(
-self.config.clip_sample_range , self.config.clip_sample_range)
# 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
_UpperCamelCase = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon
# 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
_UpperCamelCase = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction
if not return_dict:
return (prev_sample, pred_original_sample)
return DDIMSchedulerOutput(prev_sample=UpperCamelCase__ , pred_original_sample=UpperCamelCase__)
def __len__( self) -> Union[str, Any]:
'''simple docstring'''
return self.config.num_train_timesteps
| 700 |
"""simple docstring"""
from math import sqrt
def lowerCamelCase__ ( __snake_case ) -> bool:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (
number >= 0
), "'number' must been an int and positive"
_UpperCamelCase = True
# 0 and 1 are none primes.
if number <= 1:
_UpperCamelCase = False
for divisor in range(2, int(round(sqrt(__snake_case ) ) ) + 1 ):
# if 'number' divisible by 'divisor' then sets 'status'
# of false and break up the loop.
if number % divisor == 0:
_UpperCamelCase = False
break
# precondition
assert isinstance(__snake_case, __snake_case ), "'status' must been from type bool"
return status
def lowerCamelCase__ ( __snake_case ) -> Dict:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n > 2), "'N' must been an int and > 2"
# beginList: contains all natural numbers from 2 up to N
_UpperCamelCase = list(range(2, n + 1 ) )
_UpperCamelCase = [] # this list will be returns.
# actual sieve of erathostenes
for i in range(len(__snake_case ) ):
for j in range(i + 1, len(__snake_case ) ):
if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0):
_UpperCamelCase = 0
# filters actual prime numbers.
_UpperCamelCase = [x for x in begin_list if x != 0]
# precondition
assert isinstance(__snake_case, __snake_case ), "'ans' must been from type list"
return ans
def lowerCamelCase__ ( __snake_case ) -> List[str]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n > 2), "'N' must been an int and > 2"
_UpperCamelCase = []
# iterates over all numbers between 2 up to N+1
# if a number is prime then appends to list 'ans'
for number in range(2, n + 1 ):
if is_prime(__snake_case ):
ans.append(__snake_case )
# precondition
assert isinstance(__snake_case, __snake_case ), "'ans' must been from type list"
return ans
def lowerCamelCase__ ( __snake_case ) -> Optional[int]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and number >= 0, "'number' must been an int and >= 0"
_UpperCamelCase = [] # this list will be returns of the function.
# potential prime number factors.
_UpperCamelCase = 2
_UpperCamelCase = number
if number == 0 or number == 1:
ans.append(__snake_case )
# if 'number' not prime then builds the prime factorization of 'number'
elif not is_prime(__snake_case ):
while quotient != 1:
if is_prime(__snake_case ) and (quotient % factor == 0):
ans.append(__snake_case )
quotient /= factor
else:
factor += 1
else:
ans.append(__snake_case )
# precondition
assert isinstance(__snake_case, __snake_case ), "'ans' must been from type list"
return ans
def lowerCamelCase__ ( __snake_case ) -> Optional[Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (
number >= 0
), "'number' bust been an int and >= 0"
_UpperCamelCase = 0
# prime factorization of 'number'
_UpperCamelCase = prime_factorization(__snake_case )
_UpperCamelCase = max(__snake_case )
# precondition
assert isinstance(__snake_case, __snake_case ), "'ans' must been from type int"
return ans
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (
number >= 0
), "'number' bust been an int and >= 0"
_UpperCamelCase = 0
# prime factorization of 'number'
_UpperCamelCase = prime_factorization(__snake_case )
_UpperCamelCase = min(__snake_case )
# precondition
assert isinstance(__snake_case, __snake_case ), "'ans' must been from type int"
return ans
def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ), "'number' must been an int"
assert isinstance(number % 2 == 0, __snake_case ), "compare bust been from type bool"
return number % 2 == 0
def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ), "'number' must been an int"
assert isinstance(number % 2 != 0, __snake_case ), "compare bust been from type bool"
return number % 2 != 0
def lowerCamelCase__ ( __snake_case ) -> str:
"""simple docstring"""
assert (
isinstance(__snake_case, __snake_case ) and (number > 2) and is_even(__snake_case )
), "'number' must been an int, even and > 2"
_UpperCamelCase = [] # this list will returned
# creates a list of prime numbers between 2 up to 'number'
_UpperCamelCase = get_prime_numbers(__snake_case )
_UpperCamelCase = len(__snake_case )
# run variable for while-loops.
_UpperCamelCase = 0
_UpperCamelCase = None
# exit variable. for break up the loops
_UpperCamelCase = True
while i < len_pn and loop:
_UpperCamelCase = i + 1
while j < len_pn and loop:
if prime_numbers[i] + prime_numbers[j] == number:
_UpperCamelCase = False
ans.append(prime_numbers[i] )
ans.append(prime_numbers[j] )
j += 1
i += 1
# precondition
assert (
isinstance(__snake_case, __snake_case )
and (len(__snake_case ) == 2)
and (ans[0] + ans[1] == number)
and is_prime(ans[0] )
and is_prime(ans[1] )
), "'ans' must contains two primes. And sum of elements must been eq 'number'"
return ans
def lowerCamelCase__ ( __snake_case, __snake_case ) -> str:
"""simple docstring"""
assert (
isinstance(__snake_case, __snake_case )
and isinstance(__snake_case, __snake_case )
and (numbera >= 0)
and (numbera >= 0)
), "'number1' and 'number2' must been positive integer."
_UpperCamelCase = 0
while numbera != 0:
_UpperCamelCase = numbera % numbera
_UpperCamelCase = numbera
_UpperCamelCase = rest
# precondition
assert isinstance(__snake_case, __snake_case ) and (
numbera >= 0
), "'number' must been from type int and positive"
return numbera
def lowerCamelCase__ ( __snake_case, __snake_case ) -> List[str]:
"""simple docstring"""
assert (
isinstance(__snake_case, __snake_case )
and isinstance(__snake_case, __snake_case )
and (numbera >= 1)
and (numbera >= 1)
), "'number1' and 'number2' must been positive integer."
_UpperCamelCase = 1 # actual answer that will be return.
# for kgV (x,1)
if numbera > 1 and numbera > 1:
# builds the prime factorization of 'number1' and 'number2'
_UpperCamelCase = prime_factorization(__snake_case )
_UpperCamelCase = prime_factorization(__snake_case )
elif numbera == 1 or numbera == 1:
_UpperCamelCase = []
_UpperCamelCase = []
_UpperCamelCase = max(__snake_case, __snake_case )
_UpperCamelCase = 0
_UpperCamelCase = 0
_UpperCamelCase = [] # captured numbers int both 'primeFac1' and 'primeFac2'
# iterates through primeFac1
for n in prime_fac_a:
if n not in done:
if n in prime_fac_a:
_UpperCamelCase = prime_fac_a.count(__snake_case )
_UpperCamelCase = prime_fac_a.count(__snake_case )
for _ in range(max(__snake_case, __snake_case ) ):
ans *= n
else:
_UpperCamelCase = prime_fac_a.count(__snake_case )
for _ in range(__snake_case ):
ans *= n
done.append(__snake_case )
# iterates through primeFac2
for n in prime_fac_a:
if n not in done:
_UpperCamelCase = prime_fac_a.count(__snake_case )
for _ in range(__snake_case ):
ans *= n
done.append(__snake_case )
# precondition
assert isinstance(__snake_case, __snake_case ) and (
ans >= 0
), "'ans' must been from type int and positive"
return ans
def lowerCamelCase__ ( __snake_case ) -> Tuple:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n >= 0), "'number' must been a positive int"
_UpperCamelCase = 0
_UpperCamelCase = 2 # this variable holds the answer
while index < n:
index += 1
ans += 1 # counts to the next number
# if ans not prime then
# runs to the next prime number.
while not is_prime(__snake_case ):
ans += 1
# precondition
assert isinstance(__snake_case, __snake_case ) and is_prime(
__snake_case ), "'ans' must been a prime number and from type int"
return ans
def lowerCamelCase__ ( __snake_case, __snake_case ) -> Tuple:
"""simple docstring"""
assert (
is_prime(__snake_case ) and is_prime(__snake_case ) and (p_number_a < p_number_a)
), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'"
_UpperCamelCase = p_number_a + 1 # jump to the next number
_UpperCamelCase = [] # this list will be returns.
# if number is not prime then
# fetch the next prime number.
while not is_prime(__snake_case ):
number += 1
while number < p_number_a:
ans.append(__snake_case )
number += 1
# fetch the next prime number.
while not is_prime(__snake_case ):
number += 1
# precondition
assert (
isinstance(__snake_case, __snake_case )
and ans[0] != p_number_a
and ans[len(__snake_case ) - 1] != p_number_a
), "'ans' must been a list without the arguments"
# 'ans' contains not 'pNumber1' and 'pNumber2' !
return ans
def lowerCamelCase__ ( __snake_case ) -> List[Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n >= 1), "'n' must been int and >= 1"
_UpperCamelCase = [] # will be returned.
for divisor in range(1, n + 1 ):
if n % divisor == 0:
ans.append(__snake_case )
# precondition
assert ans[0] == 1 and ans[len(__snake_case ) - 1] == n, "Error in function getDivisiors(...)"
return ans
def lowerCamelCase__ ( __snake_case ) -> str:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (
number > 1
), "'number' must been an int and >= 1"
_UpperCamelCase = get_divisors(__snake_case )
# precondition
assert (
isinstance(__snake_case, __snake_case )
and (divisors[0] == 1)
and (divisors[len(__snake_case ) - 1] == number)
), "Error in help-function getDivisiors(...)"
# summed all divisors up to 'number' (exclusive), hence [:-1]
return sum(divisors[:-1] ) == number
def lowerCamelCase__ ( __snake_case, __snake_case ) -> Optional[Any]:
"""simple docstring"""
assert (
isinstance(__snake_case, __snake_case )
and isinstance(__snake_case, __snake_case )
and (denominator != 0)
), "The arguments must been from type int and 'denominator' != 0"
# build the greatest common divisor of numerator and denominator.
_UpperCamelCase = gcd(abs(__snake_case ), abs(__snake_case ) )
# precondition
assert (
isinstance(__snake_case, __snake_case )
and (numerator % gcd_of_fraction == 0)
and (denominator % gcd_of_fraction == 0)
), "Error in function gcd(...,...)"
return (numerator // gcd_of_fraction, denominator // gcd_of_fraction)
def lowerCamelCase__ ( __snake_case ) -> Optional[Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n >= 0), "'n' must been a int and >= 0"
_UpperCamelCase = 1 # this will be return.
for factor in range(1, n + 1 ):
ans *= factor
return ans
def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n >= 0), "'n' must been an int and >= 0"
_UpperCamelCase = 0
_UpperCamelCase = 1
_UpperCamelCase = 1 # this will be return
for _ in range(n - 1 ):
_UpperCamelCase = ans
ans += fiba
_UpperCamelCase = tmp
return ans
| 78 | 0 |
"""simple docstring"""
import tempfile
import unittest
from make_student import create_student_by_copying_alternating_layers
from transformers import AutoConfig
from transformers.file_utils import cached_property
from transformers.testing_utils import require_torch
_a = """sshleifer/bart-tiny-random"""
_a = """patrickvonplaten/t5-tiny-random"""
@require_torch
class _UpperCAmelCase( unittest.TestCase ):
@cached_property
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
return AutoConfig.from_pretrained(__a)
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase , *_UpperCamelCase = create_student_by_copying_alternating_layers(__a , tempfile.mkdtemp() , e=1 , d=1)
self.assertEqual(student.config.num_hidden_layers , 1)
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
_UpperCamelCase , *_UpperCamelCase = create_student_by_copying_alternating_layers(__a , tempfile.mkdtemp() , e=1 , d=__a)
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
_UpperCamelCase , *_UpperCamelCase = create_student_by_copying_alternating_layers(__a , tempfile.mkdtemp() , e=1 , d=__a)
self.assertEqual(student.config.encoder_layers , 1)
self.assertEqual(student.config.decoder_layers , self.teacher_config.encoder_layers)
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase , *_UpperCamelCase = create_student_by_copying_alternating_layers(__a , tempfile.mkdtemp() , e=1 , d=1)
self.assertEqual(student.config.encoder_layers , 1)
self.assertEqual(student.config.decoder_layers , 1)
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
with self.assertRaises(__a):
create_student_by_copying_alternating_layers(__a , tempfile.mkdtemp() , e=__a , d=__a)
| 701 |
"""simple docstring"""
import logging
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional, Union
from .generation.configuration_utils import GenerationConfig
from .training_args import TrainingArguments
from .utils import add_start_docstrings
_a = logging.getLogger(__name__)
@dataclass
@add_start_docstrings(TrainingArguments.__doc__ )
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = field(default=lowerCamelCase , metadata={'help': 'Whether to use SortishSampler or not.'} )
lowercase__ = field(
default=lowerCamelCase , metadata={'help': 'Whether to use generate to calculate generative metrics (ROUGE, BLEU).'} )
lowercase__ = field(
default=lowerCamelCase , metadata={
'help': (
'The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default '
'to the `max_length` value of the model configuration.'
)
} , )
lowercase__ = field(
default=lowerCamelCase , metadata={
'help': (
'The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default '
'to the `num_beams` value of the model configuration.'
)
} , )
lowercase__ = field(
default=lowerCamelCase , metadata={
'help': 'Model id, file path or url pointing to a GenerationConfig json file, to use during prediction.'
} , )
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = super().to_dict()
for k, v in d.items():
if isinstance(__a , __a):
_UpperCamelCase = v.to_dict()
return d
| 78 | 0 |
"""simple docstring"""
import os
import re
import unicodedata
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import is_torch_available, logging
if is_torch_available():
import torch
if TYPE_CHECKING:
from transformers.pipelines.conversational import Conversation
_a = logging.get_logger(__name__)
_a = {"""vocab_file""": """spiece.model"""}
_a = {
"""vocab_file""": {
"""AI-Sweden/gpt-sw3-126m""": """https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model""",
"""AI-Sweden/gpt-sw3-350m""": """https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model""",
"""AI-Sweden/gpt-sw3-1.6b""": """https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model""",
"""AI-Sweden/gpt-sw3-6.7b""": """https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model""",
"""AI-Sweden/gpt-sw3-20b""": """https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model""",
}
}
_a = {
"""AI-Sweden/gpt-sw3-126m""": 2048,
"""AI-Sweden/gpt-sw3-350m""": 2048,
"""AI-Sweden/gpt-sw3-1.6b""": 2048,
"""AI-Sweden/gpt-sw3-6.7b""": 2048,
"""AI-Sweden/gpt-sw3-20b""": 2048,
}
class _UpperCAmelCase( _UpperCAmelCase ):
lowercase__ = VOCAB_FILES_NAMES
lowercase__ = PRETRAINED_VOCAB_FILES_MAP
lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
lowercase__ = ['input_ids', 'attention_mask']
def __init__( self , __a , __a=False , __a=False , __a=False , __a=None , __a=None , __a=None , __a=None , __a = None , **__a , ) -> List[str]:
'''simple docstring'''
_UpperCamelCase = {} if sp_model_kwargs is None else sp_model_kwargs
_UpperCamelCase = kwargs.get('''name_or_path''')
if name_or_path is None:
logger.warning(
'''name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,'''
''' you are testing the model, this can safely be ignored''')
_UpperCamelCase = "None"
# Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing
_UpperCamelCase = "<|endoftext|>" if eos_token is None else eos_token
_UpperCamelCase = "<unk>" if unk_token is None else unk_token
if "gpt-sw3-7b" in name_or_path:
_UpperCamelCase = unk_token if pad_token is None else pad_token
_UpperCamelCase = eos_token if bos_token is None else bos_token
else:
_UpperCamelCase = "<pad>" if pad_token is None else pad_token
_UpperCamelCase = "<s>" if bos_token is None else bos_token
super().__init__(
do_lower_case=lowercase__ , remove_space=lowercase__ , keep_accents=lowercase__ , bos_token=lowercase__ , eos_token=lowercase__ , unk_token=lowercase__ , pad_token=lowercase__ , sp_model_kwargs=self.sp_model_kwargs , **lowercase__ , )
_UpperCamelCase = do_lower_case
_UpperCamelCase = remove_space
_UpperCamelCase = keep_accents
_UpperCamelCase = vocab_file
_UpperCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs)
self.sp_model.Load(lowercase__)
# Used for whitespace normalization in input texts
# fmt : off
_UpperCamelCase = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "", ""}
# fmt : on
# Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing
_UpperCamelCase = re.compile(
F'''[{"".join(map(lowercase__ , list(range(0 , 9)) + list(range(11 , 32)) + list(range(1_27 , 1_60)) + [1_60, 1_73, 82_03]))}]''')
def __getstate__( self) -> int:
'''simple docstring'''
_UpperCamelCase = self.__dict__.copy()
_UpperCamelCase = None
return state
def __setstate__( self , __a) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = d
# for backward compatibility
if not hasattr(self , '''sp_model_kwargs'''):
_UpperCamelCase = {}
_UpperCamelCase = spm.SentencePieceProcessor(**self.sp_model_kwargs)
self.sp_model.Load(self.vocab_file)
@property
# Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
return len(self.sp_model)
def UpperCAmelCase ( self , __a) -> Tuple:
'''simple docstring'''
_UpperCamelCase = self.non_printing_characters_re.sub('''''' , lowercase__)
# Normalize whitespaces
_UpperCamelCase = "".join([char if char not in self.whitespaces else ''' ''' for char in text])
# NFC Unicode normalization
_UpperCamelCase = unicodedata.normalize('''NFC''' , lowercase__)
return text
def UpperCAmelCase ( self , __a , **__a) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.preprocess_text(lowercase__)
return self.sp_model.encode(lowercase__ , out_type=lowercase__)
def UpperCAmelCase ( self , __a) -> Any:
'''simple docstring'''
return self.sp_model.PieceToId(lowercase__)
def UpperCAmelCase ( self , __a) -> Optional[int]:
'''simple docstring'''
return self.sp_model.IdToPiece(lowercase__)
@staticmethod
def UpperCAmelCase ( __a) -> Union[str, Any]:
'''simple docstring'''
return out_string
def UpperCAmelCase ( self , __a) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = []
_UpperCamelCase = ""
_UpperCamelCase = False
for token in tokens:
# make sure that special tokens are not decoded using sentencepiece model
if token in self.all_special_tokens:
# TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document
if not prev_is_special:
out_string += " "
out_string += self.sp_model.decode(lowercase__) + token
_UpperCamelCase = True
_UpperCamelCase = []
else:
current_sub_tokens.append(lowercase__)
_UpperCamelCase = False
out_string += self.sp_model.decode(lowercase__)
return out_string
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
_UpperCamelCase = {self.convert_ids_to_tokens(lowercase__): i for i in range(self.vocab_size)}
vocab.update(self.added_tokens_encoder)
return vocab
def UpperCAmelCase ( self , __a , __a = None) -> List[str]:
'''simple docstring'''
if not os.path.isdir(lowercase__):
logger.error(F'''Vocabulary path ({save_directory}) should be a directory''')
return
_UpperCamelCase = os.path.join(
lowercase__ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''])
if os.path.abspath(self.vocab_file) != os.path.abspath(lowercase__) and os.path.isfile(self.vocab_file):
copyfile(self.vocab_file , lowercase__)
elif not os.path.isfile(self.vocab_file):
with open(lowercase__ , '''wb''') as fi:
_UpperCamelCase = self.sp_model.serialized_model_proto()
fi.write(lowercase__)
return (out_vocab_file,)
def UpperCAmelCase ( self , __a , __a = False) -> Tuple:
'''simple docstring'''
if isinstance(lowercase__ , lowercase__):
_UpperCamelCase = self.preprocess_text(lowercase__)
_UpperCamelCase = self.sp_model.encode(lowercase__)
else:
_UpperCamelCase = [self.preprocess_text(lowercase__) for t in text]
_UpperCamelCase = self.sp_model.encode(lowercase__)
if return_tensors is True or return_tensors == "pt":
_UpperCamelCase = torch.tensor(lowercase__)
return token_ids
def UpperCAmelCase ( self , __a) -> List[Any]:
'''simple docstring'''
return self.sp_model.decode(lowercase__)
def UpperCAmelCase ( self , __a) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = [F'''User: {text}''' if is_user else F'''Bot: {text}''' for is_user, text in conversation.iter_texts()]
_UpperCamelCase = (
F'''{self.eos_token}{self.bos_token}''' + F'''{self.bos_token}'''.join(lowercase__) + F'''{self.bos_token}Bot:'''
)
return self.encode(text=lowercase__)
| 702 |
"""simple docstring"""
import argparse
import torch
from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration
from transformers.utils import logging
logging.set_verbosity_info()
_a = logging.get_logger(__name__)
_a = [
["""attention""", """attn"""],
["""encoder_attention""", """encoder_attn"""],
["""q_lin""", """q_proj"""],
["""k_lin""", """k_proj"""],
["""v_lin""", """v_proj"""],
["""out_lin""", """out_proj"""],
["""norm_embeddings""", """layernorm_embedding"""],
["""position_embeddings""", """embed_positions"""],
["""embeddings""", """embed_tokens"""],
["""ffn.lin""", """fc"""],
]
def lowerCamelCase__ ( __snake_case ) -> Optional[Any]:
"""simple docstring"""
if k == "embeddings.weight":
return "shared.weight"
for parlai_name, hf_name in PATTERNS:
_UpperCamelCase = k.replace(__snake_case, __snake_case )
if k.startswith('''encoder''' ):
_UpperCamelCase = k.replace('''.attn''', '''.self_attn''' )
_UpperCamelCase = k.replace('''norm1''', '''self_attn_layer_norm''' )
_UpperCamelCase = k.replace('''norm2''', '''final_layer_norm''' )
elif k.startswith('''decoder''' ):
_UpperCamelCase = k.replace('''norm1''', '''self_attn_layer_norm''' )
_UpperCamelCase = k.replace('''norm2''', '''encoder_attn_layer_norm''' )
_UpperCamelCase = k.replace('''norm3''', '''final_layer_norm''' )
return k
def lowerCamelCase__ ( __snake_case ) -> Optional[int]:
"""simple docstring"""
_UpperCamelCase = [
'''model.encoder.layernorm_embedding.weight''',
'''model.encoder.layernorm_embedding.bias''',
'''model.decoder.layernorm_embedding.weight''',
'''model.decoder.layernorm_embedding.bias''',
]
for k in keys:
_UpperCamelCase = sd.pop(__snake_case )
_UpperCamelCase = k.replace('''layernorm_embedding''', '''layer_norm''' )
assert new_k not in sd
_UpperCamelCase = v
_a = ["""START"""]
@torch.no_grad()
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = torch.load(__snake_case, map_location='''cpu''' )
_UpperCamelCase = model['''model''']
_UpperCamelCase = BlenderbotConfig.from_json_file(__snake_case )
_UpperCamelCase = BlenderbotForConditionalGeneration(__snake_case )
_UpperCamelCase = m.model.state_dict().keys()
_UpperCamelCase = []
_UpperCamelCase = {}
for k, v in sd.items():
if k in IGNORE_KEYS:
continue
_UpperCamelCase = rename_state_dict_key(__snake_case )
if new_k not in valid_keys:
failures.append([k, new_k] )
else:
_UpperCamelCase = v
if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm
rename_layernorm_keys(__snake_case )
m.model.load_state_dict(__snake_case, strict=__snake_case )
m.half()
m.save_pretrained(__snake_case )
if __name__ == "__main__":
_a = argparse.ArgumentParser()
# Required parameters
parser.add_argument("""--src_path""", type=str, help="""like blenderbot-model.bin""")
parser.add_argument("""--save_dir""", default="""hf_blenderbot""", type=str, help="""Where to save converted model.""")
parser.add_argument(
"""--hf_config_json""", default="""blenderbot-3b-config.json""", type=str, help="""Path to config to use"""
)
_a = parser.parse_args()
convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
| 78 | 0 |
"""simple docstring"""
from math import factorial
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> float:
"""simple docstring"""
if successes > trials:
raise ValueError('''successes must be lower or equal to trials''' )
if trials < 0 or successes < 0:
raise ValueError('''the function is defined for non-negative integers''' )
if not isinstance(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ) or not isinstance(SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_ ):
raise ValueError('''the function is defined for non-negative integers''' )
if not 0 < prob < 1:
raise ValueError('''prob has to be in range of 1 - 0''' )
_UpperCamelCase = (prob**successes) * ((1 - prob) ** (trials - successes))
# Calculate the binomial coefficient: n! / k!(n-k)!
_UpperCamelCase = float(factorial(SCREAMING_SNAKE_CASE_ ) )
coefficient /= factorial(SCREAMING_SNAKE_CASE_ ) * factorial(trials - successes )
return probability * coefficient
if __name__ == "__main__":
from doctest import testmod
testmod()
print("""Probability of 2 successes out of 4 trails""")
print("""with probability of 0.75 is:""", end=""" """)
print(binomial_distribution(2, 4, 0.75))
| 703 |
"""simple docstring"""
import argparse
import os.path as osp
import re
import torch
from safetensors.torch import load_file, save_file
# =================#
# UNet Conversion #
# =================#
_a = [
# (stable-diffusion, HF Diffusers)
("""time_embed.0.weight""", """time_embedding.linear_1.weight"""),
("""time_embed.0.bias""", """time_embedding.linear_1.bias"""),
("""time_embed.2.weight""", """time_embedding.linear_2.weight"""),
("""time_embed.2.bias""", """time_embedding.linear_2.bias"""),
("""input_blocks.0.0.weight""", """conv_in.weight"""),
("""input_blocks.0.0.bias""", """conv_in.bias"""),
("""out.0.weight""", """conv_norm_out.weight"""),
("""out.0.bias""", """conv_norm_out.bias"""),
("""out.2.weight""", """conv_out.weight"""),
("""out.2.bias""", """conv_out.bias"""),
]
_a = [
# (stable-diffusion, HF Diffusers)
("""in_layers.0""", """norm1"""),
("""in_layers.2""", """conv1"""),
("""out_layers.0""", """norm2"""),
("""out_layers.3""", """conv2"""),
("""emb_layers.1""", """time_emb_proj"""),
("""skip_connection""", """conv_shortcut"""),
]
_a = []
# hardcoded number of downblocks and resnets/attentions...
# would need smarter logic for other networks.
for i in range(4):
# loop over downblocks/upblocks
for j in range(2):
# loop over resnets/attentions for downblocks
_a = F"""down_blocks.{i}.resnets.{j}."""
_a = F"""input_blocks.{3*i + j + 1}.0."""
unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix))
if i < 3:
# no attention layers in down_blocks.3
_a = F"""down_blocks.{i}.attentions.{j}."""
_a = F"""input_blocks.{3*i + j + 1}.1."""
unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix))
for j in range(3):
# loop over resnets/attentions for upblocks
_a = F"""up_blocks.{i}.resnets.{j}."""
_a = F"""output_blocks.{3*i + j}.0."""
unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix))
if i > 0:
# no attention layers in up_blocks.0
_a = F"""up_blocks.{i}.attentions.{j}."""
_a = F"""output_blocks.{3*i + j}.1."""
unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix))
if i < 3:
# no downsample in down_blocks.3
_a = F"""down_blocks.{i}.downsamplers.0.conv."""
_a = F"""input_blocks.{3*(i+1)}.0.op."""
unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix))
# no upsample in up_blocks.3
_a = F"""up_blocks.{i}.upsamplers.0."""
_a = F"""output_blocks.{3*i + 2}.{1 if i == 0 else 2}."""
unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix))
_a = """mid_block.attentions.0."""
_a = """middle_block.1."""
unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix))
for j in range(2):
_a = F"""mid_block.resnets.{j}."""
_a = F"""middle_block.{2*j}."""
unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix))
def lowerCamelCase__ ( __snake_case ) -> str:
"""simple docstring"""
_UpperCamelCase = {k: k for k in unet_state_dict.keys()}
for sd_name, hf_name in unet_conversion_map:
_UpperCamelCase = sd_name
for k, v in mapping.items():
if "resnets" in k:
for sd_part, hf_part in unet_conversion_map_resnet:
_UpperCamelCase = v.replace(__snake_case, __snake_case )
_UpperCamelCase = v
for k, v in mapping.items():
for sd_part, hf_part in unet_conversion_map_layer:
_UpperCamelCase = v.replace(__snake_case, __snake_case )
_UpperCamelCase = v
_UpperCamelCase = {v: unet_state_dict[k] for k, v in mapping.items()}
return new_state_dict
# ================#
# VAE Conversion #
# ================#
_a = [
# (stable-diffusion, HF Diffusers)
("""nin_shortcut""", """conv_shortcut"""),
("""norm_out""", """conv_norm_out"""),
("""mid.attn_1.""", """mid_block.attentions.0."""),
]
for i in range(4):
# down_blocks have two resnets
for j in range(2):
_a = F"""encoder.down_blocks.{i}.resnets.{j}."""
_a = F"""encoder.down.{i}.block.{j}."""
vae_conversion_map.append((sd_down_prefix, hf_down_prefix))
if i < 3:
_a = F"""down_blocks.{i}.downsamplers.0."""
_a = F"""down.{i}.downsample."""
vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix))
_a = F"""up_blocks.{i}.upsamplers.0."""
_a = F"""up.{3-i}.upsample."""
vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix))
# up_blocks have three resnets
# also, up blocks in hf are numbered in reverse from sd
for j in range(3):
_a = F"""decoder.up_blocks.{i}.resnets.{j}."""
_a = F"""decoder.up.{3-i}.block.{j}."""
vae_conversion_map.append((sd_up_prefix, hf_up_prefix))
# this part accounts for mid blocks in both the encoder and the decoder
for i in range(2):
_a = F"""mid_block.resnets.{i}."""
_a = F"""mid.block_{i+1}."""
vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix))
_a = [
# (stable-diffusion, HF Diffusers)
("""norm.""", """group_norm."""),
("""q.""", """query."""),
("""k.""", """key."""),
("""v.""", """value."""),
("""proj_out.""", """proj_attn."""),
]
def lowerCamelCase__ ( __snake_case ) -> List[str]:
"""simple docstring"""
return w.reshape(*w.shape, 1, 1 )
def lowerCamelCase__ ( __snake_case ) -> Optional[Any]:
"""simple docstring"""
_UpperCamelCase = {k: k for k in vae_state_dict.keys()}
for k, v in mapping.items():
for sd_part, hf_part in vae_conversion_map:
_UpperCamelCase = v.replace(__snake_case, __snake_case )
_UpperCamelCase = v
for k, v in mapping.items():
if "attentions" in k:
for sd_part, hf_part in vae_conversion_map_attn:
_UpperCamelCase = v.replace(__snake_case, __snake_case )
_UpperCamelCase = v
_UpperCamelCase = {v: vae_state_dict[k] for k, v in mapping.items()}
_UpperCamelCase = ['''q''', '''k''', '''v''', '''proj_out''']
for k, v in new_state_dict.items():
for weight_name in weights_to_convert:
if F'''mid.attn_1.{weight_name}.weight''' in k:
print(F'''Reshaping {k} for SD format''' )
_UpperCamelCase = reshape_weight_for_sd(__snake_case )
return new_state_dict
# =========================#
# Text Encoder Conversion #
# =========================#
_a = [
# (stable-diffusion, HF Diffusers)
("""resblocks.""", """text_model.encoder.layers."""),
("""ln_1""", """layer_norm1"""),
("""ln_2""", """layer_norm2"""),
(""".c_fc.""", """.fc1."""),
(""".c_proj.""", """.fc2."""),
(""".attn""", """.self_attn"""),
("""ln_final.""", """transformer.text_model.final_layer_norm."""),
("""token_embedding.weight""", """transformer.text_model.embeddings.token_embedding.weight"""),
("""positional_embedding""", """transformer.text_model.embeddings.position_embedding.weight"""),
]
_a = {re.escape(x[1]): x[0] for x in textenc_conversion_lst}
_a = re.compile("""|""".join(protected.keys()))
# Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp
_a = {"""q""": 0, """k""": 1, """v""": 2}
def lowerCamelCase__ ( __snake_case ) -> Any:
"""simple docstring"""
_UpperCamelCase = {}
_UpperCamelCase = {}
_UpperCamelCase = {}
for k, v in text_enc_dict.items():
if (
k.endswith('''.self_attn.q_proj.weight''' )
or k.endswith('''.self_attn.k_proj.weight''' )
or k.endswith('''.self_attn.v_proj.weight''' )
):
_UpperCamelCase = k[: -len('''.q_proj.weight''' )]
_UpperCamelCase = k[-len('''q_proj.weight''' )]
if k_pre not in capture_qkv_weight:
_UpperCamelCase = [None, None, None]
_UpperCamelCase = v
continue
if (
k.endswith('''.self_attn.q_proj.bias''' )
or k.endswith('''.self_attn.k_proj.bias''' )
or k.endswith('''.self_attn.v_proj.bias''' )
):
_UpperCamelCase = k[: -len('''.q_proj.bias''' )]
_UpperCamelCase = k[-len('''q_proj.bias''' )]
if k_pre not in capture_qkv_bias:
_UpperCamelCase = [None, None, None]
_UpperCamelCase = v
continue
_UpperCamelCase = textenc_pattern.sub(lambda __snake_case : protected[re.escape(m.group(0 ) )], __snake_case )
_UpperCamelCase = v
for k_pre, tensors in capture_qkv_weight.items():
if None in tensors:
raise Exception('''CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing''' )
_UpperCamelCase = textenc_pattern.sub(lambda __snake_case : protected[re.escape(m.group(0 ) )], __snake_case )
_UpperCamelCase = torch.cat(__snake_case )
for k_pre, tensors in capture_qkv_bias.items():
if None in tensors:
raise Exception('''CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing''' )
_UpperCamelCase = textenc_pattern.sub(lambda __snake_case : protected[re.escape(m.group(0 ) )], __snake_case )
_UpperCamelCase = torch.cat(__snake_case )
return new_state_dict
def lowerCamelCase__ ( __snake_case ) -> Tuple:
"""simple docstring"""
return text_enc_dict
if __name__ == "__main__":
_a = argparse.ArgumentParser()
parser.add_argument("""--model_path""", default=None, type=str, required=True, help="""Path to the model to convert.""")
parser.add_argument("""--checkpoint_path""", default=None, type=str, required=True, help="""Path to the output model.""")
parser.add_argument("""--half""", action="""store_true""", help="""Save weights in half precision.""")
parser.add_argument(
"""--use_safetensors""", action="""store_true""", help="""Save weights use safetensors, default is ckpt."""
)
_a = parser.parse_args()
assert args.model_path is not None, "Must provide a model path!"
assert args.checkpoint_path is not None, "Must provide a checkpoint path!"
# Path for safetensors
_a = osp.join(args.model_path, """unet""", """diffusion_pytorch_model.safetensors""")
_a = osp.join(args.model_path, """vae""", """diffusion_pytorch_model.safetensors""")
_a = osp.join(args.model_path, """text_encoder""", """model.safetensors""")
# Load models from safetensors if it exists, if it doesn't pytorch
if osp.exists(unet_path):
_a = load_file(unet_path, device="""cpu""")
else:
_a = osp.join(args.model_path, """unet""", """diffusion_pytorch_model.bin""")
_a = torch.load(unet_path, map_location="""cpu""")
if osp.exists(vae_path):
_a = load_file(vae_path, device="""cpu""")
else:
_a = osp.join(args.model_path, """vae""", """diffusion_pytorch_model.bin""")
_a = torch.load(vae_path, map_location="""cpu""")
if osp.exists(text_enc_path):
_a = load_file(text_enc_path, device="""cpu""")
else:
_a = osp.join(args.model_path, """text_encoder""", """pytorch_model.bin""")
_a = torch.load(text_enc_path, map_location="""cpu""")
# Convert the UNet model
_a = convert_unet_state_dict(unet_state_dict)
_a = {"""model.diffusion_model.""" + k: v for k, v in unet_state_dict.items()}
# Convert the VAE model
_a = convert_vae_state_dict(vae_state_dict)
_a = {"""first_stage_model.""" + k: v for k, v in vae_state_dict.items()}
# Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper
_a = """text_model.encoder.layers.22.layer_norm2.bias""" in text_enc_dict
if is_vaa_model:
# Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm
_a = {"""transformer.""" + k: v for k, v in text_enc_dict.items()}
_a = convert_text_enc_state_dict_vaa(text_enc_dict)
_a = {"""cond_stage_model.model.""" + k: v for k, v in text_enc_dict.items()}
else:
_a = convert_text_enc_state_dict(text_enc_dict)
_a = {"""cond_stage_model.transformer.""" + k: v for k, v in text_enc_dict.items()}
# Put together new checkpoint
_a = {**unet_state_dict, **vae_state_dict, **text_enc_dict}
if args.half:
_a = {k: v.half() for k, v in state_dict.items()}
if args.use_safetensors:
save_file(state_dict, args.checkpoint_path)
else:
_a = {"""state_dict""": state_dict}
torch.save(state_dict, args.checkpoint_path)
| 78 | 0 |
"""simple docstring"""
from __future__ import annotations
def lowerCamelCase__ ( __snake_case ) -> List[Any]:
"""simple docstring"""
_UpperCamelCase = str(__lowercase )
return len(__lowercase ) == 9 and set(__lowercase ) == set('''123456789''' )
def lowerCamelCase__ ( ) -> Any:
"""simple docstring"""
for base_num in range(99_99, 49_99, -1 ):
_UpperCamelCase = 10_00_02 * base_num
if is_9_pandigital(__lowercase ):
return candidate
for base_num in range(3_33, 99, -1 ):
_UpperCamelCase = 1_00_20_03 * base_num
if is_9_pandigital(__lowercase ):
return candidate
return None
if __name__ == "__main__":
print(F"""{solution() = }""")
| 704 |
"""simple docstring"""
import argparse
import torch
from transformers import OpenAIGPTConfig, OpenAIGPTModel, load_tf_weights_in_openai_gpt
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging
logging.set_verbosity_info()
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> Union[str, Any]:
"""simple docstring"""
if openai_config_file == "":
_UpperCamelCase = OpenAIGPTConfig()
else:
_UpperCamelCase = OpenAIGPTConfig.from_json_file(__snake_case )
_UpperCamelCase = OpenAIGPTModel(__snake_case )
# Load weights from numpy
load_tf_weights_in_openai_gpt(__snake_case, __snake_case, __snake_case )
# Save pytorch-model
_UpperCamelCase = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME
_UpperCamelCase = pytorch_dump_folder_path + '''/''' + CONFIG_NAME
print(F'''Save PyTorch model to {pytorch_weights_dump_path}''' )
torch.save(model.state_dict(), __snake_case )
print(F'''Save configuration file to {pytorch_config_dump_path}''' )
with open(__snake_case, '''w''', encoding='''utf-8''' ) as f:
f.write(config.to_json_string() )
if __name__ == "__main__":
_a = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--openai_checkpoint_folder_path""",
default=None,
type=str,
required=True,
help="""Path to the TensorFlow checkpoint path.""",
)
parser.add_argument(
"""--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
)
parser.add_argument(
"""--openai_config_file""",
default="""""",
type=str,
help=(
"""An optional config json file corresponding to the pre-trained OpenAI model. \n"""
"""This specifies the model architecture."""
),
)
_a = parser.parse_args()
convert_openai_checkpoint_to_pytorch(
args.openai_checkpoint_folder_path, args.openai_config_file, args.pytorch_dump_folder_path
)
| 78 | 0 |
"""simple docstring"""
import json
import os
import re
import unicodedata
from json.encoder import INFINITY
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import regex
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, is_flax_available, is_tf_available, is_torch_available, logging
from ...utils.generic import _is_jax, _is_numpy
_a = logging.get_logger(__name__)
_a = {
"""artists_file""": """artists.json""",
"""lyrics_file""": """lyrics.json""",
"""genres_file""": """genres.json""",
}
_a = {
"""artists_file""": {
"""jukebox""": """https://huggingface.co/ArthurZ/jukebox/blob/main/artists.json""",
},
"""genres_file""": {
"""jukebox""": """https://huggingface.co/ArthurZ/jukebox/blob/main/genres.json""",
},
"""lyrics_file""": {
"""jukebox""": """https://huggingface.co/ArthurZ/jukebox/blob/main/lyrics.json""",
},
}
_a = {
"""jukebox""": 512,
}
class _UpperCAmelCase( __lowercase ):
lowercase__ = VOCAB_FILES_NAMES
lowercase__ = PRETRAINED_VOCAB_FILES_MAP
lowercase__ = PRETRAINED_LYRIC_TOKENS_SIZES
lowercase__ = ['input_ids', 'attention_mask']
def __init__( self , __a , __a , __a , __a=["v3", "v2", "v2"] , __a=5_12 , __a=5 , __a="<|endoftext|>" , **__a , ) -> Tuple:
'''simple docstring'''
_UpperCamelCase = AddedToken(_A , lstrip=_A , rstrip=_A) if isinstance(_A , _A) else unk_token
super().__init__(
unk_token=_A , n_genres=_A , version=_A , max_n_lyric_tokens=_A , **_A , )
_UpperCamelCase = version
_UpperCamelCase = max_n_lyric_tokens
_UpperCamelCase = n_genres
with open(_A , encoding='''utf-8''') as vocab_handle:
_UpperCamelCase = json.load(_A)
with open(_A , encoding='''utf-8''') as vocab_handle:
_UpperCamelCase = json.load(_A)
with open(_A , encoding='''utf-8''') as vocab_handle:
_UpperCamelCase = json.load(_A)
_UpperCamelCase = R'''[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+'''
# In v2, we had a n_vocab=80 and in v3 we missed + and so n_vocab=79 of characters.
if len(self.lyrics_encoder) == 79:
_UpperCamelCase = oov.replace(R'''\-\'''' , R'''\-+\'''')
_UpperCamelCase = regex.compile(_A)
_UpperCamelCase = {v: k for k, v in self.artists_encoder.items()}
_UpperCamelCase = {v: k for k, v in self.genres_encoder.items()}
_UpperCamelCase = {v: k for k, v in self.lyrics_encoder.items()}
@property
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
return len(self.artists_encoder) + len(self.genres_encoder) + len(self.lyrics_encoder)
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
return dict(self.artists_encoder , self.genres_encoder , self.lyrics_encoder)
def UpperCAmelCase ( self , __a , __a , __a) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = [self.artists_encoder.get(_A , 0) for artist in list_artists]
for genres in range(len(_A)):
_UpperCamelCase = [self.genres_encoder.get(_A , 0) for genre in list_genres[genres]]
_UpperCamelCase = list_genres[genres] + [-1] * (self.n_genres - len(list_genres[genres]))
_UpperCamelCase = [[self.lyrics_encoder.get(_A , 0) for character in list_lyrics[0]], [], []]
return artists_id, list_genres, lyric_ids
def UpperCAmelCase ( self , __a) -> Any:
'''simple docstring'''
return list(_A)
def UpperCAmelCase ( self , __a , __a , __a , **__a) -> str:
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = self.prepare_for_tokenization(_A , _A , _A)
_UpperCamelCase = self._tokenize(_A)
return artist, genre, lyrics
def UpperCAmelCase ( self , __a , __a , __a , __a = False) -> List[str]:
'''simple docstring'''
for idx in range(len(self.version)):
if self.version[idx] == "v3":
_UpperCamelCase = artists[idx].lower()
_UpperCamelCase = [genres[idx].lower()]
else:
_UpperCamelCase = self._normalize(artists[idx]) + '''.v2'''
_UpperCamelCase = [
self._normalize(_A) + '''.v2''' for genre in genres[idx].split('''_''')
] # split is for the full dictionary with combined genres
if self.version[0] == "v2":
_UpperCamelCase = regex.compile(R'''[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+''')
_UpperCamelCase = '''ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-+\'\"()[] \t\n'''
_UpperCamelCase = {vocab[index]: index + 1 for index in range(len(_A))}
_UpperCamelCase = 0
_UpperCamelCase = len(_A) + 1
_UpperCamelCase = self.vocab
_UpperCamelCase = {v: k for k, v in self.vocab.items()}
_UpperCamelCase = ''''''
else:
_UpperCamelCase = regex.compile(R'''[^A-Za-z0-9.,:;!?\-+\'\"()\[\] \t\n]+''')
_UpperCamelCase = self._run_strip_accents(_A)
_UpperCamelCase = lyrics.replace('''\\''' , '''\n''')
_UpperCamelCase = self.out_of_vocab.sub('''''' , _A), [], []
return artists, genres, lyrics
def UpperCAmelCase ( self , __a) -> int:
'''simple docstring'''
_UpperCamelCase = unicodedata.normalize('''NFD''' , _A)
_UpperCamelCase = []
for char in text:
_UpperCamelCase = unicodedata.category(_A)
if cat == "Mn":
continue
output.append(_A)
return "".join(_A)
def UpperCAmelCase ( self , __a) -> int:
'''simple docstring'''
_UpperCamelCase = (
[chr(_A) for i in range(ord('''a''') , ord('''z''') + 1)]
+ [chr(_A) for i in range(ord('''A''') , ord('''Z''') + 1)]
+ [chr(_A) for i in range(ord('''0''') , ord('''9''') + 1)]
+ ['''.''']
)
_UpperCamelCase = frozenset(_A)
_UpperCamelCase = re.compile(R'''_+''')
_UpperCamelCase = ''''''.join([c if c in accepted else '''_''' for c in text.lower()])
_UpperCamelCase = pattern.sub('''_''' , _A).strip('''_''')
return text
def UpperCAmelCase ( self , __a) -> Union[str, Any]:
'''simple docstring'''
return " ".join(_A)
def UpperCAmelCase ( self , __a , __a = None , __a = False) -> Union[str, Any]:
'''simple docstring'''
# Convert to TensorType
if not isinstance(_A , _A):
_UpperCamelCase = TensorType(_A)
# Get a function reference for the correct framework
if tensor_type == TensorType.TENSORFLOW:
if not is_tf_available():
raise ImportError(
'''Unable to convert output to TensorFlow tensors format, TensorFlow is not installed.''')
import tensorflow as tf
_UpperCamelCase = tf.constant
_UpperCamelCase = tf.is_tensor
elif tensor_type == TensorType.PYTORCH:
if not is_torch_available():
raise ImportError('''Unable to convert output to PyTorch tensors format, PyTorch is not installed.''')
import torch
_UpperCamelCase = torch.tensor
_UpperCamelCase = torch.is_tensor
elif tensor_type == TensorType.JAX:
if not is_flax_available():
raise ImportError('''Unable to convert output to JAX tensors format, JAX is not installed.''')
import jax.numpy as jnp # noqa: F811
_UpperCamelCase = jnp.array
_UpperCamelCase = _is_jax
else:
_UpperCamelCase = np.asarray
_UpperCamelCase = _is_numpy
# Do the tensor conversion in batch
try:
if prepend_batch_axis:
_UpperCamelCase = [inputs]
if not is_tensor(_A):
_UpperCamelCase = as_tensor(_A)
except: # noqa E722
raise ValueError(
'''Unable to create tensor, you should probably activate truncation and/or padding '''
'''with \'padding=True\' \'truncation=True\' to have batched tensors with the same length.''')
return inputs
def __call__( self , __a , __a , __a="" , __a="pt") -> Tuple:
'''simple docstring'''
_UpperCamelCase = [0, 0, 0]
_UpperCamelCase = [artist] * len(self.version)
_UpperCamelCase = [genres] * len(self.version)
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = self.tokenize(_A , _A , _A)
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = self._convert_token_to_id(_A , _A , _A)
_UpperCamelCase = [-INFINITY] * len(full_tokens[-1])
_UpperCamelCase = [
self.convert_to_tensors(
[input_ids + [artists_id[i]] + genres_ids[i] + full_tokens[i]] , tensor_type=_A)
for i in range(len(self.version))
]
return BatchEncoding({'''input_ids''': input_ids, '''attention_masks''': attention_masks})
def UpperCAmelCase ( self , __a , __a = None) -> Dict:
'''simple docstring'''
if not os.path.isdir(_A):
logger.error(F'''Vocabulary path ({save_directory}) should be a directory''')
return
_UpperCamelCase = os.path.join(
_A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''artists_file'''])
with open(_A , '''w''' , encoding='''utf-8''') as f:
f.write(json.dumps(self.artists_encoder , ensure_ascii=_A))
_UpperCamelCase = os.path.join(
_A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''genres_file'''])
with open(_A , '''w''' , encoding='''utf-8''') as f:
f.write(json.dumps(self.genres_encoder , ensure_ascii=_A))
_UpperCamelCase = os.path.join(
_A , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''lyrics_file'''])
with open(_A , '''w''' , encoding='''utf-8''') as f:
f.write(json.dumps(self.lyrics_encoder , ensure_ascii=_A))
return (artists_file, genres_file, lyrics_file)
def UpperCAmelCase ( self , __a , __a , __a) -> Tuple:
'''simple docstring'''
_UpperCamelCase = self.artists_decoder.get(_A)
_UpperCamelCase = [self.genres_decoder.get(_A) for genre in genres_index]
_UpperCamelCase = [self.lyrics_decoder.get(_A) for character in lyric_index]
return artist, genres, lyrics
| 705 |
"""simple docstring"""
from __future__ import annotations
import unittest
from transformers import AutoTokenizer, MBartConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel
@require_tf
class _UpperCAmelCase:
lowercase__ = MBartConfig
lowercase__ = {}
lowercase__ = 'gelu'
def __init__( self , __a , __a=13 , __a=7 , __a=True , __a=False , __a=99 , __a=32 , __a=2 , __a=4 , __a=37 , __a=0.1 , __a=0.1 , __a=20 , __a=2 , __a=1 , __a=0 , ) -> Any:
'''simple docstring'''
_UpperCamelCase = parent
_UpperCamelCase = batch_size
_UpperCamelCase = seq_length
_UpperCamelCase = is_training
_UpperCamelCase = use_labels
_UpperCamelCase = vocab_size
_UpperCamelCase = hidden_size
_UpperCamelCase = num_hidden_layers
_UpperCamelCase = num_attention_heads
_UpperCamelCase = intermediate_size
_UpperCamelCase = hidden_dropout_prob
_UpperCamelCase = attention_probs_dropout_prob
_UpperCamelCase = max_position_embeddings
_UpperCamelCase = eos_token_id
_UpperCamelCase = pad_token_id
_UpperCamelCase = bos_token_id
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size)
_UpperCamelCase = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size) , 1)
_UpperCamelCase = tf.concat([input_ids, eos_tensor] , axis=1)
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size)
_UpperCamelCase = self.config_cls(
vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , )
_UpperCamelCase = prepare_mbart_inputs_dict(__a , __a , __a)
return config, inputs_dict
def UpperCAmelCase ( self , __a , __a) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = TFMBartModel(config=__a).get_decoder()
_UpperCamelCase = inputs_dict['''input_ids''']
_UpperCamelCase = input_ids[:1, :]
_UpperCamelCase = inputs_dict['''attention_mask'''][:1, :]
_UpperCamelCase = inputs_dict['''head_mask''']
_UpperCamelCase = 1
# first forward pass
_UpperCamelCase = model(__a , attention_mask=__a , head_mask=__a , use_cache=__a)
_UpperCamelCase , _UpperCamelCase = outputs.to_tuple()
_UpperCamelCase = past_key_values[1]
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case, __snake_case=None, __snake_case=None, __snake_case=None, __snake_case=None, __snake_case=None, ) -> Optional[int]:
"""simple docstring"""
if attention_mask is None:
_UpperCamelCase = tf.cast(tf.math.not_equal(__snake_case, config.pad_token_id ), tf.inta )
if decoder_attention_mask is None:
_UpperCamelCase = tf.concat(
[
tf.ones(decoder_input_ids[:, :1].shape, dtype=tf.inta ),
tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:], config.pad_token_id ), tf.inta ),
], axis=-1, )
if head_mask is None:
_UpperCamelCase = tf.ones((config.encoder_layers, config.encoder_attention_heads) )
if decoder_head_mask is None:
_UpperCamelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
if cross_attn_head_mask is None:
_UpperCamelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
return {
"input_ids": input_ids,
"decoder_input_ids": decoder_input_ids,
"attention_mask": attention_mask,
"decoder_attention_mask": decoder_attention_mask,
"head_mask": head_mask,
"decoder_head_mask": decoder_head_mask,
"cross_attn_head_mask": cross_attn_head_mask,
}
@require_tf
class _UpperCAmelCase( lowerCamelCase , lowerCamelCase , unittest.TestCase ):
lowercase__ = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else ()
lowercase__ = (TFMBartForConditionalGeneration,) if is_tf_available() else ()
lowercase__ = (
{
'conversational': TFMBartForConditionalGeneration,
'feature-extraction': TFMBartModel,
'summarization': TFMBartForConditionalGeneration,
'text2text-generation': TFMBartForConditionalGeneration,
'translation': TFMBartForConditionalGeneration,
}
if is_tf_available()
else {}
)
lowercase__ = True
lowercase__ = False
lowercase__ = False
def UpperCAmelCase ( self , __a , __a , __a , __a , __a) -> Dict:
'''simple docstring'''
if pipeline_test_casse_name != "FeatureExtractionPipelineTests":
# Exception encountered when calling layer '...'
return True
return False
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase = TFMBartModelTester(self)
_UpperCamelCase = ConfigTester(self , config_class=__a)
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
self.config_tester.run_common_tests()
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_decoder_model_past_large_inputs(*__a)
@require_sentencepiece
@require_tokenizers
@require_tf
class _UpperCAmelCase( unittest.TestCase ):
lowercase__ = [
' UN Chief Says There Is No Military Solution in Syria',
]
lowercase__ = [
'Şeful ONU declară că nu există o soluţie militară în Siria',
]
lowercase__ = 'facebook/mbart-large-en-ro'
@cached_property
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
return AutoTokenizer.from_pretrained(self.model_name)
@cached_property
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
_UpperCamelCase = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name)
return model
def UpperCAmelCase ( self , **__a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.translate_src_text(**__a)
self.assertListEqual(self.expected_text , __a)
def UpperCAmelCase ( self , **__a) -> Dict:
'''simple docstring'''
_UpperCamelCase = self.tokenizer(self.src_text , **__a , return_tensors='''tf''')
_UpperCamelCase = self.model.generate(
model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2)
_UpperCamelCase = self.tokenizer.batch_decode(__a , skip_special_tokens=__a)
return generated_words
@slow
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
self._assert_generated_batch_equal_expected()
| 78 | 0 |
"""simple docstring"""
from __future__ import annotations
from collections import deque
from collections.abc import Iterator
from dataclasses import dataclass
@dataclass
class _UpperCAmelCase:
lowercase__ = 42
lowercase__ = 42
class _UpperCAmelCase:
def __init__( self , __a) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = [[] for _ in range(snake_case__)]
_UpperCamelCase = size
def __getitem__( self , __a) -> Tuple:
'''simple docstring'''
return iter(self._graph[vertex])
@property
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
return self._size
def UpperCAmelCase ( self , __a , __a , __a) -> Any:
'''simple docstring'''
if weight not in (0, 1):
raise ValueError('''Edge weight must be either 0 or 1.''')
if to_vertex < 0 or to_vertex >= self.size:
raise ValueError('''Vertex indexes must be in [0; size).''')
self._graph[from_vertex].append(Edge(snake_case__ , snake_case__))
def UpperCAmelCase ( self , __a , __a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = deque([start_vertex])
_UpperCamelCase = [None] * self.size
_UpperCamelCase = 0
while queue:
_UpperCamelCase = queue.popleft()
_UpperCamelCase = distances[current_vertex]
if current_distance is None:
continue
for edge in self[current_vertex]:
_UpperCamelCase = current_distance + edge.weight
_UpperCamelCase = distances[edge.destination_vertex]
if (
isinstance(snake_case__ , snake_case__)
and new_distance >= dest_vertex_distance
):
continue
_UpperCamelCase = new_distance
if edge.weight == 0:
queue.appendleft(edge.destination_vertex)
else:
queue.append(edge.destination_vertex)
if distances[finish_vertex] is None:
raise ValueError('''No path from start_vertex to finish_vertex.''')
return distances[finish_vertex]
if __name__ == "__main__":
import doctest
doctest.testmod()
| 706 |
"""simple docstring"""
from typing import Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format
from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images
from ...utils import TensorType, logging
_a = logging.get_logger(__name__)
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = ['pixel_values']
def __init__( self , __a = True , __a = 1 / 2_55 , __a = True , __a = 8 , **__a , ) -> None:
'''simple docstring'''
super().__init__(**__a)
_UpperCamelCase = do_rescale
_UpperCamelCase = rescale_factor
_UpperCamelCase = do_pad
_UpperCamelCase = pad_size
def UpperCAmelCase ( self , __a , __a , __a = None , **__a) -> np.ndarray:
'''simple docstring'''
return rescale(__a , scale=__a , data_format=__a , **__a)
def UpperCAmelCase ( self , __a , __a , __a = None) -> List[Any]:
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase = get_image_size(__a)
_UpperCamelCase = (old_height // size + 1) * size - old_height
_UpperCamelCase = (old_width // size + 1) * size - old_width
return pad(__a , ((0, pad_height), (0, pad_width)) , mode='''symmetric''' , data_format=__a)
def UpperCAmelCase ( self , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = ChannelDimension.FIRST , **__a , ) -> Tuple:
'''simple docstring'''
_UpperCamelCase = do_rescale if do_rescale is not None else self.do_rescale
_UpperCamelCase = rescale_factor if rescale_factor is not None else self.rescale_factor
_UpperCamelCase = do_pad if do_pad is not None else self.do_pad
_UpperCamelCase = pad_size if pad_size is not None else self.pad_size
_UpperCamelCase = make_list_of_images(__a)
if not valid_images(__a):
raise ValueError(
'''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
'''torch.Tensor, tf.Tensor or jax.ndarray.''')
if do_rescale and rescale_factor is None:
raise ValueError('''Rescale factor must be specified if do_rescale is True.''')
# All transformations expect numpy arrays.
_UpperCamelCase = [to_numpy_array(__a) for image in images]
if do_rescale:
_UpperCamelCase = [self.rescale(image=__a , scale=__a) for image in images]
if do_pad:
_UpperCamelCase = [self.pad(__a , size=__a) for image in images]
_UpperCamelCase = [to_channel_dimension_format(__a , __a) for image in images]
_UpperCamelCase = {'''pixel_values''': images}
return BatchFeature(data=__a , tensor_type=__a)
| 78 | 0 |
"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_a = logging.get_logger(__name__)
_a = {
"""SCUT-DLVCLab/lilt-roberta-en-base""": (
"""https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json"""
),
}
class _UpperCAmelCase( __lowerCamelCase ):
lowercase__ = '''lilt'''
def __init__( self , __a=3_05_22 , __a=7_68 , __a=12 , __a=12 , __a=30_72 , __a="gelu" , __a=0.1 , __a=0.1 , __a=5_12 , __a=2 , __a=0.02 , __a=1e-12 , __a=0 , __a="absolute" , __a=None , __a=4 , __a=10_24 , **__a , ) -> List[str]:
'''simple docstring'''
super().__init__(pad_token_id=a_ , **a_)
_UpperCamelCase = vocab_size
_UpperCamelCase = hidden_size
_UpperCamelCase = num_hidden_layers
_UpperCamelCase = num_attention_heads
_UpperCamelCase = hidden_act
_UpperCamelCase = intermediate_size
_UpperCamelCase = hidden_dropout_prob
_UpperCamelCase = attention_probs_dropout_prob
_UpperCamelCase = max_position_embeddings
_UpperCamelCase = type_vocab_size
_UpperCamelCase = initializer_range
_UpperCamelCase = layer_norm_eps
_UpperCamelCase = position_embedding_type
_UpperCamelCase = classifier_dropout
_UpperCamelCase = channel_shrink_ratio
_UpperCamelCase = max_ad_position_embeddings | 707 |
"""simple docstring"""
from importlib import import_module
from .logging import get_logger
_a = get_logger(__name__)
class _UpperCAmelCase:
def __init__( self , __a , __a=None) -> Dict:
'''simple docstring'''
_UpperCamelCase = attrs or []
if module is not None:
for key in module.__dict__:
if key in attrs or not key.startswith('''__'''):
setattr(self , __a , getattr(__a , __a))
_UpperCamelCase = module._original_module if isinstance(__a , _PatchedModuleObj) else module
class _UpperCAmelCase:
lowercase__ = []
def __init__( self , __a , __a , __a , __a=None) -> List[str]:
'''simple docstring'''
_UpperCamelCase = obj
_UpperCamelCase = target
_UpperCamelCase = new
_UpperCamelCase = target.split('''.''')[0]
_UpperCamelCase = {}
_UpperCamelCase = attrs or []
def __enter__( self) -> int:
'''simple docstring'''
*_UpperCamelCase , _UpperCamelCase = self.target.split('''.''')
# Patch modules:
# it's used to patch attributes of submodules like "os.path.join";
# in this case we need to patch "os" and "os.path"
for i in range(len(__a)):
try:
_UpperCamelCase = import_module('''.'''.join(submodules[: i + 1]))
except ModuleNotFoundError:
continue
# We iterate over all the globals in self.obj in case we find "os" or "os.path"
for attr in self.obj.__dir__():
_UpperCamelCase = getattr(self.obj , __a)
# We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
# This allows to patch renamed modules like "from os import path as ospath".
if obj_attr is submodule or (
(isinstance(__a , _PatchedModuleObj) and obj_attr._original_module is submodule)
):
_UpperCamelCase = obj_attr
# patch at top level
setattr(self.obj , __a , _PatchedModuleObj(__a , attrs=self.attrs))
_UpperCamelCase = getattr(self.obj , __a)
# construct lower levels patches
for key in submodules[i + 1 :]:
setattr(__a , __a , _PatchedModuleObj(getattr(__a , __a , __a) , attrs=self.attrs))
_UpperCamelCase = getattr(__a , __a)
# finally set the target attribute
setattr(__a , __a , self.new)
# Patch attribute itself:
# it's used for builtins like "open",
# and also to patch "os.path.join" we may also need to patch "join"
# itself if it was imported as "from os.path import join".
if submodules: # if it's an attribute of a submodule like "os.path.join"
try:
_UpperCamelCase = getattr(import_module('''.'''.join(__a)) , __a)
except (AttributeError, ModuleNotFoundError):
return
# We iterate over all the globals in self.obj in case we find "os.path.join"
for attr in self.obj.__dir__():
# We don't check for the name of the global, but rather if its value *is* "os.path.join".
# This allows to patch renamed attributes like "from os.path import join as pjoin".
if getattr(self.obj , __a) is attr_value:
_UpperCamelCase = getattr(self.obj , __a)
setattr(self.obj , __a , self.new)
elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open"
_UpperCamelCase = globals()['''__builtins__'''][target_attr]
setattr(self.obj , __a , self.new)
else:
raise RuntimeError(F'''Tried to patch attribute {target_attr} instead of a submodule.''')
def __exit__( self , *__a) -> Tuple:
'''simple docstring'''
for attr in list(self.original):
setattr(self.obj , __a , self.original.pop(__a))
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
self.__enter__()
self._active_patches.append(self)
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
try:
self._active_patches.remove(self)
except ValueError:
# If the patch hasn't been started this will fail
return None
return self.__exit__()
| 78 | 0 |
"""simple docstring"""
import copy
import fnmatch
import json
import os
import pickle as pkl
import shutil
import sys
import tarfile
import tempfile
from collections import OrderedDict
from contextlib import contextmanager
from functools import partial
from hashlib import shaaaa
from io import BytesIO
from pathlib import Path
from urllib.parse import urlparse
from zipfile import ZipFile, is_zipfile
import cva
import numpy as np
import requests
import wget
from filelock import FileLock
from PIL import Image
from tqdm.auto import tqdm
from yaml import Loader, dump, load
try:
import torch
_a : List[Any] = True
except ImportError:
_a : List[str] = False
try:
from torch.hub import _get_torch_home
_a : Optional[Any] = _get_torch_home()
except ImportError:
_a : Dict = os.path.expanduser(
os.getenv("""TORCH_HOME""", os.path.join(os.getenv("""XDG_CACHE_HOME""", """~/.cache"""), """torch"""))
)
_a : int = os.path.join(torch_cache_home, """transformers""")
_a : Optional[int] = """https://cdn.huggingface.co"""
_a : Any = """https://s3.amazonaws.com/models.huggingface.co/bert"""
_a : List[Any] = """/""".join(str(Path(__file__).resolve()).split("""/""")[:-1])
_a : Optional[Any] = os.path.join(PATH, """config.yaml""")
_a : List[Any] = os.path.join(PATH, """attributes.txt""")
_a : Dict = os.path.join(PATH, """objects.txt""")
_a : Optional[int] = os.getenv("""PYTORCH_PRETRAINED_BERT_CACHE""", default_cache_path)
_a : Tuple = os.getenv("""PYTORCH_TRANSFORMERS_CACHE""", PYTORCH_PRETRAINED_BERT_CACHE)
_a : Union[str, Any] = os.getenv("""TRANSFORMERS_CACHE""", PYTORCH_TRANSFORMERS_CACHE)
_a : Union[str, Any] = """pytorch_model.bin"""
_a : str = """config.yaml"""
def lowerCamelCase__ ( __snake_case=OBJECTS, __snake_case=ATTRIBUTES ) -> Union[str, Any]:
"""simple docstring"""
_UpperCamelCase = []
with open(_snake_case ) as f:
for object in f.readlines():
vg_classes.append(object.split(''',''' )[0].lower().strip() )
_UpperCamelCase = []
with open(_snake_case ) as f:
for object in f.readlines():
vg_attrs.append(object.split(''',''' )[0].lower().strip() )
return vg_classes, vg_attrs
def lowerCamelCase__ ( __snake_case ) -> List[Any]:
"""simple docstring"""
_UpperCamelCase = OrderedDict()
with open(_snake_case, '''rb''' ) as f:
_UpperCamelCase = pkl.load(_snake_case )['''model''']
for k in copy.deepcopy(list(ckp.keys() ) ):
_UpperCamelCase = ckp.pop(_snake_case )
if isinstance(_snake_case, np.ndarray ):
_UpperCamelCase = torch.tensor(_snake_case )
else:
assert isinstance(_snake_case, torch.tensor ), type(_snake_case )
_UpperCamelCase = v
return r
class _UpperCAmelCase:
lowercase__ = {}
def __init__( self , __a , __a = "root" , __a=0) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = name
_UpperCamelCase = level
_UpperCamelCase = {}
for k, v in dictionary.items():
if v is None:
raise ValueError()
_UpperCamelCase = copy.deepcopy(__a)
_UpperCamelCase = copy.deepcopy(__a)
if isinstance(__a , __a):
_UpperCamelCase = Config(__a , name=__a , level=level + 1)
_UpperCamelCase = v
setattr(self , __a , __a)
_UpperCamelCase = d
def __repr__( self) -> str:
'''simple docstring'''
return str(list((self._pointer.keys())))
def __setattr__( self , __a , __a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = val
_UpperCamelCase = val
_UpperCamelCase = key.split('''.''')
_UpperCamelCase = len(__a) - 1
_UpperCamelCase = self._pointer
if len(__a) > 1:
for i, l in enumerate(__a):
if hasattr(self , __a) and isinstance(getattr(self , __a) , __a):
setattr(getattr(self , __a) , '''.'''.join(levels[i:]) , __a)
if l == last_level:
_UpperCamelCase = val
else:
_UpperCamelCase = pointer[l]
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
return self._pointer
def UpperCAmelCase ( self , __a , __a) -> Any:
'''simple docstring'''
with open(F'''{file_name}''' , '''w''') as stream:
dump(__a , __a)
def UpperCAmelCase ( self , __a , __a) -> int:
'''simple docstring'''
with open(F'''{file_name}''' , '''w''') as stream:
json.dump(__a , __a)
@staticmethod
def UpperCAmelCase ( __a) -> Any:
'''simple docstring'''
with open(__a) as stream:
_UpperCamelCase = load(__a , Loader=__a)
return data
def __str__( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = ''' '''
if self._name != "root":
_UpperCamelCase = F'''{t * (self._level-1)}{self._name}:\n'''
else:
_UpperCamelCase = ''''''
_UpperCamelCase = self._level
for i, (k, v) in enumerate(self._pointer.items()):
if isinstance(__a , __a):
r += F'''{t * (self._level)}{v}\n'''
self._level += 1
else:
r += F'''{t * (self._level)}{k}: {v} ({type(__a).__name__})\n'''
_UpperCamelCase = level
return r[:-1]
@classmethod
def UpperCAmelCase ( cls , __a , **__a) -> int:
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase = cls.get_config_dict(__a , **__a)
return cls(__a)
@classmethod
def UpperCAmelCase ( cls , __a , **__a) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = kwargs.pop('''cache_dir''' , __a)
_UpperCamelCase = kwargs.pop('''force_download''' , __a)
_UpperCamelCase = kwargs.pop('''resume_download''' , __a)
_UpperCamelCase = kwargs.pop('''proxies''' , __a)
_UpperCamelCase = kwargs.pop('''local_files_only''' , __a)
if os.path.isdir(__a):
_UpperCamelCase = os.path.join(__a , __a)
elif os.path.isfile(__a) or is_remote_url(__a):
_UpperCamelCase = pretrained_model_name_or_path
else:
_UpperCamelCase = hf_bucket_url(__a , filename=__a , use_cdn=__a)
try:
# Load from URL or cache if already cached
_UpperCamelCase = cached_path(
__a , cache_dir=__a , force_download=__a , proxies=__a , resume_download=__a , local_files_only=__a , )
# Load config dict
if resolved_config_file is None:
raise EnvironmentError
_UpperCamelCase = Config.load_yaml(__a)
except EnvironmentError:
_UpperCamelCase = '''Can\'t load config for'''
raise EnvironmentError(__a)
if resolved_config_file == config_file:
print('''loading configuration file from path''')
else:
print('''loading configuration file cache''')
return Config.load_yaml(__a), kwargs
def lowerCamelCase__ ( __snake_case ) -> Optional[Any]:
"""simple docstring"""
_UpperCamelCase = torch.load('''dump.pt''', map_location=in_tensor.device )
_UpperCamelCase = in_tensor.numpy()
_UpperCamelCase = out_tensor.numpy()[0]
print(na.shape, na[0, 0, :5] )
print(na.shape, na[0, 0, :5] )
assert np.allclose(_snake_case, _snake_case, rtol=0.01, atol=0.1 ), (
F'''{sum([1 for x in np.isclose(_snake_case, _snake_case, rtol=0.01, atol=0.1 ).flatten() if x is False] )/len(na.flatten() )*1_00:.4f} %'''
" element-wise mismatch"
)
raise Exception('''tensors are all good''' )
# Hugging face functions below
def lowerCamelCase__ ( __snake_case ) -> Optional[int]:
"""simple docstring"""
_UpperCamelCase = urlparse(_snake_case )
return parsed.scheme in ("http", "https")
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case=True ) -> str:
"""simple docstring"""
_UpperCamelCase = CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX
_UpperCamelCase = '''/''' not in model_id
if legacy_format:
return F'''{endpoint}/{model_id}-{filename}'''
else:
return F'''{endpoint}/{model_id}/{filename}'''
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case=None, __snake_case=0, __snake_case=None, ) -> str:
"""simple docstring"""
_UpperCamelCase = '''python/{}'''.format(sys.version.split()[0] )
if _torch_available:
ua += "; torch/{}".format(torch.__version__ )
if isinstance(_snake_case, _snake_case ):
ua += "; " + "; ".join('''{}/{}'''.format(_snake_case, _snake_case ) for k, v in user_agent.items() )
elif isinstance(_snake_case, _snake_case ):
ua += "; " + user_agent
_UpperCamelCase = {'''user-agent''': ua}
if resume_size > 0:
_UpperCamelCase = '''bytes=%d-''' % (resume_size,)
_UpperCamelCase = requests.get(_snake_case, stream=_snake_case, proxies=_snake_case, headers=_snake_case )
if response.status_code == 4_16: # Range not satisfiable
return
_UpperCamelCase = response.headers.get('''Content-Length''' )
_UpperCamelCase = resume_size + int(_snake_case ) if content_length is not None else None
_UpperCamelCase = tqdm(
unit='''B''', unit_scale=_snake_case, total=_snake_case, initial=_snake_case, desc='''Downloading''', )
for chunk in response.iter_content(chunk_size=10_24 ):
if chunk: # filter out keep-alive new chunks
progress.update(len(_snake_case ) )
temp_file.write(_snake_case )
progress.close()
def lowerCamelCase__ ( __snake_case, __snake_case=None, __snake_case=False, __snake_case=None, __snake_case=10, __snake_case=False, __snake_case=None, __snake_case=False, ) -> Any:
"""simple docstring"""
if cache_dir is None:
_UpperCamelCase = TRANSFORMERS_CACHE
if isinstance(_snake_case, _snake_case ):
_UpperCamelCase = str(_snake_case )
os.makedirs(_snake_case, exist_ok=_snake_case )
_UpperCamelCase = None
if not local_files_only:
try:
_UpperCamelCase = requests.head(_snake_case, allow_redirects=_snake_case, proxies=_snake_case, timeout=_snake_case )
if response.status_code == 2_00:
_UpperCamelCase = response.headers.get('''ETag''' )
except (EnvironmentError, requests.exceptions.Timeout):
# etag is already None
pass
_UpperCamelCase = url_to_filename(_snake_case, _snake_case )
# get cache path to put the file
_UpperCamelCase = os.path.join(_snake_case, _snake_case )
# etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible.
# try to get the last downloaded one
if etag is None:
if os.path.exists(_snake_case ):
return cache_path
else:
_UpperCamelCase = [
file
for file in fnmatch.filter(os.listdir(_snake_case ), filename + '''.*''' )
if not file.endswith('''.json''' ) and not file.endswith('''.lock''' )
]
if len(_snake_case ) > 0:
return os.path.join(_snake_case, matching_files[-1] )
else:
# If files cannot be found and local_files_only=True,
# the models might've been found if local_files_only=False
# Notify the user about that
if local_files_only:
raise ValueError(
'''Cannot find the requested files in the cached path and outgoing traffic has been'''
''' disabled. To enable model look-ups and downloads online, set \'local_files_only\''''
''' to False.''' )
return None
# From now on, etag is not None.
if os.path.exists(_snake_case ) and not force_download:
return cache_path
# Prevent parallel downloads of the same file with a lock.
_UpperCamelCase = cache_path + '''.lock'''
with FileLock(_snake_case ):
# If the download just completed while the lock was activated.
if os.path.exists(_snake_case ) and not force_download:
# Even if returning early like here, the lock will be released.
return cache_path
if resume_download:
_UpperCamelCase = cache_path + '''.incomplete'''
@contextmanager
def _resumable_file_manager():
with open(_snake_case, '''a+b''' ) as f:
yield f
_UpperCamelCase = _resumable_file_manager
if os.path.exists(_snake_case ):
_UpperCamelCase = os.stat(_snake_case ).st_size
else:
_UpperCamelCase = 0
else:
_UpperCamelCase = partial(tempfile.NamedTemporaryFile, dir=_snake_case, delete=_snake_case )
_UpperCamelCase = 0
# Download to temporary file, then copy to cache dir once finished.
# Otherwise you get corrupt cache entries if the download gets interrupted.
with temp_file_manager() as temp_file:
print(
'''%s not found in cache or force_download set to True, downloading to %s''', _snake_case, temp_file.name, )
http_get(
_snake_case, _snake_case, proxies=_snake_case, resume_size=_snake_case, user_agent=_snake_case, )
os.replace(temp_file.name, _snake_case )
_UpperCamelCase = {'''url''': url, '''etag''': etag}
_UpperCamelCase = cache_path + '''.json'''
with open(_snake_case, '''w''' ) as meta_file:
json.dump(_snake_case, _snake_case )
return cache_path
def lowerCamelCase__ ( __snake_case, __snake_case=None ) -> int:
"""simple docstring"""
_UpperCamelCase = url.encode('''utf-8''' )
_UpperCamelCase = shaaaa(_snake_case )
_UpperCamelCase = url_hash.hexdigest()
if etag:
_UpperCamelCase = etag.encode('''utf-8''' )
_UpperCamelCase = shaaaa(_snake_case )
filename += "." + etag_hash.hexdigest()
if url.endswith('''.h5''' ):
filename += ".h5"
return filename
def lowerCamelCase__ ( __snake_case, __snake_case=None, __snake_case=False, __snake_case=None, __snake_case=False, __snake_case=None, __snake_case=False, __snake_case=False, __snake_case=False, ) -> Any:
"""simple docstring"""
if cache_dir is None:
_UpperCamelCase = TRANSFORMERS_CACHE
if isinstance(_snake_case, _snake_case ):
_UpperCamelCase = str(_snake_case )
if isinstance(_snake_case, _snake_case ):
_UpperCamelCase = str(_snake_case )
if is_remote_url(_snake_case ):
# URL, so get it from the cache (downloading if necessary)
_UpperCamelCase = get_from_cache(
_snake_case, cache_dir=_snake_case, force_download=_snake_case, proxies=_snake_case, resume_download=_snake_case, user_agent=_snake_case, local_files_only=_snake_case, )
elif os.path.exists(_snake_case ):
# File, and it exists.
_UpperCamelCase = url_or_filename
elif urlparse(_snake_case ).scheme == "":
# File, but it doesn't exist.
raise EnvironmentError('''file {} not found'''.format(_snake_case ) )
else:
# Something unknown
raise ValueError('''unable to parse {} as a URL or as a local path'''.format(_snake_case ) )
if extract_compressed_file:
if not is_zipfile(_snake_case ) and not tarfile.is_tarfile(_snake_case ):
return output_path
# Path where we extract compressed archives
# We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/"
_UpperCamelCase , _UpperCamelCase = os.path.split(_snake_case )
_UpperCamelCase = output_file.replace('''.''', '''-''' ) + '''-extracted'''
_UpperCamelCase = os.path.join(_snake_case, _snake_case )
if os.path.isdir(_snake_case ) and os.listdir(_snake_case ) and not force_extract:
return output_path_extracted
# Prevent parallel extractions
_UpperCamelCase = output_path + '''.lock'''
with FileLock(_snake_case ):
shutil.rmtree(_snake_case, ignore_errors=_snake_case )
os.makedirs(_snake_case )
if is_zipfile(_snake_case ):
with ZipFile(_snake_case, '''r''' ) as zip_file:
zip_file.extractall(_snake_case )
zip_file.close()
elif tarfile.is_tarfile(_snake_case ):
_UpperCamelCase = tarfile.open(_snake_case )
tar_file.extractall(_snake_case )
tar_file.close()
else:
raise EnvironmentError('''Archive format of {} could not be identified'''.format(_snake_case ) )
return output_path_extracted
return output_path
def lowerCamelCase__ ( __snake_case, __snake_case="," ) -> Dict:
"""simple docstring"""
assert isinstance(_snake_case, _snake_case )
if os.path.isfile(_snake_case ):
with open(_snake_case ) as f:
_UpperCamelCase = eval(f.read() )
else:
_UpperCamelCase = requests.get(_snake_case )
try:
_UpperCamelCase = requests.json()
except Exception:
_UpperCamelCase = req.content.decode()
assert data is not None, "could not connect"
try:
_UpperCamelCase = eval(_snake_case )
except Exception:
_UpperCamelCase = data.split('''\n''' )
req.close()
return data
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = requests.get(_snake_case )
_UpperCamelCase = np.array(Image.open(BytesIO(response.content ) ) )
return img
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = url.split('''/''' )[-1]
if fn not in os.listdir(os.getcwd() ):
wget.download(_snake_case )
with open(_snake_case, '''rb''' ) as stream:
_UpperCamelCase = pkl.load(_snake_case )
_UpperCamelCase = weights.pop('''model''' )
_UpperCamelCase = {}
for k, v in model.items():
_UpperCamelCase = torch.from_numpy(_snake_case )
if "running_var" in k:
_UpperCamelCase = torch.tensor([0] )
_UpperCamelCase = k.replace('''running_var''', '''num_batches_tracked''' )
_UpperCamelCase = zero
return new
def lowerCamelCase__ ( ) -> Union[str, Any]:
"""simple docstring"""
print(F'''{os.path.abspath(os.path.join(_snake_case, os.pardir ) )}/demo.ipynb''' )
def lowerCamelCase__ ( __snake_case, __snake_case="RGB" ) -> List[Any]:
"""simple docstring"""
assert isinstance(_snake_case, _snake_case )
if os.path.isfile(_snake_case ):
_UpperCamelCase = cva.imread(_snake_case )
else:
_UpperCamelCase = get_image_from_url(_snake_case )
assert img is not None, F'''could not connect to: {im}'''
_UpperCamelCase = cva.cvtColor(_snake_case, cva.COLOR_BGR2RGB )
if input_format == "RGB":
_UpperCamelCase = img[:, :, ::-1]
return img
def lowerCamelCase__ ( __snake_case, __snake_case=1 ) -> Dict:
"""simple docstring"""
return (images[i : i + batch] for i in range(0, len(_snake_case ), _snake_case ))
| 708 |
"""simple docstring"""
from ...utils import (
OptionalDependencyNotAvailable,
is_flax_available,
is_torch_available,
is_transformers_available,
)
try:
if not (is_transformers_available() and is_torch_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ...utils.dummy_torch_and_transformers_objects import * # noqa F403
else:
from .multicontrolnet import MultiControlNetModel
from .pipeline_controlnet import StableDiffusionControlNetPipeline
from .pipeline_controlnet_imgaimg import StableDiffusionControlNetImgaImgPipeline
from .pipeline_controlnet_inpaint import StableDiffusionControlNetInpaintPipeline
if is_transformers_available() and is_flax_available():
from .pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline
| 78 | 0 |
"""simple docstring"""
from typing import Dict, Iterable, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format, to_pil_image
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, is_pytesseract_available, is_vision_available, logging, requires_backends
if is_vision_available():
import PIL
# soft dependency
if is_pytesseract_available():
import pytesseract
_a = logging.get_logger(__name__)
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> Any:
"""simple docstring"""
return [
int(10_00 * (box[0] / width) ),
int(10_00 * (box[1] / height) ),
int(10_00 * (box[2] / width) ),
int(10_00 * (box[3] / height) ),
]
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> List[str]:
"""simple docstring"""
_UpperCamelCase = to_pil_image(_A )
_UpperCamelCase , _UpperCamelCase = pil_image.size
_UpperCamelCase = pytesseract.image_to_data(_A, lang=_A, output_type='''dict''', config=_A )
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = data['''text'''], data['''left'''], data['''top'''], data['''width'''], data['''height''']
# filter empty words and corresponding coordinates
_UpperCamelCase = [idx for idx, word in enumerate(_A ) if not word.strip()]
_UpperCamelCase = [word for idx, word in enumerate(_A ) if idx not in irrelevant_indices]
_UpperCamelCase = [coord for idx, coord in enumerate(_A ) if idx not in irrelevant_indices]
_UpperCamelCase = [coord for idx, coord in enumerate(_A ) if idx not in irrelevant_indices]
_UpperCamelCase = [coord for idx, coord in enumerate(_A ) if idx not in irrelevant_indices]
_UpperCamelCase = [coord for idx, coord in enumerate(_A ) if idx not in irrelevant_indices]
# turn coordinates into (left, top, left+width, top+height) format
_UpperCamelCase = []
for x, y, w, h in zip(_A, _A, _A, _A ):
_UpperCamelCase = [x, y, x + w, y + h]
actual_boxes.append(_A )
# finally, normalize the bounding boxes
_UpperCamelCase = []
for box in actual_boxes:
normalized_boxes.append(normalize_box(_A, _A, _A ) )
assert len(_A ) == len(_A ), "Not as many words as there are bounding boxes"
return words, normalized_boxes
class _UpperCAmelCase( lowerCAmelCase__ ):
lowercase__ = ["pixel_values"]
def __init__( self , __a = True , __a = None , __a = PILImageResampling.BILINEAR , __a = True , __a = 1 / 2_55 , __a = True , __a = None , __a = None , __a = True , __a = None , __a = "" , **__a , ) -> None:
'''simple docstring'''
super().__init__(**_SCREAMING_SNAKE_CASE)
_UpperCamelCase = size if size is not None else {'''height''': 2_24, '''width''': 2_24}
_UpperCamelCase = get_size_dict(_SCREAMING_SNAKE_CASE)
_UpperCamelCase = do_resize
_UpperCamelCase = size
_UpperCamelCase = resample
_UpperCamelCase = do_rescale
_UpperCamelCase = rescale_value
_UpperCamelCase = do_normalize
_UpperCamelCase = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
_UpperCamelCase = image_std if image_std is not None else IMAGENET_STANDARD_STD
_UpperCamelCase = apply_ocr
_UpperCamelCase = ocr_lang
_UpperCamelCase = tesseract_config
def UpperCAmelCase ( self , __a , __a , __a = PILImageResampling.BILINEAR , __a = None , **__a , ) -> np.ndarray:
'''simple docstring'''
_UpperCamelCase = get_size_dict(_SCREAMING_SNAKE_CASE)
if "height" not in size or "width" not in size:
raise ValueError(F'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}''')
_UpperCamelCase = (size['''height'''], size['''width'''])
return resize(_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE , resample=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE)
def UpperCAmelCase ( self , __a , __a , __a = None , **__a , ) -> np.ndarray:
'''simple docstring'''
return rescale(_SCREAMING_SNAKE_CASE , scale=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE)
def UpperCAmelCase ( self , __a , __a , __a , __a = None , **__a , ) -> np.ndarray:
'''simple docstring'''
return normalize(_SCREAMING_SNAKE_CASE , mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE , data_format=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE)
def UpperCAmelCase ( self , __a , __a = None , __a = None , __a=None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = None , __a = ChannelDimension.FIRST , **__a , ) -> PIL.Image.Image:
'''simple docstring'''
_UpperCamelCase = do_resize if do_resize is not None else self.do_resize
_UpperCamelCase = size if size is not None else self.size
_UpperCamelCase = get_size_dict(_SCREAMING_SNAKE_CASE)
_UpperCamelCase = resample if resample is not None else self.resample
_UpperCamelCase = do_rescale if do_rescale is not None else self.do_rescale
_UpperCamelCase = rescale_factor if rescale_factor is not None else self.rescale_factor
_UpperCamelCase = do_normalize if do_normalize is not None else self.do_normalize
_UpperCamelCase = image_mean if image_mean is not None else self.image_mean
_UpperCamelCase = image_std if image_std is not None else self.image_std
_UpperCamelCase = apply_ocr if apply_ocr is not None else self.apply_ocr
_UpperCamelCase = ocr_lang if ocr_lang is not None else self.ocr_lang
_UpperCamelCase = tesseract_config if tesseract_config is not None else self.tesseract_config
_UpperCamelCase = make_list_of_images(_SCREAMING_SNAKE_CASE)
if not valid_images(_SCREAMING_SNAKE_CASE):
raise ValueError(
'''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
'''torch.Tensor, tf.Tensor or jax.ndarray.''')
if do_resize and size is None:
raise ValueError('''Size must be specified if do_resize is True.''')
if do_rescale and rescale_factor is None:
raise ValueError('''Rescale factor must be specified if do_rescale is True.''')
if do_normalize and (image_mean is None or image_std is None):
raise ValueError('''If do_normalize is True, image_mean and image_std must be specified.''')
# All transformations expect numpy arrays.
_UpperCamelCase = [to_numpy_array(_SCREAMING_SNAKE_CASE) for image in images]
# Tesseract OCR to get words + normalized bounding boxes
if apply_ocr:
requires_backends(self , '''pytesseract''')
_UpperCamelCase = []
_UpperCamelCase = []
for image in images:
_UpperCamelCase , _UpperCamelCase = apply_tesseract(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE)
words_batch.append(_SCREAMING_SNAKE_CASE)
boxes_batch.append(_SCREAMING_SNAKE_CASE)
if do_resize:
_UpperCamelCase = [self.resize(image=_SCREAMING_SNAKE_CASE , size=_SCREAMING_SNAKE_CASE , resample=_SCREAMING_SNAKE_CASE) for image in images]
if do_rescale:
_UpperCamelCase = [self.rescale(image=_SCREAMING_SNAKE_CASE , scale=_SCREAMING_SNAKE_CASE) for image in images]
if do_normalize:
_UpperCamelCase = [self.normalize(image=_SCREAMING_SNAKE_CASE , mean=_SCREAMING_SNAKE_CASE , std=_SCREAMING_SNAKE_CASE) for image in images]
_UpperCamelCase = [to_channel_dimension_format(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE) for image in images]
_UpperCamelCase = BatchFeature(data={'''pixel_values''': images} , tensor_type=_SCREAMING_SNAKE_CASE)
if apply_ocr:
_UpperCamelCase = words_batch
_UpperCamelCase = boxes_batch
return data
| 709 |
"""simple docstring"""
from collections import OrderedDict
from typing import Any, Mapping, Optional
from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast
from ...utils import logging
_a = logging.get_logger(__name__)
_a = {
"""EleutherAI/gpt-neo-1.3B""": """https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json""",
# See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo
}
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = 'gpt_neo'
lowercase__ = ['past_key_values']
lowercase__ = {'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers'}
def __init__( self , __a=5_02_57 , __a=20_48 , __a=20_48 , __a=24 , __a=[[["global", "local"], 12]] , __a=16 , __a=None , __a=2_56 , __a="gelu_new" , __a=0.0 , __a=0.0 , __a=0.0 , __a=0.1 , __a=1e-5 , __a=0.02 , __a=True , __a=5_02_56 , __a=5_02_56 , **__a , ) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = vocab_size
_UpperCamelCase = max_position_embeddings
_UpperCamelCase = hidden_size
_UpperCamelCase = num_layers
_UpperCamelCase = num_heads
_UpperCamelCase = intermediate_size
_UpperCamelCase = window_size
_UpperCamelCase = activation_function
_UpperCamelCase = resid_dropout
_UpperCamelCase = embed_dropout
_UpperCamelCase = attention_dropout
_UpperCamelCase = classifier_dropout
_UpperCamelCase = layer_norm_epsilon
_UpperCamelCase = initializer_range
_UpperCamelCase = use_cache
_UpperCamelCase = bos_token_id
_UpperCamelCase = eos_token_id
_UpperCamelCase = attention_types
_UpperCamelCase = self.expand_attention_types_params(__a)
if len(self.attention_layers) != self.num_layers:
raise ValueError(
'''Configuration for convolutional module is incorrect. '''
'''It is required that `len(config.attention_layers)` == `config.num_layers` '''
F'''but is `len(config.attention_layers) = {len(self.attention_layers)}`, '''
F'''`config.num_layers = {self.num_layers}`. '''
'''`config.attention_layers` is prepared using `config.attention_types`. '''
'''Please verify the value of `config.attention_types` argument.''')
super().__init__(bos_token_id=__a , eos_token_id=__a , **__a)
@staticmethod
def UpperCAmelCase ( __a) -> int:
'''simple docstring'''
_UpperCamelCase = []
for item in attention_types:
for _ in range(item[1]):
attentions.extend(item[0])
return attentions
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case, __snake_case ) -> str:
"""simple docstring"""
import torch
_UpperCamelCase = input.size()
_UpperCamelCase = len(__snake_case )
_UpperCamelCase = shape[dimension]
_UpperCamelCase = torch.arange(0, __snake_case, __snake_case )
_UpperCamelCase = torch.div(sizedim - size, __snake_case, rounding_mode='''floor''' ) + 1
_UpperCamelCase = torch.arange(__snake_case ) + low_indices[:min_length][:, None]
_UpperCamelCase = [slice(__snake_case )] * rank
_UpperCamelCase = indices
_UpperCamelCase = input[s]
_UpperCamelCase = list(range(0, rank + 1 ) )
perm.append(perm.pop(dimension + 1 ) )
return sliced.permute(__snake_case )
def lowerCamelCase__ ( __snake_case, __snake_case ) -> str:
"""simple docstring"""
import torch
_UpperCamelCase = torch.arange(1, __snake_case )
_UpperCamelCase = torch.remainder(__snake_case, __snake_case )
_UpperCamelCase = remainders == 0
_UpperCamelCase = candidates[divisor_indices]
_UpperCamelCase = torch.max(__snake_case )
return largest_divisor, torch.div(__snake_case, __snake_case, rounding_mode='''floor''' )
class _UpperCAmelCase( lowerCamelCase ):
@property
def UpperCAmelCase ( self) -> Mapping[str, Mapping[int, str]]:
'''simple docstring'''
_UpperCamelCase = OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}})
if self.use_past:
self.fill_with_past_key_values_(__a , direction='''inputs''')
_UpperCamelCase = {0: '''batch''', 1: '''past_sequence + sequence'''}
else:
_UpperCamelCase = {0: '''batch''', 1: '''sequence'''}
return common_inputs
@property
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
return self._config.num_heads
def UpperCAmelCase ( self , __a , __a = -1 , __a = -1 , __a = False , __a = None , ) -> Mapping[str, Any]:
'''simple docstring'''
_UpperCamelCase = 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()
_UpperCamelCase = 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
_UpperCamelCase , _UpperCamelCase = common_inputs['''input_ids'''].shape
# Not using the same length for past_key_values
_UpperCamelCase = seqlen + 2
_UpperCamelCase = (
batch,
self.num_attention_heads,
past_key_values_length,
self._config.hidden_size // self.num_attention_heads,
)
_UpperCamelCase = [
(torch.zeros(__a), torch.zeros(__a)) for _ in range(self.num_layers)
]
_UpperCamelCase = common_inputs['''attention_mask''']
if self.use_past:
_UpperCamelCase = ordered_inputs['''attention_mask'''].dtype
_UpperCamelCase = torch.cat(
[ordered_inputs['''attention_mask'''], torch.ones(__a , __a , dtype=__a)] , dim=1)
return ordered_inputs
@property
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
return 13
| 78 | 0 |
"""simple docstring"""
def lowerCamelCase__ ( __snake_case, __snake_case ) -> Optional[int]:
"""simple docstring"""
print('''\nThe shortest path matrix using Floyd Warshall algorithm\n''' )
for i in range(A_ ):
for j in range(A_ ):
if dist[i][j] != float('''inf''' ):
print(int(dist[i][j] ), end='''\t''' )
else:
print('''INF''', end='''\t''' )
print()
def lowerCamelCase__ ( __snake_case, __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = [[float('''inf''' ) for _ in range(A_ )] for _ in range(A_ )]
for i in range(A_ ):
for j in range(A_ ):
_UpperCamelCase = graph[i][j]
# check vertex k against all other vertices (i, j)
for k in range(A_ ):
# looping through rows of graph array
for i in range(A_ ):
# looping through columns of graph array
for j in range(A_ ):
if (
dist[i][k] != float('''inf''' )
and dist[k][j] != float('''inf''' )
and dist[i][k] + dist[k][j] < dist[i][j]
):
_UpperCamelCase = dist[i][k] + dist[k][j]
_print_dist(A_, A_ )
return dist, v
if __name__ == "__main__":
_a = int(input("""Enter number of vertices: """))
_a = int(input("""Enter number of edges: """))
_a = [[float("""inf""") for i in range(v)] for j in range(v)]
for i in range(v):
_a = 0.0
# src and dst are indices that must be within the array size graph[e][v]
# failure to follow this will result in an error
for i in range(e):
print("""\nEdge """, i + 1)
_a = int(input("""Enter source:"""))
_a = int(input("""Enter destination:"""))
_a = float(input("""Enter weight:"""))
_a = weight
floyd_warshall(graph, v)
# Example Input
# Enter number of vertices: 3
# Enter number of edges: 2
# # generated graph from vertex and edge inputs
# [[inf, inf, inf], [inf, inf, inf], [inf, inf, inf]]
# [[0.0, inf, inf], [inf, 0.0, inf], [inf, inf, 0.0]]
# specify source, destination and weight for edge #1
# Edge 1
# Enter source:1
# Enter destination:2
# Enter weight:2
# specify source, destination and weight for edge #2
# Edge 2
# Enter source:2
# Enter destination:1
# Enter weight:1
# # Expected Output from the vertice, edge and src, dst, weight inputs!!
# 0 INF INF
# INF 0 2
# INF 1 0
| 710 |
"""simple docstring"""
import sys
from collections import defaultdict
class _UpperCAmelCase:
def __init__( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = []
def UpperCAmelCase ( self , __a) -> Optional[Any]:
'''simple docstring'''
return self.node_position[vertex]
def UpperCAmelCase ( self , __a , __a) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = pos
def UpperCAmelCase ( self , __a , __a , __a , __a) -> Tuple:
'''simple docstring'''
if start > size // 2 - 1:
return
else:
if 2 * start + 2 >= size:
_UpperCamelCase = 2 * start + 1
else:
if heap[2 * start + 1] < heap[2 * start + 2]:
_UpperCamelCase = 2 * start + 1
else:
_UpperCamelCase = 2 * start + 2
if heap[smallest_child] < heap[start]:
_UpperCamelCase , _UpperCamelCase = heap[smallest_child], positions[smallest_child]
_UpperCamelCase , _UpperCamelCase = (
heap[start],
positions[start],
)
_UpperCamelCase , _UpperCamelCase = temp, tempa
_UpperCamelCase = self.get_position(positions[smallest_child])
self.set_position(
positions[smallest_child] , self.get_position(positions[start]))
self.set_position(positions[start] , __a)
self.top_to_bottom(__a , __a , __a , __a)
def UpperCAmelCase ( self , __a , __a , __a , __a) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = position[index]
while index != 0:
_UpperCamelCase = int((index - 2) / 2) if index % 2 == 0 else int((index - 1) / 2)
if val < heap[parent]:
_UpperCamelCase = heap[parent]
_UpperCamelCase = position[parent]
self.set_position(position[parent] , __a)
else:
_UpperCamelCase = val
_UpperCamelCase = temp
self.set_position(__a , __a)
break
_UpperCamelCase = parent
else:
_UpperCamelCase = val
_UpperCamelCase = temp
self.set_position(__a , 0)
def UpperCAmelCase ( self , __a , __a) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = len(__a) // 2 - 1
for i in range(__a , -1 , -1):
self.top_to_bottom(__a , __a , len(__a) , __a)
def UpperCAmelCase ( self , __a , __a) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = positions[0]
_UpperCamelCase = sys.maxsize
self.top_to_bottom(__a , 0 , len(__a) , __a)
return temp
def lowerCamelCase__ ( __snake_case ) -> Optional[int]:
"""simple docstring"""
_UpperCamelCase = Heap()
_UpperCamelCase = [0] * len(__snake_case )
_UpperCamelCase = [-1] * len(__snake_case ) # Neighboring Tree Vertex of selected vertex
# Minimum Distance of explored vertex with neighboring vertex of partial tree
# formed in graph
_UpperCamelCase = [] # Heap of Distance of vertices from their neighboring vertex
_UpperCamelCase = []
for vertex in range(len(__snake_case ) ):
distance_tv.append(sys.maxsize )
positions.append(__snake_case )
heap.node_position.append(__snake_case )
_UpperCamelCase = []
_UpperCamelCase = 1
_UpperCamelCase = sys.maxsize
for neighbor, distance in adjacency_list[0]:
_UpperCamelCase = 0
_UpperCamelCase = distance
heap.heapify(__snake_case, __snake_case )
for _ in range(1, len(__snake_case ) ):
_UpperCamelCase = heap.delete_minimum(__snake_case, __snake_case )
if visited[vertex] == 0:
tree_edges.append((nbr_tv[vertex], vertex) )
_UpperCamelCase = 1
for neighbor, distance in adjacency_list[vertex]:
if (
visited[neighbor] == 0
and distance < distance_tv[heap.get_position(__snake_case )]
):
_UpperCamelCase = distance
heap.bottom_to_top(
__snake_case, heap.get_position(__snake_case ), __snake_case, __snake_case )
_UpperCamelCase = vertex
return tree_edges
if __name__ == "__main__": # pragma: no cover
# < --------- Prims Algorithm --------- >
_a = int(input("""Enter number of edges: """).strip())
_a = defaultdict(list)
for _ in range(edges_number):
_a = [int(x) for x in input().strip().split()]
adjacency_list[edge[0]].append([edge[1], edge[2]])
adjacency_list[edge[1]].append([edge[0], edge[2]])
print(prisms_algorithm(adjacency_list))
| 78 | 0 |
"""simple docstring"""
from dataclasses import dataclass
from typing import Dict, Optional, Union
import torch
import torch.nn.functional as F
from torch import nn
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .attention import BasicTransformerBlock
from .attention_processor import AttentionProcessor, AttnProcessor
from .embeddings import TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin
@dataclass
class _UpperCAmelCase( snake_case__ ):
lowercase__ = 42
class _UpperCAmelCase( snake_case__ , snake_case__ ):
@register_to_config
def __init__( self , __a = 32 , __a = 64 , __a = 20 , __a = 7_68 , __a=77 , __a=4 , __a = 0.0 , __a = "silu" , __a = None , __a = None , __a = "linear" , __a = "prd" , __a = None , __a = None , __a = None , ) -> Dict:
'''simple docstring'''
super().__init__()
_UpperCamelCase = num_attention_heads
_UpperCamelCase = attention_head_dim
_UpperCamelCase = num_attention_heads * attention_head_dim
_UpperCamelCase = additional_embeddings
_UpperCamelCase = time_embed_dim or inner_dim
_UpperCamelCase = embedding_proj_dim or embedding_dim
_UpperCamelCase = clip_embed_dim or embedding_dim
_UpperCamelCase = Timesteps(_A , _A , 0)
_UpperCamelCase = TimestepEmbedding(_A , _A , out_dim=_A , act_fn=_A)
_UpperCamelCase = nn.Linear(_A , _A)
if embedding_proj_norm_type is None:
_UpperCamelCase = None
elif embedding_proj_norm_type == "layer":
_UpperCamelCase = nn.LayerNorm(_A)
else:
raise ValueError(F'''unsupported embedding_proj_norm_type: {embedding_proj_norm_type}''')
_UpperCamelCase = nn.Linear(_A , _A)
if encoder_hid_proj_type is None:
_UpperCamelCase = None
elif encoder_hid_proj_type == "linear":
_UpperCamelCase = nn.Linear(_A , _A)
else:
raise ValueError(F'''unsupported encoder_hid_proj_type: {encoder_hid_proj_type}''')
_UpperCamelCase = nn.Parameter(torch.zeros(1 , num_embeddings + additional_embeddings , _A))
if added_emb_type == "prd":
_UpperCamelCase = nn.Parameter(torch.zeros(1 , 1 , _A))
elif added_emb_type is None:
_UpperCamelCase = None
else:
raise ValueError(
F'''`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `\'prd\'` or `None`.''')
_UpperCamelCase = nn.ModuleList(
[
BasicTransformerBlock(
_A , _A , _A , dropout=_A , activation_fn='''gelu''' , attention_bias=_A , )
for d in range(_A)
])
if norm_in_type == "layer":
_UpperCamelCase = nn.LayerNorm(_A)
elif norm_in_type is None:
_UpperCamelCase = None
else:
raise ValueError(F'''Unsupported norm_in_type: {norm_in_type}.''')
_UpperCamelCase = nn.LayerNorm(_A)
_UpperCamelCase = nn.Linear(_A , _A)
_UpperCamelCase = torch.full(
[num_embeddings + additional_embeddings, num_embeddings + additional_embeddings] , -1_00_00.0)
causal_attention_mask.triu_(1)
_UpperCamelCase = causal_attention_mask[None, ...]
self.register_buffer('''causal_attention_mask''' , _A , persistent=_A)
_UpperCamelCase = nn.Parameter(torch.zeros(1 , _A))
_UpperCamelCase = nn.Parameter(torch.zeros(1 , _A))
@property
# Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase = {}
def fn_recursive_add_processors(__a , __a , __a):
if hasattr(_A , '''set_processor'''):
_UpperCamelCase = module.processor
for sub_name, child in module.named_children():
fn_recursive_add_processors(F'''{name}.{sub_name}''' , _A , _A)
return processors
for name, module in self.named_children():
fn_recursive_add_processors(_A , _A , _A)
return processors
def UpperCAmelCase ( self , __a) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = len(self.attn_processors.keys())
if isinstance(_A , _A) and len(_A) != count:
raise ValueError(
F'''A dict of processors was passed, but the number of processors {len(_A)} does not match the'''
F''' number of attention layers: {count}. Please make sure to pass {count} processor classes.''')
def fn_recursive_attn_processor(__a , __a , __a):
if hasattr(_A , '''set_processor'''):
if not isinstance(_A , _A):
module.set_processor(_A)
else:
module.set_processor(processor.pop(F'''{name}.processor'''))
for sub_name, child in module.named_children():
fn_recursive_attn_processor(F'''{name}.{sub_name}''' , _A , _A)
for name, module in self.named_children():
fn_recursive_attn_processor(_A , _A , _A)
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
self.set_attn_processor(AttnProcessor())
def UpperCAmelCase ( self , __a , __a , __a , __a = None , __a = None , __a = True , ) -> int:
'''simple docstring'''
_UpperCamelCase = hidden_states.shape[0]
_UpperCamelCase = timestep
if not torch.is_tensor(_A):
_UpperCamelCase = torch.tensor([timesteps] , dtype=torch.long , device=hidden_states.device)
elif torch.is_tensor(_A) and len(timesteps.shape) == 0:
_UpperCamelCase = timesteps[None].to(hidden_states.device)
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
_UpperCamelCase = timesteps * torch.ones(_A , dtype=timesteps.dtype , device=timesteps.device)
_UpperCamelCase = self.time_proj(_A)
# timesteps does not contain any weights and will always return f32 tensors
# but time_embedding might be fp16, so we need to cast here.
_UpperCamelCase = timesteps_projected.to(dtype=self.dtype)
_UpperCamelCase = self.time_embedding(_A)
if self.embedding_proj_norm is not None:
_UpperCamelCase = self.embedding_proj_norm(_A)
_UpperCamelCase = self.embedding_proj(_A)
if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None:
_UpperCamelCase = self.encoder_hidden_states_proj(_A)
elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None:
raise ValueError('''`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set''')
_UpperCamelCase = self.proj_in(_A)
_UpperCamelCase = self.positional_embedding.to(hidden_states.dtype)
_UpperCamelCase = []
_UpperCamelCase = 0
if encoder_hidden_states is not None:
additional_embeds.append(_A)
additional_embeddings_len += encoder_hidden_states.shape[1]
if len(proj_embeddings.shape) == 2:
_UpperCamelCase = proj_embeddings[:, None, :]
if len(hidden_states.shape) == 2:
_UpperCamelCase = hidden_states[:, None, :]
_UpperCamelCase = additional_embeds + [
proj_embeddings,
time_embeddings[:, None, :],
hidden_states,
]
if self.prd_embedding is not None:
_UpperCamelCase = self.prd_embedding.to(hidden_states.dtype).expand(_A , -1 , -1)
additional_embeds.append(_A)
_UpperCamelCase = torch.cat(
_A , dim=1 , )
# Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens
_UpperCamelCase = additional_embeddings_len + proj_embeddings.shape[1] + 1
if positional_embeddings.shape[1] < hidden_states.shape[1]:
_UpperCamelCase = F.pad(
_A , (
0,
0,
additional_embeddings_len,
self.prd_embedding.shape[1] if self.prd_embedding is not None else 0,
) , value=0.0 , )
_UpperCamelCase = hidden_states + positional_embeddings
if attention_mask is not None:
_UpperCamelCase = (1 - attention_mask.to(hidden_states.dtype)) * -1_00_00.0
_UpperCamelCase = F.pad(_A , (0, self.additional_embeddings) , value=0.0)
_UpperCamelCase = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype)
_UpperCamelCase = attention_mask.repeat_interleave(self.config.num_attention_heads , dim=0)
if self.norm_in is not None:
_UpperCamelCase = self.norm_in(_A)
for block in self.transformer_blocks:
_UpperCamelCase = block(_A , attention_mask=_A)
_UpperCamelCase = self.norm_out(_A)
if self.prd_embedding is not None:
_UpperCamelCase = hidden_states[:, -1]
else:
_UpperCamelCase = hidden_states[:, additional_embeddings_len:]
_UpperCamelCase = self.proj_to_clip_embeddings(_A)
if not return_dict:
return (predicted_image_embedding,)
return PriorTransformerOutput(predicted_image_embedding=_A)
def UpperCAmelCase ( self , __a) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = (prior_latents * self.clip_std) + self.clip_mean
return prior_latents
| 711 |
"""simple docstring"""
import json
import sys
def lowerCamelCase__ ( __snake_case, __snake_case ) -> Union[str, Any]:
"""simple docstring"""
with open(__snake_case, encoding='''utf-8''' ) as f:
_UpperCamelCase = json.load(__snake_case )
_UpperCamelCase = ['''<details>''', '''<summary>Show updated benchmarks!</summary>''', ''' ''']
for benchmark_name in sorted(__snake_case ):
_UpperCamelCase = results[benchmark_name]
_UpperCamelCase = benchmark_name.split('''/''' )[-1]
output_md.append(F'''### Benchmark: {benchmark_file_name}''' )
_UpperCamelCase = '''| metric |'''
_UpperCamelCase = '''|--------|'''
_UpperCamelCase = '''| new / old (diff) |'''
for metric_name in sorted(__snake_case ):
_UpperCamelCase = benchmark_res[metric_name]
_UpperCamelCase = metric_vals['''new''']
_UpperCamelCase = metric_vals.get('''old''', __snake_case )
_UpperCamelCase = metric_vals.get('''diff''', __snake_case )
_UpperCamelCase = F''' {new_val:f}''' if isinstance(__snake_case, (int, float) ) else '''None'''
if old_val is not None:
val_str += F''' / {old_val:f}''' if isinstance(__snake_case, (int, float) ) else "None"
if dif_val is not None:
val_str += F''' ({dif_val:f})''' if isinstance(__snake_case, (int, float) ) else "None"
title += " " + metric_name + " |"
lines += "---|"
value += val_str + " |"
output_md += [title, lines, value, " "]
output_md.append('''</details>''' )
with open(__snake_case, '''w''', encoding='''utf-8''' ) as f:
f.writelines('''\n'''.join(__snake_case ) )
if __name__ == "__main__":
_a = sys.argv[1]
_a = sys.argv[2]
format_json_to_md(input_json_file, output_md_file)
| 78 | 0 |
"""simple docstring"""
import baseaa
def lowerCamelCase__ ( __snake_case ) -> Any:
"""simple docstring"""
return baseaa.baaencode(string.encode('''utf-8''' ) )
def lowerCamelCase__ ( __snake_case ) -> Dict:
"""simple docstring"""
return baseaa.baadecode(lowerCamelCase_ ).decode('''utf-8''' )
if __name__ == "__main__":
_a = """Hello World!"""
_a = baseaa_encode(test)
print(encoded)
_a = baseaa_decode(encoded)
print(decoded)
| 712 |
"""simple docstring"""
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()
_a = logging.get_logger(__name__)
def lowerCamelCase__ ( __snake_case, __snake_case=False ) -> Tuple:
"""simple docstring"""
_UpperCamelCase = []
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"
_UpperCamelCase = [(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 lowerCamelCase__ ( __snake_case, __snake_case, __snake_case=False ) -> str:
"""simple docstring"""
for i in range(config.num_hidden_layers ):
if base_model:
_UpperCamelCase = ''''''
else:
_UpperCamelCase = '''vit.'''
# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
_UpperCamelCase = state_dict.pop(F'''blocks.{i}.attn.qkv.weight''' )
_UpperCamelCase = state_dict.pop(F'''blocks.{i}.attn.qkv.bias''' )
# next, add query, keys and values (in that order) to the state dict
_UpperCamelCase = in_proj_weight[
: config.hidden_size, :
]
_UpperCamelCase = in_proj_bias[: config.hidden_size]
_UpperCamelCase = in_proj_weight[
config.hidden_size : config.hidden_size * 2, :
]
_UpperCamelCase = in_proj_bias[
config.hidden_size : config.hidden_size * 2
]
_UpperCamelCase = in_proj_weight[
-config.hidden_size :, :
]
_UpperCamelCase = in_proj_bias[-config.hidden_size :]
def lowerCamelCase__ ( __snake_case ) -> Dict:
"""simple docstring"""
_UpperCamelCase = ['''head.weight''', '''head.bias''']
for k in ignore_keys:
state_dict.pop(__snake_case, __snake_case )
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> Any:
"""simple docstring"""
_UpperCamelCase = dct.pop(__snake_case )
_UpperCamelCase = val
def lowerCamelCase__ ( ) -> Dict:
"""simple docstring"""
_UpperCamelCase = '''http://images.cocodataset.org/val2017/000000039769.jpg'''
_UpperCamelCase = Image.open(requests.get(__snake_case, stream=__snake_case ).raw )
return im
@torch.no_grad()
def lowerCamelCase__ ( __snake_case, __snake_case ) -> Union[str, Any]:
"""simple docstring"""
_UpperCamelCase = ViTConfig()
_UpperCamelCase = False
# dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size
if vit_name[-5:] == "in21k":
_UpperCamelCase = True
_UpperCamelCase = int(vit_name[-12:-10] )
_UpperCamelCase = int(vit_name[-9:-6] )
else:
_UpperCamelCase = 10_00
_UpperCamelCase = '''huggingface/label-files'''
_UpperCamelCase = '''imagenet-1k-id2label.json'''
_UpperCamelCase = json.load(open(hf_hub_download(__snake_case, __snake_case, repo_type='''dataset''' ), '''r''' ) )
_UpperCamelCase = {int(__snake_case ): v for k, v in idalabel.items()}
_UpperCamelCase = idalabel
_UpperCamelCase = {v: k for k, v in idalabel.items()}
_UpperCamelCase = int(vit_name[-6:-4] )
_UpperCamelCase = int(vit_name[-3:] )
# size of the architecture
if "deit" in vit_name:
if vit_name[9:].startswith('''tiny''' ):
_UpperCamelCase = 1_92
_UpperCamelCase = 7_68
_UpperCamelCase = 12
_UpperCamelCase = 3
elif vit_name[9:].startswith('''small''' ):
_UpperCamelCase = 3_84
_UpperCamelCase = 15_36
_UpperCamelCase = 12
_UpperCamelCase = 6
else:
pass
else:
if vit_name[4:].startswith('''small''' ):
_UpperCamelCase = 7_68
_UpperCamelCase = 23_04
_UpperCamelCase = 8
_UpperCamelCase = 8
elif vit_name[4:].startswith('''base''' ):
pass
elif vit_name[4:].startswith('''large''' ):
_UpperCamelCase = 10_24
_UpperCamelCase = 40_96
_UpperCamelCase = 24
_UpperCamelCase = 16
elif vit_name[4:].startswith('''huge''' ):
_UpperCamelCase = 12_80
_UpperCamelCase = 51_20
_UpperCamelCase = 32
_UpperCamelCase = 16
# load original model from timm
_UpperCamelCase = timm.create_model(__snake_case, pretrained=__snake_case )
timm_model.eval()
# load state_dict of original model, remove and rename some keys
_UpperCamelCase = timm_model.state_dict()
if base_model:
remove_classification_head_(__snake_case )
_UpperCamelCase = create_rename_keys(__snake_case, __snake_case )
for src, dest in rename_keys:
rename_key(__snake_case, __snake_case, __snake_case )
read_in_q_k_v(__snake_case, __snake_case, __snake_case )
# load HuggingFace model
if vit_name[-5:] == "in21k":
_UpperCamelCase = ViTModel(__snake_case ).eval()
else:
_UpperCamelCase = ViTForImageClassification(__snake_case ).eval()
model.load_state_dict(__snake_case )
# Check outputs on an image, prepared by ViTImageProcessor/DeiTImageProcessor
if "deit" in vit_name:
_UpperCamelCase = DeiTImageProcessor(size=config.image_size )
else:
_UpperCamelCase = ViTImageProcessor(size=config.image_size )
_UpperCamelCase = image_processor(images=prepare_img(), return_tensors='''pt''' )
_UpperCamelCase = encoding['''pixel_values''']
_UpperCamelCase = model(__snake_case )
if base_model:
_UpperCamelCase = timm_model.forward_features(__snake_case )
assert timm_pooled_output.shape == outputs.pooler_output.shape
assert torch.allclose(__snake_case, outputs.pooler_output, atol=1e-3 )
else:
_UpperCamelCase = timm_model(__snake_case )
assert timm_logits.shape == outputs.logits.shape
assert torch.allclose(__snake_case, outputs.logits, atol=1e-3 )
Path(__snake_case ).mkdir(exist_ok=__snake_case )
print(F'''Saving model {vit_name} to {pytorch_dump_folder_path}''' )
model.save_pretrained(__snake_case )
print(F'''Saving image processor to {pytorch_dump_folder_path}''' )
image_processor.save_pretrained(__snake_case )
if __name__ == "__main__":
_a = 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."""
)
_a = parser.parse_args()
convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path)
| 78 | 0 |
"""simple docstring"""
from __future__ import annotations
from collections.abc import MutableSequence
class a_:
def __init__( self , __a , __a) -> Optional[int]:
'''simple docstring'''
if len(UpperCamelCase_) != degree + 1:
raise ValueError(
'''The number of coefficients should be equal to the degree + 1.''')
_UpperCamelCase = list(UpperCamelCase_)
_UpperCamelCase = degree
def __add__( self , __a) -> List[Any]:
'''simple docstring'''
if self.degree > polynomial_a.degree:
_UpperCamelCase = self.coefficients[:]
for i in range(polynomial_a.degree + 1):
coefficients[i] += polynomial_a.coefficients[i]
return Polynomial(self.degree , UpperCamelCase_)
else:
_UpperCamelCase = polynomial_a.coefficients[:]
for i in range(self.degree + 1):
coefficients[i] += self.coefficients[i]
return Polynomial(polynomial_a.degree , UpperCamelCase_)
def __sub__( self , __a) -> Any:
'''simple docstring'''
return self + polynomial_a * Polynomial(0 , [-1])
def __neg__( self) -> Optional[Any]:
'''simple docstring'''
return Polynomial(self.degree , [-c for c in self.coefficients])
def __mul__( self , __a) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = [0] * (self.degree + polynomial_a.degree + 1)
for i in range(self.degree + 1):
for j in range(polynomial_a.degree + 1):
coefficients[i + j] += (
self.coefficients[i] * polynomial_a.coefficients[j]
)
return Polynomial(self.degree + polynomial_a.degree , UpperCamelCase_)
def UpperCAmelCase ( self , __a) -> int:
'''simple docstring'''
_UpperCamelCase = 0
for i in range(self.degree + 1):
result += self.coefficients[i] * (substitution**i)
return result
def __str__( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase = ''''''
for i in range(self.degree , -1 , -1):
if self.coefficients[i] == 0:
continue
elif self.coefficients[i] > 0:
if polynomial:
polynomial += " + "
else:
polynomial += " - "
if i == 0:
polynomial += str(abs(self.coefficients[i]))
elif i == 1:
polynomial += str(abs(self.coefficients[i])) + "x"
else:
polynomial += str(abs(self.coefficients[i])) + "x^" + str(UpperCamelCase_)
return polynomial
def __repr__( self) -> str:
'''simple docstring'''
return self.__str__()
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = [0] * self.degree
for i in range(self.degree):
_UpperCamelCase = self.coefficients[i + 1] * (i + 1)
return Polynomial(self.degree - 1 , UpperCamelCase_)
def UpperCAmelCase ( self , __a = 0) -> int:
'''simple docstring'''
_UpperCamelCase = [0] * (self.degree + 2)
_UpperCamelCase = constant
for i in range(self.degree + 1):
_UpperCamelCase = self.coefficients[i] / (i + 1)
return Polynomial(self.degree + 1 , UpperCamelCase_)
def __eq__( self , __a) -> str:
'''simple docstring'''
if not isinstance(UpperCamelCase_ , UpperCamelCase_):
return False
if self.degree != polynomial_a.degree:
return False
for i in range(self.degree + 1):
if self.coefficients[i] != polynomial_a.coefficients[i]:
return False
return True
def __ne__( self , __a) -> Dict:
'''simple docstring'''
return not self.__eq__(UpperCamelCase_)
| 713 |
"""simple docstring"""
import unittest
from transformers import AlbertConfig, is_torch_available
from transformers.models.auto import get_values
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 (
MODEL_FOR_PRETRAINING_MAPPING,
AlbertForMaskedLM,
AlbertForMultipleChoice,
AlbertForPreTraining,
AlbertForQuestionAnswering,
AlbertForSequenceClassification,
AlbertForTokenClassification,
AlbertModel,
)
from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST
class _UpperCAmelCase:
def __init__( self , __a , __a=13 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=99 , __a=16 , __a=36 , __a=6 , __a=6 , __a=6 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=5_12 , __a=16 , __a=2 , __a=0.02 , __a=3 , __a=4 , __a=None , ) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = parent
_UpperCamelCase = batch_size
_UpperCamelCase = seq_length
_UpperCamelCase = is_training
_UpperCamelCase = use_input_mask
_UpperCamelCase = use_token_type_ids
_UpperCamelCase = use_labels
_UpperCamelCase = vocab_size
_UpperCamelCase = embedding_size
_UpperCamelCase = hidden_size
_UpperCamelCase = num_hidden_layers
_UpperCamelCase = num_hidden_groups
_UpperCamelCase = num_attention_heads
_UpperCamelCase = intermediate_size
_UpperCamelCase = hidden_act
_UpperCamelCase = hidden_dropout_prob
_UpperCamelCase = attention_probs_dropout_prob
_UpperCamelCase = max_position_embeddings
_UpperCamelCase = type_vocab_size
_UpperCamelCase = type_sequence_label_size
_UpperCamelCase = initializer_range
_UpperCamelCase = num_labels
_UpperCamelCase = num_choices
_UpperCamelCase = scope
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size)
_UpperCamelCase = None
if self.use_input_mask:
_UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length])
_UpperCamelCase = None
if self.use_token_type_ids:
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size)
_UpperCamelCase = None
_UpperCamelCase = None
_UpperCamelCase = None
if self.use_labels:
_UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size)
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels)
_UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices)
_UpperCamelCase = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
return 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 , initializer_range=self.initializer_range , num_hidden_groups=self.num_hidden_groups , )
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = AlbertModel(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a , attention_mask=__a , token_type_ids=__a)
_UpperCamelCase = model(__a , token_type_ids=__a)
_UpperCamelCase = model(__a)
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))
self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = AlbertForPreTraining(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(
__a , attention_mask=__a , token_type_ids=__a , labels=__a , sentence_order_label=__a , )
self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size))
self.parent.assertEqual(result.sop_logits.shape , (self.batch_size, config.num_labels))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = AlbertForMaskedLM(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a , attention_mask=__a , token_type_ids=__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) -> Any:
'''simple docstring'''
_UpperCamelCase = AlbertForQuestionAnswering(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(
__a , attention_mask=__a , token_type_ids=__a , start_positions=__a , end_positions=__a , )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length))
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = self.num_labels
_UpperCamelCase = AlbertForSequenceClassification(__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.num_labels
_UpperCamelCase = AlbertForTokenClassification(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = self.num_choices
_UpperCamelCase = AlbertForMultipleChoice(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = input_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous()
_UpperCamelCase = token_type_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous()
_UpperCamelCase = input_mask.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous()
_UpperCamelCase = model(
__a , attention_mask=__a , token_type_ids=__a , labels=__a , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices))
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = self.prepare_config_and_inputs()
(
(
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) ,
) = config_and_inputs
_UpperCamelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
return config, inputs_dict
@require_torch
class _UpperCAmelCase( lowerCamelCase , lowerCamelCase , unittest.TestCase ):
lowercase__ = (
(
AlbertModel,
AlbertForPreTraining,
AlbertForMaskedLM,
AlbertForMultipleChoice,
AlbertForSequenceClassification,
AlbertForTokenClassification,
AlbertForQuestionAnswering,
)
if is_torch_available()
else ()
)
lowercase__ = (
{
'feature-extraction': AlbertModel,
'fill-mask': AlbertForMaskedLM,
'question-answering': AlbertForQuestionAnswering,
'text-classification': AlbertForSequenceClassification,
'token-classification': AlbertForTokenClassification,
'zero-shot': AlbertForSequenceClassification,
}
if is_torch_available()
else {}
)
lowercase__ = True
def UpperCAmelCase ( self , __a , __a , __a=False) -> List[str]:
'''simple docstring'''
_UpperCamelCase = super()._prepare_for_class(__a , __a , return_labels=__a)
if return_labels:
if model_class in get_values(__a):
_UpperCamelCase = torch.zeros(
(self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=__a)
_UpperCamelCase = torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=__a)
return inputs_dict
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = AlbertModelTester(self)
_UpperCamelCase = ConfigTester(self , config_class=__a , hidden_size=37)
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
self.config_tester.run_common_tests()
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__a)
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_pretraining(*__a)
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*__a)
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*__a)
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*__a)
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*__a)
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
_UpperCamelCase = type
self.model_tester.create_and_check_model(*__a)
@slow
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_UpperCamelCase = AlbertModel.from_pretrained(__a)
self.assertIsNotNone(__a)
@require_torch
class _UpperCAmelCase( unittest.TestCase ):
@slow
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = AlbertModel.from_pretrained('''albert-base-v2''')
_UpperCamelCase = torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]])
_UpperCamelCase = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
with torch.no_grad():
_UpperCamelCase = model(__a , attention_mask=__a)[0]
_UpperCamelCase = torch.Size((1, 11, 7_68))
self.assertEqual(output.shape , __a)
_UpperCamelCase = torch.tensor(
[[[-0.6513, 1.5035, -0.2766], [-0.6515, 1.5046, -0.2780], [-0.6512, 1.5049, -0.2784]]])
self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __a , atol=1e-4))
| 78 | 0 |
"""simple docstring"""
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
_a = {"""configuration_timm_backbone""": ["""TimmBackboneConfig"""]}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_a = ["""TimmBackbone"""]
if TYPE_CHECKING:
from .configuration_timm_backbone import TimmBackboneConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_timm_backbone import TimmBackbone
else:
import sys
_a = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 714 |
"""simple docstring"""
import os
from typing import BinaryIO, Optional, Union
import numpy as np
import pyarrow.parquet as pq
from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config
from ..features.features import FeatureType, _visit
from ..formatting import query_table
from ..packaged_modules import _PACKAGED_DATASETS_MODULES
from ..packaged_modules.parquet.parquet import Parquet
from ..utils import logging
from ..utils.typing import NestedDataStructureLike, PathLike
from .abc import AbstractDatasetReader
def lowerCamelCase__ ( __snake_case ) -> Optional[int]:
"""simple docstring"""
_UpperCamelCase = np.inf
def set_batch_size(__snake_case ) -> None:
nonlocal batch_size
if isinstance(__snake_case, __snake_case ):
_UpperCamelCase = min(__snake_case, config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS )
elif isinstance(__snake_case, __snake_case ):
_UpperCamelCase = min(__snake_case, config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS )
elif isinstance(__snake_case, __snake_case ) and feature.dtype == "binary":
_UpperCamelCase = min(__snake_case, config.PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS )
_visit(__snake_case, __snake_case )
return None if batch_size is np.inf else batch_size
class _UpperCAmelCase( lowerCamelCase ):
def __init__( self , __a , __a = None , __a = None , __a = None , __a = False , __a = False , __a = None , **__a , ) -> Dict:
'''simple docstring'''
super().__init__(
__a , split=__a , features=__a , cache_dir=__a , keep_in_memory=__a , streaming=__a , num_proc=__a , **__a , )
_UpperCamelCase = path_or_paths if isinstance(__a , __a) else {self.split: path_or_paths}
_UpperCamelCase = _PACKAGED_DATASETS_MODULES['''parquet'''][1]
_UpperCamelCase = Parquet(
cache_dir=__a , data_files=__a , features=__a , hash=__a , **__a , )
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
# Build iterable dataset
if self.streaming:
_UpperCamelCase = self.builder.as_streaming_dataset(split=self.split)
# Build regular (map-style) dataset
else:
_UpperCamelCase = None
_UpperCamelCase = None
_UpperCamelCase = None
_UpperCamelCase = None
self.builder.download_and_prepare(
download_config=__a , download_mode=__a , verification_mode=__a , base_path=__a , num_proc=self.num_proc , )
_UpperCamelCase = self.builder.as_dataset(
split=self.split , verification_mode=__a , in_memory=self.keep_in_memory)
return dataset
class _UpperCAmelCase:
def __init__( self , __a , __a , __a = None , **__a , ) -> Dict:
'''simple docstring'''
_UpperCamelCase = dataset
_UpperCamelCase = path_or_buf
_UpperCamelCase = batch_size or get_writer_batch_size(dataset.features)
_UpperCamelCase = parquet_writer_kwargs
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
_UpperCamelCase = self.batch_size if self.batch_size else config.DEFAULT_MAX_BATCH_SIZE
if isinstance(self.path_or_buf , (str, bytes, os.PathLike)):
with open(self.path_or_buf , '''wb+''') as buffer:
_UpperCamelCase = self._write(file_obj=__a , batch_size=__a , **self.parquet_writer_kwargs)
else:
_UpperCamelCase = self._write(file_obj=self.path_or_buf , batch_size=__a , **self.parquet_writer_kwargs)
return written
def UpperCAmelCase ( self , __a , __a , **__a) -> int:
'''simple docstring'''
_UpperCamelCase = 0
_UpperCamelCase = parquet_writer_kwargs.pop('''path_or_buf''' , __a)
_UpperCamelCase = self.dataset.features.arrow_schema
_UpperCamelCase = pq.ParquetWriter(__a , schema=__a , **__a)
for offset in logging.tqdm(
range(0 , len(self.dataset) , __a) , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating parquet from Arrow format''' , ):
_UpperCamelCase = query_table(
table=self.dataset._data , key=slice(__a , offset + batch_size) , indices=self.dataset._indices if self.dataset._indices is not None else None , )
writer.write_table(__a)
written += batch.nbytes
writer.close()
return written
| 78 | 0 |
"""simple docstring"""
# Lint as: python3
import dataclasses
import re
from dataclasses import dataclass
from functools import total_ordering
from typing import Optional, Union
_a = re.compile(R"""^(?P<major>\d+)""" R"""\.(?P<minor>\d+)""" R"""\.(?P<patch>\d+)$""")
@total_ordering
@dataclass
class _UpperCAmelCase:
lowercase__ = 42
lowercase__ = None
lowercase__ = None
lowercase__ = None
lowercase__ = None
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = _str_to_version_tuple(self.version_str)
def __repr__( self) -> int:
'''simple docstring'''
return F'''{self.tuple[0]}.{self.tuple[1]}.{self.tuple[2]}'''
@property
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
return self.major, self.minor, self.patch
def UpperCAmelCase ( self , __a) -> Dict:
'''simple docstring'''
if isinstance(lowercase_ , lowercase_):
return Version(lowercase_)
elif isinstance(lowercase_ , lowercase_):
return other
raise TypeError(F'''{other} (type {type(lowercase_)}) cannot be compared to version.''')
def __eq__( self , __a) -> int:
'''simple docstring'''
try:
_UpperCamelCase = self._validate_operand(lowercase_)
except (TypeError, ValueError):
return False
else:
return self.tuple == other.tuple
def __lt__( self , __a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self._validate_operand(lowercase_)
return self.tuple < other.tuple
def __hash__( self) -> str:
'''simple docstring'''
return hash(_version_tuple_to_str(self.tuple))
@classmethod
def UpperCAmelCase ( cls , __a) -> Any:
'''simple docstring'''
_UpperCamelCase = {f.name for f in dataclasses.fields(cls)}
return cls(**{k: v for k, v in dic.items() if k in field_names})
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
return self.version_str
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = _VERSION_REG.match(a__ )
if not res:
raise ValueError(F'''Invalid version \'{version_str}\'. Format should be x.y.z with {{x,y,z}} being digits.''' )
return tuple(int(a__ ) for v in [res.group('''major''' ), res.group('''minor''' ), res.group('''patch''' )] )
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
return ".".join(str(a__ ) for v in version_tuple )
| 715 |
"""simple docstring"""
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import MobileViTImageProcessor
class _UpperCAmelCase( unittest.TestCase ):
def __init__( self , __a , __a=7 , __a=3 , __a=18 , __a=30 , __a=4_00 , __a=True , __a=None , __a=True , __a=None , __a=True , ) -> int:
'''simple docstring'''
_UpperCamelCase = size if size is not None else {'''shortest_edge''': 20}
_UpperCamelCase = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}
_UpperCamelCase = parent
_UpperCamelCase = batch_size
_UpperCamelCase = num_channels
_UpperCamelCase = image_size
_UpperCamelCase = min_resolution
_UpperCamelCase = max_resolution
_UpperCamelCase = do_resize
_UpperCamelCase = size
_UpperCamelCase = do_center_crop
_UpperCamelCase = crop_size
_UpperCamelCase = do_flip_channel_order
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
return {
"do_resize": self.do_resize,
"size": self.size,
"do_center_crop": self.do_center_crop,
"crop_size": self.crop_size,
"do_flip_channel_order": self.do_flip_channel_order,
}
@require_torch
@require_vision
class _UpperCAmelCase( lowerCamelCase , unittest.TestCase ):
lowercase__ = MobileViTImageProcessor if is_vision_available() else None
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = MobileViTImageProcessingTester(self)
@property
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
return self.image_processor_tester.prepare_image_processor_dict()
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(__a , '''do_resize'''))
self.assertTrue(hasattr(__a , '''size'''))
self.assertTrue(hasattr(__a , '''do_center_crop'''))
self.assertTrue(hasattr(__a , '''center_crop'''))
self.assertTrue(hasattr(__a , '''do_flip_channel_order'''))
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.image_processing_class.from_dict(self.image_processor_dict)
self.assertEqual(image_processor.size , {'''shortest_edge''': 20})
self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18})
_UpperCamelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84)
self.assertEqual(image_processor.size , {'''shortest_edge''': 42})
self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84})
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
pass
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
# Initialize image_processing
_UpperCamelCase = self.image_processing_class(**self.image_processor_dict)
# create random PIL images
_UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a)
for image in image_inputs:
self.assertIsInstance(__a , Image.Image)
# Test not batched input
_UpperCamelCase = image_processing(image_inputs[0] , return_tensors='''pt''').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
# Test batched
_UpperCamelCase = image_processing(__a , return_tensors='''pt''').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
# Initialize image_processing
_UpperCamelCase = self.image_processing_class(**self.image_processor_dict)
# create random numpy tensors
_UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , numpify=__a)
for image in image_inputs:
self.assertIsInstance(__a , np.ndarray)
# Test not batched input
_UpperCamelCase = image_processing(image_inputs[0] , return_tensors='''pt''').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
# Test batched
_UpperCamelCase = image_processing(__a , return_tensors='''pt''').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
# Initialize image_processing
_UpperCamelCase = self.image_processing_class(**self.image_processor_dict)
# create random PyTorch tensors
_UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , torchify=__a)
for image in image_inputs:
self.assertIsInstance(__a , torch.Tensor)
# Test not batched input
_UpperCamelCase = image_processing(image_inputs[0] , return_tensors='''pt''').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
# Test batched
_UpperCamelCase = image_processing(__a , return_tensors='''pt''').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
| 78 | 0 |
"""simple docstring"""
import functools
import operator
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_a = logging.get_logger(__name__)
_a = {
"""facebook/wav2vec2-base-960h""": """https://huggingface.co/facebook/wav2vec2-base-960h/resolve/main/config.json""",
# See all Wav2Vec2 models at https://huggingface.co/models?filter=wav2vec2
}
class _UpperCAmelCase( __lowerCAmelCase ):
lowercase__ = '''wav2vec2'''
def __init__( self , __a=32 , __a=7_68 , __a=12 , __a=12 , __a=30_72 , __a="gelu" , __a=0.1 , __a=0.1 , __a=0.1 , __a=0.0 , __a=0.0 , __a=0.1 , __a=0.1 , __a=0.02 , __a=1e-5 , __a="group" , __a="gelu" , __a=(5_12, 5_12, 5_12, 5_12, 5_12, 5_12, 5_12) , __a=(5, 2, 2, 2, 2, 2, 2) , __a=(10, 3, 3, 3, 3, 2, 2) , __a=False , __a=1_28 , __a=16 , __a=False , __a=True , __a=0.05 , __a=10 , __a=2 , __a=0.0 , __a=10 , __a=0 , __a=3_20 , __a=2 , __a=0.1 , __a=1_00 , __a=2_56 , __a=2_56 , __a=0.1 , __a="sum" , __a=False , __a=False , __a=2_56 , __a=(5_12, 5_12, 5_12, 5_12, 15_00) , __a=(5, 3, 3, 1, 1) , __a=(1, 2, 3, 1, 1) , __a=5_12 , __a=0 , __a=1 , __a=2 , __a=False , __a=3 , __a=2 , __a=3 , __a=None , __a=None , **__a , ) -> Optional[Any]:
'''simple docstring'''
super().__init__(**lowerCAmelCase_ , pad_token_id=lowerCAmelCase_ , bos_token_id=lowerCAmelCase_ , eos_token_id=lowerCAmelCase_)
_UpperCamelCase = hidden_size
_UpperCamelCase = feat_extract_norm
_UpperCamelCase = feat_extract_activation
_UpperCamelCase = list(lowerCAmelCase_)
_UpperCamelCase = list(lowerCAmelCase_)
_UpperCamelCase = list(lowerCAmelCase_)
_UpperCamelCase = conv_bias
_UpperCamelCase = num_conv_pos_embeddings
_UpperCamelCase = num_conv_pos_embedding_groups
_UpperCamelCase = len(self.conv_dim)
_UpperCamelCase = num_hidden_layers
_UpperCamelCase = intermediate_size
_UpperCamelCase = hidden_act
_UpperCamelCase = num_attention_heads
_UpperCamelCase = hidden_dropout
_UpperCamelCase = attention_dropout
_UpperCamelCase = activation_dropout
_UpperCamelCase = feat_proj_dropout
_UpperCamelCase = final_dropout
_UpperCamelCase = layerdrop
_UpperCamelCase = layer_norm_eps
_UpperCamelCase = initializer_range
_UpperCamelCase = vocab_size
_UpperCamelCase = do_stable_layer_norm
_UpperCamelCase = use_weighted_layer_sum
if (
(len(self.conv_stride) != self.num_feat_extract_layers)
or (len(self.conv_kernel) != self.num_feat_extract_layers)
or (len(self.conv_dim) != self.num_feat_extract_layers)
):
raise ValueError(
'''Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =='''
''' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ='''
F''' {len(self.conv_dim)}`, `len(config.conv_stride) = {len(self.conv_stride)}`,'''
F''' `len(config.conv_kernel) = {len(self.conv_kernel)}`.''')
# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
_UpperCamelCase = apply_spec_augment
_UpperCamelCase = mask_time_prob
_UpperCamelCase = mask_time_length
_UpperCamelCase = mask_time_min_masks
_UpperCamelCase = mask_feature_prob
_UpperCamelCase = mask_feature_length
_UpperCamelCase = mask_feature_min_masks
# parameters for pretraining with codevector quantized representations
_UpperCamelCase = num_codevectors_per_group
_UpperCamelCase = num_codevector_groups
_UpperCamelCase = contrastive_logits_temperature
_UpperCamelCase = feat_quantizer_dropout
_UpperCamelCase = num_negatives
_UpperCamelCase = codevector_dim
_UpperCamelCase = proj_codevector_dim
_UpperCamelCase = diversity_loss_weight
# ctc loss
_UpperCamelCase = ctc_loss_reduction
_UpperCamelCase = ctc_zero_infinity
# adapter
_UpperCamelCase = add_adapter
_UpperCamelCase = adapter_kernel_size
_UpperCamelCase = adapter_stride
_UpperCamelCase = num_adapter_layers
_UpperCamelCase = output_hidden_size or hidden_size
_UpperCamelCase = adapter_attn_dim
# SequenceClassification-specific parameter. Feel free to ignore for other classes.
_UpperCamelCase = classifier_proj_size
# XVector-specific parameters. Feel free to ignore for other classes.
_UpperCamelCase = list(lowerCAmelCase_)
_UpperCamelCase = list(lowerCAmelCase_)
_UpperCamelCase = list(lowerCAmelCase_)
_UpperCamelCase = xvector_output_dim
@property
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
return functools.reduce(operator.mul , self.conv_stride , 1)
| 716 |
"""simple docstring"""
import warnings
from typing import List
import numpy as np
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import is_flax_available, is_tf_available, is_torch_available
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = ['image_processor', 'tokenizer']
lowercase__ = 'OwlViTImageProcessor'
lowercase__ = ('CLIPTokenizer', 'CLIPTokenizerFast')
def __init__( self , __a=None , __a=None , **__a) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = None
if "feature_extractor" in kwargs:
warnings.warn(
'''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
''' instead.''' , __a , )
_UpperCamelCase = kwargs.pop('''feature_extractor''')
_UpperCamelCase = image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError('''You need to specify an `image_processor`.''')
if tokenizer is None:
raise ValueError('''You need to specify a `tokenizer`.''')
super().__init__(__a , __a)
def __call__( self , __a=None , __a=None , __a=None , __a="max_length" , __a="np" , **__a) -> List[str]:
'''simple docstring'''
if text is None and query_images is None and images is None:
raise ValueError(
'''You have to specify at least one text or query image or image. All three cannot be none.''')
if text is not None:
if isinstance(__a , __a) or (isinstance(__a , __a) and not isinstance(text[0] , __a)):
_UpperCamelCase = [self.tokenizer(__a , padding=__a , return_tensors=__a , **__a)]
elif isinstance(__a , __a) and isinstance(text[0] , __a):
_UpperCamelCase = []
# Maximum number of queries across batch
_UpperCamelCase = max([len(__a) for t in text])
# Pad all batch samples to max number of text queries
for t in text:
if len(__a) != max_num_queries:
_UpperCamelCase = t + [''' '''] * (max_num_queries - len(__a))
_UpperCamelCase = self.tokenizer(__a , padding=__a , return_tensors=__a , **__a)
encodings.append(__a)
else:
raise TypeError('''Input text should be a string, a list of strings or a nested list of strings''')
if return_tensors == "np":
_UpperCamelCase = np.concatenate([encoding['''input_ids'''] for encoding in encodings] , axis=0)
_UpperCamelCase = np.concatenate([encoding['''attention_mask'''] for encoding in encodings] , axis=0)
elif return_tensors == "jax" and is_flax_available():
import jax.numpy as jnp
_UpperCamelCase = jnp.concatenate([encoding['''input_ids'''] for encoding in encodings] , axis=0)
_UpperCamelCase = jnp.concatenate([encoding['''attention_mask'''] for encoding in encodings] , axis=0)
elif return_tensors == "pt" and is_torch_available():
import torch
_UpperCamelCase = torch.cat([encoding['''input_ids'''] for encoding in encodings] , dim=0)
_UpperCamelCase = torch.cat([encoding['''attention_mask'''] for encoding in encodings] , dim=0)
elif return_tensors == "tf" and is_tf_available():
import tensorflow as tf
_UpperCamelCase = tf.stack([encoding['''input_ids'''] for encoding in encodings] , axis=0)
_UpperCamelCase = tf.stack([encoding['''attention_mask'''] for encoding in encodings] , axis=0)
else:
raise ValueError('''Target return tensor type could not be returned''')
_UpperCamelCase = BatchEncoding()
_UpperCamelCase = input_ids
_UpperCamelCase = attention_mask
if query_images is not None:
_UpperCamelCase = BatchEncoding()
_UpperCamelCase = self.image_processor(
__a , return_tensors=__a , **__a).pixel_values
_UpperCamelCase = query_pixel_values
if images is not None:
_UpperCamelCase = self.image_processor(__a , return_tensors=__a , **__a)
if text is not None and images is not None:
_UpperCamelCase = image_features.pixel_values
return encoding
elif query_images is not None and images is not None:
_UpperCamelCase = image_features.pixel_values
return encoding
elif text is not None or query_images is not None:
return encoding
else:
return BatchEncoding(data=dict(**__a) , tensor_type=__a)
def UpperCAmelCase ( self , *__a , **__a) -> str:
'''simple docstring'''
return self.image_processor.post_process(*__a , **__a)
def UpperCAmelCase ( self , *__a , **__a) -> Dict:
'''simple docstring'''
return self.image_processor.post_process_object_detection(*__a , **__a)
def UpperCAmelCase ( self , *__a , **__a) -> Optional[Any]:
'''simple docstring'''
return self.image_processor.post_process_image_guided_detection(*__a , **__a)
def UpperCAmelCase ( self , *__a , **__a) -> Optional[int]:
'''simple docstring'''
return self.tokenizer.batch_decode(*__a , **__a)
def UpperCAmelCase ( self , *__a , **__a) -> Optional[Any]:
'''simple docstring'''
return self.tokenizer.decode(*__a , **__a)
@property
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
warnings.warn(
'''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , __a , )
return self.image_processor_class
@property
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
warnings.warn(
'''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , __a , )
return self.image_processor
| 78 | 0 |
"""simple docstring"""
# 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 typing import TYPE_CHECKING
from ..models.auto import AutoModelForVisionaSeq
from ..utils import requires_backends
from .base import PipelineTool
if TYPE_CHECKING:
from PIL import Image
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = 'Salesforce/blip-image-captioning-base'
lowercase__ = (
'This is a tool that generates a description of an image. It takes an input named `image` which should be the '
'image to caption, and returns a text that contains the description in English.'
)
lowercase__ = 'image_captioner'
lowercase__ = AutoModelForVisionaSeq
lowercase__ = ['image']
lowercase__ = ['text']
def __init__( self , *__a , **__a) -> str:
'''simple docstring'''
requires_backends(self , ['''vision'''])
super().__init__(*UpperCAmelCase__ , **UpperCAmelCase__)
def UpperCAmelCase ( self , __a) -> int:
'''simple docstring'''
return self.pre_processor(images=UpperCAmelCase__ , return_tensors='''pt''')
def UpperCAmelCase ( self , __a) -> Tuple:
'''simple docstring'''
return self.model.generate(**UpperCAmelCase__)
def UpperCAmelCase ( self , __a) -> int:
'''simple docstring'''
return self.pre_processor.batch_decode(UpperCAmelCase__ , skip_special_tokens=UpperCAmelCase__)[0].strip()
| 717 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tokenizers_available,
is_torch_available,
is_vision_available,
)
_a = {
"""configuration_perceiver""": ["""PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """PerceiverConfig""", """PerceiverOnnxConfig"""],
"""tokenization_perceiver""": ["""PerceiverTokenizer"""],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_a = ["""PerceiverFeatureExtractor"""]
_a = ["""PerceiverImageProcessor"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_a = [
"""PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""PerceiverForImageClassificationConvProcessing""",
"""PerceiverForImageClassificationFourier""",
"""PerceiverForImageClassificationLearned""",
"""PerceiverForMaskedLM""",
"""PerceiverForMultimodalAutoencoding""",
"""PerceiverForOpticalFlow""",
"""PerceiverForSequenceClassification""",
"""PerceiverLayer""",
"""PerceiverModel""",
"""PerceiverPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_perceiver import PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP, PerceiverConfig, PerceiverOnnxConfig
from .tokenization_perceiver import PerceiverTokenizer
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_perceiver import PerceiverFeatureExtractor
from .image_processing_perceiver import PerceiverImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_perceiver import (
PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST,
PerceiverForImageClassificationConvProcessing,
PerceiverForImageClassificationFourier,
PerceiverForImageClassificationLearned,
PerceiverForMaskedLM,
PerceiverForMultimodalAutoencoding,
PerceiverForOpticalFlow,
PerceiverForSequenceClassification,
PerceiverLayer,
PerceiverModel,
PerceiverPreTrainedModel,
)
else:
import sys
_a = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 78 | 0 |
"""simple docstring"""
import tempfile
import numpy as np
import torch
from transformers import AutoTokenizer, TaEncoderModel
from diffusers import DDPMScheduler, UNetaDConditionModel
from diffusers.models.attention_processor import AttnAddedKVProcessor
from diffusers.pipelines.deepfloyd_if import IFWatermarker
from diffusers.utils.testing_utils import torch_device
from ..test_pipelines_common import to_np
class _UpperCAmelCase:
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
torch.manual_seed(0)
_UpperCamelCase = TaEncoderModel.from_pretrained('''hf-internal-testing/tiny-random-t5''')
torch.manual_seed(0)
_UpperCamelCase = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-t5''')
torch.manual_seed(0)
_UpperCamelCase = UNetaDConditionModel(
sample_size=32 , layers_per_block=1 , block_out_channels=[32, 64] , down_block_types=[
'''ResnetDownsampleBlock2D''',
'''SimpleCrossAttnDownBlock2D''',
] , mid_block_type='''UNetMidBlock2DSimpleCrossAttn''' , up_block_types=['''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''] , in_channels=3 , out_channels=6 , cross_attention_dim=32 , encoder_hid_dim=32 , attention_head_dim=8 , addition_embed_type='''text''' , addition_embed_type_num_heads=2 , cross_attention_norm='''group_norm''' , resnet_time_scale_shift='''scale_shift''' , act_fn='''gelu''' , )
unet.set_attn_processor(AttnAddedKVProcessor()) # For reproducibility tests
torch.manual_seed(0)
_UpperCamelCase = DDPMScheduler(
num_train_timesteps=10_00 , beta_schedule='''squaredcos_cap_v2''' , beta_start=0.0001 , beta_end=0.02 , thresholding=snake_case__ , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type='''epsilon''' , variance_type='''learned_range''' , )
torch.manual_seed(0)
_UpperCamelCase = IFWatermarker()
return {
"text_encoder": text_encoder,
"tokenizer": tokenizer,
"unet": unet,
"scheduler": scheduler,
"watermarker": watermarker,
"safety_checker": None,
"feature_extractor": None,
}
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
torch.manual_seed(0)
_UpperCamelCase = TaEncoderModel.from_pretrained('''hf-internal-testing/tiny-random-t5''')
torch.manual_seed(0)
_UpperCamelCase = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-t5''')
torch.manual_seed(0)
_UpperCamelCase = UNetaDConditionModel(
sample_size=32 , layers_per_block=[1, 2] , block_out_channels=[32, 64] , down_block_types=[
'''ResnetDownsampleBlock2D''',
'''SimpleCrossAttnDownBlock2D''',
] , mid_block_type='''UNetMidBlock2DSimpleCrossAttn''' , up_block_types=['''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''] , in_channels=6 , out_channels=6 , cross_attention_dim=32 , encoder_hid_dim=32 , attention_head_dim=8 , addition_embed_type='''text''' , addition_embed_type_num_heads=2 , cross_attention_norm='''group_norm''' , resnet_time_scale_shift='''scale_shift''' , act_fn='''gelu''' , class_embed_type='''timestep''' , mid_block_scale_factor=1.414 , time_embedding_act_fn='''gelu''' , time_embedding_dim=32 , )
unet.set_attn_processor(AttnAddedKVProcessor()) # For reproducibility tests
torch.manual_seed(0)
_UpperCamelCase = DDPMScheduler(
num_train_timesteps=10_00 , beta_schedule='''squaredcos_cap_v2''' , beta_start=0.0001 , beta_end=0.02 , thresholding=snake_case__ , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type='''epsilon''' , variance_type='''learned_range''' , )
torch.manual_seed(0)
_UpperCamelCase = DDPMScheduler(
num_train_timesteps=10_00 , beta_schedule='''squaredcos_cap_v2''' , beta_start=0.0001 , beta_end=0.02 , )
torch.manual_seed(0)
_UpperCamelCase = IFWatermarker()
return {
"text_encoder": text_encoder,
"tokenizer": tokenizer,
"unet": unet,
"scheduler": scheduler,
"image_noising_scheduler": image_noising_scheduler,
"watermarker": watermarker,
"safety_checker": None,
"feature_extractor": None,
}
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = self.get_dummy_components()
_UpperCamelCase = self.pipeline_class(**snake_case__)
pipe.to(snake_case__)
pipe.set_progress_bar_config(disable=snake_case__)
_UpperCamelCase = self.get_dummy_inputs(snake_case__)
_UpperCamelCase = inputs["prompt"]
_UpperCamelCase = inputs["generator"]
_UpperCamelCase = inputs["num_inference_steps"]
_UpperCamelCase = inputs["output_type"]
if "image" in inputs:
_UpperCamelCase = inputs["image"]
else:
_UpperCamelCase = None
if "mask_image" in inputs:
_UpperCamelCase = inputs["mask_image"]
else:
_UpperCamelCase = None
if "original_image" in inputs:
_UpperCamelCase = inputs["original_image"]
else:
_UpperCamelCase = None
_UpperCamelCase = pipe.encode_prompt(snake_case__)
# inputs with prompt converted to embeddings
_UpperCamelCase = {
"prompt_embeds": prompt_embeds,
"negative_prompt_embeds": negative_prompt_embeds,
"generator": generator,
"num_inference_steps": num_inference_steps,
"output_type": output_type,
}
if image is not None:
_UpperCamelCase = image
if mask_image is not None:
_UpperCamelCase = mask_image
if original_image is not None:
_UpperCamelCase = original_image
# set all optional components to None
for optional_component in pipe._optional_components:
setattr(snake_case__ , snake_case__ , snake_case__)
_UpperCamelCase = pipe(**snake_case__)[0]
with tempfile.TemporaryDirectory() as tmpdir:
pipe.save_pretrained(snake_case__)
_UpperCamelCase = self.pipeline_class.from_pretrained(snake_case__)
pipe_loaded.to(snake_case__)
pipe_loaded.set_progress_bar_config(disable=snake_case__)
pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor()) # For reproducibility tests
for optional_component in pipe._optional_components:
self.assertTrue(
getattr(snake_case__ , snake_case__) is None , F'''`{optional_component}` did not stay set to None after loading.''' , )
_UpperCamelCase = self.get_dummy_inputs(snake_case__)
_UpperCamelCase = inputs["generator"]
_UpperCamelCase = inputs["num_inference_steps"]
_UpperCamelCase = inputs["output_type"]
# inputs with prompt converted to embeddings
_UpperCamelCase = {
"prompt_embeds": prompt_embeds,
"negative_prompt_embeds": negative_prompt_embeds,
"generator": generator,
"num_inference_steps": num_inference_steps,
"output_type": output_type,
}
if image is not None:
_UpperCamelCase = image
if mask_image is not None:
_UpperCamelCase = mask_image
if original_image is not None:
_UpperCamelCase = original_image
_UpperCamelCase = pipe_loaded(**snake_case__)[0]
_UpperCamelCase = np.abs(to_np(snake_case__) - to_np(snake_case__)).max()
self.assertLess(snake_case__ , 1e-4)
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = self.get_dummy_components()
_UpperCamelCase = self.pipeline_class(**snake_case__)
pipe.to(snake_case__)
pipe.set_progress_bar_config(disable=snake_case__)
_UpperCamelCase = self.get_dummy_inputs(snake_case__)
_UpperCamelCase = pipe(**snake_case__)[0]
with tempfile.TemporaryDirectory() as tmpdir:
pipe.save_pretrained(snake_case__)
_UpperCamelCase = self.pipeline_class.from_pretrained(snake_case__)
pipe_loaded.to(snake_case__)
pipe_loaded.set_progress_bar_config(disable=snake_case__)
pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor()) # For reproducibility tests
_UpperCamelCase = self.get_dummy_inputs(snake_case__)
_UpperCamelCase = pipe_loaded(**snake_case__)[0]
_UpperCamelCase = np.abs(to_np(snake_case__) - to_np(snake_case__)).max()
self.assertLess(snake_case__ , 1e-4)
| 718 |
"""simple docstring"""
import inspect
import unittest
from huggingface_hub import hf_hub_download
from transformers import ASTConfig
from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_torchaudio_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import ASTForAudioClassification, ASTModel
from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import (
AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
)
if is_torchaudio_available():
import torchaudio
from transformers import ASTFeatureExtractor
class _UpperCAmelCase:
def __init__( self , __a , __a=13 , __a=2 , __a=24 , __a=16 , __a=True , __a=True , __a=32 , __a=5 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=10 , __a=0.02 , __a=None , __a=2 , __a=2 , ) -> List[str]:
'''simple docstring'''
_UpperCamelCase = parent
_UpperCamelCase = batch_size
_UpperCamelCase = patch_size
_UpperCamelCase = max_length
_UpperCamelCase = num_mel_bins
_UpperCamelCase = is_training
_UpperCamelCase = use_labels
_UpperCamelCase = hidden_size
_UpperCamelCase = num_hidden_layers
_UpperCamelCase = num_attention_heads
_UpperCamelCase = intermediate_size
_UpperCamelCase = hidden_act
_UpperCamelCase = hidden_dropout_prob
_UpperCamelCase = attention_probs_dropout_prob
_UpperCamelCase = type_sequence_label_size
_UpperCamelCase = initializer_range
_UpperCamelCase = scope
_UpperCamelCase = frequency_stride
_UpperCamelCase = time_stride
# in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
_UpperCamelCase = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1
_UpperCamelCase = (self.max_length - self.patch_size) // self.time_stride + 1
_UpperCamelCase = frequency_out_dimension * time_out_dimension
_UpperCamelCase = num_patches + 2
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins])
_UpperCamelCase = None
if self.use_labels:
_UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size)
_UpperCamelCase = self.get_config()
return config, input_values, labels
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
return ASTConfig(
patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__a , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , )
def UpperCAmelCase ( self , __a , __a , __a) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = ASTModel(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a)
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.prepare_config_and_inputs()
(
(
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) ,
) = config_and_inputs
_UpperCamelCase = {'''input_values''': input_values}
return config, inputs_dict
@require_torch
class _UpperCAmelCase( lowerCamelCase , lowerCamelCase , unittest.TestCase ):
lowercase__ = (
(
ASTModel,
ASTForAudioClassification,
)
if is_torch_available()
else ()
)
lowercase__ = (
{'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel}
if is_torch_available()
else {}
)
lowercase__ = False
lowercase__ = False
lowercase__ = False
lowercase__ = False
def UpperCAmelCase ( self , __a , __a , __a , __a , __a) -> Optional[Any]:
'''simple docstring'''
if pipeline_test_casse_name == "AudioClassificationPipelineTests":
return True
return False
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
_UpperCamelCase = ASTModelTester(self)
_UpperCamelCase = ConfigTester(self , config_class=__a , has_text_modality=__a , hidden_size=37)
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
self.config_tester.run_common_tests()
@unittest.skip(reason='''AST does not use inputs_embeds''')
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
pass
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_UpperCamelCase = model_class(__a)
self.assertIsInstance(model.get_input_embeddings() , (nn.Module))
_UpperCamelCase = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(__a , nn.Linear))
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_UpperCamelCase = model_class(__a)
_UpperCamelCase = inspect.signature(model.forward)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
_UpperCamelCase = [*signature.parameters.keys()]
_UpperCamelCase = ['''input_values''']
self.assertListEqual(arg_names[:1] , __a)
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__a)
@slow
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_UpperCamelCase = ASTModel.from_pretrained(__a)
self.assertIsNotNone(__a)
def lowerCamelCase__ ( ) -> List[str]:
"""simple docstring"""
_UpperCamelCase = hf_hub_download(
repo_id='''nielsr/audio-spectogram-transformer-checkpoint''', filename='''sample_audio.flac''', repo_type='''dataset''' )
_UpperCamelCase , _UpperCamelCase = torchaudio.load(__snake_case )
return audio, sampling_rate
@require_torch
@require_torchaudio
class _UpperCAmelCase( unittest.TestCase ):
@cached_property
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
return (
ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''')
if is_torchaudio_available()
else None
)
@slow
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.default_feature_extractor
_UpperCamelCase = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''').to(__a)
_UpperCamelCase = self.default_feature_extractor
_UpperCamelCase , _UpperCamelCase = prepare_audio()
_UpperCamelCase = audio.squeeze().numpy()
_UpperCamelCase = feature_extractor(__a , sampling_rate=__a , return_tensors='''pt''').to(__a)
# forward pass
with torch.no_grad():
_UpperCamelCase = model(**__a)
# verify the logits
_UpperCamelCase = torch.Size((1, 5_27))
self.assertEqual(outputs.logits.shape , __a)
_UpperCamelCase = torch.tensor([-0.8760, -7.0042, -8.6602]).to(__a)
self.assertTrue(torch.allclose(outputs.logits[0, :3] , __a , atol=1e-4))
| 78 | 0 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_torch_available,
)
_a = {
"""configuration_vision_encoder_decoder""": ["""VisionEncoderDecoderConfig""", """VisionEncoderDecoderOnnxConfig"""]
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_a = ["""VisionEncoderDecoderModel"""]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_a = ["""TFVisionEncoderDecoderModel"""]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_a = ["""FlaxVisionEncoderDecoderModel"""]
if TYPE_CHECKING:
from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel
else:
import sys
_a = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 719 |
"""simple docstring"""
def lowerCamelCase__ ( ) -> list[list[int]]:
"""simple docstring"""
return [list(range(10_00 - i, -10_00 - i, -1 ) ) for i in range(10_00 )]
_a = generate_large_matrix()
_a = (
[[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]],
[[3, 2], [1, 0]],
[[7, 7, 6]],
[[7, 7, 6], [-1, -2, -3]],
grid,
)
def lowerCamelCase__ ( __snake_case ) -> None:
"""simple docstring"""
assert all(row == sorted(__snake_case, reverse=__snake_case ) for row in grid )
assert all(list(__snake_case ) == sorted(__snake_case, reverse=__snake_case ) for col in zip(*__snake_case ) )
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = 0
_UpperCamelCase = len(__snake_case ) - 1
# Edge cases such as no values or all numbers are negative.
if not array or array[0] < 0:
return 0
while right + 1 > left:
_UpperCamelCase = (left + right) // 2
_UpperCamelCase = array[mid]
# Num must be negative and the index must be greater than or equal to 0.
if num < 0 and array[mid - 1] >= 0:
return mid
if num >= 0:
_UpperCamelCase = mid + 1
else:
_UpperCamelCase = mid - 1
# No negative numbers so return the last index of the array + 1 which is the length.
return len(__snake_case )
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = 0
_UpperCamelCase = len(grid[0] )
for i in range(len(__snake_case ) ):
_UpperCamelCase = find_negative_index(grid[i][:bound] )
total += bound
return (len(__snake_case ) * len(grid[0] )) - total
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
return len([number for row in grid for number in row if number < 0] )
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = 0
for row in grid:
for i, number in enumerate(__snake_case ):
if number < 0:
total += len(__snake_case ) - i
break
return total
def lowerCamelCase__ ( ) -> None:
"""simple docstring"""
from timeit import timeit
print('''Running benchmarks''' )
_UpperCamelCase = (
'''from __main__ import count_negatives_binary_search, '''
'''count_negatives_brute_force, count_negatives_brute_force_with_break, grid'''
)
for func in (
"count_negatives_binary_search", # took 0.7727 seconds
"count_negatives_brute_force_with_break", # took 4.6505 seconds
"count_negatives_brute_force", # took 12.8160 seconds
):
_UpperCamelCase = timeit(F'''{func}(grid=grid)''', setup=__snake_case, number=5_00 )
print(F'''{func}() took {time:0.4f} seconds''' )
if __name__ == "__main__":
import doctest
doctest.testmod()
benchmark()
| 78 | 0 |
"""simple docstring"""
from __future__ import annotations
_a = tuple[int, int, int]
_a = tuple[str, str, str]
# used alphabet --------------------------
# from string.ascii_uppercase
_a = """ABCDEFGHIJKLMNOPQRSTUVWXYZ"""
# -------------------------- default selection --------------------------
# rotors --------------------------
_a = """EGZWVONAHDCLFQMSIPJBYUKXTR"""
_a = """FOBHMDKEXQNRAULPGSJVTYICZW"""
_a = """ZJXESIUQLHAVRMDOYGTNFWPBKC"""
# reflector --------------------------
_a = {
"""A""": """N""",
"""N""": """A""",
"""B""": """O""",
"""O""": """B""",
"""C""": """P""",
"""P""": """C""",
"""D""": """Q""",
"""Q""": """D""",
"""E""": """R""",
"""R""": """E""",
"""F""": """S""",
"""S""": """F""",
"""G""": """T""",
"""T""": """G""",
"""H""": """U""",
"""U""": """H""",
"""I""": """V""",
"""V""": """I""",
"""J""": """W""",
"""W""": """J""",
"""K""": """X""",
"""X""": """K""",
"""L""": """Y""",
"""Y""": """L""",
"""M""": """Z""",
"""Z""": """M""",
}
# -------------------------- extra rotors --------------------------
_a = """RMDJXFUWGISLHVTCQNKYPBEZOA"""
_a = """SGLCPQWZHKXAREONTFBVIYJUDM"""
_a = """HVSICLTYKQUBXDWAJZOMFGPREN"""
_a = """RZWQHFMVDBKICJLNTUXAGYPSOE"""
_a = """LFKIJODBEGAMQPXVUHYSTCZRWN"""
_a = """KOAEGVDHXPQZMLFTYWJNBRCIUS"""
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> Union[str, Any]:
if (unique_rotsel := len(set(__snake_case ) )) < 3:
_UpperCamelCase = F'''Please use 3 unique rotors (not {unique_rotsel})'''
raise Exception(__snake_case )
# Checks if rotor positions are valid
_UpperCamelCase = rotpos
if not 0 < rotorposa <= len(__snake_case ):
_UpperCamelCase = F'''First rotor position is not within range of 1..26 ({rotorposa}'''
raise ValueError(__snake_case )
if not 0 < rotorposa <= len(__snake_case ):
_UpperCamelCase = F'''Second rotor position is not within range of 1..26 ({rotorposa})'''
raise ValueError(__snake_case )
if not 0 < rotorposa <= len(__snake_case ):
_UpperCamelCase = F'''Third rotor position is not within range of 1..26 ({rotorposa})'''
raise ValueError(__snake_case )
# Validates string and returns dict
_UpperCamelCase = _plugboard(__snake_case )
return rotpos, rotsel, pbdict
def lowerCamelCase__ ( __snake_case ) -> Any:
if not isinstance(__snake_case, __snake_case ):
_UpperCamelCase = F'''Plugboard setting isn\'t type string ({type(__snake_case )})'''
raise TypeError(__snake_case )
elif len(__snake_case ) % 2 != 0:
_UpperCamelCase = F'''Odd number of symbols ({len(__snake_case )})'''
raise Exception(__snake_case )
elif pbstring == "":
return {}
pbstring.replace(''' ''', '''''' )
# Checks if all characters are unique
_UpperCamelCase = set()
for i in pbstring:
if i not in abc:
_UpperCamelCase = F'''\'{i}\' not in list of symbols'''
raise Exception(__snake_case )
elif i in tmppbl:
_UpperCamelCase = F'''Duplicate symbol ({i})'''
raise Exception(__snake_case )
else:
tmppbl.add(__snake_case )
del tmppbl
# Created the dictionary
_UpperCamelCase = {}
for j in range(0, len(__snake_case ) - 1, 2 ):
_UpperCamelCase = pbstring[j + 1]
_UpperCamelCase = pbstring[j]
return pb
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case = (rotora, rotora, rotora), __snake_case = "", ) -> Tuple:
_UpperCamelCase = text.upper()
_UpperCamelCase = _validator(
__snake_case, __snake_case, plugb.upper() )
_UpperCamelCase = rotor_position
_UpperCamelCase = rotor_selection
rotorposa -= 1
rotorposa -= 1
rotorposa -= 1
_UpperCamelCase = []
# encryption/decryption process --------------------------
for symbol in text:
if symbol in abc:
# 1st plugboard --------------------------
if symbol in plugboard:
_UpperCamelCase = plugboard[symbol]
# rotor ra --------------------------
_UpperCamelCase = abc.index(__snake_case ) + rotorposa
_UpperCamelCase = rotora[index % len(__snake_case )]
# rotor rb --------------------------
_UpperCamelCase = abc.index(__snake_case ) + rotorposa
_UpperCamelCase = rotora[index % len(__snake_case )]
# rotor rc --------------------------
_UpperCamelCase = abc.index(__snake_case ) + rotorposa
_UpperCamelCase = rotora[index % len(__snake_case )]
# reflector --------------------------
# this is the reason you don't need another machine to decipher
_UpperCamelCase = reflector[symbol]
# 2nd rotors
_UpperCamelCase = abc[rotora.index(__snake_case ) - rotorposa]
_UpperCamelCase = abc[rotora.index(__snake_case ) - rotorposa]
_UpperCamelCase = abc[rotora.index(__snake_case ) - rotorposa]
# 2nd plugboard
if symbol in plugboard:
_UpperCamelCase = plugboard[symbol]
# moves/resets rotor positions
rotorposa += 1
if rotorposa >= len(__snake_case ):
_UpperCamelCase = 0
rotorposa += 1
if rotorposa >= len(__snake_case ):
_UpperCamelCase = 0
rotorposa += 1
if rotorposa >= len(__snake_case ):
_UpperCamelCase = 0
# else:
# pass
# Error could be also raised
# raise ValueError(
# 'Invalid symbol('+repr(symbol)+')')
result.append(__snake_case )
return "".join(__snake_case )
if __name__ == "__main__":
_a = """This is my Python script that emulates the Enigma machine from WWII."""
_a = (1, 1, 1)
_a = """pictures"""
_a = (rotora, rotora, rotora)
_a = enigma(message, rotor_pos, rotor_sel, pb)
print("""Encrypted message:""", en)
print("""Decrypted message:""", enigma(en, rotor_pos, rotor_sel, pb))
| 720 |
"""simple docstring"""
import copy
import re
class _UpperCAmelCase:
lowercase__ = 'hp'
lowercase__ = {}
lowercase__ = None
@classmethod
def UpperCAmelCase ( cls , __a , __a) -> Dict:
'''simple docstring'''
_UpperCamelCase = prefix
_UpperCamelCase = defaults
cls.build_naming_info()
@staticmethod
def UpperCAmelCase ( __a , __a) -> Union[str, Any]:
'''simple docstring'''
if len(__a) == 0:
return ""
_UpperCamelCase = None
if any(char.isdigit() for char in word):
raise Exception(F'''Parameters should not contain numbers: \'{word}\' contains a number''')
if word in info["short_word"]:
return info["short_word"][word]
for prefix_len in range(1 , len(__a) + 1):
_UpperCamelCase = word[:prefix_len]
if prefix in info["reverse_short_word"]:
continue
else:
_UpperCamelCase = prefix
break
if short_word is None:
# Paranoid fallback
def int_to_alphabetic(__a):
_UpperCamelCase = ''''''
while integer != 0:
_UpperCamelCase = chr(ord('''A''') + integer % 10) + s
integer //= 10
return s
_UpperCamelCase = 0
while True:
_UpperCamelCase = word + '''#''' + int_to_alphabetic(__a)
if sword in info["reverse_short_word"]:
continue
else:
_UpperCamelCase = sword
break
_UpperCamelCase = short_word
_UpperCamelCase = word
return short_word
@staticmethod
def UpperCAmelCase ( __a , __a) -> Any:
'''simple docstring'''
_UpperCamelCase = param_name.split('''_''')
_UpperCamelCase = [TrialShortNamer.shortname_for_word(__a , __a) for word in words]
# We try to create a separatorless short name, but if there is a collision we have to fallback
# to a separated short name
_UpperCamelCase = ['''''', '''_''']
for separator in separators:
_UpperCamelCase = separator.join(__a)
if shortname not in info["reverse_short_param"]:
_UpperCamelCase = shortname
_UpperCamelCase = param_name
return shortname
return param_name
@staticmethod
def UpperCAmelCase ( __a , __a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = TrialShortNamer.shortname_for_key(__a , __a)
_UpperCamelCase = short_name
_UpperCamelCase = param_name
@classmethod
def UpperCAmelCase ( cls) -> Any:
'''simple docstring'''
if cls.NAMING_INFO is not None:
return
_UpperCamelCase = {
'''short_word''': {},
'''reverse_short_word''': {},
'''short_param''': {},
'''reverse_short_param''': {},
}
_UpperCamelCase = list(cls.DEFAULTS.keys())
for k in field_keys:
cls.add_new_param_name(__a , __a)
_UpperCamelCase = info
@classmethod
def UpperCAmelCase ( cls , __a) -> Optional[Any]:
'''simple docstring'''
cls.build_naming_info()
assert cls.PREFIX is not None
_UpperCamelCase = [copy.copy(cls.PREFIX)]
for k, v in params.items():
if k not in cls.DEFAULTS:
raise Exception(F'''You should provide a default value for the param name {k} with value {v}''')
if v == cls.DEFAULTS[k]:
# The default value is not added to the name
continue
_UpperCamelCase = cls.NAMING_INFO['''short_param'''][k]
if isinstance(__a , __a):
_UpperCamelCase = 1 if v else 0
_UpperCamelCase = '''''' if isinstance(__a , (int, float)) else '''-'''
_UpperCamelCase = F'''{key}{sep}{v}'''
name.append(__a)
return "_".join(__a)
@classmethod
def UpperCAmelCase ( cls , __a) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = repr[len(cls.PREFIX) + 1 :]
if repr == "":
_UpperCamelCase = []
else:
_UpperCamelCase = repr.split('''_''')
_UpperCamelCase = {}
for value in values:
if "-" in value:
_UpperCamelCase , _UpperCamelCase = value.split('''-''')
else:
_UpperCamelCase = re.sub('''[0-9.]''' , '''''' , __a)
_UpperCamelCase = float(re.sub('''[^0-9.]''' , '''''' , __a))
_UpperCamelCase = cls.NAMING_INFO['''reverse_short_param'''][p_k]
_UpperCamelCase = p_v
for k in cls.DEFAULTS:
if k not in parameters:
_UpperCamelCase = cls.DEFAULTS[k]
return parameters
| 78 | 0 |
"""simple docstring"""
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
_a = 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 lowerCamelCase__ ( __snake_case, __snake_case ) -> Tuple:
"""simple docstring"""
return (abs(source - target ) / target) < 0.01
@pytest.mark.integration
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = _TestCommandArgs(dataset=__snake_case, all_configs=__snake_case, save_infos=__snake_case )
_UpperCamelCase = TestCommand(*__snake_case )
test_command.run()
_UpperCamelCase = os.path.join(__snake_case, '''README.md''' )
assert os.path.exists(__snake_case )
_UpperCamelCase = DatasetInfosDict.from_directory(__snake_case )
_UpperCamelCase = 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''': 2_35_15_63,
'''num_examples''': 1_00_00,
},
{
'''name''': '''validation''',
'''num_bytes''': 23_84_18,
'''num_examples''': 10_00,
},
], download_size=3_94_06_80, dataset_size=2_58_99_81, )
} )
assert dataset_infos.keys() == expected_dataset_infos.keys()
for key in DatasetInfo._INCLUDED_INFO_IN_YAML:
_UpperCamelCase = getattr(dataset_infos['''default'''], __snake_case ), getattr(expected_dataset_infos['''default'''], __snake_case )
if key == "num_bytes":
assert is_apercent_close(__snake_case, __snake_case )
elif key == "splits":
assert list(__snake_case ) == list(__snake_case )
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
| 721 |
"""simple docstring"""
import os
import time
import pytest
from datasets.utils.filelock import FileLock, Timeout
def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]:
"""simple docstring"""
_UpperCamelCase = FileLock(str(tmpdir / '''foo.lock''' ) )
_UpperCamelCase = FileLock(str(tmpdir / '''foo.lock''' ) )
_UpperCamelCase = 0.01
with locka.acquire():
with pytest.raises(__snake_case ):
_UpperCamelCase = time.time()
locka.acquire(__snake_case )
assert time.time() - _start > timeout
def lowerCamelCase__ ( __snake_case ) -> List[Any]:
"""simple docstring"""
_UpperCamelCase = '''a''' * 10_00 + '''.lock'''
_UpperCamelCase = FileLock(str(tmpdir / filename ) )
assert locka._lock_file.endswith('''.lock''' )
assert not locka._lock_file.endswith(__snake_case )
assert len(os.path.basename(locka._lock_file ) ) <= 2_55
_UpperCamelCase = FileLock(tmpdir / filename )
with locka.acquire():
with pytest.raises(__snake_case ):
locka.acquire(0 )
| 78 | 0 |
"""simple docstring"""
import logging
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union
from filelock import FileLock
from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available
_a = logging.getLogger(__name__)
@dataclass
class _UpperCAmelCase:
lowercase__ = 42
lowercase__ = 42
lowercase__ = 42
@dataclass
class _UpperCAmelCase:
lowercase__ = 42
lowercase__ = 42
lowercase__ = None
lowercase__ = None
class _UpperCAmelCase( __UpperCAmelCase ):
lowercase__ = "train"
lowercase__ = "dev"
lowercase__ = "test"
class _UpperCAmelCase:
@staticmethod
def UpperCAmelCase ( __a , __a) -> List[Any]:
'''simple docstring'''
raise NotImplementedError
@staticmethod
def UpperCAmelCase ( __a) -> Tuple:
'''simple docstring'''
raise NotImplementedError
@staticmethod
def UpperCAmelCase ( __a , __a , __a , __a , __a=False , __a="[CLS]" , __a=1 , __a="[SEP]" , __a=False , __a=False , __a=0 , __a=0 , __a=-1_00 , __a=0 , __a=True , ) -> Any:
'''simple docstring'''
_UpperCamelCase = {label: i for i, label in enumerate(_lowerCamelCase)}
_UpperCamelCase = []
for ex_index, example in enumerate(_lowerCamelCase):
if ex_index % 1_00_00 == 0:
logger.info('''Writing example %d of %d''' , _lowerCamelCase , len(_lowerCamelCase))
_UpperCamelCase = []
_UpperCamelCase = []
for word, label in zip(example.words , example.labels):
_UpperCamelCase = tokenizer.tokenize(_lowerCamelCase)
# bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space.
if len(_lowerCamelCase) > 0:
tokens.extend(_lowerCamelCase)
# Use the real label id for the first token of the word, and padding ids for the remaining tokens
label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(_lowerCamelCase) - 1))
# Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa.
_UpperCamelCase = tokenizer.num_special_tokens_to_add()
if len(_lowerCamelCase) > max_seq_length - special_tokens_count:
_UpperCamelCase = tokens[: (max_seq_length - special_tokens_count)]
_UpperCamelCase = label_ids[: (max_seq_length - special_tokens_count)]
# The convention in BERT is:
# (a) For sequence pairs:
# tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
# type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
# (b) For single sequences:
# tokens: [CLS] the dog is hairy . [SEP]
# type_ids: 0 0 0 0 0 0 0
#
# Where "type_ids" are used to indicate whether this is the first
# sequence or the second sequence. The embedding vectors for `type=0` and
# `type=1` were learned during pre-training and are added to the wordpiece
# embedding vector (and position vector). This is not *strictly* necessary
# since the [SEP] token unambiguously separates the sequences, but it makes
# it easier for the model to learn the concept of sequences.
#
# For classification tasks, the first vector (corresponding to [CLS]) is
# used as the "sentence vector". Note that this only makes sense because
# the entire model is fine-tuned.
tokens += [sep_token]
label_ids += [pad_token_label_id]
if sep_token_extra:
# roberta uses an extra separator b/w pairs of sentences
tokens += [sep_token]
label_ids += [pad_token_label_id]
_UpperCamelCase = [sequence_a_segment_id] * len(_lowerCamelCase)
if cls_token_at_end:
tokens += [cls_token]
label_ids += [pad_token_label_id]
segment_ids += [cls_token_segment_id]
else:
_UpperCamelCase = [cls_token] + tokens
_UpperCamelCase = [pad_token_label_id] + label_ids
_UpperCamelCase = [cls_token_segment_id] + segment_ids
_UpperCamelCase = tokenizer.convert_tokens_to_ids(_lowerCamelCase)
# The mask has 1 for real tokens and 0 for padding tokens. Only real
# tokens are attended to.
_UpperCamelCase = [1 if mask_padding_with_zero else 0] * len(_lowerCamelCase)
# Zero-pad up to the sequence length.
_UpperCamelCase = max_seq_length - len(_lowerCamelCase)
if pad_on_left:
_UpperCamelCase = ([pad_token] * padding_length) + input_ids
_UpperCamelCase = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask
_UpperCamelCase = ([pad_token_segment_id] * padding_length) + segment_ids
_UpperCamelCase = ([pad_token_label_id] * padding_length) + label_ids
else:
input_ids += [pad_token] * padding_length
input_mask += [0 if mask_padding_with_zero else 1] * padding_length
segment_ids += [pad_token_segment_id] * padding_length
label_ids += [pad_token_label_id] * padding_length
assert len(_lowerCamelCase) == max_seq_length
assert len(_lowerCamelCase) == max_seq_length
assert len(_lowerCamelCase) == max_seq_length
assert len(_lowerCamelCase) == max_seq_length
if ex_index < 5:
logger.info('''*** Example ***''')
logger.info('''guid: %s''' , example.guid)
logger.info('''tokens: %s''' , ''' '''.join([str(_lowerCamelCase) for x in tokens]))
logger.info('''input_ids: %s''' , ''' '''.join([str(_lowerCamelCase) for x in input_ids]))
logger.info('''input_mask: %s''' , ''' '''.join([str(_lowerCamelCase) for x in input_mask]))
logger.info('''segment_ids: %s''' , ''' '''.join([str(_lowerCamelCase) for x in segment_ids]))
logger.info('''label_ids: %s''' , ''' '''.join([str(_lowerCamelCase) for x in label_ids]))
if "token_type_ids" not in tokenizer.model_input_names:
_UpperCamelCase = None
features.append(
InputFeatures(
input_ids=_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , label_ids=_lowerCamelCase))
return features
if is_torch_available():
import torch
from torch import nn
from torch.utils.data import Dataset
class _UpperCAmelCase( __UpperCAmelCase ):
lowercase__ = 42
lowercase__ = nn.CrossEntropyLoss().ignore_index
def __init__( self , __a , __a , __a , __a , __a , __a = None , __a=False , __a = Split.train , ) -> Any:
'''simple docstring'''
# Load data features from cache or dataset file
_UpperCamelCase = os.path.join(
_lowerCamelCase , '''cached_{}_{}_{}'''.format(mode.value , tokenizer.__class__.__name__ , str(_lowerCamelCase)) , )
# Make sure only the first process in distributed training processes the dataset,
# and the others will use the cache.
_UpperCamelCase = cached_features_file + '''.lock'''
with FileLock(_lowerCamelCase):
if os.path.exists(_lowerCamelCase) and not overwrite_cache:
logger.info(F'''Loading features from cached file {cached_features_file}''')
_UpperCamelCase = torch.load(_lowerCamelCase)
else:
logger.info(F'''Creating features from dataset file at {data_dir}''')
_UpperCamelCase = token_classification_task.read_examples_from_file(_lowerCamelCase , _lowerCamelCase)
# TODO clean up all this to leverage built-in features of tokenizers
_UpperCamelCase = token_classification_task.convert_examples_to_features(
_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , cls_token_at_end=bool(model_type in ['''xlnet''']) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=_lowerCamelCase , pad_on_left=bool(tokenizer.padding_side == '''left''') , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , )
logger.info(F'''Saving features into cached file {cached_features_file}''')
torch.save(self.features , _lowerCamelCase)
def __len__( self) -> Optional[Any]:
'''simple docstring'''
return len(self.features)
def __getitem__( self , __a) -> Optional[int]:
'''simple docstring'''
return self.features[i]
if is_tf_available():
import tensorflow as tf
class _UpperCAmelCase:
lowercase__ = 42
lowercase__ = -1_00
def __init__( self , __a , __a , __a , __a , __a , __a = None , __a=False , __a = Split.train , ) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = token_classification_task.read_examples_from_file(_lowerCamelCase , _lowerCamelCase)
# TODO clean up all this to leverage built-in features of tokenizers
_UpperCamelCase = token_classification_task.convert_examples_to_features(
_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , cls_token_at_end=bool(model_type in ['''xlnet''']) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=_lowerCamelCase , pad_on_left=bool(tokenizer.padding_side == '''left''') , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , )
def gen():
for ex in self.features:
if ex.token_type_ids is None:
yield (
{"input_ids": ex.input_ids, "attention_mask": ex.attention_mask},
ex.label_ids,
)
else:
yield (
{
"input_ids": ex.input_ids,
"attention_mask": ex.attention_mask,
"token_type_ids": ex.token_type_ids,
},
ex.label_ids,
)
if "token_type_ids" not in tokenizer.model_input_names:
_UpperCamelCase = tf.data.Dataset.from_generator(
_lowerCamelCase , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa}, tf.intaa) , (
{'''input_ids''': tf.TensorShape([None]), '''attention_mask''': tf.TensorShape([None])},
tf.TensorShape([None]),
) , )
else:
_UpperCamelCase = tf.data.Dataset.from_generator(
_lowerCamelCase , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa}, tf.intaa) , (
{
'''input_ids''': tf.TensorShape([None]),
'''attention_mask''': tf.TensorShape([None]),
'''token_type_ids''': tf.TensorShape([None]),
},
tf.TensorShape([None]),
) , )
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features)))
return self.dataset
def __len__( self) -> List[str]:
'''simple docstring'''
return len(self.features)
def __getitem__( self , __a) -> Dict:
'''simple docstring'''
return self.features[i]
| 700 |
"""simple docstring"""
from math import sqrt
def lowerCamelCase__ ( __snake_case ) -> bool:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (
number >= 0
), "'number' must been an int and positive"
_UpperCamelCase = True
# 0 and 1 are none primes.
if number <= 1:
_UpperCamelCase = False
for divisor in range(2, int(round(sqrt(__snake_case ) ) ) + 1 ):
# if 'number' divisible by 'divisor' then sets 'status'
# of false and break up the loop.
if number % divisor == 0:
_UpperCamelCase = False
break
# precondition
assert isinstance(__snake_case, __snake_case ), "'status' must been from type bool"
return status
def lowerCamelCase__ ( __snake_case ) -> Dict:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n > 2), "'N' must been an int and > 2"
# beginList: contains all natural numbers from 2 up to N
_UpperCamelCase = list(range(2, n + 1 ) )
_UpperCamelCase = [] # this list will be returns.
# actual sieve of erathostenes
for i in range(len(__snake_case ) ):
for j in range(i + 1, len(__snake_case ) ):
if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0):
_UpperCamelCase = 0
# filters actual prime numbers.
_UpperCamelCase = [x for x in begin_list if x != 0]
# precondition
assert isinstance(__snake_case, __snake_case ), "'ans' must been from type list"
return ans
def lowerCamelCase__ ( __snake_case ) -> List[str]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n > 2), "'N' must been an int and > 2"
_UpperCamelCase = []
# iterates over all numbers between 2 up to N+1
# if a number is prime then appends to list 'ans'
for number in range(2, n + 1 ):
if is_prime(__snake_case ):
ans.append(__snake_case )
# precondition
assert isinstance(__snake_case, __snake_case ), "'ans' must been from type list"
return ans
def lowerCamelCase__ ( __snake_case ) -> Optional[int]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and number >= 0, "'number' must been an int and >= 0"
_UpperCamelCase = [] # this list will be returns of the function.
# potential prime number factors.
_UpperCamelCase = 2
_UpperCamelCase = number
if number == 0 or number == 1:
ans.append(__snake_case )
# if 'number' not prime then builds the prime factorization of 'number'
elif not is_prime(__snake_case ):
while quotient != 1:
if is_prime(__snake_case ) and (quotient % factor == 0):
ans.append(__snake_case )
quotient /= factor
else:
factor += 1
else:
ans.append(__snake_case )
# precondition
assert isinstance(__snake_case, __snake_case ), "'ans' must been from type list"
return ans
def lowerCamelCase__ ( __snake_case ) -> Optional[Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (
number >= 0
), "'number' bust been an int and >= 0"
_UpperCamelCase = 0
# prime factorization of 'number'
_UpperCamelCase = prime_factorization(__snake_case )
_UpperCamelCase = max(__snake_case )
# precondition
assert isinstance(__snake_case, __snake_case ), "'ans' must been from type int"
return ans
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (
number >= 0
), "'number' bust been an int and >= 0"
_UpperCamelCase = 0
# prime factorization of 'number'
_UpperCamelCase = prime_factorization(__snake_case )
_UpperCamelCase = min(__snake_case )
# precondition
assert isinstance(__snake_case, __snake_case ), "'ans' must been from type int"
return ans
def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ), "'number' must been an int"
assert isinstance(number % 2 == 0, __snake_case ), "compare bust been from type bool"
return number % 2 == 0
def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ), "'number' must been an int"
assert isinstance(number % 2 != 0, __snake_case ), "compare bust been from type bool"
return number % 2 != 0
def lowerCamelCase__ ( __snake_case ) -> str:
"""simple docstring"""
assert (
isinstance(__snake_case, __snake_case ) and (number > 2) and is_even(__snake_case )
), "'number' must been an int, even and > 2"
_UpperCamelCase = [] # this list will returned
# creates a list of prime numbers between 2 up to 'number'
_UpperCamelCase = get_prime_numbers(__snake_case )
_UpperCamelCase = len(__snake_case )
# run variable for while-loops.
_UpperCamelCase = 0
_UpperCamelCase = None
# exit variable. for break up the loops
_UpperCamelCase = True
while i < len_pn and loop:
_UpperCamelCase = i + 1
while j < len_pn and loop:
if prime_numbers[i] + prime_numbers[j] == number:
_UpperCamelCase = False
ans.append(prime_numbers[i] )
ans.append(prime_numbers[j] )
j += 1
i += 1
# precondition
assert (
isinstance(__snake_case, __snake_case )
and (len(__snake_case ) == 2)
and (ans[0] + ans[1] == number)
and is_prime(ans[0] )
and is_prime(ans[1] )
), "'ans' must contains two primes. And sum of elements must been eq 'number'"
return ans
def lowerCamelCase__ ( __snake_case, __snake_case ) -> str:
"""simple docstring"""
assert (
isinstance(__snake_case, __snake_case )
and isinstance(__snake_case, __snake_case )
and (numbera >= 0)
and (numbera >= 0)
), "'number1' and 'number2' must been positive integer."
_UpperCamelCase = 0
while numbera != 0:
_UpperCamelCase = numbera % numbera
_UpperCamelCase = numbera
_UpperCamelCase = rest
# precondition
assert isinstance(__snake_case, __snake_case ) and (
numbera >= 0
), "'number' must been from type int and positive"
return numbera
def lowerCamelCase__ ( __snake_case, __snake_case ) -> List[str]:
"""simple docstring"""
assert (
isinstance(__snake_case, __snake_case )
and isinstance(__snake_case, __snake_case )
and (numbera >= 1)
and (numbera >= 1)
), "'number1' and 'number2' must been positive integer."
_UpperCamelCase = 1 # actual answer that will be return.
# for kgV (x,1)
if numbera > 1 and numbera > 1:
# builds the prime factorization of 'number1' and 'number2'
_UpperCamelCase = prime_factorization(__snake_case )
_UpperCamelCase = prime_factorization(__snake_case )
elif numbera == 1 or numbera == 1:
_UpperCamelCase = []
_UpperCamelCase = []
_UpperCamelCase = max(__snake_case, __snake_case )
_UpperCamelCase = 0
_UpperCamelCase = 0
_UpperCamelCase = [] # captured numbers int both 'primeFac1' and 'primeFac2'
# iterates through primeFac1
for n in prime_fac_a:
if n not in done:
if n in prime_fac_a:
_UpperCamelCase = prime_fac_a.count(__snake_case )
_UpperCamelCase = prime_fac_a.count(__snake_case )
for _ in range(max(__snake_case, __snake_case ) ):
ans *= n
else:
_UpperCamelCase = prime_fac_a.count(__snake_case )
for _ in range(__snake_case ):
ans *= n
done.append(__snake_case )
# iterates through primeFac2
for n in prime_fac_a:
if n not in done:
_UpperCamelCase = prime_fac_a.count(__snake_case )
for _ in range(__snake_case ):
ans *= n
done.append(__snake_case )
# precondition
assert isinstance(__snake_case, __snake_case ) and (
ans >= 0
), "'ans' must been from type int and positive"
return ans
def lowerCamelCase__ ( __snake_case ) -> Tuple:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n >= 0), "'number' must been a positive int"
_UpperCamelCase = 0
_UpperCamelCase = 2 # this variable holds the answer
while index < n:
index += 1
ans += 1 # counts to the next number
# if ans not prime then
# runs to the next prime number.
while not is_prime(__snake_case ):
ans += 1
# precondition
assert isinstance(__snake_case, __snake_case ) and is_prime(
__snake_case ), "'ans' must been a prime number and from type int"
return ans
def lowerCamelCase__ ( __snake_case, __snake_case ) -> Tuple:
"""simple docstring"""
assert (
is_prime(__snake_case ) and is_prime(__snake_case ) and (p_number_a < p_number_a)
), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'"
_UpperCamelCase = p_number_a + 1 # jump to the next number
_UpperCamelCase = [] # this list will be returns.
# if number is not prime then
# fetch the next prime number.
while not is_prime(__snake_case ):
number += 1
while number < p_number_a:
ans.append(__snake_case )
number += 1
# fetch the next prime number.
while not is_prime(__snake_case ):
number += 1
# precondition
assert (
isinstance(__snake_case, __snake_case )
and ans[0] != p_number_a
and ans[len(__snake_case ) - 1] != p_number_a
), "'ans' must been a list without the arguments"
# 'ans' contains not 'pNumber1' and 'pNumber2' !
return ans
def lowerCamelCase__ ( __snake_case ) -> List[Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n >= 1), "'n' must been int and >= 1"
_UpperCamelCase = [] # will be returned.
for divisor in range(1, n + 1 ):
if n % divisor == 0:
ans.append(__snake_case )
# precondition
assert ans[0] == 1 and ans[len(__snake_case ) - 1] == n, "Error in function getDivisiors(...)"
return ans
def lowerCamelCase__ ( __snake_case ) -> str:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (
number > 1
), "'number' must been an int and >= 1"
_UpperCamelCase = get_divisors(__snake_case )
# precondition
assert (
isinstance(__snake_case, __snake_case )
and (divisors[0] == 1)
and (divisors[len(__snake_case ) - 1] == number)
), "Error in help-function getDivisiors(...)"
# summed all divisors up to 'number' (exclusive), hence [:-1]
return sum(divisors[:-1] ) == number
def lowerCamelCase__ ( __snake_case, __snake_case ) -> Optional[Any]:
"""simple docstring"""
assert (
isinstance(__snake_case, __snake_case )
and isinstance(__snake_case, __snake_case )
and (denominator != 0)
), "The arguments must been from type int and 'denominator' != 0"
# build the greatest common divisor of numerator and denominator.
_UpperCamelCase = gcd(abs(__snake_case ), abs(__snake_case ) )
# precondition
assert (
isinstance(__snake_case, __snake_case )
and (numerator % gcd_of_fraction == 0)
and (denominator % gcd_of_fraction == 0)
), "Error in function gcd(...,...)"
return (numerator // gcd_of_fraction, denominator // gcd_of_fraction)
def lowerCamelCase__ ( __snake_case ) -> Optional[Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n >= 0), "'n' must been a int and >= 0"
_UpperCamelCase = 1 # this will be return.
for factor in range(1, n + 1 ):
ans *= factor
return ans
def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n >= 0), "'n' must been an int and >= 0"
_UpperCamelCase = 0
_UpperCamelCase = 1
_UpperCamelCase = 1 # this will be return
for _ in range(n - 1 ):
_UpperCamelCase = ans
ans += fiba
_UpperCamelCase = tmp
return ans
| 78 | 0 |
"""simple docstring"""
from __future__ import annotations
_a = list[list[int]]
# assigning initial values to the grid
_a = [
[3, 0, 6, 5, 0, 8, 4, 0, 0],
[5, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 8, 7, 0, 0, 0, 0, 3, 1],
[0, 0, 3, 0, 1, 0, 0, 8, 0],
[9, 0, 0, 8, 6, 3, 0, 0, 5],
[0, 5, 0, 0, 9, 0, 6, 0, 0],
[1, 3, 0, 0, 0, 0, 2, 5, 0],
[0, 0, 0, 0, 0, 0, 0, 7, 4],
[0, 0, 5, 2, 0, 6, 3, 0, 0],
]
# a grid with no solution
_a = [
[5, 0, 6, 5, 0, 8, 4, 0, 3],
[5, 2, 0, 0, 0, 0, 0, 0, 2],
[1, 8, 7, 0, 0, 0, 0, 3, 1],
[0, 0, 3, 0, 1, 0, 0, 8, 0],
[9, 0, 0, 8, 6, 3, 0, 0, 5],
[0, 5, 0, 0, 9, 0, 6, 0, 0],
[1, 3, 0, 0, 0, 0, 2, 5, 0],
[0, 0, 0, 0, 0, 0, 0, 7, 4],
[0, 0, 5, 2, 0, 6, 3, 0, 0],
]
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case, __snake_case ) -> int:
"""simple docstring"""
for i in range(9 ):
if grid[row][i] == n or grid[i][column] == n:
return False
for i in range(3 ):
for j in range(3 ):
if grid[(row - row % 3) + i][(column - column % 3) + j] == n:
return False
return True
def lowerCamelCase__ ( __snake_case ) -> str:
"""simple docstring"""
for i in range(9 ):
for j in range(9 ):
if grid[i][j] == 0:
return i, j
return None
def lowerCamelCase__ ( __snake_case ) -> Optional[int]:
"""simple docstring"""
if location := find_empty_location(lowerCamelCase_ ):
_UpperCamelCase = location
else:
# If the location is ``None``, then the grid is solved.
return grid
for digit in range(1, 10 ):
if is_safe(lowerCamelCase_, lowerCamelCase_, lowerCamelCase_, lowerCamelCase_ ):
_UpperCamelCase = digit
if sudoku(lowerCamelCase_ ) is not None:
return grid
_UpperCamelCase = 0
return None
def lowerCamelCase__ ( __snake_case ) -> Dict:
"""simple docstring"""
for row in grid:
for cell in row:
print(lowerCamelCase_, end=''' ''' )
print()
if __name__ == "__main__":
# make a copy of grid so that you can compare with the unmodified grid
for example_grid in (initial_grid, no_solution):
print("""\nExample grid:\n""" + """=""" * 20)
print_solution(example_grid)
print("""\nExample grid solution:""")
_a = sudoku(example_grid)
if solution is not None:
print_solution(solution)
else:
print("""Cannot find a solution.""")
| 701 |
"""simple docstring"""
import logging
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional, Union
from .generation.configuration_utils import GenerationConfig
from .training_args import TrainingArguments
from .utils import add_start_docstrings
_a = logging.getLogger(__name__)
@dataclass
@add_start_docstrings(TrainingArguments.__doc__ )
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = field(default=lowerCamelCase , metadata={'help': 'Whether to use SortishSampler or not.'} )
lowercase__ = field(
default=lowerCamelCase , metadata={'help': 'Whether to use generate to calculate generative metrics (ROUGE, BLEU).'} )
lowercase__ = field(
default=lowerCamelCase , metadata={
'help': (
'The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default '
'to the `max_length` value of the model configuration.'
)
} , )
lowercase__ = field(
default=lowerCamelCase , metadata={
'help': (
'The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default '
'to the `num_beams` value of the model configuration.'
)
} , )
lowercase__ = field(
default=lowerCamelCase , metadata={
'help': 'Model id, file path or url pointing to a GenerationConfig json file, to use during prediction.'
} , )
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = super().to_dict()
for k, v in d.items():
if isinstance(__a , __a):
_UpperCamelCase = v.to_dict()
return d
| 78 | 0 |
"""simple docstring"""
import numpy as np
from matplotlib import pyplot as plt
from sklearn import datasets
def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]:
"""simple docstring"""
return 1 / (1 + np.exp(-z ))
def lowerCamelCase__ ( __snake_case, __snake_case ) -> Tuple:
"""simple docstring"""
return (-y * np.log(UpperCamelCase__ ) - (1 - y) * np.log(1 - h )).mean()
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> Optional[int]:
"""simple docstring"""
_UpperCamelCase = np.dot(UpperCamelCase__, UpperCamelCase__ )
return np.sum(y * scores - np.log(1 + np.exp(UpperCamelCase__ ) ) )
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case, __snake_case=7_00_00 ) -> Union[str, Any]:
"""simple docstring"""
_UpperCamelCase = np.zeros(x.shape[1] )
for iterations in range(UpperCamelCase__ ):
_UpperCamelCase = np.dot(UpperCamelCase__, UpperCamelCase__ )
_UpperCamelCase = sigmoid_function(UpperCamelCase__ )
_UpperCamelCase = np.dot(x.T, h - y ) / y.size
_UpperCamelCase = theta - alpha * gradient # updating the weights
_UpperCamelCase = np.dot(UpperCamelCase__, UpperCamelCase__ )
_UpperCamelCase = sigmoid_function(UpperCamelCase__ )
_UpperCamelCase = cost_function(UpperCamelCase__, UpperCamelCase__ )
if iterations % 1_00 == 0:
print(F'''loss: {j} \t''' ) # printing the loss after every 100 iterations
return theta
# In[68]:
if __name__ == "__main__":
_a = datasets.load_iris()
_a = iris.data[:, :2]
_a = (iris.target != 0) * 1
_a = 0.1
_a = logistic_reg(alpha, x, y, max_iterations=7_0000)
print("""theta: """, theta) # printing the theta i.e our weights vector
def lowerCamelCase__ ( __snake_case ) -> Dict:
"""simple docstring"""
return sigmoid_function(
np.dot(UpperCamelCase__, UpperCamelCase__ ) ) # predicting the value of probability from the logistic regression algorithm
plt.figure(figsize=(10, 6))
plt.scatter(x[y == 0][:, 0], x[y == 0][:, 1], color="""b""", label="""0""")
plt.scatter(x[y == 1][:, 0], x[y == 1][:, 1], color="""r""", label="""1""")
(_a) = (x[:, 0].min(), x[:, 0].max())
(_a) = (x[:, 1].min(), x[:, 1].max())
(_a) = np.meshgrid(np.linspace(xa_min, xa_max), np.linspace(xa_min, xa_max))
_a = np.c_[xxa.ravel(), xxa.ravel()]
_a = predict_prob(grid).reshape(xxa.shape)
plt.contour(xxa, xxa, probs, [0.5], linewidths=1, colors="""black""")
plt.legend()
plt.show()
| 702 |
"""simple docstring"""
import argparse
import torch
from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration
from transformers.utils import logging
logging.set_verbosity_info()
_a = logging.get_logger(__name__)
_a = [
["""attention""", """attn"""],
["""encoder_attention""", """encoder_attn"""],
["""q_lin""", """q_proj"""],
["""k_lin""", """k_proj"""],
["""v_lin""", """v_proj"""],
["""out_lin""", """out_proj"""],
["""norm_embeddings""", """layernorm_embedding"""],
["""position_embeddings""", """embed_positions"""],
["""embeddings""", """embed_tokens"""],
["""ffn.lin""", """fc"""],
]
def lowerCamelCase__ ( __snake_case ) -> Optional[Any]:
"""simple docstring"""
if k == "embeddings.weight":
return "shared.weight"
for parlai_name, hf_name in PATTERNS:
_UpperCamelCase = k.replace(__snake_case, __snake_case )
if k.startswith('''encoder''' ):
_UpperCamelCase = k.replace('''.attn''', '''.self_attn''' )
_UpperCamelCase = k.replace('''norm1''', '''self_attn_layer_norm''' )
_UpperCamelCase = k.replace('''norm2''', '''final_layer_norm''' )
elif k.startswith('''decoder''' ):
_UpperCamelCase = k.replace('''norm1''', '''self_attn_layer_norm''' )
_UpperCamelCase = k.replace('''norm2''', '''encoder_attn_layer_norm''' )
_UpperCamelCase = k.replace('''norm3''', '''final_layer_norm''' )
return k
def lowerCamelCase__ ( __snake_case ) -> Optional[int]:
"""simple docstring"""
_UpperCamelCase = [
'''model.encoder.layernorm_embedding.weight''',
'''model.encoder.layernorm_embedding.bias''',
'''model.decoder.layernorm_embedding.weight''',
'''model.decoder.layernorm_embedding.bias''',
]
for k in keys:
_UpperCamelCase = sd.pop(__snake_case )
_UpperCamelCase = k.replace('''layernorm_embedding''', '''layer_norm''' )
assert new_k not in sd
_UpperCamelCase = v
_a = ["""START"""]
@torch.no_grad()
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = torch.load(__snake_case, map_location='''cpu''' )
_UpperCamelCase = model['''model''']
_UpperCamelCase = BlenderbotConfig.from_json_file(__snake_case )
_UpperCamelCase = BlenderbotForConditionalGeneration(__snake_case )
_UpperCamelCase = m.model.state_dict().keys()
_UpperCamelCase = []
_UpperCamelCase = {}
for k, v in sd.items():
if k in IGNORE_KEYS:
continue
_UpperCamelCase = rename_state_dict_key(__snake_case )
if new_k not in valid_keys:
failures.append([k, new_k] )
else:
_UpperCamelCase = v
if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm
rename_layernorm_keys(__snake_case )
m.model.load_state_dict(__snake_case, strict=__snake_case )
m.half()
m.save_pretrained(__snake_case )
if __name__ == "__main__":
_a = argparse.ArgumentParser()
# Required parameters
parser.add_argument("""--src_path""", type=str, help="""like blenderbot-model.bin""")
parser.add_argument("""--save_dir""", default="""hf_blenderbot""", type=str, help="""Where to save converted model.""")
parser.add_argument(
"""--hf_config_json""", default="""blenderbot-3b-config.json""", type=str, help="""Path to config to use"""
)
_a = parser.parse_args()
convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
| 78 | 0 |
"""simple docstring"""
import argparse
import requests
import torch
from PIL import Image
from transformers import SwinConfig, SwinForMaskedImageModeling, ViTImageProcessor
def lowerCamelCase__ ( __snake_case ) -> Any:
"""simple docstring"""
_UpperCamelCase = SwinConfig(image_size=1_92 )
if "base" in model_name:
_UpperCamelCase = 6
_UpperCamelCase = 1_28
_UpperCamelCase = (2, 2, 18, 2)
_UpperCamelCase = (4, 8, 16, 32)
elif "large" in model_name:
_UpperCamelCase = 12
_UpperCamelCase = 1_92
_UpperCamelCase = (2, 2, 18, 2)
_UpperCamelCase = (6, 12, 24, 48)
else:
raise ValueError('''Model not supported, only supports base and large variants''' )
_UpperCamelCase = window_size
_UpperCamelCase = embed_dim
_UpperCamelCase = depths
_UpperCamelCase = num_heads
return config
def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]:
"""simple docstring"""
if "encoder.mask_token" in name:
_UpperCamelCase = name.replace('''encoder.mask_token''', '''embeddings.mask_token''' )
if "encoder.patch_embed.proj" in name:
_UpperCamelCase = name.replace('''encoder.patch_embed.proj''', '''embeddings.patch_embeddings.projection''' )
if "encoder.patch_embed.norm" in name:
_UpperCamelCase = name.replace('''encoder.patch_embed.norm''', '''embeddings.norm''' )
if "attn.proj" in name:
_UpperCamelCase = name.replace('''attn.proj''', '''attention.output.dense''' )
if "attn" in name:
_UpperCamelCase = name.replace('''attn''', '''attention.self''' )
if "norm1" in name:
_UpperCamelCase = name.replace('''norm1''', '''layernorm_before''' )
if "norm2" in name:
_UpperCamelCase = name.replace('''norm2''', '''layernorm_after''' )
if "mlp.fc1" in name:
_UpperCamelCase = name.replace('''mlp.fc1''', '''intermediate.dense''' )
if "mlp.fc2" in name:
_UpperCamelCase = name.replace('''mlp.fc2''', '''output.dense''' )
if name == "encoder.norm.weight":
_UpperCamelCase = "layernorm.weight"
if name == "encoder.norm.bias":
_UpperCamelCase = "layernorm.bias"
if "decoder" in name:
pass
else:
_UpperCamelCase = "swin." + name
return name
def lowerCamelCase__ ( __snake_case, __snake_case ) -> Union[str, Any]:
"""simple docstring"""
for key in orig_state_dict.copy().keys():
_UpperCamelCase = orig_state_dict.pop(__SCREAMING_SNAKE_CASE )
if "attn_mask" in key:
pass
elif "qkv" in key:
_UpperCamelCase = key.split('''.''' )
_UpperCamelCase = int(key_split[2] )
_UpperCamelCase = int(key_split[4] )
_UpperCamelCase = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size
if "weight" in key:
_UpperCamelCase = val[:dim, :]
_UpperCamelCase = val[
dim : dim * 2, :
]
_UpperCamelCase = val[-dim:, :]
else:
_UpperCamelCase = val[
:dim
]
_UpperCamelCase = val[
dim : dim * 2
]
_UpperCamelCase = val[
-dim:
]
else:
_UpperCamelCase = val
return orig_state_dict
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case, __snake_case ) -> Tuple:
"""simple docstring"""
_UpperCamelCase = torch.load(__SCREAMING_SNAKE_CASE, map_location='''cpu''' )["model"]
_UpperCamelCase = get_swin_config(__SCREAMING_SNAKE_CASE )
_UpperCamelCase = SwinForMaskedImageModeling(__SCREAMING_SNAKE_CASE )
model.eval()
_UpperCamelCase = convert_state_dict(__SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE )
model.load_state_dict(__SCREAMING_SNAKE_CASE )
_UpperCamelCase = "http://images.cocodataset.org/val2017/000000039769.jpg"
_UpperCamelCase = ViTImageProcessor(size={'''height''': 1_92, '''width''': 1_92} )
_UpperCamelCase = Image.open(requests.get(__SCREAMING_SNAKE_CASE, stream=__SCREAMING_SNAKE_CASE ).raw )
_UpperCamelCase = image_processor(images=__SCREAMING_SNAKE_CASE, return_tensors='''pt''' )
with torch.no_grad():
_UpperCamelCase = model(**__SCREAMING_SNAKE_CASE ).logits
print(outputs.keys() )
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(__SCREAMING_SNAKE_CASE )
print(F'''Saving image processor to {pytorch_dump_folder_path}''' )
image_processor.save_pretrained(__SCREAMING_SNAKE_CASE )
if push_to_hub:
print(F'''Pushing model and image processor for {model_name} to hub''' )
model.push_to_hub(F'''microsoft/{model_name}''' )
image_processor.push_to_hub(F'''microsoft/{model_name}''' )
if __name__ == "__main__":
_a = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--model_name""",
default="""swin-base-simmim-window6-192""",
type=str,
choices=["""swin-base-simmim-window6-192""", """swin-large-simmim-window12-192"""],
help="""Name of the Swin SimMIM model you'd like to convert.""",
)
parser.add_argument(
"""--checkpoint_path""",
default="""/Users/nielsrogge/Documents/SwinSimMIM/simmim_pretrain__swin_base__img192_window6__100ep.pth""",
type=str,
help="""Path to the original PyTorch checkpoint (.pth file).""",
)
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."""
)
_a = parser.parse_args()
convert_swin_checkpoint(args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
| 703 |
"""simple docstring"""
import argparse
import os.path as osp
import re
import torch
from safetensors.torch import load_file, save_file
# =================#
# UNet Conversion #
# =================#
_a = [
# (stable-diffusion, HF Diffusers)
("""time_embed.0.weight""", """time_embedding.linear_1.weight"""),
("""time_embed.0.bias""", """time_embedding.linear_1.bias"""),
("""time_embed.2.weight""", """time_embedding.linear_2.weight"""),
("""time_embed.2.bias""", """time_embedding.linear_2.bias"""),
("""input_blocks.0.0.weight""", """conv_in.weight"""),
("""input_blocks.0.0.bias""", """conv_in.bias"""),
("""out.0.weight""", """conv_norm_out.weight"""),
("""out.0.bias""", """conv_norm_out.bias"""),
("""out.2.weight""", """conv_out.weight"""),
("""out.2.bias""", """conv_out.bias"""),
]
_a = [
# (stable-diffusion, HF Diffusers)
("""in_layers.0""", """norm1"""),
("""in_layers.2""", """conv1"""),
("""out_layers.0""", """norm2"""),
("""out_layers.3""", """conv2"""),
("""emb_layers.1""", """time_emb_proj"""),
("""skip_connection""", """conv_shortcut"""),
]
_a = []
# hardcoded number of downblocks and resnets/attentions...
# would need smarter logic for other networks.
for i in range(4):
# loop over downblocks/upblocks
for j in range(2):
# loop over resnets/attentions for downblocks
_a = F"""down_blocks.{i}.resnets.{j}."""
_a = F"""input_blocks.{3*i + j + 1}.0."""
unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix))
if i < 3:
# no attention layers in down_blocks.3
_a = F"""down_blocks.{i}.attentions.{j}."""
_a = F"""input_blocks.{3*i + j + 1}.1."""
unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix))
for j in range(3):
# loop over resnets/attentions for upblocks
_a = F"""up_blocks.{i}.resnets.{j}."""
_a = F"""output_blocks.{3*i + j}.0."""
unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix))
if i > 0:
# no attention layers in up_blocks.0
_a = F"""up_blocks.{i}.attentions.{j}."""
_a = F"""output_blocks.{3*i + j}.1."""
unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix))
if i < 3:
# no downsample in down_blocks.3
_a = F"""down_blocks.{i}.downsamplers.0.conv."""
_a = F"""input_blocks.{3*(i+1)}.0.op."""
unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix))
# no upsample in up_blocks.3
_a = F"""up_blocks.{i}.upsamplers.0."""
_a = F"""output_blocks.{3*i + 2}.{1 if i == 0 else 2}."""
unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix))
_a = """mid_block.attentions.0."""
_a = """middle_block.1."""
unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix))
for j in range(2):
_a = F"""mid_block.resnets.{j}."""
_a = F"""middle_block.{2*j}."""
unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix))
def lowerCamelCase__ ( __snake_case ) -> str:
"""simple docstring"""
_UpperCamelCase = {k: k for k in unet_state_dict.keys()}
for sd_name, hf_name in unet_conversion_map:
_UpperCamelCase = sd_name
for k, v in mapping.items():
if "resnets" in k:
for sd_part, hf_part in unet_conversion_map_resnet:
_UpperCamelCase = v.replace(__snake_case, __snake_case )
_UpperCamelCase = v
for k, v in mapping.items():
for sd_part, hf_part in unet_conversion_map_layer:
_UpperCamelCase = v.replace(__snake_case, __snake_case )
_UpperCamelCase = v
_UpperCamelCase = {v: unet_state_dict[k] for k, v in mapping.items()}
return new_state_dict
# ================#
# VAE Conversion #
# ================#
_a = [
# (stable-diffusion, HF Diffusers)
("""nin_shortcut""", """conv_shortcut"""),
("""norm_out""", """conv_norm_out"""),
("""mid.attn_1.""", """mid_block.attentions.0."""),
]
for i in range(4):
# down_blocks have two resnets
for j in range(2):
_a = F"""encoder.down_blocks.{i}.resnets.{j}."""
_a = F"""encoder.down.{i}.block.{j}."""
vae_conversion_map.append((sd_down_prefix, hf_down_prefix))
if i < 3:
_a = F"""down_blocks.{i}.downsamplers.0."""
_a = F"""down.{i}.downsample."""
vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix))
_a = F"""up_blocks.{i}.upsamplers.0."""
_a = F"""up.{3-i}.upsample."""
vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix))
# up_blocks have three resnets
# also, up blocks in hf are numbered in reverse from sd
for j in range(3):
_a = F"""decoder.up_blocks.{i}.resnets.{j}."""
_a = F"""decoder.up.{3-i}.block.{j}."""
vae_conversion_map.append((sd_up_prefix, hf_up_prefix))
# this part accounts for mid blocks in both the encoder and the decoder
for i in range(2):
_a = F"""mid_block.resnets.{i}."""
_a = F"""mid.block_{i+1}."""
vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix))
_a = [
# (stable-diffusion, HF Diffusers)
("""norm.""", """group_norm."""),
("""q.""", """query."""),
("""k.""", """key."""),
("""v.""", """value."""),
("""proj_out.""", """proj_attn."""),
]
def lowerCamelCase__ ( __snake_case ) -> List[str]:
"""simple docstring"""
return w.reshape(*w.shape, 1, 1 )
def lowerCamelCase__ ( __snake_case ) -> Optional[Any]:
"""simple docstring"""
_UpperCamelCase = {k: k for k in vae_state_dict.keys()}
for k, v in mapping.items():
for sd_part, hf_part in vae_conversion_map:
_UpperCamelCase = v.replace(__snake_case, __snake_case )
_UpperCamelCase = v
for k, v in mapping.items():
if "attentions" in k:
for sd_part, hf_part in vae_conversion_map_attn:
_UpperCamelCase = v.replace(__snake_case, __snake_case )
_UpperCamelCase = v
_UpperCamelCase = {v: vae_state_dict[k] for k, v in mapping.items()}
_UpperCamelCase = ['''q''', '''k''', '''v''', '''proj_out''']
for k, v in new_state_dict.items():
for weight_name in weights_to_convert:
if F'''mid.attn_1.{weight_name}.weight''' in k:
print(F'''Reshaping {k} for SD format''' )
_UpperCamelCase = reshape_weight_for_sd(__snake_case )
return new_state_dict
# =========================#
# Text Encoder Conversion #
# =========================#
_a = [
# (stable-diffusion, HF Diffusers)
("""resblocks.""", """text_model.encoder.layers."""),
("""ln_1""", """layer_norm1"""),
("""ln_2""", """layer_norm2"""),
(""".c_fc.""", """.fc1."""),
(""".c_proj.""", """.fc2."""),
(""".attn""", """.self_attn"""),
("""ln_final.""", """transformer.text_model.final_layer_norm."""),
("""token_embedding.weight""", """transformer.text_model.embeddings.token_embedding.weight"""),
("""positional_embedding""", """transformer.text_model.embeddings.position_embedding.weight"""),
]
_a = {re.escape(x[1]): x[0] for x in textenc_conversion_lst}
_a = re.compile("""|""".join(protected.keys()))
# Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp
_a = {"""q""": 0, """k""": 1, """v""": 2}
def lowerCamelCase__ ( __snake_case ) -> Any:
"""simple docstring"""
_UpperCamelCase = {}
_UpperCamelCase = {}
_UpperCamelCase = {}
for k, v in text_enc_dict.items():
if (
k.endswith('''.self_attn.q_proj.weight''' )
or k.endswith('''.self_attn.k_proj.weight''' )
or k.endswith('''.self_attn.v_proj.weight''' )
):
_UpperCamelCase = k[: -len('''.q_proj.weight''' )]
_UpperCamelCase = k[-len('''q_proj.weight''' )]
if k_pre not in capture_qkv_weight:
_UpperCamelCase = [None, None, None]
_UpperCamelCase = v
continue
if (
k.endswith('''.self_attn.q_proj.bias''' )
or k.endswith('''.self_attn.k_proj.bias''' )
or k.endswith('''.self_attn.v_proj.bias''' )
):
_UpperCamelCase = k[: -len('''.q_proj.bias''' )]
_UpperCamelCase = k[-len('''q_proj.bias''' )]
if k_pre not in capture_qkv_bias:
_UpperCamelCase = [None, None, None]
_UpperCamelCase = v
continue
_UpperCamelCase = textenc_pattern.sub(lambda __snake_case : protected[re.escape(m.group(0 ) )], __snake_case )
_UpperCamelCase = v
for k_pre, tensors in capture_qkv_weight.items():
if None in tensors:
raise Exception('''CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing''' )
_UpperCamelCase = textenc_pattern.sub(lambda __snake_case : protected[re.escape(m.group(0 ) )], __snake_case )
_UpperCamelCase = torch.cat(__snake_case )
for k_pre, tensors in capture_qkv_bias.items():
if None in tensors:
raise Exception('''CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing''' )
_UpperCamelCase = textenc_pattern.sub(lambda __snake_case : protected[re.escape(m.group(0 ) )], __snake_case )
_UpperCamelCase = torch.cat(__snake_case )
return new_state_dict
def lowerCamelCase__ ( __snake_case ) -> Tuple:
"""simple docstring"""
return text_enc_dict
if __name__ == "__main__":
_a = argparse.ArgumentParser()
parser.add_argument("""--model_path""", default=None, type=str, required=True, help="""Path to the model to convert.""")
parser.add_argument("""--checkpoint_path""", default=None, type=str, required=True, help="""Path to the output model.""")
parser.add_argument("""--half""", action="""store_true""", help="""Save weights in half precision.""")
parser.add_argument(
"""--use_safetensors""", action="""store_true""", help="""Save weights use safetensors, default is ckpt."""
)
_a = parser.parse_args()
assert args.model_path is not None, "Must provide a model path!"
assert args.checkpoint_path is not None, "Must provide a checkpoint path!"
# Path for safetensors
_a = osp.join(args.model_path, """unet""", """diffusion_pytorch_model.safetensors""")
_a = osp.join(args.model_path, """vae""", """diffusion_pytorch_model.safetensors""")
_a = osp.join(args.model_path, """text_encoder""", """model.safetensors""")
# Load models from safetensors if it exists, if it doesn't pytorch
if osp.exists(unet_path):
_a = load_file(unet_path, device="""cpu""")
else:
_a = osp.join(args.model_path, """unet""", """diffusion_pytorch_model.bin""")
_a = torch.load(unet_path, map_location="""cpu""")
if osp.exists(vae_path):
_a = load_file(vae_path, device="""cpu""")
else:
_a = osp.join(args.model_path, """vae""", """diffusion_pytorch_model.bin""")
_a = torch.load(vae_path, map_location="""cpu""")
if osp.exists(text_enc_path):
_a = load_file(text_enc_path, device="""cpu""")
else:
_a = osp.join(args.model_path, """text_encoder""", """pytorch_model.bin""")
_a = torch.load(text_enc_path, map_location="""cpu""")
# Convert the UNet model
_a = convert_unet_state_dict(unet_state_dict)
_a = {"""model.diffusion_model.""" + k: v for k, v in unet_state_dict.items()}
# Convert the VAE model
_a = convert_vae_state_dict(vae_state_dict)
_a = {"""first_stage_model.""" + k: v for k, v in vae_state_dict.items()}
# Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper
_a = """text_model.encoder.layers.22.layer_norm2.bias""" in text_enc_dict
if is_vaa_model:
# Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm
_a = {"""transformer.""" + k: v for k, v in text_enc_dict.items()}
_a = convert_text_enc_state_dict_vaa(text_enc_dict)
_a = {"""cond_stage_model.model.""" + k: v for k, v in text_enc_dict.items()}
else:
_a = convert_text_enc_state_dict(text_enc_dict)
_a = {"""cond_stage_model.transformer.""" + k: v for k, v in text_enc_dict.items()}
# Put together new checkpoint
_a = {**unet_state_dict, **vae_state_dict, **text_enc_dict}
if args.half:
_a = {k: v.half() for k, v in state_dict.items()}
if args.use_safetensors:
save_file(state_dict, args.checkpoint_path)
else:
_a = {"""state_dict""": state_dict}
torch.save(state_dict, args.checkpoint_path)
| 78 | 0 |
"""simple docstring"""
from dataclasses import dataclass, field
from typing import ClassVar, Dict
from ..features import Features, Value
from .base import TaskTemplate
@dataclass(frozen=_UpperCAmelCase )
class _UpperCAmelCase( _UpperCAmelCase ):
lowercase__ = field(default='summarization' , metadata={'include_in_asdict_even_if_is_default': True} )
lowercase__ = Features({'text': Value('string' )} )
lowercase__ = Features({'summary': Value('string' )} )
lowercase__ = "text"
lowercase__ = "summary"
@property
def UpperCAmelCase ( self) -> Dict[str, str]:
'''simple docstring'''
return {self.text_column: "text", self.summary_column: "summary"}
| 704 |
"""simple docstring"""
import argparse
import torch
from transformers import OpenAIGPTConfig, OpenAIGPTModel, load_tf_weights_in_openai_gpt
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging
logging.set_verbosity_info()
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> Union[str, Any]:
"""simple docstring"""
if openai_config_file == "":
_UpperCamelCase = OpenAIGPTConfig()
else:
_UpperCamelCase = OpenAIGPTConfig.from_json_file(__snake_case )
_UpperCamelCase = OpenAIGPTModel(__snake_case )
# Load weights from numpy
load_tf_weights_in_openai_gpt(__snake_case, __snake_case, __snake_case )
# Save pytorch-model
_UpperCamelCase = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME
_UpperCamelCase = pytorch_dump_folder_path + '''/''' + CONFIG_NAME
print(F'''Save PyTorch model to {pytorch_weights_dump_path}''' )
torch.save(model.state_dict(), __snake_case )
print(F'''Save configuration file to {pytorch_config_dump_path}''' )
with open(__snake_case, '''w''', encoding='''utf-8''' ) as f:
f.write(config.to_json_string() )
if __name__ == "__main__":
_a = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--openai_checkpoint_folder_path""",
default=None,
type=str,
required=True,
help="""Path to the TensorFlow checkpoint path.""",
)
parser.add_argument(
"""--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
)
parser.add_argument(
"""--openai_config_file""",
default="""""",
type=str,
help=(
"""An optional config json file corresponding to the pre-trained OpenAI model. \n"""
"""This specifies the model architecture."""
),
)
_a = parser.parse_args()
convert_openai_checkpoint_to_pytorch(
args.openai_checkpoint_folder_path, args.openai_config_file, args.pytorch_dump_folder_path
)
| 78 | 0 |
"""simple docstring"""
import json
import os
import re
import unicodedata
from json.encoder import INFINITY
from typing import Any, Dict, List, Optional, Tuple, Union
import numpy as np
import regex
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, is_flax_available, is_tf_available, is_torch_available, logging
from ...utils.generic import _is_jax, _is_numpy
_a = logging.get_logger(__name__)
_a = {
'artists_file': 'artists.json',
'lyrics_file': 'lyrics.json',
'genres_file': 'genres.json',
}
_a = {
'artists_file': {
'jukebox': 'https://huggingface.co/ArthurZ/jukebox/blob/main/artists.json',
},
'genres_file': {
'jukebox': 'https://huggingface.co/ArthurZ/jukebox/blob/main/genres.json',
},
'lyrics_file': {
'jukebox': 'https://huggingface.co/ArthurZ/jukebox/blob/main/lyrics.json',
},
}
_a = {
'jukebox': 512,
}
class _UpperCAmelCase( __lowercase ):
lowercase__ = VOCAB_FILES_NAMES
lowercase__ = PRETRAINED_VOCAB_FILES_MAP
lowercase__ = PRETRAINED_LYRIC_TOKENS_SIZES
lowercase__ = ['input_ids', 'attention_mask']
def __init__( self , __a , __a , __a , __a=["v3", "v2", "v2"] , __a=5_12 , __a=5 , __a="<|endoftext|>" , **__a , ) -> Any:
'''simple docstring'''
_UpperCamelCase = AddedToken(__a , lstrip=__a , rstrip=__a) if isinstance(__a , __a) else unk_token
super().__init__(
unk_token=__a , n_genres=__a , version=__a , max_n_lyric_tokens=__a , **__a , )
_UpperCamelCase = version
_UpperCamelCase = max_n_lyric_tokens
_UpperCamelCase = n_genres
with open(__a , encoding='''utf-8''') as vocab_handle:
_UpperCamelCase = json.load(__a)
with open(__a , encoding='''utf-8''') as vocab_handle:
_UpperCamelCase = json.load(__a)
with open(__a , encoding='''utf-8''') as vocab_handle:
_UpperCamelCase = json.load(__a)
_UpperCamelCase = r"[^A-Za-z0-9.,:;!?\-'\"()\[\] \t\n]+"
# In v2, we had a n_vocab=80 and in v3 we missed + and so n_vocab=79 of characters.
if len(self.lyrics_encoder) == 79:
_UpperCamelCase = oov.replace(R'''\-\'''' , R'''\-+\'''')
_UpperCamelCase = regex.compile(__a)
_UpperCamelCase = {v: k for k, v in self.artists_encoder.items()}
_UpperCamelCase = {v: k for k, v in self.genres_encoder.items()}
_UpperCamelCase = {v: k for k, v in self.lyrics_encoder.items()}
@property
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
return len(self.artists_encoder) + len(self.genres_encoder) + len(self.lyrics_encoder)
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
return dict(self.artists_encoder , self.genres_encoder , self.lyrics_encoder)
def UpperCAmelCase ( self , __a , __a , __a) -> Tuple:
'''simple docstring'''
_UpperCamelCase = [self.artists_encoder.get(__a , 0) for artist in list_artists]
for genres in range(len(__a)):
_UpperCamelCase = [self.genres_encoder.get(__a , 0) for genre in list_genres[genres]]
_UpperCamelCase = list_genres[genres] + [-1] * (self.n_genres - len(list_genres[genres]))
_UpperCamelCase = [[self.lyrics_encoder.get(__a , 0) for character in list_lyrics[0]], [], []]
return artists_id, list_genres, lyric_ids
def UpperCAmelCase ( self , __a) -> Tuple:
'''simple docstring'''
return list(__a)
def UpperCAmelCase ( self , __a , __a , __a , **__a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.prepare_for_tokenization(__a , __a , __a)
_UpperCamelCase = self._tokenize(__a)
return artist, genre, lyrics
def UpperCAmelCase ( self , __a , __a , __a , __a = False) -> Tuple[str, str, str, Dict[str, Any]]:
'''simple docstring'''
for idx in range(len(self.version)):
if self.version[idx] == "v3":
_UpperCamelCase = artists[idx].lower()
_UpperCamelCase = [genres[idx].lower()]
else:
_UpperCamelCase = self._normalize(artists[idx]) + ".v2"
_UpperCamelCase = [
self._normalize(__a) + ".v2" for genre in genres[idx].split('''_''')
] # split is for the full dictionary with combined genres
if self.version[0] == "v2":
_UpperCamelCase = regex.compile(R'''[^A-Za-z0-9.,:;!?\-\'\"()\[\] \t\n]+''')
_UpperCamelCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-+'\"()[] \t\n"
_UpperCamelCase = {vocab[index]: index + 1 for index in range(len(__a))}
_UpperCamelCase = 0
_UpperCamelCase = len(__a) + 1
_UpperCamelCase = self.vocab
_UpperCamelCase = {v: k for k, v in self.vocab.items()}
_UpperCamelCase = ""
else:
_UpperCamelCase = regex.compile(R'''[^A-Za-z0-9.,:;!?\-+\'\"()\[\] \t\n]+''')
_UpperCamelCase = self._run_strip_accents(__a)
_UpperCamelCase = lyrics.replace('''\\''' , '''\n''')
_UpperCamelCase = self.out_of_vocab.sub('''''' , __a), [], []
return artists, genres, lyrics
def UpperCAmelCase ( self , __a) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = unicodedata.normalize('''NFD''' , __a)
_UpperCamelCase = []
for char in text:
_UpperCamelCase = unicodedata.category(__a)
if cat == "Mn":
continue
output.append(__a)
return "".join(__a)
def UpperCAmelCase ( self , __a) -> str:
'''simple docstring'''
_UpperCamelCase = (
[chr(__a) for i in range(ord('''a''') , ord('''z''') + 1)]
+ [chr(__a) for i in range(ord('''A''') , ord('''Z''') + 1)]
+ [chr(__a) for i in range(ord('''0''') , ord('''9''') + 1)]
+ ["."]
)
_UpperCamelCase = frozenset(__a)
_UpperCamelCase = re.compile(R'''_+''')
_UpperCamelCase = "".join([c if c in accepted else '''_''' for c in text.lower()])
_UpperCamelCase = pattern.sub('''_''' , __a).strip('''_''')
return text
def UpperCAmelCase ( self , __a) -> str:
'''simple docstring'''
return " ".join(__a)
def UpperCAmelCase ( self , __a , __a = None , __a = False) -> Dict:
'''simple docstring'''
# Convert to TensorType
if not isinstance(__a , __a):
_UpperCamelCase = TensorType(__a)
# Get a function reference for the correct framework
if tensor_type == TensorType.TENSORFLOW:
if not is_tf_available():
raise ImportError(
'''Unable to convert output to TensorFlow tensors format, TensorFlow is not installed.''')
import tensorflow as tf
_UpperCamelCase = tf.constant
_UpperCamelCase = tf.is_tensor
elif tensor_type == TensorType.PYTORCH:
if not is_torch_available():
raise ImportError('''Unable to convert output to PyTorch tensors format, PyTorch is not installed.''')
import torch
_UpperCamelCase = torch.tensor
_UpperCamelCase = torch.is_tensor
elif tensor_type == TensorType.JAX:
if not is_flax_available():
raise ImportError('''Unable to convert output to JAX tensors format, JAX is not installed.''')
import jax.numpy as jnp # noqa: F811
_UpperCamelCase = jnp.array
_UpperCamelCase = _is_jax
else:
_UpperCamelCase = np.asarray
_UpperCamelCase = _is_numpy
# Do the tensor conversion in batch
try:
if prepend_batch_axis:
_UpperCamelCase = [inputs]
if not is_tensor(__a):
_UpperCamelCase = as_tensor(__a)
except: # noqa E722
raise ValueError(
'''Unable to create tensor, you should probably activate truncation and/or padding '''
'''with \'padding=True\' \'truncation=True\' to have batched tensors with the same length.''')
return inputs
def __call__( self , __a , __a , __a="" , __a="pt") -> BatchEncoding:
'''simple docstring'''
_UpperCamelCase = [0, 0, 0]
_UpperCamelCase = [artist] * len(self.version)
_UpperCamelCase = [genres] * len(self.version)
_UpperCamelCase = self.tokenize(__a , __a , __a)
_UpperCamelCase = self._convert_token_to_id(__a , __a , __a)
_UpperCamelCase = [-INFINITY] * len(full_tokens[-1])
_UpperCamelCase = [
self.convert_to_tensors(
[input_ids + [artists_id[i]] + genres_ids[i] + full_tokens[i]] , tensor_type=__a)
for i in range(len(self.version))
]
return BatchEncoding({'''input_ids''': input_ids, '''attention_masks''': attention_masks})
def UpperCAmelCase ( self , __a , __a = None) -> Tuple[str]:
'''simple docstring'''
if not os.path.isdir(__a):
logger.error(F'''Vocabulary path ({save_directory}) should be a directory''')
return
_UpperCamelCase = os.path.join(
__a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''artists_file'''])
with open(__a , '''w''' , encoding='''utf-8''') as f:
f.write(json.dumps(self.artists_encoder , ensure_ascii=__a))
_UpperCamelCase = os.path.join(
__a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''genres_file'''])
with open(__a , '''w''' , encoding='''utf-8''') as f:
f.write(json.dumps(self.genres_encoder , ensure_ascii=__a))
_UpperCamelCase = os.path.join(
__a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''lyrics_file'''])
with open(__a , '''w''' , encoding='''utf-8''') as f:
f.write(json.dumps(self.lyrics_encoder , ensure_ascii=__a))
return (artists_file, genres_file, lyrics_file)
def UpperCAmelCase ( self , __a , __a , __a) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = self.artists_decoder.get(__a)
_UpperCamelCase = [self.genres_decoder.get(__a) for genre in genres_index]
_UpperCamelCase = [self.lyrics_decoder.get(__a) for character in lyric_index]
return artist, genres, lyrics
| 705 |
"""simple docstring"""
from __future__ import annotations
import unittest
from transformers import AutoTokenizer, MBartConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel
@require_tf
class _UpperCAmelCase:
lowercase__ = MBartConfig
lowercase__ = {}
lowercase__ = 'gelu'
def __init__( self , __a , __a=13 , __a=7 , __a=True , __a=False , __a=99 , __a=32 , __a=2 , __a=4 , __a=37 , __a=0.1 , __a=0.1 , __a=20 , __a=2 , __a=1 , __a=0 , ) -> Any:
'''simple docstring'''
_UpperCamelCase = parent
_UpperCamelCase = batch_size
_UpperCamelCase = seq_length
_UpperCamelCase = is_training
_UpperCamelCase = use_labels
_UpperCamelCase = vocab_size
_UpperCamelCase = hidden_size
_UpperCamelCase = num_hidden_layers
_UpperCamelCase = num_attention_heads
_UpperCamelCase = intermediate_size
_UpperCamelCase = hidden_dropout_prob
_UpperCamelCase = attention_probs_dropout_prob
_UpperCamelCase = max_position_embeddings
_UpperCamelCase = eos_token_id
_UpperCamelCase = pad_token_id
_UpperCamelCase = bos_token_id
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size)
_UpperCamelCase = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size) , 1)
_UpperCamelCase = tf.concat([input_ids, eos_tensor] , axis=1)
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size)
_UpperCamelCase = self.config_cls(
vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , )
_UpperCamelCase = prepare_mbart_inputs_dict(__a , __a , __a)
return config, inputs_dict
def UpperCAmelCase ( self , __a , __a) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = TFMBartModel(config=__a).get_decoder()
_UpperCamelCase = inputs_dict['''input_ids''']
_UpperCamelCase = input_ids[:1, :]
_UpperCamelCase = inputs_dict['''attention_mask'''][:1, :]
_UpperCamelCase = inputs_dict['''head_mask''']
_UpperCamelCase = 1
# first forward pass
_UpperCamelCase = model(__a , attention_mask=__a , head_mask=__a , use_cache=__a)
_UpperCamelCase , _UpperCamelCase = outputs.to_tuple()
_UpperCamelCase = past_key_values[1]
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case, __snake_case=None, __snake_case=None, __snake_case=None, __snake_case=None, __snake_case=None, ) -> Optional[int]:
"""simple docstring"""
if attention_mask is None:
_UpperCamelCase = tf.cast(tf.math.not_equal(__snake_case, config.pad_token_id ), tf.inta )
if decoder_attention_mask is None:
_UpperCamelCase = tf.concat(
[
tf.ones(decoder_input_ids[:, :1].shape, dtype=tf.inta ),
tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:], config.pad_token_id ), tf.inta ),
], axis=-1, )
if head_mask is None:
_UpperCamelCase = tf.ones((config.encoder_layers, config.encoder_attention_heads) )
if decoder_head_mask is None:
_UpperCamelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
if cross_attn_head_mask is None:
_UpperCamelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
return {
"input_ids": input_ids,
"decoder_input_ids": decoder_input_ids,
"attention_mask": attention_mask,
"decoder_attention_mask": decoder_attention_mask,
"head_mask": head_mask,
"decoder_head_mask": decoder_head_mask,
"cross_attn_head_mask": cross_attn_head_mask,
}
@require_tf
class _UpperCAmelCase( lowerCamelCase , lowerCamelCase , unittest.TestCase ):
lowercase__ = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else ()
lowercase__ = (TFMBartForConditionalGeneration,) if is_tf_available() else ()
lowercase__ = (
{
'conversational': TFMBartForConditionalGeneration,
'feature-extraction': TFMBartModel,
'summarization': TFMBartForConditionalGeneration,
'text2text-generation': TFMBartForConditionalGeneration,
'translation': TFMBartForConditionalGeneration,
}
if is_tf_available()
else {}
)
lowercase__ = True
lowercase__ = False
lowercase__ = False
def UpperCAmelCase ( self , __a , __a , __a , __a , __a) -> Dict:
'''simple docstring'''
if pipeline_test_casse_name != "FeatureExtractionPipelineTests":
# Exception encountered when calling layer '...'
return True
return False
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase = TFMBartModelTester(self)
_UpperCamelCase = ConfigTester(self , config_class=__a)
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
self.config_tester.run_common_tests()
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_decoder_model_past_large_inputs(*__a)
@require_sentencepiece
@require_tokenizers
@require_tf
class _UpperCAmelCase( unittest.TestCase ):
lowercase__ = [
' UN Chief Says There Is No Military Solution in Syria',
]
lowercase__ = [
'Şeful ONU declară că nu există o soluţie militară în Siria',
]
lowercase__ = 'facebook/mbart-large-en-ro'
@cached_property
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
return AutoTokenizer.from_pretrained(self.model_name)
@cached_property
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
_UpperCamelCase = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name)
return model
def UpperCAmelCase ( self , **__a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.translate_src_text(**__a)
self.assertListEqual(self.expected_text , __a)
def UpperCAmelCase ( self , **__a) -> Dict:
'''simple docstring'''
_UpperCamelCase = self.tokenizer(self.src_text , **__a , return_tensors='''tf''')
_UpperCamelCase = self.model.generate(
model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2)
_UpperCamelCase = self.tokenizer.batch_decode(__a , skip_special_tokens=__a)
return generated_words
@slow
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
self._assert_generated_batch_equal_expected()
| 78 | 0 |
"""simple docstring"""
from string import ascii_uppercase
_a = {str(ord(c) - 55): c for c in ascii_uppercase}
def lowerCamelCase__ ( __snake_case, __snake_case ) -> List[str]:
"""simple docstring"""
if isinstance(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ):
raise TypeError('''int() can\'t convert non-string with explicit base''' )
if num < 0:
raise ValueError('''parameter must be positive int''' )
if isinstance(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ):
raise TypeError('''\'str\' object cannot be interpreted as an integer''' )
if isinstance(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE ):
raise TypeError('''\'float\' object cannot be interpreted as an integer''' )
if base in (0, 1):
raise ValueError('''base must be >= 2''' )
if base > 36:
raise ValueError('''base must be <= 36''' )
_UpperCamelCase = ''''''
_UpperCamelCase = 0
_UpperCamelCase = 0
while div != 1:
_UpperCamelCase , _UpperCamelCase = divmod(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE )
if base >= 11 and 9 < mod < 36:
_UpperCamelCase = ALPHABET_VALUES[str(_SCREAMING_SNAKE_CASE )]
else:
_UpperCamelCase = str(_SCREAMING_SNAKE_CASE )
new_value += actual_value
_UpperCamelCase = num // base
_UpperCamelCase = div
if div == 0:
return str(new_value[::-1] )
elif div == 1:
new_value += str(_SCREAMING_SNAKE_CASE )
return str(new_value[::-1] )
return new_value[::-1]
if __name__ == "__main__":
import doctest
doctest.testmod()
for base in range(2, 37):
for num in range(1000):
assert int(decimal_to_any(num, base), base) == num, (
num,
base,
decimal_to_any(num, base),
int(decimal_to_any(num, base), base),
)
| 706 |
"""simple docstring"""
from typing import Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format
from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images
from ...utils import TensorType, logging
_a = logging.get_logger(__name__)
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = ['pixel_values']
def __init__( self , __a = True , __a = 1 / 2_55 , __a = True , __a = 8 , **__a , ) -> None:
'''simple docstring'''
super().__init__(**__a)
_UpperCamelCase = do_rescale
_UpperCamelCase = rescale_factor
_UpperCamelCase = do_pad
_UpperCamelCase = pad_size
def UpperCAmelCase ( self , __a , __a , __a = None , **__a) -> np.ndarray:
'''simple docstring'''
return rescale(__a , scale=__a , data_format=__a , **__a)
def UpperCAmelCase ( self , __a , __a , __a = None) -> List[Any]:
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase = get_image_size(__a)
_UpperCamelCase = (old_height // size + 1) * size - old_height
_UpperCamelCase = (old_width // size + 1) * size - old_width
return pad(__a , ((0, pad_height), (0, pad_width)) , mode='''symmetric''' , data_format=__a)
def UpperCAmelCase ( self , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = ChannelDimension.FIRST , **__a , ) -> Tuple:
'''simple docstring'''
_UpperCamelCase = do_rescale if do_rescale is not None else self.do_rescale
_UpperCamelCase = rescale_factor if rescale_factor is not None else self.rescale_factor
_UpperCamelCase = do_pad if do_pad is not None else self.do_pad
_UpperCamelCase = pad_size if pad_size is not None else self.pad_size
_UpperCamelCase = make_list_of_images(__a)
if not valid_images(__a):
raise ValueError(
'''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
'''torch.Tensor, tf.Tensor or jax.ndarray.''')
if do_rescale and rescale_factor is None:
raise ValueError('''Rescale factor must be specified if do_rescale is True.''')
# All transformations expect numpy arrays.
_UpperCamelCase = [to_numpy_array(__a) for image in images]
if do_rescale:
_UpperCamelCase = [self.rescale(image=__a , scale=__a) for image in images]
if do_pad:
_UpperCamelCase = [self.pad(__a , size=__a) for image in images]
_UpperCamelCase = [to_channel_dimension_format(__a , __a) for image in images]
_UpperCamelCase = {'''pixel_values''': images}
return BatchFeature(data=__a , tensor_type=__a)
| 78 | 0 |
"""simple docstring"""
import os
import unittest
from huggingface_hub.utils import are_progress_bars_disabled
import transformers.models.bart.tokenization_bart
from transformers import logging
from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context
from transformers.utils.logging import disable_progress_bar, enable_progress_bar
class _UpperCAmelCase( unittest.TestCase ):
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = logging.get_logger()
# the current default level is logging.WARNING
_UpperCamelCase = logging.get_verbosity()
logging.set_verbosity_error()
self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity())
logging.set_verbosity_warning()
self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity())
logging.set_verbosity_info()
self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity())
logging.set_verbosity_debug()
self.assertEqual(logger.getEffectiveLevel() , logging.get_verbosity())
# restore to the original level
logging.set_verbosity(__a)
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
_UpperCamelCase = logging.get_verbosity()
_UpperCamelCase = logging.get_logger('''transformers.models.bart.tokenization_bart''')
_UpperCamelCase = """Testing 1, 2, 3"""
# should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`)
if level_origin <= logging.WARNING:
with CaptureLogger(__a) as cl:
logger.warning(__a)
self.assertEqual(cl.out , msg + '''\n''')
# this is setting the level for all of `transformers.*` loggers
logging.set_verbosity_error()
# should not be able to log warnings
with CaptureLogger(__a) as cl:
logger.warning(__a)
self.assertEqual(cl.out , '''''')
# should be able to log warnings again
logging.set_verbosity_warning()
with CaptureLogger(__a) as cl:
logger.warning(__a)
self.assertEqual(cl.out , msg + '''\n''')
# restore to the original level
logging.set_verbosity(__a)
@mockenv(TRANSFORMERS_VERBOSITY='''error''')
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
# reset for the env var to take effect, next time some logger call is made
transformers.utils.logging._reset_library_root_logger()
# this action activates the env var
_UpperCamelCase = logging.get_logger('''transformers.models.bart.tokenization_bart''')
_UpperCamelCase = os.getenv('''TRANSFORMERS_VERBOSITY''' , __a)
_UpperCamelCase = logging.log_levels[env_level_str]
_UpperCamelCase = logging.get_verbosity()
self.assertEqual(
__a , __a , F'''TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}''' , )
# restore to the original level
_UpperCamelCase = """"""
transformers.utils.logging._reset_library_root_logger()
@mockenv(TRANSFORMERS_VERBOSITY='''super-error''')
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
# reset for the env var to take effect, next time some logger call is made
transformers.utils.logging._reset_library_root_logger()
_UpperCamelCase = logging.logging.getLogger()
with CaptureLogger(__a) as cl:
# this action activates the env var
logging.get_logger('''transformers.models.bart.tokenization_bart''')
self.assertIn('''Unknown option TRANSFORMERS_VERBOSITY=super-error''' , cl.out)
# no need to restore as nothing was changed
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
# testing `logger.warning_advice()`
transformers.utils.logging._reset_library_root_logger()
_UpperCamelCase = logging.get_logger('''transformers.models.bart.tokenization_bart''')
_UpperCamelCase = """Testing 1, 2, 3"""
with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS='''1'''):
# nothing should be logged as env var disables this method
with CaptureLogger(__a) as cl:
logger.warning_advice(__a)
self.assertEqual(cl.out , '''''')
with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS=''''''):
# should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset
with CaptureLogger(__a) as cl:
logger.warning_advice(__a)
self.assertEqual(cl.out , msg + '''\n''')
def lowerCamelCase__ ( ) -> Any:
"""simple docstring"""
disable_progress_bar()
assert are_progress_bars_disabled()
enable_progress_bar()
assert not are_progress_bars_disabled() | 707 |
"""simple docstring"""
from importlib import import_module
from .logging import get_logger
_a = get_logger(__name__)
class _UpperCAmelCase:
def __init__( self , __a , __a=None) -> Dict:
'''simple docstring'''
_UpperCamelCase = attrs or []
if module is not None:
for key in module.__dict__:
if key in attrs or not key.startswith('''__'''):
setattr(self , __a , getattr(__a , __a))
_UpperCamelCase = module._original_module if isinstance(__a , _PatchedModuleObj) else module
class _UpperCAmelCase:
lowercase__ = []
def __init__( self , __a , __a , __a , __a=None) -> List[str]:
'''simple docstring'''
_UpperCamelCase = obj
_UpperCamelCase = target
_UpperCamelCase = new
_UpperCamelCase = target.split('''.''')[0]
_UpperCamelCase = {}
_UpperCamelCase = attrs or []
def __enter__( self) -> int:
'''simple docstring'''
*_UpperCamelCase , _UpperCamelCase = self.target.split('''.''')
# Patch modules:
# it's used to patch attributes of submodules like "os.path.join";
# in this case we need to patch "os" and "os.path"
for i in range(len(__a)):
try:
_UpperCamelCase = import_module('''.'''.join(submodules[: i + 1]))
except ModuleNotFoundError:
continue
# We iterate over all the globals in self.obj in case we find "os" or "os.path"
for attr in self.obj.__dir__():
_UpperCamelCase = getattr(self.obj , __a)
# We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
# This allows to patch renamed modules like "from os import path as ospath".
if obj_attr is submodule or (
(isinstance(__a , _PatchedModuleObj) and obj_attr._original_module is submodule)
):
_UpperCamelCase = obj_attr
# patch at top level
setattr(self.obj , __a , _PatchedModuleObj(__a , attrs=self.attrs))
_UpperCamelCase = getattr(self.obj , __a)
# construct lower levels patches
for key in submodules[i + 1 :]:
setattr(__a , __a , _PatchedModuleObj(getattr(__a , __a , __a) , attrs=self.attrs))
_UpperCamelCase = getattr(__a , __a)
# finally set the target attribute
setattr(__a , __a , self.new)
# Patch attribute itself:
# it's used for builtins like "open",
# and also to patch "os.path.join" we may also need to patch "join"
# itself if it was imported as "from os.path import join".
if submodules: # if it's an attribute of a submodule like "os.path.join"
try:
_UpperCamelCase = getattr(import_module('''.'''.join(__a)) , __a)
except (AttributeError, ModuleNotFoundError):
return
# We iterate over all the globals in self.obj in case we find "os.path.join"
for attr in self.obj.__dir__():
# We don't check for the name of the global, but rather if its value *is* "os.path.join".
# This allows to patch renamed attributes like "from os.path import join as pjoin".
if getattr(self.obj , __a) is attr_value:
_UpperCamelCase = getattr(self.obj , __a)
setattr(self.obj , __a , self.new)
elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open"
_UpperCamelCase = globals()['''__builtins__'''][target_attr]
setattr(self.obj , __a , self.new)
else:
raise RuntimeError(F'''Tried to patch attribute {target_attr} instead of a submodule.''')
def __exit__( self , *__a) -> Tuple:
'''simple docstring'''
for attr in list(self.original):
setattr(self.obj , __a , self.original.pop(__a))
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
self.__enter__()
self._active_patches.append(self)
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
try:
self._active_patches.remove(self)
except ValueError:
# If the patch hasn't been started this will fail
return None
return self.__exit__()
| 78 | 0 |
"""simple docstring"""
def lowerCamelCase__ ( __snake_case = 1_00_00_00 ) -> Any:
"""simple docstring"""
_UpperCamelCase = 1
_UpperCamelCase = 1
_UpperCamelCase = {1: 1}
for inputa in range(2, lowerCAmelCase__ ):
_UpperCamelCase = 0
_UpperCamelCase = inputa
while True:
if number in counters:
counter += counters[number]
break
if number % 2 == 0:
number //= 2
counter += 1
else:
_UpperCamelCase = (3 * number) + 1
counter += 1
if inputa not in counters:
_UpperCamelCase = counter
if counter > pre_counter:
_UpperCamelCase = inputa
_UpperCamelCase = counter
return largest_number
if __name__ == "__main__":
print(solution(int(input().strip())))
| 708 |
"""simple docstring"""
from ...utils import (
OptionalDependencyNotAvailable,
is_flax_available,
is_torch_available,
is_transformers_available,
)
try:
if not (is_transformers_available() and is_torch_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ...utils.dummy_torch_and_transformers_objects import * # noqa F403
else:
from .multicontrolnet import MultiControlNetModel
from .pipeline_controlnet import StableDiffusionControlNetPipeline
from .pipeline_controlnet_imgaimg import StableDiffusionControlNetImgaImgPipeline
from .pipeline_controlnet_inpaint import StableDiffusionControlNetInpaintPipeline
if is_transformers_available() and is_flax_available():
from .pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline
| 78 | 0 |
"""simple docstring"""
import argparse
import os
import transformers
from .convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS
from .utils import logging
logging.set_verbosity_info()
_a = logging.get_logger(__name__)
_a = {name: getattr(transformers, name + """Fast""") for name in SLOW_TO_FAST_CONVERTERS}
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case, __snake_case ) -> List[str]:
"""simple docstring"""
if tokenizer_name is not None and tokenizer_name not in TOKENIZER_CLASSES:
raise ValueError(F'''Unrecognized tokenizer name, should be one of {list(TOKENIZER_CLASSES.keys() )}.''' )
if tokenizer_name is None:
_UpperCamelCase = TOKENIZER_CLASSES
else:
_UpperCamelCase = {tokenizer_name: getattr(__snake_case, tokenizer_name + '''Fast''' )}
logger.info(F'''Loading tokenizer classes: {tokenizer_names}''' )
for tokenizer_name in tokenizer_names:
_UpperCamelCase = TOKENIZER_CLASSES[tokenizer_name]
_UpperCamelCase = True
if checkpoint_name is None:
_UpperCamelCase = list(tokenizer_class.max_model_input_sizes.keys() )
else:
_UpperCamelCase = [checkpoint_name]
logger.info(F'''For tokenizer {tokenizer_class.__class__.__name__} loading checkpoints: {checkpoint_names}''' )
for checkpoint in checkpoint_names:
logger.info(F'''Loading {tokenizer_class.__class__.__name__} {checkpoint}''' )
# Load tokenizer
_UpperCamelCase = tokenizer_class.from_pretrained(__snake_case, force_download=__snake_case )
# Save fast tokenizer
logger.info(F'''Save fast tokenizer to {dump_path} with prefix {checkpoint} add_prefix {add_prefix}''' )
# For organization names we create sub-directories
if "/" in checkpoint:
_UpperCamelCase , _UpperCamelCase = checkpoint.split('''/''' )
_UpperCamelCase = os.path.join(__snake_case, __snake_case )
elif add_prefix:
_UpperCamelCase = checkpoint
_UpperCamelCase = dump_path
else:
_UpperCamelCase = None
_UpperCamelCase = dump_path
logger.info(F'''=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}''' )
if checkpoint in list(tokenizer.pretrained_vocab_files_map.values() )[0]:
_UpperCamelCase = list(tokenizer.pretrained_vocab_files_map.values() )[0][checkpoint]
_UpperCamelCase = file_path.split(__snake_case )[-1][0]
if next_char == "/":
_UpperCamelCase = os.path.join(__snake_case, __snake_case )
_UpperCamelCase = None
logger.info(F'''=> {dump_path_full} with prefix {checkpoint_prefix_name}, add_prefix {add_prefix}''' )
_UpperCamelCase = tokenizer.save_pretrained(
__snake_case, legacy_format=__snake_case, filename_prefix=__snake_case )
logger.info(F'''=> File names {file_names}''' )
for file_name in file_names:
if not file_name.endswith('''tokenizer.json''' ):
os.remove(__snake_case )
logger.info(F'''=> removing {file_name}''' )
if __name__ == "__main__":
_a = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--dump_path""", default=None, type=str, required=True, help="""Path to output generated fast tokenizer files."""
)
parser.add_argument(
"""--tokenizer_name""",
default=None,
type=str,
help=(
F"""Optional tokenizer type selected in the list of {list(TOKENIZER_CLASSES.keys())}. If not given, will """
"""download and convert all the checkpoints from AWS."""
),
)
parser.add_argument(
"""--checkpoint_name""",
default=None,
type=str,
help="""Optional checkpoint name. If not given, will download and convert the canonical checkpoints from AWS.""",
)
parser.add_argument(
"""--force_download""",
action="""store_true""",
help="""Re-download checkpoints.""",
)
_a = parser.parse_args()
convert_slow_checkpoint_to_fast(args.tokenizer_name, args.checkpoint_name, args.dump_path, args.force_download)
| 709 |
"""simple docstring"""
from collections import OrderedDict
from typing import Any, Mapping, Optional
from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast
from ...utils import logging
_a = logging.get_logger(__name__)
_a = {
"""EleutherAI/gpt-neo-1.3B""": """https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json""",
# See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo
}
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = 'gpt_neo'
lowercase__ = ['past_key_values']
lowercase__ = {'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers'}
def __init__( self , __a=5_02_57 , __a=20_48 , __a=20_48 , __a=24 , __a=[[["global", "local"], 12]] , __a=16 , __a=None , __a=2_56 , __a="gelu_new" , __a=0.0 , __a=0.0 , __a=0.0 , __a=0.1 , __a=1e-5 , __a=0.02 , __a=True , __a=5_02_56 , __a=5_02_56 , **__a , ) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = vocab_size
_UpperCamelCase = max_position_embeddings
_UpperCamelCase = hidden_size
_UpperCamelCase = num_layers
_UpperCamelCase = num_heads
_UpperCamelCase = intermediate_size
_UpperCamelCase = window_size
_UpperCamelCase = activation_function
_UpperCamelCase = resid_dropout
_UpperCamelCase = embed_dropout
_UpperCamelCase = attention_dropout
_UpperCamelCase = classifier_dropout
_UpperCamelCase = layer_norm_epsilon
_UpperCamelCase = initializer_range
_UpperCamelCase = use_cache
_UpperCamelCase = bos_token_id
_UpperCamelCase = eos_token_id
_UpperCamelCase = attention_types
_UpperCamelCase = self.expand_attention_types_params(__a)
if len(self.attention_layers) != self.num_layers:
raise ValueError(
'''Configuration for convolutional module is incorrect. '''
'''It is required that `len(config.attention_layers)` == `config.num_layers` '''
F'''but is `len(config.attention_layers) = {len(self.attention_layers)}`, '''
F'''`config.num_layers = {self.num_layers}`. '''
'''`config.attention_layers` is prepared using `config.attention_types`. '''
'''Please verify the value of `config.attention_types` argument.''')
super().__init__(bos_token_id=__a , eos_token_id=__a , **__a)
@staticmethod
def UpperCAmelCase ( __a) -> int:
'''simple docstring'''
_UpperCamelCase = []
for item in attention_types:
for _ in range(item[1]):
attentions.extend(item[0])
return attentions
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case, __snake_case ) -> str:
"""simple docstring"""
import torch
_UpperCamelCase = input.size()
_UpperCamelCase = len(__snake_case )
_UpperCamelCase = shape[dimension]
_UpperCamelCase = torch.arange(0, __snake_case, __snake_case )
_UpperCamelCase = torch.div(sizedim - size, __snake_case, rounding_mode='''floor''' ) + 1
_UpperCamelCase = torch.arange(__snake_case ) + low_indices[:min_length][:, None]
_UpperCamelCase = [slice(__snake_case )] * rank
_UpperCamelCase = indices
_UpperCamelCase = input[s]
_UpperCamelCase = list(range(0, rank + 1 ) )
perm.append(perm.pop(dimension + 1 ) )
return sliced.permute(__snake_case )
def lowerCamelCase__ ( __snake_case, __snake_case ) -> str:
"""simple docstring"""
import torch
_UpperCamelCase = torch.arange(1, __snake_case )
_UpperCamelCase = torch.remainder(__snake_case, __snake_case )
_UpperCamelCase = remainders == 0
_UpperCamelCase = candidates[divisor_indices]
_UpperCamelCase = torch.max(__snake_case )
return largest_divisor, torch.div(__snake_case, __snake_case, rounding_mode='''floor''' )
class _UpperCAmelCase( lowerCamelCase ):
@property
def UpperCAmelCase ( self) -> Mapping[str, Mapping[int, str]]:
'''simple docstring'''
_UpperCamelCase = OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}})
if self.use_past:
self.fill_with_past_key_values_(__a , direction='''inputs''')
_UpperCamelCase = {0: '''batch''', 1: '''past_sequence + sequence'''}
else:
_UpperCamelCase = {0: '''batch''', 1: '''sequence'''}
return common_inputs
@property
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
return self._config.num_heads
def UpperCAmelCase ( self , __a , __a = -1 , __a = -1 , __a = False , __a = None , ) -> Mapping[str, Any]:
'''simple docstring'''
_UpperCamelCase = 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()
_UpperCamelCase = 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
_UpperCamelCase , _UpperCamelCase = common_inputs['''input_ids'''].shape
# Not using the same length for past_key_values
_UpperCamelCase = seqlen + 2
_UpperCamelCase = (
batch,
self.num_attention_heads,
past_key_values_length,
self._config.hidden_size // self.num_attention_heads,
)
_UpperCamelCase = [
(torch.zeros(__a), torch.zeros(__a)) for _ in range(self.num_layers)
]
_UpperCamelCase = common_inputs['''attention_mask''']
if self.use_past:
_UpperCamelCase = ordered_inputs['''attention_mask'''].dtype
_UpperCamelCase = torch.cat(
[ordered_inputs['''attention_mask'''], torch.ones(__a , __a , dtype=__a)] , dim=1)
return ordered_inputs
@property
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
return 13
| 78 | 0 |
"""simple docstring"""
def lowerCamelCase__ ( __snake_case = 4_00_00_00 ) -> Union[str, Any]:
"""simple docstring"""
_UpperCamelCase = []
_UpperCamelCase , _UpperCamelCase = 0, 1
while b <= n:
if b % 2 == 0:
even_fibs.append(__snake_case )
_UpperCamelCase , _UpperCamelCase = b, a + b
return sum(__snake_case )
if __name__ == "__main__":
print(F"""{solution() = }""")
| 710 |
"""simple docstring"""
import sys
from collections import defaultdict
class _UpperCAmelCase:
def __init__( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = []
def UpperCAmelCase ( self , __a) -> Optional[Any]:
'''simple docstring'''
return self.node_position[vertex]
def UpperCAmelCase ( self , __a , __a) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = pos
def UpperCAmelCase ( self , __a , __a , __a , __a) -> Tuple:
'''simple docstring'''
if start > size // 2 - 1:
return
else:
if 2 * start + 2 >= size:
_UpperCamelCase = 2 * start + 1
else:
if heap[2 * start + 1] < heap[2 * start + 2]:
_UpperCamelCase = 2 * start + 1
else:
_UpperCamelCase = 2 * start + 2
if heap[smallest_child] < heap[start]:
_UpperCamelCase , _UpperCamelCase = heap[smallest_child], positions[smallest_child]
_UpperCamelCase , _UpperCamelCase = (
heap[start],
positions[start],
)
_UpperCamelCase , _UpperCamelCase = temp, tempa
_UpperCamelCase = self.get_position(positions[smallest_child])
self.set_position(
positions[smallest_child] , self.get_position(positions[start]))
self.set_position(positions[start] , __a)
self.top_to_bottom(__a , __a , __a , __a)
def UpperCAmelCase ( self , __a , __a , __a , __a) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = position[index]
while index != 0:
_UpperCamelCase = int((index - 2) / 2) if index % 2 == 0 else int((index - 1) / 2)
if val < heap[parent]:
_UpperCamelCase = heap[parent]
_UpperCamelCase = position[parent]
self.set_position(position[parent] , __a)
else:
_UpperCamelCase = val
_UpperCamelCase = temp
self.set_position(__a , __a)
break
_UpperCamelCase = parent
else:
_UpperCamelCase = val
_UpperCamelCase = temp
self.set_position(__a , 0)
def UpperCAmelCase ( self , __a , __a) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = len(__a) // 2 - 1
for i in range(__a , -1 , -1):
self.top_to_bottom(__a , __a , len(__a) , __a)
def UpperCAmelCase ( self , __a , __a) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = positions[0]
_UpperCamelCase = sys.maxsize
self.top_to_bottom(__a , 0 , len(__a) , __a)
return temp
def lowerCamelCase__ ( __snake_case ) -> Optional[int]:
"""simple docstring"""
_UpperCamelCase = Heap()
_UpperCamelCase = [0] * len(__snake_case )
_UpperCamelCase = [-1] * len(__snake_case ) # Neighboring Tree Vertex of selected vertex
# Minimum Distance of explored vertex with neighboring vertex of partial tree
# formed in graph
_UpperCamelCase = [] # Heap of Distance of vertices from their neighboring vertex
_UpperCamelCase = []
for vertex in range(len(__snake_case ) ):
distance_tv.append(sys.maxsize )
positions.append(__snake_case )
heap.node_position.append(__snake_case )
_UpperCamelCase = []
_UpperCamelCase = 1
_UpperCamelCase = sys.maxsize
for neighbor, distance in adjacency_list[0]:
_UpperCamelCase = 0
_UpperCamelCase = distance
heap.heapify(__snake_case, __snake_case )
for _ in range(1, len(__snake_case ) ):
_UpperCamelCase = heap.delete_minimum(__snake_case, __snake_case )
if visited[vertex] == 0:
tree_edges.append((nbr_tv[vertex], vertex) )
_UpperCamelCase = 1
for neighbor, distance in adjacency_list[vertex]:
if (
visited[neighbor] == 0
and distance < distance_tv[heap.get_position(__snake_case )]
):
_UpperCamelCase = distance
heap.bottom_to_top(
__snake_case, heap.get_position(__snake_case ), __snake_case, __snake_case )
_UpperCamelCase = vertex
return tree_edges
if __name__ == "__main__": # pragma: no cover
# < --------- Prims Algorithm --------- >
_a = int(input("""Enter number of edges: """).strip())
_a = defaultdict(list)
for _ in range(edges_number):
_a = [int(x) for x in input().strip().split()]
adjacency_list[edge[0]].append([edge[1], edge[2]])
adjacency_list[edge[1]].append([edge[0], edge[2]])
print(prisms_algorithm(adjacency_list))
| 78 | 0 |
"""simple docstring"""
import json
import os
import unittest
from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer
from transformers.testing_utils import slow
from ...test_tokenization_common import TokenizerTesterMixin
class _UpperCAmelCase( __UpperCAmelCase , unittest.TestCase ):
lowercase__ = BioGptTokenizer
lowercase__ = False
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
_UpperCamelCase = [
'''l''',
'''o''',
'''w''',
'''e''',
'''r''',
'''s''',
'''t''',
'''i''',
'''d''',
'''n''',
'''w</w>''',
'''r</w>''',
'''t</w>''',
'''lo''',
'''low''',
'''er</w>''',
'''low</w>''',
'''lowest</w>''',
'''newer</w>''',
'''wider</w>''',
'''<unk>''',
]
_UpperCamelCase = dict(zip(lowerCAmelCase_ , range(len(lowerCAmelCase_))))
_UpperCamelCase = ['''l o 123''', '''lo w 1456''', '''e r</w> 1789''', '''''']
_UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''])
_UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''])
with open(self.vocab_file , '''w''') as fp:
fp.write(json.dumps(lowerCAmelCase_))
with open(self.merges_file , '''w''') as fp:
fp.write('''\n'''.join(lowerCAmelCase_))
def UpperCAmelCase ( self , __a) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = '''lower newer'''
_UpperCamelCase = '''lower newer'''
return input_text, output_text
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = BioGptTokenizer(self.vocab_file , self.merges_file)
_UpperCamelCase = '''lower'''
_UpperCamelCase = ['''low''', '''er</w>''']
_UpperCamelCase = tokenizer.tokenize(lowerCAmelCase_)
self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_)
_UpperCamelCase = tokens + ['''<unk>''']
_UpperCamelCase = [14, 15, 20]
self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase_) , lowerCAmelCase_)
@slow
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = BioGptTokenizer.from_pretrained('''microsoft/biogpt''')
_UpperCamelCase = tokenizer.encode('''sequence builders''' , add_special_tokens=lowerCAmelCase_)
_UpperCamelCase = tokenizer.encode('''multi-sequence build''' , add_special_tokens=lowerCAmelCase_)
_UpperCamelCase = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase_)
_UpperCamelCase = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase_ , lowerCAmelCase_)
self.assertTrue(encoded_sentence == [2] + text)
self.assertTrue(encoded_pair == [2] + text + [2] + text_a)
| 711 |
"""simple docstring"""
import json
import sys
def lowerCamelCase__ ( __snake_case, __snake_case ) -> Union[str, Any]:
"""simple docstring"""
with open(__snake_case, encoding='''utf-8''' ) as f:
_UpperCamelCase = json.load(__snake_case )
_UpperCamelCase = ['''<details>''', '''<summary>Show updated benchmarks!</summary>''', ''' ''']
for benchmark_name in sorted(__snake_case ):
_UpperCamelCase = results[benchmark_name]
_UpperCamelCase = benchmark_name.split('''/''' )[-1]
output_md.append(F'''### Benchmark: {benchmark_file_name}''' )
_UpperCamelCase = '''| metric |'''
_UpperCamelCase = '''|--------|'''
_UpperCamelCase = '''| new / old (diff) |'''
for metric_name in sorted(__snake_case ):
_UpperCamelCase = benchmark_res[metric_name]
_UpperCamelCase = metric_vals['''new''']
_UpperCamelCase = metric_vals.get('''old''', __snake_case )
_UpperCamelCase = metric_vals.get('''diff''', __snake_case )
_UpperCamelCase = F''' {new_val:f}''' if isinstance(__snake_case, (int, float) ) else '''None'''
if old_val is not None:
val_str += F''' / {old_val:f}''' if isinstance(__snake_case, (int, float) ) else "None"
if dif_val is not None:
val_str += F''' ({dif_val:f})''' if isinstance(__snake_case, (int, float) ) else "None"
title += " " + metric_name + " |"
lines += "---|"
value += val_str + " |"
output_md += [title, lines, value, " "]
output_md.append('''</details>''' )
with open(__snake_case, '''w''', encoding='''utf-8''' ) as f:
f.writelines('''\n'''.join(__snake_case ) )
if __name__ == "__main__":
_a = sys.argv[1]
_a = sys.argv[2]
format_json_to_md(input_json_file, output_md_file)
| 78 | 0 |
"""simple docstring"""
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available
from transformers.models.bert.tokenization_bert import BertTokenizer
from transformers.testing_utils import require_tensorflow_text, require_tf, slow
if is_tf_available():
import tensorflow as tf
if is_tensorflow_text_available():
from transformers.models.bert import TFBertTokenizer
_a = ["""bert-base-uncased""", """bert-base-cased"""]
_a = """hf-internal-testing/tiny-bert-tf-only"""
if is_tf_available():
class _UpperCAmelCase( tf.keras.Model ):
def __init__( self , __a) -> List[Any]:
'''simple docstring'''
super().__init__()
_UpperCamelCase = tokenizer
_UpperCamelCase = AutoConfig.from_pretrained(_UpperCAmelCase)
_UpperCamelCase = TFAutoModel.from_config(_UpperCAmelCase)
def UpperCAmelCase ( self , __a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.tokenizer(_UpperCAmelCase)
_UpperCamelCase = self.bert(**_UpperCAmelCase)
return out["pooler_output"]
@require_tf
@require_tensorflow_text
class _UpperCAmelCase( unittest.TestCase ):
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
super().setUp()
_UpperCamelCase = [
BertTokenizer.from_pretrained(_UpperCAmelCase) for checkpoint in (TOKENIZER_CHECKPOINTS * 2)
] # repeat for when fast_bert_tokenizer=false
_UpperCamelCase = [TFBertTokenizer.from_pretrained(_UpperCAmelCase) for checkpoint in TOKENIZER_CHECKPOINTS] + [
TFBertTokenizer.from_pretrained(_UpperCAmelCase , use_fast_bert_tokenizer=_UpperCAmelCase)
for checkpoint in TOKENIZER_CHECKPOINTS
]
assert len(self.tokenizers) == len(self.tf_tokenizers)
_UpperCamelCase = [
'''This is a straightforward English test sentence.''',
'''This one has some weird characters\rto\nsee\r\nif those\u00E9break things.''',
'''Now we\'re going to add some Chinese: 一 二 三 一二三''',
'''And some much more rare Chinese: 齉 堃 齉堃''',
'''Je vais aussi écrire en français pour tester les accents''',
'''Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ''',
]
_UpperCamelCase = list(zip(self.test_sentences , self.test_sentences[::-1]))
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers):
for test_inputs in (self.test_sentences, self.paired_sentences):
_UpperCamelCase = tokenizer(_UpperCAmelCase , return_tensors='''tf''' , padding='''longest''')
_UpperCamelCase = tf_tokenizer(_UpperCAmelCase)
for key in python_outputs.keys():
self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape))
self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key] , tf.intaa) == tf_outputs[key]))
@slow
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
for tf_tokenizer in self.tf_tokenizers:
_UpperCamelCase = tf_tokenizer(self.paired_sentences)
_UpperCamelCase = tf_tokenizer(
text=[sentence[0] for sentence in self.paired_sentences] , text_pair=[sentence[1] for sentence in self.paired_sentences] , )
for key in merged_outputs.keys():
self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key] , tf.intaa) == separated_outputs[key]))
@slow
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
for tf_tokenizer in self.tf_tokenizers:
_UpperCamelCase = tf.function(_UpperCAmelCase)
for test_inputs in (self.test_sentences, self.paired_sentences):
_UpperCamelCase = tf.constant(_UpperCAmelCase)
_UpperCamelCase = compiled_tokenizer(_UpperCAmelCase)
_UpperCamelCase = tf_tokenizer(_UpperCAmelCase)
for key in eager_outputs.keys():
self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key]))
@slow
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
for tf_tokenizer in self.tf_tokenizers:
_UpperCamelCase = ModelToSave(tokenizer=_UpperCAmelCase)
_UpperCamelCase = tf.convert_to_tensor(self.test_sentences)
_UpperCamelCase = model(_UpperCAmelCase) # Build model with some sample inputs
with TemporaryDirectory() as tempdir:
_UpperCamelCase = Path(_UpperCAmelCase) / '''saved.model'''
model.save(_UpperCAmelCase)
_UpperCamelCase = tf.keras.models.load_model(_UpperCAmelCase)
_UpperCamelCase = loaded_model(_UpperCAmelCase)
# We may see small differences because the loaded model is compiled, so we need an epsilon for the test
self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output)) , 1e-5)
| 712 |
"""simple docstring"""
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()
_a = logging.get_logger(__name__)
def lowerCamelCase__ ( __snake_case, __snake_case=False ) -> Tuple:
"""simple docstring"""
_UpperCamelCase = []
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"
_UpperCamelCase = [(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 lowerCamelCase__ ( __snake_case, __snake_case, __snake_case=False ) -> str:
"""simple docstring"""
for i in range(config.num_hidden_layers ):
if base_model:
_UpperCamelCase = ''''''
else:
_UpperCamelCase = '''vit.'''
# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
_UpperCamelCase = state_dict.pop(F'''blocks.{i}.attn.qkv.weight''' )
_UpperCamelCase = state_dict.pop(F'''blocks.{i}.attn.qkv.bias''' )
# next, add query, keys and values (in that order) to the state dict
_UpperCamelCase = in_proj_weight[
: config.hidden_size, :
]
_UpperCamelCase = in_proj_bias[: config.hidden_size]
_UpperCamelCase = in_proj_weight[
config.hidden_size : config.hidden_size * 2, :
]
_UpperCamelCase = in_proj_bias[
config.hidden_size : config.hidden_size * 2
]
_UpperCamelCase = in_proj_weight[
-config.hidden_size :, :
]
_UpperCamelCase = in_proj_bias[-config.hidden_size :]
def lowerCamelCase__ ( __snake_case ) -> Dict:
"""simple docstring"""
_UpperCamelCase = ['''head.weight''', '''head.bias''']
for k in ignore_keys:
state_dict.pop(__snake_case, __snake_case )
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> Any:
"""simple docstring"""
_UpperCamelCase = dct.pop(__snake_case )
_UpperCamelCase = val
def lowerCamelCase__ ( ) -> Dict:
"""simple docstring"""
_UpperCamelCase = '''http://images.cocodataset.org/val2017/000000039769.jpg'''
_UpperCamelCase = Image.open(requests.get(__snake_case, stream=__snake_case ).raw )
return im
@torch.no_grad()
def lowerCamelCase__ ( __snake_case, __snake_case ) -> Union[str, Any]:
"""simple docstring"""
_UpperCamelCase = ViTConfig()
_UpperCamelCase = False
# dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size
if vit_name[-5:] == "in21k":
_UpperCamelCase = True
_UpperCamelCase = int(vit_name[-12:-10] )
_UpperCamelCase = int(vit_name[-9:-6] )
else:
_UpperCamelCase = 10_00
_UpperCamelCase = '''huggingface/label-files'''
_UpperCamelCase = '''imagenet-1k-id2label.json'''
_UpperCamelCase = json.load(open(hf_hub_download(__snake_case, __snake_case, repo_type='''dataset''' ), '''r''' ) )
_UpperCamelCase = {int(__snake_case ): v for k, v in idalabel.items()}
_UpperCamelCase = idalabel
_UpperCamelCase = {v: k for k, v in idalabel.items()}
_UpperCamelCase = int(vit_name[-6:-4] )
_UpperCamelCase = int(vit_name[-3:] )
# size of the architecture
if "deit" in vit_name:
if vit_name[9:].startswith('''tiny''' ):
_UpperCamelCase = 1_92
_UpperCamelCase = 7_68
_UpperCamelCase = 12
_UpperCamelCase = 3
elif vit_name[9:].startswith('''small''' ):
_UpperCamelCase = 3_84
_UpperCamelCase = 15_36
_UpperCamelCase = 12
_UpperCamelCase = 6
else:
pass
else:
if vit_name[4:].startswith('''small''' ):
_UpperCamelCase = 7_68
_UpperCamelCase = 23_04
_UpperCamelCase = 8
_UpperCamelCase = 8
elif vit_name[4:].startswith('''base''' ):
pass
elif vit_name[4:].startswith('''large''' ):
_UpperCamelCase = 10_24
_UpperCamelCase = 40_96
_UpperCamelCase = 24
_UpperCamelCase = 16
elif vit_name[4:].startswith('''huge''' ):
_UpperCamelCase = 12_80
_UpperCamelCase = 51_20
_UpperCamelCase = 32
_UpperCamelCase = 16
# load original model from timm
_UpperCamelCase = timm.create_model(__snake_case, pretrained=__snake_case )
timm_model.eval()
# load state_dict of original model, remove and rename some keys
_UpperCamelCase = timm_model.state_dict()
if base_model:
remove_classification_head_(__snake_case )
_UpperCamelCase = create_rename_keys(__snake_case, __snake_case )
for src, dest in rename_keys:
rename_key(__snake_case, __snake_case, __snake_case )
read_in_q_k_v(__snake_case, __snake_case, __snake_case )
# load HuggingFace model
if vit_name[-5:] == "in21k":
_UpperCamelCase = ViTModel(__snake_case ).eval()
else:
_UpperCamelCase = ViTForImageClassification(__snake_case ).eval()
model.load_state_dict(__snake_case )
# Check outputs on an image, prepared by ViTImageProcessor/DeiTImageProcessor
if "deit" in vit_name:
_UpperCamelCase = DeiTImageProcessor(size=config.image_size )
else:
_UpperCamelCase = ViTImageProcessor(size=config.image_size )
_UpperCamelCase = image_processor(images=prepare_img(), return_tensors='''pt''' )
_UpperCamelCase = encoding['''pixel_values''']
_UpperCamelCase = model(__snake_case )
if base_model:
_UpperCamelCase = timm_model.forward_features(__snake_case )
assert timm_pooled_output.shape == outputs.pooler_output.shape
assert torch.allclose(__snake_case, outputs.pooler_output, atol=1e-3 )
else:
_UpperCamelCase = timm_model(__snake_case )
assert timm_logits.shape == outputs.logits.shape
assert torch.allclose(__snake_case, outputs.logits, atol=1e-3 )
Path(__snake_case ).mkdir(exist_ok=__snake_case )
print(F'''Saving model {vit_name} to {pytorch_dump_folder_path}''' )
model.save_pretrained(__snake_case )
print(F'''Saving image processor to {pytorch_dump_folder_path}''' )
image_processor.save_pretrained(__snake_case )
if __name__ == "__main__":
_a = 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."""
)
_a = parser.parse_args()
convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path)
| 78 | 0 |
"""simple docstring"""
# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING
import numpy as np
import pyarrow as pa
from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter
if TYPE_CHECKING:
import torch
class a_( TensorFormatter[Mapping, 'torch.Tensor', Mapping] ):
def __init__( self , __a=None , **__a) -> Union[str, Any]:
'''simple docstring'''
super().__init__(features=_A)
_UpperCamelCase = torch_tensor_kwargs
import torch # noqa import torch at initialization
def UpperCAmelCase ( self , __a) -> List[str]:
'''simple docstring'''
import torch
if isinstance(_A , _A) and column:
if all(
isinstance(_A , torch.Tensor) and x.shape == column[0].shape and x.dtype == column[0].dtype
for x in column):
return torch.stack(_A)
return column
def UpperCAmelCase ( self , __a) -> Union[str, Any]:
'''simple docstring'''
import torch
if isinstance(_A , (str, bytes, type(_A))):
return value
elif isinstance(_A , (np.character, np.ndarray)) and np.issubdtype(value.dtype , np.character):
return value.tolist()
_UpperCamelCase = {}
if isinstance(_A , (np.number, np.ndarray)) and np.issubdtype(value.dtype , np.integer):
_UpperCamelCase = {'''dtype''': torch.intaa}
elif isinstance(_A , (np.number, np.ndarray)) and np.issubdtype(value.dtype , np.floating):
_UpperCamelCase = {'''dtype''': torch.floataa}
elif config.PIL_AVAILABLE and "PIL" in sys.modules:
import PIL.Image
if isinstance(_A , PIL.Image.Image):
_UpperCamelCase = np.asarray(_A)
return torch.tensor(_A , **{**default_dtype, **self.torch_tensor_kwargs})
def UpperCAmelCase ( self , __a) -> Optional[int]:
'''simple docstring'''
import torch
# support for torch, tf, jax etc.
if hasattr(_A , '''__array__''') and not isinstance(_A , torch.Tensor):
_UpperCamelCase = data_struct.__array__()
# support for nested types like struct of list of struct
if isinstance(_A , np.ndarray):
if data_struct.dtype == object: # torch tensors cannot be instantied from an array of objects
return self._consolidate([self.recursive_tensorize(_A) for substruct in data_struct])
elif isinstance(_A , (list, tuple)):
return self._consolidate([self.recursive_tensorize(_A) for substruct in data_struct])
return self._tensorize(_A)
def UpperCAmelCase ( self , __a) -> Union[str, Any]:
'''simple docstring'''
return map_nested(self._recursive_tensorize , _A , map_list=_A)
def UpperCAmelCase ( self , __a) -> str:
'''simple docstring'''
_UpperCamelCase = self.numpy_arrow_extractor().extract_row(_A)
_UpperCamelCase = self.python_features_decoder.decode_row(_A)
return self.recursive_tensorize(_A)
def UpperCAmelCase ( self , __a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.numpy_arrow_extractor().extract_column(_A)
_UpperCamelCase = self.python_features_decoder.decode_column(_A , pa_table.column_names[0])
_UpperCamelCase = self.recursive_tensorize(_A)
_UpperCamelCase = self._consolidate(_A)
return column
def UpperCAmelCase ( self , __a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.numpy_arrow_extractor().extract_batch(_A)
_UpperCamelCase = self.python_features_decoder.decode_batch(_A)
_UpperCamelCase = self.recursive_tensorize(_A)
for column_name in batch:
_UpperCamelCase = self._consolidate(batch[column_name])
return batch
| 713 |
"""simple docstring"""
import unittest
from transformers import AlbertConfig, is_torch_available
from transformers.models.auto import get_values
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 (
MODEL_FOR_PRETRAINING_MAPPING,
AlbertForMaskedLM,
AlbertForMultipleChoice,
AlbertForPreTraining,
AlbertForQuestionAnswering,
AlbertForSequenceClassification,
AlbertForTokenClassification,
AlbertModel,
)
from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST
class _UpperCAmelCase:
def __init__( self , __a , __a=13 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=99 , __a=16 , __a=36 , __a=6 , __a=6 , __a=6 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=5_12 , __a=16 , __a=2 , __a=0.02 , __a=3 , __a=4 , __a=None , ) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = parent
_UpperCamelCase = batch_size
_UpperCamelCase = seq_length
_UpperCamelCase = is_training
_UpperCamelCase = use_input_mask
_UpperCamelCase = use_token_type_ids
_UpperCamelCase = use_labels
_UpperCamelCase = vocab_size
_UpperCamelCase = embedding_size
_UpperCamelCase = hidden_size
_UpperCamelCase = num_hidden_layers
_UpperCamelCase = num_hidden_groups
_UpperCamelCase = num_attention_heads
_UpperCamelCase = intermediate_size
_UpperCamelCase = hidden_act
_UpperCamelCase = hidden_dropout_prob
_UpperCamelCase = attention_probs_dropout_prob
_UpperCamelCase = max_position_embeddings
_UpperCamelCase = type_vocab_size
_UpperCamelCase = type_sequence_label_size
_UpperCamelCase = initializer_range
_UpperCamelCase = num_labels
_UpperCamelCase = num_choices
_UpperCamelCase = scope
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size)
_UpperCamelCase = None
if self.use_input_mask:
_UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length])
_UpperCamelCase = None
if self.use_token_type_ids:
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size)
_UpperCamelCase = None
_UpperCamelCase = None
_UpperCamelCase = None
if self.use_labels:
_UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size)
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels)
_UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices)
_UpperCamelCase = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
return 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 , initializer_range=self.initializer_range , num_hidden_groups=self.num_hidden_groups , )
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = AlbertModel(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a , attention_mask=__a , token_type_ids=__a)
_UpperCamelCase = model(__a , token_type_ids=__a)
_UpperCamelCase = model(__a)
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))
self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = AlbertForPreTraining(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(
__a , attention_mask=__a , token_type_ids=__a , labels=__a , sentence_order_label=__a , )
self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size))
self.parent.assertEqual(result.sop_logits.shape , (self.batch_size, config.num_labels))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = AlbertForMaskedLM(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a , attention_mask=__a , token_type_ids=__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) -> Any:
'''simple docstring'''
_UpperCamelCase = AlbertForQuestionAnswering(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(
__a , attention_mask=__a , token_type_ids=__a , start_positions=__a , end_positions=__a , )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length))
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = self.num_labels
_UpperCamelCase = AlbertForSequenceClassification(__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.num_labels
_UpperCamelCase = AlbertForTokenClassification(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = self.num_choices
_UpperCamelCase = AlbertForMultipleChoice(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = input_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous()
_UpperCamelCase = token_type_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous()
_UpperCamelCase = input_mask.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous()
_UpperCamelCase = model(
__a , attention_mask=__a , token_type_ids=__a , labels=__a , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices))
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = self.prepare_config_and_inputs()
(
(
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) ,
) = config_and_inputs
_UpperCamelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
return config, inputs_dict
@require_torch
class _UpperCAmelCase( lowerCamelCase , lowerCamelCase , unittest.TestCase ):
lowercase__ = (
(
AlbertModel,
AlbertForPreTraining,
AlbertForMaskedLM,
AlbertForMultipleChoice,
AlbertForSequenceClassification,
AlbertForTokenClassification,
AlbertForQuestionAnswering,
)
if is_torch_available()
else ()
)
lowercase__ = (
{
'feature-extraction': AlbertModel,
'fill-mask': AlbertForMaskedLM,
'question-answering': AlbertForQuestionAnswering,
'text-classification': AlbertForSequenceClassification,
'token-classification': AlbertForTokenClassification,
'zero-shot': AlbertForSequenceClassification,
}
if is_torch_available()
else {}
)
lowercase__ = True
def UpperCAmelCase ( self , __a , __a , __a=False) -> List[str]:
'''simple docstring'''
_UpperCamelCase = super()._prepare_for_class(__a , __a , return_labels=__a)
if return_labels:
if model_class in get_values(__a):
_UpperCamelCase = torch.zeros(
(self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=__a)
_UpperCamelCase = torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=__a)
return inputs_dict
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = AlbertModelTester(self)
_UpperCamelCase = ConfigTester(self , config_class=__a , hidden_size=37)
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
self.config_tester.run_common_tests()
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__a)
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_pretraining(*__a)
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*__a)
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*__a)
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*__a)
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*__a)
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
_UpperCamelCase = type
self.model_tester.create_and_check_model(*__a)
@slow
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_UpperCamelCase = AlbertModel.from_pretrained(__a)
self.assertIsNotNone(__a)
@require_torch
class _UpperCAmelCase( unittest.TestCase ):
@slow
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = AlbertModel.from_pretrained('''albert-base-v2''')
_UpperCamelCase = torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]])
_UpperCamelCase = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
with torch.no_grad():
_UpperCamelCase = model(__a , attention_mask=__a)[0]
_UpperCamelCase = torch.Size((1, 11, 7_68))
self.assertEqual(output.shape , __a)
_UpperCamelCase = torch.tensor(
[[[-0.6513, 1.5035, -0.2766], [-0.6515, 1.5046, -0.2780], [-0.6512, 1.5049, -0.2784]]])
self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __a , atol=1e-4))
| 78 | 0 |
"""simple docstring"""
def lowerCamelCase__ ( __snake_case , __snake_case ) -> int:
"""simple docstring"""
return 1 if input_a == input_a else 0
def lowerCamelCase__ ( ) -> None:
"""simple docstring"""
assert xnor_gate(0 , 0 ) == 1
assert xnor_gate(0 , 1 ) == 0
assert xnor_gate(1 , 0 ) == 0
assert xnor_gate(1 , 1 ) == 1
if __name__ == "__main__":
print(xnor_gate(0, 0))
print(xnor_gate(0, 1))
print(xnor_gate(1, 0))
print(xnor_gate(1, 1))
| 714 |
"""simple docstring"""
import os
from typing import BinaryIO, Optional, Union
import numpy as np
import pyarrow.parquet as pq
from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config
from ..features.features import FeatureType, _visit
from ..formatting import query_table
from ..packaged_modules import _PACKAGED_DATASETS_MODULES
from ..packaged_modules.parquet.parquet import Parquet
from ..utils import logging
from ..utils.typing import NestedDataStructureLike, PathLike
from .abc import AbstractDatasetReader
def lowerCamelCase__ ( __snake_case ) -> Optional[int]:
"""simple docstring"""
_UpperCamelCase = np.inf
def set_batch_size(__snake_case ) -> None:
nonlocal batch_size
if isinstance(__snake_case, __snake_case ):
_UpperCamelCase = min(__snake_case, config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS )
elif isinstance(__snake_case, __snake_case ):
_UpperCamelCase = min(__snake_case, config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS )
elif isinstance(__snake_case, __snake_case ) and feature.dtype == "binary":
_UpperCamelCase = min(__snake_case, config.PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS )
_visit(__snake_case, __snake_case )
return None if batch_size is np.inf else batch_size
class _UpperCAmelCase( lowerCamelCase ):
def __init__( self , __a , __a = None , __a = None , __a = None , __a = False , __a = False , __a = None , **__a , ) -> Dict:
'''simple docstring'''
super().__init__(
__a , split=__a , features=__a , cache_dir=__a , keep_in_memory=__a , streaming=__a , num_proc=__a , **__a , )
_UpperCamelCase = path_or_paths if isinstance(__a , __a) else {self.split: path_or_paths}
_UpperCamelCase = _PACKAGED_DATASETS_MODULES['''parquet'''][1]
_UpperCamelCase = Parquet(
cache_dir=__a , data_files=__a , features=__a , hash=__a , **__a , )
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
# Build iterable dataset
if self.streaming:
_UpperCamelCase = self.builder.as_streaming_dataset(split=self.split)
# Build regular (map-style) dataset
else:
_UpperCamelCase = None
_UpperCamelCase = None
_UpperCamelCase = None
_UpperCamelCase = None
self.builder.download_and_prepare(
download_config=__a , download_mode=__a , verification_mode=__a , base_path=__a , num_proc=self.num_proc , )
_UpperCamelCase = self.builder.as_dataset(
split=self.split , verification_mode=__a , in_memory=self.keep_in_memory)
return dataset
class _UpperCAmelCase:
def __init__( self , __a , __a , __a = None , **__a , ) -> Dict:
'''simple docstring'''
_UpperCamelCase = dataset
_UpperCamelCase = path_or_buf
_UpperCamelCase = batch_size or get_writer_batch_size(dataset.features)
_UpperCamelCase = parquet_writer_kwargs
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
_UpperCamelCase = self.batch_size if self.batch_size else config.DEFAULT_MAX_BATCH_SIZE
if isinstance(self.path_or_buf , (str, bytes, os.PathLike)):
with open(self.path_or_buf , '''wb+''') as buffer:
_UpperCamelCase = self._write(file_obj=__a , batch_size=__a , **self.parquet_writer_kwargs)
else:
_UpperCamelCase = self._write(file_obj=self.path_or_buf , batch_size=__a , **self.parquet_writer_kwargs)
return written
def UpperCAmelCase ( self , __a , __a , **__a) -> int:
'''simple docstring'''
_UpperCamelCase = 0
_UpperCamelCase = parquet_writer_kwargs.pop('''path_or_buf''' , __a)
_UpperCamelCase = self.dataset.features.arrow_schema
_UpperCamelCase = pq.ParquetWriter(__a , schema=__a , **__a)
for offset in logging.tqdm(
range(0 , len(self.dataset) , __a) , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating parquet from Arrow format''' , ):
_UpperCamelCase = query_table(
table=self.dataset._data , key=slice(__a , offset + batch_size) , indices=self.dataset._indices if self.dataset._indices is not None else None , )
writer.write_table(__a)
written += batch.nbytes
writer.close()
return written
| 78 | 0 |
"""simple docstring"""
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 ):
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
_UpperCamelCase = tempfile.mkdtemp()
_UpperCamelCase = BlipImageProcessor()
_UpperCamelCase = GPTaTokenizer.from_pretrained('''hf-internal-testing/tiny-random-GPT2Model''')
_UpperCamelCase = BlipaProcessor(__a , __a)
processor.save_pretrained(self.tmpdirname)
def UpperCAmelCase ( self , **__a) -> Optional[int]:
'''simple docstring'''
return AutoProcessor.from_pretrained(self.tmpdirname , **__a).tokenizer
def UpperCAmelCase ( self , **__a) -> Union[str, Any]:
'''simple docstring'''
return AutoProcessor.from_pretrained(self.tmpdirname , **__a).image_processor
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
shutil.rmtree(self.tmpdirname)
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta)]
_UpperCamelCase = [Image.fromarray(np.moveaxis(__a , 0 , -1)) for x in image_inputs]
return image_inputs
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase = BlipaProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor())
processor.save_pretrained(self.tmpdirname)
_UpperCamelCase = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''')
_UpperCamelCase = self.get_image_processor(do_normalize=__a , padding_value=1.0)
_UpperCamelCase = BlipaProcessor.from_pretrained(
self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=__a , padding_value=1.0)
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) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.get_image_processor()
_UpperCamelCase = self.get_tokenizer()
_UpperCamelCase = BlipaProcessor(tokenizer=__a , image_processor=__a)
_UpperCamelCase = self.prepare_image_inputs()
_UpperCamelCase = image_processor(__a , return_tensors='''np''')
_UpperCamelCase = processor(images=__a , 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 UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.get_image_processor()
_UpperCamelCase = self.get_tokenizer()
_UpperCamelCase = BlipaProcessor(tokenizer=__a , image_processor=__a)
_UpperCamelCase = '''lower newer'''
_UpperCamelCase = processor(text=__a)
_UpperCamelCase = tokenizer(__a , return_token_type_ids=__a)
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key])
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = self.get_image_processor()
_UpperCamelCase = self.get_tokenizer()
_UpperCamelCase = BlipaProcessor(tokenizer=__a , image_processor=__a)
_UpperCamelCase = '''lower newer'''
_UpperCamelCase = self.prepare_image_inputs()
_UpperCamelCase = processor(text=__a , images=__a)
self.assertListEqual(list(inputs.keys()) , ['''pixel_values''', '''input_ids''', '''attention_mask'''])
# test if it raises when no input is passed
with pytest.raises(__a):
processor()
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.get_image_processor()
_UpperCamelCase = self.get_tokenizer()
_UpperCamelCase = BlipaProcessor(tokenizer=__a , image_processor=__a)
_UpperCamelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
_UpperCamelCase = processor.batch_decode(__a)
_UpperCamelCase = tokenizer.batch_decode(__a)
self.assertListEqual(__a , __a)
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = self.get_image_processor()
_UpperCamelCase = self.get_tokenizer()
_UpperCamelCase = BlipaProcessor(tokenizer=__a , image_processor=__a)
_UpperCamelCase = '''lower newer'''
_UpperCamelCase = self.prepare_image_inputs()
_UpperCamelCase = processor(text=__a , images=__a)
# For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask']
self.assertListEqual(list(inputs.keys()) , ['''pixel_values''', '''input_ids''', '''attention_mask'''])
| 715 |
"""simple docstring"""
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import MobileViTImageProcessor
class _UpperCAmelCase( unittest.TestCase ):
def __init__( self , __a , __a=7 , __a=3 , __a=18 , __a=30 , __a=4_00 , __a=True , __a=None , __a=True , __a=None , __a=True , ) -> int:
'''simple docstring'''
_UpperCamelCase = size if size is not None else {'''shortest_edge''': 20}
_UpperCamelCase = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}
_UpperCamelCase = parent
_UpperCamelCase = batch_size
_UpperCamelCase = num_channels
_UpperCamelCase = image_size
_UpperCamelCase = min_resolution
_UpperCamelCase = max_resolution
_UpperCamelCase = do_resize
_UpperCamelCase = size
_UpperCamelCase = do_center_crop
_UpperCamelCase = crop_size
_UpperCamelCase = do_flip_channel_order
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
return {
"do_resize": self.do_resize,
"size": self.size,
"do_center_crop": self.do_center_crop,
"crop_size": self.crop_size,
"do_flip_channel_order": self.do_flip_channel_order,
}
@require_torch
@require_vision
class _UpperCAmelCase( lowerCamelCase , unittest.TestCase ):
lowercase__ = MobileViTImageProcessor if is_vision_available() else None
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = MobileViTImageProcessingTester(self)
@property
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
return self.image_processor_tester.prepare_image_processor_dict()
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(__a , '''do_resize'''))
self.assertTrue(hasattr(__a , '''size'''))
self.assertTrue(hasattr(__a , '''do_center_crop'''))
self.assertTrue(hasattr(__a , '''center_crop'''))
self.assertTrue(hasattr(__a , '''do_flip_channel_order'''))
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.image_processing_class.from_dict(self.image_processor_dict)
self.assertEqual(image_processor.size , {'''shortest_edge''': 20})
self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18})
_UpperCamelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84)
self.assertEqual(image_processor.size , {'''shortest_edge''': 42})
self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84})
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
pass
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
# Initialize image_processing
_UpperCamelCase = self.image_processing_class(**self.image_processor_dict)
# create random PIL images
_UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a)
for image in image_inputs:
self.assertIsInstance(__a , Image.Image)
# Test not batched input
_UpperCamelCase = image_processing(image_inputs[0] , return_tensors='''pt''').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
# Test batched
_UpperCamelCase = image_processing(__a , return_tensors='''pt''').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
# Initialize image_processing
_UpperCamelCase = self.image_processing_class(**self.image_processor_dict)
# create random numpy tensors
_UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , numpify=__a)
for image in image_inputs:
self.assertIsInstance(__a , np.ndarray)
# Test not batched input
_UpperCamelCase = image_processing(image_inputs[0] , return_tensors='''pt''').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
# Test batched
_UpperCamelCase = image_processing(__a , return_tensors='''pt''').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
# Initialize image_processing
_UpperCamelCase = self.image_processing_class(**self.image_processor_dict)
# create random PyTorch tensors
_UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , torchify=__a)
for image in image_inputs:
self.assertIsInstance(__a , torch.Tensor)
# Test not batched input
_UpperCamelCase = image_processing(image_inputs[0] , return_tensors='''pt''').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
# Test batched
_UpperCamelCase = image_processing(__a , return_tensors='''pt''').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
| 78 | 0 |
"""simple docstring"""
import argparse
import shutil
import time
from json import JSONDecodeError
from logging import getLogger
from pathlib import Path
from typing import Dict, List
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
from transformers import AutoModelForSeqaSeqLM, AutoTokenizer
from utils import (
SeqaSeqDataset,
calculate_bleu,
calculate_rouge,
chunks,
lmap,
load_json,
parse_numeric_n_bool_cl_kwargs,
save_json,
use_task_specific_params,
write_txt_file,
)
_a = getLogger(__name__)
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case, __snake_case = 8, __snake_case = 10_24, __snake_case="val", __snake_case=None, __snake_case=False, __snake_case="summarization", __snake_case=None, __snake_case=1, __snake_case = None, __snake_case="", **__snake_case, ) -> List[Any]:
"""simple docstring"""
_UpperCamelCase = str(__snake_case )
assert local_rank is not None
torch.distributed.init_process_group(backend='''nccl''', rank=__snake_case )
_UpperCamelCase = Path(__snake_case )
_UpperCamelCase = save_dir.joinpath(F'''rank_{local_rank}_output.json''' )
torch.cuda.set_device(__snake_case )
_UpperCamelCase = AutoModelForSeqaSeqLM.from_pretrained(__snake_case ).cuda()
if fpaa:
_UpperCamelCase = model.half()
# determine if we need to increase num_beams
use_task_specific_params(__snake_case, __snake_case ) # update config with task specific params
_UpperCamelCase = generate_kwargs.pop('''num_beams''', model.config.num_beams ) # AttributeError risk?
if num_return_sequences > num_beams:
_UpperCamelCase = num_return_sequences
_UpperCamelCase = AutoTokenizer.from_pretrained(__snake_case )
logger.info(F'''Inferred tokenizer type: {tokenizer.__class__}''' ) # if this is wrong, check config.model_type.
if max_source_length is None:
_UpperCamelCase = tokenizer.model_max_length
if prefix is None:
_UpperCamelCase = prefix or getattr(model.config, '''prefix''', '''''' ) or ''''''
_UpperCamelCase = SeqaSeqDataset(
__snake_case, __snake_case, __snake_case, max_target_length=10_24, type_path=__snake_case, n_obs=__snake_case, prefix=__snake_case, **__snake_case, )
# I set shuffle=True for a more accurate progress bar.
# If all the longest samples are first, the prog bar estimate is too high at the beginning.
_UpperCamelCase = ds.make_sortish_sampler(__snake_case, distributed=__snake_case, add_extra_examples=__snake_case, shuffle=__snake_case )
_UpperCamelCase = DataLoader(__snake_case, sampler=__snake_case, batch_size=__snake_case, collate_fn=ds.collate_fn )
_UpperCamelCase = []
for batch in tqdm(__snake_case ):
_UpperCamelCase = model.generate(
input_ids=batch['''input_ids'''].to(model.device ), attention_mask=batch['''attention_mask'''].to(model.device ), num_return_sequences=__snake_case, num_beams=__snake_case, **__snake_case, )
_UpperCamelCase = tokenizer.batch_decode(__snake_case, skip_special_tokens=__snake_case, clean_up_tokenization_spaces=__snake_case )
_UpperCamelCase = batch['''ids''']
if num_return_sequences > 1:
_UpperCamelCase = chunks(__snake_case, __snake_case ) # batch size chunks, each of size num_return_seq
for i, pred in enumerate(__snake_case ):
results.append({'''pred''': pred, '''id''': ids[i].item()} )
save_json(__snake_case, __snake_case )
return results, sampler.num_replicas
def lowerCamelCase__ ( ) -> Union[str, Any]:
"""simple docstring"""
_UpperCamelCase = argparse.ArgumentParser(
epilog='''Unspecified args like --num_beams=2 --decoder_start_token_id=4 are passed to model.generate''' )
parser.add_argument('''--data_dir''', type=__snake_case, help='''like cnn_dm/test.source''' )
parser.add_argument(
'''--model_name''', type=__snake_case, help='''like facebook/bart-large-cnn,t5-base, etc.''', default='''sshleifer/distilbart-xsum-12-3''', )
parser.add_argument('''--save_dir''', type=__snake_case, help='''where to save''', default='''tmp_gen''' )
parser.add_argument('''--max_source_length''', type=__snake_case, default=__snake_case )
parser.add_argument(
'''--type_path''', type=__snake_case, default='''test''', help='''which subset to evaluate typically train/val/test''' )
parser.add_argument('''--task''', type=__snake_case, default='''summarization''', help='''used for task_specific_params + metrics''' )
parser.add_argument('''--bs''', type=__snake_case, default=8, required=__snake_case, help='''batch size''' )
parser.add_argument(
'''--local_rank''', type=__snake_case, default=-1, required=__snake_case, help='''should be passed by distributed.launch''' )
parser.add_argument(
'''--n_obs''', type=__snake_case, default=__snake_case, required=__snake_case, help='''How many observations. Defaults to all.''' )
parser.add_argument(
'''--num_return_sequences''', type=__snake_case, default=1, required=__snake_case, help='''How many sequences to return''' )
parser.add_argument(
'''--sync_timeout''', type=__snake_case, default=6_00, required=__snake_case, help='''How long should master process wait for other processes to finish.''', )
parser.add_argument('''--src_lang''', type=__snake_case, default=__snake_case, required=__snake_case )
parser.add_argument('''--tgt_lang''', type=__snake_case, default=__snake_case, required=__snake_case )
parser.add_argument(
'''--prefix''', type=__snake_case, required=__snake_case, default=__snake_case, help='''will be added to the begininng of src examples''' )
parser.add_argument('''--fp16''', action='''store_true''' )
parser.add_argument('''--debug''', action='''store_true''' )
_UpperCamelCase = time.time()
_UpperCamelCase , _UpperCamelCase = parser.parse_known_args()
_UpperCamelCase = parse_numeric_n_bool_cl_kwargs(__snake_case )
if generate_kwargs and args.local_rank <= 0:
print(F'''parsed the following generate kwargs: {generate_kwargs}''' )
_UpperCamelCase = Path(args.save_dir + '''_tmp''' )
Path(__snake_case ).mkdir(exist_ok=__snake_case ) # this handles locking.
_UpperCamelCase = list(json_save_dir.glob('''rank_*.json''' ) )
if intermediate_files:
raise ValueError(F'''Found files at {json_save_dir} please move or remove them.''' )
# In theory, a node could finish and save before another node hits this. If this happens, we can address later.
_UpperCamelCase = {}
if args.src_lang is not None:
_UpperCamelCase = args.src_lang
if args.tgt_lang is not None:
_UpperCamelCase = args.tgt_lang
Path(args.save_dir ).mkdir(exist_ok=__snake_case )
_UpperCamelCase , _UpperCamelCase = eval_data_dir(
args.data_dir, __snake_case, args.model_name, type_path=args.type_path, bs=args.bs, fpaa=args.fpaa, task=args.task, local_rank=args.local_rank, n_obs=args.n_obs, max_source_length=args.max_source_length, num_return_sequences=args.num_return_sequences, prefix=args.prefix, dataset_kwargs=__snake_case, **__snake_case, )
if args.local_rank <= 0:
_UpperCamelCase = Path(args.save_dir )
save_dir.mkdir(exist_ok=__snake_case )
_UpperCamelCase = gather_results_from_each_node(__snake_case, __snake_case, args.sync_timeout )
_UpperCamelCase = combine_partial_results(__snake_case )
if args.num_return_sequences > 1:
_UpperCamelCase = save_dir.joinpath('''pseudolabel_results.json''' )
print(F'''Saving aggregated results at {save_path}, intermediate in {json_save_dir}/''' )
save_json(__snake_case, __snake_case )
return
_UpperCamelCase = Path(args.data_dir ).joinpath(args.type_path + '''.target''' )
with open(__snake_case ) as f:
_UpperCamelCase = [x.rstrip() for x in f.readlines()][: len(__snake_case )]
# Calculate metrics, save metrics, and save _generations.txt
_UpperCamelCase = '''translation''' in args.task
_UpperCamelCase = calculate_bleu if calc_bleu else calculate_rouge
_UpperCamelCase = '''bleu''' if calc_bleu else '''rouge'''
_UpperCamelCase = score_fn(__snake_case, __snake_case )
_UpperCamelCase = len(__snake_case )
_UpperCamelCase = time.time() - start_time
_UpperCamelCase = round(runtime / metrics['''n_obs'''], 4 )
_UpperCamelCase = num_replicas
# TODO(@stas00): add whatever metadata to metrics
_UpperCamelCase = save_dir.joinpath(F'''{args.type_path}_{metric_name}.json''' )
save_json(__snake_case, __snake_case, indent=__snake_case )
print(__snake_case )
write_txt_file(__snake_case, save_dir.joinpath(F'''{args.type_path}_generations.txt''' ) )
if args.debug:
write_txt_file(__snake_case, save_dir.joinpath(F'''{args.type_path}.target''' ) )
else:
shutil.rmtree(__snake_case )
def lowerCamelCase__ ( __snake_case ) -> str:
"""simple docstring"""
_UpperCamelCase = []
for partial_result in partial_results:
records.extend(__snake_case )
_UpperCamelCase = sorted(__snake_case, key=lambda __snake_case : x["id"] )
_UpperCamelCase = [x['''pred'''] for x in records]
return preds
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> Dict:
"""simple docstring"""
_UpperCamelCase = time.time()
logger.info('''waiting for all nodes to finish''' )
_UpperCamelCase = None
while (time.time() - start_wait) < timeout:
_UpperCamelCase = list(save_dir.glob('''rank_*.json''' ) )
if len(__snake_case ) < num_replicas:
continue
try:
# make sure all json files are fully saved
_UpperCamelCase = lmap(__snake_case, __snake_case )
return json_data
except JSONDecodeError:
continue
else:
raise TimeoutError('''Rank 0 gave up on waiting for other processes''' )
# Unreachable
if __name__ == "__main__":
# Usage for MT:
run_generate()
| 716 |
"""simple docstring"""
import warnings
from typing import List
import numpy as np
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import is_flax_available, is_tf_available, is_torch_available
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = ['image_processor', 'tokenizer']
lowercase__ = 'OwlViTImageProcessor'
lowercase__ = ('CLIPTokenizer', 'CLIPTokenizerFast')
def __init__( self , __a=None , __a=None , **__a) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = None
if "feature_extractor" in kwargs:
warnings.warn(
'''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
''' instead.''' , __a , )
_UpperCamelCase = kwargs.pop('''feature_extractor''')
_UpperCamelCase = image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError('''You need to specify an `image_processor`.''')
if tokenizer is None:
raise ValueError('''You need to specify a `tokenizer`.''')
super().__init__(__a , __a)
def __call__( self , __a=None , __a=None , __a=None , __a="max_length" , __a="np" , **__a) -> List[str]:
'''simple docstring'''
if text is None and query_images is None and images is None:
raise ValueError(
'''You have to specify at least one text or query image or image. All three cannot be none.''')
if text is not None:
if isinstance(__a , __a) or (isinstance(__a , __a) and not isinstance(text[0] , __a)):
_UpperCamelCase = [self.tokenizer(__a , padding=__a , return_tensors=__a , **__a)]
elif isinstance(__a , __a) and isinstance(text[0] , __a):
_UpperCamelCase = []
# Maximum number of queries across batch
_UpperCamelCase = max([len(__a) for t in text])
# Pad all batch samples to max number of text queries
for t in text:
if len(__a) != max_num_queries:
_UpperCamelCase = t + [''' '''] * (max_num_queries - len(__a))
_UpperCamelCase = self.tokenizer(__a , padding=__a , return_tensors=__a , **__a)
encodings.append(__a)
else:
raise TypeError('''Input text should be a string, a list of strings or a nested list of strings''')
if return_tensors == "np":
_UpperCamelCase = np.concatenate([encoding['''input_ids'''] for encoding in encodings] , axis=0)
_UpperCamelCase = np.concatenate([encoding['''attention_mask'''] for encoding in encodings] , axis=0)
elif return_tensors == "jax" and is_flax_available():
import jax.numpy as jnp
_UpperCamelCase = jnp.concatenate([encoding['''input_ids'''] for encoding in encodings] , axis=0)
_UpperCamelCase = jnp.concatenate([encoding['''attention_mask'''] for encoding in encodings] , axis=0)
elif return_tensors == "pt" and is_torch_available():
import torch
_UpperCamelCase = torch.cat([encoding['''input_ids'''] for encoding in encodings] , dim=0)
_UpperCamelCase = torch.cat([encoding['''attention_mask'''] for encoding in encodings] , dim=0)
elif return_tensors == "tf" and is_tf_available():
import tensorflow as tf
_UpperCamelCase = tf.stack([encoding['''input_ids'''] for encoding in encodings] , axis=0)
_UpperCamelCase = tf.stack([encoding['''attention_mask'''] for encoding in encodings] , axis=0)
else:
raise ValueError('''Target return tensor type could not be returned''')
_UpperCamelCase = BatchEncoding()
_UpperCamelCase = input_ids
_UpperCamelCase = attention_mask
if query_images is not None:
_UpperCamelCase = BatchEncoding()
_UpperCamelCase = self.image_processor(
__a , return_tensors=__a , **__a).pixel_values
_UpperCamelCase = query_pixel_values
if images is not None:
_UpperCamelCase = self.image_processor(__a , return_tensors=__a , **__a)
if text is not None and images is not None:
_UpperCamelCase = image_features.pixel_values
return encoding
elif query_images is not None and images is not None:
_UpperCamelCase = image_features.pixel_values
return encoding
elif text is not None or query_images is not None:
return encoding
else:
return BatchEncoding(data=dict(**__a) , tensor_type=__a)
def UpperCAmelCase ( self , *__a , **__a) -> str:
'''simple docstring'''
return self.image_processor.post_process(*__a , **__a)
def UpperCAmelCase ( self , *__a , **__a) -> Dict:
'''simple docstring'''
return self.image_processor.post_process_object_detection(*__a , **__a)
def UpperCAmelCase ( self , *__a , **__a) -> Optional[Any]:
'''simple docstring'''
return self.image_processor.post_process_image_guided_detection(*__a , **__a)
def UpperCAmelCase ( self , *__a , **__a) -> Optional[int]:
'''simple docstring'''
return self.tokenizer.batch_decode(*__a , **__a)
def UpperCAmelCase ( self , *__a , **__a) -> Optional[Any]:
'''simple docstring'''
return self.tokenizer.decode(*__a , **__a)
@property
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
warnings.warn(
'''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , __a , )
return self.image_processor_class
@property
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
warnings.warn(
'''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , __a , )
return self.image_processor
| 78 | 0 |
"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_a = logging.get_logger(__name__)
_a = {
"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( __lowerCAmelCase ):
lowercase__ = "speech_to_text_2"
lowercase__ = ["past_key_values"]
lowercase__ = {"num_attention_heads": "decoder_attention_heads", "hidden_size": "d_model"}
def __init__( self , __a=1_00_00 , __a=6 , __a=20_48 , __a=4 , __a=0.0 , __a=True , __a="relu" , __a=2_56 , __a=0.1 , __a=0.0 , __a=0.0 , __a=0.02 , __a=2 , __a=True , __a=1 , __a=0 , __a=2 , __a=10_24 , **__a , ) -> Dict:
'''simple docstring'''
_UpperCamelCase = vocab_size
_UpperCamelCase = d_model
_UpperCamelCase = decoder_ffn_dim
_UpperCamelCase = decoder_layers
_UpperCamelCase = decoder_attention_heads
_UpperCamelCase = dropout
_UpperCamelCase = attention_dropout
_UpperCamelCase = activation_dropout
_UpperCamelCase = activation_function
_UpperCamelCase = init_std
_UpperCamelCase = decoder_layerdrop
_UpperCamelCase = use_cache
_UpperCamelCase = decoder_layers
_UpperCamelCase = scale_embedding # scale factor will be sqrt(d_model) if True
_UpperCamelCase = max_target_positions
super().__init__(
pad_token_id=lowerCamelCase__ , bos_token_id=lowerCamelCase__ , eos_token_id=lowerCamelCase__ , decoder_start_token_id=lowerCamelCase__ , **lowerCamelCase__ , )
| 717 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tokenizers_available,
is_torch_available,
is_vision_available,
)
_a = {
"""configuration_perceiver""": ["""PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """PerceiverConfig""", """PerceiverOnnxConfig"""],
"""tokenization_perceiver""": ["""PerceiverTokenizer"""],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_a = ["""PerceiverFeatureExtractor"""]
_a = ["""PerceiverImageProcessor"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_a = [
"""PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""PerceiverForImageClassificationConvProcessing""",
"""PerceiverForImageClassificationFourier""",
"""PerceiverForImageClassificationLearned""",
"""PerceiverForMaskedLM""",
"""PerceiverForMultimodalAutoencoding""",
"""PerceiverForOpticalFlow""",
"""PerceiverForSequenceClassification""",
"""PerceiverLayer""",
"""PerceiverModel""",
"""PerceiverPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_perceiver import PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP, PerceiverConfig, PerceiverOnnxConfig
from .tokenization_perceiver import PerceiverTokenizer
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_perceiver import PerceiverFeatureExtractor
from .image_processing_perceiver import PerceiverImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_perceiver import (
PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST,
PerceiverForImageClassificationConvProcessing,
PerceiverForImageClassificationFourier,
PerceiverForImageClassificationLearned,
PerceiverForMaskedLM,
PerceiverForMultimodalAutoencoding,
PerceiverForOpticalFlow,
PerceiverForSequenceClassification,
PerceiverLayer,
PerceiverModel,
PerceiverPreTrainedModel,
)
else:
import sys
_a = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 78 | 0 |
"""simple docstring"""
from __future__ import annotations
from statistics import mean
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> Optional[Any]:
"""simple docstring"""
_UpperCamelCase = [0] * no_of_processes
_UpperCamelCase = [0] * no_of_processes
# Initialize remaining_time to waiting_time.
for i in range(snake_case_ ):
_UpperCamelCase = burst_time[i]
_UpperCamelCase = []
_UpperCamelCase = 0
_UpperCamelCase = 0
# When processes are not completed,
# A process whose arrival time has passed \
# and has remaining execution time is put into the ready_process.
# The shortest process in the ready_process, target_process is executed.
while completed != no_of_processes:
_UpperCamelCase = []
_UpperCamelCase = -1
for i in range(snake_case_ ):
if (arrival_time[i] <= total_time) and (remaining_time[i] > 0):
ready_process.append(snake_case_ )
if len(snake_case_ ) > 0:
_UpperCamelCase = ready_process[0]
for i in ready_process:
if remaining_time[i] < remaining_time[target_process]:
_UpperCamelCase = i
total_time += burst_time[target_process]
completed += 1
_UpperCamelCase = 0
_UpperCamelCase = (
total_time - arrival_time[target_process] - burst_time[target_process]
)
else:
total_time += 1
return waiting_time
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> str:
"""simple docstring"""
_UpperCamelCase = [0] * no_of_processes
for i in range(snake_case_ ):
_UpperCamelCase = burst_time[i] + waiting_time[i]
return turn_around_time
if __name__ == "__main__":
print("""[TEST CASE 01]""")
_a = 4
_a = [2, 5, 3, 7]
_a = [0, 0, 0, 0]
_a = calculate_waitingtime(arrival_time, burst_time, no_of_processes)
_a = calculate_turnaroundtime(
burst_time, no_of_processes, waiting_time
)
# Printing the Result
print("""PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time""")
for i, process_id in enumerate(list(range(1, 5))):
print(
F"""{process_id}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t"""
F"""{waiting_time[i]}\t\t\t\t{turn_around_time[i]}"""
)
print(F"""\nAverage waiting time = {mean(waiting_time):.5f}""")
print(F"""Average turnaround time = {mean(turn_around_time):.5f}""")
| 718 |
"""simple docstring"""
import inspect
import unittest
from huggingface_hub import hf_hub_download
from transformers import ASTConfig
from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_torchaudio_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import ASTForAudioClassification, ASTModel
from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import (
AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
)
if is_torchaudio_available():
import torchaudio
from transformers import ASTFeatureExtractor
class _UpperCAmelCase:
def __init__( self , __a , __a=13 , __a=2 , __a=24 , __a=16 , __a=True , __a=True , __a=32 , __a=5 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=10 , __a=0.02 , __a=None , __a=2 , __a=2 , ) -> List[str]:
'''simple docstring'''
_UpperCamelCase = parent
_UpperCamelCase = batch_size
_UpperCamelCase = patch_size
_UpperCamelCase = max_length
_UpperCamelCase = num_mel_bins
_UpperCamelCase = is_training
_UpperCamelCase = use_labels
_UpperCamelCase = hidden_size
_UpperCamelCase = num_hidden_layers
_UpperCamelCase = num_attention_heads
_UpperCamelCase = intermediate_size
_UpperCamelCase = hidden_act
_UpperCamelCase = hidden_dropout_prob
_UpperCamelCase = attention_probs_dropout_prob
_UpperCamelCase = type_sequence_label_size
_UpperCamelCase = initializer_range
_UpperCamelCase = scope
_UpperCamelCase = frequency_stride
_UpperCamelCase = time_stride
# in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
_UpperCamelCase = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1
_UpperCamelCase = (self.max_length - self.patch_size) // self.time_stride + 1
_UpperCamelCase = frequency_out_dimension * time_out_dimension
_UpperCamelCase = num_patches + 2
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins])
_UpperCamelCase = None
if self.use_labels:
_UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size)
_UpperCamelCase = self.get_config()
return config, input_values, labels
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
return ASTConfig(
patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__a , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , )
def UpperCAmelCase ( self , __a , __a , __a) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = ASTModel(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a)
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.prepare_config_and_inputs()
(
(
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) ,
) = config_and_inputs
_UpperCamelCase = {'''input_values''': input_values}
return config, inputs_dict
@require_torch
class _UpperCAmelCase( lowerCamelCase , lowerCamelCase , unittest.TestCase ):
lowercase__ = (
(
ASTModel,
ASTForAudioClassification,
)
if is_torch_available()
else ()
)
lowercase__ = (
{'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel}
if is_torch_available()
else {}
)
lowercase__ = False
lowercase__ = False
lowercase__ = False
lowercase__ = False
def UpperCAmelCase ( self , __a , __a , __a , __a , __a) -> Optional[Any]:
'''simple docstring'''
if pipeline_test_casse_name == "AudioClassificationPipelineTests":
return True
return False
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
_UpperCamelCase = ASTModelTester(self)
_UpperCamelCase = ConfigTester(self , config_class=__a , has_text_modality=__a , hidden_size=37)
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
self.config_tester.run_common_tests()
@unittest.skip(reason='''AST does not use inputs_embeds''')
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
pass
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_UpperCamelCase = model_class(__a)
self.assertIsInstance(model.get_input_embeddings() , (nn.Module))
_UpperCamelCase = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(__a , nn.Linear))
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_UpperCamelCase = model_class(__a)
_UpperCamelCase = inspect.signature(model.forward)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
_UpperCamelCase = [*signature.parameters.keys()]
_UpperCamelCase = ['''input_values''']
self.assertListEqual(arg_names[:1] , __a)
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__a)
@slow
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_UpperCamelCase = ASTModel.from_pretrained(__a)
self.assertIsNotNone(__a)
def lowerCamelCase__ ( ) -> List[str]:
"""simple docstring"""
_UpperCamelCase = hf_hub_download(
repo_id='''nielsr/audio-spectogram-transformer-checkpoint''', filename='''sample_audio.flac''', repo_type='''dataset''' )
_UpperCamelCase , _UpperCamelCase = torchaudio.load(__snake_case )
return audio, sampling_rate
@require_torch
@require_torchaudio
class _UpperCAmelCase( unittest.TestCase ):
@cached_property
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
return (
ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''')
if is_torchaudio_available()
else None
)
@slow
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.default_feature_extractor
_UpperCamelCase = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''').to(__a)
_UpperCamelCase = self.default_feature_extractor
_UpperCamelCase , _UpperCamelCase = prepare_audio()
_UpperCamelCase = audio.squeeze().numpy()
_UpperCamelCase = feature_extractor(__a , sampling_rate=__a , return_tensors='''pt''').to(__a)
# forward pass
with torch.no_grad():
_UpperCamelCase = model(**__a)
# verify the logits
_UpperCamelCase = torch.Size((1, 5_27))
self.assertEqual(outputs.logits.shape , __a)
_UpperCamelCase = torch.tensor([-0.8760, -7.0042, -8.6602]).to(__a)
self.assertTrue(torch.allclose(outputs.logits[0, :3] , __a , atol=1e-4))
| 78 | 0 |
"""simple docstring"""
def lowerCamelCase__ ( __snake_case ) -> Optional[int]:
"""simple docstring"""
if not isinstance(UpperCamelCase__, UpperCamelCase__ ):
raise ValueError('''check_bouncy() accepts only integer arguments''' )
_UpperCamelCase = str(UpperCamelCase__ )
_UpperCamelCase = ''''''.join(sorted(UpperCamelCase__ ) )
return sorted_str_n != str_n and sorted_str_n[::-1] != str_n
def lowerCamelCase__ ( __snake_case = 99 ) -> Any:
"""simple docstring"""
if not 0 < percent < 1_00:
raise ValueError('''solution() only accepts values from 0 to 100''' )
_UpperCamelCase = 0
_UpperCamelCase = 1
while True:
if check_bouncy(UpperCamelCase__ ):
bouncy_num += 1
if (bouncy_num / num) * 1_00 >= percent:
return num
num += 1
if __name__ == "__main__":
from doctest import testmod
testmod()
print(F"""{solution(99)}""")
| 719 |
"""simple docstring"""
def lowerCamelCase__ ( ) -> list[list[int]]:
"""simple docstring"""
return [list(range(10_00 - i, -10_00 - i, -1 ) ) for i in range(10_00 )]
_a = generate_large_matrix()
_a = (
[[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]],
[[3, 2], [1, 0]],
[[7, 7, 6]],
[[7, 7, 6], [-1, -2, -3]],
grid,
)
def lowerCamelCase__ ( __snake_case ) -> None:
"""simple docstring"""
assert all(row == sorted(__snake_case, reverse=__snake_case ) for row in grid )
assert all(list(__snake_case ) == sorted(__snake_case, reverse=__snake_case ) for col in zip(*__snake_case ) )
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = 0
_UpperCamelCase = len(__snake_case ) - 1
# Edge cases such as no values or all numbers are negative.
if not array or array[0] < 0:
return 0
while right + 1 > left:
_UpperCamelCase = (left + right) // 2
_UpperCamelCase = array[mid]
# Num must be negative and the index must be greater than or equal to 0.
if num < 0 and array[mid - 1] >= 0:
return mid
if num >= 0:
_UpperCamelCase = mid + 1
else:
_UpperCamelCase = mid - 1
# No negative numbers so return the last index of the array + 1 which is the length.
return len(__snake_case )
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = 0
_UpperCamelCase = len(grid[0] )
for i in range(len(__snake_case ) ):
_UpperCamelCase = find_negative_index(grid[i][:bound] )
total += bound
return (len(__snake_case ) * len(grid[0] )) - total
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
return len([number for row in grid for number in row if number < 0] )
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = 0
for row in grid:
for i, number in enumerate(__snake_case ):
if number < 0:
total += len(__snake_case ) - i
break
return total
def lowerCamelCase__ ( ) -> None:
"""simple docstring"""
from timeit import timeit
print('''Running benchmarks''' )
_UpperCamelCase = (
'''from __main__ import count_negatives_binary_search, '''
'''count_negatives_brute_force, count_negatives_brute_force_with_break, grid'''
)
for func in (
"count_negatives_binary_search", # took 0.7727 seconds
"count_negatives_brute_force_with_break", # took 4.6505 seconds
"count_negatives_brute_force", # took 12.8160 seconds
):
_UpperCamelCase = timeit(F'''{func}(grid=grid)''', setup=__snake_case, number=5_00 )
print(F'''{func}() took {time:0.4f} seconds''' )
if __name__ == "__main__":
import doctest
doctest.testmod()
benchmark()
| 78 | 0 |
"""simple docstring"""
import argparse
import json
import os
import re
from collections import OrderedDict
from os.path import basename, dirname
import fairseq
import torch
from fairseq import hub_utils
from fairseq.data.dictionary import Dictionary
from transformers import FSMTConfig, FSMTForConditionalGeneration
from transformers.models.fsmt.tokenization_fsmt import VOCAB_FILES_NAMES
from transformers.tokenization_utils_base import TOKENIZER_CONFIG_FILE
from transformers.utils import WEIGHTS_NAME, logging
logging.set_verbosity_warning()
_a = 2
# based on the results of a search on a range of `num_beams`, `length_penalty` and `early_stopping`
# values against wmt19 test data to obtain the best BLEU scores, we will use the following defaults:
#
# * `num_beams`: 5 (higher scores better, but requires more memory/is slower, can be adjusted by users)
# * `early_stopping`: `False` consistently scored better
# * `length_penalty` varied, so will assign the best one depending on the model
_a = {
# fairseq:
"""wmt19-ru-en""": {"""length_penalty""": 1.1},
"""wmt19-en-ru""": {"""length_penalty""": 1.15},
"""wmt19-en-de""": {"""length_penalty""": 1.0},
"""wmt19-de-en""": {"""length_penalty""": 1.1},
# allenai:
"""wmt16-en-de-dist-12-1""": {"""length_penalty""": 0.6},
"""wmt16-en-de-dist-6-1""": {"""length_penalty""": 0.6},
"""wmt16-en-de-12-1""": {"""length_penalty""": 0.8},
"""wmt19-de-en-6-6-base""": {"""length_penalty""": 0.6},
"""wmt19-de-en-6-6-big""": {"""length_penalty""": 0.6},
}
# this remaps the different models to their organization names
_a = {}
for m in ["wmt19-ru-en", "wmt19-en-ru", "wmt19-en-de", "wmt19-de-en"]:
_a = """facebook"""
for m in [
"wmt16-en-de-dist-12-1",
"wmt16-en-de-dist-6-1",
"wmt16-en-de-12-1",
"wmt19-de-en-6-6-base",
"wmt19-de-en-6-6-big",
]:
_a = """allenai"""
def lowerCamelCase__ ( __snake_case ) -> Dict:
# (1) remove word breaking symbol, (2) add word ending symbol where the word is not broken up,
# e.g.: d = {'le@@': 5, 'tt@@': 6, 'er': 7} => {'le': 5, 'tt': 6, 'er</w>': 7}
_UpperCamelCase = dict((re.sub(r'''@@$''', '''''', lowerCamelCase__ ), v) if k.endswith('''@@''' ) else (re.sub(r'''$''', '''</w>''', lowerCamelCase__ ), v) for k, v in d.items() )
_UpperCamelCase = '''<s> <pad> </s> <unk>'''.split()
# restore the special tokens
for k in keep_keys:
del da[F'''{k}</w>''']
_UpperCamelCase = d[k] # restore
return da
def lowerCamelCase__ ( __snake_case, __snake_case ) -> Optional[int]:
# prep
assert os.path.exists(lowerCamelCase__ )
os.makedirs(lowerCamelCase__, exist_ok=lowerCamelCase__ )
print(F'''Writing results to {pytorch_dump_folder_path}''' )
# handle various types of models
_UpperCamelCase = basename(lowerCamelCase__ )
_UpperCamelCase = dirname(lowerCamelCase__ )
_UpperCamelCase = fairseq.model_parallel.models.transformer.ModelParallelTransformerModel
_UpperCamelCase = cls.hub_models()
_UpperCamelCase = {'''bpe''': '''fastbpe''', '''tokenizer''': '''moses'''}
_UpperCamelCase = '''.'''
# note: since the model dump is old, fairseq has upgraded its model some
# time later, and it does a whole lot of rewrites and splits on the saved
# weights, therefore we can't use torch.load() directly on the model file.
# see: upgrade_state_dict(state_dict) in fairseq_model.py
print(F'''using checkpoint {checkpoint_file}''' )
_UpperCamelCase = hub_utils.from_pretrained(
lowerCamelCase__, lowerCamelCase__, lowerCamelCase__, archive_map=lowerCamelCase__, **lowerCamelCase__ )
_UpperCamelCase = vars(chkpt['''args''']['''model'''] )
_UpperCamelCase = args['''source_lang''']
_UpperCamelCase = args['''target_lang''']
_UpperCamelCase = dirname(lowerCamelCase__ )
_UpperCamelCase = basename(lowerCamelCase__ )
# dicts
_UpperCamelCase = os.path.join(lowerCamelCase__, F'''dict.{src_lang}.txt''' )
_UpperCamelCase = os.path.join(lowerCamelCase__, F'''dict.{tgt_lang}.txt''' )
_UpperCamelCase = Dictionary.load(lowerCamelCase__ )
_UpperCamelCase = rewrite_dict_keys(src_dict.indices )
_UpperCamelCase = len(lowerCamelCase__ )
_UpperCamelCase = os.path.join(lowerCamelCase__, '''vocab-src.json''' )
print(F'''Generating {src_vocab_file} of {src_vocab_size} of {src_lang} records''' )
with open(lowerCamelCase__, '''w''', encoding='''utf-8''' ) as f:
f.write(json.dumps(lowerCamelCase__, ensure_ascii=lowerCamelCase__, indent=lowerCamelCase__ ) )
# detect whether this is a do_lower_case situation, which can be derived by checking whether we
# have at least one uppercase letter in the source vocab
_UpperCamelCase = True
for k in src_vocab.keys():
if not k.islower():
_UpperCamelCase = False
break
_UpperCamelCase = Dictionary.load(lowerCamelCase__ )
_UpperCamelCase = rewrite_dict_keys(tgt_dict.indices )
_UpperCamelCase = len(lowerCamelCase__ )
_UpperCamelCase = os.path.join(lowerCamelCase__, '''vocab-tgt.json''' )
print(F'''Generating {tgt_vocab_file} of {tgt_vocab_size} of {tgt_lang} records''' )
with open(lowerCamelCase__, '''w''', encoding='''utf-8''' ) as f:
f.write(json.dumps(lowerCamelCase__, ensure_ascii=lowerCamelCase__, indent=lowerCamelCase__ ) )
# merges_file (bpecodes)
_UpperCamelCase = os.path.join(lowerCamelCase__, VOCAB_FILES_NAMES['''merges_file'''] )
for fn in ["bpecodes", "code"]: # older fairseq called the merges file "code"
_UpperCamelCase = os.path.join(lowerCamelCase__, lowerCamelCase__ )
if os.path.exists(lowerCamelCase__ ):
break
with open(lowerCamelCase__, encoding='''utf-8''' ) as fin:
_UpperCamelCase = fin.read()
_UpperCamelCase = re.sub(r''' \d+$''', '''''', lowerCamelCase__, 0, re.M ) # remove frequency number
print(F'''Generating {merges_file}''' )
with open(lowerCamelCase__, '''w''', encoding='''utf-8''' ) as fout:
fout.write(lowerCamelCase__ )
# model config
_UpperCamelCase = os.path.join(lowerCamelCase__, '''config.json''' )
# validate bpe/tokenizer config, as currently it's hardcoded to moses+fastbpe -
# may have to modify the tokenizer if a different type is used by a future model
assert args["bpe"] == "fastbpe", F'''need to extend tokenizer to support bpe={args["bpe"]}'''
assert args["tokenizer"] == "moses", F'''need to extend tokenizer to support bpe={args["tokenizer"]}'''
_UpperCamelCase = {
'''architectures''': ['''FSMTForConditionalGeneration'''],
'''model_type''': '''fsmt''',
'''activation_dropout''': args['''activation_dropout'''],
'''activation_function''': '''relu''',
'''attention_dropout''': args['''attention_dropout'''],
'''d_model''': args['''decoder_embed_dim'''],
'''dropout''': args['''dropout'''],
'''init_std''': 0.02,
'''max_position_embeddings''': args['''max_source_positions'''],
'''num_hidden_layers''': args['''encoder_layers'''],
'''src_vocab_size''': src_vocab_size,
'''tgt_vocab_size''': tgt_vocab_size,
'''langs''': [src_lang, tgt_lang],
'''encoder_attention_heads''': args['''encoder_attention_heads'''],
'''encoder_ffn_dim''': args['''encoder_ffn_embed_dim'''],
'''encoder_layerdrop''': args['''encoder_layerdrop'''],
'''encoder_layers''': args['''encoder_layers'''],
'''decoder_attention_heads''': args['''decoder_attention_heads'''],
'''decoder_ffn_dim''': args['''decoder_ffn_embed_dim'''],
'''decoder_layerdrop''': args['''decoder_layerdrop'''],
'''decoder_layers''': args['''decoder_layers'''],
'''bos_token_id''': 0,
'''pad_token_id''': 1,
'''eos_token_id''': 2,
'''is_encoder_decoder''': True,
'''scale_embedding''': not args['''no_scale_embedding'''],
'''tie_word_embeddings''': args['''share_all_embeddings'''],
}
# good hparam defaults to start with
_UpperCamelCase = 5
_UpperCamelCase = False
if model_dir in best_score_hparams and "length_penalty" in best_score_hparams[model_dir]:
_UpperCamelCase = best_score_hparams[model_dir]['''length_penalty''']
else:
_UpperCamelCase = 1.0
print(F'''Generating {fsmt_model_config_file}''' )
with open(lowerCamelCase__, '''w''', encoding='''utf-8''' ) as f:
f.write(json.dumps(lowerCamelCase__, ensure_ascii=lowerCamelCase__, indent=lowerCamelCase__ ) )
# tokenizer config
_UpperCamelCase = os.path.join(lowerCamelCase__, lowerCamelCase__ )
_UpperCamelCase = {
'''langs''': [src_lang, tgt_lang],
'''model_max_length''': 10_24,
'''do_lower_case''': do_lower_case,
}
print(F'''Generating {fsmt_tokenizer_config_file}''' )
with open(lowerCamelCase__, '''w''', encoding='''utf-8''' ) as f:
f.write(json.dumps(lowerCamelCase__, ensure_ascii=lowerCamelCase__, indent=lowerCamelCase__ ) )
# model
_UpperCamelCase = chkpt['''models'''][0]
_UpperCamelCase = model.state_dict()
# rename keys to start with 'model.'
_UpperCamelCase = OrderedDict(('''model.''' + k, v) for k, v in model_state_dict.items() )
# remove unneeded keys
_UpperCamelCase = [
'''model.model''',
'''model.encoder.version''',
'''model.decoder.version''',
'''model.encoder_embed_tokens.weight''',
'''model.decoder_embed_tokens.weight''',
'''model.encoder.embed_positions._float_tensor''',
'''model.decoder.embed_positions._float_tensor''',
]
for k in ignore_keys:
model_state_dict.pop(lowerCamelCase__, lowerCamelCase__ )
_UpperCamelCase = FSMTConfig.from_pretrained(lowerCamelCase__ )
_UpperCamelCase = FSMTForConditionalGeneration(lowerCamelCase__ )
# check that it loads ok
model_new.load_state_dict(lowerCamelCase__, strict=lowerCamelCase__ )
# save
_UpperCamelCase = os.path.join(lowerCamelCase__, lowerCamelCase__ )
print(F'''Generating {pytorch_weights_dump_path}''' )
torch.save(lowerCamelCase__, lowerCamelCase__ )
print('''Conversion is done!''' )
print('''\nLast step is to upload the files to s3''' )
print(F'''cd {data_root}''' )
print(F'''transformers-cli upload {model_dir}''' )
if __name__ == "__main__":
_a = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--fsmt_checkpoint_path""",
default=None,
type=str,
required=True,
help=(
"""Path to the official PyTorch checkpoint file which is expected to reside in the dump dir with dicts,"""
""" bpecodes, etc."""
),
)
parser.add_argument(
"""--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
)
_a = parser.parse_args()
convert_fsmt_checkpoint_to_pytorch(args.fsmt_checkpoint_path, args.pytorch_dump_folder_path)
| 720 |
"""simple docstring"""
import copy
import re
class _UpperCAmelCase:
lowercase__ = 'hp'
lowercase__ = {}
lowercase__ = None
@classmethod
def UpperCAmelCase ( cls , __a , __a) -> Dict:
'''simple docstring'''
_UpperCamelCase = prefix
_UpperCamelCase = defaults
cls.build_naming_info()
@staticmethod
def UpperCAmelCase ( __a , __a) -> Union[str, Any]:
'''simple docstring'''
if len(__a) == 0:
return ""
_UpperCamelCase = None
if any(char.isdigit() for char in word):
raise Exception(F'''Parameters should not contain numbers: \'{word}\' contains a number''')
if word in info["short_word"]:
return info["short_word"][word]
for prefix_len in range(1 , len(__a) + 1):
_UpperCamelCase = word[:prefix_len]
if prefix in info["reverse_short_word"]:
continue
else:
_UpperCamelCase = prefix
break
if short_word is None:
# Paranoid fallback
def int_to_alphabetic(__a):
_UpperCamelCase = ''''''
while integer != 0:
_UpperCamelCase = chr(ord('''A''') + integer % 10) + s
integer //= 10
return s
_UpperCamelCase = 0
while True:
_UpperCamelCase = word + '''#''' + int_to_alphabetic(__a)
if sword in info["reverse_short_word"]:
continue
else:
_UpperCamelCase = sword
break
_UpperCamelCase = short_word
_UpperCamelCase = word
return short_word
@staticmethod
def UpperCAmelCase ( __a , __a) -> Any:
'''simple docstring'''
_UpperCamelCase = param_name.split('''_''')
_UpperCamelCase = [TrialShortNamer.shortname_for_word(__a , __a) for word in words]
# We try to create a separatorless short name, but if there is a collision we have to fallback
# to a separated short name
_UpperCamelCase = ['''''', '''_''']
for separator in separators:
_UpperCamelCase = separator.join(__a)
if shortname not in info["reverse_short_param"]:
_UpperCamelCase = shortname
_UpperCamelCase = param_name
return shortname
return param_name
@staticmethod
def UpperCAmelCase ( __a , __a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = TrialShortNamer.shortname_for_key(__a , __a)
_UpperCamelCase = short_name
_UpperCamelCase = param_name
@classmethod
def UpperCAmelCase ( cls) -> Any:
'''simple docstring'''
if cls.NAMING_INFO is not None:
return
_UpperCamelCase = {
'''short_word''': {},
'''reverse_short_word''': {},
'''short_param''': {},
'''reverse_short_param''': {},
}
_UpperCamelCase = list(cls.DEFAULTS.keys())
for k in field_keys:
cls.add_new_param_name(__a , __a)
_UpperCamelCase = info
@classmethod
def UpperCAmelCase ( cls , __a) -> Optional[Any]:
'''simple docstring'''
cls.build_naming_info()
assert cls.PREFIX is not None
_UpperCamelCase = [copy.copy(cls.PREFIX)]
for k, v in params.items():
if k not in cls.DEFAULTS:
raise Exception(F'''You should provide a default value for the param name {k} with value {v}''')
if v == cls.DEFAULTS[k]:
# The default value is not added to the name
continue
_UpperCamelCase = cls.NAMING_INFO['''short_param'''][k]
if isinstance(__a , __a):
_UpperCamelCase = 1 if v else 0
_UpperCamelCase = '''''' if isinstance(__a , (int, float)) else '''-'''
_UpperCamelCase = F'''{key}{sep}{v}'''
name.append(__a)
return "_".join(__a)
@classmethod
def UpperCAmelCase ( cls , __a) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = repr[len(cls.PREFIX) + 1 :]
if repr == "":
_UpperCamelCase = []
else:
_UpperCamelCase = repr.split('''_''')
_UpperCamelCase = {}
for value in values:
if "-" in value:
_UpperCamelCase , _UpperCamelCase = value.split('''-''')
else:
_UpperCamelCase = re.sub('''[0-9.]''' , '''''' , __a)
_UpperCamelCase = float(re.sub('''[^0-9.]''' , '''''' , __a))
_UpperCamelCase = cls.NAMING_INFO['''reverse_short_param'''][p_k]
_UpperCamelCase = p_v
for k in cls.DEFAULTS:
if k not in parameters:
_UpperCamelCase = cls.DEFAULTS[k]
return parameters
| 78 | 0 |
"""simple docstring"""
import argparse
_a = """docs/source/_static/js/custom.js"""
def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]:
"""simple docstring"""
with open(__snake_case, encoding='''utf-8''', newline='''\n''' ) as f:
_UpperCamelCase = f.readlines()
_UpperCamelCase = 0
# First let's put the right version
while not lines[index].startswith('''const stableVersion =''' ):
index += 1
_UpperCamelCase = F'''const stableVersion = "v{version}"\n'''
# Then update the dictionary
while not lines[index].startswith('''const versionMapping = {''' ):
index += 1
# We go until the end
while not lines[index].startswith('''}''' ):
index += 1
# We add the new version at the end
lines[index - 1] += F''' "v{version}": "v{version}",\n'''
with open(__snake_case, '''w''', encoding='''utf-8''', newline='''\n''' ) as f:
f.writelines(__snake_case )
if __name__ == "__main__":
_a = argparse.ArgumentParser()
parser.add_argument("""--version""", help="""Release version.""")
_a = parser.parse_args()
update_custom_js(args.version)
| 721 |
"""simple docstring"""
import os
import time
import pytest
from datasets.utils.filelock import FileLock, Timeout
def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]:
"""simple docstring"""
_UpperCamelCase = FileLock(str(tmpdir / '''foo.lock''' ) )
_UpperCamelCase = FileLock(str(tmpdir / '''foo.lock''' ) )
_UpperCamelCase = 0.01
with locka.acquire():
with pytest.raises(__snake_case ):
_UpperCamelCase = time.time()
locka.acquire(__snake_case )
assert time.time() - _start > timeout
def lowerCamelCase__ ( __snake_case ) -> List[Any]:
"""simple docstring"""
_UpperCamelCase = '''a''' * 10_00 + '''.lock'''
_UpperCamelCase = FileLock(str(tmpdir / filename ) )
assert locka._lock_file.endswith('''.lock''' )
assert not locka._lock_file.endswith(__snake_case )
assert len(os.path.basename(locka._lock_file ) ) <= 2_55
_UpperCamelCase = FileLock(tmpdir / filename )
with locka.acquire():
with pytest.raises(__snake_case ):
locka.acquire(0 )
| 78 | 0 |
"""simple docstring"""
from math import acos, sin
from typing import List, Tuple, Union
import numpy as np
import torch
from PIL import Image
from ...models import AutoencoderKL, UNetaDConditionModel
from ...schedulers import DDIMScheduler, DDPMScheduler
from ...utils import randn_tensor
from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput
from .mel import Mel
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = ['vqvae']
def __init__( self , __a , __a , __a , __a , ) -> Dict:
'''simple docstring'''
super().__init__()
self.register_modules(unet=__a , scheduler=__a , mel=__a , vqvae=__a)
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
return 50 if isinstance(self.scheduler , __a) else 10_00
@torch.no_grad()
def __call__( self , __a = 1 , __a = None , __a = None , __a = 0 , __a = 0 , __a = None , __a = None , __a = 0 , __a = 0 , __a = None , __a = 0 , __a = None , __a = None , __a=True , ) -> Union[
Union[AudioPipelineOutput, ImagePipelineOutput],
Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]],
]:
'''simple docstring'''
_UpperCamelCase = steps or self.get_default_steps()
self.scheduler.set_timesteps(__a)
_UpperCamelCase = step_generator or generator
# For backwards compatibility
if type(self.unet.config.sample_size) == int:
_UpperCamelCase = (self.unet.config.sample_size, self.unet.config.sample_size)
if noise is None:
_UpperCamelCase = randn_tensor(
(
batch_size,
self.unet.config.in_channels,
self.unet.config.sample_size[0],
self.unet.config.sample_size[1],
) , generator=__a , device=self.device , )
_UpperCamelCase = noise
_UpperCamelCase = None
if audio_file is not None or raw_audio is not None:
self.mel.load_audio(__a , __a)
_UpperCamelCase = self.mel.audio_slice_to_image(__a)
_UpperCamelCase = np.frombuffer(input_image.tobytes() , dtype='''uint8''').reshape(
(input_image.height, input_image.width))
_UpperCamelCase = (input_image / 2_55) * 2 - 1
_UpperCamelCase = torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float).to(self.device)
if self.vqvae is not None:
_UpperCamelCase = self.vqvae.encode(torch.unsqueeze(__a , 0)).latent_dist.sample(
generator=__a)[0]
_UpperCamelCase = self.vqvae.config.scaling_factor * input_images
if start_step > 0:
_UpperCamelCase = self.scheduler.add_noise(__a , __a , self.scheduler.timesteps[start_step - 1])
_UpperCamelCase = (
self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length
)
_UpperCamelCase = int(mask_start_secs * pixels_per_second)
_UpperCamelCase = int(mask_end_secs * pixels_per_second)
_UpperCamelCase = self.scheduler.add_noise(__a , __a , torch.tensor(self.scheduler.timesteps[start_step:]))
for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:])):
if isinstance(self.unet , __a):
_UpperCamelCase = self.unet(__a , __a , __a)['''sample''']
else:
_UpperCamelCase = self.unet(__a , __a)['''sample''']
if isinstance(self.scheduler , __a):
_UpperCamelCase = self.scheduler.step(
model_output=__a , timestep=__a , sample=__a , eta=__a , generator=__a , )['''prev_sample''']
else:
_UpperCamelCase = self.scheduler.step(
model_output=__a , timestep=__a , sample=__a , generator=__a , )['''prev_sample''']
if mask is not None:
if mask_start > 0:
_UpperCamelCase = mask[:, step, :, :mask_start]
if mask_end > 0:
_UpperCamelCase = mask[:, step, :, -mask_end:]
if self.vqvae is not None:
# 0.18215 was scaling factor used in training to ensure unit variance
_UpperCamelCase = 1 / self.vqvae.config.scaling_factor * images
_UpperCamelCase = self.vqvae.decode(__a)['''sample''']
_UpperCamelCase = (images / 2 + 0.5).clamp(0 , 1)
_UpperCamelCase = images.cpu().permute(0 , 2 , 3 , 1).numpy()
_UpperCamelCase = (images * 2_55).round().astype('''uint8''')
_UpperCamelCase = list(
(Image.fromarray(_[:, :, 0]) for _ in images)
if images.shape[3] == 1
else (Image.fromarray(__a , mode='''RGB''').convert('''L''') for _ in images))
_UpperCamelCase = [self.mel.image_to_audio(__a) for _ in images]
if not return_dict:
return images, (self.mel.get_sample_rate(), audios)
return BaseOutput(**AudioPipelineOutput(np.array(__a)[:, np.newaxis, :]) , **ImagePipelineOutput(__a))
@torch.no_grad()
def UpperCAmelCase ( self , __a , __a = 50) -> np.ndarray:
'''simple docstring'''
assert isinstance(self.scheduler , __a)
self.scheduler.set_timesteps(__a)
_UpperCamelCase = np.array(
[np.frombuffer(image.tobytes() , dtype='''uint8''').reshape((1, image.height, image.width)) for image in images])
_UpperCamelCase = (sample / 2_55) * 2 - 1
_UpperCamelCase = torch.Tensor(__a).to(self.device)
for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,))):
_UpperCamelCase = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps
_UpperCamelCase = self.scheduler.alphas_cumprod[t]
_UpperCamelCase = (
self.scheduler.alphas_cumprod[prev_timestep]
if prev_timestep >= 0
else self.scheduler.final_alpha_cumprod
)
_UpperCamelCase = 1 - alpha_prod_t
_UpperCamelCase = self.unet(__a , __a)['''sample''']
_UpperCamelCase = (1 - alpha_prod_t_prev) ** 0.5 * model_output
_UpperCamelCase = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5)
_UpperCamelCase = sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output
return sample
@staticmethod
def UpperCAmelCase ( __a , __a , __a) -> torch.Tensor:
'''simple docstring'''
_UpperCamelCase = acos(torch.dot(torch.flatten(__a) , torch.flatten(__a)) / torch.norm(__a) / torch.norm(__a))
return sin((1 - alpha) * theta) * xa / sin(__a) + sin(alpha * theta) * xa / sin(__a)
| 700 |
"""simple docstring"""
from math import sqrt
def lowerCamelCase__ ( __snake_case ) -> bool:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (
number >= 0
), "'number' must been an int and positive"
_UpperCamelCase = True
# 0 and 1 are none primes.
if number <= 1:
_UpperCamelCase = False
for divisor in range(2, int(round(sqrt(__snake_case ) ) ) + 1 ):
# if 'number' divisible by 'divisor' then sets 'status'
# of false and break up the loop.
if number % divisor == 0:
_UpperCamelCase = False
break
# precondition
assert isinstance(__snake_case, __snake_case ), "'status' must been from type bool"
return status
def lowerCamelCase__ ( __snake_case ) -> Dict:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n > 2), "'N' must been an int and > 2"
# beginList: contains all natural numbers from 2 up to N
_UpperCamelCase = list(range(2, n + 1 ) )
_UpperCamelCase = [] # this list will be returns.
# actual sieve of erathostenes
for i in range(len(__snake_case ) ):
for j in range(i + 1, len(__snake_case ) ):
if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0):
_UpperCamelCase = 0
# filters actual prime numbers.
_UpperCamelCase = [x for x in begin_list if x != 0]
# precondition
assert isinstance(__snake_case, __snake_case ), "'ans' must been from type list"
return ans
def lowerCamelCase__ ( __snake_case ) -> List[str]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n > 2), "'N' must been an int and > 2"
_UpperCamelCase = []
# iterates over all numbers between 2 up to N+1
# if a number is prime then appends to list 'ans'
for number in range(2, n + 1 ):
if is_prime(__snake_case ):
ans.append(__snake_case )
# precondition
assert isinstance(__snake_case, __snake_case ), "'ans' must been from type list"
return ans
def lowerCamelCase__ ( __snake_case ) -> Optional[int]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and number >= 0, "'number' must been an int and >= 0"
_UpperCamelCase = [] # this list will be returns of the function.
# potential prime number factors.
_UpperCamelCase = 2
_UpperCamelCase = number
if number == 0 or number == 1:
ans.append(__snake_case )
# if 'number' not prime then builds the prime factorization of 'number'
elif not is_prime(__snake_case ):
while quotient != 1:
if is_prime(__snake_case ) and (quotient % factor == 0):
ans.append(__snake_case )
quotient /= factor
else:
factor += 1
else:
ans.append(__snake_case )
# precondition
assert isinstance(__snake_case, __snake_case ), "'ans' must been from type list"
return ans
def lowerCamelCase__ ( __snake_case ) -> Optional[Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (
number >= 0
), "'number' bust been an int and >= 0"
_UpperCamelCase = 0
# prime factorization of 'number'
_UpperCamelCase = prime_factorization(__snake_case )
_UpperCamelCase = max(__snake_case )
# precondition
assert isinstance(__snake_case, __snake_case ), "'ans' must been from type int"
return ans
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (
number >= 0
), "'number' bust been an int and >= 0"
_UpperCamelCase = 0
# prime factorization of 'number'
_UpperCamelCase = prime_factorization(__snake_case )
_UpperCamelCase = min(__snake_case )
# precondition
assert isinstance(__snake_case, __snake_case ), "'ans' must been from type int"
return ans
def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ), "'number' must been an int"
assert isinstance(number % 2 == 0, __snake_case ), "compare bust been from type bool"
return number % 2 == 0
def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ), "'number' must been an int"
assert isinstance(number % 2 != 0, __snake_case ), "compare bust been from type bool"
return number % 2 != 0
def lowerCamelCase__ ( __snake_case ) -> str:
"""simple docstring"""
assert (
isinstance(__snake_case, __snake_case ) and (number > 2) and is_even(__snake_case )
), "'number' must been an int, even and > 2"
_UpperCamelCase = [] # this list will returned
# creates a list of prime numbers between 2 up to 'number'
_UpperCamelCase = get_prime_numbers(__snake_case )
_UpperCamelCase = len(__snake_case )
# run variable for while-loops.
_UpperCamelCase = 0
_UpperCamelCase = None
# exit variable. for break up the loops
_UpperCamelCase = True
while i < len_pn and loop:
_UpperCamelCase = i + 1
while j < len_pn and loop:
if prime_numbers[i] + prime_numbers[j] == number:
_UpperCamelCase = False
ans.append(prime_numbers[i] )
ans.append(prime_numbers[j] )
j += 1
i += 1
# precondition
assert (
isinstance(__snake_case, __snake_case )
and (len(__snake_case ) == 2)
and (ans[0] + ans[1] == number)
and is_prime(ans[0] )
and is_prime(ans[1] )
), "'ans' must contains two primes. And sum of elements must been eq 'number'"
return ans
def lowerCamelCase__ ( __snake_case, __snake_case ) -> str:
"""simple docstring"""
assert (
isinstance(__snake_case, __snake_case )
and isinstance(__snake_case, __snake_case )
and (numbera >= 0)
and (numbera >= 0)
), "'number1' and 'number2' must been positive integer."
_UpperCamelCase = 0
while numbera != 0:
_UpperCamelCase = numbera % numbera
_UpperCamelCase = numbera
_UpperCamelCase = rest
# precondition
assert isinstance(__snake_case, __snake_case ) and (
numbera >= 0
), "'number' must been from type int and positive"
return numbera
def lowerCamelCase__ ( __snake_case, __snake_case ) -> List[str]:
"""simple docstring"""
assert (
isinstance(__snake_case, __snake_case )
and isinstance(__snake_case, __snake_case )
and (numbera >= 1)
and (numbera >= 1)
), "'number1' and 'number2' must been positive integer."
_UpperCamelCase = 1 # actual answer that will be return.
# for kgV (x,1)
if numbera > 1 and numbera > 1:
# builds the prime factorization of 'number1' and 'number2'
_UpperCamelCase = prime_factorization(__snake_case )
_UpperCamelCase = prime_factorization(__snake_case )
elif numbera == 1 or numbera == 1:
_UpperCamelCase = []
_UpperCamelCase = []
_UpperCamelCase = max(__snake_case, __snake_case )
_UpperCamelCase = 0
_UpperCamelCase = 0
_UpperCamelCase = [] # captured numbers int both 'primeFac1' and 'primeFac2'
# iterates through primeFac1
for n in prime_fac_a:
if n not in done:
if n in prime_fac_a:
_UpperCamelCase = prime_fac_a.count(__snake_case )
_UpperCamelCase = prime_fac_a.count(__snake_case )
for _ in range(max(__snake_case, __snake_case ) ):
ans *= n
else:
_UpperCamelCase = prime_fac_a.count(__snake_case )
for _ in range(__snake_case ):
ans *= n
done.append(__snake_case )
# iterates through primeFac2
for n in prime_fac_a:
if n not in done:
_UpperCamelCase = prime_fac_a.count(__snake_case )
for _ in range(__snake_case ):
ans *= n
done.append(__snake_case )
# precondition
assert isinstance(__snake_case, __snake_case ) and (
ans >= 0
), "'ans' must been from type int and positive"
return ans
def lowerCamelCase__ ( __snake_case ) -> Tuple:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n >= 0), "'number' must been a positive int"
_UpperCamelCase = 0
_UpperCamelCase = 2 # this variable holds the answer
while index < n:
index += 1
ans += 1 # counts to the next number
# if ans not prime then
# runs to the next prime number.
while not is_prime(__snake_case ):
ans += 1
# precondition
assert isinstance(__snake_case, __snake_case ) and is_prime(
__snake_case ), "'ans' must been a prime number and from type int"
return ans
def lowerCamelCase__ ( __snake_case, __snake_case ) -> Tuple:
"""simple docstring"""
assert (
is_prime(__snake_case ) and is_prime(__snake_case ) and (p_number_a < p_number_a)
), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'"
_UpperCamelCase = p_number_a + 1 # jump to the next number
_UpperCamelCase = [] # this list will be returns.
# if number is not prime then
# fetch the next prime number.
while not is_prime(__snake_case ):
number += 1
while number < p_number_a:
ans.append(__snake_case )
number += 1
# fetch the next prime number.
while not is_prime(__snake_case ):
number += 1
# precondition
assert (
isinstance(__snake_case, __snake_case )
and ans[0] != p_number_a
and ans[len(__snake_case ) - 1] != p_number_a
), "'ans' must been a list without the arguments"
# 'ans' contains not 'pNumber1' and 'pNumber2' !
return ans
def lowerCamelCase__ ( __snake_case ) -> List[Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n >= 1), "'n' must been int and >= 1"
_UpperCamelCase = [] # will be returned.
for divisor in range(1, n + 1 ):
if n % divisor == 0:
ans.append(__snake_case )
# precondition
assert ans[0] == 1 and ans[len(__snake_case ) - 1] == n, "Error in function getDivisiors(...)"
return ans
def lowerCamelCase__ ( __snake_case ) -> str:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (
number > 1
), "'number' must been an int and >= 1"
_UpperCamelCase = get_divisors(__snake_case )
# precondition
assert (
isinstance(__snake_case, __snake_case )
and (divisors[0] == 1)
and (divisors[len(__snake_case ) - 1] == number)
), "Error in help-function getDivisiors(...)"
# summed all divisors up to 'number' (exclusive), hence [:-1]
return sum(divisors[:-1] ) == number
def lowerCamelCase__ ( __snake_case, __snake_case ) -> Optional[Any]:
"""simple docstring"""
assert (
isinstance(__snake_case, __snake_case )
and isinstance(__snake_case, __snake_case )
and (denominator != 0)
), "The arguments must been from type int and 'denominator' != 0"
# build the greatest common divisor of numerator and denominator.
_UpperCamelCase = gcd(abs(__snake_case ), abs(__snake_case ) )
# precondition
assert (
isinstance(__snake_case, __snake_case )
and (numerator % gcd_of_fraction == 0)
and (denominator % gcd_of_fraction == 0)
), "Error in function gcd(...,...)"
return (numerator // gcd_of_fraction, denominator // gcd_of_fraction)
def lowerCamelCase__ ( __snake_case ) -> Optional[Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n >= 0), "'n' must been a int and >= 0"
_UpperCamelCase = 1 # this will be return.
for factor in range(1, n + 1 ):
ans *= factor
return ans
def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n >= 0), "'n' must been an int and >= 0"
_UpperCamelCase = 0
_UpperCamelCase = 1
_UpperCamelCase = 1 # this will be return
for _ in range(n - 1 ):
_UpperCamelCase = ans
ans += fiba
_UpperCamelCase = tmp
return ans
| 78 | 0 |
"""simple docstring"""
from abc import ABC, abstractmethod
from typing import Optional, Union
from .. import Dataset, DatasetDict, Features, IterableDataset, IterableDatasetDict, NamedSplit
from ..utils.typing import NestedDataStructureLike, PathLike
class _UpperCAmelCase( lowerCamelCase ):
def __init__( self , __a = None , __a = None , __a = None , __a = None , __a = False , __a = False , __a = None , **__a , ) -> List[str]:
'''simple docstring'''
_UpperCamelCase = path_or_paths
_UpperCamelCase = split if split or isinstance(__a , __a) else '''train'''
_UpperCamelCase = features
_UpperCamelCase = cache_dir
_UpperCamelCase = keep_in_memory
_UpperCamelCase = streaming
_UpperCamelCase = num_proc
_UpperCamelCase = kwargs
@abstractmethod
def UpperCAmelCase ( self) -> Union[Dataset, DatasetDict, IterableDataset, IterableDatasetDict]:
'''simple docstring'''
pass
class _UpperCAmelCase( lowerCamelCase ):
def __init__( self , __a = None , __a = None , __a = False , __a = False , __a = None , **__a , ) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = features
_UpperCamelCase = cache_dir
_UpperCamelCase = keep_in_memory
_UpperCamelCase = streaming
_UpperCamelCase = num_proc
_UpperCamelCase = kwargs
@abstractmethod
def UpperCAmelCase ( self) -> Union[Dataset, IterableDataset]:
'''simple docstring'''
pass
| 701 |
"""simple docstring"""
import logging
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional, Union
from .generation.configuration_utils import GenerationConfig
from .training_args import TrainingArguments
from .utils import add_start_docstrings
_a = logging.getLogger(__name__)
@dataclass
@add_start_docstrings(TrainingArguments.__doc__ )
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = field(default=lowerCamelCase , metadata={'help': 'Whether to use SortishSampler or not.'} )
lowercase__ = field(
default=lowerCamelCase , metadata={'help': 'Whether to use generate to calculate generative metrics (ROUGE, BLEU).'} )
lowercase__ = field(
default=lowerCamelCase , metadata={
'help': (
'The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default '
'to the `max_length` value of the model configuration.'
)
} , )
lowercase__ = field(
default=lowerCamelCase , metadata={
'help': (
'The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default '
'to the `num_beams` value of the model configuration.'
)
} , )
lowercase__ = field(
default=lowerCamelCase , metadata={
'help': 'Model id, file path or url pointing to a GenerationConfig json file, to use during prediction.'
} , )
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = super().to_dict()
for k, v in d.items():
if isinstance(__a , __a):
_UpperCamelCase = v.to_dict()
return d
| 78 | 0 |
"""simple docstring"""
def lowerCamelCase__ ( __snake_case ) -> float:
"""simple docstring"""
if not nums: # Makes sure that the list is not empty
raise ValueError('''List is empty''' )
_UpperCamelCase = sum(__snake_case ) / len(__snake_case ) # Calculate the average
return sum(abs(x - average ) for x in nums ) / len(__snake_case )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 702 |
"""simple docstring"""
import argparse
import torch
from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration
from transformers.utils import logging
logging.set_verbosity_info()
_a = logging.get_logger(__name__)
_a = [
["""attention""", """attn"""],
["""encoder_attention""", """encoder_attn"""],
["""q_lin""", """q_proj"""],
["""k_lin""", """k_proj"""],
["""v_lin""", """v_proj"""],
["""out_lin""", """out_proj"""],
["""norm_embeddings""", """layernorm_embedding"""],
["""position_embeddings""", """embed_positions"""],
["""embeddings""", """embed_tokens"""],
["""ffn.lin""", """fc"""],
]
def lowerCamelCase__ ( __snake_case ) -> Optional[Any]:
"""simple docstring"""
if k == "embeddings.weight":
return "shared.weight"
for parlai_name, hf_name in PATTERNS:
_UpperCamelCase = k.replace(__snake_case, __snake_case )
if k.startswith('''encoder''' ):
_UpperCamelCase = k.replace('''.attn''', '''.self_attn''' )
_UpperCamelCase = k.replace('''norm1''', '''self_attn_layer_norm''' )
_UpperCamelCase = k.replace('''norm2''', '''final_layer_norm''' )
elif k.startswith('''decoder''' ):
_UpperCamelCase = k.replace('''norm1''', '''self_attn_layer_norm''' )
_UpperCamelCase = k.replace('''norm2''', '''encoder_attn_layer_norm''' )
_UpperCamelCase = k.replace('''norm3''', '''final_layer_norm''' )
return k
def lowerCamelCase__ ( __snake_case ) -> Optional[int]:
"""simple docstring"""
_UpperCamelCase = [
'''model.encoder.layernorm_embedding.weight''',
'''model.encoder.layernorm_embedding.bias''',
'''model.decoder.layernorm_embedding.weight''',
'''model.decoder.layernorm_embedding.bias''',
]
for k in keys:
_UpperCamelCase = sd.pop(__snake_case )
_UpperCamelCase = k.replace('''layernorm_embedding''', '''layer_norm''' )
assert new_k not in sd
_UpperCamelCase = v
_a = ["""START"""]
@torch.no_grad()
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = torch.load(__snake_case, map_location='''cpu''' )
_UpperCamelCase = model['''model''']
_UpperCamelCase = BlenderbotConfig.from_json_file(__snake_case )
_UpperCamelCase = BlenderbotForConditionalGeneration(__snake_case )
_UpperCamelCase = m.model.state_dict().keys()
_UpperCamelCase = []
_UpperCamelCase = {}
for k, v in sd.items():
if k in IGNORE_KEYS:
continue
_UpperCamelCase = rename_state_dict_key(__snake_case )
if new_k not in valid_keys:
failures.append([k, new_k] )
else:
_UpperCamelCase = v
if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm
rename_layernorm_keys(__snake_case )
m.model.load_state_dict(__snake_case, strict=__snake_case )
m.half()
m.save_pretrained(__snake_case )
if __name__ == "__main__":
_a = argparse.ArgumentParser()
# Required parameters
parser.add_argument("""--src_path""", type=str, help="""like blenderbot-model.bin""")
parser.add_argument("""--save_dir""", default="""hf_blenderbot""", type=str, help="""Where to save converted model.""")
parser.add_argument(
"""--hf_config_json""", default="""blenderbot-3b-config.json""", type=str, help="""Path to config to use"""
)
_a = parser.parse_args()
convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
| 78 | 0 |
"""simple docstring"""
import inspect
import unittest
from transformers import DecisionTransformerConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import DecisionTransformerModel
from transformers.models.decision_transformer.modeling_decision_transformer import (
DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
)
class _UpperCAmelCase:
def __init__( self , __a , __a=13 , __a=7 , __a=6 , __a=17 , __a=23 , __a=11 , __a=True , ) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = parent
_UpperCamelCase = batch_size
_UpperCamelCase = seq_length
_UpperCamelCase = act_dim
_UpperCamelCase = state_dim
_UpperCamelCase = hidden_size
_UpperCamelCase = max_length
_UpperCamelCase = is_training
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase = floats_tensor((self.batch_size, self.seq_length, self.state_dim))
_UpperCamelCase = floats_tensor((self.batch_size, self.seq_length, self.act_dim))
_UpperCamelCase = floats_tensor((self.batch_size, self.seq_length, 1))
_UpperCamelCase = floats_tensor((self.batch_size, self.seq_length, 1))
_UpperCamelCase = ids_tensor((self.batch_size, self.seq_length) , vocab_size=10_00)
_UpperCamelCase = random_attention_mask((self.batch_size, self.seq_length))
_UpperCamelCase = self.get_config()
return (
config,
states,
actions,
rewards,
returns_to_go,
timesteps,
attention_mask,
)
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
return DecisionTransformerConfig(
batch_size=self.batch_size , seq_length=self.seq_length , act_dim=self.act_dim , state_dim=self.state_dim , hidden_size=self.hidden_size , max_length=self.max_length , )
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a , ) -> Dict:
'''simple docstring'''
_UpperCamelCase = DecisionTransformerModel(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a , __a , __a , __a , __a , __a)
self.parent.assertEqual(result.state_preds.shape , states.shape)
self.parent.assertEqual(result.action_preds.shape , actions.shape)
self.parent.assertEqual(result.return_preds.shape , returns_to_go.shape)
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.seq_length * 3, self.hidden_size)) # seq length *3 as there are 3 modelities: states, returns and actions
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.prepare_config_and_inputs()
(
(
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) ,
) = config_and_inputs
_UpperCamelCase = {
'''states''': states,
'''actions''': actions,
'''rewards''': rewards,
'''returns_to_go''': returns_to_go,
'''timesteps''': timesteps,
'''attention_mask''': attention_mask,
}
return config, inputs_dict
@require_torch
class _UpperCAmelCase( lowerCamelCase , lowerCamelCase , lowerCamelCase , unittest.TestCase ):
lowercase__ = (DecisionTransformerModel,) if is_torch_available() else ()
lowercase__ = ()
lowercase__ = {'feature-extraction': DecisionTransformerModel} if is_torch_available() else {}
# Ignoring of a failing test from GenerationTesterMixin, as the model does not use inputs_ids
lowercase__ = False
# Ignoring of a failing tests from ModelTesterMixin, as the model does not implement these features
lowercase__ = False
lowercase__ = False
lowercase__ = False
lowercase__ = False
lowercase__ = False
lowercase__ = False
lowercase__ = False
lowercase__ = False
lowercase__ = False
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase = DecisionTransformerModelTester(self)
_UpperCamelCase = ConfigTester(self , config_class=__a , hidden_size=37)
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
self.config_tester.run_common_tests()
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__a)
@slow
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
for model_name in DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_UpperCamelCase = DecisionTransformerModel.from_pretrained(__a)
self.assertIsNotNone(__a)
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_UpperCamelCase = model_class(__a)
_UpperCamelCase = inspect.signature(model.forward)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
_UpperCamelCase = [*signature.parameters.keys()]
_UpperCamelCase = [
'''states''',
'''actions''',
'''rewards''',
'''returns_to_go''',
'''timesteps''',
'''attention_mask''',
]
self.assertListEqual(arg_names[: len(__a)] , __a)
@require_torch
class _UpperCAmelCase( unittest.TestCase ):
@slow
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = 2 # number of steps of autoregressive prediction we will perform
_UpperCamelCase = 10 # defined by the RL environment, may be normalized
_UpperCamelCase = DecisionTransformerModel.from_pretrained('''edbeeching/decision-transformer-gym-hopper-expert''')
_UpperCamelCase = model.to(__a)
_UpperCamelCase = model.config
torch.manual_seed(0)
_UpperCamelCase = torch.randn(1 , 1 , config.state_dim).to(device=__a , dtype=torch.floataa) # env.reset()
_UpperCamelCase = torch.tensor(
[[0.24_2793, -0.2869_3074, 0.874_2613], [0.6781_5274, -0.0810_1085, -0.1295_2147]] , device=__a)
_UpperCamelCase = torch.tensor(__a , device=__a , dtype=torch.floataa).reshape(1 , 1 , 1)
_UpperCamelCase = state
_UpperCamelCase = torch.zeros(1 , 0 , config.act_dim , device=__a , dtype=torch.floataa)
_UpperCamelCase = torch.zeros(1 , 0 , device=__a , dtype=torch.floataa)
_UpperCamelCase = torch.tensor(0 , device=__a , dtype=torch.long).reshape(1 , 1)
for step in range(__a):
_UpperCamelCase = torch.cat([actions, torch.zeros(1 , 1 , config.act_dim , device=__a)] , dim=1)
_UpperCamelCase = torch.cat([rewards, torch.zeros(1 , 1 , device=__a)] , dim=1)
_UpperCamelCase = torch.ones(1 , states.shape[1]).to(dtype=torch.long , device=states.device)
with torch.no_grad():
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = model(
states=__a , actions=__a , rewards=__a , returns_to_go=__a , timesteps=__a , attention_mask=__a , return_dict=__a , )
self.assertEqual(action_pred.shape , actions.shape)
self.assertTrue(torch.allclose(action_pred[0, -1] , expected_outputs[step] , atol=1e-4))
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = ( # env.step(action)
torch.randn(1 , 1 , config.state_dim).to(device=__a , dtype=torch.floataa),
1.0,
False,
{},
)
_UpperCamelCase = action_pred[0, -1]
_UpperCamelCase = torch.cat([states, state] , dim=1)
_UpperCamelCase = returns_to_go[0, -1] - reward
_UpperCamelCase = torch.cat([returns_to_go, pred_return.reshape(1 , 1 , 1)] , dim=1)
_UpperCamelCase = torch.cat(
[timesteps, torch.ones((1, 1) , device=__a , dtype=torch.long) * (step + 1)] , dim=1)
| 703 |
"""simple docstring"""
import argparse
import os.path as osp
import re
import torch
from safetensors.torch import load_file, save_file
# =================#
# UNet Conversion #
# =================#
_a = [
# (stable-diffusion, HF Diffusers)
("""time_embed.0.weight""", """time_embedding.linear_1.weight"""),
("""time_embed.0.bias""", """time_embedding.linear_1.bias"""),
("""time_embed.2.weight""", """time_embedding.linear_2.weight"""),
("""time_embed.2.bias""", """time_embedding.linear_2.bias"""),
("""input_blocks.0.0.weight""", """conv_in.weight"""),
("""input_blocks.0.0.bias""", """conv_in.bias"""),
("""out.0.weight""", """conv_norm_out.weight"""),
("""out.0.bias""", """conv_norm_out.bias"""),
("""out.2.weight""", """conv_out.weight"""),
("""out.2.bias""", """conv_out.bias"""),
]
_a = [
# (stable-diffusion, HF Diffusers)
("""in_layers.0""", """norm1"""),
("""in_layers.2""", """conv1"""),
("""out_layers.0""", """norm2"""),
("""out_layers.3""", """conv2"""),
("""emb_layers.1""", """time_emb_proj"""),
("""skip_connection""", """conv_shortcut"""),
]
_a = []
# hardcoded number of downblocks and resnets/attentions...
# would need smarter logic for other networks.
for i in range(4):
# loop over downblocks/upblocks
for j in range(2):
# loop over resnets/attentions for downblocks
_a = F"""down_blocks.{i}.resnets.{j}."""
_a = F"""input_blocks.{3*i + j + 1}.0."""
unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix))
if i < 3:
# no attention layers in down_blocks.3
_a = F"""down_blocks.{i}.attentions.{j}."""
_a = F"""input_blocks.{3*i + j + 1}.1."""
unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix))
for j in range(3):
# loop over resnets/attentions for upblocks
_a = F"""up_blocks.{i}.resnets.{j}."""
_a = F"""output_blocks.{3*i + j}.0."""
unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix))
if i > 0:
# no attention layers in up_blocks.0
_a = F"""up_blocks.{i}.attentions.{j}."""
_a = F"""output_blocks.{3*i + j}.1."""
unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix))
if i < 3:
# no downsample in down_blocks.3
_a = F"""down_blocks.{i}.downsamplers.0.conv."""
_a = F"""input_blocks.{3*(i+1)}.0.op."""
unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix))
# no upsample in up_blocks.3
_a = F"""up_blocks.{i}.upsamplers.0."""
_a = F"""output_blocks.{3*i + 2}.{1 if i == 0 else 2}."""
unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix))
_a = """mid_block.attentions.0."""
_a = """middle_block.1."""
unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix))
for j in range(2):
_a = F"""mid_block.resnets.{j}."""
_a = F"""middle_block.{2*j}."""
unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix))
def lowerCamelCase__ ( __snake_case ) -> str:
"""simple docstring"""
_UpperCamelCase = {k: k for k in unet_state_dict.keys()}
for sd_name, hf_name in unet_conversion_map:
_UpperCamelCase = sd_name
for k, v in mapping.items():
if "resnets" in k:
for sd_part, hf_part in unet_conversion_map_resnet:
_UpperCamelCase = v.replace(__snake_case, __snake_case )
_UpperCamelCase = v
for k, v in mapping.items():
for sd_part, hf_part in unet_conversion_map_layer:
_UpperCamelCase = v.replace(__snake_case, __snake_case )
_UpperCamelCase = v
_UpperCamelCase = {v: unet_state_dict[k] for k, v in mapping.items()}
return new_state_dict
# ================#
# VAE Conversion #
# ================#
_a = [
# (stable-diffusion, HF Diffusers)
("""nin_shortcut""", """conv_shortcut"""),
("""norm_out""", """conv_norm_out"""),
("""mid.attn_1.""", """mid_block.attentions.0."""),
]
for i in range(4):
# down_blocks have two resnets
for j in range(2):
_a = F"""encoder.down_blocks.{i}.resnets.{j}."""
_a = F"""encoder.down.{i}.block.{j}."""
vae_conversion_map.append((sd_down_prefix, hf_down_prefix))
if i < 3:
_a = F"""down_blocks.{i}.downsamplers.0."""
_a = F"""down.{i}.downsample."""
vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix))
_a = F"""up_blocks.{i}.upsamplers.0."""
_a = F"""up.{3-i}.upsample."""
vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix))
# up_blocks have three resnets
# also, up blocks in hf are numbered in reverse from sd
for j in range(3):
_a = F"""decoder.up_blocks.{i}.resnets.{j}."""
_a = F"""decoder.up.{3-i}.block.{j}."""
vae_conversion_map.append((sd_up_prefix, hf_up_prefix))
# this part accounts for mid blocks in both the encoder and the decoder
for i in range(2):
_a = F"""mid_block.resnets.{i}."""
_a = F"""mid.block_{i+1}."""
vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix))
_a = [
# (stable-diffusion, HF Diffusers)
("""norm.""", """group_norm."""),
("""q.""", """query."""),
("""k.""", """key."""),
("""v.""", """value."""),
("""proj_out.""", """proj_attn."""),
]
def lowerCamelCase__ ( __snake_case ) -> List[str]:
"""simple docstring"""
return w.reshape(*w.shape, 1, 1 )
def lowerCamelCase__ ( __snake_case ) -> Optional[Any]:
"""simple docstring"""
_UpperCamelCase = {k: k for k in vae_state_dict.keys()}
for k, v in mapping.items():
for sd_part, hf_part in vae_conversion_map:
_UpperCamelCase = v.replace(__snake_case, __snake_case )
_UpperCamelCase = v
for k, v in mapping.items():
if "attentions" in k:
for sd_part, hf_part in vae_conversion_map_attn:
_UpperCamelCase = v.replace(__snake_case, __snake_case )
_UpperCamelCase = v
_UpperCamelCase = {v: vae_state_dict[k] for k, v in mapping.items()}
_UpperCamelCase = ['''q''', '''k''', '''v''', '''proj_out''']
for k, v in new_state_dict.items():
for weight_name in weights_to_convert:
if F'''mid.attn_1.{weight_name}.weight''' in k:
print(F'''Reshaping {k} for SD format''' )
_UpperCamelCase = reshape_weight_for_sd(__snake_case )
return new_state_dict
# =========================#
# Text Encoder Conversion #
# =========================#
_a = [
# (stable-diffusion, HF Diffusers)
("""resblocks.""", """text_model.encoder.layers."""),
("""ln_1""", """layer_norm1"""),
("""ln_2""", """layer_norm2"""),
(""".c_fc.""", """.fc1."""),
(""".c_proj.""", """.fc2."""),
(""".attn""", """.self_attn"""),
("""ln_final.""", """transformer.text_model.final_layer_norm."""),
("""token_embedding.weight""", """transformer.text_model.embeddings.token_embedding.weight"""),
("""positional_embedding""", """transformer.text_model.embeddings.position_embedding.weight"""),
]
_a = {re.escape(x[1]): x[0] for x in textenc_conversion_lst}
_a = re.compile("""|""".join(protected.keys()))
# Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp
_a = {"""q""": 0, """k""": 1, """v""": 2}
def lowerCamelCase__ ( __snake_case ) -> Any:
"""simple docstring"""
_UpperCamelCase = {}
_UpperCamelCase = {}
_UpperCamelCase = {}
for k, v in text_enc_dict.items():
if (
k.endswith('''.self_attn.q_proj.weight''' )
or k.endswith('''.self_attn.k_proj.weight''' )
or k.endswith('''.self_attn.v_proj.weight''' )
):
_UpperCamelCase = k[: -len('''.q_proj.weight''' )]
_UpperCamelCase = k[-len('''q_proj.weight''' )]
if k_pre not in capture_qkv_weight:
_UpperCamelCase = [None, None, None]
_UpperCamelCase = v
continue
if (
k.endswith('''.self_attn.q_proj.bias''' )
or k.endswith('''.self_attn.k_proj.bias''' )
or k.endswith('''.self_attn.v_proj.bias''' )
):
_UpperCamelCase = k[: -len('''.q_proj.bias''' )]
_UpperCamelCase = k[-len('''q_proj.bias''' )]
if k_pre not in capture_qkv_bias:
_UpperCamelCase = [None, None, None]
_UpperCamelCase = v
continue
_UpperCamelCase = textenc_pattern.sub(lambda __snake_case : protected[re.escape(m.group(0 ) )], __snake_case )
_UpperCamelCase = v
for k_pre, tensors in capture_qkv_weight.items():
if None in tensors:
raise Exception('''CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing''' )
_UpperCamelCase = textenc_pattern.sub(lambda __snake_case : protected[re.escape(m.group(0 ) )], __snake_case )
_UpperCamelCase = torch.cat(__snake_case )
for k_pre, tensors in capture_qkv_bias.items():
if None in tensors:
raise Exception('''CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing''' )
_UpperCamelCase = textenc_pattern.sub(lambda __snake_case : protected[re.escape(m.group(0 ) )], __snake_case )
_UpperCamelCase = torch.cat(__snake_case )
return new_state_dict
def lowerCamelCase__ ( __snake_case ) -> Tuple:
"""simple docstring"""
return text_enc_dict
if __name__ == "__main__":
_a = argparse.ArgumentParser()
parser.add_argument("""--model_path""", default=None, type=str, required=True, help="""Path to the model to convert.""")
parser.add_argument("""--checkpoint_path""", default=None, type=str, required=True, help="""Path to the output model.""")
parser.add_argument("""--half""", action="""store_true""", help="""Save weights in half precision.""")
parser.add_argument(
"""--use_safetensors""", action="""store_true""", help="""Save weights use safetensors, default is ckpt."""
)
_a = parser.parse_args()
assert args.model_path is not None, "Must provide a model path!"
assert args.checkpoint_path is not None, "Must provide a checkpoint path!"
# Path for safetensors
_a = osp.join(args.model_path, """unet""", """diffusion_pytorch_model.safetensors""")
_a = osp.join(args.model_path, """vae""", """diffusion_pytorch_model.safetensors""")
_a = osp.join(args.model_path, """text_encoder""", """model.safetensors""")
# Load models from safetensors if it exists, if it doesn't pytorch
if osp.exists(unet_path):
_a = load_file(unet_path, device="""cpu""")
else:
_a = osp.join(args.model_path, """unet""", """diffusion_pytorch_model.bin""")
_a = torch.load(unet_path, map_location="""cpu""")
if osp.exists(vae_path):
_a = load_file(vae_path, device="""cpu""")
else:
_a = osp.join(args.model_path, """vae""", """diffusion_pytorch_model.bin""")
_a = torch.load(vae_path, map_location="""cpu""")
if osp.exists(text_enc_path):
_a = load_file(text_enc_path, device="""cpu""")
else:
_a = osp.join(args.model_path, """text_encoder""", """pytorch_model.bin""")
_a = torch.load(text_enc_path, map_location="""cpu""")
# Convert the UNet model
_a = convert_unet_state_dict(unet_state_dict)
_a = {"""model.diffusion_model.""" + k: v for k, v in unet_state_dict.items()}
# Convert the VAE model
_a = convert_vae_state_dict(vae_state_dict)
_a = {"""first_stage_model.""" + k: v for k, v in vae_state_dict.items()}
# Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper
_a = """text_model.encoder.layers.22.layer_norm2.bias""" in text_enc_dict
if is_vaa_model:
# Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm
_a = {"""transformer.""" + k: v for k, v in text_enc_dict.items()}
_a = convert_text_enc_state_dict_vaa(text_enc_dict)
_a = {"""cond_stage_model.model.""" + k: v for k, v in text_enc_dict.items()}
else:
_a = convert_text_enc_state_dict(text_enc_dict)
_a = {"""cond_stage_model.transformer.""" + k: v for k, v in text_enc_dict.items()}
# Put together new checkpoint
_a = {**unet_state_dict, **vae_state_dict, **text_enc_dict}
if args.half:
_a = {k: v.half() for k, v in state_dict.items()}
if args.use_safetensors:
save_file(state_dict, args.checkpoint_path)
else:
_a = {"""state_dict""": state_dict}
torch.save(state_dict, args.checkpoint_path)
| 78 | 0 |
"""simple docstring"""
import unittest
import torch
from torch import nn
from diffusers.models.activations import get_activation
class _UpperCAmelCase( unittest.TestCase ):
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase = get_activation('''swish''')
self.assertIsInstance(__a , nn.SiLU)
self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa)).item() , 0)
self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa)).item() , 0)
self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa)).item() , 0)
self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa)).item() , 20)
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
_UpperCamelCase = get_activation('''silu''')
self.assertIsInstance(__a , nn.SiLU)
self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa)).item() , 0)
self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa)).item() , 0)
self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa)).item() , 0)
self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa)).item() , 20)
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = get_activation('''mish''')
self.assertIsInstance(__a , nn.Mish)
self.assertEqual(act(torch.tensor(-2_00 , dtype=torch.floataa)).item() , 0)
self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa)).item() , 0)
self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa)).item() , 0)
self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa)).item() , 20)
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = get_activation('''gelu''')
self.assertIsInstance(__a , nn.GELU)
self.assertEqual(act(torch.tensor(-1_00 , dtype=torch.floataa)).item() , 0)
self.assertNotEqual(act(torch.tensor(-1 , dtype=torch.floataa)).item() , 0)
self.assertEqual(act(torch.tensor(0 , dtype=torch.floataa)).item() , 0)
self.assertEqual(act(torch.tensor(20 , dtype=torch.floataa)).item() , 20)
| 704 |
"""simple docstring"""
import argparse
import torch
from transformers import OpenAIGPTConfig, OpenAIGPTModel, load_tf_weights_in_openai_gpt
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging
logging.set_verbosity_info()
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> Union[str, Any]:
"""simple docstring"""
if openai_config_file == "":
_UpperCamelCase = OpenAIGPTConfig()
else:
_UpperCamelCase = OpenAIGPTConfig.from_json_file(__snake_case )
_UpperCamelCase = OpenAIGPTModel(__snake_case )
# Load weights from numpy
load_tf_weights_in_openai_gpt(__snake_case, __snake_case, __snake_case )
# Save pytorch-model
_UpperCamelCase = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME
_UpperCamelCase = pytorch_dump_folder_path + '''/''' + CONFIG_NAME
print(F'''Save PyTorch model to {pytorch_weights_dump_path}''' )
torch.save(model.state_dict(), __snake_case )
print(F'''Save configuration file to {pytorch_config_dump_path}''' )
with open(__snake_case, '''w''', encoding='''utf-8''' ) as f:
f.write(config.to_json_string() )
if __name__ == "__main__":
_a = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--openai_checkpoint_folder_path""",
default=None,
type=str,
required=True,
help="""Path to the TensorFlow checkpoint path.""",
)
parser.add_argument(
"""--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
)
parser.add_argument(
"""--openai_config_file""",
default="""""",
type=str,
help=(
"""An optional config json file corresponding to the pre-trained OpenAI model. \n"""
"""This specifies the model architecture."""
),
)
_a = parser.parse_args()
convert_openai_checkpoint_to_pytorch(
args.openai_checkpoint_folder_path, args.openai_config_file, args.pytorch_dump_folder_path
)
| 78 | 0 |
"""simple docstring"""
import unittest
from transformers import AlbertConfig, is_torch_available
from transformers.models.auto import get_values
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 (
MODEL_FOR_PRETRAINING_MAPPING,
AlbertForMaskedLM,
AlbertForMultipleChoice,
AlbertForPreTraining,
AlbertForQuestionAnswering,
AlbertForSequenceClassification,
AlbertForTokenClassification,
AlbertModel,
)
from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST
class _UpperCAmelCase:
def __init__( self , __a , __a=13 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=99 , __a=16 , __a=36 , __a=6 , __a=6 , __a=6 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=5_12 , __a=16 , __a=2 , __a=0.02 , __a=3 , __a=4 , __a=None , ) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = parent
_UpperCamelCase = batch_size
_UpperCamelCase = seq_length
_UpperCamelCase = is_training
_UpperCamelCase = use_input_mask
_UpperCamelCase = use_token_type_ids
_UpperCamelCase = use_labels
_UpperCamelCase = vocab_size
_UpperCamelCase = embedding_size
_UpperCamelCase = hidden_size
_UpperCamelCase = num_hidden_layers
_UpperCamelCase = num_hidden_groups
_UpperCamelCase = num_attention_heads
_UpperCamelCase = intermediate_size
_UpperCamelCase = hidden_act
_UpperCamelCase = hidden_dropout_prob
_UpperCamelCase = attention_probs_dropout_prob
_UpperCamelCase = max_position_embeddings
_UpperCamelCase = type_vocab_size
_UpperCamelCase = type_sequence_label_size
_UpperCamelCase = initializer_range
_UpperCamelCase = num_labels
_UpperCamelCase = num_choices
_UpperCamelCase = scope
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size)
_UpperCamelCase = None
if self.use_input_mask:
_UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length])
_UpperCamelCase = None
if self.use_token_type_ids:
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size)
_UpperCamelCase = None
_UpperCamelCase = None
_UpperCamelCase = None
if self.use_labels:
_UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size)
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels)
_UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices)
_UpperCamelCase = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
return 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 , initializer_range=self.initializer_range , num_hidden_groups=self.num_hidden_groups , )
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = AlbertModel(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a , attention_mask=__a , token_type_ids=__a)
_UpperCamelCase = model(__a , token_type_ids=__a)
_UpperCamelCase = model(__a)
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))
self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = AlbertForPreTraining(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(
__a , attention_mask=__a , token_type_ids=__a , labels=__a , sentence_order_label=__a , )
self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size))
self.parent.assertEqual(result.sop_logits.shape , (self.batch_size, config.num_labels))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = AlbertForMaskedLM(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a , attention_mask=__a , token_type_ids=__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) -> Any:
'''simple docstring'''
_UpperCamelCase = AlbertForQuestionAnswering(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(
__a , attention_mask=__a , token_type_ids=__a , start_positions=__a , end_positions=__a , )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length))
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = self.num_labels
_UpperCamelCase = AlbertForSequenceClassification(__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.num_labels
_UpperCamelCase = AlbertForTokenClassification(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = self.num_choices
_UpperCamelCase = AlbertForMultipleChoice(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = input_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous()
_UpperCamelCase = token_type_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous()
_UpperCamelCase = input_mask.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous()
_UpperCamelCase = model(
__a , attention_mask=__a , token_type_ids=__a , labels=__a , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices))
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = self.prepare_config_and_inputs()
(
(
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) ,
) = config_and_inputs
_UpperCamelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
return config, inputs_dict
@require_torch
class _UpperCAmelCase( lowerCamelCase , lowerCamelCase , unittest.TestCase ):
lowercase__ = (
(
AlbertModel,
AlbertForPreTraining,
AlbertForMaskedLM,
AlbertForMultipleChoice,
AlbertForSequenceClassification,
AlbertForTokenClassification,
AlbertForQuestionAnswering,
)
if is_torch_available()
else ()
)
lowercase__ = (
{
'feature-extraction': AlbertModel,
'fill-mask': AlbertForMaskedLM,
'question-answering': AlbertForQuestionAnswering,
'text-classification': AlbertForSequenceClassification,
'token-classification': AlbertForTokenClassification,
'zero-shot': AlbertForSequenceClassification,
}
if is_torch_available()
else {}
)
lowercase__ = True
def UpperCAmelCase ( self , __a , __a , __a=False) -> List[str]:
'''simple docstring'''
_UpperCamelCase = super()._prepare_for_class(__a , __a , return_labels=__a)
if return_labels:
if model_class in get_values(__a):
_UpperCamelCase = torch.zeros(
(self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=__a)
_UpperCamelCase = torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=__a)
return inputs_dict
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = AlbertModelTester(self)
_UpperCamelCase = ConfigTester(self , config_class=__a , hidden_size=37)
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
self.config_tester.run_common_tests()
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__a)
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_pretraining(*__a)
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*__a)
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*__a)
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*__a)
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*__a)
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
_UpperCamelCase = type
self.model_tester.create_and_check_model(*__a)
@slow
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_UpperCamelCase = AlbertModel.from_pretrained(__a)
self.assertIsNotNone(__a)
@require_torch
class _UpperCAmelCase( unittest.TestCase ):
@slow
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = AlbertModel.from_pretrained('''albert-base-v2''')
_UpperCamelCase = torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]])
_UpperCamelCase = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
with torch.no_grad():
_UpperCamelCase = model(__a , attention_mask=__a)[0]
_UpperCamelCase = torch.Size((1, 11, 7_68))
self.assertEqual(output.shape , __a)
_UpperCamelCase = torch.tensor(
[[[-0.6513, 1.5035, -0.2766], [-0.6515, 1.5046, -0.2780], [-0.6512, 1.5049, -0.2784]]])
self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __a , atol=1e-4))
| 705 |
"""simple docstring"""
from __future__ import annotations
import unittest
from transformers import AutoTokenizer, MBartConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel
@require_tf
class _UpperCAmelCase:
lowercase__ = MBartConfig
lowercase__ = {}
lowercase__ = 'gelu'
def __init__( self , __a , __a=13 , __a=7 , __a=True , __a=False , __a=99 , __a=32 , __a=2 , __a=4 , __a=37 , __a=0.1 , __a=0.1 , __a=20 , __a=2 , __a=1 , __a=0 , ) -> Any:
'''simple docstring'''
_UpperCamelCase = parent
_UpperCamelCase = batch_size
_UpperCamelCase = seq_length
_UpperCamelCase = is_training
_UpperCamelCase = use_labels
_UpperCamelCase = vocab_size
_UpperCamelCase = hidden_size
_UpperCamelCase = num_hidden_layers
_UpperCamelCase = num_attention_heads
_UpperCamelCase = intermediate_size
_UpperCamelCase = hidden_dropout_prob
_UpperCamelCase = attention_probs_dropout_prob
_UpperCamelCase = max_position_embeddings
_UpperCamelCase = eos_token_id
_UpperCamelCase = pad_token_id
_UpperCamelCase = bos_token_id
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size)
_UpperCamelCase = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size) , 1)
_UpperCamelCase = tf.concat([input_ids, eos_tensor] , axis=1)
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size)
_UpperCamelCase = self.config_cls(
vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , )
_UpperCamelCase = prepare_mbart_inputs_dict(__a , __a , __a)
return config, inputs_dict
def UpperCAmelCase ( self , __a , __a) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = TFMBartModel(config=__a).get_decoder()
_UpperCamelCase = inputs_dict['''input_ids''']
_UpperCamelCase = input_ids[:1, :]
_UpperCamelCase = inputs_dict['''attention_mask'''][:1, :]
_UpperCamelCase = inputs_dict['''head_mask''']
_UpperCamelCase = 1
# first forward pass
_UpperCamelCase = model(__a , attention_mask=__a , head_mask=__a , use_cache=__a)
_UpperCamelCase , _UpperCamelCase = outputs.to_tuple()
_UpperCamelCase = past_key_values[1]
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case, __snake_case=None, __snake_case=None, __snake_case=None, __snake_case=None, __snake_case=None, ) -> Optional[int]:
"""simple docstring"""
if attention_mask is None:
_UpperCamelCase = tf.cast(tf.math.not_equal(__snake_case, config.pad_token_id ), tf.inta )
if decoder_attention_mask is None:
_UpperCamelCase = tf.concat(
[
tf.ones(decoder_input_ids[:, :1].shape, dtype=tf.inta ),
tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:], config.pad_token_id ), tf.inta ),
], axis=-1, )
if head_mask is None:
_UpperCamelCase = tf.ones((config.encoder_layers, config.encoder_attention_heads) )
if decoder_head_mask is None:
_UpperCamelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
if cross_attn_head_mask is None:
_UpperCamelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
return {
"input_ids": input_ids,
"decoder_input_ids": decoder_input_ids,
"attention_mask": attention_mask,
"decoder_attention_mask": decoder_attention_mask,
"head_mask": head_mask,
"decoder_head_mask": decoder_head_mask,
"cross_attn_head_mask": cross_attn_head_mask,
}
@require_tf
class _UpperCAmelCase( lowerCamelCase , lowerCamelCase , unittest.TestCase ):
lowercase__ = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else ()
lowercase__ = (TFMBartForConditionalGeneration,) if is_tf_available() else ()
lowercase__ = (
{
'conversational': TFMBartForConditionalGeneration,
'feature-extraction': TFMBartModel,
'summarization': TFMBartForConditionalGeneration,
'text2text-generation': TFMBartForConditionalGeneration,
'translation': TFMBartForConditionalGeneration,
}
if is_tf_available()
else {}
)
lowercase__ = True
lowercase__ = False
lowercase__ = False
def UpperCAmelCase ( self , __a , __a , __a , __a , __a) -> Dict:
'''simple docstring'''
if pipeline_test_casse_name != "FeatureExtractionPipelineTests":
# Exception encountered when calling layer '...'
return True
return False
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase = TFMBartModelTester(self)
_UpperCamelCase = ConfigTester(self , config_class=__a)
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
self.config_tester.run_common_tests()
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_decoder_model_past_large_inputs(*__a)
@require_sentencepiece
@require_tokenizers
@require_tf
class _UpperCAmelCase( unittest.TestCase ):
lowercase__ = [
' UN Chief Says There Is No Military Solution in Syria',
]
lowercase__ = [
'Şeful ONU declară că nu există o soluţie militară în Siria',
]
lowercase__ = 'facebook/mbart-large-en-ro'
@cached_property
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
return AutoTokenizer.from_pretrained(self.model_name)
@cached_property
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
_UpperCamelCase = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name)
return model
def UpperCAmelCase ( self , **__a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.translate_src_text(**__a)
self.assertListEqual(self.expected_text , __a)
def UpperCAmelCase ( self , **__a) -> Dict:
'''simple docstring'''
_UpperCamelCase = self.tokenizer(self.src_text , **__a , return_tensors='''tf''')
_UpperCamelCase = self.model.generate(
model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2)
_UpperCamelCase = self.tokenizer.batch_decode(__a , skip_special_tokens=__a)
return generated_words
@slow
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
self._assert_generated_batch_equal_expected()
| 78 | 0 |
"""simple docstring"""
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
_a = logging.get_logger(__name__)
_a = Dict[str, Any]
_a = List[Prediction]
@add_end_docstrings(lowerCamelCase )
class _UpperCAmelCase( lowerCamelCase ):
def __init__( self , *__a , **__a) -> Union[str, Any]:
'''simple docstring'''
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) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = {}
if "threshold" in kwargs:
_UpperCamelCase = kwargs['''threshold''']
return {}, {}, postprocess_kwargs
def __call__( self , *__a , **__a) -> Union[Predictions, List[Prediction]]:
'''simple docstring'''
return super().__call__(*__a , **__a)
def UpperCAmelCase ( self , __a) -> Any:
'''simple docstring'''
_UpperCamelCase = load_image(__a)
_UpperCamelCase = torch.IntTensor([[image.height, image.width]])
_UpperCamelCase = self.image_processor(images=[image] , return_tensors='''pt''')
if self.tokenizer is not None:
_UpperCamelCase = self.tokenizer(text=inputs['''words'''] , boxes=inputs['''boxes'''] , return_tensors='''pt''')
_UpperCamelCase = target_size
return inputs
def UpperCAmelCase ( self , __a) -> int:
'''simple docstring'''
_UpperCamelCase = model_inputs.pop('''target_size''')
_UpperCamelCase = self.model(**__a)
_UpperCamelCase = outputs.__class__({'''target_size''': target_size, **outputs})
if self.tokenizer is not None:
_UpperCamelCase = model_inputs['''bbox''']
return model_outputs
def UpperCAmelCase ( self , __a , __a=0.9) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = 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.
_UpperCamelCase , _UpperCamelCase = target_size[0].tolist()
def unnormalize(__a):
return self._get_bounding_box(
torch.Tensor(
[
(width * bbox[0] / 10_00),
(height * bbox[1] / 10_00),
(width * bbox[2] / 10_00),
(height * bbox[3] / 10_00),
]))
_UpperCamelCase , _UpperCamelCase = model_outputs['''logits'''].squeeze(0).softmax(dim=-1).max(dim=-1)
_UpperCamelCase = [self.model.config.idalabel[prediction] for prediction in classes.tolist()]
_UpperCamelCase = [unnormalize(__a) for bbox in model_outputs['''bbox'''].squeeze(0)]
_UpperCamelCase = ['''score''', '''label''', '''box''']
_UpperCamelCase = [dict(zip(__a , __a)) for vals in zip(scores.tolist() , __a , __a) if vals[0] > threshold]
else:
# This is a regular ForObjectDetectionModel
_UpperCamelCase = self.image_processor.post_process_object_detection(__a , __a , __a)
_UpperCamelCase = raw_annotations[0]
_UpperCamelCase = raw_annotation['''scores''']
_UpperCamelCase = raw_annotation['''labels''']
_UpperCamelCase = raw_annotation['''boxes''']
_UpperCamelCase = scores.tolist()
_UpperCamelCase = [self.model.config.idalabel[label.item()] for label in labels]
_UpperCamelCase = [self._get_bounding_box(__a) for box in boxes]
# {"scores": [...], ...} --> [{"score":x, ...}, ...]
_UpperCamelCase = ['''score''', '''label''', '''box''']
_UpperCamelCase = [
dict(zip(__a , __a))
for vals in zip(raw_annotation['''scores'''] , raw_annotation['''labels'''] , raw_annotation['''boxes'''])
]
return annotation
def UpperCAmelCase ( self , __a) -> Dict[str, int]:
'''simple docstring'''
if self.framework != "pt":
raise ValueError('''The ObjectDetectionPipeline is only available in PyTorch.''')
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = box.int().tolist()
_UpperCamelCase = {
'''xmin''': xmin,
'''ymin''': ymin,
'''xmax''': xmax,
'''ymax''': ymax,
}
return bbox
| 706 |
"""simple docstring"""
from typing import Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format
from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images
from ...utils import TensorType, logging
_a = logging.get_logger(__name__)
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = ['pixel_values']
def __init__( self , __a = True , __a = 1 / 2_55 , __a = True , __a = 8 , **__a , ) -> None:
'''simple docstring'''
super().__init__(**__a)
_UpperCamelCase = do_rescale
_UpperCamelCase = rescale_factor
_UpperCamelCase = do_pad
_UpperCamelCase = pad_size
def UpperCAmelCase ( self , __a , __a , __a = None , **__a) -> np.ndarray:
'''simple docstring'''
return rescale(__a , scale=__a , data_format=__a , **__a)
def UpperCAmelCase ( self , __a , __a , __a = None) -> List[Any]:
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase = get_image_size(__a)
_UpperCamelCase = (old_height // size + 1) * size - old_height
_UpperCamelCase = (old_width // size + 1) * size - old_width
return pad(__a , ((0, pad_height), (0, pad_width)) , mode='''symmetric''' , data_format=__a)
def UpperCAmelCase ( self , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = ChannelDimension.FIRST , **__a , ) -> Tuple:
'''simple docstring'''
_UpperCamelCase = do_rescale if do_rescale is not None else self.do_rescale
_UpperCamelCase = rescale_factor if rescale_factor is not None else self.rescale_factor
_UpperCamelCase = do_pad if do_pad is not None else self.do_pad
_UpperCamelCase = pad_size if pad_size is not None else self.pad_size
_UpperCamelCase = make_list_of_images(__a)
if not valid_images(__a):
raise ValueError(
'''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
'''torch.Tensor, tf.Tensor or jax.ndarray.''')
if do_rescale and rescale_factor is None:
raise ValueError('''Rescale factor must be specified if do_rescale is True.''')
# All transformations expect numpy arrays.
_UpperCamelCase = [to_numpy_array(__a) for image in images]
if do_rescale:
_UpperCamelCase = [self.rescale(image=__a , scale=__a) for image in images]
if do_pad:
_UpperCamelCase = [self.pad(__a , size=__a) for image in images]
_UpperCamelCase = [to_channel_dimension_format(__a , __a) for image in images]
_UpperCamelCase = {'''pixel_values''': images}
return BatchFeature(data=__a , tensor_type=__a)
| 78 | 0 |
"""simple docstring"""
import os
import time
import pytest
from datasets.utils.filelock import FileLock, Timeout
def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]:
"""simple docstring"""
_UpperCamelCase = FileLock(str(tmpdir / '''foo.lock''' ) )
_UpperCamelCase = FileLock(str(tmpdir / '''foo.lock''' ) )
_UpperCamelCase = 0.01
with locka.acquire():
with pytest.raises(__snake_case ):
_UpperCamelCase = time.time()
locka.acquire(__snake_case )
assert time.time() - _start > timeout
def lowerCamelCase__ ( __snake_case ) -> List[Any]:
"""simple docstring"""
_UpperCamelCase = '''a''' * 10_00 + '''.lock'''
_UpperCamelCase = FileLock(str(tmpdir / filename ) )
assert locka._lock_file.endswith('''.lock''' )
assert not locka._lock_file.endswith(__snake_case )
assert len(os.path.basename(locka._lock_file ) ) <= 2_55
_UpperCamelCase = FileLock(tmpdir / filename )
with locka.acquire():
with pytest.raises(__snake_case ):
locka.acquire(0 ) | 707 |
"""simple docstring"""
from importlib import import_module
from .logging import get_logger
_a = get_logger(__name__)
class _UpperCAmelCase:
def __init__( self , __a , __a=None) -> Dict:
'''simple docstring'''
_UpperCamelCase = attrs or []
if module is not None:
for key in module.__dict__:
if key in attrs or not key.startswith('''__'''):
setattr(self , __a , getattr(__a , __a))
_UpperCamelCase = module._original_module if isinstance(__a , _PatchedModuleObj) else module
class _UpperCAmelCase:
lowercase__ = []
def __init__( self , __a , __a , __a , __a=None) -> List[str]:
'''simple docstring'''
_UpperCamelCase = obj
_UpperCamelCase = target
_UpperCamelCase = new
_UpperCamelCase = target.split('''.''')[0]
_UpperCamelCase = {}
_UpperCamelCase = attrs or []
def __enter__( self) -> int:
'''simple docstring'''
*_UpperCamelCase , _UpperCamelCase = self.target.split('''.''')
# Patch modules:
# it's used to patch attributes of submodules like "os.path.join";
# in this case we need to patch "os" and "os.path"
for i in range(len(__a)):
try:
_UpperCamelCase = import_module('''.'''.join(submodules[: i + 1]))
except ModuleNotFoundError:
continue
# We iterate over all the globals in self.obj in case we find "os" or "os.path"
for attr in self.obj.__dir__():
_UpperCamelCase = getattr(self.obj , __a)
# We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
# This allows to patch renamed modules like "from os import path as ospath".
if obj_attr is submodule or (
(isinstance(__a , _PatchedModuleObj) and obj_attr._original_module is submodule)
):
_UpperCamelCase = obj_attr
# patch at top level
setattr(self.obj , __a , _PatchedModuleObj(__a , attrs=self.attrs))
_UpperCamelCase = getattr(self.obj , __a)
# construct lower levels patches
for key in submodules[i + 1 :]:
setattr(__a , __a , _PatchedModuleObj(getattr(__a , __a , __a) , attrs=self.attrs))
_UpperCamelCase = getattr(__a , __a)
# finally set the target attribute
setattr(__a , __a , self.new)
# Patch attribute itself:
# it's used for builtins like "open",
# and also to patch "os.path.join" we may also need to patch "join"
# itself if it was imported as "from os.path import join".
if submodules: # if it's an attribute of a submodule like "os.path.join"
try:
_UpperCamelCase = getattr(import_module('''.'''.join(__a)) , __a)
except (AttributeError, ModuleNotFoundError):
return
# We iterate over all the globals in self.obj in case we find "os.path.join"
for attr in self.obj.__dir__():
# We don't check for the name of the global, but rather if its value *is* "os.path.join".
# This allows to patch renamed attributes like "from os.path import join as pjoin".
if getattr(self.obj , __a) is attr_value:
_UpperCamelCase = getattr(self.obj , __a)
setattr(self.obj , __a , self.new)
elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open"
_UpperCamelCase = globals()['''__builtins__'''][target_attr]
setattr(self.obj , __a , self.new)
else:
raise RuntimeError(F'''Tried to patch attribute {target_attr} instead of a submodule.''')
def __exit__( self , *__a) -> Tuple:
'''simple docstring'''
for attr in list(self.original):
setattr(self.obj , __a , self.original.pop(__a))
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
self.__enter__()
self._active_patches.append(self)
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
try:
self._active_patches.remove(self)
except ValueError:
# If the patch hasn't been started this will fail
return None
return self.__exit__()
| 78 | 0 |
"""simple docstring"""
def lowerCamelCase__ ( __snake_case=2_81_23 ) -> Optional[int]:
"""simple docstring"""
_UpperCamelCase = [1] * (limit + 1)
for i in range(2, int(limit**0.5 ) + 1 ):
sum_divs[i * i] += i
for k in range(i + 1, limit // i + 1 ):
sum_divs[k * i] += k + i
_UpperCamelCase = set()
_UpperCamelCase = 0
for n in range(1, limit + 1 ):
if sum_divs[n] > n:
abundants.add(__snake_case )
if not any((n - a in abundants) for a in abundants ):
res += n
return res
if __name__ == "__main__":
print(solution())
| 708 |
"""simple docstring"""
from ...utils import (
OptionalDependencyNotAvailable,
is_flax_available,
is_torch_available,
is_transformers_available,
)
try:
if not (is_transformers_available() and is_torch_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ...utils.dummy_torch_and_transformers_objects import * # noqa F403
else:
from .multicontrolnet import MultiControlNetModel
from .pipeline_controlnet import StableDiffusionControlNetPipeline
from .pipeline_controlnet_imgaimg import StableDiffusionControlNetImgaImgPipeline
from .pipeline_controlnet_inpaint import StableDiffusionControlNetInpaintPipeline
if is_transformers_available() and is_flax_available():
from .pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline
| 78 | 0 |
"""simple docstring"""
import sacrebleu as scb
from packaging import version
from sacrebleu import CHRF
import datasets
_a = """\
@inproceedings{popovic-2015-chrf,
title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",
author = \"Popovi{\'c}, Maja\",
booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",
month = sep,
year = \"2015\",
address = \"Lisbon, Portugal\",
publisher = \"Association for Computational Linguistics\",
url = \"https://aclanthology.org/W15-3049\",
doi = \"10.18653/v1/W15-3049\",
pages = \"392--395\",
}
@inproceedings{popovic-2017-chrf,
title = \"chr{F}++: words helping character n-grams\",
author = \"Popovi{\'c}, Maja\",
booktitle = \"Proceedings of the Second Conference on Machine Translation\",
month = sep,
year = \"2017\",
address = \"Copenhagen, Denmark\",
publisher = \"Association for Computational Linguistics\",
url = \"https://aclanthology.org/W17-4770\",
doi = \"10.18653/v1/W17-4770\",
pages = \"612--618\",
}
@inproceedings{post-2018-call,
title = \"A Call for Clarity in Reporting {BLEU} Scores\",
author = \"Post, Matt\",
booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",
month = oct,
year = \"2018\",
address = \"Belgium, Brussels\",
publisher = \"Association for Computational Linguistics\",
url = \"https://www.aclweb.org/anthology/W18-6319\",
pages = \"186--191\",
}
"""
_a = """\
ChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,
and ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation
that is already present in sacrebleu.
The implementation here is slightly different from sacrebleu in terms of the required input format. The length of
the references and hypotheses lists need to be the same, so you may need to transpose your references compared to
sacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534
See the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.
"""
_a = """
Produces ChrF(++) scores for hypotheses given reference translations.
Args:
predictions (list of str): The predicted sentences.
references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.
char_order (int): Character n-gram order. Defaults to `6`.
word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.
beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.
lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.
whitespace (bool): If `True`, include whitespaces when extracting character n-grams.
eps_smoothing (bool): If `True`, applies epsilon smoothing similar
to reference chrF++.py, NLTK and Moses implementations. If `False`,
it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.
Returns:
'score' (float): The chrF (chrF++) score,
'char_order' (int): The character n-gram order,
'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,
'beta' (int): Determine the importance of recall w.r.t precision
Examples:
Example 1--a simple example of calculating chrF:
>>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]
>>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]
>>> chrf = datasets.load_metric(\"chrf\")
>>> results = chrf.compute(predictions=prediction, references=reference)
>>> print(results)
{'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}
Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:
>>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]
>>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]
>>> chrf = datasets.load_metric(\"chrf\")
>>> results = chrf.compute(predictions=prediction,
... references=reference,
... word_order=2)
>>> print(results)
{'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}
Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:
>>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]
>>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]
>>> chrf = datasets.load_metric(\"chrf\")
>>> results = chrf.compute(predictions=prediction,
... references=reference,
... word_order=2,
... lowercase=True)
>>> print(results)
{'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class _UpperCAmelCase( datasets.Metric ):
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
if version.parse(scb.__version__) < version.parse('''1.4.12'''):
raise ImportWarning(
'''To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n'''
'''You can install it with `pip install "sacrebleu>=1.4.12"`.''')
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/mjpost/sacreBLEU#chrf--chrf''' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
'''predictions''': datasets.Value('''string''' , id='''sequence'''),
'''references''': datasets.Sequence(datasets.Value('''string''' , id='''sequence''') , id='''references'''),
}) , codebase_urls=['''https://github.com/mjpost/sacreBLEU#chrf--chrf'''] , reference_urls=[
'''https://github.com/m-popovic/chrF''',
] , )
def UpperCAmelCase ( self , __a , __a , __a = CHRF.CHAR_ORDER , __a = CHRF.WORD_ORDER , __a = CHRF.BETA , __a = False , __a = False , __a = False , ) -> Dict:
'''simple docstring'''
_UpperCamelCase = len(references[0])
if any(len(__a) != references_per_prediction for refs in references):
raise ValueError('''Sacrebleu requires the same number of references for each prediction''')
_UpperCamelCase = [[refs[i] for refs in references] for i in range(__a)]
_UpperCamelCase = CHRF(__a , __a , __a , __a , __a , __a)
_UpperCamelCase = sb_chrf.corpus_score(__a , __a)
return {
"score": output.score,
"char_order": output.char_order,
"word_order": output.word_order,
"beta": output.beta,
}
| 709 |
"""simple docstring"""
from collections import OrderedDict
from typing import Any, Mapping, Optional
from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast
from ...utils import logging
_a = logging.get_logger(__name__)
_a = {
"""EleutherAI/gpt-neo-1.3B""": """https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json""",
# See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo
}
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = 'gpt_neo'
lowercase__ = ['past_key_values']
lowercase__ = {'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers'}
def __init__( self , __a=5_02_57 , __a=20_48 , __a=20_48 , __a=24 , __a=[[["global", "local"], 12]] , __a=16 , __a=None , __a=2_56 , __a="gelu_new" , __a=0.0 , __a=0.0 , __a=0.0 , __a=0.1 , __a=1e-5 , __a=0.02 , __a=True , __a=5_02_56 , __a=5_02_56 , **__a , ) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = vocab_size
_UpperCamelCase = max_position_embeddings
_UpperCamelCase = hidden_size
_UpperCamelCase = num_layers
_UpperCamelCase = num_heads
_UpperCamelCase = intermediate_size
_UpperCamelCase = window_size
_UpperCamelCase = activation_function
_UpperCamelCase = resid_dropout
_UpperCamelCase = embed_dropout
_UpperCamelCase = attention_dropout
_UpperCamelCase = classifier_dropout
_UpperCamelCase = layer_norm_epsilon
_UpperCamelCase = initializer_range
_UpperCamelCase = use_cache
_UpperCamelCase = bos_token_id
_UpperCamelCase = eos_token_id
_UpperCamelCase = attention_types
_UpperCamelCase = self.expand_attention_types_params(__a)
if len(self.attention_layers) != self.num_layers:
raise ValueError(
'''Configuration for convolutional module is incorrect. '''
'''It is required that `len(config.attention_layers)` == `config.num_layers` '''
F'''but is `len(config.attention_layers) = {len(self.attention_layers)}`, '''
F'''`config.num_layers = {self.num_layers}`. '''
'''`config.attention_layers` is prepared using `config.attention_types`. '''
'''Please verify the value of `config.attention_types` argument.''')
super().__init__(bos_token_id=__a , eos_token_id=__a , **__a)
@staticmethod
def UpperCAmelCase ( __a) -> int:
'''simple docstring'''
_UpperCamelCase = []
for item in attention_types:
for _ in range(item[1]):
attentions.extend(item[0])
return attentions
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case, __snake_case ) -> str:
"""simple docstring"""
import torch
_UpperCamelCase = input.size()
_UpperCamelCase = len(__snake_case )
_UpperCamelCase = shape[dimension]
_UpperCamelCase = torch.arange(0, __snake_case, __snake_case )
_UpperCamelCase = torch.div(sizedim - size, __snake_case, rounding_mode='''floor''' ) + 1
_UpperCamelCase = torch.arange(__snake_case ) + low_indices[:min_length][:, None]
_UpperCamelCase = [slice(__snake_case )] * rank
_UpperCamelCase = indices
_UpperCamelCase = input[s]
_UpperCamelCase = list(range(0, rank + 1 ) )
perm.append(perm.pop(dimension + 1 ) )
return sliced.permute(__snake_case )
def lowerCamelCase__ ( __snake_case, __snake_case ) -> str:
"""simple docstring"""
import torch
_UpperCamelCase = torch.arange(1, __snake_case )
_UpperCamelCase = torch.remainder(__snake_case, __snake_case )
_UpperCamelCase = remainders == 0
_UpperCamelCase = candidates[divisor_indices]
_UpperCamelCase = torch.max(__snake_case )
return largest_divisor, torch.div(__snake_case, __snake_case, rounding_mode='''floor''' )
class _UpperCAmelCase( lowerCamelCase ):
@property
def UpperCAmelCase ( self) -> Mapping[str, Mapping[int, str]]:
'''simple docstring'''
_UpperCamelCase = OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}})
if self.use_past:
self.fill_with_past_key_values_(__a , direction='''inputs''')
_UpperCamelCase = {0: '''batch''', 1: '''past_sequence + sequence'''}
else:
_UpperCamelCase = {0: '''batch''', 1: '''sequence'''}
return common_inputs
@property
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
return self._config.num_heads
def UpperCAmelCase ( self , __a , __a = -1 , __a = -1 , __a = False , __a = None , ) -> Mapping[str, Any]:
'''simple docstring'''
_UpperCamelCase = 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()
_UpperCamelCase = 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
_UpperCamelCase , _UpperCamelCase = common_inputs['''input_ids'''].shape
# Not using the same length for past_key_values
_UpperCamelCase = seqlen + 2
_UpperCamelCase = (
batch,
self.num_attention_heads,
past_key_values_length,
self._config.hidden_size // self.num_attention_heads,
)
_UpperCamelCase = [
(torch.zeros(__a), torch.zeros(__a)) for _ in range(self.num_layers)
]
_UpperCamelCase = common_inputs['''attention_mask''']
if self.use_past:
_UpperCamelCase = ordered_inputs['''attention_mask'''].dtype
_UpperCamelCase = torch.cat(
[ordered_inputs['''attention_mask'''], torch.ones(__a , __a , dtype=__a)] , dim=1)
return ordered_inputs
@property
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
return 13
| 78 | 0 |
"""simple docstring"""
from __future__ import annotations
import math
def lowerCamelCase__ ( __snake_case ) -> bool:
"""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(__snake_case ) + 1 ), 6 ):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
_a = [num for num in range(3, 10_0001, 2) if not is_prime(num)]
def lowerCamelCase__ ( __snake_case ) -> list[int]:
"""simple docstring"""
if not isinstance(__snake_case, __snake_case ):
raise ValueError('''n must be an integer''' )
if n <= 0:
raise ValueError('''n must be >= 0''' )
_UpperCamelCase = []
for num in range(len(__snake_case ) ):
_UpperCamelCase = 0
while 2 * i * i <= odd_composites[num]:
_UpperCamelCase = odd_composites[num] - 2 * i * i
if is_prime(__snake_case ):
break
i += 1
else:
list_nums.append(odd_composites[num] )
if len(__snake_case ) == n:
return list_nums
return []
def lowerCamelCase__ ( ) -> int:
"""simple docstring"""
return compute_nums(1 )[0]
if __name__ == "__main__":
print(F"""{solution() = }""")
| 710 |
"""simple docstring"""
import sys
from collections import defaultdict
class _UpperCAmelCase:
def __init__( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = []
def UpperCAmelCase ( self , __a) -> Optional[Any]:
'''simple docstring'''
return self.node_position[vertex]
def UpperCAmelCase ( self , __a , __a) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = pos
def UpperCAmelCase ( self , __a , __a , __a , __a) -> Tuple:
'''simple docstring'''
if start > size // 2 - 1:
return
else:
if 2 * start + 2 >= size:
_UpperCamelCase = 2 * start + 1
else:
if heap[2 * start + 1] < heap[2 * start + 2]:
_UpperCamelCase = 2 * start + 1
else:
_UpperCamelCase = 2 * start + 2
if heap[smallest_child] < heap[start]:
_UpperCamelCase , _UpperCamelCase = heap[smallest_child], positions[smallest_child]
_UpperCamelCase , _UpperCamelCase = (
heap[start],
positions[start],
)
_UpperCamelCase , _UpperCamelCase = temp, tempa
_UpperCamelCase = self.get_position(positions[smallest_child])
self.set_position(
positions[smallest_child] , self.get_position(positions[start]))
self.set_position(positions[start] , __a)
self.top_to_bottom(__a , __a , __a , __a)
def UpperCAmelCase ( self , __a , __a , __a , __a) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = position[index]
while index != 0:
_UpperCamelCase = int((index - 2) / 2) if index % 2 == 0 else int((index - 1) / 2)
if val < heap[parent]:
_UpperCamelCase = heap[parent]
_UpperCamelCase = position[parent]
self.set_position(position[parent] , __a)
else:
_UpperCamelCase = val
_UpperCamelCase = temp
self.set_position(__a , __a)
break
_UpperCamelCase = parent
else:
_UpperCamelCase = val
_UpperCamelCase = temp
self.set_position(__a , 0)
def UpperCAmelCase ( self , __a , __a) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = len(__a) // 2 - 1
for i in range(__a , -1 , -1):
self.top_to_bottom(__a , __a , len(__a) , __a)
def UpperCAmelCase ( self , __a , __a) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = positions[0]
_UpperCamelCase = sys.maxsize
self.top_to_bottom(__a , 0 , len(__a) , __a)
return temp
def lowerCamelCase__ ( __snake_case ) -> Optional[int]:
"""simple docstring"""
_UpperCamelCase = Heap()
_UpperCamelCase = [0] * len(__snake_case )
_UpperCamelCase = [-1] * len(__snake_case ) # Neighboring Tree Vertex of selected vertex
# Minimum Distance of explored vertex with neighboring vertex of partial tree
# formed in graph
_UpperCamelCase = [] # Heap of Distance of vertices from their neighboring vertex
_UpperCamelCase = []
for vertex in range(len(__snake_case ) ):
distance_tv.append(sys.maxsize )
positions.append(__snake_case )
heap.node_position.append(__snake_case )
_UpperCamelCase = []
_UpperCamelCase = 1
_UpperCamelCase = sys.maxsize
for neighbor, distance in adjacency_list[0]:
_UpperCamelCase = 0
_UpperCamelCase = distance
heap.heapify(__snake_case, __snake_case )
for _ in range(1, len(__snake_case ) ):
_UpperCamelCase = heap.delete_minimum(__snake_case, __snake_case )
if visited[vertex] == 0:
tree_edges.append((nbr_tv[vertex], vertex) )
_UpperCamelCase = 1
for neighbor, distance in adjacency_list[vertex]:
if (
visited[neighbor] == 0
and distance < distance_tv[heap.get_position(__snake_case )]
):
_UpperCamelCase = distance
heap.bottom_to_top(
__snake_case, heap.get_position(__snake_case ), __snake_case, __snake_case )
_UpperCamelCase = vertex
return tree_edges
if __name__ == "__main__": # pragma: no cover
# < --------- Prims Algorithm --------- >
_a = int(input("""Enter number of edges: """).strip())
_a = defaultdict(list)
for _ in range(edges_number):
_a = [int(x) for x in input().strip().split()]
adjacency_list[edge[0]].append([edge[1], edge[2]])
adjacency_list[edge[1]].append([edge[0], edge[2]])
print(prisms_algorithm(adjacency_list))
| 78 | 0 |
"""simple docstring"""
from __future__ import annotations
from collections import namedtuple
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> tuple:
"""simple docstring"""
_UpperCamelCase = namedtuple('''result''', '''name value''' )
if (voltage, current, power).count(0 ) != 1:
raise ValueError('''Only one argument must be 0''' )
elif power < 0:
raise ValueError(
'''Power cannot be negative in any electrical/electronics system''' )
elif voltage == 0:
return result('''voltage''', power / current )
elif current == 0:
return result('''current''', power / voltage )
elif power == 0:
return result('''power''', float(round(abs(voltage * current ), 2 ) ) )
else:
raise ValueError('''Exactly one argument must be 0''' )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 711 |
"""simple docstring"""
import json
import sys
def lowerCamelCase__ ( __snake_case, __snake_case ) -> Union[str, Any]:
"""simple docstring"""
with open(__snake_case, encoding='''utf-8''' ) as f:
_UpperCamelCase = json.load(__snake_case )
_UpperCamelCase = ['''<details>''', '''<summary>Show updated benchmarks!</summary>''', ''' ''']
for benchmark_name in sorted(__snake_case ):
_UpperCamelCase = results[benchmark_name]
_UpperCamelCase = benchmark_name.split('''/''' )[-1]
output_md.append(F'''### Benchmark: {benchmark_file_name}''' )
_UpperCamelCase = '''| metric |'''
_UpperCamelCase = '''|--------|'''
_UpperCamelCase = '''| new / old (diff) |'''
for metric_name in sorted(__snake_case ):
_UpperCamelCase = benchmark_res[metric_name]
_UpperCamelCase = metric_vals['''new''']
_UpperCamelCase = metric_vals.get('''old''', __snake_case )
_UpperCamelCase = metric_vals.get('''diff''', __snake_case )
_UpperCamelCase = F''' {new_val:f}''' if isinstance(__snake_case, (int, float) ) else '''None'''
if old_val is not None:
val_str += F''' / {old_val:f}''' if isinstance(__snake_case, (int, float) ) else "None"
if dif_val is not None:
val_str += F''' ({dif_val:f})''' if isinstance(__snake_case, (int, float) ) else "None"
title += " " + metric_name + " |"
lines += "---|"
value += val_str + " |"
output_md += [title, lines, value, " "]
output_md.append('''</details>''' )
with open(__snake_case, '''w''', encoding='''utf-8''' ) as f:
f.writelines('''\n'''.join(__snake_case ) )
if __name__ == "__main__":
_a = sys.argv[1]
_a = sys.argv[2]
format_json_to_md(input_json_file, output_md_file)
| 78 | 0 |
"""simple docstring"""
import warnings
from typing import Dict, List, Optional, Tuple
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging
_a = logging.get_logger(__name__)
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = ['input_ids', 'attention_mask']
def __init__( self , __a="</s>" , __a="<unk>" , __a="<pad>" , __a=1_25 , __a=None , **__a , ) -> None:
'''simple docstring'''
# Add extra_ids to the special token list
if extra_ids > 0 and additional_special_tokens is None:
_UpperCamelCase = [F'''<extra_id_{i}>''' for i in range(__a)]
elif extra_ids > 0 and additional_special_tokens is not None:
# Check that we have the right number of extra_id special tokens
_UpperCamelCase = len(set(filter(lambda __a: bool('''extra_id''' in str(__a)) , __a)))
if extra_tokens != extra_ids:
raise ValueError(
F'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are'''
''' provided to ByT5Tokenizer. In this case the additional_special_tokens must include the'''
''' extra_ids tokens''')
_UpperCamelCase = AddedToken(__a , lstrip=__a , rstrip=__a) if isinstance(__a , __a) else pad_token
_UpperCamelCase = AddedToken(__a , lstrip=__a , rstrip=__a) if isinstance(__a , __a) else eos_token
_UpperCamelCase = AddedToken(__a , lstrip=__a , rstrip=__a) if isinstance(__a , __a) else unk_token
super().__init__(
eos_token=__a , unk_token=__a , pad_token=__a , extra_ids=__a , additional_special_tokens=__a , **__a , )
_UpperCamelCase = extra_ids
_UpperCamelCase = 2**8 # utf is 8 bits
# define special tokens dict
_UpperCamelCase = {
self.pad_token: 0,
self.eos_token: 1,
self.unk_token: 2,
}
_UpperCamelCase = len(self.special_tokens_encoder)
_UpperCamelCase = len(__a)
for i, token in enumerate(__a):
_UpperCamelCase = self.vocab_size + i - n
_UpperCamelCase = {v: k for k, v in self.special_tokens_encoder.items()}
@property
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
return self._utf_vocab_size + self._num_special_tokens + self._extra_ids
def UpperCAmelCase ( self , __a , __a = None , __a = False) -> List[int]:
'''simple docstring'''
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=__a , token_ids_a=__a , already_has_special_tokens=__a)
# normal case: some special tokens
if token_ids_a is None:
return ([0] * len(__a)) + [1]
return ([0] * len(__a)) + [1] + ([0] * len(__a)) + [1]
def UpperCAmelCase ( self , __a) -> List[int]:
'''simple docstring'''
if len(__a) > 0 and token_ids[-1] == self.eos_token_id:
warnings.warn(
F'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated'''
''' eos tokens being added.''')
return token_ids
else:
return token_ids + [self.eos_token_id]
def UpperCAmelCase ( self , __a , __a = None) -> List[int]:
'''simple docstring'''
_UpperCamelCase = [self.eos_token_id]
if token_ids_a is None:
return len(token_ids_a + eos) * [0]
return len(token_ids_a + eos + token_ids_a + eos) * [0]
def UpperCAmelCase ( self , __a , __a = None) -> List[int]:
'''simple docstring'''
_UpperCamelCase = self._add_eos_if_not_present(__a)
if token_ids_a is None:
return token_ids_a
else:
_UpperCamelCase = self._add_eos_if_not_present(__a)
return token_ids_a + token_ids_a
def UpperCAmelCase ( self , __a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = [chr(__a) for i in text.encode('''utf-8''')]
return tokens
def UpperCAmelCase ( self , __a) -> Any:
'''simple docstring'''
if token in self.special_tokens_encoder:
_UpperCamelCase = self.special_tokens_encoder[token]
elif token in self.added_tokens_encoder:
_UpperCamelCase = self.added_tokens_encoder[token]
elif len(__a) != 1:
_UpperCamelCase = self.unk_token_id
else:
_UpperCamelCase = ord(__a) + self._num_special_tokens
return token_id
def UpperCAmelCase ( self , __a) -> Tuple:
'''simple docstring'''
if index in self.special_tokens_decoder:
_UpperCamelCase = self.special_tokens_decoder[index]
else:
_UpperCamelCase = chr(index - self._num_special_tokens)
return token
def UpperCAmelCase ( self , __a) -> Any:
'''simple docstring'''
_UpperCamelCase = B''''''
for token in tokens:
if token in self.special_tokens_decoder:
_UpperCamelCase = self.special_tokens_decoder[token].encode('''utf-8''')
elif token in self.added_tokens_decoder:
_UpperCamelCase = self.special_tokens_decoder[token].encode('''utf-8''')
elif token in self.special_tokens_encoder:
_UpperCamelCase = token.encode('''utf-8''')
elif token in self.added_tokens_encoder:
_UpperCamelCase = token.encode('''utf-8''')
else:
_UpperCamelCase = bytes([ord(__a)])
bstring += tok_string
_UpperCamelCase = bstring.decode('''utf-8''' , errors='''ignore''')
return string
def UpperCAmelCase ( self , __a , __a = None) -> Tuple[str]:
'''simple docstring'''
return ()
| 712 |
"""simple docstring"""
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()
_a = logging.get_logger(__name__)
def lowerCamelCase__ ( __snake_case, __snake_case=False ) -> Tuple:
"""simple docstring"""
_UpperCamelCase = []
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"
_UpperCamelCase = [(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 lowerCamelCase__ ( __snake_case, __snake_case, __snake_case=False ) -> str:
"""simple docstring"""
for i in range(config.num_hidden_layers ):
if base_model:
_UpperCamelCase = ''''''
else:
_UpperCamelCase = '''vit.'''
# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
_UpperCamelCase = state_dict.pop(F'''blocks.{i}.attn.qkv.weight''' )
_UpperCamelCase = state_dict.pop(F'''blocks.{i}.attn.qkv.bias''' )
# next, add query, keys and values (in that order) to the state dict
_UpperCamelCase = in_proj_weight[
: config.hidden_size, :
]
_UpperCamelCase = in_proj_bias[: config.hidden_size]
_UpperCamelCase = in_proj_weight[
config.hidden_size : config.hidden_size * 2, :
]
_UpperCamelCase = in_proj_bias[
config.hidden_size : config.hidden_size * 2
]
_UpperCamelCase = in_proj_weight[
-config.hidden_size :, :
]
_UpperCamelCase = in_proj_bias[-config.hidden_size :]
def lowerCamelCase__ ( __snake_case ) -> Dict:
"""simple docstring"""
_UpperCamelCase = ['''head.weight''', '''head.bias''']
for k in ignore_keys:
state_dict.pop(__snake_case, __snake_case )
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> Any:
"""simple docstring"""
_UpperCamelCase = dct.pop(__snake_case )
_UpperCamelCase = val
def lowerCamelCase__ ( ) -> Dict:
"""simple docstring"""
_UpperCamelCase = '''http://images.cocodataset.org/val2017/000000039769.jpg'''
_UpperCamelCase = Image.open(requests.get(__snake_case, stream=__snake_case ).raw )
return im
@torch.no_grad()
def lowerCamelCase__ ( __snake_case, __snake_case ) -> Union[str, Any]:
"""simple docstring"""
_UpperCamelCase = ViTConfig()
_UpperCamelCase = False
# dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size
if vit_name[-5:] == "in21k":
_UpperCamelCase = True
_UpperCamelCase = int(vit_name[-12:-10] )
_UpperCamelCase = int(vit_name[-9:-6] )
else:
_UpperCamelCase = 10_00
_UpperCamelCase = '''huggingface/label-files'''
_UpperCamelCase = '''imagenet-1k-id2label.json'''
_UpperCamelCase = json.load(open(hf_hub_download(__snake_case, __snake_case, repo_type='''dataset''' ), '''r''' ) )
_UpperCamelCase = {int(__snake_case ): v for k, v in idalabel.items()}
_UpperCamelCase = idalabel
_UpperCamelCase = {v: k for k, v in idalabel.items()}
_UpperCamelCase = int(vit_name[-6:-4] )
_UpperCamelCase = int(vit_name[-3:] )
# size of the architecture
if "deit" in vit_name:
if vit_name[9:].startswith('''tiny''' ):
_UpperCamelCase = 1_92
_UpperCamelCase = 7_68
_UpperCamelCase = 12
_UpperCamelCase = 3
elif vit_name[9:].startswith('''small''' ):
_UpperCamelCase = 3_84
_UpperCamelCase = 15_36
_UpperCamelCase = 12
_UpperCamelCase = 6
else:
pass
else:
if vit_name[4:].startswith('''small''' ):
_UpperCamelCase = 7_68
_UpperCamelCase = 23_04
_UpperCamelCase = 8
_UpperCamelCase = 8
elif vit_name[4:].startswith('''base''' ):
pass
elif vit_name[4:].startswith('''large''' ):
_UpperCamelCase = 10_24
_UpperCamelCase = 40_96
_UpperCamelCase = 24
_UpperCamelCase = 16
elif vit_name[4:].startswith('''huge''' ):
_UpperCamelCase = 12_80
_UpperCamelCase = 51_20
_UpperCamelCase = 32
_UpperCamelCase = 16
# load original model from timm
_UpperCamelCase = timm.create_model(__snake_case, pretrained=__snake_case )
timm_model.eval()
# load state_dict of original model, remove and rename some keys
_UpperCamelCase = timm_model.state_dict()
if base_model:
remove_classification_head_(__snake_case )
_UpperCamelCase = create_rename_keys(__snake_case, __snake_case )
for src, dest in rename_keys:
rename_key(__snake_case, __snake_case, __snake_case )
read_in_q_k_v(__snake_case, __snake_case, __snake_case )
# load HuggingFace model
if vit_name[-5:] == "in21k":
_UpperCamelCase = ViTModel(__snake_case ).eval()
else:
_UpperCamelCase = ViTForImageClassification(__snake_case ).eval()
model.load_state_dict(__snake_case )
# Check outputs on an image, prepared by ViTImageProcessor/DeiTImageProcessor
if "deit" in vit_name:
_UpperCamelCase = DeiTImageProcessor(size=config.image_size )
else:
_UpperCamelCase = ViTImageProcessor(size=config.image_size )
_UpperCamelCase = image_processor(images=prepare_img(), return_tensors='''pt''' )
_UpperCamelCase = encoding['''pixel_values''']
_UpperCamelCase = model(__snake_case )
if base_model:
_UpperCamelCase = timm_model.forward_features(__snake_case )
assert timm_pooled_output.shape == outputs.pooler_output.shape
assert torch.allclose(__snake_case, outputs.pooler_output, atol=1e-3 )
else:
_UpperCamelCase = timm_model(__snake_case )
assert timm_logits.shape == outputs.logits.shape
assert torch.allclose(__snake_case, outputs.logits, atol=1e-3 )
Path(__snake_case ).mkdir(exist_ok=__snake_case )
print(F'''Saving model {vit_name} to {pytorch_dump_folder_path}''' )
model.save_pretrained(__snake_case )
print(F'''Saving image processor to {pytorch_dump_folder_path}''' )
image_processor.save_pretrained(__snake_case )
if __name__ == "__main__":
_a = 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."""
)
_a = parser.parse_args()
convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path)
| 78 | 0 |
"""simple docstring"""
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
if not isinstance(__snake_case, __snake_case ):
_UpperCamelCase = F'''Input value of [number={number}] must be an integer'''
raise TypeError(__snake_case )
if number < 1:
_UpperCamelCase = F'''Input value of [number={number}] must be > 0'''
raise ValueError(__snake_case )
_UpperCamelCase = 1
for i in range(1, __snake_case ):
current_number *= 4 * i - 2
current_number //= i + 1
return current_number
if __name__ == "__main__":
import doctest
doctest.testmod()
| 713 |
"""simple docstring"""
import unittest
from transformers import AlbertConfig, is_torch_available
from transformers.models.auto import get_values
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 (
MODEL_FOR_PRETRAINING_MAPPING,
AlbertForMaskedLM,
AlbertForMultipleChoice,
AlbertForPreTraining,
AlbertForQuestionAnswering,
AlbertForSequenceClassification,
AlbertForTokenClassification,
AlbertModel,
)
from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST
class _UpperCAmelCase:
def __init__( self , __a , __a=13 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=99 , __a=16 , __a=36 , __a=6 , __a=6 , __a=6 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=5_12 , __a=16 , __a=2 , __a=0.02 , __a=3 , __a=4 , __a=None , ) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = parent
_UpperCamelCase = batch_size
_UpperCamelCase = seq_length
_UpperCamelCase = is_training
_UpperCamelCase = use_input_mask
_UpperCamelCase = use_token_type_ids
_UpperCamelCase = use_labels
_UpperCamelCase = vocab_size
_UpperCamelCase = embedding_size
_UpperCamelCase = hidden_size
_UpperCamelCase = num_hidden_layers
_UpperCamelCase = num_hidden_groups
_UpperCamelCase = num_attention_heads
_UpperCamelCase = intermediate_size
_UpperCamelCase = hidden_act
_UpperCamelCase = hidden_dropout_prob
_UpperCamelCase = attention_probs_dropout_prob
_UpperCamelCase = max_position_embeddings
_UpperCamelCase = type_vocab_size
_UpperCamelCase = type_sequence_label_size
_UpperCamelCase = initializer_range
_UpperCamelCase = num_labels
_UpperCamelCase = num_choices
_UpperCamelCase = scope
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size)
_UpperCamelCase = None
if self.use_input_mask:
_UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length])
_UpperCamelCase = None
if self.use_token_type_ids:
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size)
_UpperCamelCase = None
_UpperCamelCase = None
_UpperCamelCase = None
if self.use_labels:
_UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size)
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels)
_UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices)
_UpperCamelCase = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
return 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 , initializer_range=self.initializer_range , num_hidden_groups=self.num_hidden_groups , )
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = AlbertModel(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a , attention_mask=__a , token_type_ids=__a)
_UpperCamelCase = model(__a , token_type_ids=__a)
_UpperCamelCase = model(__a)
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))
self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = AlbertForPreTraining(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(
__a , attention_mask=__a , token_type_ids=__a , labels=__a , sentence_order_label=__a , )
self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size))
self.parent.assertEqual(result.sop_logits.shape , (self.batch_size, config.num_labels))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = AlbertForMaskedLM(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a , attention_mask=__a , token_type_ids=__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) -> Any:
'''simple docstring'''
_UpperCamelCase = AlbertForQuestionAnswering(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(
__a , attention_mask=__a , token_type_ids=__a , start_positions=__a , end_positions=__a , )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length))
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = self.num_labels
_UpperCamelCase = AlbertForSequenceClassification(__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.num_labels
_UpperCamelCase = AlbertForTokenClassification(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = self.num_choices
_UpperCamelCase = AlbertForMultipleChoice(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = input_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous()
_UpperCamelCase = token_type_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous()
_UpperCamelCase = input_mask.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous()
_UpperCamelCase = model(
__a , attention_mask=__a , token_type_ids=__a , labels=__a , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices))
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = self.prepare_config_and_inputs()
(
(
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) ,
) = config_and_inputs
_UpperCamelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
return config, inputs_dict
@require_torch
class _UpperCAmelCase( lowerCamelCase , lowerCamelCase , unittest.TestCase ):
lowercase__ = (
(
AlbertModel,
AlbertForPreTraining,
AlbertForMaskedLM,
AlbertForMultipleChoice,
AlbertForSequenceClassification,
AlbertForTokenClassification,
AlbertForQuestionAnswering,
)
if is_torch_available()
else ()
)
lowercase__ = (
{
'feature-extraction': AlbertModel,
'fill-mask': AlbertForMaskedLM,
'question-answering': AlbertForQuestionAnswering,
'text-classification': AlbertForSequenceClassification,
'token-classification': AlbertForTokenClassification,
'zero-shot': AlbertForSequenceClassification,
}
if is_torch_available()
else {}
)
lowercase__ = True
def UpperCAmelCase ( self , __a , __a , __a=False) -> List[str]:
'''simple docstring'''
_UpperCamelCase = super()._prepare_for_class(__a , __a , return_labels=__a)
if return_labels:
if model_class in get_values(__a):
_UpperCamelCase = torch.zeros(
(self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=__a)
_UpperCamelCase = torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=__a)
return inputs_dict
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = AlbertModelTester(self)
_UpperCamelCase = ConfigTester(self , config_class=__a , hidden_size=37)
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
self.config_tester.run_common_tests()
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__a)
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_pretraining(*__a)
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*__a)
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*__a)
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*__a)
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*__a)
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
_UpperCamelCase = type
self.model_tester.create_and_check_model(*__a)
@slow
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_UpperCamelCase = AlbertModel.from_pretrained(__a)
self.assertIsNotNone(__a)
@require_torch
class _UpperCAmelCase( unittest.TestCase ):
@slow
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = AlbertModel.from_pretrained('''albert-base-v2''')
_UpperCamelCase = torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]])
_UpperCamelCase = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
with torch.no_grad():
_UpperCamelCase = model(__a , attention_mask=__a)[0]
_UpperCamelCase = torch.Size((1, 11, 7_68))
self.assertEqual(output.shape , __a)
_UpperCamelCase = torch.tensor(
[[[-0.6513, 1.5035, -0.2766], [-0.6515, 1.5046, -0.2780], [-0.6512, 1.5049, -0.2784]]])
self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __a , atol=1e-4))
| 78 | 0 |
"""simple docstring"""
from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor
from .base import PipelineTool
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = 'openai/whisper-base'
lowercase__ = (
'This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the '
'transcribed text.'
)
lowercase__ = 'transcriber'
lowercase__ = WhisperProcessor
lowercase__ = WhisperForConditionalGeneration
lowercase__ = ['audio']
lowercase__ = ['text']
def UpperCAmelCase ( self , __a) -> Union[str, Any]:
'''simple docstring'''
return self.pre_processor(__a , return_tensors='''pt''').input_features
def UpperCAmelCase ( self , __a) -> List[str]:
'''simple docstring'''
return self.model.generate(inputs=__a)
def UpperCAmelCase ( self , __a) -> Union[str, Any]:
'''simple docstring'''
return self.pre_processor.batch_decode(__a , skip_special_tokens=__a)[0]
| 714 |
"""simple docstring"""
import os
from typing import BinaryIO, Optional, Union
import numpy as np
import pyarrow.parquet as pq
from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config
from ..features.features import FeatureType, _visit
from ..formatting import query_table
from ..packaged_modules import _PACKAGED_DATASETS_MODULES
from ..packaged_modules.parquet.parquet import Parquet
from ..utils import logging
from ..utils.typing import NestedDataStructureLike, PathLike
from .abc import AbstractDatasetReader
def lowerCamelCase__ ( __snake_case ) -> Optional[int]:
"""simple docstring"""
_UpperCamelCase = np.inf
def set_batch_size(__snake_case ) -> None:
nonlocal batch_size
if isinstance(__snake_case, __snake_case ):
_UpperCamelCase = min(__snake_case, config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS )
elif isinstance(__snake_case, __snake_case ):
_UpperCamelCase = min(__snake_case, config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS )
elif isinstance(__snake_case, __snake_case ) and feature.dtype == "binary":
_UpperCamelCase = min(__snake_case, config.PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS )
_visit(__snake_case, __snake_case )
return None if batch_size is np.inf else batch_size
class _UpperCAmelCase( lowerCamelCase ):
def __init__( self , __a , __a = None , __a = None , __a = None , __a = False , __a = False , __a = None , **__a , ) -> Dict:
'''simple docstring'''
super().__init__(
__a , split=__a , features=__a , cache_dir=__a , keep_in_memory=__a , streaming=__a , num_proc=__a , **__a , )
_UpperCamelCase = path_or_paths if isinstance(__a , __a) else {self.split: path_or_paths}
_UpperCamelCase = _PACKAGED_DATASETS_MODULES['''parquet'''][1]
_UpperCamelCase = Parquet(
cache_dir=__a , data_files=__a , features=__a , hash=__a , **__a , )
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
# Build iterable dataset
if self.streaming:
_UpperCamelCase = self.builder.as_streaming_dataset(split=self.split)
# Build regular (map-style) dataset
else:
_UpperCamelCase = None
_UpperCamelCase = None
_UpperCamelCase = None
_UpperCamelCase = None
self.builder.download_and_prepare(
download_config=__a , download_mode=__a , verification_mode=__a , base_path=__a , num_proc=self.num_proc , )
_UpperCamelCase = self.builder.as_dataset(
split=self.split , verification_mode=__a , in_memory=self.keep_in_memory)
return dataset
class _UpperCAmelCase:
def __init__( self , __a , __a , __a = None , **__a , ) -> Dict:
'''simple docstring'''
_UpperCamelCase = dataset
_UpperCamelCase = path_or_buf
_UpperCamelCase = batch_size or get_writer_batch_size(dataset.features)
_UpperCamelCase = parquet_writer_kwargs
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
_UpperCamelCase = self.batch_size if self.batch_size else config.DEFAULT_MAX_BATCH_SIZE
if isinstance(self.path_or_buf , (str, bytes, os.PathLike)):
with open(self.path_or_buf , '''wb+''') as buffer:
_UpperCamelCase = self._write(file_obj=__a , batch_size=__a , **self.parquet_writer_kwargs)
else:
_UpperCamelCase = self._write(file_obj=self.path_or_buf , batch_size=__a , **self.parquet_writer_kwargs)
return written
def UpperCAmelCase ( self , __a , __a , **__a) -> int:
'''simple docstring'''
_UpperCamelCase = 0
_UpperCamelCase = parquet_writer_kwargs.pop('''path_or_buf''' , __a)
_UpperCamelCase = self.dataset.features.arrow_schema
_UpperCamelCase = pq.ParquetWriter(__a , schema=__a , **__a)
for offset in logging.tqdm(
range(0 , len(self.dataset) , __a) , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating parquet from Arrow format''' , ):
_UpperCamelCase = query_table(
table=self.dataset._data , key=slice(__a , offset + batch_size) , indices=self.dataset._indices if self.dataset._indices is not None else None , )
writer.write_table(__a)
written += batch.nbytes
writer.close()
return written
| 78 | 0 |
"""simple docstring"""
import argparse
import re
import requests
import torch
# git clone https://github.com/salesforce/BLIP.git
from models.blip import blip_decoder
from models.blip_itm import blip_itm
from models.blip_vqa import blip_vqa
from PIL import Image
from torchvision import transforms
from torchvision.transforms.functional import InterpolationMode
from transformers import (
BertTokenizer,
BlipConfig,
BlipForConditionalGeneration,
BlipForImageTextRetrieval,
BlipForQuestionAnswering,
)
def lowerCamelCase__ ( __snake_case, __snake_case ) -> Optional[int]:
"""simple docstring"""
_UpperCamelCase = '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg'''
_UpperCamelCase = Image.open(requests.get(__snake_case, stream=__snake_case ).raw ).convert('''RGB''' )
_UpperCamelCase = transforms.Compose(
[
transforms.Resize((image_size, image_size), interpolation=InterpolationMode.BICUBIC ),
transforms.ToTensor(),
transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711) ),
] )
_UpperCamelCase = transform(__snake_case ).unsqueeze(0 ).to(__snake_case )
return image
def lowerCamelCase__ ( __snake_case ) -> Dict:
"""simple docstring"""
if "visual_encoder" in key:
_UpperCamelCase = re.sub('''visual_encoder*''', '''vision_model.encoder''', __snake_case )
if "blocks" in key:
_UpperCamelCase = re.sub(r'''blocks''', '''layers''', __snake_case )
if "attn" in key:
_UpperCamelCase = re.sub(r'''attn''', '''self_attn''', __snake_case )
if "norm1" in key:
_UpperCamelCase = re.sub(r'''norm1''', '''layer_norm1''', __snake_case )
if "norm2" in key:
_UpperCamelCase = re.sub(r'''norm2''', '''layer_norm2''', __snake_case )
if "encoder.norm" in key:
_UpperCamelCase = re.sub(r'''encoder.norm''', '''post_layernorm''', __snake_case )
if "encoder.patch_embed.proj" in key:
_UpperCamelCase = re.sub(r'''encoder.patch_embed.proj''', '''embeddings.patch_embedding''', __snake_case )
if "encoder.pos_embed" in key:
_UpperCamelCase = re.sub(r'''encoder.pos_embed''', '''embeddings.position_embedding''', __snake_case )
if "encoder.cls_token" in key:
_UpperCamelCase = re.sub(r'''encoder.cls_token''', '''embeddings.class_embedding''', __snake_case )
if "self_attn" in key:
_UpperCamelCase = re.sub(r'''self_attn.proj''', '''self_attn.projection''', __snake_case )
return key
@torch.no_grad()
def lowerCamelCase__ ( __snake_case, __snake_case=None ) -> Union[str, Any]:
"""simple docstring"""
if config_path is not None:
_UpperCamelCase = BlipConfig.from_pretrained(__snake_case )
else:
_UpperCamelCase = BlipConfig(projection_dim=5_12, text_config={}, vision_config={} )
_UpperCamelCase = BlipForConditionalGeneration(__snake_case ).eval()
_UpperCamelCase = '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth'''
_UpperCamelCase = blip_decoder(pretrained=__snake_case, image_size=3_84, vit='''base''' )
_UpperCamelCase = pt_model.eval()
_UpperCamelCase = pt_model.state_dict()
for key in modified_state_dict.copy():
_UpperCamelCase = modified_state_dict.pop(__snake_case )
_UpperCamelCase = rename_key(__snake_case )
_UpperCamelCase = value
hf_model.load_state_dict(__snake_case )
_UpperCamelCase = 3_84
_UpperCamelCase = load_demo_image(image_size=__snake_case, device='''cpu''' )
_UpperCamelCase = BertTokenizer.from_pretrained('''bert-base-uncased''' )
_UpperCamelCase = tokenizer(['''a picture of'''] ).input_ids
_UpperCamelCase = hf_model.generate(__snake_case, __snake_case )
assert out[0].tolist() == [3_05_22, 10_37, 38_61, 19_97, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02]
_UpperCamelCase = hf_model.generate(__snake_case )
assert out[0].tolist() == [3_05_22, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02]
if pytorch_dump_folder_path is not None:
hf_model.save_pretrained(__snake_case )
# model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth'
_UpperCamelCase = (
'''https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth'''
)
_UpperCamelCase = blip_vqa(pretrained=__snake_case, image_size=__snake_case, vit='''base''' )
vqa_model.eval()
_UpperCamelCase = vqa_model.state_dict()
for key in modified_state_dict.copy():
_UpperCamelCase = modified_state_dict.pop(__snake_case )
_UpperCamelCase = rename_key(__snake_case )
_UpperCamelCase = value
_UpperCamelCase = BlipForQuestionAnswering(__snake_case )
hf_vqa_model.load_state_dict(__snake_case )
_UpperCamelCase = ['''How many dogs are in this image?''']
_UpperCamelCase = tokenizer(__snake_case, return_tensors='''pt''' ).input_ids
_UpperCamelCase = hf_vqa_model.generate(__snake_case, __snake_case )
print(tokenizer.decode(answer[0] ) )
assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]"
if pytorch_dump_folder_path is not None:
hf_vqa_model.save_pretrained(pytorch_dump_folder_path + '''_vqa''' )
_UpperCamelCase = '''https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth'''
_UpperCamelCase = blip_itm(pretrained=__snake_case, image_size=__snake_case, vit='''base''' )
itm_model.eval()
_UpperCamelCase = itm_model.state_dict()
for key in modified_state_dict.copy():
_UpperCamelCase = modified_state_dict.pop(__snake_case )
_UpperCamelCase = rename_key(__snake_case )
_UpperCamelCase = value
_UpperCamelCase = BlipForImageTextRetrieval(__snake_case )
_UpperCamelCase = ['''A picture of a woman with a dog sitting in a beach''']
_UpperCamelCase = tokenizer(
__snake_case, return_tensors='''pt''', padding='''max_length''', truncation=__snake_case, max_length=35, ).input_ids
hf_itm_model.load_state_dict(__snake_case )
hf_itm_model.eval()
_UpperCamelCase = hf_itm_model(__snake_case, __snake_case, use_itm_head=__snake_case )
_UpperCamelCase = hf_itm_model(__snake_case, __snake_case, use_itm_head=__snake_case )
assert out[0].item() == 0.2110687494277954
assert torch.nn.functional.softmax(out_itm[0], dim=1 )[:, 1].item() == 0.45698845386505127
if pytorch_dump_folder_path is not None:
hf_itm_model.save_pretrained(pytorch_dump_folder_path + '''_itm''' )
if __name__ == "__main__":
_a = argparse.ArgumentParser()
parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""")
parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""")
_a = parser.parse_args()
convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
| 715 |
"""simple docstring"""
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import MobileViTImageProcessor
class _UpperCAmelCase( unittest.TestCase ):
def __init__( self , __a , __a=7 , __a=3 , __a=18 , __a=30 , __a=4_00 , __a=True , __a=None , __a=True , __a=None , __a=True , ) -> int:
'''simple docstring'''
_UpperCamelCase = size if size is not None else {'''shortest_edge''': 20}
_UpperCamelCase = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}
_UpperCamelCase = parent
_UpperCamelCase = batch_size
_UpperCamelCase = num_channels
_UpperCamelCase = image_size
_UpperCamelCase = min_resolution
_UpperCamelCase = max_resolution
_UpperCamelCase = do_resize
_UpperCamelCase = size
_UpperCamelCase = do_center_crop
_UpperCamelCase = crop_size
_UpperCamelCase = do_flip_channel_order
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
return {
"do_resize": self.do_resize,
"size": self.size,
"do_center_crop": self.do_center_crop,
"crop_size": self.crop_size,
"do_flip_channel_order": self.do_flip_channel_order,
}
@require_torch
@require_vision
class _UpperCAmelCase( lowerCamelCase , unittest.TestCase ):
lowercase__ = MobileViTImageProcessor if is_vision_available() else None
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = MobileViTImageProcessingTester(self)
@property
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
return self.image_processor_tester.prepare_image_processor_dict()
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(__a , '''do_resize'''))
self.assertTrue(hasattr(__a , '''size'''))
self.assertTrue(hasattr(__a , '''do_center_crop'''))
self.assertTrue(hasattr(__a , '''center_crop'''))
self.assertTrue(hasattr(__a , '''do_flip_channel_order'''))
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.image_processing_class.from_dict(self.image_processor_dict)
self.assertEqual(image_processor.size , {'''shortest_edge''': 20})
self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18})
_UpperCamelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84)
self.assertEqual(image_processor.size , {'''shortest_edge''': 42})
self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84})
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
pass
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
# Initialize image_processing
_UpperCamelCase = self.image_processing_class(**self.image_processor_dict)
# create random PIL images
_UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a)
for image in image_inputs:
self.assertIsInstance(__a , Image.Image)
# Test not batched input
_UpperCamelCase = image_processing(image_inputs[0] , return_tensors='''pt''').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
# Test batched
_UpperCamelCase = image_processing(__a , return_tensors='''pt''').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
# Initialize image_processing
_UpperCamelCase = self.image_processing_class(**self.image_processor_dict)
# create random numpy tensors
_UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , numpify=__a)
for image in image_inputs:
self.assertIsInstance(__a , np.ndarray)
# Test not batched input
_UpperCamelCase = image_processing(image_inputs[0] , return_tensors='''pt''').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
# Test batched
_UpperCamelCase = image_processing(__a , return_tensors='''pt''').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
# Initialize image_processing
_UpperCamelCase = self.image_processing_class(**self.image_processor_dict)
# create random PyTorch tensors
_UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , torchify=__a)
for image in image_inputs:
self.assertIsInstance(__a , torch.Tensor)
# Test not batched input
_UpperCamelCase = image_processing(image_inputs[0] , return_tensors='''pt''').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
# Test batched
_UpperCamelCase = image_processing(__a , return_tensors='''pt''').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
| 78 | 0 |
"""simple docstring"""
import argparse
import json
import os
import fairseq
import torch
from torch import nn
from transformers import (
SpeechaTextaConfig,
SpeechaTextaForCausalLM,
SpeechaTextaTokenizer,
SpeechEncoderDecoderConfig,
SpeechEncoderDecoderModel,
WavaVecaConfig,
WavaVecaFeatureExtractor,
WavaVecaModel,
logging,
)
logging.set_verbosity_info()
_a = logging.get_logger(__name__)
_a = {
"""post_extract_proj""": """feature_projection.projection""",
"""encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""",
"""self_attn.k_proj""": """encoder.layers.*.attention.k_proj""",
"""self_attn.v_proj""": """encoder.layers.*.attention.v_proj""",
"""self_attn.q_proj""": """encoder.layers.*.attention.q_proj""",
"""self_attn.out_proj""": """encoder.layers.*.attention.out_proj""",
"""self_attn_layer_norm""": """encoder.layers.*.layer_norm""",
"""fc1""": """encoder.layers.*.feed_forward.intermediate_dense""",
"""fc2""": """encoder.layers.*.feed_forward.output_dense""",
"""final_layer_norm""": """encoder.layers.*.final_layer_norm""",
"""encoder.layer_norm""": """encoder.layer_norm""",
"""w2v_model.layer_norm""": """feature_projection.layer_norm""",
"""quantizer.weight_proj""": """quantizer.weight_proj""",
"""quantizer.vars""": """quantizer.codevectors""",
"""project_q""": """project_q""",
"""final_proj""": """project_hid""",
"""w2v_encoder.proj""": """lm_head""",
"""mask_emb""": """masked_spec_embed""",
}
_a = [
"""lm_head""",
"""quantizer.weight_proj""",
"""quantizer.codevectors""",
"""project_q""",
"""project_hid""",
]
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case, __snake_case, __snake_case ) -> Tuple:
"""simple docstring"""
for attribute in key.split('''.''' ):
_UpperCamelCase = getattr(__snake_case, __snake_case )
if weight_type is not None:
_UpperCamelCase = getattr(__snake_case, __snake_case ).shape
else:
_UpperCamelCase = hf_pointer.shape
assert hf_shape == value.shape, (
F'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be'''
F''' {value.shape} for {full_name}'''
)
if weight_type == "weight":
_UpperCamelCase = value
elif weight_type == "weight_g":
_UpperCamelCase = value
elif weight_type == "weight_v":
_UpperCamelCase = value
elif weight_type == "bias":
_UpperCamelCase = value
else:
_UpperCamelCase = value
logger.info(F'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' )
def lowerCamelCase__ ( __snake_case, __snake_case ) -> List[str]:
"""simple docstring"""
_UpperCamelCase = []
_UpperCamelCase = fairseq_model.state_dict()
_UpperCamelCase = hf_model.feature_extractor
# if encoder has different dim to decoder -> use proj_weight
_UpperCamelCase = None
for name, value in fairseq_dict.items():
_UpperCamelCase = False
if "conv_layers" in name:
load_conv_layer(
__snake_case, __snake_case, __snake_case, __snake_case, hf_model.config.feat_extract_norm == '''group''', )
_UpperCamelCase = True
elif name.split('''.''' )[0] == "proj":
_UpperCamelCase = fairseq_model.proj
_UpperCamelCase = True
else:
for key, mapped_key in MAPPING.items():
if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]:
_UpperCamelCase = True
if "*" in mapped_key:
_UpperCamelCase = name.split(__snake_case )[0].split('''.''' )[-2]
_UpperCamelCase = mapped_key.replace('''*''', __snake_case )
if "weight_g" in name:
_UpperCamelCase = '''weight_g'''
elif "weight_v" in name:
_UpperCamelCase = '''weight_v'''
elif "bias" in name:
_UpperCamelCase = '''bias'''
elif "weight" in name:
_UpperCamelCase = '''weight'''
else:
_UpperCamelCase = None
set_recursively(__snake_case, __snake_case, __snake_case, __snake_case, __snake_case )
continue
if not is_used:
unused_weights.append(__snake_case )
logger.warning(F'''Unused weights: {unused_weights}''' )
return proj_weight
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case, __snake_case, __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = full_name.split('''conv_layers.''' )[-1]
_UpperCamelCase = name.split('''.''' )
_UpperCamelCase = int(items[0] )
_UpperCamelCase = int(items[1] )
if type_id == 0:
if "bias" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.'''
)
_UpperCamelCase = value
logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' )
elif "weight" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.'''
)
_UpperCamelCase = value
logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' )
elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
if "bias" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
F'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was'''
" found."
)
_UpperCamelCase = value
logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' )
elif "weight" in name:
assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
F'''{full_name} has size {value.shape}, but'''
F''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.'''
)
_UpperCamelCase = value
logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' )
else:
unused_weights.append(__snake_case )
def lowerCamelCase__ ( __snake_case ) -> Any:
"""simple docstring"""
_UpperCamelCase , _UpperCamelCase = emb.weight.shape
_UpperCamelCase = nn.Linear(__snake_case, __snake_case, bias=__snake_case )
_UpperCamelCase = emb.weight.data
return lin_layer
def lowerCamelCase__ ( __snake_case ) -> str:
"""simple docstring"""
with open(__snake_case, '''r''', encoding='''utf-8''' ) as f:
_UpperCamelCase = f.readlines()
_UpperCamelCase = [line.split(''' ''' )[0] for line in lines]
_UpperCamelCase = len(__snake_case )
_UpperCamelCase = {
'''<s>''': 0,
'''<pad>''': 1,
'''</s>''': 2,
'''<unk>''': 3,
}
vocab_dict.update(dict(zip(__snake_case, range(4, num_words + 4 ) ) ) )
return vocab_dict
@torch.no_grad()
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case, __snake_case, __snake_case, __snake_case, __snake_case, ) -> List[Any]:
"""simple docstring"""
_UpperCamelCase = WavaVecaConfig.from_pretrained(__snake_case )
_UpperCamelCase = SpeechaTextaConfig.from_pretrained(
__snake_case, vocab_size=__snake_case, decoder_layers=__snake_case, do_stable_layer_norm=__snake_case )
_UpperCamelCase = WavaVecaFeatureExtractor(
feature_size=1, sampling_rate=1_60_00, padding_value=0, do_normalize=__snake_case, return_attention_mask=__snake_case, )
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = fairseq.checkpoint_utils.load_model_ensemble_and_task(
[checkpoint_path], arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} )
_UpperCamelCase = model[0].eval()
# set weights for wav2vec2 encoder
_UpperCamelCase = WavaVecaModel(__snake_case )
_UpperCamelCase = recursively_load_weights_wavaveca(model.encoder, __snake_case )
_UpperCamelCase = SpeechaTextaForCausalLM(__snake_case )
_UpperCamelCase , _UpperCamelCase = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict(), strict=__snake_case )
# set output linear layer
unexpected_keys.remove('''embed_out''' )
_UpperCamelCase = nn.Parameter(model.decoder.embed_out.detach() )
# layer norm is init to identity matrix so leaving it is fine
logger.warning(F'''The following keys are missing when loading the decoder weights: {missing_keys}''' )
logger.warning(F'''The following keys are unexpected when loading the decoder weights: {unexpected_keys}''' )
_UpperCamelCase = SpeechEncoderDecoderModel(encoder=__snake_case, decoder=__snake_case )
_UpperCamelCase = False
# add projection layer
_UpperCamelCase = nn.Parameter(projection_layer.weight )
_UpperCamelCase = nn.Parameter(projection_layer.bias )
_UpperCamelCase = create_vocab_dict(__snake_case )
with open(os.path.join(__snake_case, '''vocab.json''' ), '''w''' ) as fp:
json.dump(__snake_case, __snake_case )
_UpperCamelCase = SpeechaTextaTokenizer(os.path.join(__snake_case, '''vocab.json''' ) )
tokenizer.save_pretrained(__snake_case )
_UpperCamelCase = hf_wavavec.config.to_dict()
_UpperCamelCase = tokenizer.pad_token_id
_UpperCamelCase = tokenizer.bos_token_id
_UpperCamelCase = tokenizer.eos_token_id
_UpperCamelCase = '''speech_to_text_2'''
_UpperCamelCase = '''wav2vec2'''
_UpperCamelCase = SpeechEncoderDecoderConfig.from_dict(__snake_case )
hf_wavavec.save_pretrained(__snake_case )
feature_extractor.save_pretrained(__snake_case )
if __name__ == "__main__":
_a = 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(
"""--encoder_config_path""",
default="""facebook/wav2vec2-large-lv60""",
type=str,
help="""Path to hf encoder wav2vec2 checkpoint config""",
)
parser.add_argument(
"""--decoder_config_path""",
default="""facebook/s2t-small-mustc-en-fr-st""",
type=str,
help="""Path to hf decoder s2t checkpoint config""",
)
parser.add_argument("""--vocab_size""", default=1_0224, type=int, help="""Vocab size of decoder""")
parser.add_argument("""--num_decoder_layers""", default=7, type=int, help="""Number of decoder layers""")
_a = parser.parse_args()
convert_wavaveca_checkpoint(
args.checkpoint_path,
args.pytorch_dump_folder_path,
args.dict_path,
encoder_config_path=args.encoder_config_path,
decoder_config_path=args.decoder_config_path,
vocab_size=args.vocab_size,
num_decoder_layers=args.num_decoder_layers,
)
| 716 |
"""simple docstring"""
import warnings
from typing import List
import numpy as np
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import is_flax_available, is_tf_available, is_torch_available
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = ['image_processor', 'tokenizer']
lowercase__ = 'OwlViTImageProcessor'
lowercase__ = ('CLIPTokenizer', 'CLIPTokenizerFast')
def __init__( self , __a=None , __a=None , **__a) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = None
if "feature_extractor" in kwargs:
warnings.warn(
'''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
''' instead.''' , __a , )
_UpperCamelCase = kwargs.pop('''feature_extractor''')
_UpperCamelCase = image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError('''You need to specify an `image_processor`.''')
if tokenizer is None:
raise ValueError('''You need to specify a `tokenizer`.''')
super().__init__(__a , __a)
def __call__( self , __a=None , __a=None , __a=None , __a="max_length" , __a="np" , **__a) -> List[str]:
'''simple docstring'''
if text is None and query_images is None and images is None:
raise ValueError(
'''You have to specify at least one text or query image or image. All three cannot be none.''')
if text is not None:
if isinstance(__a , __a) or (isinstance(__a , __a) and not isinstance(text[0] , __a)):
_UpperCamelCase = [self.tokenizer(__a , padding=__a , return_tensors=__a , **__a)]
elif isinstance(__a , __a) and isinstance(text[0] , __a):
_UpperCamelCase = []
# Maximum number of queries across batch
_UpperCamelCase = max([len(__a) for t in text])
# Pad all batch samples to max number of text queries
for t in text:
if len(__a) != max_num_queries:
_UpperCamelCase = t + [''' '''] * (max_num_queries - len(__a))
_UpperCamelCase = self.tokenizer(__a , padding=__a , return_tensors=__a , **__a)
encodings.append(__a)
else:
raise TypeError('''Input text should be a string, a list of strings or a nested list of strings''')
if return_tensors == "np":
_UpperCamelCase = np.concatenate([encoding['''input_ids'''] for encoding in encodings] , axis=0)
_UpperCamelCase = np.concatenate([encoding['''attention_mask'''] for encoding in encodings] , axis=0)
elif return_tensors == "jax" and is_flax_available():
import jax.numpy as jnp
_UpperCamelCase = jnp.concatenate([encoding['''input_ids'''] for encoding in encodings] , axis=0)
_UpperCamelCase = jnp.concatenate([encoding['''attention_mask'''] for encoding in encodings] , axis=0)
elif return_tensors == "pt" and is_torch_available():
import torch
_UpperCamelCase = torch.cat([encoding['''input_ids'''] for encoding in encodings] , dim=0)
_UpperCamelCase = torch.cat([encoding['''attention_mask'''] for encoding in encodings] , dim=0)
elif return_tensors == "tf" and is_tf_available():
import tensorflow as tf
_UpperCamelCase = tf.stack([encoding['''input_ids'''] for encoding in encodings] , axis=0)
_UpperCamelCase = tf.stack([encoding['''attention_mask'''] for encoding in encodings] , axis=0)
else:
raise ValueError('''Target return tensor type could not be returned''')
_UpperCamelCase = BatchEncoding()
_UpperCamelCase = input_ids
_UpperCamelCase = attention_mask
if query_images is not None:
_UpperCamelCase = BatchEncoding()
_UpperCamelCase = self.image_processor(
__a , return_tensors=__a , **__a).pixel_values
_UpperCamelCase = query_pixel_values
if images is not None:
_UpperCamelCase = self.image_processor(__a , return_tensors=__a , **__a)
if text is not None and images is not None:
_UpperCamelCase = image_features.pixel_values
return encoding
elif query_images is not None and images is not None:
_UpperCamelCase = image_features.pixel_values
return encoding
elif text is not None or query_images is not None:
return encoding
else:
return BatchEncoding(data=dict(**__a) , tensor_type=__a)
def UpperCAmelCase ( self , *__a , **__a) -> str:
'''simple docstring'''
return self.image_processor.post_process(*__a , **__a)
def UpperCAmelCase ( self , *__a , **__a) -> Dict:
'''simple docstring'''
return self.image_processor.post_process_object_detection(*__a , **__a)
def UpperCAmelCase ( self , *__a , **__a) -> Optional[Any]:
'''simple docstring'''
return self.image_processor.post_process_image_guided_detection(*__a , **__a)
def UpperCAmelCase ( self , *__a , **__a) -> Optional[int]:
'''simple docstring'''
return self.tokenizer.batch_decode(*__a , **__a)
def UpperCAmelCase ( self , *__a , **__a) -> Optional[Any]:
'''simple docstring'''
return self.tokenizer.decode(*__a , **__a)
@property
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
warnings.warn(
'''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , __a , )
return self.image_processor_class
@property
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
warnings.warn(
'''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , __a , )
return self.image_processor
| 78 | 0 |
"""simple docstring"""
import requests
def lowerCamelCase__ ( __snake_case, __snake_case ):
"""simple docstring"""
_UpperCamelCase = {'''Content-Type''': '''application/json'''}
_UpperCamelCase = requests.post(__snake_case, json={'''text''': message_body}, headers=__snake_case )
if response.status_code != 2_00:
_UpperCamelCase = (
'''Request to slack returned an error '''
F'''{response.status_code}, the response is:\n{response.text}'''
)
raise ValueError(__snake_case )
if __name__ == "__main__":
# Set the slack url to the one provided by Slack when you create the webhook at
# https://my.slack.com/services/new/incoming-webhook/
send_slack_message("""<YOUR MESSAGE BODY>""", """<SLACK CHANNEL URL>""")
| 717 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tokenizers_available,
is_torch_available,
is_vision_available,
)
_a = {
"""configuration_perceiver""": ["""PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """PerceiverConfig""", """PerceiverOnnxConfig"""],
"""tokenization_perceiver""": ["""PerceiverTokenizer"""],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_a = ["""PerceiverFeatureExtractor"""]
_a = ["""PerceiverImageProcessor"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_a = [
"""PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""PerceiverForImageClassificationConvProcessing""",
"""PerceiverForImageClassificationFourier""",
"""PerceiverForImageClassificationLearned""",
"""PerceiverForMaskedLM""",
"""PerceiverForMultimodalAutoencoding""",
"""PerceiverForOpticalFlow""",
"""PerceiverForSequenceClassification""",
"""PerceiverLayer""",
"""PerceiverModel""",
"""PerceiverPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_perceiver import PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP, PerceiverConfig, PerceiverOnnxConfig
from .tokenization_perceiver import PerceiverTokenizer
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_perceiver import PerceiverFeatureExtractor
from .image_processing_perceiver import PerceiverImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_perceiver import (
PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST,
PerceiverForImageClassificationConvProcessing,
PerceiverForImageClassificationFourier,
PerceiverForImageClassificationLearned,
PerceiverForMaskedLM,
PerceiverForMultimodalAutoencoding,
PerceiverForOpticalFlow,
PerceiverForSequenceClassification,
PerceiverLayer,
PerceiverModel,
PerceiverPreTrainedModel,
)
else:
import sys
_a = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 78 | 0 |
"""simple docstring"""
import argparse
import os.path as osp
import re
import torch
from safetensors.torch import load_file, save_file
# =================#
# UNet Conversion #
# =================#
_a = [
# (stable-diffusion, HF Diffusers)
("""time_embed.0.weight""", """time_embedding.linear_1.weight"""),
("""time_embed.0.bias""", """time_embedding.linear_1.bias"""),
("""time_embed.2.weight""", """time_embedding.linear_2.weight"""),
("""time_embed.2.bias""", """time_embedding.linear_2.bias"""),
("""input_blocks.0.0.weight""", """conv_in.weight"""),
("""input_blocks.0.0.bias""", """conv_in.bias"""),
("""out.0.weight""", """conv_norm_out.weight"""),
("""out.0.bias""", """conv_norm_out.bias"""),
("""out.2.weight""", """conv_out.weight"""),
("""out.2.bias""", """conv_out.bias"""),
]
_a = [
# (stable-diffusion, HF Diffusers)
("""in_layers.0""", """norm1"""),
("""in_layers.2""", """conv1"""),
("""out_layers.0""", """norm2"""),
("""out_layers.3""", """conv2"""),
("""emb_layers.1""", """time_emb_proj"""),
("""skip_connection""", """conv_shortcut"""),
]
_a = []
# hardcoded number of downblocks and resnets/attentions...
# would need smarter logic for other networks.
for i in range(4):
# loop over downblocks/upblocks
for j in range(2):
# loop over resnets/attentions for downblocks
_a = F"""down_blocks.{i}.resnets.{j}."""
_a = F"""input_blocks.{3*i + j + 1}.0."""
unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix))
if i < 3:
# no attention layers in down_blocks.3
_a = F"""down_blocks.{i}.attentions.{j}."""
_a = F"""input_blocks.{3*i + j + 1}.1."""
unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix))
for j in range(3):
# loop over resnets/attentions for upblocks
_a = F"""up_blocks.{i}.resnets.{j}."""
_a = F"""output_blocks.{3*i + j}.0."""
unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix))
if i > 0:
# no attention layers in up_blocks.0
_a = F"""up_blocks.{i}.attentions.{j}."""
_a = F"""output_blocks.{3*i + j}.1."""
unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix))
if i < 3:
# no downsample in down_blocks.3
_a = F"""down_blocks.{i}.downsamplers.0.conv."""
_a = F"""input_blocks.{3*(i+1)}.0.op."""
unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix))
# no upsample in up_blocks.3
_a = F"""up_blocks.{i}.upsamplers.0."""
_a = F"""output_blocks.{3*i + 2}.{1 if i == 0 else 2}."""
unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix))
_a = """mid_block.attentions.0."""
_a = """middle_block.1."""
unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix))
for j in range(2):
_a = F"""mid_block.resnets.{j}."""
_a = F"""middle_block.{2*j}."""
unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix))
def lowerCamelCase__ ( __snake_case ) -> str:
"""simple docstring"""
_UpperCamelCase = {k: k for k in unet_state_dict.keys()}
for sd_name, hf_name in unet_conversion_map:
_UpperCamelCase = sd_name
for k, v in mapping.items():
if "resnets" in k:
for sd_part, hf_part in unet_conversion_map_resnet:
_UpperCamelCase = v.replace(__snake_case, __snake_case )
_UpperCamelCase = v
for k, v in mapping.items():
for sd_part, hf_part in unet_conversion_map_layer:
_UpperCamelCase = v.replace(__snake_case, __snake_case )
_UpperCamelCase = v
_UpperCamelCase = {v: unet_state_dict[k] for k, v in mapping.items()}
return new_state_dict
# ================#
# VAE Conversion #
# ================#
_a = [
# (stable-diffusion, HF Diffusers)
("""nin_shortcut""", """conv_shortcut"""),
("""norm_out""", """conv_norm_out"""),
("""mid.attn_1.""", """mid_block.attentions.0."""),
]
for i in range(4):
# down_blocks have two resnets
for j in range(2):
_a = F"""encoder.down_blocks.{i}.resnets.{j}."""
_a = F"""encoder.down.{i}.block.{j}."""
vae_conversion_map.append((sd_down_prefix, hf_down_prefix))
if i < 3:
_a = F"""down_blocks.{i}.downsamplers.0."""
_a = F"""down.{i}.downsample."""
vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix))
_a = F"""up_blocks.{i}.upsamplers.0."""
_a = F"""up.{3-i}.upsample."""
vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix))
# up_blocks have three resnets
# also, up blocks in hf are numbered in reverse from sd
for j in range(3):
_a = F"""decoder.up_blocks.{i}.resnets.{j}."""
_a = F"""decoder.up.{3-i}.block.{j}."""
vae_conversion_map.append((sd_up_prefix, hf_up_prefix))
# this part accounts for mid blocks in both the encoder and the decoder
for i in range(2):
_a = F"""mid_block.resnets.{i}."""
_a = F"""mid.block_{i+1}."""
vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix))
_a = [
# (stable-diffusion, HF Diffusers)
("""norm.""", """group_norm."""),
("""q.""", """query."""),
("""k.""", """key."""),
("""v.""", """value."""),
("""proj_out.""", """proj_attn."""),
]
def lowerCamelCase__ ( __snake_case ) -> List[str]:
"""simple docstring"""
return w.reshape(*w.shape, 1, 1 )
def lowerCamelCase__ ( __snake_case ) -> Optional[Any]:
"""simple docstring"""
_UpperCamelCase = {k: k for k in vae_state_dict.keys()}
for k, v in mapping.items():
for sd_part, hf_part in vae_conversion_map:
_UpperCamelCase = v.replace(__snake_case, __snake_case )
_UpperCamelCase = v
for k, v in mapping.items():
if "attentions" in k:
for sd_part, hf_part in vae_conversion_map_attn:
_UpperCamelCase = v.replace(__snake_case, __snake_case )
_UpperCamelCase = v
_UpperCamelCase = {v: vae_state_dict[k] for k, v in mapping.items()}
_UpperCamelCase = ['''q''', '''k''', '''v''', '''proj_out''']
for k, v in new_state_dict.items():
for weight_name in weights_to_convert:
if F'''mid.attn_1.{weight_name}.weight''' in k:
print(F'''Reshaping {k} for SD format''' )
_UpperCamelCase = reshape_weight_for_sd(__snake_case )
return new_state_dict
# =========================#
# Text Encoder Conversion #
# =========================#
_a = [
# (stable-diffusion, HF Diffusers)
("""resblocks.""", """text_model.encoder.layers."""),
("""ln_1""", """layer_norm1"""),
("""ln_2""", """layer_norm2"""),
(""".c_fc.""", """.fc1."""),
(""".c_proj.""", """.fc2."""),
(""".attn""", """.self_attn"""),
("""ln_final.""", """transformer.text_model.final_layer_norm."""),
("""token_embedding.weight""", """transformer.text_model.embeddings.token_embedding.weight"""),
("""positional_embedding""", """transformer.text_model.embeddings.position_embedding.weight"""),
]
_a = {re.escape(x[1]): x[0] for x in textenc_conversion_lst}
_a = re.compile("""|""".join(protected.keys()))
# Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp
_a = {"""q""": 0, """k""": 1, """v""": 2}
def lowerCamelCase__ ( __snake_case ) -> Any:
"""simple docstring"""
_UpperCamelCase = {}
_UpperCamelCase = {}
_UpperCamelCase = {}
for k, v in text_enc_dict.items():
if (
k.endswith('''.self_attn.q_proj.weight''' )
or k.endswith('''.self_attn.k_proj.weight''' )
or k.endswith('''.self_attn.v_proj.weight''' )
):
_UpperCamelCase = k[: -len('''.q_proj.weight''' )]
_UpperCamelCase = k[-len('''q_proj.weight''' )]
if k_pre not in capture_qkv_weight:
_UpperCamelCase = [None, None, None]
_UpperCamelCase = v
continue
if (
k.endswith('''.self_attn.q_proj.bias''' )
or k.endswith('''.self_attn.k_proj.bias''' )
or k.endswith('''.self_attn.v_proj.bias''' )
):
_UpperCamelCase = k[: -len('''.q_proj.bias''' )]
_UpperCamelCase = k[-len('''q_proj.bias''' )]
if k_pre not in capture_qkv_bias:
_UpperCamelCase = [None, None, None]
_UpperCamelCase = v
continue
_UpperCamelCase = textenc_pattern.sub(lambda __snake_case : protected[re.escape(m.group(0 ) )], __snake_case )
_UpperCamelCase = v
for k_pre, tensors in capture_qkv_weight.items():
if None in tensors:
raise Exception('''CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing''' )
_UpperCamelCase = textenc_pattern.sub(lambda __snake_case : protected[re.escape(m.group(0 ) )], __snake_case )
_UpperCamelCase = torch.cat(__snake_case )
for k_pre, tensors in capture_qkv_bias.items():
if None in tensors:
raise Exception('''CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing''' )
_UpperCamelCase = textenc_pattern.sub(lambda __snake_case : protected[re.escape(m.group(0 ) )], __snake_case )
_UpperCamelCase = torch.cat(__snake_case )
return new_state_dict
def lowerCamelCase__ ( __snake_case ) -> Tuple:
"""simple docstring"""
return text_enc_dict
if __name__ == "__main__":
_a = argparse.ArgumentParser()
parser.add_argument("""--model_path""", default=None, type=str, required=True, help="""Path to the model to convert.""")
parser.add_argument("""--checkpoint_path""", default=None, type=str, required=True, help="""Path to the output model.""")
parser.add_argument("""--half""", action="""store_true""", help="""Save weights in half precision.""")
parser.add_argument(
"""--use_safetensors""", action="""store_true""", help="""Save weights use safetensors, default is ckpt."""
)
_a = parser.parse_args()
assert args.model_path is not None, "Must provide a model path!"
assert args.checkpoint_path is not None, "Must provide a checkpoint path!"
# Path for safetensors
_a = osp.join(args.model_path, """unet""", """diffusion_pytorch_model.safetensors""")
_a = osp.join(args.model_path, """vae""", """diffusion_pytorch_model.safetensors""")
_a = osp.join(args.model_path, """text_encoder""", """model.safetensors""")
# Load models from safetensors if it exists, if it doesn't pytorch
if osp.exists(unet_path):
_a = load_file(unet_path, device="""cpu""")
else:
_a = osp.join(args.model_path, """unet""", """diffusion_pytorch_model.bin""")
_a = torch.load(unet_path, map_location="""cpu""")
if osp.exists(vae_path):
_a = load_file(vae_path, device="""cpu""")
else:
_a = osp.join(args.model_path, """vae""", """diffusion_pytorch_model.bin""")
_a = torch.load(vae_path, map_location="""cpu""")
if osp.exists(text_enc_path):
_a = load_file(text_enc_path, device="""cpu""")
else:
_a = osp.join(args.model_path, """text_encoder""", """pytorch_model.bin""")
_a = torch.load(text_enc_path, map_location="""cpu""")
# Convert the UNet model
_a = convert_unet_state_dict(unet_state_dict)
_a = {"""model.diffusion_model.""" + k: v for k, v in unet_state_dict.items()}
# Convert the VAE model
_a = convert_vae_state_dict(vae_state_dict)
_a = {"""first_stage_model.""" + k: v for k, v in vae_state_dict.items()}
# Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper
_a = """text_model.encoder.layers.22.layer_norm2.bias""" in text_enc_dict
if is_vaa_model:
# Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm
_a = {"""transformer.""" + k: v for k, v in text_enc_dict.items()}
_a = convert_text_enc_state_dict_vaa(text_enc_dict)
_a = {"""cond_stage_model.model.""" + k: v for k, v in text_enc_dict.items()}
else:
_a = convert_text_enc_state_dict(text_enc_dict)
_a = {"""cond_stage_model.transformer.""" + k: v for k, v in text_enc_dict.items()}
# Put together new checkpoint
_a = {**unet_state_dict, **vae_state_dict, **text_enc_dict}
if args.half:
_a = {k: v.half() for k, v in state_dict.items()}
if args.use_safetensors:
save_file(state_dict, args.checkpoint_path)
else:
_a = {"""state_dict""": state_dict}
torch.save(state_dict, args.checkpoint_path)
| 718 |
"""simple docstring"""
import inspect
import unittest
from huggingface_hub import hf_hub_download
from transformers import ASTConfig
from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_torchaudio_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import ASTForAudioClassification, ASTModel
from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import (
AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
)
if is_torchaudio_available():
import torchaudio
from transformers import ASTFeatureExtractor
class _UpperCAmelCase:
def __init__( self , __a , __a=13 , __a=2 , __a=24 , __a=16 , __a=True , __a=True , __a=32 , __a=5 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=10 , __a=0.02 , __a=None , __a=2 , __a=2 , ) -> List[str]:
'''simple docstring'''
_UpperCamelCase = parent
_UpperCamelCase = batch_size
_UpperCamelCase = patch_size
_UpperCamelCase = max_length
_UpperCamelCase = num_mel_bins
_UpperCamelCase = is_training
_UpperCamelCase = use_labels
_UpperCamelCase = hidden_size
_UpperCamelCase = num_hidden_layers
_UpperCamelCase = num_attention_heads
_UpperCamelCase = intermediate_size
_UpperCamelCase = hidden_act
_UpperCamelCase = hidden_dropout_prob
_UpperCamelCase = attention_probs_dropout_prob
_UpperCamelCase = type_sequence_label_size
_UpperCamelCase = initializer_range
_UpperCamelCase = scope
_UpperCamelCase = frequency_stride
_UpperCamelCase = time_stride
# in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
_UpperCamelCase = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1
_UpperCamelCase = (self.max_length - self.patch_size) // self.time_stride + 1
_UpperCamelCase = frequency_out_dimension * time_out_dimension
_UpperCamelCase = num_patches + 2
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins])
_UpperCamelCase = None
if self.use_labels:
_UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size)
_UpperCamelCase = self.get_config()
return config, input_values, labels
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
return ASTConfig(
patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__a , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , )
def UpperCAmelCase ( self , __a , __a , __a) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = ASTModel(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a)
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.prepare_config_and_inputs()
(
(
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) ,
) = config_and_inputs
_UpperCamelCase = {'''input_values''': input_values}
return config, inputs_dict
@require_torch
class _UpperCAmelCase( lowerCamelCase , lowerCamelCase , unittest.TestCase ):
lowercase__ = (
(
ASTModel,
ASTForAudioClassification,
)
if is_torch_available()
else ()
)
lowercase__ = (
{'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel}
if is_torch_available()
else {}
)
lowercase__ = False
lowercase__ = False
lowercase__ = False
lowercase__ = False
def UpperCAmelCase ( self , __a , __a , __a , __a , __a) -> Optional[Any]:
'''simple docstring'''
if pipeline_test_casse_name == "AudioClassificationPipelineTests":
return True
return False
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
_UpperCamelCase = ASTModelTester(self)
_UpperCamelCase = ConfigTester(self , config_class=__a , has_text_modality=__a , hidden_size=37)
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
self.config_tester.run_common_tests()
@unittest.skip(reason='''AST does not use inputs_embeds''')
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
pass
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_UpperCamelCase = model_class(__a)
self.assertIsInstance(model.get_input_embeddings() , (nn.Module))
_UpperCamelCase = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(__a , nn.Linear))
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_UpperCamelCase = model_class(__a)
_UpperCamelCase = inspect.signature(model.forward)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
_UpperCamelCase = [*signature.parameters.keys()]
_UpperCamelCase = ['''input_values''']
self.assertListEqual(arg_names[:1] , __a)
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__a)
@slow
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_UpperCamelCase = ASTModel.from_pretrained(__a)
self.assertIsNotNone(__a)
def lowerCamelCase__ ( ) -> List[str]:
"""simple docstring"""
_UpperCamelCase = hf_hub_download(
repo_id='''nielsr/audio-spectogram-transformer-checkpoint''', filename='''sample_audio.flac''', repo_type='''dataset''' )
_UpperCamelCase , _UpperCamelCase = torchaudio.load(__snake_case )
return audio, sampling_rate
@require_torch
@require_torchaudio
class _UpperCAmelCase( unittest.TestCase ):
@cached_property
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
return (
ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''')
if is_torchaudio_available()
else None
)
@slow
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.default_feature_extractor
_UpperCamelCase = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''').to(__a)
_UpperCamelCase = self.default_feature_extractor
_UpperCamelCase , _UpperCamelCase = prepare_audio()
_UpperCamelCase = audio.squeeze().numpy()
_UpperCamelCase = feature_extractor(__a , sampling_rate=__a , return_tensors='''pt''').to(__a)
# forward pass
with torch.no_grad():
_UpperCamelCase = model(**__a)
# verify the logits
_UpperCamelCase = torch.Size((1, 5_27))
self.assertEqual(outputs.logits.shape , __a)
_UpperCamelCase = torch.tensor([-0.8760, -7.0042, -8.6602]).to(__a)
self.assertTrue(torch.allclose(outputs.logits[0, :3] , __a , atol=1e-4))
| 78 | 0 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available
_a = {}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_a = ["""BartphoTokenizer"""]
if TYPE_CHECKING:
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_bartpho import BartphoTokenizer
else:
import sys
_a = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 719 |
"""simple docstring"""
def lowerCamelCase__ ( ) -> list[list[int]]:
"""simple docstring"""
return [list(range(10_00 - i, -10_00 - i, -1 ) ) for i in range(10_00 )]
_a = generate_large_matrix()
_a = (
[[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]],
[[3, 2], [1, 0]],
[[7, 7, 6]],
[[7, 7, 6], [-1, -2, -3]],
grid,
)
def lowerCamelCase__ ( __snake_case ) -> None:
"""simple docstring"""
assert all(row == sorted(__snake_case, reverse=__snake_case ) for row in grid )
assert all(list(__snake_case ) == sorted(__snake_case, reverse=__snake_case ) for col in zip(*__snake_case ) )
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = 0
_UpperCamelCase = len(__snake_case ) - 1
# Edge cases such as no values or all numbers are negative.
if not array or array[0] < 0:
return 0
while right + 1 > left:
_UpperCamelCase = (left + right) // 2
_UpperCamelCase = array[mid]
# Num must be negative and the index must be greater than or equal to 0.
if num < 0 and array[mid - 1] >= 0:
return mid
if num >= 0:
_UpperCamelCase = mid + 1
else:
_UpperCamelCase = mid - 1
# No negative numbers so return the last index of the array + 1 which is the length.
return len(__snake_case )
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = 0
_UpperCamelCase = len(grid[0] )
for i in range(len(__snake_case ) ):
_UpperCamelCase = find_negative_index(grid[i][:bound] )
total += bound
return (len(__snake_case ) * len(grid[0] )) - total
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
return len([number for row in grid for number in row if number < 0] )
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = 0
for row in grid:
for i, number in enumerate(__snake_case ):
if number < 0:
total += len(__snake_case ) - i
break
return total
def lowerCamelCase__ ( ) -> None:
"""simple docstring"""
from timeit import timeit
print('''Running benchmarks''' )
_UpperCamelCase = (
'''from __main__ import count_negatives_binary_search, '''
'''count_negatives_brute_force, count_negatives_brute_force_with_break, grid'''
)
for func in (
"count_negatives_binary_search", # took 0.7727 seconds
"count_negatives_brute_force_with_break", # took 4.6505 seconds
"count_negatives_brute_force", # took 12.8160 seconds
):
_UpperCamelCase = timeit(F'''{func}(grid=grid)''', setup=__snake_case, number=5_00 )
print(F'''{func}() took {time:0.4f} seconds''' )
if __name__ == "__main__":
import doctest
doctest.testmod()
benchmark()
| 78 | 0 |
"""simple docstring"""
import argparse
import torch
from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration
from transformers.utils import logging
logging.set_verbosity_info()
_a = logging.get_logger(__name__)
_a = [
["""attention""", """attn"""],
["""encoder_attention""", """encoder_attn"""],
["""q_lin""", """q_proj"""],
["""k_lin""", """k_proj"""],
["""v_lin""", """v_proj"""],
["""out_lin""", """out_proj"""],
["""norm_embeddings""", """layernorm_embedding"""],
["""position_embeddings""", """embed_positions"""],
["""embeddings""", """embed_tokens"""],
["""ffn.lin""", """fc"""],
]
def lowerCamelCase__ ( __snake_case ) -> Optional[Any]:
if k == "embeddings.weight":
return "shared.weight"
for parlai_name, hf_name in PATTERNS:
_UpperCamelCase = k.replace(__snake_case, __snake_case )
if k.startswith('''encoder''' ):
_UpperCamelCase = k.replace('''.attn''', '''.self_attn''' )
_UpperCamelCase = k.replace('''norm1''', '''self_attn_layer_norm''' )
_UpperCamelCase = k.replace('''norm2''', '''final_layer_norm''' )
elif k.startswith('''decoder''' ):
_UpperCamelCase = k.replace('''norm1''', '''self_attn_layer_norm''' )
_UpperCamelCase = k.replace('''norm2''', '''encoder_attn_layer_norm''' )
_UpperCamelCase = k.replace('''norm3''', '''final_layer_norm''' )
return k
def lowerCamelCase__ ( __snake_case ) -> Optional[int]:
_UpperCamelCase = [
'''model.encoder.layernorm_embedding.weight''',
'''model.encoder.layernorm_embedding.bias''',
'''model.decoder.layernorm_embedding.weight''',
'''model.decoder.layernorm_embedding.bias''',
]
for k in keys:
_UpperCamelCase = sd.pop(__snake_case )
_UpperCamelCase = k.replace('''layernorm_embedding''', '''layer_norm''' )
assert new_k not in sd
_UpperCamelCase = v
_a = ["""START"""]
@torch.no_grad()
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> int:
_UpperCamelCase = torch.load(__snake_case, map_location='''cpu''' )
_UpperCamelCase = model['''model''']
_UpperCamelCase = BlenderbotConfig.from_json_file(__snake_case )
_UpperCamelCase = BlenderbotForConditionalGeneration(__snake_case )
_UpperCamelCase = m.model.state_dict().keys()
_UpperCamelCase = []
_UpperCamelCase = {}
for k, v in sd.items():
if k in IGNORE_KEYS:
continue
_UpperCamelCase = rename_state_dict_key(__snake_case )
if new_k not in valid_keys:
failures.append([k, new_k] )
else:
_UpperCamelCase = v
if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm
rename_layernorm_keys(__snake_case )
m.model.load_state_dict(__snake_case, strict=__snake_case )
m.half()
m.save_pretrained(__snake_case )
if __name__ == "__main__":
_a = argparse.ArgumentParser()
# Required parameters
parser.add_argument("""--src_path""", type=str, help="""like blenderbot-model.bin""")
parser.add_argument("""--save_dir""", default="""hf_blenderbot""", type=str, help="""Where to save converted model.""")
parser.add_argument(
"""--hf_config_json""", default="""blenderbot-3b-config.json""", type=str, help="""Path to config to use"""
)
_a = parser.parse_args()
convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
| 720 |
"""simple docstring"""
import copy
import re
class _UpperCAmelCase:
lowercase__ = 'hp'
lowercase__ = {}
lowercase__ = None
@classmethod
def UpperCAmelCase ( cls , __a , __a) -> Dict:
'''simple docstring'''
_UpperCamelCase = prefix
_UpperCamelCase = defaults
cls.build_naming_info()
@staticmethod
def UpperCAmelCase ( __a , __a) -> Union[str, Any]:
'''simple docstring'''
if len(__a) == 0:
return ""
_UpperCamelCase = None
if any(char.isdigit() for char in word):
raise Exception(F'''Parameters should not contain numbers: \'{word}\' contains a number''')
if word in info["short_word"]:
return info["short_word"][word]
for prefix_len in range(1 , len(__a) + 1):
_UpperCamelCase = word[:prefix_len]
if prefix in info["reverse_short_word"]:
continue
else:
_UpperCamelCase = prefix
break
if short_word is None:
# Paranoid fallback
def int_to_alphabetic(__a):
_UpperCamelCase = ''''''
while integer != 0:
_UpperCamelCase = chr(ord('''A''') + integer % 10) + s
integer //= 10
return s
_UpperCamelCase = 0
while True:
_UpperCamelCase = word + '''#''' + int_to_alphabetic(__a)
if sword in info["reverse_short_word"]:
continue
else:
_UpperCamelCase = sword
break
_UpperCamelCase = short_word
_UpperCamelCase = word
return short_word
@staticmethod
def UpperCAmelCase ( __a , __a) -> Any:
'''simple docstring'''
_UpperCamelCase = param_name.split('''_''')
_UpperCamelCase = [TrialShortNamer.shortname_for_word(__a , __a) for word in words]
# We try to create a separatorless short name, but if there is a collision we have to fallback
# to a separated short name
_UpperCamelCase = ['''''', '''_''']
for separator in separators:
_UpperCamelCase = separator.join(__a)
if shortname not in info["reverse_short_param"]:
_UpperCamelCase = shortname
_UpperCamelCase = param_name
return shortname
return param_name
@staticmethod
def UpperCAmelCase ( __a , __a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = TrialShortNamer.shortname_for_key(__a , __a)
_UpperCamelCase = short_name
_UpperCamelCase = param_name
@classmethod
def UpperCAmelCase ( cls) -> Any:
'''simple docstring'''
if cls.NAMING_INFO is not None:
return
_UpperCamelCase = {
'''short_word''': {},
'''reverse_short_word''': {},
'''short_param''': {},
'''reverse_short_param''': {},
}
_UpperCamelCase = list(cls.DEFAULTS.keys())
for k in field_keys:
cls.add_new_param_name(__a , __a)
_UpperCamelCase = info
@classmethod
def UpperCAmelCase ( cls , __a) -> Optional[Any]:
'''simple docstring'''
cls.build_naming_info()
assert cls.PREFIX is not None
_UpperCamelCase = [copy.copy(cls.PREFIX)]
for k, v in params.items():
if k not in cls.DEFAULTS:
raise Exception(F'''You should provide a default value for the param name {k} with value {v}''')
if v == cls.DEFAULTS[k]:
# The default value is not added to the name
continue
_UpperCamelCase = cls.NAMING_INFO['''short_param'''][k]
if isinstance(__a , __a):
_UpperCamelCase = 1 if v else 0
_UpperCamelCase = '''''' if isinstance(__a , (int, float)) else '''-'''
_UpperCamelCase = F'''{key}{sep}{v}'''
name.append(__a)
return "_".join(__a)
@classmethod
def UpperCAmelCase ( cls , __a) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = repr[len(cls.PREFIX) + 1 :]
if repr == "":
_UpperCamelCase = []
else:
_UpperCamelCase = repr.split('''_''')
_UpperCamelCase = {}
for value in values:
if "-" in value:
_UpperCamelCase , _UpperCamelCase = value.split('''-''')
else:
_UpperCamelCase = re.sub('''[0-9.]''' , '''''' , __a)
_UpperCamelCase = float(re.sub('''[^0-9.]''' , '''''' , __a))
_UpperCamelCase = cls.NAMING_INFO['''reverse_short_param'''][p_k]
_UpperCamelCase = p_v
for k in cls.DEFAULTS:
if k not in parameters:
_UpperCamelCase = cls.DEFAULTS[k]
return parameters
| 78 | 0 |
"""simple docstring"""
import os
from shutil import copyfile
from typing import List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
_a = logging.get_logger(__name__)
_a = {"""vocab_file""": """sentencepiece.model"""}
_a = {
"""vocab_file""": {
"""google/rembert""": """https://huggingface.co/google/rembert/resolve/main/sentencepiece.model""",
},
}
_a = {
"""google/rembert""": 256,
}
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = VOCAB_FILES_NAMES
lowercase__ = PRETRAINED_VOCAB_FILES_MAP
lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__( self , __a , __a=False , __a=True , __a=True , __a="[CLS]" , __a="[SEP]" , __a="[UNK]" , __a="[SEP]" , __a="[PAD]" , __a="[CLS]" , __a="[MASK]" , **__a , ) -> Optional[int]:
'''simple docstring'''
super().__init__(
do_lower_case=__a , remove_space=__a , keep_accents=__a , bos_token=__a , eos_token=__a , unk_token=__a , sep_token=__a , pad_token=__a , cls_token=__a , mask_token=__a , **__a , )
_UpperCamelCase = do_lower_case
_UpperCamelCase = remove_space
_UpperCamelCase = keep_accents
_UpperCamelCase = vocab_file
_UpperCamelCase = spm.SentencePieceProcessor()
self.sp_model.Load(__a)
@property
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
return len(self.sp_model)
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
_UpperCamelCase = {self.convert_ids_to_tokens(__a): i for i in range(self.vocab_size)}
vocab.update(self.added_tokens_encoder)
return vocab
def __getstate__( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = self.__dict__.copy()
_UpperCamelCase = None
return state
def __setstate__( self , __a) -> str:
'''simple docstring'''
_UpperCamelCase = d
_UpperCamelCase = spm.SentencePieceProcessor()
self.sp_model.Load(self.vocab_file)
def UpperCAmelCase ( self , __a , __a=False) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = self.sp_model.EncodeAsPieces(__a)
return pieces
def UpperCAmelCase ( self , __a) -> Union[str, Any]:
'''simple docstring'''
return self.sp_model.PieceToId(__a)
def UpperCAmelCase ( self , __a) -> Dict:
'''simple docstring'''
return self.sp_model.IdToPiece(__a)
def UpperCAmelCase ( self , __a) -> Tuple:
'''simple docstring'''
_UpperCamelCase = self.sp_model.decode_pieces(__a)
return out_string
def UpperCAmelCase ( self , __a , __a = None) -> List[int]:
'''simple docstring'''
_UpperCamelCase = [self.sep_token_id]
_UpperCamelCase = [self.cls_token_id]
if token_ids_a is None:
return cls + token_ids_a + sep
return cls + token_ids_a + sep + token_ids_a + sep
def UpperCAmelCase ( self , __a , __a = None , __a = False) -> List[int]:
'''simple docstring'''
if already_has_special_tokens:
if token_ids_a is not None:
raise ValueError(
'''You should not supply a second sequence if the provided sequence of '''
'''ids is already formatted with special tokens for the model.''')
return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]
if token_ids_a is not None:
return [1] + ([0] * len(__a)) + [1] + ([0] * len(__a)) + [1]
return [1] + ([0] * len(__a)) + [1]
def UpperCAmelCase ( self , __a , __a = None) -> List[int]:
'''simple docstring'''
_UpperCamelCase = [self.sep_token_id]
_UpperCamelCase = [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) -> Tuple[str]:
'''simple docstring'''
if not os.path.isdir(__a):
logger.error('''Vocabulary path ({}) should be a directory'''.format(__a))
return
_UpperCamelCase = os.path.join(
__a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''])
if os.path.abspath(self.vocab_file) != os.path.abspath(__a):
copyfile(self.vocab_file , __a)
return (out_vocab_file,)
| 721 |
"""simple docstring"""
import os
import time
import pytest
from datasets.utils.filelock import FileLock, Timeout
def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]:
"""simple docstring"""
_UpperCamelCase = FileLock(str(tmpdir / '''foo.lock''' ) )
_UpperCamelCase = FileLock(str(tmpdir / '''foo.lock''' ) )
_UpperCamelCase = 0.01
with locka.acquire():
with pytest.raises(__snake_case ):
_UpperCamelCase = time.time()
locka.acquire(__snake_case )
assert time.time() - _start > timeout
def lowerCamelCase__ ( __snake_case ) -> List[Any]:
"""simple docstring"""
_UpperCamelCase = '''a''' * 10_00 + '''.lock'''
_UpperCamelCase = FileLock(str(tmpdir / filename ) )
assert locka._lock_file.endswith('''.lock''' )
assert not locka._lock_file.endswith(__snake_case )
assert len(os.path.basename(locka._lock_file ) ) <= 2_55
_UpperCamelCase = FileLock(tmpdir / filename )
with locka.acquire():
with pytest.raises(__snake_case ):
locka.acquire(0 )
| 78 | 0 |
"""simple docstring"""
import copy
from collections import OrderedDict
from typing import Dict, Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING
_a = logging.get_logger(__name__)
_a = {
"""facebook/detr-resnet-50""": """https://huggingface.co/facebook/detr-resnet-50/resolve/main/config.json""",
# See all DETR models at https://huggingface.co/models?filter=detr
}
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = 'detr'
lowercase__ = ['past_key_values']
lowercase__ = {
'hidden_size': 'd_model',
'num_attention_heads': 'encoder_attention_heads',
}
def __init__( self , __a=True , __a=None , __a=3 , __a=1_00 , __a=6 , __a=20_48 , __a=8 , __a=6 , __a=20_48 , __a=8 , __a=0.0 , __a=0.0 , __a=True , __a="relu" , __a=2_56 , __a=0.1 , __a=0.0 , __a=0.0 , __a=0.02 , __a=1.0 , __a=False , __a="sine" , __a="resnet50" , __a=True , __a=False , __a=1 , __a=5 , __a=2 , __a=1 , __a=1 , __a=5 , __a=2 , __a=0.1 , **__a , ) -> Union[str, Any]:
'''simple docstring'''
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.''')
_UpperCamelCase = CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''])
elif isinstance(__a , __a):
_UpperCamelCase = backbone_config.get('''model_type''')
_UpperCamelCase = CONFIG_MAPPING[backbone_model_type]
_UpperCamelCase = config_class.from_dict(__a)
# set timm attributes to None
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = None, None, None
_UpperCamelCase = use_timm_backbone
_UpperCamelCase = backbone_config
_UpperCamelCase = num_channels
_UpperCamelCase = num_queries
_UpperCamelCase = d_model
_UpperCamelCase = encoder_ffn_dim
_UpperCamelCase = encoder_layers
_UpperCamelCase = encoder_attention_heads
_UpperCamelCase = decoder_ffn_dim
_UpperCamelCase = decoder_layers
_UpperCamelCase = decoder_attention_heads
_UpperCamelCase = dropout
_UpperCamelCase = attention_dropout
_UpperCamelCase = activation_dropout
_UpperCamelCase = activation_function
_UpperCamelCase = init_std
_UpperCamelCase = init_xavier_std
_UpperCamelCase = encoder_layerdrop
_UpperCamelCase = decoder_layerdrop
_UpperCamelCase = encoder_layers
_UpperCamelCase = auxiliary_loss
_UpperCamelCase = position_embedding_type
_UpperCamelCase = backbone
_UpperCamelCase = use_pretrained_backbone
_UpperCamelCase = dilation
# Hungarian matcher
_UpperCamelCase = class_cost
_UpperCamelCase = bbox_cost
_UpperCamelCase = giou_cost
# Loss coefficients
_UpperCamelCase = mask_loss_coefficient
_UpperCamelCase = dice_loss_coefficient
_UpperCamelCase = bbox_loss_coefficient
_UpperCamelCase = giou_loss_coefficient
_UpperCamelCase = eos_coefficient
super().__init__(is_encoder_decoder=__a , **__a)
@property
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
return self.encoder_attention_heads
@property
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
return self.d_model
@classmethod
def UpperCAmelCase ( cls , __a , **__a) -> List[Any]:
'''simple docstring'''
return cls(backbone_config=__a , **__a)
def UpperCAmelCase ( self) -> Dict[str, any]:
'''simple docstring'''
_UpperCamelCase = copy.deepcopy(self.__dict__)
if output["backbone_config"] is not None:
_UpperCamelCase = self.backbone_config.to_dict()
_UpperCamelCase = self.__class__.model_type
return output
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = version.parse('1.11' )
@property
def UpperCAmelCase ( self) -> Mapping[str, Mapping[int, str]]:
'''simple docstring'''
return OrderedDict(
[
('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
('''pixel_mask''', {0: '''batch'''}),
])
@property
def UpperCAmelCase ( self) -> float:
'''simple docstring'''
return 1e-5
@property
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
return 12
| 700 |
"""simple docstring"""
from math import sqrt
def lowerCamelCase__ ( __snake_case ) -> bool:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (
number >= 0
), "'number' must been an int and positive"
_UpperCamelCase = True
# 0 and 1 are none primes.
if number <= 1:
_UpperCamelCase = False
for divisor in range(2, int(round(sqrt(__snake_case ) ) ) + 1 ):
# if 'number' divisible by 'divisor' then sets 'status'
# of false and break up the loop.
if number % divisor == 0:
_UpperCamelCase = False
break
# precondition
assert isinstance(__snake_case, __snake_case ), "'status' must been from type bool"
return status
def lowerCamelCase__ ( __snake_case ) -> Dict:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n > 2), "'N' must been an int and > 2"
# beginList: contains all natural numbers from 2 up to N
_UpperCamelCase = list(range(2, n + 1 ) )
_UpperCamelCase = [] # this list will be returns.
# actual sieve of erathostenes
for i in range(len(__snake_case ) ):
for j in range(i + 1, len(__snake_case ) ):
if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0):
_UpperCamelCase = 0
# filters actual prime numbers.
_UpperCamelCase = [x for x in begin_list if x != 0]
# precondition
assert isinstance(__snake_case, __snake_case ), "'ans' must been from type list"
return ans
def lowerCamelCase__ ( __snake_case ) -> List[str]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n > 2), "'N' must been an int and > 2"
_UpperCamelCase = []
# iterates over all numbers between 2 up to N+1
# if a number is prime then appends to list 'ans'
for number in range(2, n + 1 ):
if is_prime(__snake_case ):
ans.append(__snake_case )
# precondition
assert isinstance(__snake_case, __snake_case ), "'ans' must been from type list"
return ans
def lowerCamelCase__ ( __snake_case ) -> Optional[int]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and number >= 0, "'number' must been an int and >= 0"
_UpperCamelCase = [] # this list will be returns of the function.
# potential prime number factors.
_UpperCamelCase = 2
_UpperCamelCase = number
if number == 0 or number == 1:
ans.append(__snake_case )
# if 'number' not prime then builds the prime factorization of 'number'
elif not is_prime(__snake_case ):
while quotient != 1:
if is_prime(__snake_case ) and (quotient % factor == 0):
ans.append(__snake_case )
quotient /= factor
else:
factor += 1
else:
ans.append(__snake_case )
# precondition
assert isinstance(__snake_case, __snake_case ), "'ans' must been from type list"
return ans
def lowerCamelCase__ ( __snake_case ) -> Optional[Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (
number >= 0
), "'number' bust been an int and >= 0"
_UpperCamelCase = 0
# prime factorization of 'number'
_UpperCamelCase = prime_factorization(__snake_case )
_UpperCamelCase = max(__snake_case )
# precondition
assert isinstance(__snake_case, __snake_case ), "'ans' must been from type int"
return ans
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (
number >= 0
), "'number' bust been an int and >= 0"
_UpperCamelCase = 0
# prime factorization of 'number'
_UpperCamelCase = prime_factorization(__snake_case )
_UpperCamelCase = min(__snake_case )
# precondition
assert isinstance(__snake_case, __snake_case ), "'ans' must been from type int"
return ans
def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ), "'number' must been an int"
assert isinstance(number % 2 == 0, __snake_case ), "compare bust been from type bool"
return number % 2 == 0
def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ), "'number' must been an int"
assert isinstance(number % 2 != 0, __snake_case ), "compare bust been from type bool"
return number % 2 != 0
def lowerCamelCase__ ( __snake_case ) -> str:
"""simple docstring"""
assert (
isinstance(__snake_case, __snake_case ) and (number > 2) and is_even(__snake_case )
), "'number' must been an int, even and > 2"
_UpperCamelCase = [] # this list will returned
# creates a list of prime numbers between 2 up to 'number'
_UpperCamelCase = get_prime_numbers(__snake_case )
_UpperCamelCase = len(__snake_case )
# run variable for while-loops.
_UpperCamelCase = 0
_UpperCamelCase = None
# exit variable. for break up the loops
_UpperCamelCase = True
while i < len_pn and loop:
_UpperCamelCase = i + 1
while j < len_pn and loop:
if prime_numbers[i] + prime_numbers[j] == number:
_UpperCamelCase = False
ans.append(prime_numbers[i] )
ans.append(prime_numbers[j] )
j += 1
i += 1
# precondition
assert (
isinstance(__snake_case, __snake_case )
and (len(__snake_case ) == 2)
and (ans[0] + ans[1] == number)
and is_prime(ans[0] )
and is_prime(ans[1] )
), "'ans' must contains two primes. And sum of elements must been eq 'number'"
return ans
def lowerCamelCase__ ( __snake_case, __snake_case ) -> str:
"""simple docstring"""
assert (
isinstance(__snake_case, __snake_case )
and isinstance(__snake_case, __snake_case )
and (numbera >= 0)
and (numbera >= 0)
), "'number1' and 'number2' must been positive integer."
_UpperCamelCase = 0
while numbera != 0:
_UpperCamelCase = numbera % numbera
_UpperCamelCase = numbera
_UpperCamelCase = rest
# precondition
assert isinstance(__snake_case, __snake_case ) and (
numbera >= 0
), "'number' must been from type int and positive"
return numbera
def lowerCamelCase__ ( __snake_case, __snake_case ) -> List[str]:
"""simple docstring"""
assert (
isinstance(__snake_case, __snake_case )
and isinstance(__snake_case, __snake_case )
and (numbera >= 1)
and (numbera >= 1)
), "'number1' and 'number2' must been positive integer."
_UpperCamelCase = 1 # actual answer that will be return.
# for kgV (x,1)
if numbera > 1 and numbera > 1:
# builds the prime factorization of 'number1' and 'number2'
_UpperCamelCase = prime_factorization(__snake_case )
_UpperCamelCase = prime_factorization(__snake_case )
elif numbera == 1 or numbera == 1:
_UpperCamelCase = []
_UpperCamelCase = []
_UpperCamelCase = max(__snake_case, __snake_case )
_UpperCamelCase = 0
_UpperCamelCase = 0
_UpperCamelCase = [] # captured numbers int both 'primeFac1' and 'primeFac2'
# iterates through primeFac1
for n in prime_fac_a:
if n not in done:
if n in prime_fac_a:
_UpperCamelCase = prime_fac_a.count(__snake_case )
_UpperCamelCase = prime_fac_a.count(__snake_case )
for _ in range(max(__snake_case, __snake_case ) ):
ans *= n
else:
_UpperCamelCase = prime_fac_a.count(__snake_case )
for _ in range(__snake_case ):
ans *= n
done.append(__snake_case )
# iterates through primeFac2
for n in prime_fac_a:
if n not in done:
_UpperCamelCase = prime_fac_a.count(__snake_case )
for _ in range(__snake_case ):
ans *= n
done.append(__snake_case )
# precondition
assert isinstance(__snake_case, __snake_case ) and (
ans >= 0
), "'ans' must been from type int and positive"
return ans
def lowerCamelCase__ ( __snake_case ) -> Tuple:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n >= 0), "'number' must been a positive int"
_UpperCamelCase = 0
_UpperCamelCase = 2 # this variable holds the answer
while index < n:
index += 1
ans += 1 # counts to the next number
# if ans not prime then
# runs to the next prime number.
while not is_prime(__snake_case ):
ans += 1
# precondition
assert isinstance(__snake_case, __snake_case ) and is_prime(
__snake_case ), "'ans' must been a prime number and from type int"
return ans
def lowerCamelCase__ ( __snake_case, __snake_case ) -> Tuple:
"""simple docstring"""
assert (
is_prime(__snake_case ) and is_prime(__snake_case ) and (p_number_a < p_number_a)
), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'"
_UpperCamelCase = p_number_a + 1 # jump to the next number
_UpperCamelCase = [] # this list will be returns.
# if number is not prime then
# fetch the next prime number.
while not is_prime(__snake_case ):
number += 1
while number < p_number_a:
ans.append(__snake_case )
number += 1
# fetch the next prime number.
while not is_prime(__snake_case ):
number += 1
# precondition
assert (
isinstance(__snake_case, __snake_case )
and ans[0] != p_number_a
and ans[len(__snake_case ) - 1] != p_number_a
), "'ans' must been a list without the arguments"
# 'ans' contains not 'pNumber1' and 'pNumber2' !
return ans
def lowerCamelCase__ ( __snake_case ) -> List[Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n >= 1), "'n' must been int and >= 1"
_UpperCamelCase = [] # will be returned.
for divisor in range(1, n + 1 ):
if n % divisor == 0:
ans.append(__snake_case )
# precondition
assert ans[0] == 1 and ans[len(__snake_case ) - 1] == n, "Error in function getDivisiors(...)"
return ans
def lowerCamelCase__ ( __snake_case ) -> str:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (
number > 1
), "'number' must been an int and >= 1"
_UpperCamelCase = get_divisors(__snake_case )
# precondition
assert (
isinstance(__snake_case, __snake_case )
and (divisors[0] == 1)
and (divisors[len(__snake_case ) - 1] == number)
), "Error in help-function getDivisiors(...)"
# summed all divisors up to 'number' (exclusive), hence [:-1]
return sum(divisors[:-1] ) == number
def lowerCamelCase__ ( __snake_case, __snake_case ) -> Optional[Any]:
"""simple docstring"""
assert (
isinstance(__snake_case, __snake_case )
and isinstance(__snake_case, __snake_case )
and (denominator != 0)
), "The arguments must been from type int and 'denominator' != 0"
# build the greatest common divisor of numerator and denominator.
_UpperCamelCase = gcd(abs(__snake_case ), abs(__snake_case ) )
# precondition
assert (
isinstance(__snake_case, __snake_case )
and (numerator % gcd_of_fraction == 0)
and (denominator % gcd_of_fraction == 0)
), "Error in function gcd(...,...)"
return (numerator // gcd_of_fraction, denominator // gcd_of_fraction)
def lowerCamelCase__ ( __snake_case ) -> Optional[Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n >= 0), "'n' must been a int and >= 0"
_UpperCamelCase = 1 # this will be return.
for factor in range(1, n + 1 ):
ans *= factor
return ans
def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n >= 0), "'n' must been an int and >= 0"
_UpperCamelCase = 0
_UpperCamelCase = 1
_UpperCamelCase = 1 # this will be return
for _ in range(n - 1 ):
_UpperCamelCase = ans
ans += fiba
_UpperCamelCase = tmp
return ans
| 78 | 0 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available
_a = {"""configuration_swin""": ["""SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP""", """SwinConfig""", """SwinOnnxConfig"""]}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_a = [
"""SWIN_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""SwinForImageClassification""",
"""SwinForMaskedImageModeling""",
"""SwinModel""",
"""SwinPreTrainedModel""",
"""SwinBackbone""",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_a = [
"""TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""TFSwinForImageClassification""",
"""TFSwinForMaskedImageModeling""",
"""TFSwinModel""",
"""TFSwinPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_swin import SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinConfig, SwinOnnxConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_swin import (
SWIN_PRETRAINED_MODEL_ARCHIVE_LIST,
SwinBackbone,
SwinForImageClassification,
SwinForMaskedImageModeling,
SwinModel,
SwinPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_swin import (
TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST,
TFSwinForImageClassification,
TFSwinForMaskedImageModeling,
TFSwinModel,
TFSwinPreTrainedModel,
)
else:
import sys
_a = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 701 |
"""simple docstring"""
import logging
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional, Union
from .generation.configuration_utils import GenerationConfig
from .training_args import TrainingArguments
from .utils import add_start_docstrings
_a = logging.getLogger(__name__)
@dataclass
@add_start_docstrings(TrainingArguments.__doc__ )
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = field(default=lowerCamelCase , metadata={'help': 'Whether to use SortishSampler or not.'} )
lowercase__ = field(
default=lowerCamelCase , metadata={'help': 'Whether to use generate to calculate generative metrics (ROUGE, BLEU).'} )
lowercase__ = field(
default=lowerCamelCase , metadata={
'help': (
'The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default '
'to the `max_length` value of the model configuration.'
)
} , )
lowercase__ = field(
default=lowerCamelCase , metadata={
'help': (
'The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default '
'to the `num_beams` value of the model configuration.'
)
} , )
lowercase__ = field(
default=lowerCamelCase , metadata={
'help': 'Model id, file path or url pointing to a GenerationConfig json file, to use during prediction.'
} , )
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = super().to_dict()
for k, v in d.items():
if isinstance(__a , __a):
_UpperCamelCase = v.to_dict()
return d
| 78 | 0 |
"""simple docstring"""
from __future__ import annotations
import unittest
from transformers import is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
if is_tf_available():
import tensorflow as tf
from transformers import AutoTokenizer, TFAutoModelForSeqaSeqLM
@require_tf
@require_sentencepiece
@require_tokenizers
class _UpperCAmelCase( unittest.TestCase ):
@slow
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = TFAutoModelForSeqaSeqLM.from_pretrained('''google/mt5-small''')
_UpperCamelCase = AutoTokenizer.from_pretrained('''google/mt5-small''')
_UpperCamelCase = tokenizer('''Hello there''' , return_tensors='''tf''').input_ids
_UpperCamelCase = tokenizer('''Hi I am''' , return_tensors='''tf''').input_ids
_UpperCamelCase = model(__a , labels=__a).loss
_UpperCamelCase = -tf.math.reduce_mean(__a).numpy()
_UpperCamelCase = -21.22_8168
self.assertTrue(abs(mtf_score - EXPECTED_SCORE) < 2e-4)
| 702 |
"""simple docstring"""
import argparse
import torch
from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration
from transformers.utils import logging
logging.set_verbosity_info()
_a = logging.get_logger(__name__)
_a = [
["""attention""", """attn"""],
["""encoder_attention""", """encoder_attn"""],
["""q_lin""", """q_proj"""],
["""k_lin""", """k_proj"""],
["""v_lin""", """v_proj"""],
["""out_lin""", """out_proj"""],
["""norm_embeddings""", """layernorm_embedding"""],
["""position_embeddings""", """embed_positions"""],
["""embeddings""", """embed_tokens"""],
["""ffn.lin""", """fc"""],
]
def lowerCamelCase__ ( __snake_case ) -> Optional[Any]:
"""simple docstring"""
if k == "embeddings.weight":
return "shared.weight"
for parlai_name, hf_name in PATTERNS:
_UpperCamelCase = k.replace(__snake_case, __snake_case )
if k.startswith('''encoder''' ):
_UpperCamelCase = k.replace('''.attn''', '''.self_attn''' )
_UpperCamelCase = k.replace('''norm1''', '''self_attn_layer_norm''' )
_UpperCamelCase = k.replace('''norm2''', '''final_layer_norm''' )
elif k.startswith('''decoder''' ):
_UpperCamelCase = k.replace('''norm1''', '''self_attn_layer_norm''' )
_UpperCamelCase = k.replace('''norm2''', '''encoder_attn_layer_norm''' )
_UpperCamelCase = k.replace('''norm3''', '''final_layer_norm''' )
return k
def lowerCamelCase__ ( __snake_case ) -> Optional[int]:
"""simple docstring"""
_UpperCamelCase = [
'''model.encoder.layernorm_embedding.weight''',
'''model.encoder.layernorm_embedding.bias''',
'''model.decoder.layernorm_embedding.weight''',
'''model.decoder.layernorm_embedding.bias''',
]
for k in keys:
_UpperCamelCase = sd.pop(__snake_case )
_UpperCamelCase = k.replace('''layernorm_embedding''', '''layer_norm''' )
assert new_k not in sd
_UpperCamelCase = v
_a = ["""START"""]
@torch.no_grad()
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = torch.load(__snake_case, map_location='''cpu''' )
_UpperCamelCase = model['''model''']
_UpperCamelCase = BlenderbotConfig.from_json_file(__snake_case )
_UpperCamelCase = BlenderbotForConditionalGeneration(__snake_case )
_UpperCamelCase = m.model.state_dict().keys()
_UpperCamelCase = []
_UpperCamelCase = {}
for k, v in sd.items():
if k in IGNORE_KEYS:
continue
_UpperCamelCase = rename_state_dict_key(__snake_case )
if new_k not in valid_keys:
failures.append([k, new_k] )
else:
_UpperCamelCase = v
if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm
rename_layernorm_keys(__snake_case )
m.model.load_state_dict(__snake_case, strict=__snake_case )
m.half()
m.save_pretrained(__snake_case )
if __name__ == "__main__":
_a = argparse.ArgumentParser()
# Required parameters
parser.add_argument("""--src_path""", type=str, help="""like blenderbot-model.bin""")
parser.add_argument("""--save_dir""", default="""hf_blenderbot""", type=str, help="""Where to save converted model.""")
parser.add_argument(
"""--hf_config_json""", default="""blenderbot-3b-config.json""", type=str, help="""Path to config to use"""
)
_a = parser.parse_args()
convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
| 78 | 0 |
"""simple docstring"""
import warnings
from typing import List
import numpy as np
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import is_flax_available, is_tf_available, is_torch_available
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = ['image_processor', 'tokenizer']
lowercase__ = 'OwlViTImageProcessor'
lowercase__ = ('CLIPTokenizer', 'CLIPTokenizerFast')
def __init__( self , __a=None , __a=None , **__a) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = None
if "feature_extractor" in kwargs:
warnings.warn(
'''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
''' instead.''' , __a , )
_UpperCamelCase = kwargs.pop('''feature_extractor''')
_UpperCamelCase = image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError('''You need to specify an `image_processor`.''')
if tokenizer is None:
raise ValueError('''You need to specify a `tokenizer`.''')
super().__init__(__a , __a)
def __call__( self , __a=None , __a=None , __a=None , __a="max_length" , __a="np" , **__a) -> List[str]:
'''simple docstring'''
if text is None and query_images is None and images is None:
raise ValueError(
'''You have to specify at least one text or query image or image. All three cannot be none.''')
if text is not None:
if isinstance(__a , __a) or (isinstance(__a , __a) and not isinstance(text[0] , __a)):
_UpperCamelCase = [self.tokenizer(__a , padding=__a , return_tensors=__a , **__a)]
elif isinstance(__a , __a) and isinstance(text[0] , __a):
_UpperCamelCase = []
# Maximum number of queries across batch
_UpperCamelCase = max([len(__a) for t in text])
# Pad all batch samples to max number of text queries
for t in text:
if len(__a) != max_num_queries:
_UpperCamelCase = t + [''' '''] * (max_num_queries - len(__a))
_UpperCamelCase = self.tokenizer(__a , padding=__a , return_tensors=__a , **__a)
encodings.append(__a)
else:
raise TypeError('''Input text should be a string, a list of strings or a nested list of strings''')
if return_tensors == "np":
_UpperCamelCase = np.concatenate([encoding['''input_ids'''] for encoding in encodings] , axis=0)
_UpperCamelCase = np.concatenate([encoding['''attention_mask'''] for encoding in encodings] , axis=0)
elif return_tensors == "jax" and is_flax_available():
import jax.numpy as jnp
_UpperCamelCase = jnp.concatenate([encoding['''input_ids'''] for encoding in encodings] , axis=0)
_UpperCamelCase = jnp.concatenate([encoding['''attention_mask'''] for encoding in encodings] , axis=0)
elif return_tensors == "pt" and is_torch_available():
import torch
_UpperCamelCase = torch.cat([encoding['''input_ids'''] for encoding in encodings] , dim=0)
_UpperCamelCase = torch.cat([encoding['''attention_mask'''] for encoding in encodings] , dim=0)
elif return_tensors == "tf" and is_tf_available():
import tensorflow as tf
_UpperCamelCase = tf.stack([encoding['''input_ids'''] for encoding in encodings] , axis=0)
_UpperCamelCase = tf.stack([encoding['''attention_mask'''] for encoding in encodings] , axis=0)
else:
raise ValueError('''Target return tensor type could not be returned''')
_UpperCamelCase = BatchEncoding()
_UpperCamelCase = input_ids
_UpperCamelCase = attention_mask
if query_images is not None:
_UpperCamelCase = BatchEncoding()
_UpperCamelCase = self.image_processor(
__a , return_tensors=__a , **__a).pixel_values
_UpperCamelCase = query_pixel_values
if images is not None:
_UpperCamelCase = self.image_processor(__a , return_tensors=__a , **__a)
if text is not None and images is not None:
_UpperCamelCase = image_features.pixel_values
return encoding
elif query_images is not None and images is not None:
_UpperCamelCase = image_features.pixel_values
return encoding
elif text is not None or query_images is not None:
return encoding
else:
return BatchEncoding(data=dict(**__a) , tensor_type=__a)
def UpperCAmelCase ( self , *__a , **__a) -> str:
'''simple docstring'''
return self.image_processor.post_process(*__a , **__a)
def UpperCAmelCase ( self , *__a , **__a) -> Dict:
'''simple docstring'''
return self.image_processor.post_process_object_detection(*__a , **__a)
def UpperCAmelCase ( self , *__a , **__a) -> Optional[Any]:
'''simple docstring'''
return self.image_processor.post_process_image_guided_detection(*__a , **__a)
def UpperCAmelCase ( self , *__a , **__a) -> Optional[int]:
'''simple docstring'''
return self.tokenizer.batch_decode(*__a , **__a)
def UpperCAmelCase ( self , *__a , **__a) -> Optional[Any]:
'''simple docstring'''
return self.tokenizer.decode(*__a , **__a)
@property
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
warnings.warn(
'''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , __a , )
return self.image_processor_class
@property
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
warnings.warn(
'''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , __a , )
return self.image_processor
| 703 |
"""simple docstring"""
import argparse
import os.path as osp
import re
import torch
from safetensors.torch import load_file, save_file
# =================#
# UNet Conversion #
# =================#
_a = [
# (stable-diffusion, HF Diffusers)
("""time_embed.0.weight""", """time_embedding.linear_1.weight"""),
("""time_embed.0.bias""", """time_embedding.linear_1.bias"""),
("""time_embed.2.weight""", """time_embedding.linear_2.weight"""),
("""time_embed.2.bias""", """time_embedding.linear_2.bias"""),
("""input_blocks.0.0.weight""", """conv_in.weight"""),
("""input_blocks.0.0.bias""", """conv_in.bias"""),
("""out.0.weight""", """conv_norm_out.weight"""),
("""out.0.bias""", """conv_norm_out.bias"""),
("""out.2.weight""", """conv_out.weight"""),
("""out.2.bias""", """conv_out.bias"""),
]
_a = [
# (stable-diffusion, HF Diffusers)
("""in_layers.0""", """norm1"""),
("""in_layers.2""", """conv1"""),
("""out_layers.0""", """norm2"""),
("""out_layers.3""", """conv2"""),
("""emb_layers.1""", """time_emb_proj"""),
("""skip_connection""", """conv_shortcut"""),
]
_a = []
# hardcoded number of downblocks and resnets/attentions...
# would need smarter logic for other networks.
for i in range(4):
# loop over downblocks/upblocks
for j in range(2):
# loop over resnets/attentions for downblocks
_a = F"""down_blocks.{i}.resnets.{j}."""
_a = F"""input_blocks.{3*i + j + 1}.0."""
unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix))
if i < 3:
# no attention layers in down_blocks.3
_a = F"""down_blocks.{i}.attentions.{j}."""
_a = F"""input_blocks.{3*i + j + 1}.1."""
unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix))
for j in range(3):
# loop over resnets/attentions for upblocks
_a = F"""up_blocks.{i}.resnets.{j}."""
_a = F"""output_blocks.{3*i + j}.0."""
unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix))
if i > 0:
# no attention layers in up_blocks.0
_a = F"""up_blocks.{i}.attentions.{j}."""
_a = F"""output_blocks.{3*i + j}.1."""
unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix))
if i < 3:
# no downsample in down_blocks.3
_a = F"""down_blocks.{i}.downsamplers.0.conv."""
_a = F"""input_blocks.{3*(i+1)}.0.op."""
unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix))
# no upsample in up_blocks.3
_a = F"""up_blocks.{i}.upsamplers.0."""
_a = F"""output_blocks.{3*i + 2}.{1 if i == 0 else 2}."""
unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix))
_a = """mid_block.attentions.0."""
_a = """middle_block.1."""
unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix))
for j in range(2):
_a = F"""mid_block.resnets.{j}."""
_a = F"""middle_block.{2*j}."""
unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix))
def lowerCamelCase__ ( __snake_case ) -> str:
"""simple docstring"""
_UpperCamelCase = {k: k for k in unet_state_dict.keys()}
for sd_name, hf_name in unet_conversion_map:
_UpperCamelCase = sd_name
for k, v in mapping.items():
if "resnets" in k:
for sd_part, hf_part in unet_conversion_map_resnet:
_UpperCamelCase = v.replace(__snake_case, __snake_case )
_UpperCamelCase = v
for k, v in mapping.items():
for sd_part, hf_part in unet_conversion_map_layer:
_UpperCamelCase = v.replace(__snake_case, __snake_case )
_UpperCamelCase = v
_UpperCamelCase = {v: unet_state_dict[k] for k, v in mapping.items()}
return new_state_dict
# ================#
# VAE Conversion #
# ================#
_a = [
# (stable-diffusion, HF Diffusers)
("""nin_shortcut""", """conv_shortcut"""),
("""norm_out""", """conv_norm_out"""),
("""mid.attn_1.""", """mid_block.attentions.0."""),
]
for i in range(4):
# down_blocks have two resnets
for j in range(2):
_a = F"""encoder.down_blocks.{i}.resnets.{j}."""
_a = F"""encoder.down.{i}.block.{j}."""
vae_conversion_map.append((sd_down_prefix, hf_down_prefix))
if i < 3:
_a = F"""down_blocks.{i}.downsamplers.0."""
_a = F"""down.{i}.downsample."""
vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix))
_a = F"""up_blocks.{i}.upsamplers.0."""
_a = F"""up.{3-i}.upsample."""
vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix))
# up_blocks have three resnets
# also, up blocks in hf are numbered in reverse from sd
for j in range(3):
_a = F"""decoder.up_blocks.{i}.resnets.{j}."""
_a = F"""decoder.up.{3-i}.block.{j}."""
vae_conversion_map.append((sd_up_prefix, hf_up_prefix))
# this part accounts for mid blocks in both the encoder and the decoder
for i in range(2):
_a = F"""mid_block.resnets.{i}."""
_a = F"""mid.block_{i+1}."""
vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix))
_a = [
# (stable-diffusion, HF Diffusers)
("""norm.""", """group_norm."""),
("""q.""", """query."""),
("""k.""", """key."""),
("""v.""", """value."""),
("""proj_out.""", """proj_attn."""),
]
def lowerCamelCase__ ( __snake_case ) -> List[str]:
"""simple docstring"""
return w.reshape(*w.shape, 1, 1 )
def lowerCamelCase__ ( __snake_case ) -> Optional[Any]:
"""simple docstring"""
_UpperCamelCase = {k: k for k in vae_state_dict.keys()}
for k, v in mapping.items():
for sd_part, hf_part in vae_conversion_map:
_UpperCamelCase = v.replace(__snake_case, __snake_case )
_UpperCamelCase = v
for k, v in mapping.items():
if "attentions" in k:
for sd_part, hf_part in vae_conversion_map_attn:
_UpperCamelCase = v.replace(__snake_case, __snake_case )
_UpperCamelCase = v
_UpperCamelCase = {v: vae_state_dict[k] for k, v in mapping.items()}
_UpperCamelCase = ['''q''', '''k''', '''v''', '''proj_out''']
for k, v in new_state_dict.items():
for weight_name in weights_to_convert:
if F'''mid.attn_1.{weight_name}.weight''' in k:
print(F'''Reshaping {k} for SD format''' )
_UpperCamelCase = reshape_weight_for_sd(__snake_case )
return new_state_dict
# =========================#
# Text Encoder Conversion #
# =========================#
_a = [
# (stable-diffusion, HF Diffusers)
("""resblocks.""", """text_model.encoder.layers."""),
("""ln_1""", """layer_norm1"""),
("""ln_2""", """layer_norm2"""),
(""".c_fc.""", """.fc1."""),
(""".c_proj.""", """.fc2."""),
(""".attn""", """.self_attn"""),
("""ln_final.""", """transformer.text_model.final_layer_norm."""),
("""token_embedding.weight""", """transformer.text_model.embeddings.token_embedding.weight"""),
("""positional_embedding""", """transformer.text_model.embeddings.position_embedding.weight"""),
]
_a = {re.escape(x[1]): x[0] for x in textenc_conversion_lst}
_a = re.compile("""|""".join(protected.keys()))
# Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp
_a = {"""q""": 0, """k""": 1, """v""": 2}
def lowerCamelCase__ ( __snake_case ) -> Any:
"""simple docstring"""
_UpperCamelCase = {}
_UpperCamelCase = {}
_UpperCamelCase = {}
for k, v in text_enc_dict.items():
if (
k.endswith('''.self_attn.q_proj.weight''' )
or k.endswith('''.self_attn.k_proj.weight''' )
or k.endswith('''.self_attn.v_proj.weight''' )
):
_UpperCamelCase = k[: -len('''.q_proj.weight''' )]
_UpperCamelCase = k[-len('''q_proj.weight''' )]
if k_pre not in capture_qkv_weight:
_UpperCamelCase = [None, None, None]
_UpperCamelCase = v
continue
if (
k.endswith('''.self_attn.q_proj.bias''' )
or k.endswith('''.self_attn.k_proj.bias''' )
or k.endswith('''.self_attn.v_proj.bias''' )
):
_UpperCamelCase = k[: -len('''.q_proj.bias''' )]
_UpperCamelCase = k[-len('''q_proj.bias''' )]
if k_pre not in capture_qkv_bias:
_UpperCamelCase = [None, None, None]
_UpperCamelCase = v
continue
_UpperCamelCase = textenc_pattern.sub(lambda __snake_case : protected[re.escape(m.group(0 ) )], __snake_case )
_UpperCamelCase = v
for k_pre, tensors in capture_qkv_weight.items():
if None in tensors:
raise Exception('''CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing''' )
_UpperCamelCase = textenc_pattern.sub(lambda __snake_case : protected[re.escape(m.group(0 ) )], __snake_case )
_UpperCamelCase = torch.cat(__snake_case )
for k_pre, tensors in capture_qkv_bias.items():
if None in tensors:
raise Exception('''CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing''' )
_UpperCamelCase = textenc_pattern.sub(lambda __snake_case : protected[re.escape(m.group(0 ) )], __snake_case )
_UpperCamelCase = torch.cat(__snake_case )
return new_state_dict
def lowerCamelCase__ ( __snake_case ) -> Tuple:
"""simple docstring"""
return text_enc_dict
if __name__ == "__main__":
_a = argparse.ArgumentParser()
parser.add_argument("""--model_path""", default=None, type=str, required=True, help="""Path to the model to convert.""")
parser.add_argument("""--checkpoint_path""", default=None, type=str, required=True, help="""Path to the output model.""")
parser.add_argument("""--half""", action="""store_true""", help="""Save weights in half precision.""")
parser.add_argument(
"""--use_safetensors""", action="""store_true""", help="""Save weights use safetensors, default is ckpt."""
)
_a = parser.parse_args()
assert args.model_path is not None, "Must provide a model path!"
assert args.checkpoint_path is not None, "Must provide a checkpoint path!"
# Path for safetensors
_a = osp.join(args.model_path, """unet""", """diffusion_pytorch_model.safetensors""")
_a = osp.join(args.model_path, """vae""", """diffusion_pytorch_model.safetensors""")
_a = osp.join(args.model_path, """text_encoder""", """model.safetensors""")
# Load models from safetensors if it exists, if it doesn't pytorch
if osp.exists(unet_path):
_a = load_file(unet_path, device="""cpu""")
else:
_a = osp.join(args.model_path, """unet""", """diffusion_pytorch_model.bin""")
_a = torch.load(unet_path, map_location="""cpu""")
if osp.exists(vae_path):
_a = load_file(vae_path, device="""cpu""")
else:
_a = osp.join(args.model_path, """vae""", """diffusion_pytorch_model.bin""")
_a = torch.load(vae_path, map_location="""cpu""")
if osp.exists(text_enc_path):
_a = load_file(text_enc_path, device="""cpu""")
else:
_a = osp.join(args.model_path, """text_encoder""", """pytorch_model.bin""")
_a = torch.load(text_enc_path, map_location="""cpu""")
# Convert the UNet model
_a = convert_unet_state_dict(unet_state_dict)
_a = {"""model.diffusion_model.""" + k: v for k, v in unet_state_dict.items()}
# Convert the VAE model
_a = convert_vae_state_dict(vae_state_dict)
_a = {"""first_stage_model.""" + k: v for k, v in vae_state_dict.items()}
# Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper
_a = """text_model.encoder.layers.22.layer_norm2.bias""" in text_enc_dict
if is_vaa_model:
# Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm
_a = {"""transformer.""" + k: v for k, v in text_enc_dict.items()}
_a = convert_text_enc_state_dict_vaa(text_enc_dict)
_a = {"""cond_stage_model.model.""" + k: v for k, v in text_enc_dict.items()}
else:
_a = convert_text_enc_state_dict(text_enc_dict)
_a = {"""cond_stage_model.transformer.""" + k: v for k, v in text_enc_dict.items()}
# Put together new checkpoint
_a = {**unet_state_dict, **vae_state_dict, **text_enc_dict}
if args.half:
_a = {k: v.half() for k, v in state_dict.items()}
if args.use_safetensors:
save_file(state_dict, args.checkpoint_path)
else:
_a = {"""state_dict""": state_dict}
torch.save(state_dict, args.checkpoint_path)
| 78 | 0 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tokenizers_available,
is_torch_available,
is_vision_available,
)
_a = {
"""configuration_perceiver""": ["""PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """PerceiverConfig""", """PerceiverOnnxConfig"""],
"""tokenization_perceiver""": ["""PerceiverTokenizer"""],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_a = ["""PerceiverFeatureExtractor"""]
_a = ["""PerceiverImageProcessor"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_a = [
"""PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""PerceiverForImageClassificationConvProcessing""",
"""PerceiverForImageClassificationFourier""",
"""PerceiverForImageClassificationLearned""",
"""PerceiverForMaskedLM""",
"""PerceiverForMultimodalAutoencoding""",
"""PerceiverForOpticalFlow""",
"""PerceiverForSequenceClassification""",
"""PerceiverLayer""",
"""PerceiverModel""",
"""PerceiverPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_perceiver import PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP, PerceiverConfig, PerceiverOnnxConfig
from .tokenization_perceiver import PerceiverTokenizer
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_perceiver import PerceiverFeatureExtractor
from .image_processing_perceiver import PerceiverImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_perceiver import (
PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST,
PerceiverForImageClassificationConvProcessing,
PerceiverForImageClassificationFourier,
PerceiverForImageClassificationLearned,
PerceiverForMaskedLM,
PerceiverForMultimodalAutoencoding,
PerceiverForOpticalFlow,
PerceiverForSequenceClassification,
PerceiverLayer,
PerceiverModel,
PerceiverPreTrainedModel,
)
else:
import sys
_a = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 704 |
"""simple docstring"""
import argparse
import torch
from transformers import OpenAIGPTConfig, OpenAIGPTModel, load_tf_weights_in_openai_gpt
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging
logging.set_verbosity_info()
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> Union[str, Any]:
"""simple docstring"""
if openai_config_file == "":
_UpperCamelCase = OpenAIGPTConfig()
else:
_UpperCamelCase = OpenAIGPTConfig.from_json_file(__snake_case )
_UpperCamelCase = OpenAIGPTModel(__snake_case )
# Load weights from numpy
load_tf_weights_in_openai_gpt(__snake_case, __snake_case, __snake_case )
# Save pytorch-model
_UpperCamelCase = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME
_UpperCamelCase = pytorch_dump_folder_path + '''/''' + CONFIG_NAME
print(F'''Save PyTorch model to {pytorch_weights_dump_path}''' )
torch.save(model.state_dict(), __snake_case )
print(F'''Save configuration file to {pytorch_config_dump_path}''' )
with open(__snake_case, '''w''', encoding='''utf-8''' ) as f:
f.write(config.to_json_string() )
if __name__ == "__main__":
_a = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--openai_checkpoint_folder_path""",
default=None,
type=str,
required=True,
help="""Path to the TensorFlow checkpoint path.""",
)
parser.add_argument(
"""--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
)
parser.add_argument(
"""--openai_config_file""",
default="""""",
type=str,
help=(
"""An optional config json file corresponding to the pre-trained OpenAI model. \n"""
"""This specifies the model architecture."""
),
)
_a = parser.parse_args()
convert_openai_checkpoint_to_pytorch(
args.openai_checkpoint_folder_path, args.openai_config_file, args.pytorch_dump_folder_path
)
| 78 | 0 |
"""simple docstring"""
from torch import nn
def lowerCamelCase__ ( __snake_case ) -> Tuple:
"""simple docstring"""
if act_fn in ["swish", "silu"]:
return nn.SiLU()
elif act_fn == "mish":
return nn.Mish()
elif act_fn == "gelu":
return nn.GELU()
else:
raise ValueError(F'''Unsupported activation function: {act_fn}''' )
| 705 |
"""simple docstring"""
from __future__ import annotations
import unittest
from transformers import AutoTokenizer, MBartConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel
@require_tf
class _UpperCAmelCase:
lowercase__ = MBartConfig
lowercase__ = {}
lowercase__ = 'gelu'
def __init__( self , __a , __a=13 , __a=7 , __a=True , __a=False , __a=99 , __a=32 , __a=2 , __a=4 , __a=37 , __a=0.1 , __a=0.1 , __a=20 , __a=2 , __a=1 , __a=0 , ) -> Any:
'''simple docstring'''
_UpperCamelCase = parent
_UpperCamelCase = batch_size
_UpperCamelCase = seq_length
_UpperCamelCase = is_training
_UpperCamelCase = use_labels
_UpperCamelCase = vocab_size
_UpperCamelCase = hidden_size
_UpperCamelCase = num_hidden_layers
_UpperCamelCase = num_attention_heads
_UpperCamelCase = intermediate_size
_UpperCamelCase = hidden_dropout_prob
_UpperCamelCase = attention_probs_dropout_prob
_UpperCamelCase = max_position_embeddings
_UpperCamelCase = eos_token_id
_UpperCamelCase = pad_token_id
_UpperCamelCase = bos_token_id
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size)
_UpperCamelCase = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size) , 1)
_UpperCamelCase = tf.concat([input_ids, eos_tensor] , axis=1)
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size)
_UpperCamelCase = self.config_cls(
vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , )
_UpperCamelCase = prepare_mbart_inputs_dict(__a , __a , __a)
return config, inputs_dict
def UpperCAmelCase ( self , __a , __a) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = TFMBartModel(config=__a).get_decoder()
_UpperCamelCase = inputs_dict['''input_ids''']
_UpperCamelCase = input_ids[:1, :]
_UpperCamelCase = inputs_dict['''attention_mask'''][:1, :]
_UpperCamelCase = inputs_dict['''head_mask''']
_UpperCamelCase = 1
# first forward pass
_UpperCamelCase = model(__a , attention_mask=__a , head_mask=__a , use_cache=__a)
_UpperCamelCase , _UpperCamelCase = outputs.to_tuple()
_UpperCamelCase = past_key_values[1]
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case, __snake_case=None, __snake_case=None, __snake_case=None, __snake_case=None, __snake_case=None, ) -> Optional[int]:
"""simple docstring"""
if attention_mask is None:
_UpperCamelCase = tf.cast(tf.math.not_equal(__snake_case, config.pad_token_id ), tf.inta )
if decoder_attention_mask is None:
_UpperCamelCase = tf.concat(
[
tf.ones(decoder_input_ids[:, :1].shape, dtype=tf.inta ),
tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:], config.pad_token_id ), tf.inta ),
], axis=-1, )
if head_mask is None:
_UpperCamelCase = tf.ones((config.encoder_layers, config.encoder_attention_heads) )
if decoder_head_mask is None:
_UpperCamelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
if cross_attn_head_mask is None:
_UpperCamelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
return {
"input_ids": input_ids,
"decoder_input_ids": decoder_input_ids,
"attention_mask": attention_mask,
"decoder_attention_mask": decoder_attention_mask,
"head_mask": head_mask,
"decoder_head_mask": decoder_head_mask,
"cross_attn_head_mask": cross_attn_head_mask,
}
@require_tf
class _UpperCAmelCase( lowerCamelCase , lowerCamelCase , unittest.TestCase ):
lowercase__ = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else ()
lowercase__ = (TFMBartForConditionalGeneration,) if is_tf_available() else ()
lowercase__ = (
{
'conversational': TFMBartForConditionalGeneration,
'feature-extraction': TFMBartModel,
'summarization': TFMBartForConditionalGeneration,
'text2text-generation': TFMBartForConditionalGeneration,
'translation': TFMBartForConditionalGeneration,
}
if is_tf_available()
else {}
)
lowercase__ = True
lowercase__ = False
lowercase__ = False
def UpperCAmelCase ( self , __a , __a , __a , __a , __a) -> Dict:
'''simple docstring'''
if pipeline_test_casse_name != "FeatureExtractionPipelineTests":
# Exception encountered when calling layer '...'
return True
return False
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase = TFMBartModelTester(self)
_UpperCamelCase = ConfigTester(self , config_class=__a)
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
self.config_tester.run_common_tests()
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_decoder_model_past_large_inputs(*__a)
@require_sentencepiece
@require_tokenizers
@require_tf
class _UpperCAmelCase( unittest.TestCase ):
lowercase__ = [
' UN Chief Says There Is No Military Solution in Syria',
]
lowercase__ = [
'Şeful ONU declară că nu există o soluţie militară în Siria',
]
lowercase__ = 'facebook/mbart-large-en-ro'
@cached_property
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
return AutoTokenizer.from_pretrained(self.model_name)
@cached_property
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
_UpperCamelCase = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name)
return model
def UpperCAmelCase ( self , **__a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.translate_src_text(**__a)
self.assertListEqual(self.expected_text , __a)
def UpperCAmelCase ( self , **__a) -> Dict:
'''simple docstring'''
_UpperCamelCase = self.tokenizer(self.src_text , **__a , return_tensors='''tf''')
_UpperCamelCase = self.model.generate(
model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2)
_UpperCamelCase = self.tokenizer.batch_decode(__a , skip_special_tokens=__a)
return generated_words
@slow
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
self._assert_generated_batch_equal_expected()
| 78 | 0 |
"""simple docstring"""
import functools
def lowerCamelCase__ ( __snake_case, __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = len(__snake_case )
_UpperCamelCase = len(__snake_case )
@functools.cache
def min_distance(__snake_case, __snake_case ) -> int:
# if first word index is overflow - delete all from the second word
if indexa >= len_worda:
return len_worda - indexa
# if second word index is overflow - delete all from the first word
if indexa >= len_worda:
return len_worda - indexa
_UpperCamelCase = int(worda[indexa] != worda[indexa] ) # current letters not identical
return min(
1 + min_distance(indexa + 1, __snake_case ), 1 + min_distance(__snake_case, indexa + 1 ), diff + min_distance(indexa + 1, indexa + 1 ), )
return min_distance(0, 0 )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 706 |
"""simple docstring"""
from typing import Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format
from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images
from ...utils import TensorType, logging
_a = logging.get_logger(__name__)
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = ['pixel_values']
def __init__( self , __a = True , __a = 1 / 2_55 , __a = True , __a = 8 , **__a , ) -> None:
'''simple docstring'''
super().__init__(**__a)
_UpperCamelCase = do_rescale
_UpperCamelCase = rescale_factor
_UpperCamelCase = do_pad
_UpperCamelCase = pad_size
def UpperCAmelCase ( self , __a , __a , __a = None , **__a) -> np.ndarray:
'''simple docstring'''
return rescale(__a , scale=__a , data_format=__a , **__a)
def UpperCAmelCase ( self , __a , __a , __a = None) -> List[Any]:
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase = get_image_size(__a)
_UpperCamelCase = (old_height // size + 1) * size - old_height
_UpperCamelCase = (old_width // size + 1) * size - old_width
return pad(__a , ((0, pad_height), (0, pad_width)) , mode='''symmetric''' , data_format=__a)
def UpperCAmelCase ( self , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = ChannelDimension.FIRST , **__a , ) -> Tuple:
'''simple docstring'''
_UpperCamelCase = do_rescale if do_rescale is not None else self.do_rescale
_UpperCamelCase = rescale_factor if rescale_factor is not None else self.rescale_factor
_UpperCamelCase = do_pad if do_pad is not None else self.do_pad
_UpperCamelCase = pad_size if pad_size is not None else self.pad_size
_UpperCamelCase = make_list_of_images(__a)
if not valid_images(__a):
raise ValueError(
'''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
'''torch.Tensor, tf.Tensor or jax.ndarray.''')
if do_rescale and rescale_factor is None:
raise ValueError('''Rescale factor must be specified if do_rescale is True.''')
# All transformations expect numpy arrays.
_UpperCamelCase = [to_numpy_array(__a) for image in images]
if do_rescale:
_UpperCamelCase = [self.rescale(image=__a , scale=__a) for image in images]
if do_pad:
_UpperCamelCase = [self.pad(__a , size=__a) for image in images]
_UpperCamelCase = [to_channel_dimension_format(__a , __a) for image in images]
_UpperCamelCase = {'''pixel_values''': images}
return BatchFeature(data=__a , tensor_type=__a)
| 78 | 0 |
"""simple docstring"""
from __future__ import annotations
_a = [True] * 100_0001
_a = 2
while i * i <= 100_0000:
if seive[i]:
for j in range(i * i, 100_0001, i):
_a = False
i += 1
def lowerCamelCase__ ( __snake_case ) -> bool:
"""simple docstring"""
return seive[n]
def lowerCamelCase__ ( __snake_case ) -> bool:
"""simple docstring"""
return any(digit in '''02468''' for digit in str(__snake_case ) )
def lowerCamelCase__ ( __snake_case = 1_00_00_00 ) -> list[int]:
"""simple docstring"""
_UpperCamelCase = [2] # result already includes the number 2.
for num in range(3, limit + 1, 2 ):
if is_prime(__snake_case ) and not contains_an_even_digit(__snake_case ):
_UpperCamelCase = str(__snake_case )
_UpperCamelCase = [int(str_num[j:] + str_num[:j] ) for j in range(len(__snake_case ) )]
if all(is_prime(__snake_case ) for i in list_nums ):
result.append(__snake_case )
return result
def lowerCamelCase__ ( ) -> int:
"""simple docstring"""
return len(find_circular_primes() )
if __name__ == "__main__":
print(F"""{len(find_circular_primes()) = }""") | 707 |
"""simple docstring"""
from importlib import import_module
from .logging import get_logger
_a = get_logger(__name__)
class _UpperCAmelCase:
def __init__( self , __a , __a=None) -> Dict:
'''simple docstring'''
_UpperCamelCase = attrs or []
if module is not None:
for key in module.__dict__:
if key in attrs or not key.startswith('''__'''):
setattr(self , __a , getattr(__a , __a))
_UpperCamelCase = module._original_module if isinstance(__a , _PatchedModuleObj) else module
class _UpperCAmelCase:
lowercase__ = []
def __init__( self , __a , __a , __a , __a=None) -> List[str]:
'''simple docstring'''
_UpperCamelCase = obj
_UpperCamelCase = target
_UpperCamelCase = new
_UpperCamelCase = target.split('''.''')[0]
_UpperCamelCase = {}
_UpperCamelCase = attrs or []
def __enter__( self) -> int:
'''simple docstring'''
*_UpperCamelCase , _UpperCamelCase = self.target.split('''.''')
# Patch modules:
# it's used to patch attributes of submodules like "os.path.join";
# in this case we need to patch "os" and "os.path"
for i in range(len(__a)):
try:
_UpperCamelCase = import_module('''.'''.join(submodules[: i + 1]))
except ModuleNotFoundError:
continue
# We iterate over all the globals in self.obj in case we find "os" or "os.path"
for attr in self.obj.__dir__():
_UpperCamelCase = getattr(self.obj , __a)
# We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
# This allows to patch renamed modules like "from os import path as ospath".
if obj_attr is submodule or (
(isinstance(__a , _PatchedModuleObj) and obj_attr._original_module is submodule)
):
_UpperCamelCase = obj_attr
# patch at top level
setattr(self.obj , __a , _PatchedModuleObj(__a , attrs=self.attrs))
_UpperCamelCase = getattr(self.obj , __a)
# construct lower levels patches
for key in submodules[i + 1 :]:
setattr(__a , __a , _PatchedModuleObj(getattr(__a , __a , __a) , attrs=self.attrs))
_UpperCamelCase = getattr(__a , __a)
# finally set the target attribute
setattr(__a , __a , self.new)
# Patch attribute itself:
# it's used for builtins like "open",
# and also to patch "os.path.join" we may also need to patch "join"
# itself if it was imported as "from os.path import join".
if submodules: # if it's an attribute of a submodule like "os.path.join"
try:
_UpperCamelCase = getattr(import_module('''.'''.join(__a)) , __a)
except (AttributeError, ModuleNotFoundError):
return
# We iterate over all the globals in self.obj in case we find "os.path.join"
for attr in self.obj.__dir__():
# We don't check for the name of the global, but rather if its value *is* "os.path.join".
# This allows to patch renamed attributes like "from os.path import join as pjoin".
if getattr(self.obj , __a) is attr_value:
_UpperCamelCase = getattr(self.obj , __a)
setattr(self.obj , __a , self.new)
elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open"
_UpperCamelCase = globals()['''__builtins__'''][target_attr]
setattr(self.obj , __a , self.new)
else:
raise RuntimeError(F'''Tried to patch attribute {target_attr} instead of a submodule.''')
def __exit__( self , *__a) -> Tuple:
'''simple docstring'''
for attr in list(self.original):
setattr(self.obj , __a , self.original.pop(__a))
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
self.__enter__()
self._active_patches.append(self)
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
try:
self._active_patches.remove(self)
except ValueError:
# If the patch hasn't been started this will fail
return None
return self.__exit__()
| 78 | 0 |
"""simple docstring"""
import os
from shutil import copyfile
from typing import List, Optional, Tuple
from ...tokenization_utils import AddedToken
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging
if is_sentencepiece_available():
from .tokenization_rembert import RemBertTokenizer
else:
_a : Union[str, Any] = None
_a : int = logging.get_logger(__name__)
_a : Union[str, Any] = {"""vocab_file""": """sentencepiece.model""", """tokenizer_file""": """tokenizer.json"""}
_a : Dict = {
"""vocab_file""": {
"""google/rembert""": """https://huggingface.co/google/rembert/resolve/main/sentencepiece.model""",
},
"""tokenizer_file""": {
"""google/rembert""": """https://huggingface.co/google/rembert/resolve/main/tokenizer.json""",
},
}
_a : List[str] = {
"""google/rembert""": 256,
}
_a : Any = """▁"""
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = VOCAB_FILES_NAMES
lowercase__ = PRETRAINED_VOCAB_FILES_MAP
lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
lowercase__ = RemBertTokenizer
def __init__( self , __a=None , __a=None , __a=True , __a=True , __a=False , __a="[CLS]" , __a="[SEP]" , __a="<unk>" , __a="[SEP]" , __a="<pad>" , __a="[CLS]" , __a="[MASK]" , **__a , ) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = AddedToken(__a , lstrip=__a , rstrip=__a) if isinstance(__a , __a) else mask_token
super().__init__(
__a , tokenizer_file=__a , do_lower_case=__a , remove_space=__a , keep_accents=__a , bos_token=__a , eos_token=__a , unk_token=__a , sep_token=__a , pad_token=__a , cls_token=__a , mask_token=__a , **__a , )
_UpperCamelCase = do_lower_case
_UpperCamelCase = remove_space
_UpperCamelCase = keep_accents
_UpperCamelCase = vocab_file
_UpperCamelCase = False if not self.vocab_file else True
def UpperCAmelCase ( self , __a , __a = None) -> List[int]:
'''simple docstring'''
_UpperCamelCase = [self.sep_token_id]
_UpperCamelCase = [self.cls_token_id]
if token_ids_a is None:
return cls + token_ids_a + sep
return cls + token_ids_a + sep + token_ids_a + sep
def UpperCAmelCase ( self , __a , __a = None , __a = False) -> List[int]:
'''simple docstring'''
if already_has_special_tokens:
if token_ids_a is not None:
raise ValueError(
'''You should not supply a second sequence if the provided sequence of '''
'''ids is already formatted with special tokens for the model.''')
return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]
if token_ids_a is not None:
return [1] + ([0] * len(__a)) + [1] + ([0] * len(__a)) + [1]
return [1] + ([0] * len(__a)) + [1]
def UpperCAmelCase ( self , __a , __a = None) -> List[int]:
'''simple docstring'''
_UpperCamelCase = [self.sep_token_id]
_UpperCamelCase = [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) -> Tuple[str]:
'''simple docstring'''
if not os.path.isdir(__a):
logger.error('''Vocabulary path ({}) should be a directory'''.format(__a))
return
_UpperCamelCase = os.path.join(
__a , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''])
if os.path.abspath(self.vocab_file) != os.path.abspath(__a):
copyfile(self.vocab_file , __a)
return (out_vocab_file,)
| 708 |
"""simple docstring"""
from ...utils import (
OptionalDependencyNotAvailable,
is_flax_available,
is_torch_available,
is_transformers_available,
)
try:
if not (is_transformers_available() and is_torch_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ...utils.dummy_torch_and_transformers_objects import * # noqa F403
else:
from .multicontrolnet import MultiControlNetModel
from .pipeline_controlnet import StableDiffusionControlNetPipeline
from .pipeline_controlnet_imgaimg import StableDiffusionControlNetImgaImgPipeline
from .pipeline_controlnet_inpaint import StableDiffusionControlNetInpaintPipeline
if is_transformers_available() and is_flax_available():
from .pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline
| 78 | 0 |
"""simple docstring"""
import flax.linen as nn
import jax.numpy as jnp
from .attention_flax import FlaxTransformeraDModel
from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD
class _UpperCAmelCase( nn.Module ):
lowercase__ = 42
lowercase__ = 42
lowercase__ = 0.0
lowercase__ = 1
lowercase__ = 1
lowercase__ = True
lowercase__ = False
lowercase__ = False
lowercase__ = False
lowercase__ = jnp.floataa
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = []
_UpperCamelCase = []
for i in range(self.num_layers):
_UpperCamelCase = self.in_channels if i == 0 else self.out_channels
_UpperCamelCase = FlaxResnetBlockaD(
in_channels=__a , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , )
resnets.append(__a)
_UpperCamelCase = FlaxTransformeraDModel(
in_channels=self.out_channels , n_heads=self.num_attention_heads , d_head=self.out_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , only_cross_attention=self.only_cross_attention , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , )
attentions.append(__a)
_UpperCamelCase = resnets
_UpperCamelCase = attentions
if self.add_downsample:
_UpperCamelCase = FlaxDownsampleaD(self.out_channels , dtype=self.dtype)
def __call__( self , __a , __a , __a , __a=True) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = ()
for resnet, attn in zip(self.resnets , self.attentions):
_UpperCamelCase = resnet(__a , __a , deterministic=__a)
_UpperCamelCase = attn(__a , __a , deterministic=__a)
output_states += (hidden_states,)
if self.add_downsample:
_UpperCamelCase = self.downsamplers_a(__a)
output_states += (hidden_states,)
return hidden_states, output_states
class _UpperCAmelCase( nn.Module ):
lowercase__ = 42
lowercase__ = 42
lowercase__ = 0.0
lowercase__ = 1
lowercase__ = True
lowercase__ = jnp.floataa
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
_UpperCamelCase = []
for i in range(self.num_layers):
_UpperCamelCase = self.in_channels if i == 0 else self.out_channels
_UpperCamelCase = FlaxResnetBlockaD(
in_channels=__a , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , )
resnets.append(__a)
_UpperCamelCase = resnets
if self.add_downsample:
_UpperCamelCase = FlaxDownsampleaD(self.out_channels , dtype=self.dtype)
def __call__( self , __a , __a , __a=True) -> str:
'''simple docstring'''
_UpperCamelCase = ()
for resnet in self.resnets:
_UpperCamelCase = resnet(__a , __a , deterministic=__a)
output_states += (hidden_states,)
if self.add_downsample:
_UpperCamelCase = self.downsamplers_a(__a)
output_states += (hidden_states,)
return hidden_states, output_states
class _UpperCAmelCase( nn.Module ):
lowercase__ = 42
lowercase__ = 42
lowercase__ = 42
lowercase__ = 0.0
lowercase__ = 1
lowercase__ = 1
lowercase__ = True
lowercase__ = False
lowercase__ = False
lowercase__ = False
lowercase__ = jnp.floataa
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
_UpperCamelCase = []
_UpperCamelCase = []
for i in range(self.num_layers):
_UpperCamelCase = self.in_channels if (i == self.num_layers - 1) else self.out_channels
_UpperCamelCase = self.prev_output_channel if i == 0 else self.out_channels
_UpperCamelCase = FlaxResnetBlockaD(
in_channels=resnet_in_channels + res_skip_channels , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , )
resnets.append(__a)
_UpperCamelCase = FlaxTransformeraDModel(
in_channels=self.out_channels , n_heads=self.num_attention_heads , d_head=self.out_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , only_cross_attention=self.only_cross_attention , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , )
attentions.append(__a)
_UpperCamelCase = resnets
_UpperCamelCase = attentions
if self.add_upsample:
_UpperCamelCase = FlaxUpsampleaD(self.out_channels , dtype=self.dtype)
def __call__( self , __a , __a , __a , __a , __a=True) -> Dict:
'''simple docstring'''
for resnet, attn in zip(self.resnets , self.attentions):
# pop res hidden states
_UpperCamelCase = res_hidden_states_tuple[-1]
_UpperCamelCase = res_hidden_states_tuple[:-1]
_UpperCamelCase = jnp.concatenate((hidden_states, res_hidden_states) , axis=-1)
_UpperCamelCase = resnet(__a , __a , deterministic=__a)
_UpperCamelCase = attn(__a , __a , deterministic=__a)
if self.add_upsample:
_UpperCamelCase = self.upsamplers_a(__a)
return hidden_states
class _UpperCAmelCase( nn.Module ):
lowercase__ = 42
lowercase__ = 42
lowercase__ = 42
lowercase__ = 0.0
lowercase__ = 1
lowercase__ = True
lowercase__ = jnp.floataa
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = []
for i in range(self.num_layers):
_UpperCamelCase = self.in_channels if (i == self.num_layers - 1) else self.out_channels
_UpperCamelCase = self.prev_output_channel if i == 0 else self.out_channels
_UpperCamelCase = FlaxResnetBlockaD(
in_channels=resnet_in_channels + res_skip_channels , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , )
resnets.append(__a)
_UpperCamelCase = resnets
if self.add_upsample:
_UpperCamelCase = FlaxUpsampleaD(self.out_channels , dtype=self.dtype)
def __call__( self , __a , __a , __a , __a=True) -> Any:
'''simple docstring'''
for resnet in self.resnets:
# pop res hidden states
_UpperCamelCase = res_hidden_states_tuple[-1]
_UpperCamelCase = res_hidden_states_tuple[:-1]
_UpperCamelCase = jnp.concatenate((hidden_states, res_hidden_states) , axis=-1)
_UpperCamelCase = resnet(__a , __a , deterministic=__a)
if self.add_upsample:
_UpperCamelCase = self.upsamplers_a(__a)
return hidden_states
class _UpperCAmelCase( nn.Module ):
lowercase__ = 42
lowercase__ = 0.0
lowercase__ = 1
lowercase__ = 1
lowercase__ = False
lowercase__ = False
lowercase__ = jnp.floataa
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
_UpperCamelCase = [
FlaxResnetBlockaD(
in_channels=self.in_channels , out_channels=self.in_channels , dropout_prob=self.dropout , dtype=self.dtype , )
]
_UpperCamelCase = []
for _ in range(self.num_layers):
_UpperCamelCase = FlaxTransformeraDModel(
in_channels=self.in_channels , n_heads=self.num_attention_heads , d_head=self.in_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , )
attentions.append(__a)
_UpperCamelCase = FlaxResnetBlockaD(
in_channels=self.in_channels , out_channels=self.in_channels , dropout_prob=self.dropout , dtype=self.dtype , )
resnets.append(__a)
_UpperCamelCase = resnets
_UpperCamelCase = attentions
def __call__( self , __a , __a , __a , __a=True) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.resnets[0](__a , __a)
for attn, resnet in zip(self.attentions , self.resnets[1:]):
_UpperCamelCase = attn(__a , __a , deterministic=__a)
_UpperCamelCase = resnet(__a , __a , deterministic=__a)
return hidden_states
| 709 |
"""simple docstring"""
from collections import OrderedDict
from typing import Any, Mapping, Optional
from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast
from ...utils import logging
_a = logging.get_logger(__name__)
_a = {
"""EleutherAI/gpt-neo-1.3B""": """https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json""",
# See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo
}
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = 'gpt_neo'
lowercase__ = ['past_key_values']
lowercase__ = {'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers'}
def __init__( self , __a=5_02_57 , __a=20_48 , __a=20_48 , __a=24 , __a=[[["global", "local"], 12]] , __a=16 , __a=None , __a=2_56 , __a="gelu_new" , __a=0.0 , __a=0.0 , __a=0.0 , __a=0.1 , __a=1e-5 , __a=0.02 , __a=True , __a=5_02_56 , __a=5_02_56 , **__a , ) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = vocab_size
_UpperCamelCase = max_position_embeddings
_UpperCamelCase = hidden_size
_UpperCamelCase = num_layers
_UpperCamelCase = num_heads
_UpperCamelCase = intermediate_size
_UpperCamelCase = window_size
_UpperCamelCase = activation_function
_UpperCamelCase = resid_dropout
_UpperCamelCase = embed_dropout
_UpperCamelCase = attention_dropout
_UpperCamelCase = classifier_dropout
_UpperCamelCase = layer_norm_epsilon
_UpperCamelCase = initializer_range
_UpperCamelCase = use_cache
_UpperCamelCase = bos_token_id
_UpperCamelCase = eos_token_id
_UpperCamelCase = attention_types
_UpperCamelCase = self.expand_attention_types_params(__a)
if len(self.attention_layers) != self.num_layers:
raise ValueError(
'''Configuration for convolutional module is incorrect. '''
'''It is required that `len(config.attention_layers)` == `config.num_layers` '''
F'''but is `len(config.attention_layers) = {len(self.attention_layers)}`, '''
F'''`config.num_layers = {self.num_layers}`. '''
'''`config.attention_layers` is prepared using `config.attention_types`. '''
'''Please verify the value of `config.attention_types` argument.''')
super().__init__(bos_token_id=__a , eos_token_id=__a , **__a)
@staticmethod
def UpperCAmelCase ( __a) -> int:
'''simple docstring'''
_UpperCamelCase = []
for item in attention_types:
for _ in range(item[1]):
attentions.extend(item[0])
return attentions
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case, __snake_case ) -> str:
"""simple docstring"""
import torch
_UpperCamelCase = input.size()
_UpperCamelCase = len(__snake_case )
_UpperCamelCase = shape[dimension]
_UpperCamelCase = torch.arange(0, __snake_case, __snake_case )
_UpperCamelCase = torch.div(sizedim - size, __snake_case, rounding_mode='''floor''' ) + 1
_UpperCamelCase = torch.arange(__snake_case ) + low_indices[:min_length][:, None]
_UpperCamelCase = [slice(__snake_case )] * rank
_UpperCamelCase = indices
_UpperCamelCase = input[s]
_UpperCamelCase = list(range(0, rank + 1 ) )
perm.append(perm.pop(dimension + 1 ) )
return sliced.permute(__snake_case )
def lowerCamelCase__ ( __snake_case, __snake_case ) -> str:
"""simple docstring"""
import torch
_UpperCamelCase = torch.arange(1, __snake_case )
_UpperCamelCase = torch.remainder(__snake_case, __snake_case )
_UpperCamelCase = remainders == 0
_UpperCamelCase = candidates[divisor_indices]
_UpperCamelCase = torch.max(__snake_case )
return largest_divisor, torch.div(__snake_case, __snake_case, rounding_mode='''floor''' )
class _UpperCAmelCase( lowerCamelCase ):
@property
def UpperCAmelCase ( self) -> Mapping[str, Mapping[int, str]]:
'''simple docstring'''
_UpperCamelCase = OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}})
if self.use_past:
self.fill_with_past_key_values_(__a , direction='''inputs''')
_UpperCamelCase = {0: '''batch''', 1: '''past_sequence + sequence'''}
else:
_UpperCamelCase = {0: '''batch''', 1: '''sequence'''}
return common_inputs
@property
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
return self._config.num_heads
def UpperCAmelCase ( self , __a , __a = -1 , __a = -1 , __a = False , __a = None , ) -> Mapping[str, Any]:
'''simple docstring'''
_UpperCamelCase = 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()
_UpperCamelCase = 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
_UpperCamelCase , _UpperCamelCase = common_inputs['''input_ids'''].shape
# Not using the same length for past_key_values
_UpperCamelCase = seqlen + 2
_UpperCamelCase = (
batch,
self.num_attention_heads,
past_key_values_length,
self._config.hidden_size // self.num_attention_heads,
)
_UpperCamelCase = [
(torch.zeros(__a), torch.zeros(__a)) for _ in range(self.num_layers)
]
_UpperCamelCase = common_inputs['''attention_mask''']
if self.use_past:
_UpperCamelCase = ordered_inputs['''attention_mask'''].dtype
_UpperCamelCase = torch.cat(
[ordered_inputs['''attention_mask'''], torch.ones(__a , __a , dtype=__a)] , dim=1)
return ordered_inputs
@property
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
return 13
| 78 | 0 |
"""simple docstring"""
import argparse
import json
import os
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
from accelerate.utils.deepspeed import DummyOptim, DummyScheduler
_a = 16
_a = 32
def lowerCamelCase__ ( __snake_case, __snake_case = 16, __snake_case = "bert-base-cased" ) -> str:
"""simple docstring"""
_UpperCamelCase = AutoTokenizer.from_pretrained(__snake_case )
_UpperCamelCase = load_dataset('''glue''', '''mrpc''' )
def tokenize_function(__snake_case ):
# max_length=None => use the model max length (it's actually the default)
_UpperCamelCase = tokenizer(examples['''sentence1'''], examples['''sentence2'''], truncation=__snake_case, max_length=__snake_case )
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
_UpperCamelCase = datasets.map(
__snake_case, batched=__snake_case, remove_columns=['''idx''', '''sentence1''', '''sentence2'''], load_from_cache_file=__snake_case )
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
_UpperCamelCase = tokenized_datasets.rename_column('''label''', '''labels''' )
def collate_fn(__snake_case ):
# On TPU it's best to pad everything to the same length or training will be very slow.
if accelerator.distributed_type == DistributedType.TPU:
return tokenizer.pad(__snake_case, padding='''max_length''', max_length=1_28, return_tensors='''pt''' )
return tokenizer.pad(__snake_case, padding='''longest''', return_tensors='''pt''' )
# Instantiate dataloaders.
_UpperCamelCase = DataLoader(
tokenized_datasets['''train'''], shuffle=__snake_case, collate_fn=__snake_case, batch_size=__snake_case )
_UpperCamelCase = DataLoader(
tokenized_datasets['''validation'''], shuffle=__snake_case, collate_fn=__snake_case, batch_size=__snake_case )
return train_dataloader, eval_dataloader
def lowerCamelCase__ ( __snake_case, __snake_case ) -> Dict:
"""simple docstring"""
_UpperCamelCase = Accelerator()
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
_UpperCamelCase = config['''lr''']
_UpperCamelCase = int(config['''num_epochs'''] )
_UpperCamelCase = int(config['''seed'''] )
_UpperCamelCase = int(config['''batch_size'''] )
_UpperCamelCase = args.model_name_or_path
set_seed(__snake_case )
_UpperCamelCase , _UpperCamelCase = get_dataloaders(__snake_case, __snake_case, __snake_case )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
_UpperCamelCase = AutoModelForSequenceClassification.from_pretrained(__snake_case, return_dict=__snake_case )
# Instantiate optimizer
_UpperCamelCase = (
AdamW
if accelerator.state.deepspeed_plugin is None
or '''optimizer''' not in accelerator.state.deepspeed_plugin.deepspeed_config
else DummyOptim
)
_UpperCamelCase = optimizer_cls(params=model.parameters(), lr=__snake_case )
if accelerator.state.deepspeed_plugin is not None:
_UpperCamelCase = accelerator.state.deepspeed_plugin.deepspeed_config[
'''gradient_accumulation_steps'''
]
else:
_UpperCamelCase = 1
_UpperCamelCase = (len(__snake_case ) * num_epochs) // gradient_accumulation_steps
# Instantiate scheduler
if (
accelerator.state.deepspeed_plugin is None
or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config
):
_UpperCamelCase = get_linear_schedule_with_warmup(
optimizer=__snake_case, num_warmup_steps=0, num_training_steps=__snake_case, )
else:
_UpperCamelCase = DummyScheduler(__snake_case, total_num_steps=__snake_case, warmup_num_steps=0 )
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = accelerator.prepare(
__snake_case, __snake_case, __snake_case, __snake_case, __snake_case )
# We need to keep track of how many total steps we have iterated over
_UpperCamelCase = 0
# We also need to keep track of the stating epoch so files are named properly
_UpperCamelCase = 0
# Now we train the model
_UpperCamelCase = evaluate.load('''glue''', '''mrpc''' )
_UpperCamelCase = 0
_UpperCamelCase = {}
for epoch in range(__snake_case, __snake_case ):
model.train()
for step, batch in enumerate(__snake_case ):
_UpperCamelCase = model(**__snake_case )
_UpperCamelCase = outputs.loss
_UpperCamelCase = loss / gradient_accumulation_steps
accelerator.backward(__snake_case )
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
overall_step += 1
model.eval()
_UpperCamelCase = 0
for step, batch in enumerate(__snake_case ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
with torch.no_grad():
_UpperCamelCase = model(**__snake_case )
_UpperCamelCase = outputs.logits.argmax(dim=-1 )
# It is slightly faster to call this once, than multiple times
_UpperCamelCase , _UpperCamelCase = accelerator.gather(
(predictions, batch['''labels''']) ) # If we are in a multiprocess environment, the last batch has duplicates
if accelerator.use_distributed:
if step == len(__snake_case ) - 1:
_UpperCamelCase = predictions[: len(eval_dataloader.dataset ) - samples_seen]
_UpperCamelCase = references[: len(eval_dataloader.dataset ) - samples_seen]
else:
samples_seen += references.shape[0]
metric.add_batch(
predictions=__snake_case, references=__snake_case, )
_UpperCamelCase = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(F'''epoch {epoch}:''', __snake_case )
_UpperCamelCase = eval_metric['''accuracy''']
if best_performance < eval_metric["accuracy"]:
_UpperCamelCase = eval_metric['''accuracy''']
if args.performance_lower_bound is not None:
assert (
args.performance_lower_bound <= best_performance
), F'''Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}'''
accelerator.wait_for_everyone()
if accelerator.is_main_process:
with open(os.path.join(args.output_dir, '''all_results.json''' ), '''w''' ) as f:
json.dump(__snake_case, __snake_case )
def lowerCamelCase__ ( ) -> str:
"""simple docstring"""
_UpperCamelCase = argparse.ArgumentParser(description='''Simple example of training script tracking peak GPU memory usage.''' )
parser.add_argument(
'''--model_name_or_path''', type=__snake_case, default='''bert-base-cased''', help='''Path to pretrained model or model identifier from huggingface.co/models.''', required=__snake_case, )
parser.add_argument(
'''--output_dir''', type=__snake_case, default='''.''', help='''Optional save directory where all checkpoint folders will be stored. Default is the current working directory.''', )
parser.add_argument(
'''--performance_lower_bound''', type=__snake_case, default=__snake_case, help='''Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.''', )
parser.add_argument(
'''--num_epochs''', type=__snake_case, default=3, help='''Number of train epochs.''', )
_UpperCamelCase = parser.parse_args()
_UpperCamelCase = {'''lr''': 2e-5, '''num_epochs''': args.num_epochs, '''seed''': 42, '''batch_size''': 16}
training_function(__snake_case, __snake_case )
if __name__ == "__main__":
main()
| 710 |
"""simple docstring"""
import sys
from collections import defaultdict
class _UpperCAmelCase:
def __init__( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = []
def UpperCAmelCase ( self , __a) -> Optional[Any]:
'''simple docstring'''
return self.node_position[vertex]
def UpperCAmelCase ( self , __a , __a) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = pos
def UpperCAmelCase ( self , __a , __a , __a , __a) -> Tuple:
'''simple docstring'''
if start > size // 2 - 1:
return
else:
if 2 * start + 2 >= size:
_UpperCamelCase = 2 * start + 1
else:
if heap[2 * start + 1] < heap[2 * start + 2]:
_UpperCamelCase = 2 * start + 1
else:
_UpperCamelCase = 2 * start + 2
if heap[smallest_child] < heap[start]:
_UpperCamelCase , _UpperCamelCase = heap[smallest_child], positions[smallest_child]
_UpperCamelCase , _UpperCamelCase = (
heap[start],
positions[start],
)
_UpperCamelCase , _UpperCamelCase = temp, tempa
_UpperCamelCase = self.get_position(positions[smallest_child])
self.set_position(
positions[smallest_child] , self.get_position(positions[start]))
self.set_position(positions[start] , __a)
self.top_to_bottom(__a , __a , __a , __a)
def UpperCAmelCase ( self , __a , __a , __a , __a) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = position[index]
while index != 0:
_UpperCamelCase = int((index - 2) / 2) if index % 2 == 0 else int((index - 1) / 2)
if val < heap[parent]:
_UpperCamelCase = heap[parent]
_UpperCamelCase = position[parent]
self.set_position(position[parent] , __a)
else:
_UpperCamelCase = val
_UpperCamelCase = temp
self.set_position(__a , __a)
break
_UpperCamelCase = parent
else:
_UpperCamelCase = val
_UpperCamelCase = temp
self.set_position(__a , 0)
def UpperCAmelCase ( self , __a , __a) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = len(__a) // 2 - 1
for i in range(__a , -1 , -1):
self.top_to_bottom(__a , __a , len(__a) , __a)
def UpperCAmelCase ( self , __a , __a) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = positions[0]
_UpperCamelCase = sys.maxsize
self.top_to_bottom(__a , 0 , len(__a) , __a)
return temp
def lowerCamelCase__ ( __snake_case ) -> Optional[int]:
"""simple docstring"""
_UpperCamelCase = Heap()
_UpperCamelCase = [0] * len(__snake_case )
_UpperCamelCase = [-1] * len(__snake_case ) # Neighboring Tree Vertex of selected vertex
# Minimum Distance of explored vertex with neighboring vertex of partial tree
# formed in graph
_UpperCamelCase = [] # Heap of Distance of vertices from their neighboring vertex
_UpperCamelCase = []
for vertex in range(len(__snake_case ) ):
distance_tv.append(sys.maxsize )
positions.append(__snake_case )
heap.node_position.append(__snake_case )
_UpperCamelCase = []
_UpperCamelCase = 1
_UpperCamelCase = sys.maxsize
for neighbor, distance in adjacency_list[0]:
_UpperCamelCase = 0
_UpperCamelCase = distance
heap.heapify(__snake_case, __snake_case )
for _ in range(1, len(__snake_case ) ):
_UpperCamelCase = heap.delete_minimum(__snake_case, __snake_case )
if visited[vertex] == 0:
tree_edges.append((nbr_tv[vertex], vertex) )
_UpperCamelCase = 1
for neighbor, distance in adjacency_list[vertex]:
if (
visited[neighbor] == 0
and distance < distance_tv[heap.get_position(__snake_case )]
):
_UpperCamelCase = distance
heap.bottom_to_top(
__snake_case, heap.get_position(__snake_case ), __snake_case, __snake_case )
_UpperCamelCase = vertex
return tree_edges
if __name__ == "__main__": # pragma: no cover
# < --------- Prims Algorithm --------- >
_a = int(input("""Enter number of edges: """).strip())
_a = defaultdict(list)
for _ in range(edges_number):
_a = [int(x) for x in input().strip().split()]
adjacency_list[edge[0]].append([edge[1], edge[2]])
adjacency_list[edge[1]].append([edge[0], edge[2]])
print(prisms_algorithm(adjacency_list))
| 78 | 0 |
"""simple docstring"""
import json
import os
import unittest
from typing import Tuple
from transformers import WavaVecaPhonemeCTCTokenizer
from transformers.models.wavaveca.tokenization_wavaveca import VOCAB_FILES_NAMES
from transformers.models.wavaveca_phoneme.tokenization_wavaveca_phoneme import WavaVecaPhonemeCTCTokenizerOutput
from transformers.testing_utils import require_phonemizer
from ...test_tokenization_common import TokenizerTesterMixin
@require_phonemizer
class _UpperCAmelCase( lowerCamelCase , unittest.TestCase ):
lowercase__ = WavaVecaPhonemeCTCTokenizer
lowercase__ = False
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
super().setUp()
_UpperCamelCase = (
'''<s> <pad> </s> <unk> n s t ə l a i k d m ɛ ɾ e ɪ p o ɐ z ð f j v b ɹ ʁ ʊ iː r w ʌ u ɡ æ aɪ ʃ h ɔ ɑː '''
'''ŋ ɚ eɪ β uː y ɑ̃ oʊ ᵻ eː θ aʊ ts oː ɔ̃ ɣ ɜ ɑ dʒ əl x ɜː ç ʒ tʃ ɔː ɑːɹ ɛ̃ ʎ ɔːɹ ʋ aː ɕ œ ø oːɹ ɲ yː '''
'''ʔ iə i5 s. tɕ ?? nʲ ɛː œ̃ ɭ ɔø ʑ tʲ ɨ ɛɹ ts. rʲ ɪɹ ɭʲ i.5 ɔɪ q sʲ u5 ʊɹ iɜ a5 iɛ5 øː ʕ ja əɜ th ɑ5 '''
'''oɪ dʲ ə5 tɕh ts.h mʲ ɯ dʑ vʲ e̞ tʃʲ ei5 o5 onɡ5 ɑu5 iɑ5 ai5 aɪɚ kh ə1 ʐ i2 ʉ ħ t[ aɪə ʲ ju ə2 u2 oɜ '''
'''pː iɛɜ ou5 y5 uɜ tː uo5 d[ uoɜ tsh ɑɜ ɵ i̪5 uei5 ɟ aɜ ɑɨ i.ɜ eʊ o2 ɐ̃ ä pʲ kʲ n̩ ɒ ph ɑu2 uɨ əɪ ɫ ɬ '''
'''yɜ bʲ ɑ2 s̪ aiɜ χ ɐ̃ʊ̃ 1 ə4 yæɜ a2 ɨː t̪ iouɜ ũ onɡɜ aɨ iɛ2 ɔɨ ɑuɜ o̞ ei2 iou2 c kː y2 ɖ oe dˤ yɛɜ '''
'''əʊ S ɡʲ onɡ2 u" eiɜ ʈ ɯᵝ iou5 dZ r̝̊ i.2 tS s^ ʝ yə5 iɑɜ uə5 pf ɨu iɑ2 ou2 ər2 fʲ ai2 r̝ uəɜ ɳ əɨ '''
'''ua5 uɪ ɽ bː yu5 uo2 yɛ5 l̩ ɻ ərɜ ʂ i̪2 ouɜ uaɜ a. a.ː yæ5 dː r̩ ee ɪu ər5 i̪ ɜ æi u: i.ː t^ o1 ɪ^ '''
'''ai ueiɜ æː ɛɪ eə i. ɴ ie ua2 ɑ1 o4 tʃː o: ɑ: u1 N i̪1 au yæ2 u. qː yəɜ y: kʰ tʃʰ iʊ sx õ uo tʰ '''
'''uai5 bʰ u.ː uə2 ʊə d^ s̪ː yiɜ dʰ r. oe: i1 ɟː yu2 nʲʲ i̪4 uei2 tsʲ ɸ ĩ ɑ4 t̪ː eɑ u4 e: tsː ʈʰ ɡʰ '''
'''ɯɯ dʒʲ ʂʲ X ɵː uaiɜ tɕʲ ã t^ː ẽː yɛ2 cː i.1 ɛʊ dˤdˤ dʒː i4 ɡː yi ɕʲ ɟʰ pʰ dʑʲ yuɜ ua1 ua4 æiː ɐɐ '''
'''ui iou1 ʊː a1 iou4 cʰ iɛ1 yə2 ɖʰ ẽ ʒʲ ää ər4 iːː ɪː iɑ1 ər1 œː øi ɪuː cʰcʰ əː1 iː1 ũ kʰː o̞o̞ xʲ '''
'''ou1 iɛ4 e̞e̞ y1 dzː dʲʲ dʰː ɯᵝɯᵝ lː uo1 i.4 i: yɛ5ʲ a4'''
).split(''' ''')
_UpperCamelCase = dict(zip(__a , range(len(__a))))
_UpperCamelCase = {'''pad_token''': '''<pad>''', '''unk_token''': '''<unk>''', '''bos_token''': '''<s>''', '''eos_token''': '''</s>'''}
_UpperCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''])
with open(self.vocab_file , '''w''' , encoding='''utf-8''') as fp:
fp.write(json.dumps(__a) + '''\n''')
def UpperCAmelCase ( self , __a , __a=False , __a=20 , __a=5) -> Tuple[str, list]:
'''simple docstring'''
_UpperCamelCase = [(i, tokenizer.decode([i] , clean_up_tokenization_spaces=__a)) for i in range(len(__a))]
_UpperCamelCase = list(filter(lambda __a: [t[0]] == tokenizer.encode(t[1] , do_phonemize=__a) , __a))
if max_length is not None and len(__a) > max_length:
_UpperCamelCase = toks[:max_length]
if min_length is not None and len(__a) < min_length and len(__a) > 0:
while len(__a) < min_length:
_UpperCamelCase = toks + toks
# toks_str = [t[1] for t in toks]
_UpperCamelCase = [t[0] for t in toks]
# Ensure consistency
_UpperCamelCase = tokenizer.decode(__a , clean_up_tokenization_spaces=__a)
if " " not in output_txt and len(__a) > 1:
_UpperCamelCase = (
tokenizer.decode([toks_ids[0]] , clean_up_tokenization_spaces=__a)
+ ''' '''
+ tokenizer.decode(toks_ids[1:] , clean_up_tokenization_spaces=__a)
)
if with_prefix_space:
_UpperCamelCase = ''' ''' + output_txt
_UpperCamelCase = tokenizer.encode(__a , add_special_tokens=__a)
return output_txt, output_ids
def UpperCAmelCase ( self , **__a) -> Tuple:
'''simple docstring'''
kwargs.update(self.special_tokens_map)
return WavaVecaPhonemeCTCTokenizer.from_pretrained(self.tmpdirname , **__a)
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.tokenizer_class.from_pretrained('''facebook/wav2vec2-lv-60-espeak-cv-ft''')
# check adding a single token
tokenizer.add_tokens('''xxx''')
_UpperCamelCase = tokenizer('''m xxx ɪ''' , do_phonemize=__a).input_ids
self.assertEqual(__a , [13, 3_92, 17]) # xxx should be last token
tokenizer.add_tokens(['''aaa''', '''bbb''', '''ccc'''])
_UpperCamelCase = tokenizer('''m aaa ɪ ccc''' , do_phonemize=__a).input_ids
self.assertEqual(__a , [13, 3_93, 17, 3_95]) # aaa and ccc should be after xxx and 2 after aaa
_UpperCamelCase = tokenizer('''maɪ c''' , do_phonemize=__a).input_ids
self.assertEqual(__a , [3, 2_00]) # mai should be <unk> (=3)
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
_UpperCamelCase = self.tokenizer_class.from_pretrained('''facebook/wav2vec2-lv-60-espeak-cv-ft''')
_UpperCamelCase = '''Hello how are you'''
_UpperCamelCase = tokenizer.phonemize(__a , phonemizer_lang='''en-us''')
self.assertEqual(__a , '''h ə l oʊ h aʊ ɑːɹ j uː''')
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
_UpperCamelCase = self.tokenizer_class.from_pretrained('''facebook/wav2vec2-lv-60-espeak-cv-ft''')
_UpperCamelCase = '''Hello how are you'''
_UpperCamelCase = tokenizer.phonemize(__a , phonemizer_lang='''en-us''')
self.assertEqual(tokenizer(__a).input_ids , tokenizer(__a , do_phonemize=__a).input_ids)
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
_UpperCamelCase = self.tokenizer_class.from_pretrained('''facebook/wav2vec2-lv-60-espeak-cv-ft''')
_UpperCamelCase = '''Hello how are you'''
_UpperCamelCase = tokenizer.phonemize(__a , phonemizer_lang='''en-us''')
_UpperCamelCase = tokenizer.decode(tokenizer(__a).input_ids)
self.assertEqual(__a , __a)
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
_UpperCamelCase = self.tokenizer_class.from_pretrained('''facebook/wav2vec2-lv-60-espeak-cv-ft''')
_UpperCamelCase = [
[11, 5, 15, tokenizer.pad_token_id, 15, 8, 98],
[24, 22, 5, 24, 22, 5, 77],
]
_UpperCamelCase = tokenizer.decode(sample_ids[0])
_UpperCamelCase = tokenizer.batch_decode(__a)
self.assertEqual(__a , batch_tokens[0])
self.assertEqual(__a , ['''k s ɾ ɾ l ɭʲ''', '''j ð s j ð s oːɹ'''])
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = self.tokenizer_class.from_pretrained(
'''facebook/wav2vec2-lv-60-espeak-cv-ft''' , word_delimiter_token='''|''')
tokenizer.add_tokens('''|''')
_UpperCamelCase = '''Hello how are you'''
_UpperCamelCase = tokenizer.phonemize(__a , phonemizer_lang='''en-us''')
self.assertEqual(__a , '''h ə l oʊ | h aʊ | ɑːɹ | j uː |''')
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = self.tokenizer_class.from_pretrained(
'''facebook/wav2vec2-lv-60-espeak-cv-ft''' , word_delimiter_token='''|''')
tokenizer.add_tokens('''|''')
_UpperCamelCase = '''Hello how are you'''
_UpperCamelCase = tokenizer.phonemize(__a , phonemizer_lang='''en-us''')
self.assertEqual(tokenizer(__a).input_ids , tokenizer(__a , do_phonemize=__a).input_ids)
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.tokenizer_class.from_pretrained(
'''facebook/wav2vec2-lv-60-espeak-cv-ft''' , word_delimiter_token='''|''')
tokenizer.add_tokens('''|''')
# fmt: off
_UpperCamelCase = [
[11, 5, 15, tokenizer.pad_token_id, tokenizer.word_delimiter_token_id, 15, 8, tokenizer.word_delimiter_token_id, 98],
[tokenizer.word_delimiter_token_id, 24, 22, tokenizer.word_delimiter_token_id, 5, 24, 22, 5, 77],
]
# fmt: on
# decode with word_del_token filter
_UpperCamelCase = tokenizer.decode(sample_ids[0])
_UpperCamelCase = tokenizer.batch_decode(__a)
self.assertEqual(__a , batch_tokens[0])
self.assertEqual(__a , ['''k s ɾ ɾ l ɭʲ''', '''j ð s j ð s oːɹ'''])
# decode with no word_del_token filter
_UpperCamelCase = tokenizer.decode(sample_ids[0] , filter_word_delimiter_token=__a)
_UpperCamelCase = tokenizer.batch_decode(__a , filter_word_delimiter_token=__a)
self.assertEqual(__a , batch_tokens[0])
self.assertEqual(__a , ['''k s ɾ | ɾ l | ɭʲ''', '''| j ð | s j ð s oːɹ'''])
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = self.tokenizer_class.from_pretrained(
'''facebook/wav2vec2-lv-60-espeak-cv-ft''' , word_delimiter_token='''|''')
tokenizer.add_tokens('''|''')
_UpperCamelCase = '''Hello how are you'''
_UpperCamelCase = tokenizer.phonemize(__a , phonemizer_lang='''en-us''')
_UpperCamelCase = tokenizer.decode(tokenizer(__a).input_ids , filter_word_delimiter_token=__a)
self.assertEqual(__a , __a)
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase = self.tokenizer_class.from_pretrained(
'''facebook/wav2vec2-lv-60-espeak-cv-ft''' , word_delimiter_token='''|''')
tokenizer.add_tokens('''|''')
_UpperCamelCase = '''Hello how are you'''
_UpperCamelCase = tokenizer.phonemize(__a , phonemizer_lang='''en-us''')
_UpperCamelCase = tokenizer.decode(tokenizer(__a).input_ids , filter_word_delimiter_token=__a)
self.assertEqual(''' '''.join([p.strip() for p in phonemes.split(''' |''')]).strip() , __a)
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = self.tokenizer_class.from_pretrained(
'''facebook/wav2vec2-lv-60-espeak-cv-ft''' , word_delimiter_token=__a)
_UpperCamelCase = '''Hello how are you'''
_UpperCamelCase = tokenizer(__a , phonemizer_lang='''en-us''').input_ids
_UpperCamelCase = tokenizer(__a , phonemizer_lang='''fr-fr''').input_ids
self.assertNotEqual(__a , __a)
_UpperCamelCase = tokenizer.decode(__a)
_UpperCamelCase = tokenizer.decode(__a)
self.assertEqual(__a , '''h ə l oʊ h aʊ ɑːɹ j uː''')
self.assertEqual(__a , '''ɛ l o h aʊ a ʁ j u''')
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
_UpperCamelCase = self.tokenizer_class.from_pretrained('''facebook/wav2vec2-lv-60-espeak-cv-ft''')
_UpperCamelCase = '''Hello how Are you'''
_UpperCamelCase = '''hello how are you'''
_UpperCamelCase = tokenizer(__a).input_ids
_UpperCamelCase = tokenizer(__a).input_ids
self.assertEqual(__a , __a)
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.tokenizer_class.from_pretrained('''facebook/wav2vec2-lv-60-espeak-cv-ft''')
tokenizer.add_tokens(['''!''', '''?'''])
tokenizer.add_special_tokens({'''cls_token''': '''$$$'''})
# fmt: off
_UpperCamelCase = [
[11, 5, 15, tokenizer.pad_token_id, 15, 8, 98, 3_92, 3_92, 3_93, 3_92, 3_92, 3_93, 3_94, 3_94],
[24, 22, 5, 24, 22, 5, 77, tokenizer.pad_token_id, 3_94, 3_94],
]
# fmt: on
_UpperCamelCase = tokenizer.batch_decode(__a)
self.assertEqual(__a , ['''k s ɾ ɾ l ɭʲ!?!? $$$''', '''j ð s j ð s oːɹ $$$'''])
@staticmethod
def UpperCAmelCase ( __a , __a) -> Dict:
'''simple docstring'''
_UpperCamelCase = [d[key] for d in offsets]
return retrieved_list
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.get_tokenizer(word_delimiter_token='''|''')
tokenizer.add_tokens('''|''')
# fmt: off
# ksssɾɾ|ɾɾ<pad>ɾɾ|<pad>ɾlll|ɭʲ -> k s ɾ ɾ | ɾ l | ɭʲ"
_UpperCamelCase = [11, 5, 5, 5, 15, 15, tokenizer.pad_token_id, 15, 15, tokenizer.word_delimiter_token_id, tokenizer.pad_token_id, 15, 8, 8, 8, tokenizer.word_delimiter_token_id, 98]
# fmt: on
_UpperCamelCase = tokenizer.decode(__a , output_char_offsets=__a , filter_word_delimiter_token=__a)
# check Wav2Vec2CTCTokenizerOutput keys for char
self.assertEqual(len(outputs.keys()) , 2)
self.assertTrue('''text''' in outputs)
self.assertTrue('''char_offsets''' in outputs)
self.assertTrue(isinstance(__a , __a))
# check that order of chars is correct and identical for both outputs
self.assertEqual(''' '''.join(self.get_from_offsets(outputs['''char_offsets'''] , '''char''')) , outputs.text)
self.assertListEqual(
self.get_from_offsets(outputs['''char_offsets'''] , '''char''') , ['''k''', '''s''', '''ɾ''', '''ɾ''', '''|''', '''ɾ''', '''l''', '''|''', '''ɭʲ'''])
# check that offsets are actually correct for char
# 0-1 is 11, 1-4 is 5, 4-6 is first 15, 6-7 is <pad> (thus not shown), 7-9 is second 15, 9-10 is word_delimiter_token,
# 10-11 is <pad> (thus not shown), 11-12 is third 15, 12-15 is 8, 15-16 is word_delimiter_token, 16-17 is 98
self.assertListEqual(
self.get_from_offsets(outputs['''char_offsets'''] , '''start_offset''') , [0, 1, 4, 7, 9, 11, 12, 15, 16])
self.assertListEqual(
self.get_from_offsets(outputs['''char_offsets'''] , '''end_offset''') , [1, 4, 6, 9, 10, 12, 15, 16, 17])
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
_UpperCamelCase = self.get_tokenizer(word_delimiter_token='''|''')
def check_list_tuples_equal(__a , __a):
self.assertTrue(isinstance(__a , __a))
self.assertTrue(isinstance(outputs_list[0] , __a))
# transform list to ModelOutput
_UpperCamelCase = WavaVecaPhonemeCTCTokenizerOutput(
{k: [d[k] for d in outputs_list] for k in outputs_list[0]})
self.assertListEqual(outputs_batch['''text'''] , outputs_batch_a['''text'''])
def recursive_check(__a , __a):
if isinstance(__a , __a):
[recursive_check(__a , __a) for la, la in zip(__a , __a)]
self.assertEqual(__a , __a)
if "char_offsets" in outputs_batch:
recursive_check(outputs_batch['''char_offsets'''] , outputs_batch_a['''char_offsets'''])
# fmt: off
_UpperCamelCase = [
[11, 5, 15, tokenizer.pad_token_id, 15, 4, 8, 98, 32, 32, 32, 32, 4, 33, tokenizer.word_delimiter_token_id, 32, 32, 33, 34, 34],
[24, 22, 5, tokenizer.word_delimiter_token_id, tokenizer.word_delimiter_token_id, 24, 22, 22, 22, 4, 5, 77, tokenizer.pad_token_id, 22, 22, 4, 34, 34, 34, 34],
]
# fmt: on
# We assume that `decode` works as expected. All we will check now is
# the output type is correct and the output is identical to `decode`
# char
_UpperCamelCase = tokenizer.batch_decode(__a , output_char_offsets=__a)
_UpperCamelCase = [tokenizer.decode(__a , output_char_offsets=__a) for ids in sample_ids]
check_list_tuples_equal(__a , __a)
@unittest.skip('''Wav2Vec2PhonemeTokenizer always lower cases letters to correctly map to phonemes''')
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
pass
@unittest.skip('''Wav2Vec2PhonemeTokenizer always puts spaces between phonemes''')
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
pass
@unittest.skip('''encodes to text to ids, but decodes ids to phonemes -> not possible to have internal consistency''')
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
pass
@unittest.skip('''Wav2Vec2PhonemeModel has no max model length => no testing''')
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
pass
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
_UpperCamelCase = self.get_tokenizers(do_lower_case=__a)
for tokenizer in tokenizers:
with self.subTest(F'''{tokenizer.__class__.__name__}'''):
_UpperCamelCase = tokenizer.vocab_size
_UpperCamelCase = len(__a)
self.assertNotEqual(__a , 0)
# We usually have added tokens from the start in tests because our vocab fixtures are
# smaller than the original vocabs - let's not assert this
# self.assertEqual(vocab_size, all_size)
_UpperCamelCase = ['''aaaaa bbbbbb''', '''cccccccccdddddddd''']
_UpperCamelCase = tokenizer.add_tokens(__a)
_UpperCamelCase = tokenizer.vocab_size
_UpperCamelCase = len(__a)
self.assertNotEqual(__a , 0)
self.assertEqual(__a , __a)
self.assertEqual(__a , len(__a))
self.assertEqual(__a , all_size + len(__a))
_UpperCamelCase = tokenizer.encode('''aaaaa bbbbbb low cccccccccdddddddd l''' , add_special_tokens=__a)
self.assertGreaterEqual(len(__a) , 4)
self.assertGreater(tokens[0] , tokenizer.vocab_size - 1)
self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1)
_UpperCamelCase = {'''eos_token''': '''>>>>|||<||<<|<<''', '''pad_token''': '''<<<<<|||>|>>>>|>'''}
_UpperCamelCase = tokenizer.add_special_tokens(__a)
_UpperCamelCase = tokenizer.vocab_size
_UpperCamelCase = len(__a)
self.assertNotEqual(__a , 0)
self.assertEqual(__a , __a)
self.assertEqual(__a , len(__a))
self.assertEqual(__a , all_size_a + len(__a))
_UpperCamelCase = tokenizer.encode(
'''>>>>|||<||<<|<< aaaaabbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l''' , add_special_tokens=__a)
self.assertGreaterEqual(len(__a) , 6)
self.assertGreater(tokens[0] , tokenizer.vocab_size - 1)
self.assertGreater(tokens[0] , tokens[1])
self.assertGreater(tokens[-3] , tokenizer.vocab_size - 1)
self.assertGreater(tokens[-3] , tokens[-4])
self.assertEqual(tokens[0] , tokenizer.eos_token_id)
self.assertEqual(tokens[-3] , tokenizer.pad_token_id)
@unittest.skip('''The tokenizer shouldn\'t be used to encode input IDs (except for labels), only to decode.''')
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
pass
@unittest.skip('''The tokenizer shouldn\'t be used to encode input IDs (except for labels), only to decode.''')
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
pass
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = self.get_tokenizers(fast=__a , do_lower_case=__a)
for tokenizer in tokenizers:
with self.subTest(F'''{tokenizer.__class__.__name__}'''):
_UpperCamelCase = ['''ð''', '''ɪ''', '''s''', '''ɪ''', '''z''', '''ɐ''', '''t''', '''ɛ''', '''k''', '''s''', '''t''']
_UpperCamelCase = tokenizer.convert_tokens_to_string(__a)
self.assertIsInstance(output['''text'''] , __a)
| 711 |
"""simple docstring"""
import json
import sys
def lowerCamelCase__ ( __snake_case, __snake_case ) -> Union[str, Any]:
"""simple docstring"""
with open(__snake_case, encoding='''utf-8''' ) as f:
_UpperCamelCase = json.load(__snake_case )
_UpperCamelCase = ['''<details>''', '''<summary>Show updated benchmarks!</summary>''', ''' ''']
for benchmark_name in sorted(__snake_case ):
_UpperCamelCase = results[benchmark_name]
_UpperCamelCase = benchmark_name.split('''/''' )[-1]
output_md.append(F'''### Benchmark: {benchmark_file_name}''' )
_UpperCamelCase = '''| metric |'''
_UpperCamelCase = '''|--------|'''
_UpperCamelCase = '''| new / old (diff) |'''
for metric_name in sorted(__snake_case ):
_UpperCamelCase = benchmark_res[metric_name]
_UpperCamelCase = metric_vals['''new''']
_UpperCamelCase = metric_vals.get('''old''', __snake_case )
_UpperCamelCase = metric_vals.get('''diff''', __snake_case )
_UpperCamelCase = F''' {new_val:f}''' if isinstance(__snake_case, (int, float) ) else '''None'''
if old_val is not None:
val_str += F''' / {old_val:f}''' if isinstance(__snake_case, (int, float) ) else "None"
if dif_val is not None:
val_str += F''' ({dif_val:f})''' if isinstance(__snake_case, (int, float) ) else "None"
title += " " + metric_name + " |"
lines += "---|"
value += val_str + " |"
output_md += [title, lines, value, " "]
output_md.append('''</details>''' )
with open(__snake_case, '''w''', encoding='''utf-8''' ) as f:
f.writelines('''\n'''.join(__snake_case ) )
if __name__ == "__main__":
_a = sys.argv[1]
_a = sys.argv[2]
format_json_to_md(input_json_file, output_md_file)
| 78 | 0 |
"""simple docstring"""
from collections.abc import Sequence
def lowerCamelCase__ ( __snake_case = None ) -> int:
"""simple docstring"""
if nums is None or not nums:
raise ValueError('''Input sequence should not be empty''' )
_UpperCamelCase = nums[0]
for i in range(1, len(__snake_case ) ):
_UpperCamelCase = nums[i]
_UpperCamelCase = max(__snake_case, ans + num, __snake_case )
return ans
if __name__ == "__main__":
import doctest
doctest.testmod()
# Try on a sample input from the user
_a = int(input("""Enter number of elements : """).strip())
_a = list(map(int, input("""\nEnter the numbers : """).strip().split()))[:n]
print(max_subsequence_sum(array))
| 712 |
"""simple docstring"""
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()
_a = logging.get_logger(__name__)
def lowerCamelCase__ ( __snake_case, __snake_case=False ) -> Tuple:
"""simple docstring"""
_UpperCamelCase = []
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"
_UpperCamelCase = [(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 lowerCamelCase__ ( __snake_case, __snake_case, __snake_case=False ) -> str:
"""simple docstring"""
for i in range(config.num_hidden_layers ):
if base_model:
_UpperCamelCase = ''''''
else:
_UpperCamelCase = '''vit.'''
# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
_UpperCamelCase = state_dict.pop(F'''blocks.{i}.attn.qkv.weight''' )
_UpperCamelCase = state_dict.pop(F'''blocks.{i}.attn.qkv.bias''' )
# next, add query, keys and values (in that order) to the state dict
_UpperCamelCase = in_proj_weight[
: config.hidden_size, :
]
_UpperCamelCase = in_proj_bias[: config.hidden_size]
_UpperCamelCase = in_proj_weight[
config.hidden_size : config.hidden_size * 2, :
]
_UpperCamelCase = in_proj_bias[
config.hidden_size : config.hidden_size * 2
]
_UpperCamelCase = in_proj_weight[
-config.hidden_size :, :
]
_UpperCamelCase = in_proj_bias[-config.hidden_size :]
def lowerCamelCase__ ( __snake_case ) -> Dict:
"""simple docstring"""
_UpperCamelCase = ['''head.weight''', '''head.bias''']
for k in ignore_keys:
state_dict.pop(__snake_case, __snake_case )
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> Any:
"""simple docstring"""
_UpperCamelCase = dct.pop(__snake_case )
_UpperCamelCase = val
def lowerCamelCase__ ( ) -> Dict:
"""simple docstring"""
_UpperCamelCase = '''http://images.cocodataset.org/val2017/000000039769.jpg'''
_UpperCamelCase = Image.open(requests.get(__snake_case, stream=__snake_case ).raw )
return im
@torch.no_grad()
def lowerCamelCase__ ( __snake_case, __snake_case ) -> Union[str, Any]:
"""simple docstring"""
_UpperCamelCase = ViTConfig()
_UpperCamelCase = False
# dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size
if vit_name[-5:] == "in21k":
_UpperCamelCase = True
_UpperCamelCase = int(vit_name[-12:-10] )
_UpperCamelCase = int(vit_name[-9:-6] )
else:
_UpperCamelCase = 10_00
_UpperCamelCase = '''huggingface/label-files'''
_UpperCamelCase = '''imagenet-1k-id2label.json'''
_UpperCamelCase = json.load(open(hf_hub_download(__snake_case, __snake_case, repo_type='''dataset''' ), '''r''' ) )
_UpperCamelCase = {int(__snake_case ): v for k, v in idalabel.items()}
_UpperCamelCase = idalabel
_UpperCamelCase = {v: k for k, v in idalabel.items()}
_UpperCamelCase = int(vit_name[-6:-4] )
_UpperCamelCase = int(vit_name[-3:] )
# size of the architecture
if "deit" in vit_name:
if vit_name[9:].startswith('''tiny''' ):
_UpperCamelCase = 1_92
_UpperCamelCase = 7_68
_UpperCamelCase = 12
_UpperCamelCase = 3
elif vit_name[9:].startswith('''small''' ):
_UpperCamelCase = 3_84
_UpperCamelCase = 15_36
_UpperCamelCase = 12
_UpperCamelCase = 6
else:
pass
else:
if vit_name[4:].startswith('''small''' ):
_UpperCamelCase = 7_68
_UpperCamelCase = 23_04
_UpperCamelCase = 8
_UpperCamelCase = 8
elif vit_name[4:].startswith('''base''' ):
pass
elif vit_name[4:].startswith('''large''' ):
_UpperCamelCase = 10_24
_UpperCamelCase = 40_96
_UpperCamelCase = 24
_UpperCamelCase = 16
elif vit_name[4:].startswith('''huge''' ):
_UpperCamelCase = 12_80
_UpperCamelCase = 51_20
_UpperCamelCase = 32
_UpperCamelCase = 16
# load original model from timm
_UpperCamelCase = timm.create_model(__snake_case, pretrained=__snake_case )
timm_model.eval()
# load state_dict of original model, remove and rename some keys
_UpperCamelCase = timm_model.state_dict()
if base_model:
remove_classification_head_(__snake_case )
_UpperCamelCase = create_rename_keys(__snake_case, __snake_case )
for src, dest in rename_keys:
rename_key(__snake_case, __snake_case, __snake_case )
read_in_q_k_v(__snake_case, __snake_case, __snake_case )
# load HuggingFace model
if vit_name[-5:] == "in21k":
_UpperCamelCase = ViTModel(__snake_case ).eval()
else:
_UpperCamelCase = ViTForImageClassification(__snake_case ).eval()
model.load_state_dict(__snake_case )
# Check outputs on an image, prepared by ViTImageProcessor/DeiTImageProcessor
if "deit" in vit_name:
_UpperCamelCase = DeiTImageProcessor(size=config.image_size )
else:
_UpperCamelCase = ViTImageProcessor(size=config.image_size )
_UpperCamelCase = image_processor(images=prepare_img(), return_tensors='''pt''' )
_UpperCamelCase = encoding['''pixel_values''']
_UpperCamelCase = model(__snake_case )
if base_model:
_UpperCamelCase = timm_model.forward_features(__snake_case )
assert timm_pooled_output.shape == outputs.pooler_output.shape
assert torch.allclose(__snake_case, outputs.pooler_output, atol=1e-3 )
else:
_UpperCamelCase = timm_model(__snake_case )
assert timm_logits.shape == outputs.logits.shape
assert torch.allclose(__snake_case, outputs.logits, atol=1e-3 )
Path(__snake_case ).mkdir(exist_ok=__snake_case )
print(F'''Saving model {vit_name} to {pytorch_dump_folder_path}''' )
model.save_pretrained(__snake_case )
print(F'''Saving image processor to {pytorch_dump_folder_path}''' )
image_processor.save_pretrained(__snake_case )
if __name__ == "__main__":
_a = 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."""
)
_a = parser.parse_args()
convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path)
| 78 | 0 |
"""simple docstring"""
import gc
import unittest
import torch
from parameterized import parameterized
from diffusers import AutoencoderKL
from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import enable_full_determinism
from .test_modeling_common import ModelTesterMixin, UNetTesterMixin
enable_full_determinism()
class a_( lowerCamelCase , lowerCamelCase , unittest.TestCase ):
lowercase__ = AutoencoderKL
lowercase__ = 'sample'
lowercase__ = 1E-2
@property
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
_UpperCamelCase = 4
_UpperCamelCase = 3
_UpperCamelCase = (32, 32)
_UpperCamelCase = floats_tensor((batch_size, num_channels) + sizes).to(__a)
return {"sample": image}
@property
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
return (3, 32, 32)
@property
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
return (3, 32, 32)
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
_UpperCamelCase = {
'''block_out_channels''': [32, 64],
'''in_channels''': 3,
'''out_channels''': 3,
'''down_block_types''': ['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''],
'''up_block_types''': ['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''],
'''latent_channels''': 4,
}
_UpperCamelCase = self.dummy_input
return init_dict, inputs_dict
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
pass
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
pass
@unittest.skipIf(torch_device == '''mps''' , '''Gradient checkpointing skipped on MPS''')
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase = self.prepare_init_args_and_inputs_for_common()
_UpperCamelCase = self.model_class(**__a)
model.to(__a)
assert not model.is_gradient_checkpointing and model.training
_UpperCamelCase = model(**__a).sample
# run the backwards pass on the model. For backwards pass, for simplicity purpose,
# we won't calculate the loss and rather backprop on out.sum()
model.zero_grad()
_UpperCamelCase = torch.randn_like(__a)
_UpperCamelCase = (out - labels).mean()
loss.backward()
# re-instantiate the model now enabling gradient checkpointing
_UpperCamelCase = self.model_class(**__a)
# clone model
model_a.load_state_dict(model.state_dict())
model_a.to(__a)
model_a.enable_gradient_checkpointing()
assert model_a.is_gradient_checkpointing and model_a.training
_UpperCamelCase = model_a(**__a).sample
# run the backwards pass on the model. For backwards pass, for simplicity purpose,
# we won't calculate the loss and rather backprop on out.sum()
model_a.zero_grad()
_UpperCamelCase = (out_a - labels).mean()
loss_a.backward()
# compare the output and parameters gradients
self.assertTrue((loss - loss_a).abs() < 1e-5)
_UpperCamelCase = dict(model.named_parameters())
_UpperCamelCase = dict(model_a.named_parameters())
for name, param in named_params.items():
self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5e-5))
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase = AutoencoderKL.from_pretrained('''fusing/autoencoder-kl-dummy''' , output_loading_info=__a)
self.assertIsNotNone(__a)
self.assertEqual(len(loading_info['''missing_keys''']) , 0)
model.to(__a)
_UpperCamelCase = model(**self.dummy_input)
assert image is not None, "Make sure output is not None"
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = AutoencoderKL.from_pretrained('''fusing/autoencoder-kl-dummy''')
_UpperCamelCase = model.to(__a)
model.eval()
if torch_device == "mps":
_UpperCamelCase = torch.manual_seed(0)
else:
_UpperCamelCase = torch.Generator(device=__a).manual_seed(0)
_UpperCamelCase = torch.randn(
1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0) , )
_UpperCamelCase = image.to(__a)
with torch.no_grad():
_UpperCamelCase = model(__a , sample_posterior=__a , generator=__a).sample
_UpperCamelCase = output[0, -1, -3:, -3:].flatten().cpu()
# Since the VAE Gaussian prior's generator is seeded on the appropriate device,
# the expected output slices are not the same for CPU and GPU.
if torch_device == "mps":
_UpperCamelCase = torch.tensor(
[
-4.0_078e-01,
-3.8_323e-04,
-1.2_681e-01,
-1.1_462e-01,
2.0_095e-01,
1.0_893e-01,
-8.8_247e-02,
-3.0_361e-01,
-9.8_644e-03,
])
elif torch_device == "cpu":
_UpperCamelCase = torch.tensor(
[-0.1352, 0.0878, 0.0419, -0.0818, -0.1069, 0.0688, -0.1458, -0.4446, -0.0026])
else:
_UpperCamelCase = torch.tensor(
[-0.2421, 0.4642, 0.2507, -0.0438, 0.0682, 0.3160, -0.2018, -0.0727, 0.2485])
self.assertTrue(torch_all_close(__a , __a , rtol=1e-2))
@slow
class a_( unittest.TestCase ):
def UpperCAmelCase ( self , __a , __a) -> Optional[Any]:
'''simple docstring'''
return F'''gaussian_noise_s={seed}_shape={"_".join([str(__a) for s in shape])}.npy'''
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def UpperCAmelCase ( self , __a=0 , __a=(4, 3, 5_12, 5_12) , __a=False) -> str:
'''simple docstring'''
_UpperCamelCase = torch.floataa if fpaa else torch.floataa
_UpperCamelCase = torch.from_numpy(load_hf_numpy(self.get_file_format(__a , __a))).to(__a).to(__a)
return image
def UpperCAmelCase ( self , __a="CompVis/stable-diffusion-v1-4" , __a=False) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = '''fp16''' if fpaa else None
_UpperCamelCase = torch.floataa if fpaa else torch.floataa
_UpperCamelCase = AutoencoderKL.from_pretrained(
__a , subfolder='''vae''' , torch_dtype=__a , revision=__a , )
model.to(__a).eval()
return model
def UpperCAmelCase ( self , __a=0) -> Tuple:
'''simple docstring'''
if torch_device == "mps":
return torch.manual_seed(__a)
return torch.Generator(device=__a).manual_seed(__a)
@parameterized.expand(
[
# fmt: off
[33, [-0.1603, 0.9878, -0.0495, -0.0790, -0.2709, 0.8375, -0.2060, -0.0824], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]],
[47, [-0.2376, 0.1168, 0.1332, -0.4840, -0.2508, -0.0791, -0.0493, -0.4089], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]],
# fmt: on
])
def UpperCAmelCase ( self , __a , __a , __a) -> Any:
'''simple docstring'''
_UpperCamelCase = self.get_sd_vae_model()
_UpperCamelCase = self.get_sd_image(__a)
_UpperCamelCase = self.get_generator(__a)
with torch.no_grad():
_UpperCamelCase = model(__a , generator=__a , sample_posterior=__a).sample
assert sample.shape == image.shape
_UpperCamelCase = sample[-1, -2:, -2:, :2].flatten().float().cpu()
_UpperCamelCase = torch.tensor(expected_slice_mps if torch_device == '''mps''' else expected_slice)
assert torch_all_close(__a , __a , atol=3e-3)
@parameterized.expand(
[
# fmt: off
[33, [-0.0513, 0.0289, 1.3799, 0.2166, -0.2573, -0.0871, 0.5103, -0.0999]],
[47, [-0.4128, -0.1320, -0.3704, 0.1965, -0.4116, -0.2332, -0.3340, 0.2247]],
# fmt: on
])
@require_torch_gpu
def UpperCAmelCase ( self , __a , __a) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = self.get_sd_vae_model(fpaa=__a)
_UpperCamelCase = self.get_sd_image(__a , fpaa=__a)
_UpperCamelCase = self.get_generator(__a)
with torch.no_grad():
_UpperCamelCase = model(__a , generator=__a , sample_posterior=__a).sample
assert sample.shape == image.shape
_UpperCamelCase = sample[-1, -2:, :2, -2:].flatten().float().cpu()
_UpperCamelCase = torch.tensor(__a)
assert torch_all_close(__a , __a , atol=1e-2)
@parameterized.expand(
[
# fmt: off
[33, [-0.1609, 0.9866, -0.0487, -0.0777, -0.2716, 0.8368, -0.2055, -0.0814], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]],
[47, [-0.2377, 0.1147, 0.1333, -0.4841, -0.2506, -0.0805, -0.0491, -0.4085], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]],
# fmt: on
])
def UpperCAmelCase ( self , __a , __a , __a) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = self.get_sd_vae_model()
_UpperCamelCase = self.get_sd_image(__a)
with torch.no_grad():
_UpperCamelCase = model(__a).sample
assert sample.shape == image.shape
_UpperCamelCase = sample[-1, -2:, -2:, :2].flatten().float().cpu()
_UpperCamelCase = torch.tensor(expected_slice_mps if torch_device == '''mps''' else expected_slice)
assert torch_all_close(__a , __a , atol=3e-3)
@parameterized.expand(
[
# fmt: off
[13, [-0.2051, -0.1803, -0.2311, -0.2114, -0.3292, -0.3574, -0.2953, -0.3323]],
[37, [-0.2632, -0.2625, -0.2199, -0.2741, -0.4539, -0.4990, -0.3720, -0.4925]],
# fmt: on
])
@require_torch_gpu
def UpperCAmelCase ( self , __a , __a) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = self.get_sd_vae_model()
_UpperCamelCase = self.get_sd_image(__a , shape=(3, 4, 64, 64))
with torch.no_grad():
_UpperCamelCase = model.decode(__a).sample
assert list(sample.shape) == [3, 3, 5_12, 5_12]
_UpperCamelCase = sample[-1, -2:, :2, -2:].flatten().cpu()
_UpperCamelCase = torch.tensor(__a)
assert torch_all_close(__a , __a , atol=1e-3)
@parameterized.expand(
[
# fmt: off
[27, [-0.0369, 0.0207, -0.0776, -0.0682, -0.1747, -0.1930, -0.1465, -0.2039]],
[16, [-0.1628, -0.2134, -0.2747, -0.2642, -0.3774, -0.4404, -0.3687, -0.4277]],
# fmt: on
])
@require_torch_gpu
def UpperCAmelCase ( self , __a , __a) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = self.get_sd_vae_model(fpaa=__a)
_UpperCamelCase = self.get_sd_image(__a , shape=(3, 4, 64, 64) , fpaa=__a)
with torch.no_grad():
_UpperCamelCase = model.decode(__a).sample
assert list(sample.shape) == [3, 3, 5_12, 5_12]
_UpperCamelCase = sample[-1, -2:, :2, -2:].flatten().float().cpu()
_UpperCamelCase = torch.tensor(__a)
assert torch_all_close(__a , __a , atol=5e-3)
@parameterized.expand([(13,), (16,), (27,)])
@require_torch_gpu
@unittest.skipIf(not is_xformers_available() , reason='''xformers is not required when using PyTorch 2.0.''')
def UpperCAmelCase ( self , __a) -> str:
'''simple docstring'''
_UpperCamelCase = self.get_sd_vae_model(fpaa=__a)
_UpperCamelCase = self.get_sd_image(__a , shape=(3, 4, 64, 64) , fpaa=__a)
with torch.no_grad():
_UpperCamelCase = model.decode(__a).sample
model.enable_xformers_memory_efficient_attention()
with torch.no_grad():
_UpperCamelCase = model.decode(__a).sample
assert list(sample.shape) == [3, 3, 5_12, 5_12]
assert torch_all_close(__a , __a , atol=1e-1)
@parameterized.expand([(13,), (16,), (37,)])
@require_torch_gpu
@unittest.skipIf(not is_xformers_available() , reason='''xformers is not required when using PyTorch 2.0.''')
def UpperCAmelCase ( self , __a) -> int:
'''simple docstring'''
_UpperCamelCase = self.get_sd_vae_model()
_UpperCamelCase = self.get_sd_image(__a , shape=(3, 4, 64, 64))
with torch.no_grad():
_UpperCamelCase = model.decode(__a).sample
model.enable_xformers_memory_efficient_attention()
with torch.no_grad():
_UpperCamelCase = model.decode(__a).sample
assert list(sample.shape) == [3, 3, 5_12, 5_12]
assert torch_all_close(__a , __a , atol=1e-2)
@parameterized.expand(
[
# fmt: off
[33, [-0.3001, 0.0918, -2.6984, -3.9720, -3.2099, -5.0353, 1.7338, -0.2065, 3.4267]],
[47, [-1.5030, -4.3871, -6.0355, -9.1157, -1.6661, -2.7853, 2.1607, -5.0823, 2.5633]],
# fmt: on
])
def UpperCAmelCase ( self , __a , __a) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = self.get_sd_vae_model()
_UpperCamelCase = self.get_sd_image(__a)
_UpperCamelCase = self.get_generator(__a)
with torch.no_grad():
_UpperCamelCase = model.encode(__a).latent_dist
_UpperCamelCase = dist.sample(generator=__a)
assert list(sample.shape) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]]
_UpperCamelCase = sample[0, -1, -3:, -3:].flatten().cpu()
_UpperCamelCase = torch.tensor(__a)
_UpperCamelCase = 3e-3 if torch_device != '''mps''' else 1e-2
assert torch_all_close(__a , __a , atol=__a)
| 713 |
"""simple docstring"""
import unittest
from transformers import AlbertConfig, is_torch_available
from transformers.models.auto import get_values
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 (
MODEL_FOR_PRETRAINING_MAPPING,
AlbertForMaskedLM,
AlbertForMultipleChoice,
AlbertForPreTraining,
AlbertForQuestionAnswering,
AlbertForSequenceClassification,
AlbertForTokenClassification,
AlbertModel,
)
from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST
class _UpperCAmelCase:
def __init__( self , __a , __a=13 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=99 , __a=16 , __a=36 , __a=6 , __a=6 , __a=6 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=5_12 , __a=16 , __a=2 , __a=0.02 , __a=3 , __a=4 , __a=None , ) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = parent
_UpperCamelCase = batch_size
_UpperCamelCase = seq_length
_UpperCamelCase = is_training
_UpperCamelCase = use_input_mask
_UpperCamelCase = use_token_type_ids
_UpperCamelCase = use_labels
_UpperCamelCase = vocab_size
_UpperCamelCase = embedding_size
_UpperCamelCase = hidden_size
_UpperCamelCase = num_hidden_layers
_UpperCamelCase = num_hidden_groups
_UpperCamelCase = num_attention_heads
_UpperCamelCase = intermediate_size
_UpperCamelCase = hidden_act
_UpperCamelCase = hidden_dropout_prob
_UpperCamelCase = attention_probs_dropout_prob
_UpperCamelCase = max_position_embeddings
_UpperCamelCase = type_vocab_size
_UpperCamelCase = type_sequence_label_size
_UpperCamelCase = initializer_range
_UpperCamelCase = num_labels
_UpperCamelCase = num_choices
_UpperCamelCase = scope
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size)
_UpperCamelCase = None
if self.use_input_mask:
_UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length])
_UpperCamelCase = None
if self.use_token_type_ids:
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size)
_UpperCamelCase = None
_UpperCamelCase = None
_UpperCamelCase = None
if self.use_labels:
_UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size)
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels)
_UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices)
_UpperCamelCase = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
return 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 , initializer_range=self.initializer_range , num_hidden_groups=self.num_hidden_groups , )
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = AlbertModel(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a , attention_mask=__a , token_type_ids=__a)
_UpperCamelCase = model(__a , token_type_ids=__a)
_UpperCamelCase = model(__a)
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))
self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = AlbertForPreTraining(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(
__a , attention_mask=__a , token_type_ids=__a , labels=__a , sentence_order_label=__a , )
self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size))
self.parent.assertEqual(result.sop_logits.shape , (self.batch_size, config.num_labels))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = AlbertForMaskedLM(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a , attention_mask=__a , token_type_ids=__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) -> Any:
'''simple docstring'''
_UpperCamelCase = AlbertForQuestionAnswering(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(
__a , attention_mask=__a , token_type_ids=__a , start_positions=__a , end_positions=__a , )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length))
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = self.num_labels
_UpperCamelCase = AlbertForSequenceClassification(__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.num_labels
_UpperCamelCase = AlbertForTokenClassification(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a)
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels))
def UpperCAmelCase ( self , __a , __a , __a , __a , __a , __a , __a) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = self.num_choices
_UpperCamelCase = AlbertForMultipleChoice(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = input_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous()
_UpperCamelCase = token_type_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous()
_UpperCamelCase = input_mask.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous()
_UpperCamelCase = model(
__a , attention_mask=__a , token_type_ids=__a , labels=__a , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices))
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = self.prepare_config_and_inputs()
(
(
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) ,
) = config_and_inputs
_UpperCamelCase = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
return config, inputs_dict
@require_torch
class _UpperCAmelCase( lowerCamelCase , lowerCamelCase , unittest.TestCase ):
lowercase__ = (
(
AlbertModel,
AlbertForPreTraining,
AlbertForMaskedLM,
AlbertForMultipleChoice,
AlbertForSequenceClassification,
AlbertForTokenClassification,
AlbertForQuestionAnswering,
)
if is_torch_available()
else ()
)
lowercase__ = (
{
'feature-extraction': AlbertModel,
'fill-mask': AlbertForMaskedLM,
'question-answering': AlbertForQuestionAnswering,
'text-classification': AlbertForSequenceClassification,
'token-classification': AlbertForTokenClassification,
'zero-shot': AlbertForSequenceClassification,
}
if is_torch_available()
else {}
)
lowercase__ = True
def UpperCAmelCase ( self , __a , __a , __a=False) -> List[str]:
'''simple docstring'''
_UpperCamelCase = super()._prepare_for_class(__a , __a , return_labels=__a)
if return_labels:
if model_class in get_values(__a):
_UpperCamelCase = torch.zeros(
(self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=__a)
_UpperCamelCase = torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=__a)
return inputs_dict
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = AlbertModelTester(self)
_UpperCamelCase = ConfigTester(self , config_class=__a , hidden_size=37)
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
self.config_tester.run_common_tests()
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__a)
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_pretraining(*__a)
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*__a)
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*__a)
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*__a)
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*__a)
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
_UpperCamelCase = type
self.model_tester.create_and_check_model(*__a)
@slow
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_UpperCamelCase = AlbertModel.from_pretrained(__a)
self.assertIsNotNone(__a)
@require_torch
class _UpperCAmelCase( unittest.TestCase ):
@slow
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = AlbertModel.from_pretrained('''albert-base-v2''')
_UpperCamelCase = torch.tensor([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]])
_UpperCamelCase = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
with torch.no_grad():
_UpperCamelCase = model(__a , attention_mask=__a)[0]
_UpperCamelCase = torch.Size((1, 11, 7_68))
self.assertEqual(output.shape , __a)
_UpperCamelCase = torch.tensor(
[[[-0.6513, 1.5035, -0.2766], [-0.6515, 1.5046, -0.2780], [-0.6512, 1.5049, -0.2784]]])
self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __a , atol=1e-4))
| 78 | 0 |
"""simple docstring"""
import unittest
from transformers import SPIECE_UNDERLINE, ReformerTokenizer, ReformerTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow
from transformers.utils import cached_property
from ...test_tokenization_common import TokenizerTesterMixin
_a = get_tests_dir("""fixtures/test_sentencepiece.model""")
@require_sentencepiece
@require_tokenizers
class _UpperCAmelCase( lowerCamelCase , unittest.TestCase ):
lowercase__ = ReformerTokenizer
lowercase__ = ReformerTokenizerFast
lowercase__ = True
lowercase__ = False
lowercase__ = True
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
super().setUp()
_UpperCamelCase = ReformerTokenizer(__a , keep_accents=__a)
tokenizer.save_pretrained(self.tmpdirname)
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase = '''<s>'''
_UpperCamelCase = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(__a) , __a)
self.assertEqual(self.get_tokenizer()._convert_id_to_token(__a) , __a)
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
_UpperCamelCase = list(self.get_tokenizer().get_vocab().keys())
self.assertEqual(vocab_keys[0] , '''<unk>''')
self.assertEqual(vocab_keys[1] , '''<s>''')
self.assertEqual(vocab_keys[-1] , '''j''')
self.assertEqual(len(__a) , 10_00)
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
self.assertEqual(self.get_tokenizer().vocab_size , 10_00)
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
if not self.test_rust_tokenizer:
return
_UpperCamelCase = self.get_tokenizer()
_UpperCamelCase = self.get_rust_tokenizer()
_UpperCamelCase = '''I was born in 92000, and this is falsé.'''
_UpperCamelCase = tokenizer.tokenize(__a)
_UpperCamelCase = rust_tokenizer.tokenize(__a)
self.assertListEqual(__a , __a)
_UpperCamelCase = tokenizer.encode(__a , add_special_tokens=__a)
_UpperCamelCase = rust_tokenizer.encode(__a , add_special_tokens=__a)
self.assertListEqual(__a , __a)
_UpperCamelCase = self.get_rust_tokenizer()
_UpperCamelCase = tokenizer.encode(__a)
_UpperCamelCase = rust_tokenizer.encode(__a)
self.assertListEqual(__a , __a)
def UpperCAmelCase ( self , __a=15) -> Optional[Any]:
'''simple docstring'''
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})'''):
_UpperCamelCase = self.rust_tokenizer_class.from_pretrained(__a , **__a)
# Simple input
_UpperCamelCase = '''This is a simple input'''
_UpperCamelCase = ['''This is a simple input 1''', '''This is a simple input 2''']
_UpperCamelCase = ('''This is a simple input''', '''This is a pair''')
_UpperCamelCase = [
('''This is a simple input 1''', '''This is a simple input 2'''),
('''This is a simple pair 1''', '''This is a simple pair 2'''),
]
# Simple input tests
self.assertRaises(__a , tokenizer_r.encode , __a , max_length=__a , padding='''max_length''')
# Simple input
self.assertRaises(__a , tokenizer_r.encode_plus , __a , max_length=__a , padding='''max_length''')
# Simple input
self.assertRaises(
__a , tokenizer_r.batch_encode_plus , __a , max_length=__a , padding='''max_length''' , )
# Pair input
self.assertRaises(__a , tokenizer_r.encode , __a , max_length=__a , padding='''max_length''')
# Pair input
self.assertRaises(__a , tokenizer_r.encode_plus , __a , max_length=__a , padding='''max_length''')
# Pair input
self.assertRaises(
__a , tokenizer_r.batch_encode_plus , __a , max_length=__a , padding='''max_length''' , )
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
pass
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
_UpperCamelCase = ReformerTokenizer(__a , keep_accents=__a)
_UpperCamelCase = tokenizer.tokenize('''This is a test''')
self.assertListEqual(__a , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''])
self.assertListEqual(
tokenizer.convert_tokens_to_ids(__a) , [2_85, 46, 10, 1_70, 3_82] , )
_UpperCamelCase = tokenizer.tokenize('''I was born in 92000, and this is falsé.''')
self.assertListEqual(
__a , [
SPIECE_UNDERLINE + '''I''',
SPIECE_UNDERLINE + '''was''',
SPIECE_UNDERLINE + '''b''',
'''or''',
'''n''',
SPIECE_UNDERLINE + '''in''',
SPIECE_UNDERLINE + '''''',
'''9''',
'''2''',
'''0''',
'''0''',
'''0''',
''',''',
SPIECE_UNDERLINE + '''and''',
SPIECE_UNDERLINE + '''this''',
SPIECE_UNDERLINE + '''is''',
SPIECE_UNDERLINE + '''f''',
'''al''',
'''s''',
'''é''',
'''.''',
] , )
_UpperCamelCase = tokenizer.convert_tokens_to_ids(__a)
self.assertListEqual(
__a , [8, 21, 84, 55, 24, 19, 7, 0, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 0, 4] , )
_UpperCamelCase = tokenizer.convert_ids_to_tokens(__a)
self.assertListEqual(
__a , [
SPIECE_UNDERLINE + '''I''',
SPIECE_UNDERLINE + '''was''',
SPIECE_UNDERLINE + '''b''',
'''or''',
'''n''',
SPIECE_UNDERLINE + '''in''',
SPIECE_UNDERLINE + '''''',
'''<unk>''',
'''2''',
'''0''',
'''0''',
'''0''',
''',''',
SPIECE_UNDERLINE + '''and''',
SPIECE_UNDERLINE + '''this''',
SPIECE_UNDERLINE + '''is''',
SPIECE_UNDERLINE + '''f''',
'''al''',
'''s''',
'''<unk>''',
'''.''',
] , )
@cached_property
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
return ReformerTokenizer.from_pretrained('''google/reformer-crime-and-punishment''')
@slow
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
_UpperCamelCase = '''Hello World!'''
_UpperCamelCase = [1_26, 32, 2_62, 1_52, 38, 72, 2_87]
self.assertListEqual(__a , self.big_tokenizer.encode(__a))
@slow
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = (
'''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will'''
''' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth'''
)
_UpperCamelCase = [
1_08,
2_65,
24,
1_11,
4,
2_58,
1_56,
35,
28,
2_75,
3,
2_59,
2_97,
2_60,
84,
4,
35,
1_10,
44,
8,
2_59,
91,
2_68,
21,
11,
2_09,
2_74,
1_09,
2_66,
2_77,
1_17,
86,
93,
3_15,
2_58,
2_78,
2_58,
2_77,
2_58,
0,
2_58,
2_88,
2_58,
3_19,
2_58,
0,
2_58,
0,
2_58,
0,
2_58,
0,
2_58,
2_87,
2_58,
3_15,
2_58,
2_89,
2_58,
2_78,
99,
2_69,
2_66,
2_62,
8,
2_59,
2_41,
4,
2_17,
2_30,
2_68,
2_66,
55,
1_68,
1_06,
75,
1_93,
2_66,
2_23,
27,
49,
26,
2_82,
25,
2_64,
2_99,
19,
26,
0,
2_58,
2_77,
1_17,
86,
93,
1_76,
1_83,
2_70,
11,
2_62,
42,
61,
2_65,
]
self.assertListEqual(__a , self.big_tokenizer.encode(__a))
@require_torch
@slow
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
import torch
from transformers import ReformerConfig, ReformerModel
# Build sequence
_UpperCamelCase = list(self.big_tokenizer.get_vocab().keys())[:10]
_UpperCamelCase = ''' '''.join(__a)
_UpperCamelCase = self.big_tokenizer.encode_plus(__a , return_tensors='''pt''')
_UpperCamelCase = self.big_tokenizer.batch_encode_plus([sequence, sequence] , return_tensors='''pt''')
_UpperCamelCase = ReformerConfig()
# The input gets padded during training so adjust the axial position encodings from the pretrained model value of (512, 1024)
_UpperCamelCase = encoded_sequence['''input_ids'''].shape
_UpperCamelCase = ReformerModel(__a)
# Reformer has config.vocab_size == tokenizer.vocab_size == len(tokenizer) - 1 = 320; len(tokenizer) is 321 (including a pad token with id 320)
assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size
with torch.no_grad():
model(**__a)
model(**__a)
@slow
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
_UpperCamelCase = {'''input_ids''': [[1_08, 2_65, 24, 1_11, 4, 2_58, 1_56, 7, 51, 2_79, 58, 7, 76, 25, 69, 2_78], [1_40, 2_43, 2_64, 1_34, 17, 2_67, 77, 2_63, 22, 2_62, 2_97, 2_58, 3_04, 1_77, 2_79, 2_66, 14, 89, 13, 35, 2_61, 2_99, 2_72, 1_37, 2_75, 2_78]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501
# fmt: on
# This tokenizer does not know some characters like ")".
# That is the reason why we use very simple texts here.
# Also see https://github.com/huggingface/transformers/pull/11737#issuecomment-850769064
_UpperCamelCase = [
'''This is a very simple sentence.''',
'''The quick brown fox jumps over the lazy dog.''',
]
self.tokenizer_integration_test_util(
expected_encoding=__a , model_name='''google/reformer-crime-and-punishment''' , revision='''0e6c3decb8211d49bf881013425dc8b0448b3f5a''' , padding=__a , sequences=__a , )
| 714 |
"""simple docstring"""
import os
from typing import BinaryIO, Optional, Union
import numpy as np
import pyarrow.parquet as pq
from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config
from ..features.features import FeatureType, _visit
from ..formatting import query_table
from ..packaged_modules import _PACKAGED_DATASETS_MODULES
from ..packaged_modules.parquet.parquet import Parquet
from ..utils import logging
from ..utils.typing import NestedDataStructureLike, PathLike
from .abc import AbstractDatasetReader
def lowerCamelCase__ ( __snake_case ) -> Optional[int]:
"""simple docstring"""
_UpperCamelCase = np.inf
def set_batch_size(__snake_case ) -> None:
nonlocal batch_size
if isinstance(__snake_case, __snake_case ):
_UpperCamelCase = min(__snake_case, config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS )
elif isinstance(__snake_case, __snake_case ):
_UpperCamelCase = min(__snake_case, config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS )
elif isinstance(__snake_case, __snake_case ) and feature.dtype == "binary":
_UpperCamelCase = min(__snake_case, config.PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS )
_visit(__snake_case, __snake_case )
return None if batch_size is np.inf else batch_size
class _UpperCAmelCase( lowerCamelCase ):
def __init__( self , __a , __a = None , __a = None , __a = None , __a = False , __a = False , __a = None , **__a , ) -> Dict:
'''simple docstring'''
super().__init__(
__a , split=__a , features=__a , cache_dir=__a , keep_in_memory=__a , streaming=__a , num_proc=__a , **__a , )
_UpperCamelCase = path_or_paths if isinstance(__a , __a) else {self.split: path_or_paths}
_UpperCamelCase = _PACKAGED_DATASETS_MODULES['''parquet'''][1]
_UpperCamelCase = Parquet(
cache_dir=__a , data_files=__a , features=__a , hash=__a , **__a , )
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
# Build iterable dataset
if self.streaming:
_UpperCamelCase = self.builder.as_streaming_dataset(split=self.split)
# Build regular (map-style) dataset
else:
_UpperCamelCase = None
_UpperCamelCase = None
_UpperCamelCase = None
_UpperCamelCase = None
self.builder.download_and_prepare(
download_config=__a , download_mode=__a , verification_mode=__a , base_path=__a , num_proc=self.num_proc , )
_UpperCamelCase = self.builder.as_dataset(
split=self.split , verification_mode=__a , in_memory=self.keep_in_memory)
return dataset
class _UpperCAmelCase:
def __init__( self , __a , __a , __a = None , **__a , ) -> Dict:
'''simple docstring'''
_UpperCamelCase = dataset
_UpperCamelCase = path_or_buf
_UpperCamelCase = batch_size or get_writer_batch_size(dataset.features)
_UpperCamelCase = parquet_writer_kwargs
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
_UpperCamelCase = self.batch_size if self.batch_size else config.DEFAULT_MAX_BATCH_SIZE
if isinstance(self.path_or_buf , (str, bytes, os.PathLike)):
with open(self.path_or_buf , '''wb+''') as buffer:
_UpperCamelCase = self._write(file_obj=__a , batch_size=__a , **self.parquet_writer_kwargs)
else:
_UpperCamelCase = self._write(file_obj=self.path_or_buf , batch_size=__a , **self.parquet_writer_kwargs)
return written
def UpperCAmelCase ( self , __a , __a , **__a) -> int:
'''simple docstring'''
_UpperCamelCase = 0
_UpperCamelCase = parquet_writer_kwargs.pop('''path_or_buf''' , __a)
_UpperCamelCase = self.dataset.features.arrow_schema
_UpperCamelCase = pq.ParquetWriter(__a , schema=__a , **__a)
for offset in logging.tqdm(
range(0 , len(self.dataset) , __a) , unit='''ba''' , disable=not logging.is_progress_bar_enabled() , desc='''Creating parquet from Arrow format''' , ):
_UpperCamelCase = query_table(
table=self.dataset._data , key=slice(__a , offset + batch_size) , indices=self.dataset._indices if self.dataset._indices is not None else None , )
writer.write_table(__a)
written += batch.nbytes
writer.close()
return written
| 78 | 0 |
"""simple docstring"""
from __future__ import annotations
import unittest
from transformers import AutoTokenizer, MBartConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel
@require_tf
class _UpperCAmelCase:
lowercase__ = MBartConfig
lowercase__ = {}
lowercase__ = 'gelu'
def __init__( self , __a , __a=13 , __a=7 , __a=True , __a=False , __a=99 , __a=32 , __a=2 , __a=4 , __a=37 , __a=0.1 , __a=0.1 , __a=20 , __a=2 , __a=1 , __a=0 , ) -> Any:
'''simple docstring'''
_UpperCamelCase = parent
_UpperCamelCase = batch_size
_UpperCamelCase = seq_length
_UpperCamelCase = is_training
_UpperCamelCase = use_labels
_UpperCamelCase = vocab_size
_UpperCamelCase = hidden_size
_UpperCamelCase = num_hidden_layers
_UpperCamelCase = num_attention_heads
_UpperCamelCase = intermediate_size
_UpperCamelCase = hidden_dropout_prob
_UpperCamelCase = attention_probs_dropout_prob
_UpperCamelCase = max_position_embeddings
_UpperCamelCase = eos_token_id
_UpperCamelCase = pad_token_id
_UpperCamelCase = bos_token_id
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size)
_UpperCamelCase = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size) , 1)
_UpperCamelCase = tf.concat([input_ids, eos_tensor] , axis=1)
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size)
_UpperCamelCase = self.config_cls(
vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , )
_UpperCamelCase = prepare_mbart_inputs_dict(__a , __a , __a)
return config, inputs_dict
def UpperCAmelCase ( self , __a , __a) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = TFMBartModel(config=__a).get_decoder()
_UpperCamelCase = inputs_dict['''input_ids''']
_UpperCamelCase = input_ids[:1, :]
_UpperCamelCase = inputs_dict['''attention_mask'''][:1, :]
_UpperCamelCase = inputs_dict['''head_mask''']
_UpperCamelCase = 1
# first forward pass
_UpperCamelCase = model(__a , attention_mask=__a , head_mask=__a , use_cache=__a)
_UpperCamelCase , _UpperCamelCase = outputs.to_tuple()
_UpperCamelCase = past_key_values[1]
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case, __snake_case=None, __snake_case=None, __snake_case=None, __snake_case=None, __snake_case=None, ) -> Optional[int]:
"""simple docstring"""
if attention_mask is None:
_UpperCamelCase = tf.cast(tf.math.not_equal(__snake_case, config.pad_token_id ), tf.inta )
if decoder_attention_mask is None:
_UpperCamelCase = tf.concat(
[
tf.ones(decoder_input_ids[:, :1].shape, dtype=tf.inta ),
tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:], config.pad_token_id ), tf.inta ),
], axis=-1, )
if head_mask is None:
_UpperCamelCase = tf.ones((config.encoder_layers, config.encoder_attention_heads) )
if decoder_head_mask is None:
_UpperCamelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
if cross_attn_head_mask is None:
_UpperCamelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
return {
"input_ids": input_ids,
"decoder_input_ids": decoder_input_ids,
"attention_mask": attention_mask,
"decoder_attention_mask": decoder_attention_mask,
"head_mask": head_mask,
"decoder_head_mask": decoder_head_mask,
"cross_attn_head_mask": cross_attn_head_mask,
}
@require_tf
class _UpperCAmelCase( lowerCamelCase , lowerCamelCase , unittest.TestCase ):
lowercase__ = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else ()
lowercase__ = (TFMBartForConditionalGeneration,) if is_tf_available() else ()
lowercase__ = (
{
'conversational': TFMBartForConditionalGeneration,
'feature-extraction': TFMBartModel,
'summarization': TFMBartForConditionalGeneration,
'text2text-generation': TFMBartForConditionalGeneration,
'translation': TFMBartForConditionalGeneration,
}
if is_tf_available()
else {}
)
lowercase__ = True
lowercase__ = False
lowercase__ = False
def UpperCAmelCase ( self , __a , __a , __a , __a , __a) -> Dict:
'''simple docstring'''
if pipeline_test_casse_name != "FeatureExtractionPipelineTests":
# Exception encountered when calling layer '...'
return True
return False
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase = TFMBartModelTester(self)
_UpperCamelCase = ConfigTester(self , config_class=__a)
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
self.config_tester.run_common_tests()
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_decoder_model_past_large_inputs(*__a)
@require_sentencepiece
@require_tokenizers
@require_tf
class _UpperCAmelCase( unittest.TestCase ):
lowercase__ = [
' UN Chief Says There Is No Military Solution in Syria',
]
lowercase__ = [
'Şeful ONU declară că nu există o soluţie militară în Siria',
]
lowercase__ = 'facebook/mbart-large-en-ro'
@cached_property
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
return AutoTokenizer.from_pretrained(self.model_name)
@cached_property
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
_UpperCamelCase = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name)
return model
def UpperCAmelCase ( self , **__a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.translate_src_text(**__a)
self.assertListEqual(self.expected_text , __a)
def UpperCAmelCase ( self , **__a) -> Dict:
'''simple docstring'''
_UpperCamelCase = self.tokenizer(self.src_text , **__a , return_tensors='''tf''')
_UpperCamelCase = self.model.generate(
model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2)
_UpperCamelCase = self.tokenizer.batch_decode(__a , skip_special_tokens=__a)
return generated_words
@slow
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
self._assert_generated_batch_equal_expected()
| 715 |
"""simple docstring"""
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import MobileViTImageProcessor
class _UpperCAmelCase( unittest.TestCase ):
def __init__( self , __a , __a=7 , __a=3 , __a=18 , __a=30 , __a=4_00 , __a=True , __a=None , __a=True , __a=None , __a=True , ) -> int:
'''simple docstring'''
_UpperCamelCase = size if size is not None else {'''shortest_edge''': 20}
_UpperCamelCase = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}
_UpperCamelCase = parent
_UpperCamelCase = batch_size
_UpperCamelCase = num_channels
_UpperCamelCase = image_size
_UpperCamelCase = min_resolution
_UpperCamelCase = max_resolution
_UpperCamelCase = do_resize
_UpperCamelCase = size
_UpperCamelCase = do_center_crop
_UpperCamelCase = crop_size
_UpperCamelCase = do_flip_channel_order
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
return {
"do_resize": self.do_resize,
"size": self.size,
"do_center_crop": self.do_center_crop,
"crop_size": self.crop_size,
"do_flip_channel_order": self.do_flip_channel_order,
}
@require_torch
@require_vision
class _UpperCAmelCase( lowerCamelCase , unittest.TestCase ):
lowercase__ = MobileViTImageProcessor if is_vision_available() else None
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = MobileViTImageProcessingTester(self)
@property
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
return self.image_processor_tester.prepare_image_processor_dict()
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(__a , '''do_resize'''))
self.assertTrue(hasattr(__a , '''size'''))
self.assertTrue(hasattr(__a , '''do_center_crop'''))
self.assertTrue(hasattr(__a , '''center_crop'''))
self.assertTrue(hasattr(__a , '''do_flip_channel_order'''))
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.image_processing_class.from_dict(self.image_processor_dict)
self.assertEqual(image_processor.size , {'''shortest_edge''': 20})
self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18})
_UpperCamelCase = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84)
self.assertEqual(image_processor.size , {'''shortest_edge''': 42})
self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84})
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
pass
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
# Initialize image_processing
_UpperCamelCase = self.image_processing_class(**self.image_processor_dict)
# create random PIL images
_UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a)
for image in image_inputs:
self.assertIsInstance(__a , Image.Image)
# Test not batched input
_UpperCamelCase = image_processing(image_inputs[0] , return_tensors='''pt''').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
# Test batched
_UpperCamelCase = image_processing(__a , return_tensors='''pt''').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
# Initialize image_processing
_UpperCamelCase = self.image_processing_class(**self.image_processor_dict)
# create random numpy tensors
_UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , numpify=__a)
for image in image_inputs:
self.assertIsInstance(__a , np.ndarray)
# Test not batched input
_UpperCamelCase = image_processing(image_inputs[0] , return_tensors='''pt''').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
# Test batched
_UpperCamelCase = image_processing(__a , return_tensors='''pt''').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
# Initialize image_processing
_UpperCamelCase = self.image_processing_class(**self.image_processor_dict)
# create random PyTorch tensors
_UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , torchify=__a)
for image in image_inputs:
self.assertIsInstance(__a , torch.Tensor)
# Test not batched input
_UpperCamelCase = image_processing(image_inputs[0] , return_tensors='''pt''').pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
# Test batched
_UpperCamelCase = image_processing(__a , return_tensors='''pt''').pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
| 78 | 0 |
"""simple docstring"""
import argparse
import torch
from transformers import OpenAIGPTConfig, OpenAIGPTModel, load_tf_weights_in_openai_gpt
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging
logging.set_verbosity_info()
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> Union[str, Any]:
"""simple docstring"""
if openai_config_file == "":
_UpperCamelCase = OpenAIGPTConfig()
else:
_UpperCamelCase = OpenAIGPTConfig.from_json_file(__snake_case )
_UpperCamelCase = OpenAIGPTModel(__snake_case )
# Load weights from numpy
load_tf_weights_in_openai_gpt(__snake_case, __snake_case, __snake_case )
# Save pytorch-model
_UpperCamelCase = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME
_UpperCamelCase = pytorch_dump_folder_path + '''/''' + CONFIG_NAME
print(F'''Save PyTorch model to {pytorch_weights_dump_path}''' )
torch.save(model.state_dict(), __snake_case )
print(F'''Save configuration file to {pytorch_config_dump_path}''' )
with open(__snake_case, '''w''', encoding='''utf-8''' ) as f:
f.write(config.to_json_string() )
if __name__ == "__main__":
_a = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--openai_checkpoint_folder_path""",
default=None,
type=str,
required=True,
help="""Path to the TensorFlow checkpoint path.""",
)
parser.add_argument(
"""--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
)
parser.add_argument(
"""--openai_config_file""",
default="""""",
type=str,
help=(
"""An optional config json file corresponding to the pre-trained OpenAI model. \n"""
"""This specifies the model architecture."""
),
)
_a = parser.parse_args()
convert_openai_checkpoint_to_pytorch(
args.openai_checkpoint_folder_path, args.openai_config_file, args.pytorch_dump_folder_path
)
| 716 |
"""simple docstring"""
import warnings
from typing import List
import numpy as np
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
from ...utils import is_flax_available, is_tf_available, is_torch_available
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = ['image_processor', 'tokenizer']
lowercase__ = 'OwlViTImageProcessor'
lowercase__ = ('CLIPTokenizer', 'CLIPTokenizerFast')
def __init__( self , __a=None , __a=None , **__a) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = None
if "feature_extractor" in kwargs:
warnings.warn(
'''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
''' instead.''' , __a , )
_UpperCamelCase = kwargs.pop('''feature_extractor''')
_UpperCamelCase = image_processor if image_processor is not None else feature_extractor
if image_processor is None:
raise ValueError('''You need to specify an `image_processor`.''')
if tokenizer is None:
raise ValueError('''You need to specify a `tokenizer`.''')
super().__init__(__a , __a)
def __call__( self , __a=None , __a=None , __a=None , __a="max_length" , __a="np" , **__a) -> List[str]:
'''simple docstring'''
if text is None and query_images is None and images is None:
raise ValueError(
'''You have to specify at least one text or query image or image. All three cannot be none.''')
if text is not None:
if isinstance(__a , __a) or (isinstance(__a , __a) and not isinstance(text[0] , __a)):
_UpperCamelCase = [self.tokenizer(__a , padding=__a , return_tensors=__a , **__a)]
elif isinstance(__a , __a) and isinstance(text[0] , __a):
_UpperCamelCase = []
# Maximum number of queries across batch
_UpperCamelCase = max([len(__a) for t in text])
# Pad all batch samples to max number of text queries
for t in text:
if len(__a) != max_num_queries:
_UpperCamelCase = t + [''' '''] * (max_num_queries - len(__a))
_UpperCamelCase = self.tokenizer(__a , padding=__a , return_tensors=__a , **__a)
encodings.append(__a)
else:
raise TypeError('''Input text should be a string, a list of strings or a nested list of strings''')
if return_tensors == "np":
_UpperCamelCase = np.concatenate([encoding['''input_ids'''] for encoding in encodings] , axis=0)
_UpperCamelCase = np.concatenate([encoding['''attention_mask'''] for encoding in encodings] , axis=0)
elif return_tensors == "jax" and is_flax_available():
import jax.numpy as jnp
_UpperCamelCase = jnp.concatenate([encoding['''input_ids'''] for encoding in encodings] , axis=0)
_UpperCamelCase = jnp.concatenate([encoding['''attention_mask'''] for encoding in encodings] , axis=0)
elif return_tensors == "pt" and is_torch_available():
import torch
_UpperCamelCase = torch.cat([encoding['''input_ids'''] for encoding in encodings] , dim=0)
_UpperCamelCase = torch.cat([encoding['''attention_mask'''] for encoding in encodings] , dim=0)
elif return_tensors == "tf" and is_tf_available():
import tensorflow as tf
_UpperCamelCase = tf.stack([encoding['''input_ids'''] for encoding in encodings] , axis=0)
_UpperCamelCase = tf.stack([encoding['''attention_mask'''] for encoding in encodings] , axis=0)
else:
raise ValueError('''Target return tensor type could not be returned''')
_UpperCamelCase = BatchEncoding()
_UpperCamelCase = input_ids
_UpperCamelCase = attention_mask
if query_images is not None:
_UpperCamelCase = BatchEncoding()
_UpperCamelCase = self.image_processor(
__a , return_tensors=__a , **__a).pixel_values
_UpperCamelCase = query_pixel_values
if images is not None:
_UpperCamelCase = self.image_processor(__a , return_tensors=__a , **__a)
if text is not None and images is not None:
_UpperCamelCase = image_features.pixel_values
return encoding
elif query_images is not None and images is not None:
_UpperCamelCase = image_features.pixel_values
return encoding
elif text is not None or query_images is not None:
return encoding
else:
return BatchEncoding(data=dict(**__a) , tensor_type=__a)
def UpperCAmelCase ( self , *__a , **__a) -> str:
'''simple docstring'''
return self.image_processor.post_process(*__a , **__a)
def UpperCAmelCase ( self , *__a , **__a) -> Dict:
'''simple docstring'''
return self.image_processor.post_process_object_detection(*__a , **__a)
def UpperCAmelCase ( self , *__a , **__a) -> Optional[Any]:
'''simple docstring'''
return self.image_processor.post_process_image_guided_detection(*__a , **__a)
def UpperCAmelCase ( self , *__a , **__a) -> Optional[int]:
'''simple docstring'''
return self.tokenizer.batch_decode(*__a , **__a)
def UpperCAmelCase ( self , *__a , **__a) -> Optional[Any]:
'''simple docstring'''
return self.tokenizer.decode(*__a , **__a)
@property
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
warnings.warn(
'''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , __a , )
return self.image_processor_class
@property
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
warnings.warn(
'''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , __a , )
return self.image_processor
| 78 | 0 |
"""simple docstring"""
import itertools
import os
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
import numpy as np
import datasets
from .execute import check_correctness
_a = """\
@misc{chen2021evaluating,
title={Evaluating Large Language Models Trained on Code},
author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \
and Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \
and Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \
and Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \
and Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \
and Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \
and Mohammad Bavarian and Clemens Winter and Philippe Tillet \
and Felipe Petroski Such and Dave Cummings and Matthias Plappert \
and Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \
and William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \
and Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \
and William Saunders and Christopher Hesse and Andrew N. Carr \
and Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \
and Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \
and Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \
and Sam McCandlish and Ilya Sutskever and Wojciech Zaremba},
year={2021},
eprint={2107.03374},
archivePrefix={arXiv},
primaryClass={cs.LG}
}
"""
_a = """\
This metric implements the evaluation harness for the HumanEval problem solving dataset
described in the paper \"Evaluating Large Language Models Trained on Code\"
(https://arxiv.org/abs/2107.03374).
"""
_a = """
Calculates how good are predictions given some references, using certain scores
Args:
predictions: list of candidates to evaluate. Each candidates should be a list
of strings with several code candidates to solve the problem.
references: a list with a test for each prediction. Each test should evaluate the
correctness of a code candidate.
k: number of code candidates to consider in the evaluation (Default: [1, 10, 100])
num_workers: number of workers used to evaluate the canidate programs (Default: 4).
timeout:
Returns:
pass_at_k: dict with pass rates for each k
results: dict with granular results of each unittest
Examples:
>>> code_eval = datasets.load_metric(\"code_eval\")
>>> test_cases = [\"assert add(2,3)==5\"]
>>> candidates = [[\"def add(a,b): return a*b\", \"def add(a, b): return a+b\"]]
>>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])
>>> print(pass_at_k)
{'pass@1': 0.5, 'pass@2': 1.0}
"""
_a = """
################################################################################
!!!WARNING!!!
################################################################################
The \"code_eval\" metric executes untrusted model-generated code in Python.
Although it is highly unlikely that model-generated code will do something
overtly malicious in response to this test suite, model-generated code may act
destructively due to a lack of model capability or alignment.
Users are strongly encouraged to sandbox this evaluation suite so that it
does not perform destructive actions on their host or network. For more
information on how OpenAI sandboxes its code, see the paper \"Evaluating Large
Language Models Trained on Code\" (https://arxiv.org/abs/2107.03374).
Once you have read this disclaimer and taken appropriate precautions,
set the environment variable HF_ALLOW_CODE_EVAL=\"1\". Within Python you can to this
with:
>>> import os
>>> os.environ[\"HF_ALLOW_CODE_EVAL\"] = \"1\"
################################################################################\
"""
_a = """The MIT License
Copyright (c) OpenAI (https://openai.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the \"Software\"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE."""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class _UpperCAmelCase( datasets.Metric ):
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
return datasets.MetricInfo(
# This is the description that will appear on the metrics page.
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
'''predictions''': datasets.Sequence(datasets.Value('''string''')),
'''references''': datasets.Value('''string'''),
}) , homepage='''https://github.com/openai/human-eval''' , codebase_urls=['''https://github.com/openai/human-eval'''] , reference_urls=['''https://github.com/openai/human-eval'''] , license=_LICENSE , )
def UpperCAmelCase ( self , __a , __a , __a=[1, 10, 1_00] , __a=4 , __a=3.0) -> Optional[int]:
'''simple docstring'''
if os.getenv('''HF_ALLOW_CODE_EVAL''' , 0) != "1":
raise ValueError(_WARNING)
if os.name == "nt":
raise NotImplementedError('''This metric is currently not supported on Windows.''')
with ThreadPoolExecutor(max_workers=__a) as executor:
_UpperCamelCase = []
_UpperCamelCase = Counter()
_UpperCamelCase = 0
_UpperCamelCase = defaultdict(__a)
for task_id, (candidates, test_case) in enumerate(zip(__a , __a)):
for candidate in candidates:
_UpperCamelCase = candidate + '''\n''' + test_case
_UpperCamelCase = (test_program, timeout, task_id, completion_id[task_id])
_UpperCamelCase = executor.submit(__a , *__a)
futures.append(__a)
completion_id[task_id] += 1
n_samples += 1
for future in as_completed(__a):
_UpperCamelCase = future.result()
results[result["task_id"]].append((result['''completion_id'''], result))
_UpperCamelCase , _UpperCamelCase = [], []
for result in results.values():
result.sort()
_UpperCamelCase = [r[1]['''passed'''] for r in result]
total.append(len(__a))
correct.append(sum(__a))
_UpperCamelCase = np.array(__a)
_UpperCamelCase = np.array(__a)
_UpperCamelCase = k
_UpperCamelCase = {F'''pass@{k}''': estimate_pass_at_k(__a , __a , __a).mean() for k in ks if (total >= k).all()}
return pass_at_k, results
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ):
"""simple docstring"""
def estimator(__snake_case, __snake_case, __snake_case ) -> float:
if n - c < k:
return 1.0
return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1, n + 1 ) )
if isinstance(__snake_case, __snake_case ):
_UpperCamelCase = itertools.repeat(__snake_case, len(__snake_case ) )
else:
assert len(__snake_case ) == len(__snake_case )
_UpperCamelCase = iter(__snake_case )
return np.array([estimator(int(__snake_case ), int(__snake_case ), __snake_case ) for n, c in zip(__snake_case, __snake_case )] )
| 717 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tokenizers_available,
is_torch_available,
is_vision_available,
)
_a = {
"""configuration_perceiver""": ["""PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """PerceiverConfig""", """PerceiverOnnxConfig"""],
"""tokenization_perceiver""": ["""PerceiverTokenizer"""],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_a = ["""PerceiverFeatureExtractor"""]
_a = ["""PerceiverImageProcessor"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_a = [
"""PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""PerceiverForImageClassificationConvProcessing""",
"""PerceiverForImageClassificationFourier""",
"""PerceiverForImageClassificationLearned""",
"""PerceiverForMaskedLM""",
"""PerceiverForMultimodalAutoencoding""",
"""PerceiverForOpticalFlow""",
"""PerceiverForSequenceClassification""",
"""PerceiverLayer""",
"""PerceiverModel""",
"""PerceiverPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_perceiver import PERCEIVER_PRETRAINED_CONFIG_ARCHIVE_MAP, PerceiverConfig, PerceiverOnnxConfig
from .tokenization_perceiver import PerceiverTokenizer
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_perceiver import PerceiverFeatureExtractor
from .image_processing_perceiver import PerceiverImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_perceiver import (
PERCEIVER_PRETRAINED_MODEL_ARCHIVE_LIST,
PerceiverForImageClassificationConvProcessing,
PerceiverForImageClassificationFourier,
PerceiverForImageClassificationLearned,
PerceiverForMaskedLM,
PerceiverForMultimodalAutoencoding,
PerceiverForOpticalFlow,
PerceiverForSequenceClassification,
PerceiverLayer,
PerceiverModel,
PerceiverPreTrainedModel,
)
else:
import sys
_a = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 78 | 0 |
"""simple docstring"""
import gc
import random
import unittest
import numpy as np
import torch
from transformers import (
CLIPImageProcessor,
CLIPTextConfig,
CLIPTextModelWithProjection,
CLIPTokenizer,
CLIPVisionConfig,
CLIPVisionModelWithProjection,
)
from diffusers import (
DiffusionPipeline,
UnCLIPImageVariationPipeline,
UnCLIPScheduler,
UNetaDConditionModel,
UNetaDModel,
)
from diffusers.pipelines.unclip.text_proj import UnCLIPTextProjModel
from diffusers.utils import floats_tensor, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, load_image, require_torch_gpu, skip_mps
from ..pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
enable_full_determinism()
class _UpperCAmelCase( lowerCamelCase , unittest.TestCase ):
lowercase__ = UnCLIPImageVariationPipeline
lowercase__ = IMAGE_VARIATION_PARAMS - {'height', 'width', 'guidance_scale'}
lowercase__ = IMAGE_VARIATION_BATCH_PARAMS
lowercase__ = [
'generator',
'return_dict',
'decoder_num_inference_steps',
'super_res_num_inference_steps',
]
lowercase__ = False
@property
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
return 32
@property
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
return 32
@property
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
return self.time_input_dim
@property
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
return self.time_input_dim * 4
@property
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
return 1_00
@property
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''')
return tokenizer
@property
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
torch.manual_seed(0)
_UpperCamelCase = 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-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , )
return CLIPTextModelWithProjection(__a)
@property
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
torch.manual_seed(0)
_UpperCamelCase = CLIPVisionConfig(
hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , )
return CLIPVisionModelWithProjection(__a)
@property
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
torch.manual_seed(0)
_UpperCamelCase = {
'''clip_embeddings_dim''': self.text_embedder_hidden_size,
'''time_embed_dim''': self.time_embed_dim,
'''cross_attention_dim''': self.cross_attention_dim,
}
_UpperCamelCase = UnCLIPTextProjModel(**__a)
return model
@property
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
torch.manual_seed(0)
_UpperCamelCase = {
'''sample_size''': 32,
# RGB in channels
'''in_channels''': 3,
# Out channels is double in channels because predicts mean and variance
'''out_channels''': 6,
'''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''),
'''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''),
'''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''',
'''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2),
'''layers_per_block''': 1,
'''cross_attention_dim''': self.cross_attention_dim,
'''attention_head_dim''': 4,
'''resnet_time_scale_shift''': '''scale_shift''',
'''class_embed_type''': '''identity''',
}
_UpperCamelCase = UNetaDConditionModel(**__a)
return model
@property
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
return {
"sample_size": 64,
"layers_per_block": 1,
"down_block_types": ("ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D"),
"up_block_types": ("ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D"),
"block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2),
"in_channels": 6,
"out_channels": 3,
}
@property
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
torch.manual_seed(0)
_UpperCamelCase = UNetaDModel(**self.dummy_super_res_kwargs)
return model
@property
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
torch.manual_seed(1)
_UpperCamelCase = UNetaDModel(**self.dummy_super_res_kwargs)
return model
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase = self.dummy_decoder
_UpperCamelCase = self.dummy_text_proj
_UpperCamelCase = self.dummy_text_encoder
_UpperCamelCase = self.dummy_tokenizer
_UpperCamelCase = self.dummy_super_res_first
_UpperCamelCase = self.dummy_super_res_last
_UpperCamelCase = UnCLIPScheduler(
variance_type='''learned_range''' , prediction_type='''epsilon''' , num_train_timesteps=10_00 , )
_UpperCamelCase = UnCLIPScheduler(
variance_type='''fixed_small_log''' , prediction_type='''epsilon''' , num_train_timesteps=10_00 , )
_UpperCamelCase = CLIPImageProcessor(crop_size=32 , size=32)
_UpperCamelCase = self.dummy_image_encoder
return {
"decoder": decoder,
"text_encoder": text_encoder,
"tokenizer": tokenizer,
"text_proj": text_proj,
"feature_extractor": feature_extractor,
"image_encoder": image_encoder,
"super_res_first": super_res_first,
"super_res_last": super_res_last,
"decoder_scheduler": decoder_scheduler,
"super_res_scheduler": super_res_scheduler,
}
def UpperCAmelCase ( self , __a , __a=0 , __a=True) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = floats_tensor((1, 3, 32, 32) , rng=random.Random(__a)).to(__a)
if str(__a).startswith('''mps'''):
_UpperCamelCase = torch.manual_seed(__a)
else:
_UpperCamelCase = torch.Generator(device=__a).manual_seed(__a)
if pil_image:
_UpperCamelCase = input_image * 0.5 + 0.5
_UpperCamelCase = input_image.clamp(0 , 1)
_UpperCamelCase = input_image.cpu().permute(0 , 2 , 3 , 1).float().numpy()
_UpperCamelCase = DiffusionPipeline.numpy_to_pil(__a)[0]
return {
"image": input_image,
"generator": generator,
"decoder_num_inference_steps": 2,
"super_res_num_inference_steps": 2,
"output_type": "np",
}
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = '''cpu'''
_UpperCamelCase = self.get_dummy_components()
_UpperCamelCase = self.pipeline_class(**__a)
_UpperCamelCase = pipe.to(__a)
pipe.set_progress_bar_config(disable=__a)
_UpperCamelCase = self.get_dummy_inputs(__a , pil_image=__a)
_UpperCamelCase = pipe(**__a)
_UpperCamelCase = output.images
_UpperCamelCase = self.get_dummy_inputs(__a , pil_image=__a)
_UpperCamelCase = pipe(
**__a , return_dict=__a , )[0]
_UpperCamelCase = image[0, -3:, -3:, -1]
_UpperCamelCase = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
_UpperCamelCase = np.array(
[
0.9997,
0.0002,
0.9997,
0.9997,
0.9969,
0.0023,
0.9997,
0.9969,
0.9970,
])
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = '''cpu'''
_UpperCamelCase = self.get_dummy_components()
_UpperCamelCase = self.pipeline_class(**__a)
_UpperCamelCase = pipe.to(__a)
pipe.set_progress_bar_config(disable=__a)
_UpperCamelCase = self.get_dummy_inputs(__a , pil_image=__a)
_UpperCamelCase = pipe(**__a)
_UpperCamelCase = output.images
_UpperCamelCase = self.get_dummy_inputs(__a , pil_image=__a)
_UpperCamelCase = pipe(
**__a , return_dict=__a , )[0]
_UpperCamelCase = image[0, -3:, -3:, -1]
_UpperCamelCase = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
_UpperCamelCase = np.array([0.9997, 0.0003, 0.9997, 0.9997, 0.9970, 0.0024, 0.9997, 0.9971, 0.9971])
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
_UpperCamelCase = '''cpu'''
_UpperCamelCase = self.get_dummy_components()
_UpperCamelCase = self.pipeline_class(**__a)
_UpperCamelCase = pipe.to(__a)
pipe.set_progress_bar_config(disable=__a)
_UpperCamelCase = self.get_dummy_inputs(__a , pil_image=__a)
_UpperCamelCase = [
pipeline_inputs['''image'''],
pipeline_inputs['''image'''],
]
_UpperCamelCase = pipe(**__a)
_UpperCamelCase = output.images
_UpperCamelCase = self.get_dummy_inputs(__a , pil_image=__a)
_UpperCamelCase = [
tuple_pipeline_inputs['''image'''],
tuple_pipeline_inputs['''image'''],
]
_UpperCamelCase = pipe(
**__a , return_dict=__a , )[0]
_UpperCamelCase = image[0, -3:, -3:, -1]
_UpperCamelCase = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (2, 64, 64, 3)
_UpperCamelCase = np.array(
[
0.9997,
0.9989,
0.0008,
0.0021,
0.9960,
0.0018,
0.0014,
0.0002,
0.9933,
])
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = torch.device('''cpu''')
class _UpperCAmelCase:
lowercase__ = 1
_UpperCamelCase = self.get_dummy_components()
_UpperCamelCase = self.pipeline_class(**__a)
_UpperCamelCase = pipe.to(__a)
pipe.set_progress_bar_config(disable=__a)
_UpperCamelCase = torch.Generator(device=__a).manual_seed(0)
_UpperCamelCase = pipe.decoder.dtype
_UpperCamelCase = 1
_UpperCamelCase = (
batch_size,
pipe.decoder.config.in_channels,
pipe.decoder.config.sample_size,
pipe.decoder.config.sample_size,
)
_UpperCamelCase = pipe.prepare_latents(
__a , dtype=__a , device=__a , generator=__a , latents=__a , scheduler=DummyScheduler())
_UpperCamelCase = (
batch_size,
pipe.super_res_first.config.in_channels // 2,
pipe.super_res_first.config.sample_size,
pipe.super_res_first.config.sample_size,
)
_UpperCamelCase = pipe.prepare_latents(
__a , dtype=__a , device=__a , generator=__a , latents=__a , scheduler=DummyScheduler())
_UpperCamelCase = self.get_dummy_inputs(__a , pil_image=__a)
_UpperCamelCase = pipe(
**__a , decoder_latents=__a , super_res_latents=__a).images
_UpperCamelCase = self.get_dummy_inputs(__a , pil_image=__a)
# Don't pass image, instead pass embedding
_UpperCamelCase = pipeline_inputs.pop('''image''')
_UpperCamelCase = pipe.image_encoder(__a).image_embeds
_UpperCamelCase = pipe(
**__a , decoder_latents=__a , super_res_latents=__a , image_embeddings=__a , ).images
# make sure passing text embeddings manually is identical
assert np.abs(img_out_a - img_out_a).max() < 1e-4
@skip_mps
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = torch_device == '''cpu'''
# Check is relaxed because there is not a torch 2.0 sliced attention added kv processor
_UpperCamelCase = 1e-2
self._test_attention_slicing_forward_pass(
test_max_difference=__a , expected_max_diff=__a)
@skip_mps
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = torch_device == '''cpu'''
_UpperCamelCase = True
_UpperCamelCase = [
'''decoder_num_inference_steps''',
'''super_res_num_inference_steps''',
]
self._test_inference_batch_single_identical(
test_max_difference=__a , relax_max_difference=__a , additional_params_copy_to_batched_inputs=__a , )
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = [
'''decoder_num_inference_steps''',
'''super_res_num_inference_steps''',
]
if torch_device == "mps":
# TODO: MPS errors with larger batch sizes
_UpperCamelCase = [2, 3]
self._test_inference_batch_consistent(
batch_sizes=__a , additional_params_copy_to_batched_inputs=__a , )
else:
self._test_inference_batch_consistent(
additional_params_copy_to_batched_inputs=__a)
@skip_mps
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
return super().test_dict_tuple_outputs_equivalent()
@skip_mps
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
return super().test_save_load_local()
@skip_mps
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
return super().test_save_load_optional_components()
@slow
@require_torch_gpu
class _UpperCAmelCase( unittest.TestCase ):
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unclip/cat.png''')
_UpperCamelCase = load_numpy(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/unclip/karlo_v1_alpha_cat_variation_fp16.npy''')
_UpperCamelCase = UnCLIPImageVariationPipeline.from_pretrained(
'''kakaobrain/karlo-v1-alpha-image-variations''' , torch_dtype=torch.floataa)
_UpperCamelCase = pipeline.to(__a)
pipeline.set_progress_bar_config(disable=__a)
_UpperCamelCase = torch.Generator(device='''cpu''').manual_seed(0)
_UpperCamelCase = pipeline(
__a , generator=__a , output_type='''np''' , )
_UpperCamelCase = output.images[0]
assert image.shape == (2_56, 2_56, 3)
assert_mean_pixel_difference(__a , __a , 15)
| 718 |
"""simple docstring"""
import inspect
import unittest
from huggingface_hub import hf_hub_download
from transformers import ASTConfig
from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_torchaudio_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import ASTForAudioClassification, ASTModel
from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import (
AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
)
if is_torchaudio_available():
import torchaudio
from transformers import ASTFeatureExtractor
class _UpperCAmelCase:
def __init__( self , __a , __a=13 , __a=2 , __a=24 , __a=16 , __a=True , __a=True , __a=32 , __a=5 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=10 , __a=0.02 , __a=None , __a=2 , __a=2 , ) -> List[str]:
'''simple docstring'''
_UpperCamelCase = parent
_UpperCamelCase = batch_size
_UpperCamelCase = patch_size
_UpperCamelCase = max_length
_UpperCamelCase = num_mel_bins
_UpperCamelCase = is_training
_UpperCamelCase = use_labels
_UpperCamelCase = hidden_size
_UpperCamelCase = num_hidden_layers
_UpperCamelCase = num_attention_heads
_UpperCamelCase = intermediate_size
_UpperCamelCase = hidden_act
_UpperCamelCase = hidden_dropout_prob
_UpperCamelCase = attention_probs_dropout_prob
_UpperCamelCase = type_sequence_label_size
_UpperCamelCase = initializer_range
_UpperCamelCase = scope
_UpperCamelCase = frequency_stride
_UpperCamelCase = time_stride
# in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
_UpperCamelCase = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1
_UpperCamelCase = (self.max_length - self.patch_size) // self.time_stride + 1
_UpperCamelCase = frequency_out_dimension * time_out_dimension
_UpperCamelCase = num_patches + 2
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins])
_UpperCamelCase = None
if self.use_labels:
_UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size)
_UpperCamelCase = self.get_config()
return config, input_values, labels
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
return ASTConfig(
patch_size=self.patch_size , max_length=self.max_length , num_mel_bins=self.num_mel_bins , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__a , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , )
def UpperCAmelCase ( self , __a , __a , __a) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = ASTModel(config=__a)
model.to(__a)
model.eval()
_UpperCamelCase = model(__a)
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size))
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.prepare_config_and_inputs()
(
(
_UpperCamelCase
) , (
_UpperCamelCase
) , (
_UpperCamelCase
) ,
) = config_and_inputs
_UpperCamelCase = {'''input_values''': input_values}
return config, inputs_dict
@require_torch
class _UpperCAmelCase( lowerCamelCase , lowerCamelCase , unittest.TestCase ):
lowercase__ = (
(
ASTModel,
ASTForAudioClassification,
)
if is_torch_available()
else ()
)
lowercase__ = (
{'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel}
if is_torch_available()
else {}
)
lowercase__ = False
lowercase__ = False
lowercase__ = False
lowercase__ = False
def UpperCAmelCase ( self , __a , __a , __a , __a , __a) -> Optional[Any]:
'''simple docstring'''
if pipeline_test_casse_name == "AudioClassificationPipelineTests":
return True
return False
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
_UpperCamelCase = ASTModelTester(self)
_UpperCamelCase = ConfigTester(self , config_class=__a , has_text_modality=__a , hidden_size=37)
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
self.config_tester.run_common_tests()
@unittest.skip(reason='''AST does not use inputs_embeds''')
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
pass
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_UpperCamelCase = model_class(__a)
self.assertIsInstance(model.get_input_embeddings() , (nn.Module))
_UpperCamelCase = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(__a , nn.Linear))
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_UpperCamelCase = model_class(__a)
_UpperCamelCase = inspect.signature(model.forward)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
_UpperCamelCase = [*signature.parameters.keys()]
_UpperCamelCase = ['''input_values''']
self.assertListEqual(arg_names[:1] , __a)
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__a)
@slow
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_UpperCamelCase = ASTModel.from_pretrained(__a)
self.assertIsNotNone(__a)
def lowerCamelCase__ ( ) -> List[str]:
"""simple docstring"""
_UpperCamelCase = hf_hub_download(
repo_id='''nielsr/audio-spectogram-transformer-checkpoint''', filename='''sample_audio.flac''', repo_type='''dataset''' )
_UpperCamelCase , _UpperCamelCase = torchaudio.load(__snake_case )
return audio, sampling_rate
@require_torch
@require_torchaudio
class _UpperCAmelCase( unittest.TestCase ):
@cached_property
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
return (
ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''')
if is_torchaudio_available()
else None
)
@slow
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.default_feature_extractor
_UpperCamelCase = ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593''').to(__a)
_UpperCamelCase = self.default_feature_extractor
_UpperCamelCase , _UpperCamelCase = prepare_audio()
_UpperCamelCase = audio.squeeze().numpy()
_UpperCamelCase = feature_extractor(__a , sampling_rate=__a , return_tensors='''pt''').to(__a)
# forward pass
with torch.no_grad():
_UpperCamelCase = model(**__a)
# verify the logits
_UpperCamelCase = torch.Size((1, 5_27))
self.assertEqual(outputs.logits.shape , __a)
_UpperCamelCase = torch.tensor([-0.8760, -7.0042, -8.6602]).to(__a)
self.assertTrue(torch.allclose(outputs.logits[0, :3] , __a , atol=1e-4))
| 78 | 0 |
"""simple docstring"""
import numpy as np
from numpy import ndarray
from scipy.optimize import Bounds, LinearConstraint, minimize
def lowerCamelCase__ ( __snake_case ) -> float:
"""simple docstring"""
return np.dot(__snake_case, __snake_case )
class _UpperCAmelCase:
def __init__( self , *,
__a = np.inf , __a = "linear" , __a = 0.0 , ) -> None:
'''simple docstring'''
_UpperCamelCase = regularization
_UpperCamelCase = gamma
if kernel == "linear":
_UpperCamelCase = self.__linear
elif kernel == "rbf":
if self.gamma == 0:
raise ValueError('''rbf kernel requires gamma''')
if not isinstance(self.gamma , (float, int)):
raise ValueError('''gamma must be float or int''')
if not self.gamma > 0:
raise ValueError('''gamma must be > 0''')
_UpperCamelCase = self.__rbf
# in the future, there could be a default value like in sklearn
# sklear: def_gamma = 1/(n_features * X.var()) (wiki)
# previously it was 1/(n_features)
else:
_UpperCamelCase = F'''Unknown kernel: {kernel}'''
raise ValueError(__a)
def UpperCAmelCase ( self , __a , __a) -> float:
'''simple docstring'''
return np.dot(__a , __a)
def UpperCAmelCase ( self , __a , __a) -> float:
'''simple docstring'''
return np.exp(-(self.gamma * norm_squared(vectora - vectora)))
def UpperCAmelCase ( self , __a , __a) -> None:
'''simple docstring'''
_UpperCamelCase = observations
_UpperCamelCase = classes
# using Wolfe's Dual to calculate w.
# Primal problem: minimize 1/2*norm_squared(w)
# constraint: yn(w . xn + b) >= 1
#
# With l a vector
# Dual problem: maximize sum_n(ln) -
# 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm))
# constraint: self.C >= ln >= 0
# and sum_n(ln*yn) = 0
# Then we get w using w = sum_n(ln*yn*xn)
# At the end we can get b ~= mean(yn - w . xn)
#
# Since we use kernels, we only need l_star to calculate b
# and to classify observations
((_UpperCamelCase ) , ) = np.shape(__a)
def to_minimize(__a) -> float:
_UpperCamelCase = 0
((_UpperCamelCase ) , ) = np.shape(__a)
for i in range(__a):
for j in range(__a):
s += (
candidate[i]
* candidate[j]
* classes[i]
* classes[j]
* self.kernel(observations[i] , observations[j])
)
return 1 / 2 * s - sum(__a)
_UpperCamelCase = LinearConstraint(__a , 0 , 0)
_UpperCamelCase = Bounds(0 , self.regularization)
_UpperCamelCase = minimize(
__a , np.ones(__a) , bounds=__a , constraints=[ly_contraint]).x
_UpperCamelCase = l_star
# calculating mean offset of separation plane to points
_UpperCamelCase = 0
for i in range(__a):
for j in range(__a):
s += classes[i] - classes[i] * self.optimum[i] * self.kernel(
observations[i] , observations[j])
_UpperCamelCase = s / n
def UpperCAmelCase ( self , __a) -> int:
'''simple docstring'''
_UpperCamelCase = sum(
self.optimum[n]
* self.classes[n]
* self.kernel(self.observations[n] , __a)
for n in range(len(self.classes)))
return 1 if s + self.offset >= 0 else -1
if __name__ == "__main__":
import doctest
doctest.testmod()
| 719 |
"""simple docstring"""
def lowerCamelCase__ ( ) -> list[list[int]]:
"""simple docstring"""
return [list(range(10_00 - i, -10_00 - i, -1 ) ) for i in range(10_00 )]
_a = generate_large_matrix()
_a = (
[[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]],
[[3, 2], [1, 0]],
[[7, 7, 6]],
[[7, 7, 6], [-1, -2, -3]],
grid,
)
def lowerCamelCase__ ( __snake_case ) -> None:
"""simple docstring"""
assert all(row == sorted(__snake_case, reverse=__snake_case ) for row in grid )
assert all(list(__snake_case ) == sorted(__snake_case, reverse=__snake_case ) for col in zip(*__snake_case ) )
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = 0
_UpperCamelCase = len(__snake_case ) - 1
# Edge cases such as no values or all numbers are negative.
if not array or array[0] < 0:
return 0
while right + 1 > left:
_UpperCamelCase = (left + right) // 2
_UpperCamelCase = array[mid]
# Num must be negative and the index must be greater than or equal to 0.
if num < 0 and array[mid - 1] >= 0:
return mid
if num >= 0:
_UpperCamelCase = mid + 1
else:
_UpperCamelCase = mid - 1
# No negative numbers so return the last index of the array + 1 which is the length.
return len(__snake_case )
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = 0
_UpperCamelCase = len(grid[0] )
for i in range(len(__snake_case ) ):
_UpperCamelCase = find_negative_index(grid[i][:bound] )
total += bound
return (len(__snake_case ) * len(grid[0] )) - total
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
return len([number for row in grid for number in row if number < 0] )
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = 0
for row in grid:
for i, number in enumerate(__snake_case ):
if number < 0:
total += len(__snake_case ) - i
break
return total
def lowerCamelCase__ ( ) -> None:
"""simple docstring"""
from timeit import timeit
print('''Running benchmarks''' )
_UpperCamelCase = (
'''from __main__ import count_negatives_binary_search, '''
'''count_negatives_brute_force, count_negatives_brute_force_with_break, grid'''
)
for func in (
"count_negatives_binary_search", # took 0.7727 seconds
"count_negatives_brute_force_with_break", # took 4.6505 seconds
"count_negatives_brute_force", # took 12.8160 seconds
):
_UpperCamelCase = timeit(F'''{func}(grid=grid)''', setup=__snake_case, number=5_00 )
print(F'''{func}() took {time:0.4f} seconds''' )
if __name__ == "__main__":
import doctest
doctest.testmod()
benchmark()
| 78 | 0 |
"""simple docstring"""
import warnings
from contextlib import contextmanager
from ....processing_utils import ProcessorMixin
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = 'MCTCTFeatureExtractor'
lowercase__ = 'AutoTokenizer'
def __init__( self , __a , __a) -> Optional[int]:
'''simple docstring'''
super().__init__(__a , __a)
_UpperCamelCase = self.feature_extractor
_UpperCamelCase = False
def __call__( self , *__a , **__a) -> Any:
'''simple docstring'''
# For backward compatibility
if self._in_target_context_manager:
return self.current_processor(*__a , **__a)
if "raw_speech" in kwargs:
warnings.warn('''Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.''')
_UpperCamelCase = kwargs.pop('''raw_speech''')
else:
_UpperCamelCase = kwargs.pop('''audio''' , __a)
_UpperCamelCase = kwargs.pop('''sampling_rate''' , __a)
_UpperCamelCase = kwargs.pop('''text''' , __a)
if len(__a) > 0:
_UpperCamelCase = args[0]
_UpperCamelCase = args[1:]
if audio is None and text is None:
raise ValueError('''You need to specify either an `audio` or `text` input to process.''')
if audio is not None:
_UpperCamelCase = self.feature_extractor(__a , *__a , sampling_rate=__a , **__a)
if text is not None:
_UpperCamelCase = self.tokenizer(__a , **__a)
if text is None:
return inputs
elif audio is None:
return encodings
else:
_UpperCamelCase = encodings['''input_ids''']
return inputs
def UpperCAmelCase ( self , *__a , **__a) -> Dict:
'''simple docstring'''
return self.tokenizer.batch_decode(*__a , **__a)
def UpperCAmelCase ( self , *__a , **__a) -> Optional[int]:
'''simple docstring'''
# For backward compatibility
if self._in_target_context_manager:
return self.current_processor.pad(*__a , **__a)
_UpperCamelCase = kwargs.pop('''input_features''' , __a)
_UpperCamelCase = kwargs.pop('''labels''' , __a)
if len(__a) > 0:
_UpperCamelCase = args[0]
_UpperCamelCase = args[1:]
if input_features is not None:
_UpperCamelCase = self.feature_extractor.pad(__a , *__a , **__a)
if labels is not None:
_UpperCamelCase = self.tokenizer.pad(__a , **__a)
if labels is None:
return input_features
elif input_features is None:
return labels
else:
_UpperCamelCase = labels['''input_ids''']
return input_features
def UpperCAmelCase ( self , *__a , **__a) -> Optional[Any]:
'''simple docstring'''
return self.tokenizer.decode(*__a , **__a)
@contextmanager
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
warnings.warn(
'''`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your '''
'''labels by using the argument `text` of the regular `__call__` method (either in the same call as '''
'''your audio inputs, or in a separate call.''')
_UpperCamelCase = True
_UpperCamelCase = self.tokenizer
yield
_UpperCamelCase = self.feature_extractor
_UpperCamelCase = False
| 720 |
"""simple docstring"""
import copy
import re
class _UpperCAmelCase:
lowercase__ = 'hp'
lowercase__ = {}
lowercase__ = None
@classmethod
def UpperCAmelCase ( cls , __a , __a) -> Dict:
'''simple docstring'''
_UpperCamelCase = prefix
_UpperCamelCase = defaults
cls.build_naming_info()
@staticmethod
def UpperCAmelCase ( __a , __a) -> Union[str, Any]:
'''simple docstring'''
if len(__a) == 0:
return ""
_UpperCamelCase = None
if any(char.isdigit() for char in word):
raise Exception(F'''Parameters should not contain numbers: \'{word}\' contains a number''')
if word in info["short_word"]:
return info["short_word"][word]
for prefix_len in range(1 , len(__a) + 1):
_UpperCamelCase = word[:prefix_len]
if prefix in info["reverse_short_word"]:
continue
else:
_UpperCamelCase = prefix
break
if short_word is None:
# Paranoid fallback
def int_to_alphabetic(__a):
_UpperCamelCase = ''''''
while integer != 0:
_UpperCamelCase = chr(ord('''A''') + integer % 10) + s
integer //= 10
return s
_UpperCamelCase = 0
while True:
_UpperCamelCase = word + '''#''' + int_to_alphabetic(__a)
if sword in info["reverse_short_word"]:
continue
else:
_UpperCamelCase = sword
break
_UpperCamelCase = short_word
_UpperCamelCase = word
return short_word
@staticmethod
def UpperCAmelCase ( __a , __a) -> Any:
'''simple docstring'''
_UpperCamelCase = param_name.split('''_''')
_UpperCamelCase = [TrialShortNamer.shortname_for_word(__a , __a) for word in words]
# We try to create a separatorless short name, but if there is a collision we have to fallback
# to a separated short name
_UpperCamelCase = ['''''', '''_''']
for separator in separators:
_UpperCamelCase = separator.join(__a)
if shortname not in info["reverse_short_param"]:
_UpperCamelCase = shortname
_UpperCamelCase = param_name
return shortname
return param_name
@staticmethod
def UpperCAmelCase ( __a , __a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = TrialShortNamer.shortname_for_key(__a , __a)
_UpperCamelCase = short_name
_UpperCamelCase = param_name
@classmethod
def UpperCAmelCase ( cls) -> Any:
'''simple docstring'''
if cls.NAMING_INFO is not None:
return
_UpperCamelCase = {
'''short_word''': {},
'''reverse_short_word''': {},
'''short_param''': {},
'''reverse_short_param''': {},
}
_UpperCamelCase = list(cls.DEFAULTS.keys())
for k in field_keys:
cls.add_new_param_name(__a , __a)
_UpperCamelCase = info
@classmethod
def UpperCAmelCase ( cls , __a) -> Optional[Any]:
'''simple docstring'''
cls.build_naming_info()
assert cls.PREFIX is not None
_UpperCamelCase = [copy.copy(cls.PREFIX)]
for k, v in params.items():
if k not in cls.DEFAULTS:
raise Exception(F'''You should provide a default value for the param name {k} with value {v}''')
if v == cls.DEFAULTS[k]:
# The default value is not added to the name
continue
_UpperCamelCase = cls.NAMING_INFO['''short_param'''][k]
if isinstance(__a , __a):
_UpperCamelCase = 1 if v else 0
_UpperCamelCase = '''''' if isinstance(__a , (int, float)) else '''-'''
_UpperCamelCase = F'''{key}{sep}{v}'''
name.append(__a)
return "_".join(__a)
@classmethod
def UpperCAmelCase ( cls , __a) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = repr[len(cls.PREFIX) + 1 :]
if repr == "":
_UpperCamelCase = []
else:
_UpperCamelCase = repr.split('''_''')
_UpperCamelCase = {}
for value in values:
if "-" in value:
_UpperCamelCase , _UpperCamelCase = value.split('''-''')
else:
_UpperCamelCase = re.sub('''[0-9.]''' , '''''' , __a)
_UpperCamelCase = float(re.sub('''[^0-9.]''' , '''''' , __a))
_UpperCamelCase = cls.NAMING_INFO['''reverse_short_param'''][p_k]
_UpperCamelCase = p_v
for k in cls.DEFAULTS:
if k not in parameters:
_UpperCamelCase = cls.DEFAULTS[k]
return parameters
| 78 | 0 |
"""simple docstring"""
def lowerCamelCase__ ( __snake_case ) -> float:
"""simple docstring"""
_UpperCamelCase = 0
while len(__snake_case ) > 1:
_UpperCamelCase = 0
# Consider two files with minimum cost to be merged
for _ in range(2 ):
_UpperCamelCase = files.index(min(__snake_case ) )
temp += files[min_index]
files.pop(__snake_case )
files.append(__snake_case )
optimal_merge_cost += temp
return optimal_merge_cost
if __name__ == "__main__":
import doctest
doctest.testmod()
| 721 |
"""simple docstring"""
import os
import time
import pytest
from datasets.utils.filelock import FileLock, Timeout
def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]:
"""simple docstring"""
_UpperCamelCase = FileLock(str(tmpdir / '''foo.lock''' ) )
_UpperCamelCase = FileLock(str(tmpdir / '''foo.lock''' ) )
_UpperCamelCase = 0.01
with locka.acquire():
with pytest.raises(__snake_case ):
_UpperCamelCase = time.time()
locka.acquire(__snake_case )
assert time.time() - _start > timeout
def lowerCamelCase__ ( __snake_case ) -> List[Any]:
"""simple docstring"""
_UpperCamelCase = '''a''' * 10_00 + '''.lock'''
_UpperCamelCase = FileLock(str(tmpdir / filename ) )
assert locka._lock_file.endswith('''.lock''' )
assert not locka._lock_file.endswith(__snake_case )
assert len(os.path.basename(locka._lock_file ) ) <= 2_55
_UpperCamelCase = FileLock(tmpdir / filename )
with locka.acquire():
with pytest.raises(__snake_case ):
locka.acquire(0 )
| 78 | 0 |
"""simple docstring"""
import unittest
from transformers import AlbertTokenizer, AlbertTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
_a = get_tests_dir("""fixtures/spiece.model""")
@require_sentencepiece
@require_tokenizers
class _UpperCAmelCase( lowerCamelCase , unittest.TestCase ):
lowercase__ = AlbertTokenizer
lowercase__ = AlbertTokenizerFast
lowercase__ = True
lowercase__ = True
lowercase__ = True
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
super().setUp()
# We have a SentencePiece fixture for testing
_UpperCamelCase = AlbertTokenizer(__a)
tokenizer.save_pretrained(self.tmpdirname)
def UpperCAmelCase ( self , __a) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = '''this is a test'''
_UpperCamelCase = '''this is a test'''
return input_text, output_text
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = '''<pad>'''
_UpperCamelCase = 0
self.assertEqual(self.get_tokenizer()._convert_token_to_id(__a) , __a)
self.assertEqual(self.get_tokenizer()._convert_id_to_token(__a) , __a)
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = list(self.get_tokenizer().get_vocab().keys())
self.assertEqual(vocab_keys[0] , '''<pad>''')
self.assertEqual(vocab_keys[1] , '''<unk>''')
self.assertEqual(vocab_keys[-1] , '''▁eloquent''')
self.assertEqual(len(__a) , 3_00_00)
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
self.assertEqual(self.get_tokenizer().vocab_size , 3_00_00)
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
if not self.test_rust_tokenizer:
return
_UpperCamelCase = self.get_tokenizer()
_UpperCamelCase = self.get_rust_tokenizer()
_UpperCamelCase = '''I was born in 92000, and this is falsé.'''
_UpperCamelCase = tokenizer.tokenize(__a)
_UpperCamelCase = rust_tokenizer.tokenize(__a)
self.assertListEqual(__a , __a)
_UpperCamelCase = tokenizer.encode(__a , add_special_tokens=__a)
_UpperCamelCase = rust_tokenizer.encode(__a , add_special_tokens=__a)
self.assertListEqual(__a , __a)
_UpperCamelCase = self.get_rust_tokenizer()
_UpperCamelCase = tokenizer.encode(__a)
_UpperCamelCase = rust_tokenizer.encode(__a)
self.assertListEqual(__a , __a)
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = AlbertTokenizer(__a , keep_accents=__a)
_UpperCamelCase = tokenizer.tokenize('''This is a test''')
self.assertListEqual(__a , ['''▁this''', '''▁is''', '''▁a''', '''▁test'''])
self.assertListEqual(tokenizer.convert_tokens_to_ids(__a) , [48, 25, 21, 12_89])
_UpperCamelCase = tokenizer.tokenize('''I was born in 92000, and this is falsé.''')
self.assertListEqual(
__a , ['''▁i''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''é''', '''.'''])
_UpperCamelCase = tokenizer.convert_tokens_to_ids(__a)
self.assertListEqual(__a , [31, 23, 3_86, 19, 5_61, 30_50, 15, 17, 48, 25, 82_56, 18, 1, 9])
_UpperCamelCase = tokenizer.convert_ids_to_tokens(__a)
self.assertListEqual(
__a , ['''▁i''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''.'''] , )
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = AlbertTokenizer(__a)
_UpperCamelCase = tokenizer.encode('''sequence builders''')
_UpperCamelCase = tokenizer.encode('''multi-sequence build''')
_UpperCamelCase = tokenizer.build_inputs_with_special_tokens(__a)
_UpperCamelCase = tokenizer.build_inputs_with_special_tokens(__a , __a)
assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id]
assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [
tokenizer.sep_token_id
]
@slow
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase = {'''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''input_ids''': [[2, 2_19_70, 13, 5, 60_92, 1_67, 28, 71_03, 21_53, 6_73, 8, 70_28, 1_20_51, 18, 17, 71_03, 21_53, 6_73, 8, 35_15, 1_86_84, 8, 44_61, 6, 19_27, 2_97, 8, 1_20_60, 26_07, 18, 13, 5, 44_61, 15, 1_05_38, 38, 8, 1_35, 15, 8_22, 58, 15, 9_93, 1_03_63, 15, 14_60, 80_05, 44_61, 15, 9_93, 2_55, 23_28, 9, 9, 9, 6, 26, 11_12, 8_16, 32_60, 13, 5, 1_03, 23_77, 6, 17, 11_12, 8_16, 27_82, 13, 5, 1_03, 1_06_41, 6, 29, 84, 25_12, 24_30, 7_82, 1_86_84, 27_61, 19, 8_08, 24_30, 25_56, 17, 8_55, 14_80, 94_77, 40_91, 1_28, 1_17_12, 15, 71_03, 21_53, 6_73, 17, 2_48_83, 99_90, 9, 3], [2, 1_15_02, 25, 10_06, 20, 7_82, 8, 1_18_09, 8_55, 17_32, 1_93_93, 1_86_67, 37, 3_67, 2_10_18, 69, 18_54, 34, 1_18_60, 1_91_24, 27, 1_56, 2_25, 17, 1_93, 41_41, 19, 65, 91_24, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 14, 22_31, 8_86, 23_85, 1_76_59, 84, 14, 1_67_92, 19_52, 9, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''token_type_ids''': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=__a , model_name='''albert-base-v2''' , revision='''6b6560eaf5ff2e250b00c50f380c5389a9c2d82e''' , )
| 700 |
"""simple docstring"""
from math import sqrt
def lowerCamelCase__ ( __snake_case ) -> bool:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (
number >= 0
), "'number' must been an int and positive"
_UpperCamelCase = True
# 0 and 1 are none primes.
if number <= 1:
_UpperCamelCase = False
for divisor in range(2, int(round(sqrt(__snake_case ) ) ) + 1 ):
# if 'number' divisible by 'divisor' then sets 'status'
# of false and break up the loop.
if number % divisor == 0:
_UpperCamelCase = False
break
# precondition
assert isinstance(__snake_case, __snake_case ), "'status' must been from type bool"
return status
def lowerCamelCase__ ( __snake_case ) -> Dict:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n > 2), "'N' must been an int and > 2"
# beginList: contains all natural numbers from 2 up to N
_UpperCamelCase = list(range(2, n + 1 ) )
_UpperCamelCase = [] # this list will be returns.
# actual sieve of erathostenes
for i in range(len(__snake_case ) ):
for j in range(i + 1, len(__snake_case ) ):
if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0):
_UpperCamelCase = 0
# filters actual prime numbers.
_UpperCamelCase = [x for x in begin_list if x != 0]
# precondition
assert isinstance(__snake_case, __snake_case ), "'ans' must been from type list"
return ans
def lowerCamelCase__ ( __snake_case ) -> List[str]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n > 2), "'N' must been an int and > 2"
_UpperCamelCase = []
# iterates over all numbers between 2 up to N+1
# if a number is prime then appends to list 'ans'
for number in range(2, n + 1 ):
if is_prime(__snake_case ):
ans.append(__snake_case )
# precondition
assert isinstance(__snake_case, __snake_case ), "'ans' must been from type list"
return ans
def lowerCamelCase__ ( __snake_case ) -> Optional[int]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and number >= 0, "'number' must been an int and >= 0"
_UpperCamelCase = [] # this list will be returns of the function.
# potential prime number factors.
_UpperCamelCase = 2
_UpperCamelCase = number
if number == 0 or number == 1:
ans.append(__snake_case )
# if 'number' not prime then builds the prime factorization of 'number'
elif not is_prime(__snake_case ):
while quotient != 1:
if is_prime(__snake_case ) and (quotient % factor == 0):
ans.append(__snake_case )
quotient /= factor
else:
factor += 1
else:
ans.append(__snake_case )
# precondition
assert isinstance(__snake_case, __snake_case ), "'ans' must been from type list"
return ans
def lowerCamelCase__ ( __snake_case ) -> Optional[Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (
number >= 0
), "'number' bust been an int and >= 0"
_UpperCamelCase = 0
# prime factorization of 'number'
_UpperCamelCase = prime_factorization(__snake_case )
_UpperCamelCase = max(__snake_case )
# precondition
assert isinstance(__snake_case, __snake_case ), "'ans' must been from type int"
return ans
def lowerCamelCase__ ( __snake_case ) -> int:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (
number >= 0
), "'number' bust been an int and >= 0"
_UpperCamelCase = 0
# prime factorization of 'number'
_UpperCamelCase = prime_factorization(__snake_case )
_UpperCamelCase = min(__snake_case )
# precondition
assert isinstance(__snake_case, __snake_case ), "'ans' must been from type int"
return ans
def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ), "'number' must been an int"
assert isinstance(number % 2 == 0, __snake_case ), "compare bust been from type bool"
return number % 2 == 0
def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ), "'number' must been an int"
assert isinstance(number % 2 != 0, __snake_case ), "compare bust been from type bool"
return number % 2 != 0
def lowerCamelCase__ ( __snake_case ) -> str:
"""simple docstring"""
assert (
isinstance(__snake_case, __snake_case ) and (number > 2) and is_even(__snake_case )
), "'number' must been an int, even and > 2"
_UpperCamelCase = [] # this list will returned
# creates a list of prime numbers between 2 up to 'number'
_UpperCamelCase = get_prime_numbers(__snake_case )
_UpperCamelCase = len(__snake_case )
# run variable for while-loops.
_UpperCamelCase = 0
_UpperCamelCase = None
# exit variable. for break up the loops
_UpperCamelCase = True
while i < len_pn and loop:
_UpperCamelCase = i + 1
while j < len_pn and loop:
if prime_numbers[i] + prime_numbers[j] == number:
_UpperCamelCase = False
ans.append(prime_numbers[i] )
ans.append(prime_numbers[j] )
j += 1
i += 1
# precondition
assert (
isinstance(__snake_case, __snake_case )
and (len(__snake_case ) == 2)
and (ans[0] + ans[1] == number)
and is_prime(ans[0] )
and is_prime(ans[1] )
), "'ans' must contains two primes. And sum of elements must been eq 'number'"
return ans
def lowerCamelCase__ ( __snake_case, __snake_case ) -> str:
"""simple docstring"""
assert (
isinstance(__snake_case, __snake_case )
and isinstance(__snake_case, __snake_case )
and (numbera >= 0)
and (numbera >= 0)
), "'number1' and 'number2' must been positive integer."
_UpperCamelCase = 0
while numbera != 0:
_UpperCamelCase = numbera % numbera
_UpperCamelCase = numbera
_UpperCamelCase = rest
# precondition
assert isinstance(__snake_case, __snake_case ) and (
numbera >= 0
), "'number' must been from type int and positive"
return numbera
def lowerCamelCase__ ( __snake_case, __snake_case ) -> List[str]:
"""simple docstring"""
assert (
isinstance(__snake_case, __snake_case )
and isinstance(__snake_case, __snake_case )
and (numbera >= 1)
and (numbera >= 1)
), "'number1' and 'number2' must been positive integer."
_UpperCamelCase = 1 # actual answer that will be return.
# for kgV (x,1)
if numbera > 1 and numbera > 1:
# builds the prime factorization of 'number1' and 'number2'
_UpperCamelCase = prime_factorization(__snake_case )
_UpperCamelCase = prime_factorization(__snake_case )
elif numbera == 1 or numbera == 1:
_UpperCamelCase = []
_UpperCamelCase = []
_UpperCamelCase = max(__snake_case, __snake_case )
_UpperCamelCase = 0
_UpperCamelCase = 0
_UpperCamelCase = [] # captured numbers int both 'primeFac1' and 'primeFac2'
# iterates through primeFac1
for n in prime_fac_a:
if n not in done:
if n in prime_fac_a:
_UpperCamelCase = prime_fac_a.count(__snake_case )
_UpperCamelCase = prime_fac_a.count(__snake_case )
for _ in range(max(__snake_case, __snake_case ) ):
ans *= n
else:
_UpperCamelCase = prime_fac_a.count(__snake_case )
for _ in range(__snake_case ):
ans *= n
done.append(__snake_case )
# iterates through primeFac2
for n in prime_fac_a:
if n not in done:
_UpperCamelCase = prime_fac_a.count(__snake_case )
for _ in range(__snake_case ):
ans *= n
done.append(__snake_case )
# precondition
assert isinstance(__snake_case, __snake_case ) and (
ans >= 0
), "'ans' must been from type int and positive"
return ans
def lowerCamelCase__ ( __snake_case ) -> Tuple:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n >= 0), "'number' must been a positive int"
_UpperCamelCase = 0
_UpperCamelCase = 2 # this variable holds the answer
while index < n:
index += 1
ans += 1 # counts to the next number
# if ans not prime then
# runs to the next prime number.
while not is_prime(__snake_case ):
ans += 1
# precondition
assert isinstance(__snake_case, __snake_case ) and is_prime(
__snake_case ), "'ans' must been a prime number and from type int"
return ans
def lowerCamelCase__ ( __snake_case, __snake_case ) -> Tuple:
"""simple docstring"""
assert (
is_prime(__snake_case ) and is_prime(__snake_case ) and (p_number_a < p_number_a)
), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'"
_UpperCamelCase = p_number_a + 1 # jump to the next number
_UpperCamelCase = [] # this list will be returns.
# if number is not prime then
# fetch the next prime number.
while not is_prime(__snake_case ):
number += 1
while number < p_number_a:
ans.append(__snake_case )
number += 1
# fetch the next prime number.
while not is_prime(__snake_case ):
number += 1
# precondition
assert (
isinstance(__snake_case, __snake_case )
and ans[0] != p_number_a
and ans[len(__snake_case ) - 1] != p_number_a
), "'ans' must been a list without the arguments"
# 'ans' contains not 'pNumber1' and 'pNumber2' !
return ans
def lowerCamelCase__ ( __snake_case ) -> List[Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n >= 1), "'n' must been int and >= 1"
_UpperCamelCase = [] # will be returned.
for divisor in range(1, n + 1 ):
if n % divisor == 0:
ans.append(__snake_case )
# precondition
assert ans[0] == 1 and ans[len(__snake_case ) - 1] == n, "Error in function getDivisiors(...)"
return ans
def lowerCamelCase__ ( __snake_case ) -> str:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (
number > 1
), "'number' must been an int and >= 1"
_UpperCamelCase = get_divisors(__snake_case )
# precondition
assert (
isinstance(__snake_case, __snake_case )
and (divisors[0] == 1)
and (divisors[len(__snake_case ) - 1] == number)
), "Error in help-function getDivisiors(...)"
# summed all divisors up to 'number' (exclusive), hence [:-1]
return sum(divisors[:-1] ) == number
def lowerCamelCase__ ( __snake_case, __snake_case ) -> Optional[Any]:
"""simple docstring"""
assert (
isinstance(__snake_case, __snake_case )
and isinstance(__snake_case, __snake_case )
and (denominator != 0)
), "The arguments must been from type int and 'denominator' != 0"
# build the greatest common divisor of numerator and denominator.
_UpperCamelCase = gcd(abs(__snake_case ), abs(__snake_case ) )
# precondition
assert (
isinstance(__snake_case, __snake_case )
and (numerator % gcd_of_fraction == 0)
and (denominator % gcd_of_fraction == 0)
), "Error in function gcd(...,...)"
return (numerator // gcd_of_fraction, denominator // gcd_of_fraction)
def lowerCamelCase__ ( __snake_case ) -> Optional[Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n >= 0), "'n' must been a int and >= 0"
_UpperCamelCase = 1 # this will be return.
for factor in range(1, n + 1 ):
ans *= factor
return ans
def lowerCamelCase__ ( __snake_case ) -> Union[str, Any]:
"""simple docstring"""
assert isinstance(__snake_case, __snake_case ) and (n >= 0), "'n' must been an int and >= 0"
_UpperCamelCase = 0
_UpperCamelCase = 1
_UpperCamelCase = 1 # this will be return
for _ in range(n - 1 ):
_UpperCamelCase = ans
ans += fiba
_UpperCamelCase = tmp
return ans
| 78 | 0 |
"""simple docstring"""
from typing import Callable, List, Optional, Union
import PIL
import torch
from transformers import (
CLIPImageProcessor,
CLIPSegForImageSegmentation,
CLIPSegProcessor,
CLIPTextModel,
CLIPTokenizer,
)
from diffusers import DiffusionPipeline
from diffusers.configuration_utils import FrozenDict
from diffusers.models import AutoencoderKL, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
from diffusers.utils import deprecate, is_accelerate_available, logging
_a = logging.get_logger(__name__) # pylint: disable=invalid-name
class _UpperCAmelCase( lowerCamelCase ):
def __init__( self , __a , __a , __a , __a , __a , __a , __a , __a , __a , ) -> Any:
'''simple docstring'''
super().__init__()
if hasattr(scheduler.config , '''steps_offset''') and scheduler.config.steps_offset != 1:
_UpperCamelCase = (
F'''The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`'''
F''' should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure '''
'''to update the config accordingly as leaving `steps_offset` might led to incorrect results'''
''' in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,'''
''' it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`'''
''' file'''
)
deprecate('''steps_offset!=1''' , '''1.0.0''' , __a , standard_warn=__a)
_UpperCamelCase = dict(scheduler.config)
_UpperCamelCase = 1
_UpperCamelCase = FrozenDict(__a)
if hasattr(scheduler.config , '''skip_prk_steps''') and scheduler.config.skip_prk_steps is False:
_UpperCamelCase = (
F'''The configuration file of this scheduler: {scheduler} has not set the configuration'''
''' `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make'''
''' sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to'''
''' incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face'''
''' Hub, it would be very nice if you could open a Pull request for the'''
''' `scheduler/scheduler_config.json` file'''
)
deprecate('''skip_prk_steps not set''' , '''1.0.0''' , __a , standard_warn=__a)
_UpperCamelCase = dict(scheduler.config)
_UpperCamelCase = True
_UpperCamelCase = FrozenDict(__a)
if safety_checker is None:
logger.warning(
F'''You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure'''
''' that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered'''
''' results in services or applications open to the public. Both the diffusers team and Hugging Face'''
''' strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling'''
''' it only for use-cases that involve analyzing network behavior or auditing its results. For more'''
''' information, please have a look at https://github.com/huggingface/diffusers/pull/254 .''')
self.register_modules(
segmentation_model=__a , segmentation_processor=__a , vae=__a , text_encoder=__a , tokenizer=__a , unet=__a , scheduler=__a , safety_checker=__a , feature_extractor=__a , )
def UpperCAmelCase ( self , __a = "auto") -> Union[str, Any]:
'''simple docstring'''
if slice_size == "auto":
# half the attention head size is usually a good trade-off between
# speed and memory
_UpperCamelCase = self.unet.config.attention_head_dim // 2
self.unet.set_attention_slice(__a)
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
self.enable_attention_slicing(__a)
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
if is_accelerate_available():
from accelerate import cpu_offload
else:
raise ImportError('''Please install accelerate via `pip install accelerate`''')
_UpperCamelCase = torch.device('''cuda''')
for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]:
if cpu_offloaded_model is not None:
cpu_offload(__a , __a)
@property
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
if self.device != torch.device('''meta''') or not hasattr(self.unet , '''_hf_hook'''):
return self.device
for module in self.unet.modules():
if (
hasattr(__a , '''_hf_hook''')
and hasattr(module._hf_hook , '''execution_device''')
and module._hf_hook.execution_device is not None
):
return torch.device(module._hf_hook.execution_device)
return self.device
@torch.no_grad()
def __call__( self , __a , __a , __a , __a = 5_12 , __a = 5_12 , __a = 50 , __a = 7.5 , __a = None , __a = 1 , __a = 0.0 , __a = None , __a = None , __a = "pil" , __a = True , __a = None , __a = 1 , **__a , ) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = self.segmentation_processor(
text=[text] , images=[image] , padding='''max_length''' , return_tensors='''pt''').to(self.device)
_UpperCamelCase = self.segmentation_model(**__a)
_UpperCamelCase = torch.sigmoid(outputs.logits).cpu().detach().unsqueeze(-1).numpy()
_UpperCamelCase = self.numpy_to_pil(__a)[0].resize(image.size)
# Run inpainting pipeline with the generated mask
_UpperCamelCase = StableDiffusionInpaintPipeline(
vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , )
return inpainting_pipeline(
prompt=__a , image=__a , mask_image=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , )
| 701 |
"""simple docstring"""
import logging
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional, Union
from .generation.configuration_utils import GenerationConfig
from .training_args import TrainingArguments
from .utils import add_start_docstrings
_a = logging.getLogger(__name__)
@dataclass
@add_start_docstrings(TrainingArguments.__doc__ )
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = field(default=lowerCamelCase , metadata={'help': 'Whether to use SortishSampler or not.'} )
lowercase__ = field(
default=lowerCamelCase , metadata={'help': 'Whether to use generate to calculate generative metrics (ROUGE, BLEU).'} )
lowercase__ = field(
default=lowerCamelCase , metadata={
'help': (
'The `max_length` to use on each evaluation loop when `predict_with_generate=True`. Will default '
'to the `max_length` value of the model configuration.'
)
} , )
lowercase__ = field(
default=lowerCamelCase , metadata={
'help': (
'The `num_beams` to use on each evaluation loop when `predict_with_generate=True`. Will default '
'to the `num_beams` value of the model configuration.'
)
} , )
lowercase__ = field(
default=lowerCamelCase , metadata={
'help': 'Model id, file path or url pointing to a GenerationConfig json file, to use during prediction.'
} , )
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = super().to_dict()
for k, v in d.items():
if isinstance(__a , __a):
_UpperCamelCase = v.to_dict()
return d
| 78 | 0 |
"""simple docstring"""
import gc
import unittest
import numpy as np
import torch
import torch.nn.functional as F
from transformers import (
ClapTextConfig,
ClapTextModelWithProjection,
RobertaTokenizer,
SpeechTaHifiGan,
SpeechTaHifiGanConfig,
)
from diffusers import (
AudioLDMPipeline,
AutoencoderKL,
DDIMScheduler,
LMSDiscreteScheduler,
PNDMScheduler,
UNetaDConditionModel,
)
from diffusers.utils import is_xformers_available, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism
from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
enable_full_determinism()
class _UpperCAmelCase( lowerCamelCase , unittest.TestCase ):
lowercase__ = AudioLDMPipeline
lowercase__ = TEXT_TO_AUDIO_PARAMS
lowercase__ = TEXT_TO_AUDIO_BATCH_PARAMS
lowercase__ = frozenset(
[
'num_inference_steps',
'num_waveforms_per_prompt',
'generator',
'latents',
'output_type',
'return_dict',
'callback',
'callback_steps',
] )
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
torch.manual_seed(0)
_UpperCamelCase = UNetaDConditionModel(
block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=(32, 64) , class_embed_type='''simple_projection''' , projection_class_embeddings_input_dim=32 , class_embeddings_concat=__a , )
_UpperCamelCase = DDIMScheduler(
beta_start=0.0_0085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , clip_sample=__a , set_alpha_to_one=__a , )
torch.manual_seed(0)
_UpperCamelCase = AutoencoderKL(
block_out_channels=[32, 64] , in_channels=1 , out_channels=1 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , )
torch.manual_seed(0)
_UpperCamelCase = ClapTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , projection_dim=32 , )
_UpperCamelCase = ClapTextModelWithProjection(__a)
_UpperCamelCase = RobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-random-roberta''' , model_max_length=77)
_UpperCamelCase = SpeechTaHifiGanConfig(
model_in_dim=8 , sampling_rate=1_60_00 , upsample_initial_channel=16 , upsample_rates=[2, 2] , upsample_kernel_sizes=[4, 4] , resblock_kernel_sizes=[3, 7] , resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]] , normalize_before=__a , )
_UpperCamelCase = SpeechTaHifiGan(__a)
_UpperCamelCase = {
'''unet''': unet,
'''scheduler''': scheduler,
'''vae''': vae,
'''text_encoder''': text_encoder,
'''tokenizer''': tokenizer,
'''vocoder''': vocoder,
}
return components
def UpperCAmelCase ( self , __a , __a=0) -> str:
'''simple docstring'''
if str(__a).startswith('''mps'''):
_UpperCamelCase = torch.manual_seed(__a)
else:
_UpperCamelCase = torch.Generator(device=__a).manual_seed(__a)
_UpperCamelCase = {
'''prompt''': '''A hammer hitting a wooden surface''',
'''generator''': generator,
'''num_inference_steps''': 2,
'''guidance_scale''': 6.0,
}
return inputs
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator
_UpperCamelCase = self.get_dummy_components()
_UpperCamelCase = AudioLDMPipeline(**__a)
_UpperCamelCase = audioldm_pipe.to(__a)
audioldm_pipe.set_progress_bar_config(disable=__a)
_UpperCamelCase = self.get_dummy_inputs(__a)
_UpperCamelCase = audioldm_pipe(**__a)
_UpperCamelCase = output.audios[0]
assert audio.ndim == 1
assert len(__a) == 2_56
_UpperCamelCase = audio[:10]
_UpperCamelCase = np.array(
[-0.0050, 0.0050, -0.0060, 0.0033, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0033])
assert np.abs(audio_slice - expected_slice).max() < 1e-2
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = self.get_dummy_components()
_UpperCamelCase = AudioLDMPipeline(**__a)
_UpperCamelCase = audioldm_pipe.to(__a)
_UpperCamelCase = audioldm_pipe.to(__a)
audioldm_pipe.set_progress_bar_config(disable=__a)
_UpperCamelCase = self.get_dummy_inputs(__a)
_UpperCamelCase = 3 * [inputs['''prompt''']]
# forward
_UpperCamelCase = audioldm_pipe(**__a)
_UpperCamelCase = output.audios[0]
_UpperCamelCase = self.get_dummy_inputs(__a)
_UpperCamelCase = 3 * [inputs.pop('''prompt''')]
_UpperCamelCase = audioldm_pipe.tokenizer(
__a , padding='''max_length''' , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=__a , return_tensors='''pt''' , )
_UpperCamelCase = text_inputs['''input_ids'''].to(__a)
_UpperCamelCase = audioldm_pipe.text_encoder(
__a , )
_UpperCamelCase = prompt_embeds.text_embeds
# additional L_2 normalization over each hidden-state
_UpperCamelCase = F.normalize(__a , dim=-1)
_UpperCamelCase = prompt_embeds
# forward
_UpperCamelCase = audioldm_pipe(**__a)
_UpperCamelCase = output.audios[0]
assert np.abs(audio_a - audio_a).max() < 1e-2
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
_UpperCamelCase = self.get_dummy_components()
_UpperCamelCase = AudioLDMPipeline(**__a)
_UpperCamelCase = audioldm_pipe.to(__a)
_UpperCamelCase = audioldm_pipe.to(__a)
audioldm_pipe.set_progress_bar_config(disable=__a)
_UpperCamelCase = self.get_dummy_inputs(__a)
_UpperCamelCase = 3 * ['''this is a negative prompt''']
_UpperCamelCase = negative_prompt
_UpperCamelCase = 3 * [inputs['''prompt''']]
# forward
_UpperCamelCase = audioldm_pipe(**__a)
_UpperCamelCase = output.audios[0]
_UpperCamelCase = self.get_dummy_inputs(__a)
_UpperCamelCase = 3 * [inputs.pop('''prompt''')]
_UpperCamelCase = []
for p in [prompt, negative_prompt]:
_UpperCamelCase = audioldm_pipe.tokenizer(
__a , padding='''max_length''' , max_length=audioldm_pipe.tokenizer.model_max_length , truncation=__a , return_tensors='''pt''' , )
_UpperCamelCase = text_inputs['''input_ids'''].to(__a)
_UpperCamelCase = audioldm_pipe.text_encoder(
__a , )
_UpperCamelCase = text_embeds.text_embeds
# additional L_2 normalization over each hidden-state
_UpperCamelCase = F.normalize(__a , dim=-1)
embeds.append(__a)
_UpperCamelCase , _UpperCamelCase = embeds
# forward
_UpperCamelCase = audioldm_pipe(**__a)
_UpperCamelCase = output.audios[0]
assert np.abs(audio_a - audio_a).max() < 1e-2
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator
_UpperCamelCase = self.get_dummy_components()
_UpperCamelCase = PNDMScheduler(skip_prk_steps=__a)
_UpperCamelCase = AudioLDMPipeline(**__a)
_UpperCamelCase = audioldm_pipe.to(__a)
audioldm_pipe.set_progress_bar_config(disable=__a)
_UpperCamelCase = self.get_dummy_inputs(__a)
_UpperCamelCase = '''egg cracking'''
_UpperCamelCase = audioldm_pipe(**__a , negative_prompt=__a)
_UpperCamelCase = output.audios[0]
assert audio.ndim == 1
assert len(__a) == 2_56
_UpperCamelCase = audio[:10]
_UpperCamelCase = np.array(
[-0.0051, 0.0050, -0.0060, 0.0034, -0.0026, 0.0033, -0.0027, 0.0033, -0.0028, 0.0032])
assert np.abs(audio_slice - expected_slice).max() < 1e-2
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator
_UpperCamelCase = self.get_dummy_components()
_UpperCamelCase = PNDMScheduler(skip_prk_steps=__a)
_UpperCamelCase = AudioLDMPipeline(**__a)
_UpperCamelCase = audioldm_pipe.to(__a)
audioldm_pipe.set_progress_bar_config(disable=__a)
_UpperCamelCase = '''A hammer hitting a wooden surface'''
# test num_waveforms_per_prompt=1 (default)
_UpperCamelCase = audioldm_pipe(__a , num_inference_steps=2).audios
assert audios.shape == (1, 2_56)
# test num_waveforms_per_prompt=1 (default) for batch of prompts
_UpperCamelCase = 2
_UpperCamelCase = audioldm_pipe([prompt] * batch_size , num_inference_steps=2).audios
assert audios.shape == (batch_size, 2_56)
# test num_waveforms_per_prompt for single prompt
_UpperCamelCase = 2
_UpperCamelCase = audioldm_pipe(__a , num_inference_steps=2 , num_waveforms_per_prompt=__a).audios
assert audios.shape == (num_waveforms_per_prompt, 2_56)
# test num_waveforms_per_prompt for batch of prompts
_UpperCamelCase = 2
_UpperCamelCase = audioldm_pipe(
[prompt] * batch_size , num_inference_steps=2 , num_waveforms_per_prompt=__a).audios
assert audios.shape == (batch_size * num_waveforms_per_prompt, 2_56)
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
_UpperCamelCase = '''cpu''' # ensure determinism for the device-dependent torch.Generator
_UpperCamelCase = self.get_dummy_components()
_UpperCamelCase = AudioLDMPipeline(**__a)
_UpperCamelCase = audioldm_pipe.to(__a)
audioldm_pipe.set_progress_bar_config(disable=__a)
_UpperCamelCase = audioldm_pipe.vocoder.config.sampling_rate
_UpperCamelCase = self.get_dummy_inputs(__a)
_UpperCamelCase = audioldm_pipe(audio_length_in_s=0.016 , **__a)
_UpperCamelCase = output.audios[0]
assert audio.ndim == 1
assert len(__a) / vocoder_sampling_rate == 0.016
_UpperCamelCase = audioldm_pipe(audio_length_in_s=0.032 , **__a)
_UpperCamelCase = output.audios[0]
assert audio.ndim == 1
assert len(__a) / vocoder_sampling_rate == 0.032
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase = self.get_dummy_components()
_UpperCamelCase = AudioLDMPipeline(**__a)
_UpperCamelCase = audioldm_pipe.to(__a)
audioldm_pipe.set_progress_bar_config(disable=__a)
_UpperCamelCase = ['''hey''']
_UpperCamelCase = audioldm_pipe(__a , num_inference_steps=1)
_UpperCamelCase = output.audios.shape
assert audio_shape == (1, 2_56)
_UpperCamelCase = audioldm_pipe.vocoder.config
config.model_in_dim *= 2
_UpperCamelCase = SpeechTaHifiGan(__a).to(__a)
_UpperCamelCase = audioldm_pipe(__a , num_inference_steps=1)
_UpperCamelCase = output.audios.shape
# waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram
assert audio_shape == (1, 2_56)
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
self._test_attention_slicing_forward_pass(test_mean_pixel_difference=__a)
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
self._test_inference_batch_single_identical(test_mean_pixel_difference=__a)
@unittest.skipIf(
torch_device != '''cuda''' or not is_xformers_available() , reason='''XFormers attention is only available with CUDA and `xformers` installed''' , )
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=__a)
@slow
class _UpperCAmelCase( unittest.TestCase ):
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def UpperCAmelCase ( self , __a , __a="cpu" , __a=torch.floataa , __a=0) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = torch.Generator(device=__a).manual_seed(__a)
_UpperCamelCase = np.random.RandomState(__a).standard_normal((1, 8, 1_28, 16))
_UpperCamelCase = torch.from_numpy(__a).to(device=__a , dtype=__a)
_UpperCamelCase = {
'''prompt''': '''A hammer hitting a wooden surface''',
'''latents''': latents,
'''generator''': generator,
'''num_inference_steps''': 3,
'''guidance_scale''': 2.5,
}
return inputs
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = AudioLDMPipeline.from_pretrained('''cvssp/audioldm''')
_UpperCamelCase = audioldm_pipe.to(__a)
audioldm_pipe.set_progress_bar_config(disable=__a)
_UpperCamelCase = self.get_inputs(__a)
_UpperCamelCase = 25
_UpperCamelCase = audioldm_pipe(**__a).audios[0]
assert audio.ndim == 1
assert len(__a) == 8_19_20
_UpperCamelCase = audio[7_72_30:7_72_40]
_UpperCamelCase = np.array(
[-0.4884, -0.4607, 0.0023, 0.5007, 0.5896, 0.5151, 0.3813, -0.0208, -0.3687, -0.4315])
_UpperCamelCase = np.abs(expected_slice - audio_slice).max()
assert max_diff < 1e-2
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = AudioLDMPipeline.from_pretrained('''cvssp/audioldm''')
_UpperCamelCase = LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config)
_UpperCamelCase = audioldm_pipe.to(__a)
audioldm_pipe.set_progress_bar_config(disable=__a)
_UpperCamelCase = self.get_inputs(__a)
_UpperCamelCase = audioldm_pipe(**__a).audios[0]
assert audio.ndim == 1
assert len(__a) == 8_19_20
_UpperCamelCase = audio[2_77_80:2_77_90]
_UpperCamelCase = np.array([-0.2131, -0.0873, -0.0124, -0.0189, 0.0569, 0.1373, 0.1883, 0.2886, 0.3297, 0.2212])
_UpperCamelCase = np.abs(expected_slice - audio_slice).max()
assert max_diff < 3e-2
| 702 |
"""simple docstring"""
import argparse
import torch
from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration
from transformers.utils import logging
logging.set_verbosity_info()
_a = logging.get_logger(__name__)
_a = [
["""attention""", """attn"""],
["""encoder_attention""", """encoder_attn"""],
["""q_lin""", """q_proj"""],
["""k_lin""", """k_proj"""],
["""v_lin""", """v_proj"""],
["""out_lin""", """out_proj"""],
["""norm_embeddings""", """layernorm_embedding"""],
["""position_embeddings""", """embed_positions"""],
["""embeddings""", """embed_tokens"""],
["""ffn.lin""", """fc"""],
]
def lowerCamelCase__ ( __snake_case ) -> Optional[Any]:
"""simple docstring"""
if k == "embeddings.weight":
return "shared.weight"
for parlai_name, hf_name in PATTERNS:
_UpperCamelCase = k.replace(__snake_case, __snake_case )
if k.startswith('''encoder''' ):
_UpperCamelCase = k.replace('''.attn''', '''.self_attn''' )
_UpperCamelCase = k.replace('''norm1''', '''self_attn_layer_norm''' )
_UpperCamelCase = k.replace('''norm2''', '''final_layer_norm''' )
elif k.startswith('''decoder''' ):
_UpperCamelCase = k.replace('''norm1''', '''self_attn_layer_norm''' )
_UpperCamelCase = k.replace('''norm2''', '''encoder_attn_layer_norm''' )
_UpperCamelCase = k.replace('''norm3''', '''final_layer_norm''' )
return k
def lowerCamelCase__ ( __snake_case ) -> Optional[int]:
"""simple docstring"""
_UpperCamelCase = [
'''model.encoder.layernorm_embedding.weight''',
'''model.encoder.layernorm_embedding.bias''',
'''model.decoder.layernorm_embedding.weight''',
'''model.decoder.layernorm_embedding.bias''',
]
for k in keys:
_UpperCamelCase = sd.pop(__snake_case )
_UpperCamelCase = k.replace('''layernorm_embedding''', '''layer_norm''' )
assert new_k not in sd
_UpperCamelCase = v
_a = ["""START"""]
@torch.no_grad()
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> int:
"""simple docstring"""
_UpperCamelCase = torch.load(__snake_case, map_location='''cpu''' )
_UpperCamelCase = model['''model''']
_UpperCamelCase = BlenderbotConfig.from_json_file(__snake_case )
_UpperCamelCase = BlenderbotForConditionalGeneration(__snake_case )
_UpperCamelCase = m.model.state_dict().keys()
_UpperCamelCase = []
_UpperCamelCase = {}
for k, v in sd.items():
if k in IGNORE_KEYS:
continue
_UpperCamelCase = rename_state_dict_key(__snake_case )
if new_k not in valid_keys:
failures.append([k, new_k] )
else:
_UpperCamelCase = v
if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm
rename_layernorm_keys(__snake_case )
m.model.load_state_dict(__snake_case, strict=__snake_case )
m.half()
m.save_pretrained(__snake_case )
if __name__ == "__main__":
_a = argparse.ArgumentParser()
# Required parameters
parser.add_argument("""--src_path""", type=str, help="""like blenderbot-model.bin""")
parser.add_argument("""--save_dir""", default="""hf_blenderbot""", type=str, help="""Where to save converted model.""")
parser.add_argument(
"""--hf_config_json""", default="""blenderbot-3b-config.json""", type=str, help="""Path to config to use"""
)
_a = parser.parse_args()
convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
| 78 | 0 |
"""simple docstring"""
from collections import OrderedDict
from typing import Any, Mapping, Optional
from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast
from ...utils import logging
_a = logging.get_logger(__name__)
_a = {
"""EleutherAI/gpt-neo-1.3B""": """https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json""",
# See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo
}
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = 'gpt_neo'
lowercase__ = ['past_key_values']
lowercase__ = {'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers'}
def __init__( self , __a=5_02_57 , __a=20_48 , __a=20_48 , __a=24 , __a=[[["global", "local"], 12]] , __a=16 , __a=None , __a=2_56 , __a="gelu_new" , __a=0.0 , __a=0.0 , __a=0.0 , __a=0.1 , __a=1e-5 , __a=0.02 , __a=True , __a=5_02_56 , __a=5_02_56 , **__a , ) -> Union[str, Any]:
'''simple docstring'''
_UpperCamelCase = vocab_size
_UpperCamelCase = max_position_embeddings
_UpperCamelCase = hidden_size
_UpperCamelCase = num_layers
_UpperCamelCase = num_heads
_UpperCamelCase = intermediate_size
_UpperCamelCase = window_size
_UpperCamelCase = activation_function
_UpperCamelCase = resid_dropout
_UpperCamelCase = embed_dropout
_UpperCamelCase = attention_dropout
_UpperCamelCase = classifier_dropout
_UpperCamelCase = layer_norm_epsilon
_UpperCamelCase = initializer_range
_UpperCamelCase = use_cache
_UpperCamelCase = bos_token_id
_UpperCamelCase = eos_token_id
_UpperCamelCase = attention_types
_UpperCamelCase = self.expand_attention_types_params(__a)
if len(self.attention_layers) != self.num_layers:
raise ValueError(
'''Configuration for convolutional module is incorrect. '''
'''It is required that `len(config.attention_layers)` == `config.num_layers` '''
F'''but is `len(config.attention_layers) = {len(self.attention_layers)}`, '''
F'''`config.num_layers = {self.num_layers}`. '''
'''`config.attention_layers` is prepared using `config.attention_types`. '''
'''Please verify the value of `config.attention_types` argument.''')
super().__init__(bos_token_id=__a , eos_token_id=__a , **__a)
@staticmethod
def UpperCAmelCase ( __a) -> int:
'''simple docstring'''
_UpperCamelCase = []
for item in attention_types:
for _ in range(item[1]):
attentions.extend(item[0])
return attentions
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case, __snake_case ) -> str:
"""simple docstring"""
import torch
_UpperCamelCase = input.size()
_UpperCamelCase = len(__snake_case )
_UpperCamelCase = shape[dimension]
_UpperCamelCase = torch.arange(0, __snake_case, __snake_case )
_UpperCamelCase = torch.div(sizedim - size, __snake_case, rounding_mode='''floor''' ) + 1
_UpperCamelCase = torch.arange(__snake_case ) + low_indices[:min_length][:, None]
_UpperCamelCase = [slice(__snake_case )] * rank
_UpperCamelCase = indices
_UpperCamelCase = input[s]
_UpperCamelCase = list(range(0, rank + 1 ) )
perm.append(perm.pop(dimension + 1 ) )
return sliced.permute(__snake_case )
def lowerCamelCase__ ( __snake_case, __snake_case ) -> str:
"""simple docstring"""
import torch
_UpperCamelCase = torch.arange(1, __snake_case )
_UpperCamelCase = torch.remainder(__snake_case, __snake_case )
_UpperCamelCase = remainders == 0
_UpperCamelCase = candidates[divisor_indices]
_UpperCamelCase = torch.max(__snake_case )
return largest_divisor, torch.div(__snake_case, __snake_case, rounding_mode='''floor''' )
class _UpperCAmelCase( lowerCamelCase ):
@property
def UpperCAmelCase ( self) -> Mapping[str, Mapping[int, str]]:
'''simple docstring'''
_UpperCamelCase = OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}})
if self.use_past:
self.fill_with_past_key_values_(__a , direction='''inputs''')
_UpperCamelCase = {0: '''batch''', 1: '''past_sequence + sequence'''}
else:
_UpperCamelCase = {0: '''batch''', 1: '''sequence'''}
return common_inputs
@property
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
return self._config.num_heads
def UpperCAmelCase ( self , __a , __a = -1 , __a = -1 , __a = False , __a = None , ) -> Mapping[str, Any]:
'''simple docstring'''
_UpperCamelCase = 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()
_UpperCamelCase = 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
_UpperCamelCase , _UpperCamelCase = common_inputs['''input_ids'''].shape
# Not using the same length for past_key_values
_UpperCamelCase = seqlen + 2
_UpperCamelCase = (
batch,
self.num_attention_heads,
past_key_values_length,
self._config.hidden_size // self.num_attention_heads,
)
_UpperCamelCase = [
(torch.zeros(__a), torch.zeros(__a)) for _ in range(self.num_layers)
]
_UpperCamelCase = common_inputs['''attention_mask''']
if self.use_past:
_UpperCamelCase = ordered_inputs['''attention_mask'''].dtype
_UpperCamelCase = torch.cat(
[ordered_inputs['''attention_mask'''], torch.ones(__a , __a , dtype=__a)] , dim=1)
return ordered_inputs
@property
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
return 13
| 703 |
"""simple docstring"""
import argparse
import os.path as osp
import re
import torch
from safetensors.torch import load_file, save_file
# =================#
# UNet Conversion #
# =================#
_a = [
# (stable-diffusion, HF Diffusers)
("""time_embed.0.weight""", """time_embedding.linear_1.weight"""),
("""time_embed.0.bias""", """time_embedding.linear_1.bias"""),
("""time_embed.2.weight""", """time_embedding.linear_2.weight"""),
("""time_embed.2.bias""", """time_embedding.linear_2.bias"""),
("""input_blocks.0.0.weight""", """conv_in.weight"""),
("""input_blocks.0.0.bias""", """conv_in.bias"""),
("""out.0.weight""", """conv_norm_out.weight"""),
("""out.0.bias""", """conv_norm_out.bias"""),
("""out.2.weight""", """conv_out.weight"""),
("""out.2.bias""", """conv_out.bias"""),
]
_a = [
# (stable-diffusion, HF Diffusers)
("""in_layers.0""", """norm1"""),
("""in_layers.2""", """conv1"""),
("""out_layers.0""", """norm2"""),
("""out_layers.3""", """conv2"""),
("""emb_layers.1""", """time_emb_proj"""),
("""skip_connection""", """conv_shortcut"""),
]
_a = []
# hardcoded number of downblocks and resnets/attentions...
# would need smarter logic for other networks.
for i in range(4):
# loop over downblocks/upblocks
for j in range(2):
# loop over resnets/attentions for downblocks
_a = F"""down_blocks.{i}.resnets.{j}."""
_a = F"""input_blocks.{3*i + j + 1}.0."""
unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix))
if i < 3:
# no attention layers in down_blocks.3
_a = F"""down_blocks.{i}.attentions.{j}."""
_a = F"""input_blocks.{3*i + j + 1}.1."""
unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix))
for j in range(3):
# loop over resnets/attentions for upblocks
_a = F"""up_blocks.{i}.resnets.{j}."""
_a = F"""output_blocks.{3*i + j}.0."""
unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix))
if i > 0:
# no attention layers in up_blocks.0
_a = F"""up_blocks.{i}.attentions.{j}."""
_a = F"""output_blocks.{3*i + j}.1."""
unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix))
if i < 3:
# no downsample in down_blocks.3
_a = F"""down_blocks.{i}.downsamplers.0.conv."""
_a = F"""input_blocks.{3*(i+1)}.0.op."""
unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix))
# no upsample in up_blocks.3
_a = F"""up_blocks.{i}.upsamplers.0."""
_a = F"""output_blocks.{3*i + 2}.{1 if i == 0 else 2}."""
unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix))
_a = """mid_block.attentions.0."""
_a = """middle_block.1."""
unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix))
for j in range(2):
_a = F"""mid_block.resnets.{j}."""
_a = F"""middle_block.{2*j}."""
unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix))
def lowerCamelCase__ ( __snake_case ) -> str:
"""simple docstring"""
_UpperCamelCase = {k: k for k in unet_state_dict.keys()}
for sd_name, hf_name in unet_conversion_map:
_UpperCamelCase = sd_name
for k, v in mapping.items():
if "resnets" in k:
for sd_part, hf_part in unet_conversion_map_resnet:
_UpperCamelCase = v.replace(__snake_case, __snake_case )
_UpperCamelCase = v
for k, v in mapping.items():
for sd_part, hf_part in unet_conversion_map_layer:
_UpperCamelCase = v.replace(__snake_case, __snake_case )
_UpperCamelCase = v
_UpperCamelCase = {v: unet_state_dict[k] for k, v in mapping.items()}
return new_state_dict
# ================#
# VAE Conversion #
# ================#
_a = [
# (stable-diffusion, HF Diffusers)
("""nin_shortcut""", """conv_shortcut"""),
("""norm_out""", """conv_norm_out"""),
("""mid.attn_1.""", """mid_block.attentions.0."""),
]
for i in range(4):
# down_blocks have two resnets
for j in range(2):
_a = F"""encoder.down_blocks.{i}.resnets.{j}."""
_a = F"""encoder.down.{i}.block.{j}."""
vae_conversion_map.append((sd_down_prefix, hf_down_prefix))
if i < 3:
_a = F"""down_blocks.{i}.downsamplers.0."""
_a = F"""down.{i}.downsample."""
vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix))
_a = F"""up_blocks.{i}.upsamplers.0."""
_a = F"""up.{3-i}.upsample."""
vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix))
# up_blocks have three resnets
# also, up blocks in hf are numbered in reverse from sd
for j in range(3):
_a = F"""decoder.up_blocks.{i}.resnets.{j}."""
_a = F"""decoder.up.{3-i}.block.{j}."""
vae_conversion_map.append((sd_up_prefix, hf_up_prefix))
# this part accounts for mid blocks in both the encoder and the decoder
for i in range(2):
_a = F"""mid_block.resnets.{i}."""
_a = F"""mid.block_{i+1}."""
vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix))
_a = [
# (stable-diffusion, HF Diffusers)
("""norm.""", """group_norm."""),
("""q.""", """query."""),
("""k.""", """key."""),
("""v.""", """value."""),
("""proj_out.""", """proj_attn."""),
]
def lowerCamelCase__ ( __snake_case ) -> List[str]:
"""simple docstring"""
return w.reshape(*w.shape, 1, 1 )
def lowerCamelCase__ ( __snake_case ) -> Optional[Any]:
"""simple docstring"""
_UpperCamelCase = {k: k for k in vae_state_dict.keys()}
for k, v in mapping.items():
for sd_part, hf_part in vae_conversion_map:
_UpperCamelCase = v.replace(__snake_case, __snake_case )
_UpperCamelCase = v
for k, v in mapping.items():
if "attentions" in k:
for sd_part, hf_part in vae_conversion_map_attn:
_UpperCamelCase = v.replace(__snake_case, __snake_case )
_UpperCamelCase = v
_UpperCamelCase = {v: vae_state_dict[k] for k, v in mapping.items()}
_UpperCamelCase = ['''q''', '''k''', '''v''', '''proj_out''']
for k, v in new_state_dict.items():
for weight_name in weights_to_convert:
if F'''mid.attn_1.{weight_name}.weight''' in k:
print(F'''Reshaping {k} for SD format''' )
_UpperCamelCase = reshape_weight_for_sd(__snake_case )
return new_state_dict
# =========================#
# Text Encoder Conversion #
# =========================#
_a = [
# (stable-diffusion, HF Diffusers)
("""resblocks.""", """text_model.encoder.layers."""),
("""ln_1""", """layer_norm1"""),
("""ln_2""", """layer_norm2"""),
(""".c_fc.""", """.fc1."""),
(""".c_proj.""", """.fc2."""),
(""".attn""", """.self_attn"""),
("""ln_final.""", """transformer.text_model.final_layer_norm."""),
("""token_embedding.weight""", """transformer.text_model.embeddings.token_embedding.weight"""),
("""positional_embedding""", """transformer.text_model.embeddings.position_embedding.weight"""),
]
_a = {re.escape(x[1]): x[0] for x in textenc_conversion_lst}
_a = re.compile("""|""".join(protected.keys()))
# Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp
_a = {"""q""": 0, """k""": 1, """v""": 2}
def lowerCamelCase__ ( __snake_case ) -> Any:
"""simple docstring"""
_UpperCamelCase = {}
_UpperCamelCase = {}
_UpperCamelCase = {}
for k, v in text_enc_dict.items():
if (
k.endswith('''.self_attn.q_proj.weight''' )
or k.endswith('''.self_attn.k_proj.weight''' )
or k.endswith('''.self_attn.v_proj.weight''' )
):
_UpperCamelCase = k[: -len('''.q_proj.weight''' )]
_UpperCamelCase = k[-len('''q_proj.weight''' )]
if k_pre not in capture_qkv_weight:
_UpperCamelCase = [None, None, None]
_UpperCamelCase = v
continue
if (
k.endswith('''.self_attn.q_proj.bias''' )
or k.endswith('''.self_attn.k_proj.bias''' )
or k.endswith('''.self_attn.v_proj.bias''' )
):
_UpperCamelCase = k[: -len('''.q_proj.bias''' )]
_UpperCamelCase = k[-len('''q_proj.bias''' )]
if k_pre not in capture_qkv_bias:
_UpperCamelCase = [None, None, None]
_UpperCamelCase = v
continue
_UpperCamelCase = textenc_pattern.sub(lambda __snake_case : protected[re.escape(m.group(0 ) )], __snake_case )
_UpperCamelCase = v
for k_pre, tensors in capture_qkv_weight.items():
if None in tensors:
raise Exception('''CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing''' )
_UpperCamelCase = textenc_pattern.sub(lambda __snake_case : protected[re.escape(m.group(0 ) )], __snake_case )
_UpperCamelCase = torch.cat(__snake_case )
for k_pre, tensors in capture_qkv_bias.items():
if None in tensors:
raise Exception('''CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing''' )
_UpperCamelCase = textenc_pattern.sub(lambda __snake_case : protected[re.escape(m.group(0 ) )], __snake_case )
_UpperCamelCase = torch.cat(__snake_case )
return new_state_dict
def lowerCamelCase__ ( __snake_case ) -> Tuple:
"""simple docstring"""
return text_enc_dict
if __name__ == "__main__":
_a = argparse.ArgumentParser()
parser.add_argument("""--model_path""", default=None, type=str, required=True, help="""Path to the model to convert.""")
parser.add_argument("""--checkpoint_path""", default=None, type=str, required=True, help="""Path to the output model.""")
parser.add_argument("""--half""", action="""store_true""", help="""Save weights in half precision.""")
parser.add_argument(
"""--use_safetensors""", action="""store_true""", help="""Save weights use safetensors, default is ckpt."""
)
_a = parser.parse_args()
assert args.model_path is not None, "Must provide a model path!"
assert args.checkpoint_path is not None, "Must provide a checkpoint path!"
# Path for safetensors
_a = osp.join(args.model_path, """unet""", """diffusion_pytorch_model.safetensors""")
_a = osp.join(args.model_path, """vae""", """diffusion_pytorch_model.safetensors""")
_a = osp.join(args.model_path, """text_encoder""", """model.safetensors""")
# Load models from safetensors if it exists, if it doesn't pytorch
if osp.exists(unet_path):
_a = load_file(unet_path, device="""cpu""")
else:
_a = osp.join(args.model_path, """unet""", """diffusion_pytorch_model.bin""")
_a = torch.load(unet_path, map_location="""cpu""")
if osp.exists(vae_path):
_a = load_file(vae_path, device="""cpu""")
else:
_a = osp.join(args.model_path, """vae""", """diffusion_pytorch_model.bin""")
_a = torch.load(vae_path, map_location="""cpu""")
if osp.exists(text_enc_path):
_a = load_file(text_enc_path, device="""cpu""")
else:
_a = osp.join(args.model_path, """text_encoder""", """pytorch_model.bin""")
_a = torch.load(text_enc_path, map_location="""cpu""")
# Convert the UNet model
_a = convert_unet_state_dict(unet_state_dict)
_a = {"""model.diffusion_model.""" + k: v for k, v in unet_state_dict.items()}
# Convert the VAE model
_a = convert_vae_state_dict(vae_state_dict)
_a = {"""first_stage_model.""" + k: v for k, v in vae_state_dict.items()}
# Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper
_a = """text_model.encoder.layers.22.layer_norm2.bias""" in text_enc_dict
if is_vaa_model:
# Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm
_a = {"""transformer.""" + k: v for k, v in text_enc_dict.items()}
_a = convert_text_enc_state_dict_vaa(text_enc_dict)
_a = {"""cond_stage_model.model.""" + k: v for k, v in text_enc_dict.items()}
else:
_a = convert_text_enc_state_dict(text_enc_dict)
_a = {"""cond_stage_model.transformer.""" + k: v for k, v in text_enc_dict.items()}
# Put together new checkpoint
_a = {**unet_state_dict, **vae_state_dict, **text_enc_dict}
if args.half:
_a = {k: v.half() for k, v in state_dict.items()}
if args.use_safetensors:
save_file(state_dict, args.checkpoint_path)
else:
_a = {"""state_dict""": state_dict}
torch.save(state_dict, args.checkpoint_path)
| 78 | 0 |
"""simple docstring"""
import json
import os
from dataclasses import dataclass
from functools import partial
from typing import Callable
import flax.linen as nn
import jax
import jax.numpy as jnp
import joblib
import optax
import wandb
from flax import jax_utils, struct, traverse_util
from flax.serialization import from_bytes, to_bytes
from flax.training import train_state
from flax.training.common_utils import shard
from tqdm.auto import tqdm
from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering
from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = 42
lowercase__ = jnp.floataa
lowercase__ = True
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
super().setup()
_UpperCamelCase = nn.Dense(5 , dtype=self.dtype)
def __call__( self , *__a , **__a) -> Dict:
'''simple docstring'''
_UpperCamelCase = super().__call__(*__a , **__a)
_UpperCamelCase = self.cls(outputs[2])
return outputs[:2] + (cls_out,)
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = FlaxBigBirdForNaturalQuestionsModule
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case, __snake_case, __snake_case, __snake_case ) -> List[str]:
"""simple docstring"""
def cross_entropy(__snake_case, __snake_case, __snake_case=None ):
_UpperCamelCase = logits.shape[-1]
_UpperCamelCase = (labels[..., None] == jnp.arange(__snake_case )[None]).astype('''f4''' )
_UpperCamelCase = jax.nn.log_softmax(__snake_case, axis=-1 )
_UpperCamelCase = -jnp.sum(labels * logits, axis=-1 )
if reduction is not None:
_UpperCamelCase = reduction(__snake_case )
return loss
_UpperCamelCase = partial(__snake_case, reduction=jnp.mean )
_UpperCamelCase = cross_entropy(__snake_case, __snake_case )
_UpperCamelCase = cross_entropy(__snake_case, __snake_case )
_UpperCamelCase = cross_entropy(__snake_case, __snake_case )
return (start_loss + end_loss + pooled_loss) / 3
@dataclass
class _UpperCAmelCase:
lowercase__ = 'google/bigbird-roberta-base'
lowercase__ = 30_00
lowercase__ = 1_05_00
lowercase__ = 1_28
lowercase__ = 3
lowercase__ = 1
lowercase__ = 5
# tx_args
lowercase__ = 3E-5
lowercase__ = 0.0
lowercase__ = 2_00_00
lowercase__ = 0.00_95
lowercase__ = 'bigbird-roberta-natural-questions'
lowercase__ = 'training-expt'
lowercase__ = 'data/nq-training.jsonl'
lowercase__ = 'data/nq-validation.jsonl'
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
os.makedirs(self.base_dir , exist_ok=__a)
_UpperCamelCase = os.path.join(self.base_dir , self.save_dir)
_UpperCamelCase = self.batch_size_per_device * jax.device_count()
@dataclass
class _UpperCAmelCase:
lowercase__ = 42
lowercase__ = 40_96 # no dynamic padding on TPUs
def __call__( self , __a) -> Dict:
'''simple docstring'''
_UpperCamelCase = self.collate_fn(__a)
_UpperCamelCase = jax.tree_util.tree_map(__a , __a)
return batch
def UpperCAmelCase ( self , __a) -> Tuple:
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase = self.fetch_inputs(features['''input_ids'''])
_UpperCamelCase = {
'''input_ids''': jnp.array(__a , dtype=jnp.intaa),
'''attention_mask''': jnp.array(__a , dtype=jnp.intaa),
'''start_labels''': jnp.array(features['''start_token'''] , dtype=jnp.intaa),
'''end_labels''': jnp.array(features['''end_token'''] , dtype=jnp.intaa),
'''pooled_labels''': jnp.array(features['''category'''] , dtype=jnp.intaa),
}
return batch
def UpperCAmelCase ( self , __a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = [self._fetch_inputs(__a) for ids in input_ids]
return zip(*__a)
def UpperCAmelCase ( self , __a) -> Any:
'''simple docstring'''
_UpperCamelCase = [1 for _ in range(len(__a))]
while len(__a) < self.max_length:
input_ids.append(self.pad_id)
attention_mask.append(0)
return input_ids, attention_mask
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case=None ) -> Optional[Any]:
"""simple docstring"""
if seed is not None:
_UpperCamelCase = dataset.shuffle(seed=__snake_case )
for i in range(len(__snake_case ) // batch_size ):
_UpperCamelCase = dataset[i * batch_size : (i + 1) * batch_size]
yield dict(__snake_case )
@partial(jax.pmap, axis_name='''batch''' )
def lowerCamelCase__ ( __snake_case, __snake_case, **__snake_case ) -> Union[str, Any]:
"""simple docstring"""
def loss_fn(__snake_case ):
_UpperCamelCase = model_inputs.pop('''start_labels''' )
_UpperCamelCase = model_inputs.pop('''end_labels''' )
_UpperCamelCase = model_inputs.pop('''pooled_labels''' )
_UpperCamelCase = state.apply_fn(**__snake_case, params=__snake_case, dropout_rng=__snake_case, train=__snake_case )
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = outputs
return state.loss_fn(
__snake_case, __snake_case, __snake_case, __snake_case, __snake_case, __snake_case, )
_UpperCamelCase , _UpperCamelCase = jax.random.split(__snake_case )
_UpperCamelCase = jax.value_and_grad(__snake_case )
_UpperCamelCase , _UpperCamelCase = grad_fn(state.params )
_UpperCamelCase = jax.lax.pmean({'''loss''': loss}, axis_name='''batch''' )
_UpperCamelCase = jax.lax.pmean(__snake_case, '''batch''' )
_UpperCamelCase = state.apply_gradients(grads=__snake_case )
return state, metrics, new_drp_rng
@partial(jax.pmap, axis_name='''batch''' )
def lowerCamelCase__ ( __snake_case, **__snake_case ) -> Union[str, Any]:
"""simple docstring"""
_UpperCamelCase = model_inputs.pop('''start_labels''' )
_UpperCamelCase = model_inputs.pop('''end_labels''' )
_UpperCamelCase = model_inputs.pop('''pooled_labels''' )
_UpperCamelCase = state.apply_fn(**__snake_case, params=state.params, train=__snake_case )
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = outputs
_UpperCamelCase = state.loss_fn(__snake_case, __snake_case, __snake_case, __snake_case, __snake_case, __snake_case )
_UpperCamelCase = jax.lax.pmean({'''loss''': loss}, axis_name='''batch''' )
return metrics
class _UpperCAmelCase( train_state.TrainState ):
lowercase__ = struct.field(pytree_node=lowerCamelCase )
@dataclass
class _UpperCAmelCase:
lowercase__ = 42
lowercase__ = 42
lowercase__ = 42
lowercase__ = 42
lowercase__ = 42
lowercase__ = 42
lowercase__ = None
def UpperCAmelCase ( self , __a , __a , __a , __a=None) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = model.params
_UpperCamelCase = TrainState.create(
apply_fn=model.__call__ , params=__a , tx=__a , loss_fn=__a , )
if ckpt_dir is not None:
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase = restore_checkpoint(__a , __a)
_UpperCamelCase = {
'''lr''': args.lr,
'''init_lr''': args.init_lr,
'''warmup_steps''': args.warmup_steps,
'''num_train_steps''': num_train_steps,
'''weight_decay''': args.weight_decay,
}
_UpperCamelCase , _UpperCamelCase = build_tx(**__a)
_UpperCamelCase = train_state.TrainState(
step=__a , apply_fn=model.__call__ , params=__a , tx=__a , opt_state=__a , )
_UpperCamelCase = args
_UpperCamelCase = data_collator
_UpperCamelCase = lr
_UpperCamelCase = params
_UpperCamelCase = jax_utils.replicate(__a)
return state
def UpperCAmelCase ( self , __a , __a , __a) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = self.args
_UpperCamelCase = len(__a) // args.batch_size
_UpperCamelCase = jax.random.PRNGKey(0)
_UpperCamelCase = jax.random.split(__a , jax.device_count())
for epoch in range(args.max_epochs):
_UpperCamelCase = jnp.array(0 , dtype=jnp.floataa)
_UpperCamelCase = get_batched_dataset(__a , args.batch_size , seed=__a)
_UpperCamelCase = 0
for batch in tqdm(__a , total=__a , desc=F'''Running EPOCH-{epoch}'''):
_UpperCamelCase = self.data_collator(__a)
_UpperCamelCase , _UpperCamelCase , _UpperCamelCase = self.train_step_fn(__a , __a , **__a)
running_loss += jax_utils.unreplicate(metrics['''loss'''])
i += 1
if i % args.logging_steps == 0:
_UpperCamelCase = jax_utils.unreplicate(state.step)
_UpperCamelCase = running_loss.item() / i
_UpperCamelCase = self.scheduler_fn(state_step - 1)
_UpperCamelCase = self.evaluate(__a , __a)
_UpperCamelCase = {
'''step''': state_step.item(),
'''eval_loss''': eval_loss.item(),
'''tr_loss''': tr_loss,
'''lr''': lr.item(),
}
tqdm.write(str(__a))
self.logger.log(__a , commit=__a)
if i % args.save_steps == 0:
self.save_checkpoint(args.save_dir + F'''-e{epoch}-s{i}''' , state=__a)
def UpperCAmelCase ( self , __a , __a) -> Any:
'''simple docstring'''
_UpperCamelCase = get_batched_dataset(__a , self.args.batch_size)
_UpperCamelCase = len(__a) // self.args.batch_size
_UpperCamelCase = jnp.array(0 , dtype=jnp.floataa)
_UpperCamelCase = 0
for batch in tqdm(__a , total=__a , desc='''Evaluating ... '''):
_UpperCamelCase = self.data_collator(__a)
_UpperCamelCase = self.val_step_fn(__a , **__a)
running_loss += jax_utils.unreplicate(metrics['''loss'''])
i += 1
return running_loss / i
def UpperCAmelCase ( self , __a , __a) -> int:
'''simple docstring'''
_UpperCamelCase = jax_utils.unreplicate(__a)
print(F'''SAVING CHECKPOINT IN {save_dir}''' , end=''' ... ''')
self.model_save_fn(__a , params=state.params)
with open(os.path.join(__a , '''opt_state.msgpack''') , '''wb''') as f:
f.write(to_bytes(state.opt_state))
joblib.dump(self.args , os.path.join(__a , '''args.joblib'''))
joblib.dump(self.data_collator , os.path.join(__a , '''data_collator.joblib'''))
with open(os.path.join(__a , '''training_state.json''') , '''w''') as f:
json.dump({'''step''': state.step.item()} , __a)
print('''DONE''')
def lowerCamelCase__ ( __snake_case, __snake_case ) -> int:
"""simple docstring"""
print(F'''RESTORING CHECKPOINT FROM {save_dir}''', end=''' ... ''' )
with open(os.path.join(__snake_case, '''flax_model.msgpack''' ), '''rb''' ) as f:
_UpperCamelCase = from_bytes(state.params, f.read() )
with open(os.path.join(__snake_case, '''opt_state.msgpack''' ), '''rb''' ) as f:
_UpperCamelCase = from_bytes(state.opt_state, f.read() )
_UpperCamelCase = joblib.load(os.path.join(__snake_case, '''args.joblib''' ) )
_UpperCamelCase = joblib.load(os.path.join(__snake_case, '''data_collator.joblib''' ) )
with open(os.path.join(__snake_case, '''training_state.json''' ), '''r''' ) as f:
_UpperCamelCase = json.load(__snake_case )
_UpperCamelCase = training_state['''step''']
print('''DONE''' )
return params, opt_state, step, args, data_collator
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case, __snake_case ) -> List[str]:
"""simple docstring"""
_UpperCamelCase = num_train_steps - warmup_steps
_UpperCamelCase = optax.linear_schedule(init_value=__snake_case, end_value=__snake_case, transition_steps=__snake_case )
_UpperCamelCase = optax.linear_schedule(init_value=__snake_case, end_value=1e-7, transition_steps=__snake_case )
_UpperCamelCase = optax.join_schedules(schedules=[warmup_fn, decay_fn], boundaries=[warmup_steps] )
return lr
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case, __snake_case, __snake_case ) -> Tuple:
"""simple docstring"""
def weight_decay_mask(__snake_case ):
_UpperCamelCase = traverse_util.flatten_dict(__snake_case )
_UpperCamelCase = {k: (v[-1] != '''bias''' and v[-2:] != ('''LayerNorm''', '''scale''')) for k, v in params.items()}
return traverse_util.unflatten_dict(__snake_case )
_UpperCamelCase = scheduler_fn(__snake_case, __snake_case, __snake_case, __snake_case )
_UpperCamelCase = optax.adamw(learning_rate=__snake_case, weight_decay=__snake_case, mask=__snake_case )
return tx, lr
| 704 |
"""simple docstring"""
import argparse
import torch
from transformers import OpenAIGPTConfig, OpenAIGPTModel, load_tf_weights_in_openai_gpt
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging
logging.set_verbosity_info()
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case ) -> Union[str, Any]:
"""simple docstring"""
if openai_config_file == "":
_UpperCamelCase = OpenAIGPTConfig()
else:
_UpperCamelCase = OpenAIGPTConfig.from_json_file(__snake_case )
_UpperCamelCase = OpenAIGPTModel(__snake_case )
# Load weights from numpy
load_tf_weights_in_openai_gpt(__snake_case, __snake_case, __snake_case )
# Save pytorch-model
_UpperCamelCase = pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME
_UpperCamelCase = pytorch_dump_folder_path + '''/''' + CONFIG_NAME
print(F'''Save PyTorch model to {pytorch_weights_dump_path}''' )
torch.save(model.state_dict(), __snake_case )
print(F'''Save configuration file to {pytorch_config_dump_path}''' )
with open(__snake_case, '''w''', encoding='''utf-8''' ) as f:
f.write(config.to_json_string() )
if __name__ == "__main__":
_a = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"""--openai_checkpoint_folder_path""",
default=None,
type=str,
required=True,
help="""Path to the TensorFlow checkpoint path.""",
)
parser.add_argument(
"""--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
)
parser.add_argument(
"""--openai_config_file""",
default="""""",
type=str,
help=(
"""An optional config json file corresponding to the pre-trained OpenAI model. \n"""
"""This specifies the model architecture."""
),
)
_a = parser.parse_args()
convert_openai_checkpoint_to_pytorch(
args.openai_checkpoint_folder_path, args.openai_config_file, args.pytorch_dump_folder_path
)
| 78 | 0 |
"""simple docstring"""
import itertools
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Union
import pandas as pd
import pyarrow as pa
import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast
from datasets.utils.py_utils import Literal
_a = datasets.utils.logging.get_logger(__name__)
_a = ["""names""", """prefix"""]
_a = ["""warn_bad_lines""", """error_bad_lines""", """mangle_dupe_cols"""]
_a = ["""encoding_errors""", """on_bad_lines"""]
_a = ["""date_format"""]
@dataclass
class _UpperCAmelCase( datasets.BuilderConfig ):
lowercase__ = ','
lowercase__ = None
lowercase__ = 'infer'
lowercase__ = None
lowercase__ = None
lowercase__ = None
lowercase__ = None
lowercase__ = None
lowercase__ = True
lowercase__ = None
lowercase__ = None
lowercase__ = None
lowercase__ = None
lowercase__ = False
lowercase__ = None
lowercase__ = None
lowercase__ = None
lowercase__ = True
lowercase__ = True
lowercase__ = False
lowercase__ = True
lowercase__ = None
lowercase__ = '.'
lowercase__ = None
lowercase__ = '"'
lowercase__ = 0
lowercase__ = None
lowercase__ = None
lowercase__ = None
lowercase__ = None
lowercase__ = True
lowercase__ = True
lowercase__ = 0
lowercase__ = True
lowercase__ = False
lowercase__ = None
lowercase__ = 1_00_00
lowercase__ = None
lowercase__ = 'strict'
lowercase__ = 'error'
lowercase__ = None
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
if self.delimiter is not None:
_UpperCamelCase = self.delimiter
if self.column_names is not None:
_UpperCamelCase = self.column_names
@property
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = {
'''sep''': self.sep,
'''header''': self.header,
'''names''': self.names,
'''index_col''': self.index_col,
'''usecols''': self.usecols,
'''prefix''': self.prefix,
'''mangle_dupe_cols''': self.mangle_dupe_cols,
'''engine''': self.engine,
'''converters''': self.converters,
'''true_values''': self.true_values,
'''false_values''': self.false_values,
'''skipinitialspace''': self.skipinitialspace,
'''skiprows''': self.skiprows,
'''nrows''': self.nrows,
'''na_values''': self.na_values,
'''keep_default_na''': self.keep_default_na,
'''na_filter''': self.na_filter,
'''verbose''': self.verbose,
'''skip_blank_lines''': self.skip_blank_lines,
'''thousands''': self.thousands,
'''decimal''': self.decimal,
'''lineterminator''': self.lineterminator,
'''quotechar''': self.quotechar,
'''quoting''': self.quoting,
'''escapechar''': self.escapechar,
'''comment''': self.comment,
'''encoding''': self.encoding,
'''dialect''': self.dialect,
'''error_bad_lines''': self.error_bad_lines,
'''warn_bad_lines''': self.warn_bad_lines,
'''skipfooter''': self.skipfooter,
'''doublequote''': self.doublequote,
'''memory_map''': self.memory_map,
'''float_precision''': self.float_precision,
'''chunksize''': self.chunksize,
'''encoding_errors''': self.encoding_errors,
'''on_bad_lines''': self.on_bad_lines,
'''date_format''': self.date_format,
}
# some kwargs must not be passed if they don't have a default value
# some others are deprecated and we can also not pass them if they are the default value
for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS:
if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , __a):
del pd_read_csv_kwargs[pd_read_csv_parameter]
# Remove 2.0 new arguments
if not (datasets.config.PANDAS_VERSION.major >= 2):
for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS:
del pd_read_csv_kwargs[pd_read_csv_parameter]
# Remove 1.3 new arguments
if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3):
for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS:
del pd_read_csv_kwargs[pd_read_csv_parameter]
return pd_read_csv_kwargs
class _UpperCAmelCase( datasets.ArrowBasedBuilder ):
lowercase__ = CsvConfig
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
return datasets.DatasetInfo(features=self.config.features)
def UpperCAmelCase ( self , __a) -> List[str]:
'''simple docstring'''
if not self.config.data_files:
raise ValueError(F'''At least one data file must be specified, but got data_files={self.config.data_files}''')
_UpperCamelCase = dl_manager.download_and_extract(self.config.data_files)
if isinstance(__a , (str, list, tuple)):
_UpperCamelCase = data_files
if isinstance(__a , __a):
_UpperCamelCase = [files]
_UpperCamelCase = [dl_manager.iter_files(__a) for file in files]
return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files})]
_UpperCamelCase = []
for split_name, files in data_files.items():
if isinstance(__a , __a):
_UpperCamelCase = [files]
_UpperCamelCase = [dl_manager.iter_files(__a) for file in files]
splits.append(datasets.SplitGenerator(name=__a , gen_kwargs={'''files''': files}))
return splits
def UpperCAmelCase ( self , __a) -> pa.Table:
'''simple docstring'''
if self.config.features is not None:
_UpperCamelCase = self.config.features.arrow_schema
if all(not require_storage_cast(__a) for feature in self.config.features.values()):
# cheaper cast
_UpperCamelCase = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=__a)
else:
# more expensive cast; allows str <-> int/float or str to Audio for example
_UpperCamelCase = table_cast(__a , __a)
return pa_table
def UpperCAmelCase ( self , __a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.config.features.arrow_schema if self.config.features else None
# dtype allows reading an int column as str
_UpperCamelCase = (
{
name: dtype.to_pandas_dtype() if not require_storage_cast(__a) else object
for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values())
}
if schema is not None
else None
)
for file_idx, file in enumerate(itertools.chain.from_iterable(__a)):
_UpperCamelCase = pd.read_csv(__a , iterator=__a , dtype=__a , **self.config.pd_read_csv_kwargs)
try:
for batch_idx, df in enumerate(__a):
_UpperCamelCase = pa.Table.from_pandas(__a)
# Uncomment for debugging (will print the Arrow table size and elements)
# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
yield (file_idx, batch_idx), self._cast_table(__a)
except ValueError as e:
logger.error(F'''Failed to read file \'{file}\' with error {type(__a)}: {e}''')
raise
| 705 |
"""simple docstring"""
from __future__ import annotations
import unittest
from transformers import AutoTokenizer, MBartConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel
@require_tf
class _UpperCAmelCase:
lowercase__ = MBartConfig
lowercase__ = {}
lowercase__ = 'gelu'
def __init__( self , __a , __a=13 , __a=7 , __a=True , __a=False , __a=99 , __a=32 , __a=2 , __a=4 , __a=37 , __a=0.1 , __a=0.1 , __a=20 , __a=2 , __a=1 , __a=0 , ) -> Any:
'''simple docstring'''
_UpperCamelCase = parent
_UpperCamelCase = batch_size
_UpperCamelCase = seq_length
_UpperCamelCase = is_training
_UpperCamelCase = use_labels
_UpperCamelCase = vocab_size
_UpperCamelCase = hidden_size
_UpperCamelCase = num_hidden_layers
_UpperCamelCase = num_attention_heads
_UpperCamelCase = intermediate_size
_UpperCamelCase = hidden_dropout_prob
_UpperCamelCase = attention_probs_dropout_prob
_UpperCamelCase = max_position_embeddings
_UpperCamelCase = eos_token_id
_UpperCamelCase = pad_token_id
_UpperCamelCase = bos_token_id
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size)
_UpperCamelCase = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size) , 1)
_UpperCamelCase = tf.concat([input_ids, eos_tensor] , axis=1)
_UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size)
_UpperCamelCase = self.config_cls(
vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , )
_UpperCamelCase = prepare_mbart_inputs_dict(__a , __a , __a)
return config, inputs_dict
def UpperCAmelCase ( self , __a , __a) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = TFMBartModel(config=__a).get_decoder()
_UpperCamelCase = inputs_dict['''input_ids''']
_UpperCamelCase = input_ids[:1, :]
_UpperCamelCase = inputs_dict['''attention_mask'''][:1, :]
_UpperCamelCase = inputs_dict['''head_mask''']
_UpperCamelCase = 1
# first forward pass
_UpperCamelCase = model(__a , attention_mask=__a , head_mask=__a , use_cache=__a)
_UpperCamelCase , _UpperCamelCase = outputs.to_tuple()
_UpperCamelCase = past_key_values[1]
def lowerCamelCase__ ( __snake_case, __snake_case, __snake_case, __snake_case=None, __snake_case=None, __snake_case=None, __snake_case=None, __snake_case=None, ) -> Optional[int]:
"""simple docstring"""
if attention_mask is None:
_UpperCamelCase = tf.cast(tf.math.not_equal(__snake_case, config.pad_token_id ), tf.inta )
if decoder_attention_mask is None:
_UpperCamelCase = tf.concat(
[
tf.ones(decoder_input_ids[:, :1].shape, dtype=tf.inta ),
tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:], config.pad_token_id ), tf.inta ),
], axis=-1, )
if head_mask is None:
_UpperCamelCase = tf.ones((config.encoder_layers, config.encoder_attention_heads) )
if decoder_head_mask is None:
_UpperCamelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
if cross_attn_head_mask is None:
_UpperCamelCase = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
return {
"input_ids": input_ids,
"decoder_input_ids": decoder_input_ids,
"attention_mask": attention_mask,
"decoder_attention_mask": decoder_attention_mask,
"head_mask": head_mask,
"decoder_head_mask": decoder_head_mask,
"cross_attn_head_mask": cross_attn_head_mask,
}
@require_tf
class _UpperCAmelCase( lowerCamelCase , lowerCamelCase , unittest.TestCase ):
lowercase__ = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else ()
lowercase__ = (TFMBartForConditionalGeneration,) if is_tf_available() else ()
lowercase__ = (
{
'conversational': TFMBartForConditionalGeneration,
'feature-extraction': TFMBartModel,
'summarization': TFMBartForConditionalGeneration,
'text2text-generation': TFMBartForConditionalGeneration,
'translation': TFMBartForConditionalGeneration,
}
if is_tf_available()
else {}
)
lowercase__ = True
lowercase__ = False
lowercase__ = False
def UpperCAmelCase ( self , __a , __a , __a , __a , __a) -> Dict:
'''simple docstring'''
if pipeline_test_casse_name != "FeatureExtractionPipelineTests":
# Exception encountered when calling layer '...'
return True
return False
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
_UpperCamelCase = TFMBartModelTester(self)
_UpperCamelCase = ConfigTester(self , config_class=__a)
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
self.config_tester.run_common_tests()
def UpperCAmelCase ( self) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_decoder_model_past_large_inputs(*__a)
@require_sentencepiece
@require_tokenizers
@require_tf
class _UpperCAmelCase( unittest.TestCase ):
lowercase__ = [
' UN Chief Says There Is No Military Solution in Syria',
]
lowercase__ = [
'Şeful ONU declară că nu există o soluţie militară în Siria',
]
lowercase__ = 'facebook/mbart-large-en-ro'
@cached_property
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
return AutoTokenizer.from_pretrained(self.model_name)
@cached_property
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
_UpperCamelCase = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name)
return model
def UpperCAmelCase ( self , **__a) -> List[str]:
'''simple docstring'''
_UpperCamelCase = self.translate_src_text(**__a)
self.assertListEqual(self.expected_text , __a)
def UpperCAmelCase ( self , **__a) -> Dict:
'''simple docstring'''
_UpperCamelCase = self.tokenizer(self.src_text , **__a , return_tensors='''tf''')
_UpperCamelCase = self.model.generate(
model_inputs.input_ids , attention_mask=model_inputs.attention_mask , num_beams=2)
_UpperCamelCase = self.tokenizer.batch_decode(__a , skip_special_tokens=__a)
return generated_words
@slow
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
self._assert_generated_batch_equal_expected()
| 78 | 0 |
"""simple docstring"""
from pathlib import Path
from typing import List
from transformers import is_torch_available, is_vision_available
from transformers.testing_utils import get_tests_dir, is_tool_test
from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
_a = ["""text""", """image""", """audio"""]
def lowerCamelCase__ ( __snake_case ) -> Tuple:
"""simple docstring"""
_UpperCamelCase = []
for input_type in input_types:
if input_type == "text":
inputs.append('''Text input''' )
elif input_type == "image":
inputs.append(
Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO''' ) ) / '''000000039769.png''' ).resize((5_12, 5_12) ) )
elif input_type == "audio":
inputs.append(torch.ones(30_00 ) )
elif isinstance(__snake_case, __snake_case ):
inputs.append(create_inputs(__snake_case ) )
else:
raise ValueError(F'''Invalid type requested: {input_type}''' )
return inputs
def lowerCamelCase__ ( __snake_case ) -> List[str]:
"""simple docstring"""
_UpperCamelCase = []
for output in outputs:
if isinstance(__snake_case, (str, AgentText) ):
output_types.append('''text''' )
elif isinstance(__snake_case, (Image.Image, AgentImage) ):
output_types.append('''image''' )
elif isinstance(__snake_case, (torch.Tensor, AgentAudio) ):
output_types.append('''audio''' )
else:
raise ValueError(F'''Invalid output: {output}''' )
return output_types
@is_tool_test
class _UpperCAmelCase:
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
self.assertTrue(hasattr(self.tool , '''inputs'''))
self.assertTrue(hasattr(self.tool , '''outputs'''))
_UpperCamelCase = self.tool.inputs
for _input in inputs:
if isinstance(_input , __a):
for __input in _input:
self.assertTrue(__input in authorized_types)
else:
self.assertTrue(_input in authorized_types)
_UpperCamelCase = self.tool.outputs
for _output in outputs:
self.assertTrue(_output in authorized_types)
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
_UpperCamelCase = create_inputs(self.tool.inputs)
_UpperCamelCase = self.tool(*__a)
# There is a single output
if len(self.tool.outputs) == 1:
_UpperCamelCase = [outputs]
self.assertListEqual(output_types(__a) , self.tool.outputs)
def UpperCAmelCase ( self) -> int:
'''simple docstring'''
self.assertTrue(hasattr(self.tool , '''description'''))
self.assertTrue(hasattr(self.tool , '''default_checkpoint'''))
self.assertTrue(self.tool.description.startswith('''This is a tool that'''))
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
_UpperCamelCase = create_inputs(self.tool.inputs)
_UpperCamelCase = self.tool(*__a)
if not isinstance(__a , __a):
_UpperCamelCase = [outputs]
self.assertEqual(len(__a) , len(self.tool.outputs))
for output, output_type in zip(__a , self.tool.outputs):
_UpperCamelCase = AGENT_TYPE_MAPPING[output_type]
self.assertTrue(isinstance(__a , __a))
def UpperCAmelCase ( self) -> str:
'''simple docstring'''
_UpperCamelCase = create_inputs(self.tool.inputs)
_UpperCamelCase = []
for _input, input_type in zip(__a , self.tool.inputs):
if isinstance(__a , __a):
_inputs.append([AGENT_TYPE_MAPPING[_input_type](_input) for _input_type in input_type])
else:
_inputs.append(AGENT_TYPE_MAPPING[input_type](_input))
# Should not raise an error
_UpperCamelCase = self.tool(*__a)
if not isinstance(__a , __a):
_UpperCamelCase = [outputs]
self.assertEqual(len(__a) , len(self.tool.outputs))
| 706 |
"""simple docstring"""
from typing import Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format
from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images
from ...utils import TensorType, logging
_a = logging.get_logger(__name__)
class _UpperCAmelCase( lowerCamelCase ):
lowercase__ = ['pixel_values']
def __init__( self , __a = True , __a = 1 / 2_55 , __a = True , __a = 8 , **__a , ) -> None:
'''simple docstring'''
super().__init__(**__a)
_UpperCamelCase = do_rescale
_UpperCamelCase = rescale_factor
_UpperCamelCase = do_pad
_UpperCamelCase = pad_size
def UpperCAmelCase ( self , __a , __a , __a = None , **__a) -> np.ndarray:
'''simple docstring'''
return rescale(__a , scale=__a , data_format=__a , **__a)
def UpperCAmelCase ( self , __a , __a , __a = None) -> List[Any]:
'''simple docstring'''
_UpperCamelCase , _UpperCamelCase = get_image_size(__a)
_UpperCamelCase = (old_height // size + 1) * size - old_height
_UpperCamelCase = (old_width // size + 1) * size - old_width
return pad(__a , ((0, pad_height), (0, pad_width)) , mode='''symmetric''' , data_format=__a)
def UpperCAmelCase ( self , __a , __a = None , __a = None , __a = None , __a = None , __a = None , __a = ChannelDimension.FIRST , **__a , ) -> Tuple:
'''simple docstring'''
_UpperCamelCase = do_rescale if do_rescale is not None else self.do_rescale
_UpperCamelCase = rescale_factor if rescale_factor is not None else self.rescale_factor
_UpperCamelCase = do_pad if do_pad is not None else self.do_pad
_UpperCamelCase = pad_size if pad_size is not None else self.pad_size
_UpperCamelCase = make_list_of_images(__a)
if not valid_images(__a):
raise ValueError(
'''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '''
'''torch.Tensor, tf.Tensor or jax.ndarray.''')
if do_rescale and rescale_factor is None:
raise ValueError('''Rescale factor must be specified if do_rescale is True.''')
# All transformations expect numpy arrays.
_UpperCamelCase = [to_numpy_array(__a) for image in images]
if do_rescale:
_UpperCamelCase = [self.rescale(image=__a , scale=__a) for image in images]
if do_pad:
_UpperCamelCase = [self.pad(__a , size=__a) for image in images]
_UpperCamelCase = [to_channel_dimension_format(__a , __a) for image in images]
_UpperCamelCase = {'''pixel_values''': images}
return BatchFeature(data=__a , tensor_type=__a)
| 78 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.