code stringlengths 82 53.2k | code_codestyle int64 0 721 | style_context stringlengths 91 41.9k | style_context_codestyle int64 0 699 | label int64 0 1 |
|---|---|---|---|---|
"""simple docstring"""
import unittest
import numpy as np
import torch
from torch import nn
from transformers import (
CLIPImageProcessor,
CLIPTextConfig,
CLIPTextModelWithProjection,
CLIPTokenizer,
CLIPVisionConfig,
CLIPVisionModelWithProjection,
)
from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps
from ..test_pipelines_common import PipelineTesterMixin
enable_full_determinism()
class _a ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ):
a_ : List[Any] = KandinskyVaaPriorPipeline
a_ : Any = ['prompt']
a_ : int = ['prompt', 'negative_prompt']
a_ : Tuple = [
'num_images_per_prompt',
'generator',
'num_inference_steps',
'latents',
'negative_prompt',
'guidance_scale',
'output_type',
'return_dict',
]
a_ : Union[str, Any] = False
@property
def _UpperCamelCase ( self : Optional[Any] ):
return 32
@property
def _UpperCamelCase ( self : List[str] ):
return 32
@property
def _UpperCamelCase ( self : Optional[int] ):
return self.time_input_dim
@property
def _UpperCamelCase ( self : int ):
return self.time_input_dim * 4
@property
def _UpperCamelCase ( self : Optional[Any] ):
return 1_00
@property
def _UpperCamelCase ( self : List[str] ):
lowerCamelCase__ = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )
return tokenizer
@property
def _UpperCamelCase ( self : Dict ):
torch.manual_seed(0 )
lowerCamelCase__ = 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(SCREAMING_SNAKE_CASE__ )
@property
def _UpperCamelCase ( self : Optional[int] ):
torch.manual_seed(0 )
lowerCamelCase__ = {
'num_attention_heads': 2,
'attention_head_dim': 12,
'embedding_dim': self.text_embedder_hidden_size,
'num_layers': 1,
}
lowerCamelCase__ = PriorTransformer(**SCREAMING_SNAKE_CASE__ )
# clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
lowerCamelCase__ = nn.Parameter(torch.ones(model.clip_std.shape ) )
return model
@property
def _UpperCamelCase ( self : List[Any] ):
torch.manual_seed(0 )
lowerCamelCase__ = CLIPVisionConfig(
hidden_size=self.text_embedder_hidden_size , image_size=2_24 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , )
lowerCamelCase__ = CLIPVisionModelWithProjection(SCREAMING_SNAKE_CASE__ )
return model
@property
def _UpperCamelCase ( self : int ):
lowerCamelCase__ = CLIPImageProcessor(
crop_size=2_24 , do_center_crop=SCREAMING_SNAKE_CASE__ , do_normalize=SCREAMING_SNAKE_CASE__ , do_resize=SCREAMING_SNAKE_CASE__ , image_mean=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73] , image_std=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11] , resample=3 , size=2_24 , )
return image_processor
def _UpperCamelCase ( self : List[Any] ):
lowerCamelCase__ = self.dummy_prior
lowerCamelCase__ = self.dummy_image_encoder
lowerCamelCase__ = self.dummy_text_encoder
lowerCamelCase__ = self.dummy_tokenizer
lowerCamelCase__ = self.dummy_image_processor
lowerCamelCase__ = UnCLIPScheduler(
variance_type='fixed_small_log' , prediction_type='sample' , num_train_timesteps=10_00 , clip_sample=SCREAMING_SNAKE_CASE__ , clip_sample_range=10.0 , )
lowerCamelCase__ = {
'prior': prior,
'image_encoder': image_encoder,
'text_encoder': text_encoder,
'tokenizer': tokenizer,
'scheduler': scheduler,
'image_processor': image_processor,
}
return components
def _UpperCamelCase ( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int]=0 ):
if str(SCREAMING_SNAKE_CASE__ ).startswith('mps' ):
lowerCamelCase__ = torch.manual_seed(SCREAMING_SNAKE_CASE__ )
else:
lowerCamelCase__ = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ )
lowerCamelCase__ = {
'prompt': 'horse',
'generator': generator,
'guidance_scale': 4.0,
'num_inference_steps': 2,
'output_type': 'np',
}
return inputs
def _UpperCamelCase ( self : Tuple ):
lowerCamelCase__ = 'cpu'
lowerCamelCase__ = self.get_dummy_components()
lowerCamelCase__ = self.pipeline_class(**SCREAMING_SNAKE_CASE__ )
lowerCamelCase__ = pipe.to(SCREAMING_SNAKE_CASE__ )
pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ )
lowerCamelCase__ = pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) )
lowerCamelCase__ = output.image_embeds
lowerCamelCase__ = pipe(
**self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) , return_dict=SCREAMING_SNAKE_CASE__ , )[0]
lowerCamelCase__ = image[0, -10:]
lowerCamelCase__ = image_from_tuple[0, -10:]
assert image.shape == (1, 32)
lowerCamelCase__ = np.array(
[-0.05_32, 1.71_20, 0.36_56, -1.08_52, -0.89_46, -1.17_56, 0.43_48, 0.24_82, 0.51_46, -0.11_56] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2
@skip_mps
def _UpperCamelCase ( self : Optional[Any] ):
lowerCamelCase__ = torch_device == 'cpu'
lowerCamelCase__ = True
lowerCamelCase__ = False
self._test_inference_batch_single_identical(
test_max_difference=SCREAMING_SNAKE_CASE__ , relax_max_difference=SCREAMING_SNAKE_CASE__ , test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , )
@skip_mps
def _UpperCamelCase ( self : Tuple ):
lowerCamelCase__ = torch_device == 'cpu'
lowerCamelCase__ = False
self._test_attention_slicing_forward_pass(
test_max_difference=SCREAMING_SNAKE_CASE__ , test_mean_pixel_difference=SCREAMING_SNAKE_CASE__ , )
| 510 |
"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_snake_case = logging.get_logger(__name__)
_snake_case = {
# See all MEGATRON_BERT models at https://huggingface.co/models?filter=bert
}
class _a ( SCREAMING_SNAKE_CASE_ ):
a_ : List[str] = 'megatron-bert'
def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict=2_90_56 , SCREAMING_SNAKE_CASE__ : Optional[int]=10_24 , SCREAMING_SNAKE_CASE__ : int=24 , SCREAMING_SNAKE_CASE__ : Optional[Any]=16 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=40_96 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , SCREAMING_SNAKE_CASE__ : Tuple=0.1 , SCREAMING_SNAKE_CASE__ : str=0.1 , SCREAMING_SNAKE_CASE__ : Any=5_12 , SCREAMING_SNAKE_CASE__ : List[Any]=2 , SCREAMING_SNAKE_CASE__ : List[Any]=0.02 , SCREAMING_SNAKE_CASE__ : str=1e-12 , SCREAMING_SNAKE_CASE__ : str=0 , SCREAMING_SNAKE_CASE__ : Any="absolute" , SCREAMING_SNAKE_CASE__ : Tuple=True , **SCREAMING_SNAKE_CASE__ : Union[str, Any] , ):
super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
lowerCamelCase__ = vocab_size
lowerCamelCase__ = hidden_size
lowerCamelCase__ = num_hidden_layers
lowerCamelCase__ = num_attention_heads
lowerCamelCase__ = hidden_act
lowerCamelCase__ = intermediate_size
lowerCamelCase__ = hidden_dropout_prob
lowerCamelCase__ = attention_probs_dropout_prob
lowerCamelCase__ = max_position_embeddings
lowerCamelCase__ = type_vocab_size
lowerCamelCase__ = initializer_range
lowerCamelCase__ = layer_norm_eps
lowerCamelCase__ = position_embedding_type
lowerCamelCase__ = use_cache
| 510 | 1 |
'''simple docstring'''
from functools import lru_cache
def __UpperCAmelCase ( SCREAMING_SNAKE_CASE__: int ) -> set:
"""simple docstring"""
__a = 2
__a = set()
while i * i <= n:
if n % i:
i += 1
else:
n //= i
factors.add(SCREAMING_SNAKE_CASE__ )
if n > 1:
factors.add(SCREAMING_SNAKE_CASE__ )
return factors
@lru_cache
def __UpperCAmelCase ( SCREAMING_SNAKE_CASE__: int ) -> int:
"""simple docstring"""
return len(unique_prime_factors(SCREAMING_SNAKE_CASE__ ) )
def __UpperCAmelCase ( SCREAMING_SNAKE_CASE__: list ) -> bool:
"""simple docstring"""
return len(set(SCREAMING_SNAKE_CASE__ ) ) in (0, 1)
def __UpperCAmelCase ( SCREAMING_SNAKE_CASE__: int ) -> list:
"""simple docstring"""
__a = 2
while True:
# Increment each value of a generated range
__a = [base + i for i in range(SCREAMING_SNAKE_CASE__ )]
# Run elements through out unique_prime_factors function
# Append our target number to the end.
__a = [upf_len(SCREAMING_SNAKE_CASE__ ) for x in group]
checker.append(SCREAMING_SNAKE_CASE__ )
# If all numbers in the list are equal, return the group variable.
if equality(SCREAMING_SNAKE_CASE__ ):
return group
# Increment our base variable by 1
base += 1
def __UpperCAmelCase ( SCREAMING_SNAKE_CASE__: int = 4 ) -> int:
"""simple docstring"""
__a = run(SCREAMING_SNAKE_CASE__ )
return results[0] if len(SCREAMING_SNAKE_CASE__ ) else None
if __name__ == "__main__":
print(solution()) | 270 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_sentencepiece_available,
is_speech_available,
is_tf_available,
is_torch_available,
)
__UpperCamelCase : Optional[int] = {
"""configuration_speech_to_text""": ["""SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Speech2TextConfig"""],
"""processing_speech_to_text""": ["""Speech2TextProcessor"""],
}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCamelCase : Union[str, Any] = ["""Speech2TextTokenizer"""]
try:
if not is_speech_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCamelCase : Optional[Any] = ["""Speech2TextFeatureExtractor"""]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCamelCase : List[Any] = [
"""TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""TFSpeech2TextForConditionalGeneration""",
"""TFSpeech2TextModel""",
"""TFSpeech2TextPreTrainedModel""",
]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
__UpperCamelCase : Tuple = [
"""SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""Speech2TextForConditionalGeneration""",
"""Speech2TextModel""",
"""Speech2TextPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig
from .processing_speech_to_text import SpeechaTextProcessor
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_speech_to_text import SpeechaTextTokenizer
try:
if not is_speech_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_speech_to_text import (
TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFSpeechaTextForConditionalGeneration,
TFSpeechaTextModel,
TFSpeechaTextPreTrainedModel,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_speech_to_text import (
SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST,
SpeechaTextForConditionalGeneration,
SpeechaTextModel,
SpeechaTextPreTrainedModel,
)
else:
import sys
__UpperCamelCase : List[str] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__) | 270 | 1 |
a : Union[str, Any] = [
"Audio",
"Array2D",
"Array3D",
"Array4D",
"Array5D",
"ClassLabel",
"Features",
"Sequence",
"Value",
"Image",
"Translation",
"TranslationVariableLanguages",
]
from .audio import Audio
from .features import ArrayaD, ArrayaD, ArrayaD, ArrayaD, ClassLabel, Features, Sequence, Value
from .image import Image
from .translation import Translation, TranslationVariableLanguages
| 63 |
import gc
import random
import unittest
import numpy as np
import torch
from PIL import Image
from diffusers import (
DDIMScheduler,
KandinskyVaaInpaintPipeline,
KandinskyVaaPriorPipeline,
UNetaDConditionModel,
VQModel,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
enable_full_determinism()
class a ( lowercase__ , unittest.TestCase ):
"""simple docstring"""
a : int = KandinskyVaaInpaintPipeline
a : Any = ['image_embeds', 'negative_image_embeds', 'image', 'mask_image']
a : Any = [
'image_embeds',
'negative_image_embeds',
'image',
'mask_image',
]
a : Any = [
'generator',
'height',
'width',
'latents',
'guidance_scale',
'num_inference_steps',
'return_dict',
'guidance_scale',
'num_images_per_prompt',
'output_type',
'return_dict',
]
a : List[Any] = False
@property
def UpperCAmelCase ( self : int ) -> Dict:
return 32
@property
def UpperCAmelCase ( self : Optional[int] ) -> Optional[Any]:
return 32
@property
def UpperCAmelCase ( self : Optional[Any] ) -> Optional[int]:
return self.time_input_dim
@property
def UpperCAmelCase ( self : str ) -> List[str]:
return self.time_input_dim * 4
@property
def UpperCAmelCase ( self : Tuple ) -> List[str]:
return 100
@property
def UpperCAmelCase ( self : Dict ) -> Any:
torch.manual_seed(0 )
__UpperCAmelCase : Optional[Any] = {
"""in_channels""": 9,
# Out channels is double in channels because predicts mean and variance
"""out_channels""": 8,
"""addition_embed_type""": """image""",
"""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,
"""encoder_hid_dim""": self.text_embedder_hidden_size,
"""encoder_hid_dim_type""": """image_proj""",
"""cross_attention_dim""": self.cross_attention_dim,
"""attention_head_dim""": 4,
"""resnet_time_scale_shift""": """scale_shift""",
"""class_embed_type""": None,
}
__UpperCAmelCase : int = UNetaDConditionModel(**__lowercase )
return model
@property
def UpperCAmelCase ( self : int ) -> int:
return {
"block_out_channels": [32, 64],
"down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
"in_channels": 3,
"latent_channels": 4,
"layers_per_block": 1,
"norm_num_groups": 8,
"norm_type": "spatial",
"num_vq_embeddings": 12,
"out_channels": 3,
"up_block_types": [
"AttnUpDecoderBlock2D",
"UpDecoderBlock2D",
],
"vq_embed_dim": 4,
}
@property
def UpperCAmelCase ( self : Dict ) -> List[str]:
torch.manual_seed(0 )
__UpperCAmelCase : List[Any] = VQModel(**self.dummy_movq_kwargs )
return model
def UpperCAmelCase ( self : Any ) -> List[Any]:
__UpperCAmelCase : List[str] = self.dummy_unet
__UpperCAmelCase : List[str] = self.dummy_movq
__UpperCAmelCase : Optional[Any] = DDIMScheduler(
num_train_timesteps=1000 , beta_schedule="""linear""" , beta_start=0.00_085 , beta_end=0.012 , clip_sample=__lowercase , set_alpha_to_one=__lowercase , steps_offset=1 , prediction_type="""epsilon""" , thresholding=__lowercase , )
__UpperCAmelCase : str = {
"""unet""": unet,
"""scheduler""": scheduler,
"""movq""": movq,
}
return components
def UpperCAmelCase ( self : str , __lowercase : Tuple , __lowercase : List[str]=0 ) -> Optional[Any]:
__UpperCAmelCase : str = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(__lowercase ) ).to(__lowercase )
__UpperCAmelCase : Optional[int] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to(
__lowercase )
# create init_image
__UpperCAmelCase : Tuple = floats_tensor((1, 3, 64, 64) , rng=random.Random(__lowercase ) ).to(__lowercase )
__UpperCAmelCase : Union[str, Any] = image.cpu().permute(0 , 2 , 3 , 1 )[0]
__UpperCAmelCase : Union[str, Any] = Image.fromarray(np.uinta(__lowercase ) ).convert("""RGB""" ).resize((256, 256) )
# create mask
__UpperCAmelCase : Union[str, Any] = np.ones((64, 64) , dtype=np.floataa )
__UpperCAmelCase : List[str] = 0
if str(__lowercase ).startswith("""mps""" ):
__UpperCAmelCase : List[str] = torch.manual_seed(__lowercase )
else:
__UpperCAmelCase : Optional[int] = torch.Generator(device=__lowercase ).manual_seed(__lowercase )
__UpperCAmelCase : Optional[Any] = {
"""image""": init_image,
"""mask_image""": mask,
"""image_embeds""": image_embeds,
"""negative_image_embeds""": negative_image_embeds,
"""generator""": generator,
"""height""": 64,
"""width""": 64,
"""num_inference_steps""": 2,
"""guidance_scale""": 4.0,
"""output_type""": """np""",
}
return inputs
def UpperCAmelCase ( self : List[str] ) -> Union[str, Any]:
__UpperCAmelCase : Optional[Any] = """cpu"""
__UpperCAmelCase : Dict = self.get_dummy_components()
__UpperCAmelCase : str = self.pipeline_class(**__lowercase )
__UpperCAmelCase : Tuple = pipe.to(__lowercase )
pipe.set_progress_bar_config(disable=__lowercase )
__UpperCAmelCase : List[Any] = pipe(**self.get_dummy_inputs(__lowercase ) )
__UpperCAmelCase : Tuple = output.images
__UpperCAmelCase : Optional[int] = pipe(
**self.get_dummy_inputs(__lowercase ) , return_dict=__lowercase , )[0]
__UpperCAmelCase : Union[str, Any] = image[0, -3:, -3:, -1]
__UpperCAmelCase : str = image_from_tuple[0, -3:, -3:, -1]
print(f"""image.shape {image.shape}""" )
assert image.shape == (1, 64, 64, 3)
__UpperCAmelCase : Optional[Any] = np.array(
[0.50_775_903, 0.49_527_195, 0.48_824_543, 0.50_192_237, 0.48_644_906, 0.49_373_814, 0.4_780_598, 0.47_234_827, 0.48_327_848] )
assert (
np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
), f""" expected_slice {expected_slice}, but got {image_slice.flatten()}"""
assert (
np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2
), f""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}"""
def UpperCAmelCase ( self : str ) -> Union[str, Any]:
super().test_inference_batch_single_identical(expected_max_diff=3e-3 )
@slow
@require_torch_gpu
class a ( unittest.TestCase ):
"""simple docstring"""
def UpperCAmelCase ( self : Union[str, Any] ) -> Any:
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def UpperCAmelCase ( self : Tuple ) -> Union[str, Any]:
__UpperCAmelCase : Any = load_numpy(
"""https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
"""/kandinskyv22/kandinskyv22_inpaint_cat_with_hat_fp16.npy""" )
__UpperCAmelCase : List[str] = load_image(
"""https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" )
__UpperCAmelCase : List[Any] = np.ones((768, 768) , dtype=np.floataa )
__UpperCAmelCase : Optional[Any] = 0
__UpperCAmelCase : Tuple = """a hat"""
__UpperCAmelCase : str = KandinskyVaaPriorPipeline.from_pretrained(
"""kandinsky-community/kandinsky-2-2-prior""" , torch_dtype=torch.floataa )
pipe_prior.to(__lowercase )
__UpperCAmelCase : Any = KandinskyVaaInpaintPipeline.from_pretrained(
"""kandinsky-community/kandinsky-2-2-decoder-inpaint""" , torch_dtype=torch.floataa )
__UpperCAmelCase : int = pipeline.to(__lowercase )
pipeline.set_progress_bar_config(disable=__lowercase )
__UpperCAmelCase : int = torch.Generator(device="""cpu""" ).manual_seed(0 )
__UpperCAmelCase , __UpperCAmelCase : Optional[int] = pipe_prior(
__lowercase , generator=__lowercase , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple()
__UpperCAmelCase : Optional[int] = pipeline(
image=__lowercase , mask_image=__lowercase , image_embeds=__lowercase , negative_image_embeds=__lowercase , generator=__lowercase , num_inference_steps=100 , height=768 , width=768 , output_type="""np""" , )
__UpperCAmelCase : List[Any] = output.images[0]
assert image.shape == (768, 768, 3)
assert_mean_pixel_difference(__lowercase , __lowercase )
| 63 | 1 |
import json
from typing import List, Optional, Tuple
from tokenizers import pre_tokenizers, processors
from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_mvp import MvpTokenizer
SCREAMING_SNAKE_CASE : List[str] = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE : str = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
# See all MVP models at https://huggingface.co/models?filter=mvp
SCREAMING_SNAKE_CASE : Optional[Any] = {
"vocab_file": {
"RUCAIBox/mvp": "https://huggingface.co/RUCAIBox/mvp/resolve/main/vocab.json",
},
"added_tokens.json": {
"RUCAIBox/mvp": "https://huggingface.co/RUCAIBox/mvp/resolve/main/added_tokens.json",
},
"merges_file": {
"RUCAIBox/mvp": "https://huggingface.co/RUCAIBox/mvp/resolve/main/merges.txt",
},
"tokenizer_file": {
"RUCAIBox/mvp": "https://huggingface.co/RUCAIBox/mvp/resolve/main/tokenizer.json",
},
}
SCREAMING_SNAKE_CASE : Optional[Any] = {
"RUCAIBox/mvp": 1024,
}
class _lowerCamelCase( _a ):
lowercase_ : Union[str, Any] = VOCAB_FILES_NAMES
lowercase_ : List[Any] = PRETRAINED_VOCAB_FILES_MAP
lowercase_ : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
lowercase_ : Optional[Any] = ["""input_ids""", """attention_mask"""]
lowercase_ : Optional[Any] = MvpTokenizer
def __init__( self, lowerCamelCase=None, lowerCamelCase=None, lowerCamelCase=None, lowerCamelCase="replace", lowerCamelCase="<s>", lowerCamelCase="</s>", lowerCamelCase="</s>", lowerCamelCase="<s>", lowerCamelCase="<unk>", lowerCamelCase="<pad>", lowerCamelCase="<mask>", lowerCamelCase=False, lowerCamelCase=True, **lowerCamelCase, ) -> List[Any]:
"""simple docstring"""
super().__init__(
lowerCamelCase, lowerCamelCase, tokenizer_file=lowerCamelCase, errors=lowerCamelCase, bos_token=lowerCamelCase, eos_token=lowerCamelCase, sep_token=lowerCamelCase, cls_token=lowerCamelCase, unk_token=lowerCamelCase, pad_token=lowerCamelCase, mask_token=lowerCamelCase, add_prefix_space=lowerCamelCase, trim_offsets=lowerCamelCase, **lowerCamelCase, )
_lowercase : List[Any] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())
if pre_tok_state.get('add_prefix_space', lowerCamelCase) != add_prefix_space:
_lowercase : Union[str, Any] = getattr(lowerCamelCase, pre_tok_state.pop('type'))
_lowercase : int = add_prefix_space
_lowercase : List[Any] = pre_tok_class(**lowerCamelCase)
_lowercase : List[Any] = add_prefix_space
# the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
_lowercase : List[str] = 'post_processor'
_lowercase : Union[str, Any] = getattr(self.backend_tokenizer, lowerCamelCase, lowerCamelCase)
if tokenizer_component_instance:
_lowercase : Any = json.loads(tokenizer_component_instance.__getstate__())
# The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
if "sep" in state:
_lowercase : Union[str, Any] = tuple(state['sep'])
if "cls" in state:
_lowercase : Tuple = tuple(state['cls'])
_lowercase : Tuple = False
if state.get('add_prefix_space', lowerCamelCase) != add_prefix_space:
_lowercase : Optional[Any] = add_prefix_space
_lowercase : int = True
if state.get('trim_offsets', lowerCamelCase) != trim_offsets:
_lowercase : List[str] = trim_offsets
_lowercase : List[str] = True
if changes_to_apply:
_lowercase : Optional[int] = getattr(lowerCamelCase, state.pop('type'))
_lowercase : Optional[Any] = component_class(**lowerCamelCase)
setattr(self.backend_tokenizer, lowerCamelCase, lowerCamelCase)
@property
def UpperCamelCase ( self) -> List[Any]:
"""simple docstring"""
if self._mask_token is None:
if self.verbose:
logger.error('Using mask_token, but it is not set yet.')
return None
return str(self._mask_token)
@mask_token.setter
def UpperCamelCase ( self, lowerCamelCase) -> Union[str, Any]:
"""simple docstring"""
_lowercase : List[Any] = AddedToken(lowerCamelCase, lstrip=lowerCamelCase, rstrip=lowerCamelCase) if isinstance(lowerCamelCase, lowerCamelCase) else value
_lowercase : List[str] = value
def UpperCamelCase ( self, *lowerCamelCase, **lowerCamelCase) -> Any:
"""simple docstring"""
_lowercase : Optional[int] = kwargs.get('is_split_into_words', lowerCamelCase)
if is_split_into_words and not self.add_prefix_space:
raise ValueError(
F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True '''
'to use it with pretokenized inputs.')
return super()._batch_encode_plus(*lowerCamelCase, **lowerCamelCase)
def UpperCamelCase ( self, *lowerCamelCase, **lowerCamelCase) -> List[Any]:
"""simple docstring"""
_lowercase : Tuple = kwargs.get('is_split_into_words', lowerCamelCase)
if is_split_into_words and not self.add_prefix_space:
raise ValueError(
F'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True '''
'to use it with pretokenized inputs.')
return super()._encode_plus(*lowerCamelCase, **lowerCamelCase)
def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase = None) -> Union[str, Any]:
"""simple docstring"""
_lowercase : Union[str, Any] = self._tokenizer.model.save(lowerCamelCase, name=lowerCamelCase)
return tuple(lowerCamelCase)
def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase=None) -> str:
"""simple docstring"""
_lowercase : str = [self.bos_token_id] + token_ids_a + [self.eos_token_id]
if token_ids_a is None:
return output
return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]
def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase = None) -> Union[str, Any]:
"""simple docstring"""
_lowercase : Dict = [self.sep_token_id]
_lowercase : str = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep) * [0]
| 703 |
def UpperCamelCase_( lowerCamelCase_ ) -> int:
assert (
isinstance(lowerCamelCase_ , lowerCamelCase_ ) and number_of_steps > 0
), F'''number_of_steps needs to be positive integer, your input {number_of_steps}'''
if number_of_steps == 1:
return 1
_lowercase , _lowercase : Dict = 1, 1
for _ in range(number_of_steps - 1 ):
_lowercase , _lowercase : Tuple = current + previous, current
return current
if __name__ == "__main__":
import doctest
doctest.testmod()
| 354 | 0 |
# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import os
from accelerate.utils import ComputeEnvironment
from .cluster import get_cluster_input
from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401
from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401
from .sagemaker import get_sagemaker_input
a ="""Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine"""
def SCREAMING_SNAKE_CASE__ ( ) -> int:
__lowerCamelCase : Optional[int] = _ask_options(
'In which compute environment are you running?' , ['This machine', 'AWS (Amazon SageMaker)'] , _convert_compute_environment , )
if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
__lowerCamelCase : List[str] = get_sagemaker_input()
else:
__lowerCamelCase : Any = get_cluster_input()
return config
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__=None ) -> Union[str, Any]:
if subparsers is not None:
__lowerCamelCase : Dict = subparsers.add_parser('config' , description=lowerCamelCase__ )
else:
__lowerCamelCase : Optional[Any] = argparse.ArgumentParser('Accelerate config command' , description=lowerCamelCase__ )
parser.add_argument(
'--config_file' , default=lowerCamelCase__ , help=(
'The path to use to store the config file. Will default to a file named default_config.yaml in the cache '
'location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have '
'such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed '
'with \'huggingface\'.'
) , )
if subparsers is not None:
parser.set_defaults(func=lowerCamelCase__ )
return parser
def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Optional[Any]:
__lowerCamelCase : str = get_user_input()
if args.config_file is not None:
__lowerCamelCase : str = args.config_file
else:
if not os.path.isdir(lowerCamelCase__ ):
os.makedirs(lowerCamelCase__ )
__lowerCamelCase : Any = default_yaml_config_file
if config_file.endswith('.json' ):
config.to_json_file(lowerCamelCase__ )
else:
config.to_yaml_file(lowerCamelCase__ )
print(F"accelerate configuration saved at {config_file}" )
def SCREAMING_SNAKE_CASE__ ( ) -> int:
__lowerCamelCase : Optional[int] = config_command_parser()
__lowerCamelCase : Optional[int] = parser.parse_args()
config_command(lowerCamelCase__ )
if __name__ == "__main__":
main()
| 652 |
from datetime import datetime
import requests
def snake_case( __magic_name__ ) -> bytes:
'''simple docstring'''
lowercase : Optional[int] = '''https://downloadgram.net/wp-json/wppress/video-downloader/video?url='''
lowercase : Tuple = requests.get(base_url + url ).json()[0]['''urls'''][0]['''src''']
return requests.get(__magic_name__ ).content
if __name__ == "__main__":
lowerCAmelCase_ = input('Enter Video/IGTV url: ').strip()
lowerCAmelCase_ = f'''{datetime.now():%Y-%m-%d_%H:%M:%S}.mp4'''
with open(file_name, 'wb') as fp:
fp.write(download_video(url))
print(f'''Done. Video saved to disk as {file_name}.''') | 217 | 0 |
"""simple docstring"""
import os
from glob import glob
import imageio
import torch
import torchvision
import wandb
from img_processing import custom_to_pil, loop_post_process, preprocess, preprocess_vqgan
from loaders import load_vqgan
from PIL import Image
from torch import nn
from transformers import CLIPModel, CLIPTokenizerFast
from utils import get_device, get_timestamp, show_pil
class __snake_case :
def __init__( self : Dict , __lowerCAmelCase : str = "cpu" , __lowerCAmelCase : str = "openai/clip-vit-large-patch14" ):
"""simple docstring"""
_lowerCamelCase : Optional[int] = device
_lowerCamelCase : Union[str, Any] = CLIPTokenizerFast.from_pretrained(__lowerCAmelCase )
_lowerCamelCase : Optional[int] = [0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]
_lowerCamelCase : Any = [0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]
_lowerCamelCase : List[str] = torchvision.transforms.Normalize(self.image_mean , self.image_std )
_lowerCamelCase : List[Any] = torchvision.transforms.Resize(2_2_4 )
_lowerCamelCase : Optional[int] = torchvision.transforms.CenterCrop(2_2_4 )
def SCREAMING_SNAKE_CASE ( self : str , __lowerCAmelCase : Optional[int] ):
"""simple docstring"""
_lowerCamelCase : Any = self.resize(__lowerCAmelCase )
_lowerCamelCase : Union[str, Any] = self.center_crop(__lowerCAmelCase )
_lowerCamelCase : Union[str, Any] = self.normalize(__lowerCAmelCase )
return images
def __call__( self : int , __lowerCAmelCase : Any=None , __lowerCAmelCase : Dict=None , **__lowerCAmelCase : Optional[int] ):
"""simple docstring"""
_lowerCamelCase : List[Any] = self.tokenizer(text=__lowerCAmelCase , **__lowerCAmelCase )
_lowerCamelCase : Dict = self.preprocess_img(__lowerCAmelCase )
_lowerCamelCase : Union[str, Any] = {key: value.to(self.device ) for (key, value) in encoding.items()}
return encoding
class __snake_case ( nn.Module):
def __init__( self : str , __lowerCAmelCase : Tuple=1_0 , __lowerCAmelCase : Dict=0.01 , __lowerCAmelCase : Optional[Any]=None , __lowerCAmelCase : Union[str, Any]=None , __lowerCAmelCase : int=None , __lowerCAmelCase : Optional[Any]=None , __lowerCAmelCase : List[Any]=None , __lowerCAmelCase : int=None , __lowerCAmelCase : Optional[Any]=False , __lowerCAmelCase : Union[str, Any]=True , __lowerCAmelCase : Optional[int]="image" , __lowerCAmelCase : Optional[Any]=True , __lowerCAmelCase : Optional[Any]=False , __lowerCAmelCase : Dict=False , __lowerCAmelCase : Any=False , ):
"""simple docstring"""
super().__init__()
_lowerCamelCase : List[Any] = None
_lowerCamelCase : Union[str, Any] = device if device else get_device()
if vqgan:
_lowerCamelCase : Union[str, Any] = vqgan
else:
_lowerCamelCase : Union[str, Any] = load_vqgan(self.device , conf_path=__lowerCAmelCase , ckpt_path=__lowerCAmelCase )
self.vqgan.eval()
if clip:
_lowerCamelCase : List[str] = clip
else:
_lowerCamelCase : int = CLIPModel.from_pretrained('''openai/clip-vit-base-patch32''' )
self.clip.to(self.device )
_lowerCamelCase : List[str] = ProcessorGradientFlow(device=self.device )
_lowerCamelCase : Tuple = iterations
_lowerCamelCase : str = lr
_lowerCamelCase : Tuple = log
_lowerCamelCase : List[str] = make_grid
_lowerCamelCase : List[Any] = return_val
_lowerCamelCase : List[str] = quantize
_lowerCamelCase : Union[str, Any] = self.vqgan.decoder.z_shape
def SCREAMING_SNAKE_CASE ( self : Any , __lowerCAmelCase : Optional[int]=None , __lowerCAmelCase : Optional[int]=None , __lowerCAmelCase : Optional[int]=5 , __lowerCAmelCase : Union[str, Any]=True ):
"""simple docstring"""
_lowerCamelCase : Dict = []
if output_path is None:
_lowerCamelCase : Dict = '''./animation.gif'''
if input_path is None:
_lowerCamelCase : Any = self.save_path
_lowerCamelCase : Union[str, Any] = sorted(glob(input_path + '''/*''' ) )
if not len(__lowerCAmelCase ):
raise ValueError(
'''No images found in save path, aborting (did you pass save_intermediate=True to the generate'''
''' function?)''' )
if len(__lowerCAmelCase ) == 1:
print('''Only one image found in save path, (did you pass save_intermediate=True to the generate function?)''' )
_lowerCamelCase : Optional[int] = total_duration / len(__lowerCAmelCase )
_lowerCamelCase : str = [frame_duration] * len(__lowerCAmelCase )
if extend_frames:
_lowerCamelCase : Tuple = 1.5
_lowerCamelCase : Any = 3
for file_name in paths:
if file_name.endswith('''.png''' ):
images.append(imageio.imread(__lowerCAmelCase ) )
imageio.mimsave(__lowerCAmelCase , __lowerCAmelCase , duration=__lowerCAmelCase )
print(f'''gif saved to {output_path}''' )
def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : List[Any]=None , __lowerCAmelCase : Dict=None ):
"""simple docstring"""
if not (path or img):
raise ValueError('''Input either path or tensor''' )
if img is not None:
raise NotImplementedError
_lowerCamelCase : Dict = preprocess(Image.open(__lowerCAmelCase ) , target_image_size=2_5_6 ).to(self.device )
_lowerCamelCase : Union[str, Any] = preprocess_vqgan(__lowerCAmelCase )
_lowerCamelCase , *_lowerCamelCase : int = self.vqgan.encode(__lowerCAmelCase )
return z
def SCREAMING_SNAKE_CASE ( self : List[str] , __lowerCAmelCase : Tuple ):
"""simple docstring"""
_lowerCamelCase : Dict = self.latent.detach().requires_grad_()
_lowerCamelCase : Optional[int] = base_latent + transform_vector
if self.quantize:
_lowerCamelCase , *_lowerCamelCase : int = self.vqgan.quantize(__lowerCAmelCase )
else:
_lowerCamelCase : Dict = trans_latent
return self.vqgan.decode(__lowerCAmelCase )
def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : str , __lowerCAmelCase : Dict , __lowerCAmelCase : Tuple=None ):
"""simple docstring"""
_lowerCamelCase : Dict = self.clip_preprocessor(text=__lowerCAmelCase , images=__lowerCAmelCase , return_tensors='''pt''' , padding=__lowerCAmelCase )
_lowerCamelCase : List[str] = self.clip(**__lowerCAmelCase )
_lowerCamelCase : Any = clip_outputs.logits_per_image
if weights is not None:
_lowerCamelCase : List[str] = similarity_logits * weights
return similarity_logits.sum()
def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : List[str] ):
"""simple docstring"""
_lowerCamelCase : str = self._get_clip_similarity(pos_prompts['''prompts'''] , __lowerCAmelCase , weights=(1 / pos_prompts['''weights''']) )
if neg_prompts:
_lowerCamelCase : Dict = self._get_clip_similarity(neg_prompts['''prompts'''] , __lowerCAmelCase , weights=neg_prompts['''weights'''] )
else:
_lowerCamelCase : Optional[int] = torch.tensor([1] , device=self.device )
_lowerCamelCase : str = -torch.log(__lowerCAmelCase ) + torch.log(__lowerCAmelCase )
return loss
def SCREAMING_SNAKE_CASE ( self : Dict , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : List[str] ):
"""simple docstring"""
_lowerCamelCase : List[Any] = torch.randn_like(self.latent , requires_grad=__lowerCAmelCase , device=self.device )
_lowerCamelCase : Dict = torch.optim.Adam([vector] , lr=self.lr )
for i in range(self.iterations ):
optim.zero_grad()
_lowerCamelCase : str = self._add_vector(__lowerCAmelCase )
_lowerCamelCase : int = loop_post_process(__lowerCAmelCase )
_lowerCamelCase : Optional[Any] = self._get_CLIP_loss(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )
print('''CLIP loss''' , __lowerCAmelCase )
if self.log:
wandb.log({'''CLIP Loss''': clip_loss} )
clip_loss.backward(retain_graph=__lowerCAmelCase )
optim.step()
if self.return_val == "image":
yield custom_to_pil(transformed_img[0] )
else:
yield vector
def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Optional[Any] ):
"""simple docstring"""
wandb.init(reinit=__lowerCAmelCase , project='''face-editor''' )
wandb.config.update({'''Positive Prompts''': positive_prompts} )
wandb.config.update({'''Negative Prompts''': negative_prompts} )
wandb.config.update({'''lr''': self.lr, '''iterations''': self.iterations} )
if image_path:
_lowerCamelCase : str = Image.open(__lowerCAmelCase )
_lowerCamelCase : Union[str, Any] = image.resize((2_5_6, 2_5_6) )
wandb.log('''Original Image''' , wandb.Image(__lowerCAmelCase ) )
def SCREAMING_SNAKE_CASE ( self : Optional[int] , __lowerCAmelCase : Tuple ):
"""simple docstring"""
if not prompts:
return []
_lowerCamelCase : List[Any] = []
_lowerCamelCase : Dict = []
if isinstance(__lowerCAmelCase , __lowerCAmelCase ):
_lowerCamelCase : List[Any] = [prompt.strip() for prompt in prompts.split('''|''' )]
for prompt in prompts:
if isinstance(__lowerCAmelCase , (tuple, list) ):
_lowerCamelCase : Optional[Any] = prompt[0]
_lowerCamelCase : Optional[Any] = float(prompt[1] )
elif ":" in prompt:
_lowerCamelCase , _lowerCamelCase : int = prompt.split(''':''' )
_lowerCamelCase : Tuple = float(__lowerCAmelCase )
else:
_lowerCamelCase : Dict = prompt
_lowerCamelCase : List[str] = 1.0
processed_prompts.append(__lowerCAmelCase )
weights.append(__lowerCAmelCase )
return {
"prompts": processed_prompts,
"weights": torch.tensor(__lowerCAmelCase , device=self.device ),
}
def SCREAMING_SNAKE_CASE ( self : Tuple , __lowerCAmelCase : List[str] , __lowerCAmelCase : Tuple=None , __lowerCAmelCase : Dict=None , __lowerCAmelCase : List[Any]=True , __lowerCAmelCase : int=False , __lowerCAmelCase : List[str]=True , __lowerCAmelCase : List[Any]=True , __lowerCAmelCase : Tuple=None , ):
"""simple docstring"""
if image_path:
_lowerCamelCase : Any = self._get_latent(__lowerCAmelCase )
else:
_lowerCamelCase : Dict = torch.randn(self.latent_dim , device=self.device )
if self.log:
self._init_logging(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )
assert pos_prompts, "You must provide at least one positive prompt."
_lowerCamelCase : Dict = self.process_prompts(__lowerCAmelCase )
_lowerCamelCase : List[Any] = self.process_prompts(__lowerCAmelCase )
if save_final and save_path is None:
_lowerCamelCase : List[str] = os.path.join('''./outputs/''' , '''_'''.join(pos_prompts['''prompts'''] ) )
if not os.path.exists(__lowerCAmelCase ):
os.makedirs(__lowerCAmelCase )
else:
_lowerCamelCase : Dict = save_path + '''_''' + get_timestamp()
os.makedirs(__lowerCAmelCase )
_lowerCamelCase : Tuple = save_path
_lowerCamelCase : Optional[int] = self.vqgan.decode(self.latent )[0]
if show_intermediate:
print('''Original Image''' )
show_pil(custom_to_pil(__lowerCAmelCase ) )
_lowerCamelCase : List[Any] = loop_post_process(__lowerCAmelCase )
for iter, transformed_img in enumerate(self._optimize_CLIP(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) ):
if show_intermediate:
show_pil(__lowerCAmelCase )
if save_intermediate:
transformed_img.save(os.path.join(self.save_path , f'''iter_{iter:03d}.png''' ) )
if self.log:
wandb.log({'''Image''': wandb.Image(__lowerCAmelCase )} )
if show_final:
show_pil(__lowerCAmelCase )
if save_final:
transformed_img.save(os.path.join(self.save_path , f'''iter_{iter:03d}_final.png''' ) )
| 598 |
"""simple docstring"""
import logging
import os
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import List, Optional
import faiss
import torch
from datasets import Features, Sequence, Value, load_dataset
from transformers import DPRContextEncoder, DPRContextEncoderTokenizerFast, HfArgumentParser
lowerCAmelCase__ = logging.getLogger(__name__)
torch.set_grad_enabled(False)
lowerCAmelCase__ = '''cuda''' if torch.cuda.is_available() else '''cpu'''
def snake_case_ ( A_ : str, A_ : Optional[int]=1_00, A_ : Optional[int]=" " ):
'''simple docstring'''
_lowerCamelCase : Dict = text.split(A_ )
return [character.join(text[i : i + n] ).strip() for i in range(0, len(A_ ), A_ )]
def snake_case_ ( A_ : dict ):
'''simple docstring'''
_lowerCamelCase , _lowerCamelCase : int = [], []
for title, text in zip(documents['''title'''], documents['''text'''] ):
if text is not None:
for passage in split_text(A_ ):
titles.append(title if title is not None else '''''' )
texts.append(A_ )
return {"title": titles, "text": texts}
def snake_case_ ( A_ : dict, A_ : DPRContextEncoder, A_ : DPRContextEncoderTokenizerFast ):
'''simple docstring'''
_lowerCamelCase : int = ctx_tokenizer(
documents['''title'''], documents['''text'''], truncation=A_, padding='''longest''', return_tensors='''pt''' )['''input_ids''']
_lowerCamelCase : Union[str, Any] = ctx_encoder(input_ids.to(device=A_ ), return_dict=A_ ).pooler_output
return {"embeddings": embeddings.detach().cpu().numpy()}
def snake_case_ ( A_ : "RagExampleArguments", A_ : "ProcessingArguments", A_ : "IndexHnswArguments", ):
'''simple docstring'''
logger.info('''Step 1 - Create the dataset''' )
######################################
# The dataset needed for RAG must have three columns:
# - title (string): title of the document
# - text (string): text of a passage of the document
# - embeddings (array of dimension d): DPR representation of the passage
# Let's say you have documents in tab-separated csv files with columns "title" and "text"
assert os.path.isfile(rag_example_args.csv_path ), "Please provide a valid path to a csv file"
# You can load a Dataset object this way
_lowerCamelCase : int = load_dataset(
'''csv''', data_files=[rag_example_args.csv_path], split='''train''', delimiter='''\t''', column_names=['''title''', '''text'''] )
# More info about loading csv files in the documentation: https://huggingface.co/docs/datasets/loading_datasets.html?highlight=csv#csv-files
# Then split the documents into passages of 100 words
_lowerCamelCase : Union[str, Any] = dataset.map(A_, batched=A_, num_proc=processing_args.num_proc )
# And compute the embeddings
_lowerCamelCase : int = DPRContextEncoder.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name ).to(device=A_ )
_lowerCamelCase : Union[str, Any] = DPRContextEncoderTokenizerFast.from_pretrained(rag_example_args.dpr_ctx_encoder_model_name )
_lowerCamelCase : Any = Features(
{'''text''': Value('''string''' ), '''title''': Value('''string''' ), '''embeddings''': Sequence(Value('''float32''' ) )} ) # optional, save as float32 instead of float64 to save space
_lowerCamelCase : str = dataset.map(
partial(A_, ctx_encoder=A_, ctx_tokenizer=A_ ), batched=A_, batch_size=processing_args.batch_size, features=A_, )
# And finally save your dataset
_lowerCamelCase : List[Any] = os.path.join(rag_example_args.output_dir, '''my_knowledge_dataset''' )
dataset.save_to_disk(A_ )
# from datasets import load_from_disk
# dataset = load_from_disk(passages_path) # to reload the dataset
######################################
logger.info('''Step 2 - Index the dataset''' )
######################################
# Let's use the Faiss implementation of HNSW for fast approximate nearest neighbor search
_lowerCamelCase : Tuple = faiss.IndexHNSWFlat(index_hnsw_args.d, index_hnsw_args.m, faiss.METRIC_INNER_PRODUCT )
dataset.add_faiss_index('''embeddings''', custom_index=A_ )
# And save the index
_lowerCamelCase : int = os.path.join(rag_example_args.output_dir, '''my_knowledge_dataset_hnsw_index.faiss''' )
dataset.get_index('''embeddings''' ).save(A_ )
# dataset.load_faiss_index("embeddings", index_path) # to reload the index
@dataclass
class __snake_case :
snake_case__ : str = field(
default=str(Path(_lowercase).parent / "test_run" / "dummy-kb" / "my_knowledge_dataset.csv") , metadata={"help": "Path to a tab-separated csv file with columns 'title' and 'text'"} , )
snake_case__ : Optional[str] = field(
default=_lowercase , metadata={"help": "Question that is passed as input to RAG. Default is 'What does Moses' rod turn into ?'."} , )
snake_case__ : str = field(
default="facebook/rag-sequence-nq" , metadata={"help": "The RAG model to use. Either 'facebook/rag-sequence-nq' or 'facebook/rag-token-nq'"} , )
snake_case__ : str = field(
default="facebook/dpr-ctx_encoder-multiset-base" , metadata={
"help": (
"The DPR context encoder model to use. Either 'facebook/dpr-ctx_encoder-single-nq-base' or"
" 'facebook/dpr-ctx_encoder-multiset-base'"
)
} , )
snake_case__ : Optional[str] = field(
default=str(Path(_lowercase).parent / "test_run" / "dummy-kb") , metadata={"help": "Path to a directory where the dataset passages and the index will be saved"} , )
@dataclass
class __snake_case :
snake_case__ : Optional[int] = field(
default=_lowercase , metadata={
"help": "The number of processes to use to split the documents into passages. Default is single process."
} , )
snake_case__ : int = field(
default=1_6 , metadata={
"help": "The batch size to use when computing the passages embeddings using the DPR context encoder."
} , )
@dataclass
class __snake_case :
snake_case__ : int = field(
default=7_6_8 , metadata={"help": "The dimension of the embeddings to pass to the HNSW Faiss index."} , )
snake_case__ : int = field(
default=1_2_8 , metadata={
"help": (
"The number of bi-directional links created for every new element during the HNSW index construction."
)
} , )
if __name__ == "__main__":
logging.basicConfig(level=logging.WARNING)
logger.setLevel(logging.INFO)
lowerCAmelCase__ = HfArgumentParser((RagExampleArguments, ProcessingArguments, IndexHnswArguments))
lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_args_into_dataclasses()
with TemporaryDirectory() as tmp_dir:
lowerCAmelCase__ = rag_example_args.output_dir or tmp_dir
main(rag_example_args, processing_args, index_hnsw_args)
| 598 | 1 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
snake_case__ : Any = logging.get_logger(__name__)
snake_case__ : Optional[Any] = {
"""microsoft/cvt-13""": """https://huggingface.co/microsoft/cvt-13/resolve/main/config.json""",
# See all Cvt models at https://huggingface.co/models?filter=cvt
}
class _a ( UpperCAmelCase__ ):
"""simple docstring"""
A_ = """cvt"""
def __init__( self , _UpperCAmelCase=3 , _UpperCAmelCase=[7, 3, 3] , _UpperCAmelCase=[4, 2, 2] , _UpperCAmelCase=[2, 1, 1] , _UpperCAmelCase=[64, 192, 384] , _UpperCAmelCase=[1, 3, 6] , _UpperCAmelCase=[1, 2, 10] , _UpperCAmelCase=[4.0, 4.0, 4.0] , _UpperCAmelCase=[0.0, 0.0, 0.0] , _UpperCAmelCase=[0.0, 0.0, 0.0] , _UpperCAmelCase=[0.0, 0.0, 0.1] , _UpperCAmelCase=[True, True, True] , _UpperCAmelCase=[False, False, True] , _UpperCAmelCase=["dw_bn", "dw_bn", "dw_bn"] , _UpperCAmelCase=[3, 3, 3] , _UpperCAmelCase=[1, 1, 1] , _UpperCAmelCase=[2, 2, 2] , _UpperCAmelCase=[1, 1, 1] , _UpperCAmelCase=[1, 1, 1] , _UpperCAmelCase=0.0_2 , _UpperCAmelCase=1e-12 , **_UpperCAmelCase , ) -> Optional[int]:
super().__init__(**_UpperCAmelCase )
UpperCamelCase_ = num_channels
UpperCamelCase_ = patch_sizes
UpperCamelCase_ = patch_stride
UpperCamelCase_ = patch_padding
UpperCamelCase_ = embed_dim
UpperCamelCase_ = num_heads
UpperCamelCase_ = depth
UpperCamelCase_ = mlp_ratio
UpperCamelCase_ = attention_drop_rate
UpperCamelCase_ = drop_rate
UpperCamelCase_ = drop_path_rate
UpperCamelCase_ = qkv_bias
UpperCamelCase_ = cls_token
UpperCamelCase_ = qkv_projection_method
UpperCamelCase_ = kernel_qkv
UpperCamelCase_ = padding_kv
UpperCamelCase_ = stride_kv
UpperCamelCase_ = padding_q
UpperCamelCase_ = stride_q
UpperCamelCase_ = initializer_range
UpperCamelCase_ = layer_norm_eps
| 23 |
_UpperCAmelCase : int = range(2, 20 + 1)
_UpperCAmelCase : Dict = [10**k for k in range(ks[-1] + 1)]
_UpperCAmelCase : dict[int, dict[int, list[list[int]]]] = {}
def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ):
'''simple docstring'''
snake_case_ = sum(a_i[j] for j in range(UpperCamelCase__ , len(UpperCamelCase__ ) ) )
snake_case_ = sum(a_i[j] * base[j] for j in range(min(len(UpperCamelCase__ ) , UpperCamelCase__ ) ) )
snake_case_ , snake_case_ = 0, 0
snake_case_ = n - i
snake_case_ = memo.get(UpperCamelCase__ )
if sub_memo is not None:
snake_case_ = sub_memo.get(UpperCamelCase__ )
if jumps is not None and len(UpperCamelCase__ ) > 0:
# find and make the largest jump without going over
snake_case_ = -1
for _k in range(len(UpperCamelCase__ ) - 1 , -1 , -1 ):
if jumps[_k][2] <= k and jumps[_k][1] <= max_dn:
snake_case_ = _k
break
if max_jump >= 0:
snake_case_ , snake_case_ , snake_case_ = jumps[max_jump]
# since the difference between jumps is cached, add c
snake_case_ = diff + c
for j in range(min(UpperCamelCase__ , len(UpperCamelCase__ ) ) ):
snake_case_ , snake_case_ = divmod(UpperCamelCase__ , 10 )
if new_c > 0:
add(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ )
else:
snake_case_ = []
else:
snake_case_ = {c: []}
snake_case_ = sub_memo
if dn >= max_dn or c + diff >= base[k]:
return diff, dn
if k > ks[0]:
while True:
# keep doing smaller jumps
snake_case_ , snake_case_ = next_term(UpperCamelCase__ , k - 1 , i + dn , UpperCamelCase__ )
diff += _diff
dn += terms_jumped
if dn >= max_dn or c + diff >= base[k]:
break
else:
# would be too small a jump, just compute sequential terms instead
snake_case_ , snake_case_ = compute(UpperCamelCase__ , UpperCamelCase__ , i + dn , UpperCamelCase__ )
diff += _diff
dn += terms_jumped
snake_case_ = sub_memo[c]
# keep jumps sorted by # of terms skipped
snake_case_ = 0
while j < len(UpperCamelCase__ ):
if jumps[j][1] > dn:
break
j += 1
# cache the jump for this value digitsum(b) and c
sub_memo[c].insert(UpperCamelCase__ , (diff, dn, k) )
return (diff, dn)
def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ):
'''simple docstring'''
if i >= n:
return 0, i
if k > len(UpperCamelCase__ ):
a_i.extend([0 for _ in range(k - len(UpperCamelCase__ ) )] )
# note: a_i -> b * 10^k + c
# ds_b -> digitsum(b)
# ds_c -> digitsum(c)
snake_case_ = i
snake_case_ , snake_case_ , snake_case_ = 0, 0, 0
for j in range(len(UpperCamelCase__ ) ):
if j >= k:
ds_b += a_i[j]
else:
ds_c += a_i[j]
while i < n:
i += 1
snake_case_ = ds_c + ds_b
diff += addend
snake_case_ = 0
for j in range(UpperCamelCase__ ):
snake_case_ = a_i[j] + addend
snake_case_ , snake_case_ = divmod(UpperCamelCase__ , 10 )
ds_c += a_i[j]
if addend > 0:
break
if addend > 0:
add(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ )
return diff, i - start_i
def __lowerCamelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ):
'''simple docstring'''
for j in range(UpperCamelCase__ , len(UpperCamelCase__ ) ):
snake_case_ = digits[j] + addend
if s >= 10:
snake_case_ , snake_case_ = divmod(UpperCamelCase__ , 10 )
snake_case_ = addend // 10 + quotient
else:
snake_case_ = s
snake_case_ = addend // 10
if addend == 0:
break
while addend > 0:
snake_case_ , snake_case_ = divmod(UpperCamelCase__ , 10 )
digits.append(UpperCamelCase__ )
def __lowerCamelCase ( UpperCamelCase__ = 10**15 ):
'''simple docstring'''
snake_case_ = [1]
snake_case_ = 1
snake_case_ = 0
while True:
snake_case_ , snake_case_ = next_term(UpperCamelCase__ , 20 , i + dn , UpperCamelCase__ )
dn += terms_jumped
if dn == n - i:
break
snake_case_ = 0
for j in range(len(UpperCamelCase__ ) ):
a_n += digits[j] * 10**j
return a_n
if __name__ == "__main__":
print(F'''{solution() = }''')
| 362 | 0 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_sentencepiece_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
snake_case = {'''configuration_mbart''': ['''MBART_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MBartConfig''', '''MBartOnnxConfig''']}
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case = ['''MBartTokenizer''']
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case = ['''MBartTokenizerFast''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case = [
'''MBART_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''MBartForCausalLM''',
'''MBartForConditionalGeneration''',
'''MBartForQuestionAnswering''',
'''MBartForSequenceClassification''',
'''MBartModel''',
'''MBartPreTrainedModel''',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case = [
'''TFMBartForConditionalGeneration''',
'''TFMBartModel''',
'''TFMBartPreTrainedModel''',
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case = [
'''FlaxMBartForConditionalGeneration''',
'''FlaxMBartForQuestionAnswering''',
'''FlaxMBartForSequenceClassification''',
'''FlaxMBartModel''',
'''FlaxMBartPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig
try:
if not is_sentencepiece_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_mbart import MBartTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_mbart_fast import MBartTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mbart import (
MBART_PRETRAINED_MODEL_ARCHIVE_LIST,
MBartForCausalLM,
MBartForConditionalGeneration,
MBartForQuestionAnswering,
MBartForSequenceClassification,
MBartModel,
MBartPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_mbart import (
FlaxMBartForConditionalGeneration,
FlaxMBartForQuestionAnswering,
FlaxMBartForSequenceClassification,
FlaxMBartModel,
FlaxMBartPreTrainedModel,
)
else:
import sys
snake_case = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 704 |
"""simple docstring"""
from math import isqrt
def snake_case ( lowerCAmelCase_ ) -> bool:
return all(number % divisor != 0 for divisor in range(2 , isqrt(lowerCAmelCase_ ) + 1 ) )
def snake_case ( lowerCAmelCase_ = 10**6 ) -> int:
_snake_case = 0
_snake_case = 1
_snake_case = 7
while prime_candidate < max_prime:
primes_count += is_prime(lowerCAmelCase_ )
cube_index += 1
prime_candidate += 6 * cube_index
return primes_count
if __name__ == "__main__":
print(F"{solution() = }")
| 404 | 0 |
from typing import Optional, Union
import torch
from torch import nn
from ...configuration_utils import ConfigMixin, register_to_config
from ...models.modeling_utils import ModelMixin
class A_ ( UpperCAmelCase , UpperCAmelCase ):
"""simple docstring"""
@register_to_config
def __init__( self : List[str] ,__A : int = 768 ,) -> List[Any]:
super().__init__()
_lowercase = nn.Parameter(torch.zeros(1 ,__A ) )
_lowercase = nn.Parameter(torch.ones(1 ,__A ) )
def __UpperCAmelCase ( self : List[str] ,__A : Optional[Union[str, torch.device]] = None ,__A : Optional[torch.dtype] = None ,) -> Optional[int]:
_lowercase = nn.Parameter(self.mean.to(__A ).to(__A ) )
_lowercase = nn.Parameter(self.std.to(__A ).to(__A ) )
return self
def __UpperCAmelCase ( self : int ,__A : str ) -> List[Any]:
_lowercase = (embeds - self.mean) * 1.0 / self.std
return embeds
def __UpperCAmelCase ( self : str ,__A : str ) -> Tuple:
_lowercase = (embeds * self.std) + self.mean
return embeds | 67 |
def SCREAMING_SNAKE_CASE ( _UpperCAmelCase ) -> str:
lowerCamelCase__ : Dict = ''
for ch in key:
if ch == " " or ch not in key_no_dups and ch.isalpha():
key_no_dups += ch
return key_no_dups
def SCREAMING_SNAKE_CASE ( _UpperCAmelCase ) -> dict[str, str]:
lowerCamelCase__ : List[str] = [chr(i + 65 ) for i in range(26 )]
# Remove duplicate characters from key
lowerCamelCase__ : Any = remove_duplicates(key.upper() )
lowerCamelCase__ : List[Any] = len(_UpperCAmelCase )
# First fill cipher with key characters
lowerCamelCase__ : Optional[int] = {alphabet[i]: char for i, char in enumerate(_UpperCAmelCase )}
# Then map remaining characters in alphabet to
# the alphabet from the beginning
for i in range(len(_UpperCAmelCase ) , 26 ):
lowerCamelCase__ : Any = alphabet[i - offset]
# Ensure we are not mapping letters to letters previously mapped
while char in key:
offset -= 1
lowerCamelCase__ : Union[str, Any] = alphabet[i - offset]
lowerCamelCase__ : int = char
return cipher_alphabet
def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase ) -> str:
return "".join(cipher_map.get(_UpperCAmelCase , _UpperCAmelCase ) for ch in message.upper() )
def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase ) -> str:
lowerCamelCase__ : List[str] = {v: k for k, v in cipher_map.items()}
return "".join(rev_cipher_map.get(_UpperCAmelCase , _UpperCAmelCase ) for ch in message.upper() )
def SCREAMING_SNAKE_CASE ( ) -> None:
lowerCamelCase__ : str = input('Enter message to encode or decode: ' ).strip()
lowerCamelCase__ : Union[str, Any] = input('Enter keyword: ' ).strip()
lowerCamelCase__ : Dict = input('Encipher or decipher? E/D:' ).strip()[0].lower()
try:
lowerCamelCase__ : Dict = {'e': encipher, 'd': decipher}[option]
except KeyError:
raise KeyError('invalid input option' )
lowerCamelCase__ : int = create_cipher_map(_UpperCAmelCase )
print(func(_UpperCAmelCase , _UpperCAmelCase ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| 295 | 0 |
from .integrations import (
is_optuna_available,
is_ray_available,
is_sigopt_available,
is_wandb_available,
run_hp_search_optuna,
run_hp_search_ray,
run_hp_search_sigopt,
run_hp_search_wandb,
)
from .trainer_utils import (
HPSearchBackend,
default_hp_space_optuna,
default_hp_space_ray,
default_hp_space_sigopt,
default_hp_space_wandb,
)
from .utils import logging
UpperCamelCase = logging.get_logger(__name__)
class _A :
lowercase_ : str
lowercase_ : str = None
@staticmethod
def a ( ):
"""simple docstring"""
raise NotImplementedError
def a ( self : Dict , lowerCamelCase__ : str , lowerCamelCase__ : int , lowerCamelCase__ : str , **lowerCamelCase__ : Optional[int] ):
"""simple docstring"""
raise NotImplementedError
def a ( self : List[Any] , lowerCamelCase__ : List[str] ):
"""simple docstring"""
raise NotImplementedError
def a ( self : Dict ):
"""simple docstring"""
if not self.is_available():
raise RuntimeError(
f'You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}.' )
@classmethod
def a ( cls : int ):
"""simple docstring"""
return f'`pip install {cls.pip_package or cls.name}`'
class _A ( UpperCAmelCase_ ):
lowercase_ : int = '''optuna'''
@staticmethod
def a ( ):
"""simple docstring"""
return is_optuna_available()
def a ( self : str , lowerCamelCase__ : Tuple , lowerCamelCase__ : int , lowerCamelCase__ : str , **lowerCamelCase__ : Tuple ):
"""simple docstring"""
return run_hp_search_optuna(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , **lowerCamelCase__ )
def a ( self : Optional[Any] , lowerCamelCase__ : List[Any] ):
"""simple docstring"""
return default_hp_space_optuna(lowerCamelCase__ )
class _A ( UpperCAmelCase_ ):
lowercase_ : int = '''ray'''
lowercase_ : Optional[Any] = '''\'ray[tune]\''''
@staticmethod
def a ( ):
"""simple docstring"""
return is_ray_available()
def a ( self : Optional[Any] , lowerCamelCase__ : List[Any] , lowerCamelCase__ : int , lowerCamelCase__ : str , **lowerCamelCase__ : Dict ):
"""simple docstring"""
return run_hp_search_ray(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , **lowerCamelCase__ )
def a ( self : Any , lowerCamelCase__ : List[Any] ):
"""simple docstring"""
return default_hp_space_ray(lowerCamelCase__ )
class _A ( UpperCAmelCase_ ):
lowercase_ : Any = '''sigopt'''
@staticmethod
def a ( ):
"""simple docstring"""
return is_sigopt_available()
def a ( self : str , lowerCamelCase__ : str , lowerCamelCase__ : int , lowerCamelCase__ : str , **lowerCamelCase__ : List[str] ):
"""simple docstring"""
return run_hp_search_sigopt(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , **lowerCamelCase__ )
def a ( self : int , lowerCamelCase__ : Tuple ):
"""simple docstring"""
return default_hp_space_sigopt(lowerCamelCase__ )
class _A ( UpperCAmelCase_ ):
lowercase_ : str = '''wandb'''
@staticmethod
def a ( ):
"""simple docstring"""
return is_wandb_available()
def a ( self : int , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : int , lowerCamelCase__ : str , **lowerCamelCase__ : Dict ):
"""simple docstring"""
return run_hp_search_wandb(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , **lowerCamelCase__ )
def a ( self : Union[str, Any] , lowerCamelCase__ : str ):
"""simple docstring"""
return default_hp_space_wandb(lowerCamelCase__ )
UpperCamelCase = {
HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend]
}
def __lowerCamelCase ( ) -> str:
__UpperCamelCase : Optional[int] = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()]
if len(__lowerCAmelCase ) > 0:
__UpperCamelCase : Optional[int] = available_backends[0].name
if len(__lowerCAmelCase ) > 1:
logger.info(
f'{len(__lowerCAmelCase )} hyperparameter search backends available. Using {name} as the default.' )
return name
raise RuntimeError(
"""No hyperparameter search backend available.\n"""
+ """\n""".join(
f' - To install {backend.name} run {backend.pip_install()}'
for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() ) )
| 515 |
def __lowerCamelCase ( __lowerCAmelCase : list ) -> list:
__UpperCamelCase : Dict = len(__lowerCAmelCase )
for i in range(1 , __lowerCAmelCase ):
__UpperCamelCase : Dict = collection[i]
__UpperCamelCase : Optional[Any] = 0
__UpperCamelCase : Dict = i - 1
while low <= high:
__UpperCamelCase : int = (low + high) // 2
if val < collection[mid]:
__UpperCamelCase : str = mid - 1
else:
__UpperCamelCase : str = mid + 1
for j in range(__lowerCAmelCase , __lowerCAmelCase , -1 ):
__UpperCamelCase : str = collection[j - 1]
__UpperCamelCase : int = val
return collection
if __name__ == "__main__":
UpperCamelCase = input('Enter numbers separated by a comma:\n').strip()
UpperCamelCase = [int(item) for item in user_input.split(',')]
print(binary_insertion_sort(unsorted))
| 515 | 1 |
"""simple docstring"""
from typing import TYPE_CHECKING
# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
_UpperCamelCase = {
"""configuration_autoformer""": [
"""AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""",
"""AutoformerConfig""",
],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_UpperCamelCase = [
"""AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""AutoformerForPrediction""",
"""AutoformerModel""",
"""AutoformerPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_autoformer import (
AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
AutoformerConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_autoformer import (
AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
AutoformerForPrediction,
AutoformerModel,
AutoformerPreTrainedModel,
)
else:
import sys
_UpperCamelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 453 |
"""simple docstring"""
import argparse
import json
import os
import sys
import tempfile
import unittest
from argparse import Namespace
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from typing import List, Literal, Optional
import yaml
from transformers import HfArgumentParser, TrainingArguments
from transformers.hf_argparser import make_choice_type_function, string_to_bool
# Since Python 3.10, we can use the builtin `|` operator for Union types
# See PEP 604: https://peps.python.org/pep-0604
_UpperCamelCase = sys.version_info >= (3, 1_0)
def SCREAMING_SNAKE_CASE ( lowercase__=None , lowercase__=None ) -> List[Any]:
return field(default_factory=lambda: default , metadata=lowercase__ )
@dataclass
class __a :
"""simple docstring"""
__UpperCamelCase : int
__UpperCamelCase : float
__UpperCamelCase : str
__UpperCamelCase : bool
@dataclass
class __a :
"""simple docstring"""
__UpperCamelCase : int = 42
__UpperCamelCase : str = field(default='toto' , metadata={'help': 'help message'} )
@dataclass
class __a :
"""simple docstring"""
__UpperCamelCase : bool = False
__UpperCamelCase : bool = True
__UpperCamelCase : Optional[bool] = None
class __a ( __magic_name__ ):
"""simple docstring"""
__UpperCamelCase : List[str] = 'titi'
__UpperCamelCase : Tuple = 'toto'
class __a ( __magic_name__ ):
"""simple docstring"""
__UpperCamelCase : Tuple = 'titi'
__UpperCamelCase : List[Any] = 'toto'
__UpperCamelCase : List[str] = 42
@dataclass
class __a :
"""simple docstring"""
__UpperCamelCase : BasicEnum = "toto"
def SCREAMING_SNAKE_CASE_ ( self ):
"""simple docstring"""
lowerCAmelCase__ : Optional[int] = BasicEnum(self.foo )
@dataclass
class __a :
"""simple docstring"""
__UpperCamelCase : MixedTypeEnum = "toto"
def SCREAMING_SNAKE_CASE_ ( self ):
"""simple docstring"""
lowerCAmelCase__ : List[str] = MixedTypeEnum(self.foo )
@dataclass
class __a :
"""simple docstring"""
__UpperCamelCase : Optional[int] = None
__UpperCamelCase : Optional[float] = field(default=__magic_name__ , metadata={'help': 'help message'} )
__UpperCamelCase : Optional[str] = None
__UpperCamelCase : Optional[List[str]] = list_field(default=[] )
__UpperCamelCase : Optional[List[int]] = list_field(default=[] )
@dataclass
class __a :
"""simple docstring"""
__UpperCamelCase : List[int] = list_field(default=[] )
__UpperCamelCase : List[int] = list_field(default=[1, 2, 3] )
__UpperCamelCase : List[str] = list_field(default=['Hallo', 'Bonjour', 'Hello'] )
__UpperCamelCase : List[float] = list_field(default=[0.1, 0.2, 0.3] )
@dataclass
class __a :
"""simple docstring"""
__UpperCamelCase : List[int] = field()
__UpperCamelCase : str = field()
__UpperCamelCase : BasicEnum = field()
def SCREAMING_SNAKE_CASE_ ( self ):
"""simple docstring"""
lowerCAmelCase__ : Optional[Any] = BasicEnum(self.required_enum )
@dataclass
class __a :
"""simple docstring"""
__UpperCamelCase : int
__UpperCamelCase : "BasicEnum" = field()
__UpperCamelCase : "Optional[bool]" = None
__UpperCamelCase : "str" = field(default='toto' , metadata={'help': 'help message'} )
__UpperCamelCase : "List[str]" = list_field(default=['Hallo', 'Bonjour', 'Hello'] )
if is_python_no_less_than_3_10:
@dataclass
class __a :
"""simple docstring"""
__UpperCamelCase : bool = False
__UpperCamelCase : bool = True
__UpperCamelCase : bool | None = None
@dataclass
class __a :
"""simple docstring"""
__UpperCamelCase : int | None = None
__UpperCamelCase : float | None = field(default=__magic_name__ , metadata={'help': 'help message'} )
__UpperCamelCase : str | None = None
__UpperCamelCase : list[str] | None = list_field(default=[] )
__UpperCamelCase : list[int] | None = list_field(default=[] )
class __a ( unittest.TestCase ):
"""simple docstring"""
def SCREAMING_SNAKE_CASE_ ( self , snake_case , snake_case ):
"""simple docstring"""
self.assertEqual(len(a._actions ) , len(b._actions ) )
for x, y in zip(a._actions , b._actions ):
lowerCAmelCase__ : Union[str, Any] = {k: v for k, v in vars(snake_case ).items() if k != "container"}
lowerCAmelCase__ : Union[str, Any] = {k: v for k, v in vars(snake_case ).items() if k != "container"}
# Choices with mixed type have custom function as "type"
# So we need to compare results directly for equality
if xx.get("choices" , snake_case ) and yy.get("choices" , snake_case ):
for expected_choice in yy["choices"] + xx["choices"]:
self.assertEqual(xx["type"](snake_case ) , yy["type"](snake_case ) )
del xx["type"], yy["type"]
self.assertEqual(snake_case , snake_case )
def SCREAMING_SNAKE_CASE_ ( self ):
"""simple docstring"""
lowerCAmelCase__ : Union[str, Any] = HfArgumentParser(snake_case )
lowerCAmelCase__ : Optional[int] = argparse.ArgumentParser()
expected.add_argument("--foo" , type=snake_case , required=snake_case )
expected.add_argument("--bar" , type=snake_case , required=snake_case )
expected.add_argument("--baz" , type=snake_case , required=snake_case )
expected.add_argument("--flag" , type=snake_case , default=snake_case , const=snake_case , nargs="?" )
self.argparsersEqual(snake_case , snake_case )
lowerCAmelCase__ : List[Any] = ["--foo", "1", "--baz", "quux", "--bar", "0.5"]
((lowerCAmelCase__) , ) : Dict = parser.parse_args_into_dataclasses(snake_case , look_for_args_file=snake_case )
self.assertFalse(example.flag )
def SCREAMING_SNAKE_CASE_ ( self ):
"""simple docstring"""
lowerCAmelCase__ : Tuple = HfArgumentParser(snake_case )
lowerCAmelCase__ : Optional[int] = argparse.ArgumentParser()
expected.add_argument("--foo" , default=42 , type=snake_case )
expected.add_argument("--baz" , default="toto" , type=snake_case , help="help message" )
self.argparsersEqual(snake_case , snake_case )
def SCREAMING_SNAKE_CASE_ ( self ):
"""simple docstring"""
lowerCAmelCase__ : Optional[Any] = argparse.ArgumentParser()
expected.add_argument("--foo" , type=snake_case , default=snake_case , const=snake_case , nargs="?" )
expected.add_argument("--baz" , type=snake_case , default=snake_case , const=snake_case , nargs="?" )
# A boolean no_* argument always has to come after its "default: True" regular counter-part
# and its default must be set to False
expected.add_argument("--no_baz" , action="store_false" , default=snake_case , dest="baz" )
expected.add_argument("--opt" , type=snake_case , default=snake_case )
lowerCAmelCase__ : Optional[Any] = [WithDefaultBoolExample]
if is_python_no_less_than_3_10:
dataclass_types.append(snake_case )
for dataclass_type in dataclass_types:
lowerCAmelCase__ : Optional[Any] = HfArgumentParser(snake_case )
self.argparsersEqual(snake_case , snake_case )
lowerCAmelCase__ : Union[str, Any] = parser.parse_args([] )
self.assertEqual(snake_case , Namespace(foo=snake_case , baz=snake_case , opt=snake_case ) )
lowerCAmelCase__ : List[str] = parser.parse_args(["--foo", "--no_baz"] )
self.assertEqual(snake_case , Namespace(foo=snake_case , baz=snake_case , opt=snake_case ) )
lowerCAmelCase__ : Optional[Any] = parser.parse_args(["--foo", "--baz"] )
self.assertEqual(snake_case , Namespace(foo=snake_case , baz=snake_case , opt=snake_case ) )
lowerCAmelCase__ : List[Any] = parser.parse_args(["--foo", "True", "--baz", "True", "--opt", "True"] )
self.assertEqual(snake_case , Namespace(foo=snake_case , baz=snake_case , opt=snake_case ) )
lowerCAmelCase__ : Optional[int] = parser.parse_args(["--foo", "False", "--baz", "False", "--opt", "False"] )
self.assertEqual(snake_case , Namespace(foo=snake_case , baz=snake_case , opt=snake_case ) )
def SCREAMING_SNAKE_CASE_ ( self ):
"""simple docstring"""
lowerCAmelCase__ : Tuple = HfArgumentParser(snake_case )
lowerCAmelCase__ : Optional[Any] = argparse.ArgumentParser()
expected.add_argument(
"--foo" , default="toto" , choices=["titi", "toto", 42] , type=make_choice_type_function(["titi", "toto", 42] ) , )
self.argparsersEqual(snake_case , snake_case )
lowerCAmelCase__ : Union[str, Any] = parser.parse_args([] )
self.assertEqual(args.foo , "toto" )
lowerCAmelCase__ : List[str] = parser.parse_args_into_dataclasses([] )[0]
self.assertEqual(enum_ex.foo , MixedTypeEnum.toto )
lowerCAmelCase__ : List[Any] = parser.parse_args(["--foo", "titi"] )
self.assertEqual(args.foo , "titi" )
lowerCAmelCase__ : Any = parser.parse_args_into_dataclasses(["--foo", "titi"] )[0]
self.assertEqual(enum_ex.foo , MixedTypeEnum.titi )
lowerCAmelCase__ : Tuple = parser.parse_args(["--foo", "42"] )
self.assertEqual(args.foo , 42 )
lowerCAmelCase__ : Tuple = parser.parse_args_into_dataclasses(["--foo", "42"] )[0]
self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo )
def SCREAMING_SNAKE_CASE_ ( self ):
"""simple docstring"""
@dataclass
class __a :
"""simple docstring"""
__UpperCamelCase : Literal["titi", "toto", 42] = "toto"
lowerCAmelCase__ : Dict = HfArgumentParser(snake_case )
lowerCAmelCase__ : Dict = argparse.ArgumentParser()
expected.add_argument(
"--foo" , default="toto" , choices=("titi", "toto", 42) , type=make_choice_type_function(["titi", "toto", 42] ) , )
self.argparsersEqual(snake_case , snake_case )
lowerCAmelCase__ : int = parser.parse_args([] )
self.assertEqual(args.foo , "toto" )
lowerCAmelCase__ : Optional[int] = parser.parse_args(["--foo", "titi"] )
self.assertEqual(args.foo , "titi" )
lowerCAmelCase__ : int = parser.parse_args(["--foo", "42"] )
self.assertEqual(args.foo , 42 )
def SCREAMING_SNAKE_CASE_ ( self ):
"""simple docstring"""
lowerCAmelCase__ : str = HfArgumentParser(snake_case )
lowerCAmelCase__ : Union[str, Any] = argparse.ArgumentParser()
expected.add_argument("--foo_int" , nargs="+" , default=[] , type=snake_case )
expected.add_argument("--bar_int" , nargs="+" , default=[1, 2, 3] , type=snake_case )
expected.add_argument("--foo_str" , nargs="+" , default=["Hallo", "Bonjour", "Hello"] , type=snake_case )
expected.add_argument("--foo_float" , nargs="+" , default=[0.1, 0.2, 0.3] , type=snake_case )
self.argparsersEqual(snake_case , snake_case )
lowerCAmelCase__ : Tuple = parser.parse_args([] )
self.assertEqual(
snake_case , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=["Hallo", "Bonjour", "Hello"] , foo_float=[0.1, 0.2, 0.3] ) , )
lowerCAmelCase__ : List[Any] = parser.parse_args("--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7".split() )
self.assertEqual(snake_case , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=["a", "b", "c"] , foo_float=[0.1, 0.7] ) )
def SCREAMING_SNAKE_CASE_ ( self ):
"""simple docstring"""
lowerCAmelCase__ : Dict = argparse.ArgumentParser()
expected.add_argument("--foo" , default=snake_case , type=snake_case )
expected.add_argument("--bar" , default=snake_case , type=snake_case , help="help message" )
expected.add_argument("--baz" , default=snake_case , type=snake_case )
expected.add_argument("--ces" , nargs="+" , default=[] , type=snake_case )
expected.add_argument("--des" , nargs="+" , default=[] , type=snake_case )
lowerCAmelCase__ : Optional[Any] = [OptionalExample]
if is_python_no_less_than_3_10:
dataclass_types.append(snake_case )
for dataclass_type in dataclass_types:
lowerCAmelCase__ : Tuple = HfArgumentParser(snake_case )
self.argparsersEqual(snake_case , snake_case )
lowerCAmelCase__ : Any = parser.parse_args([] )
self.assertEqual(snake_case , Namespace(foo=snake_case , bar=snake_case , baz=snake_case , ces=[] , des=[] ) )
lowerCAmelCase__ : List[str] = parser.parse_args("--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3".split() )
self.assertEqual(snake_case , Namespace(foo=12 , bar=3.14 , baz="42" , ces=["a", "b", "c"] , des=[1, 2, 3] ) )
def SCREAMING_SNAKE_CASE_ ( self ):
"""simple docstring"""
lowerCAmelCase__ : Optional[Any] = HfArgumentParser(snake_case )
lowerCAmelCase__ : List[Any] = argparse.ArgumentParser()
expected.add_argument("--required_list" , nargs="+" , type=snake_case , required=snake_case )
expected.add_argument("--required_str" , type=snake_case , required=snake_case )
expected.add_argument(
"--required_enum" , type=make_choice_type_function(["titi", "toto"] ) , choices=["titi", "toto"] , required=snake_case , )
self.argparsersEqual(snake_case , snake_case )
def SCREAMING_SNAKE_CASE_ ( self ):
"""simple docstring"""
lowerCAmelCase__ : Dict = HfArgumentParser(snake_case )
lowerCAmelCase__ : Optional[Any] = argparse.ArgumentParser()
expected.add_argument("--foo" , type=snake_case , required=snake_case )
expected.add_argument(
"--required_enum" , type=make_choice_type_function(["titi", "toto"] ) , choices=["titi", "toto"] , required=snake_case , )
expected.add_argument("--opt" , type=snake_case , default=snake_case )
expected.add_argument("--baz" , default="toto" , type=snake_case , help="help message" )
expected.add_argument("--foo_str" , nargs="+" , default=["Hallo", "Bonjour", "Hello"] , type=snake_case )
self.argparsersEqual(snake_case , snake_case )
def SCREAMING_SNAKE_CASE_ ( self ):
"""simple docstring"""
lowerCAmelCase__ : Any = HfArgumentParser(snake_case )
lowerCAmelCase__ : List[Any] = {
"foo": 12,
"bar": 3.14,
"baz": "42",
"flag": True,
}
lowerCAmelCase__ : Tuple = parser.parse_dict(snake_case )[0]
lowerCAmelCase__ : Any = BasicExample(**snake_case )
self.assertEqual(snake_case , snake_case )
def SCREAMING_SNAKE_CASE_ ( self ):
"""simple docstring"""
lowerCAmelCase__ : Union[str, Any] = HfArgumentParser(snake_case )
lowerCAmelCase__ : List[Any] = {
"foo": 12,
"bar": 3.14,
"baz": "42",
"flag": True,
"extra": 42,
}
self.assertRaises(snake_case , parser.parse_dict , snake_case , allow_extra_keys=snake_case )
def SCREAMING_SNAKE_CASE_ ( self ):
"""simple docstring"""
lowerCAmelCase__ : Union[str, Any] = HfArgumentParser(snake_case )
lowerCAmelCase__ : Optional[Any] = {
"foo": 12,
"bar": 3.14,
"baz": "42",
"flag": True,
}
with tempfile.TemporaryDirectory() as tmp_dir:
lowerCAmelCase__ : int = os.path.join(snake_case , "temp_json" )
os.mkdir(snake_case )
with open(temp_local_path + ".json" , "w+" ) as f:
json.dump(snake_case , snake_case )
lowerCAmelCase__ : Any = parser.parse_yaml_file(Path(temp_local_path + ".json" ) )[0]
lowerCAmelCase__ : str = BasicExample(**snake_case )
self.assertEqual(snake_case , snake_case )
def SCREAMING_SNAKE_CASE_ ( self ):
"""simple docstring"""
lowerCAmelCase__ : str = HfArgumentParser(snake_case )
lowerCAmelCase__ : int = {
"foo": 12,
"bar": 3.14,
"baz": "42",
"flag": True,
}
with tempfile.TemporaryDirectory() as tmp_dir:
lowerCAmelCase__ : Optional[Any] = os.path.join(snake_case , "temp_yaml" )
os.mkdir(snake_case )
with open(temp_local_path + ".yaml" , "w+" ) as f:
yaml.dump(snake_case , snake_case )
lowerCAmelCase__ : Dict = parser.parse_yaml_file(Path(temp_local_path + ".yaml" ) )[0]
lowerCAmelCase__ : int = BasicExample(**snake_case )
self.assertEqual(snake_case , snake_case )
def SCREAMING_SNAKE_CASE_ ( self ):
"""simple docstring"""
lowerCAmelCase__ : Union[str, Any] = HfArgumentParser(snake_case )
self.assertIsNotNone(snake_case )
| 453 | 1 |
from typing import Optional, Tuple, Union
import torch
from einops import rearrange, reduce
from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel
from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput
from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput
__lowerCAmelCase :List[Any] = 8
def A ( UpperCAmelCase , UpperCAmelCase=BITS ):
_snake_case : Dict = x.device
_snake_case : int = (x * 255).int().clamp(0 , 255 )
_snake_case : Dict = 2 ** torch.arange(bits - 1 , -1 , -1 , device=UpperCAmelCase )
_snake_case : str = rearrange(UpperCAmelCase , "d -> d 1 1" )
_snake_case : Any = rearrange(UpperCAmelCase , "b c h w -> b c 1 h w" )
_snake_case : Optional[int] = ((x & mask) != 0).float()
_snake_case : List[Any] = rearrange(UpperCAmelCase , "b c d h w -> b (c d) h w" )
_snake_case : Any = bits * 2 - 1
return bits
def A ( UpperCAmelCase , UpperCAmelCase=BITS ):
_snake_case : Optional[Any] = x.device
_snake_case : Union[str, Any] = (x > 0).int()
_snake_case : Any = 2 ** torch.arange(bits - 1 , -1 , -1 , device=UpperCAmelCase , dtype=torch.intaa )
_snake_case : Any = rearrange(UpperCAmelCase , "d -> d 1 1" )
_snake_case : List[Any] = rearrange(UpperCAmelCase , "b (c d) h w -> b c d h w" , d=8 )
_snake_case : str = reduce(x * mask , "b c d h w -> b c h w" , "sum" )
return (dec / 255).clamp(0.0 , 1.0 )
def A ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = 0.0 , UpperCAmelCase = True , UpperCAmelCase=None , UpperCAmelCase = True , ):
if self.num_inference_steps is None:
raise ValueError(
"Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler" )
# See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf
# Ideally, read DDIM paper in-detail understanding
# Notation (<variable name> -> <name in paper>
# - pred_noise_t -> e_theta(x_t, t)
# - pred_original_sample -> f_theta(x_t, t) or x_0
# - std_dev_t -> sigma_t
# - eta -> η
# - pred_sample_direction -> "direction pointing to x_t"
# - pred_prev_sample -> "x_t-1"
# 1. get previous step value (=t-1)
_snake_case : Optional[int] = timestep - self.config.num_train_timesteps // self.num_inference_steps
# 2. compute alphas, betas
_snake_case : List[str] = self.alphas_cumprod[timestep]
_snake_case : Optional[Any] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
_snake_case : Optional[Any] = 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
_snake_case : Optional[int] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
# 4. Clip "predicted x_0"
_snake_case : List[str] = self.bit_scale
if self.config.clip_sample:
_snake_case : List[str] = torch.clamp(UpperCAmelCase , -scale , UpperCAmelCase )
# 5. compute variance: "sigma_t(η)" -> see formula (16)
# σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)
_snake_case : str = self._get_variance(UpperCAmelCase , UpperCAmelCase )
_snake_case : List[str] = eta * variance ** 0.5
if use_clipped_model_output:
# the model_output is always re-derived from the clipped x_0 in Glide
_snake_case : Any = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5
# 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
_snake_case : List[str] = (1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * model_output
# 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
_snake_case : List[str] = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction
if eta > 0:
# randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072
_snake_case : List[Any] = model_output.device if torch.is_tensor(UpperCAmelCase ) else "cpu"
_snake_case : Optional[Any] = torch.randn(model_output.shape , dtype=model_output.dtype , generator=UpperCAmelCase ).to(UpperCAmelCase )
_snake_case : Optional[int] = self._get_variance(UpperCAmelCase , UpperCAmelCase ) ** 0.5 * eta * noise
_snake_case : Any = prev_sample + variance
if not return_dict:
return (prev_sample,)
return DDIMSchedulerOutput(prev_sample=UpperCAmelCase , pred_original_sample=UpperCAmelCase )
def A ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase="epsilon" , UpperCAmelCase=None , UpperCAmelCase = True , ):
_snake_case : List[str] = timestep
if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]:
_snake_case , _snake_case : Any = torch.split(UpperCAmelCase , sample.shape[1] , dim=1 )
else:
_snake_case : Tuple = None
# 1. compute alphas, betas
_snake_case : Tuple = self.alphas_cumprod[t]
_snake_case : Optional[int] = self.alphas_cumprod[t - 1] if t > 0 else self.one
_snake_case : Union[str, Any] = 1 - alpha_prod_t
_snake_case : Union[str, Any] = 1 - alpha_prod_t_prev
# 2. compute predicted original sample from predicted noise also called
# "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf
if prediction_type == "epsilon":
_snake_case : Any = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
elif prediction_type == "sample":
_snake_case : Dict = model_output
else:
raise ValueError(F"""Unsupported prediction_type {prediction_type}.""" )
# 3. Clip "predicted x_0"
_snake_case : Dict = self.bit_scale
if self.config.clip_sample:
_snake_case : int = torch.clamp(UpperCAmelCase , -scale , UpperCAmelCase )
# 4. Compute coefficients for pred_original_sample x_0 and current sample x_t
# See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
_snake_case : Union[str, Any] = (alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t
_snake_case : Optional[int] = self.alphas[t] ** 0.5 * beta_prod_t_prev / beta_prod_t
# 5. Compute predicted previous sample µ_t
# See formula (7) from https://arxiv.org/pdf/2006.11239.pdf
_snake_case : int = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample
# 6. Add noise
_snake_case : Union[str, Any] = 0
if t > 0:
_snake_case : Tuple = torch.randn(
model_output.size() , dtype=model_output.dtype , layout=model_output.layout , generator=UpperCAmelCase ).to(model_output.device )
_snake_case : Dict = (self._get_variance(UpperCAmelCase , predicted_variance=UpperCAmelCase ) ** 0.5) * noise
_snake_case : str = pred_prev_sample + variance
if not return_dict:
return (pred_prev_sample,)
return DDPMSchedulerOutput(prev_sample=UpperCAmelCase , pred_original_sample=UpperCAmelCase )
class _a( __A ):
def __init__( self , __snake_case , __snake_case , __snake_case = 1.0 , ) -> Tuple:
'''simple docstring'''
super().__init__()
_snake_case : Dict = bit_scale
_snake_case : Any = (
ddim_bit_scheduler_step if isinstance(__snake_case , __snake_case ) else ddpm_bit_scheduler_step
)
self.register_modules(unet=__snake_case , scheduler=__snake_case )
@torch.no_grad()
def __call__( self , __snake_case = 2_5_6 , __snake_case = 2_5_6 , __snake_case = 5_0 , __snake_case = None , __snake_case = 1 , __snake_case = "pil" , __snake_case = True , **__snake_case , ) -> Union[Tuple, ImagePipelineOutput]:
'''simple docstring'''
_snake_case : Union[str, Any] = torch.randn(
(batch_size, self.unet.config.in_channels, height, width) , generator=__snake_case , )
_snake_case : Any = decimal_to_bits(__snake_case ) * self.bit_scale
_snake_case : Union[str, Any] = latents.to(self.device )
self.scheduler.set_timesteps(__snake_case )
for t in self.progress_bar(self.scheduler.timesteps ):
# predict the noise residual
_snake_case : int = self.unet(__snake_case , __snake_case ).sample
# compute the previous noisy sample x_t -> x_t-1
_snake_case : Any = self.scheduler.step(__snake_case , __snake_case , __snake_case ).prev_sample
_snake_case : Optional[Any] = bits_to_decimal(__snake_case )
if output_type == "pil":
_snake_case : List[Any] = self.numpy_to_pil(__snake_case )
if not return_dict:
return (image,)
return ImagePipelineOutput(images=__snake_case ) | 278 |
import os
import time
import warnings
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional, Union
import torch
from filelock import FileLock
from torch.utils.data import Dataset
from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import logging
from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors
from ..processors.utils import InputFeatures
__lowerCAmelCase :Tuple = logging.get_logger(__name__)
@dataclass
class _a:
lowerCamelCase__ :str = field(metadata={'help': 'The name of the task to train on: ' + ', '.join(glue_processors.keys() )} )
lowerCamelCase__ :str = field(
metadata={'help': 'The input data dir. Should contain the .tsv files (or other data files) for the task.'} )
lowerCamelCase__ :int = field(
default=128 , metadata={
'help': (
'The maximum total input sequence length after tokenization. Sequences longer '
'than this will be truncated, sequences shorter will be padded.'
)
} , )
lowerCamelCase__ :bool = field(
default=__A , metadata={'help': 'Overwrite the cached training and evaluation sets'} )
def lowercase ( self ) -> Optional[Any]:
'''simple docstring'''
_snake_case : Dict = self.task_name.lower()
class _a( __A ):
lowerCamelCase__ :Optional[Any] = 'train'
lowerCamelCase__ :List[str] = 'dev'
lowerCamelCase__ :Any = 'test'
class _a( __A ):
lowerCamelCase__ :GlueDataTrainingArguments
lowerCamelCase__ :str
lowerCamelCase__ :List[InputFeatures]
def __init__( self , __snake_case , __snake_case , __snake_case = None , __snake_case = Split.train , __snake_case = None , ) -> Any:
'''simple docstring'''
warnings.warn(
"This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets "
"library. You can have a look at this example script for pointers: "
"https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py" , __snake_case , )
_snake_case : Optional[Any] = args
_snake_case : Optional[int] = glue_processors[args.task_name]()
_snake_case : int = glue_output_modes[args.task_name]
if isinstance(__snake_case , __snake_case ):
try:
_snake_case : Tuple = Split[mode]
except KeyError:
raise KeyError("mode is not a valid split name" )
# Load data features from cache or dataset file
_snake_case : List[str] = os.path.join(
cache_dir if cache_dir is not None else args.data_dir , f"""cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}""" , )
_snake_case : List[Any] = self.processor.get_labels()
if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in (
"RobertaTokenizer",
"RobertaTokenizerFast",
"XLMRobertaTokenizer",
"BartTokenizer",
"BartTokenizerFast",
):
# HACK(label indices are swapped in RoBERTa pretrained model)
_snake_case , _snake_case : int = label_list[2], label_list[1]
_snake_case : str = label_list
# Make sure only the first process in distributed training processes the dataset,
# and the others will use the cache.
_snake_case : Optional[Any] = cached_features_file + ".lock"
with FileLock(__snake_case ):
if os.path.exists(__snake_case ) and not args.overwrite_cache:
_snake_case : List[str] = time.time()
_snake_case : str = torch.load(__snake_case )
logger.info(
f"""Loading features from cached file {cached_features_file} [took %.3f s]""" , time.time() - start )
else:
logger.info(f"""Creating features from dataset file at {args.data_dir}""" )
if mode == Split.dev:
_snake_case : List[Any] = self.processor.get_dev_examples(args.data_dir )
elif mode == Split.test:
_snake_case : List[Any] = self.processor.get_test_examples(args.data_dir )
else:
_snake_case : str = self.processor.get_train_examples(args.data_dir )
if limit_length is not None:
_snake_case : Tuple = examples[:limit_length]
_snake_case : List[str] = glue_convert_examples_to_features(
__snake_case , __snake_case , max_length=args.max_seq_length , label_list=__snake_case , output_mode=self.output_mode , )
_snake_case : Optional[Any] = time.time()
torch.save(self.features , __snake_case )
# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
logger.info(
f"""Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]""" )
def __len__( self ) -> List[str]:
'''simple docstring'''
return len(self.features )
def __getitem__( self , __snake_case ) -> InputFeatures:
'''simple docstring'''
return self.features[i]
def lowercase ( self ) -> Optional[Any]:
'''simple docstring'''
return self.label_list | 278 | 1 |
"""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 lowercase:
def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=1_3 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=2_4 , __SCREAMING_SNAKE_CASE=1_6 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=3_2 , __SCREAMING_SNAKE_CASE=5 , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=3_7 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=1_0 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=2 , ) -> List[Any]:
"""simple docstring"""
a__ = parent
a__ = batch_size
a__ = patch_size
a__ = max_length
a__ = num_mel_bins
a__ = is_training
a__ = use_labels
a__ = hidden_size
a__ = num_hidden_layers
a__ = num_attention_heads
a__ = intermediate_size
a__ = hidden_act
a__ = hidden_dropout_prob
a__ = attention_probs_dropout_prob
a__ = type_sequence_label_size
a__ = initializer_range
a__ = scope
a__ = frequency_stride
a__ = time_stride
# in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
a__ = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1
a__ = (self.max_length - self.patch_size) // self.time_stride + 1
a__ = frequency_out_dimension * time_out_dimension
a__ = num_patches + 2
def lowercase__ ( self ) -> Any:
"""simple docstring"""
a__ = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] )
a__ = None
if self.use_labels:
a__ = ids_tensor([self.batch_size] , self.type_sequence_label_size )
a__ = self.get_config()
return config, input_values, labels
def lowercase__ ( self ) -> Dict:
"""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=__SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , )
def lowercase__ ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> str:
"""simple docstring"""
a__ = ASTModel(config=__SCREAMING_SNAKE_CASE )
model.to(__SCREAMING_SNAKE_CASE )
model.eval()
a__ = model(__SCREAMING_SNAKE_CASE )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def lowercase__ ( self ) -> Tuple:
"""simple docstring"""
a__ = self.prepare_config_and_inputs()
(
(
a__
) , (
a__
) , (
a__
) ,
) = config_and_inputs
a__ = {'input_values': input_values}
return config, inputs_dict
@require_torch
class lowercase(_lowercase , _lowercase , unittest.TestCase ):
__snake_case: str = (
(
ASTModel,
ASTForAudioClassification,
)
if is_torch_available()
else ()
)
__snake_case: Optional[int] = (
{'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel}
if is_torch_available()
else {}
)
__snake_case: str = False
__snake_case: Union[str, Any] = False
__snake_case: List[Any] = False
__snake_case: str = False
def lowercase__ ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> Any:
"""simple docstring"""
if pipeline_test_casse_name == "AudioClassificationPipelineTests":
return True
return False
def lowercase__ ( self ) -> int:
"""simple docstring"""
a__ = ASTModelTester(self )
a__ = ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , has_text_modality=__SCREAMING_SNAKE_CASE , hidden_size=3_7 )
def lowercase__ ( self ) -> List[str]:
"""simple docstring"""
self.config_tester.run_common_tests()
@unittest.skip(reason='AST does not use inputs_embeds' )
def lowercase__ ( self ) -> Tuple:
"""simple docstring"""
pass
def lowercase__ ( self ) -> Union[str, Any]:
"""simple docstring"""
a__ , a__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
a__ = model_class(__SCREAMING_SNAKE_CASE )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
a__ = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE , nn.Linear ) )
def lowercase__ ( self ) -> Any:
"""simple docstring"""
a__ , a__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
a__ = model_class(__SCREAMING_SNAKE_CASE )
a__ = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
a__ = [*signature.parameters.keys()]
a__ = ['input_values']
self.assertListEqual(arg_names[:1] , __SCREAMING_SNAKE_CASE )
def lowercase__ ( self ) -> str:
"""simple docstring"""
a__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE )
@slow
def lowercase__ ( self ) -> List[str]:
"""simple docstring"""
for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
a__ = ASTModel.from_pretrained(__SCREAMING_SNAKE_CASE )
self.assertIsNotNone(__SCREAMING_SNAKE_CASE )
def __magic_name__ ( ) -> Optional[Any]:
a__ = hf_hub_download(
repo_id='nielsr/audio-spectogram-transformer-checkpoint' , filename='sample_audio.flac' , repo_type='dataset' )
a__ , a__ = torchaudio.load(UpperCamelCase )
return audio, sampling_rate
@require_torch
@require_torchaudio
class lowercase(unittest.TestCase ):
@cached_property
def lowercase__ ( self ) -> Any:
"""simple docstring"""
return (
ASTFeatureExtractor.from_pretrained('MIT/ast-finetuned-audioset-10-10-0.4593' )
if is_torchaudio_available()
else None
)
@slow
def lowercase__ ( self ) -> int:
"""simple docstring"""
a__ = self.default_feature_extractor
a__ = ASTForAudioClassification.from_pretrained('MIT/ast-finetuned-audioset-10-10-0.4593' ).to(__SCREAMING_SNAKE_CASE )
a__ = self.default_feature_extractor
a__ , a__ = prepare_audio()
a__ = audio.squeeze().numpy()
a__ = feature_extractor(__SCREAMING_SNAKE_CASE , sampling_rate=__SCREAMING_SNAKE_CASE , return_tensors='pt' ).to(__SCREAMING_SNAKE_CASE )
# forward pass
with torch.no_grad():
a__ = model(**__SCREAMING_SNAKE_CASE )
# verify the logits
a__ = torch.Size((1, 5_2_7) )
self.assertEqual(outputs.logits.shape , __SCREAMING_SNAKE_CASE )
a__ = torch.tensor([-0.87_60, -7.00_42, -8.66_02] ).to(__SCREAMING_SNAKE_CASE )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , __SCREAMING_SNAKE_CASE , atol=1e-4 ) )
| 273 |
"""simple docstring"""
from __future__ import annotations
a : str = {
'A': ['B', 'C', 'E'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F', 'G'],
'D': ['B'],
'E': ['A', 'B', 'D'],
'F': ['C'],
'G': ['C'],
}
class lowercase:
def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) -> None:
"""simple docstring"""
a__ = graph
# mapping node to its parent in resulting breadth first tree
a__ = {}
a__ = source_vertex
def lowercase__ ( self ) -> None:
"""simple docstring"""
a__ = {self.source_vertex}
a__ = None
a__ = [self.source_vertex] # first in first out queue
while queue:
a__ = queue.pop(0 )
for adjacent_vertex in self.graph[vertex]:
if adjacent_vertex not in visited:
visited.add(__SCREAMING_SNAKE_CASE )
a__ = vertex
queue.append(__SCREAMING_SNAKE_CASE )
def lowercase__ ( self , __SCREAMING_SNAKE_CASE ) -> str:
"""simple docstring"""
if target_vertex == self.source_vertex:
return self.source_vertex
a__ = self.parent.get(__SCREAMING_SNAKE_CASE )
if target_vertex_parent is None:
a__ = (
f'No path from vertex: {self.source_vertex} to vertex: {target_vertex}'
)
raise ValueError(__SCREAMING_SNAKE_CASE )
return self.shortest_path(__SCREAMING_SNAKE_CASE ) + f'->{target_vertex}'
if __name__ == "__main__":
a : Optional[Any] = Graph(graph, 'G')
g.breath_first_search()
print(g.shortest_path('D'))
print(g.shortest_path('G'))
print(g.shortest_path('Foo'))
| 273 | 1 |
from __future__ import annotations
import math
def lowerCamelCase_ ( UpperCamelCase__ : int ):
'''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(UpperCamelCase__ ) + 1 ), 6 ):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
lowercase = [num for num in range(3, 1_0_0_0_0_1, 2) if not is_prime(num)]
def lowerCamelCase_ ( UpperCamelCase__ : int ):
'''simple docstring'''
if not isinstance(UpperCamelCase__, UpperCamelCase__ ):
raise ValueError('''n must be an integer''' )
if n <= 0:
raise ValueError('''n must be >= 0''' )
UpperCamelCase__ = []
for num in range(len(UpperCamelCase__ ) ):
UpperCamelCase__ = 0
while 2 * i * i <= odd_composites[num]:
UpperCamelCase__ = odd_composites[num] - 2 * i * i
if is_prime(UpperCamelCase__ ):
break
i += 1
else:
list_nums.append(odd_composites[num] )
if len(UpperCamelCase__ ) == n:
return list_nums
return []
def lowerCamelCase_ ( ):
'''simple docstring'''
return compute_nums(1 )[0]
if __name__ == "__main__":
print(f'{solution() = }')
| 720 | # Copyright 2022 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import os
import subprocess
from packaging.version import Version, parse
from accelerate.commands.config.config_args import default_config_file, load_config_from_file
lowercase = """Run commands across TPU VMs for initial setup before running `accelerate launch`."""
def lowerCamelCase_ ( UpperCamelCase__ : Optional[int]=None ):
'''simple docstring'''
if subparsers is not None:
UpperCamelCase__ = subparsers.add_parser('''tpu-config''', description=_description )
else:
UpperCamelCase__ = argparse.ArgumentParser('''Accelerate tpu-config command''', description=_description )
# Core arguments
UpperCamelCase__ = parser.add_argument_group(
'''Config Arguments''', '''Arguments that can be configured through `accelerate config`.''' )
config_args.add_argument(
'''--config_file''', type=UpperCamelCase__, default=UpperCamelCase__, help='''Path to the config file to use for accelerate.''', )
config_args.add_argument(
'''--tpu_name''', default=UpperCamelCase__, help='''The name of the TPU to use. If not specified, will use the TPU specified in the config file.''', )
config_args.add_argument(
'''--tpu_zone''', default=UpperCamelCase__, help='''The zone of the TPU to use. If not specified, will use the zone specified in the config file.''', )
UpperCamelCase__ = parser.add_argument_group('''TPU Arguments''', '''Arguments for options ran inside the TPU.''' )
pod_args.add_argument(
'''--use_alpha''', action='''store_true''', help='''Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.''', )
pod_args.add_argument(
'''--command_file''', default=UpperCamelCase__, help='''The path to the file containing the commands to run on the pod on startup.''', )
pod_args.add_argument(
'''--command''', action='''append''', nargs='''+''', help='''A command to run on the pod. Can be passed multiple times.''', )
pod_args.add_argument(
'''--install_accelerate''', action='''store_true''', help='''Whether to install accelerate on the pod. Defaults to False.''', )
pod_args.add_argument(
'''--accelerate_version''', default='''latest''', help='''The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify \'dev\' to install from GitHub.''', )
pod_args.add_argument(
'''--debug''', action='''store_true''', help='''If set, will print the command that would be run instead of running it.''' )
if subparsers is not None:
parser.set_defaults(func=UpperCamelCase__ )
return parser
def lowerCamelCase_ ( UpperCamelCase__ : str ):
'''simple docstring'''
UpperCamelCase__ = None
# Get the default from the config file if it exists.
if args.config_file is not None or os.path.isfile(UpperCamelCase__ ):
UpperCamelCase__ = load_config_from_file(args.config_file )
if not args.command_file and defaults.command_file is not None and not args.command:
UpperCamelCase__ = defaults.command_file
if not args.command and defaults.commands is not None:
UpperCamelCase__ = defaults.commands
if not args.tpu_name:
UpperCamelCase__ = defaults.tpu_name
if not args.tpu_zone:
UpperCamelCase__ = defaults.tpu_zone
if args.accelerate_version == "dev":
UpperCamelCase__ = '''git+https://github.com/huggingface/accelerate.git'''
elif args.accelerate_version == "latest":
UpperCamelCase__ = '''accelerate -U'''
elif isinstance(parse(args.accelerate_version ), UpperCamelCase__ ):
UpperCamelCase__ = F"""accelerate=={args.accelerate_version}"""
if not args.command_file and not args.command:
raise ValueError('''You must specify either a command file or a command to run on the pod.''' )
if args.command_file:
with open(args.command_file, '''r''' ) as f:
UpperCamelCase__ = [f.read().splitlines()]
# To turn list of lists into list of strings
if isinstance(args.command[0], UpperCamelCase__ ):
UpperCamelCase__ = [line for cmd in args.command for line in cmd]
# Default to the shared folder and install accelerate
UpperCamelCase__ = ['''cd /usr/share''']
if args.install_accelerate:
new_cmd += [F"""pip install {args.accelerate_version}"""]
new_cmd += args.command
UpperCamelCase__ = '''; '''.join(UpperCamelCase__ )
# Then send it to gcloud
# Eventually try to use google-api-core to do this instead of subprocess
UpperCamelCase__ = ['''gcloud''']
if args.use_alpha:
cmd += ["alpha"]
cmd += [
"compute",
"tpus",
"tpu-vm",
"ssh",
args.tpu_name,
"--zone",
args.tpu_zone,
"--command",
args.command,
"--worker",
"all",
]
if args.debug:
print(F"""Running {" ".join(UpperCamelCase__ )}""" )
return
subprocess.run(UpperCamelCase__ )
print('''Successfully setup pod.''' )
def lowerCamelCase_ ( ):
'''simple docstring'''
UpperCamelCase__ = tpu_command_parser()
UpperCamelCase__ = parser.parse_args()
tpu_command_launcher(UpperCamelCase__ )
| 591 | 0 |
import os
import pickle
import unittest
from transformers import AutoTokenizer
from transformers.models.bert.tokenization_bert import BertTokenizer
from transformers.models.bert_japanese.tokenization_bert_japanese import (
VOCAB_FILES_NAMES,
BertJapaneseTokenizer,
CharacterTokenizer,
JumanppTokenizer,
MecabTokenizer,
SudachiTokenizer,
WordpieceTokenizer,
)
from transformers.testing_utils import custom_tokenizers, require_jumanpp, require_sudachi
from ...test_tokenization_common import TokenizerTesterMixin
@custom_tokenizers
class a ( __lowercase ,unittest.TestCase ):
SCREAMING_SNAKE_CASE__ : List[Any] = BertJapaneseTokenizer
SCREAMING_SNAKE_CASE__ : Optional[Any] = False
SCREAMING_SNAKE_CASE__ : Optional[Any] = True
def snake_case_ ( self ):
"""simple docstring"""
super().setUp()
__SCREAMING_SNAKE_CASE: str = [
'''[UNK]''',
'''[CLS]''',
'''[SEP]''',
'''こんにちは''',
'''こん''',
'''にちは''',
'''ばんは''',
'''##こん''',
'''##にちは''',
'''##ばんは''',
'''世界''',
'''##世界''',
'''、''',
'''##、''',
'''。''',
'''##。''',
]
__SCREAMING_SNAKE_CASE: List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer:
vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) )
def snake_case_ ( self , _lowerCAmelCase ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: List[Any] = '''こんにちは、世界。 \nこんばんは、世界。'''
__SCREAMING_SNAKE_CASE: Tuple = '''こんにちは 、 世界 。 こんばんは 、 世界 。'''
return input_text, output_text
def snake_case_ ( self , _lowerCAmelCase ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE: Optional[Any] = self.get_input_output_texts(_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: List[Any] = tokenizer.encode(_lowerCAmelCase , add_special_tokens=_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: Tuple = tokenizer.decode(_lowerCAmelCase , clean_up_tokenization_spaces=_lowerCAmelCase )
return text, ids
def snake_case_ ( self ):
"""simple docstring"""
pass # TODO add if relevant
def snake_case_ ( self ):
"""simple docstring"""
pass # TODO add if relevant
def snake_case_ ( self ):
"""simple docstring"""
pass # TODO add if relevant
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Tuple = self.tokenizer_class(self.vocab_file )
__SCREAMING_SNAKE_CASE: Optional[Any] = tokenizer.tokenize('''こんにちは、世界。\nこんばんは、世界。''' )
self.assertListEqual(_lowerCAmelCase , ['''こんにちは''', '''、''', '''世界''', '''。''', '''こん''', '''##ばんは''', '''、''', '''世界''', '''。'''] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCAmelCase ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] )
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: str = self.tokenizer_class(self.vocab_file , word_tokenizer_type='''mecab''' )
self.assertIsNotNone(_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: Tuple = '''こんにちは、世界。\nこんばんは、世界。'''
__SCREAMING_SNAKE_CASE: Union[str, Any] = tokenizer.tokenize(_lowerCAmelCase )
self.assertListEqual(_lowerCAmelCase , ['''こんにちは''', '''、''', '''世界''', '''。''', '''こん''', '''##ばんは''', '''、''', '''世界''', '''。'''] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCAmelCase ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] )
__SCREAMING_SNAKE_CASE: Optional[Any] = os.path.join(self.tmpdirname , '''tokenizer.bin''' )
with open(_lowerCAmelCase , '''wb''' ) as handle:
pickle.dump(_lowerCAmelCase , _lowerCAmelCase )
with open(_lowerCAmelCase , '''rb''' ) as handle:
__SCREAMING_SNAKE_CASE: Any = pickle.load(_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: Any = tokenizer_new.tokenize(_lowerCAmelCase )
self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase )
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Optional[int] = MecabTokenizer(mecab_dic='''ipadic''' )
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップルストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', '''。'''] , )
def snake_case_ ( self ):
"""simple docstring"""
try:
__SCREAMING_SNAKE_CASE: str = MecabTokenizer(mecab_dic='''unidic_lite''' )
except ModuleNotFoundError:
return
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', '''。'''] , )
def snake_case_ ( self ):
"""simple docstring"""
try:
__SCREAMING_SNAKE_CASE: int = MecabTokenizer(mecab_dic='''unidic''' )
except ModuleNotFoundError:
return
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', '''。'''] , )
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Union[str, Any] = MecabTokenizer(do_lower_case=_lowerCAmelCase , mecab_dic='''ipadic''' )
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップルストア''', '''で''', '''iphone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', '''。'''] , )
def snake_case_ ( self ):
"""simple docstring"""
try:
__SCREAMING_SNAKE_CASE: int = MecabTokenizer(
do_lower_case=_lowerCAmelCase , normalize_text=_lowerCAmelCase , mecab_option='''-d /usr/local/lib/mecab/dic/jumandic''' )
except RuntimeError:
# if dict doesn't exist in the system, previous code raises this error.
return
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップルストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れた''', '''\u3000''', '''。'''] , )
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Tuple = MecabTokenizer(normalize_text=_lowerCAmelCase , mecab_dic='''ipadic''' )
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップルストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', ''' ''', '''。'''] , )
@require_sudachi
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Any = self.tokenizer_class(self.vocab_file , word_tokenizer_type='''sudachi''' )
self.assertIsNotNone(_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: str = '''こんにちは、世界。\nこんばんは、世界。'''
__SCREAMING_SNAKE_CASE: str = tokenizer.tokenize(_lowerCAmelCase )
self.assertListEqual(_lowerCAmelCase , ['''こんにちは''', '''、''', '''世界''', '''。''', '''こん''', '''##ばんは''', '''、''', '''世界''', '''。'''] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCAmelCase ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] )
__SCREAMING_SNAKE_CASE: Union[str, Any] = os.path.join(self.tmpdirname , '''tokenizer.bin''' )
with open(_lowerCAmelCase , '''wb''' ) as handle:
pickle.dump(_lowerCAmelCase , _lowerCAmelCase )
with open(_lowerCAmelCase , '''rb''' ) as handle:
__SCREAMING_SNAKE_CASE: Optional[Any] = pickle.load(_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: Optional[int] = tokenizer_new.tokenize(_lowerCAmelCase )
self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase )
@require_sudachi
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: int = SudachiTokenizer(sudachi_dict_type='''core''' )
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , [''' ''', '''\t''', '''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', ''' ''', '''が''', ''' ''', ''' ''', '''\n ''', '''発売''', '''さ''', '''れ''', '''た''', ''' ''', '''。''', ''' ''', ''' '''] , )
@require_sudachi
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Optional[Any] = SudachiTokenizer(sudachi_dict_type='''core''' , sudachi_split_mode='''A''' )
self.assertListEqual(tokenizer.tokenize('''外国人参政権''' ) , ['''外国''', '''人''', '''参政''', '''権'''] )
@require_sudachi
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: str = SudachiTokenizer(sudachi_dict_type='''core''' , sudachi_split_mode='''B''' )
self.assertListEqual(tokenizer.tokenize('''外国人参政権''' ) , ['''外国人''', '''参政権'''] )
@require_sudachi
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: List[str] = SudachiTokenizer(sudachi_dict_type='''core''' , sudachi_split_mode='''C''' )
self.assertListEqual(tokenizer.tokenize('''外国人参政権''' ) , ['''外国人参政権'''] )
@require_sudachi
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: List[str] = SudachiTokenizer(do_lower_case=_lowerCAmelCase , sudachi_dict_type='''core''' )
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , [''' ''', '''\t''', '''アップル''', '''ストア''', '''で''', '''iphone''', '''8''', ''' ''', '''が''', ''' ''', ''' ''', '''\n ''', '''発売''', '''さ''', '''れ''', '''た''', ''' ''', '''。''', ''' ''', ''' '''] , )
@require_sudachi
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: List[Any] = SudachiTokenizer(normalize_text=_lowerCAmelCase , sudachi_dict_type='''core''' )
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , [''' ''', '''\t''', '''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', ''' ''', '''が''', ''' ''', ''' ''', '''\n ''', '''発売''', '''さ''', '''れ''', '''た''', '''\u3000''', '''。''', ''' ''', ''' '''] , )
@require_sudachi
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Optional[Any] = SudachiTokenizer(trim_whitespace=_lowerCAmelCase , sudachi_dict_type='''core''' )
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れ''', '''た''', '''。'''] , )
@require_jumanpp
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Dict = self.tokenizer_class(self.vocab_file , word_tokenizer_type='''jumanpp''' )
self.assertIsNotNone(_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: List[str] = '''こんにちは、世界。\nこんばんは、世界。'''
__SCREAMING_SNAKE_CASE: Any = tokenizer.tokenize(_lowerCAmelCase )
self.assertListEqual(_lowerCAmelCase , ['''こんにちは''', '''、''', '''世界''', '''。''', '''こん''', '''##ばんは''', '''、''', '''世界''', '''。'''] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCAmelCase ) , [3, 12, 10, 14, 4, 9, 12, 10, 14] )
__SCREAMING_SNAKE_CASE: Union[str, Any] = os.path.join(self.tmpdirname , '''tokenizer.bin''' )
with open(_lowerCAmelCase , '''wb''' ) as handle:
pickle.dump(_lowerCAmelCase , _lowerCAmelCase )
with open(_lowerCAmelCase , '''rb''' ) as handle:
__SCREAMING_SNAKE_CASE: List[str] = pickle.load(_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: int = tokenizer_new.tokenize(_lowerCAmelCase )
self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase )
@require_jumanpp
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Optional[Any] = JumanppTokenizer()
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''\u3000''', '''が''', '''\u3000''', '''\u3000''', '''\u3000''', '''発売''', '''さ''', '''れた''', '''\u3000''', '''。'''] , )
@require_jumanpp
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: str = JumanppTokenizer(do_lower_case=_lowerCAmelCase )
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iphone''', '''8''', '''\u3000''', '''が''', '''\u3000''', '''\u3000''', '''\u3000''', '''発売''', '''さ''', '''れた''', '''\u3000''', '''。'''] , )
@require_jumanpp
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Optional[Any] = JumanppTokenizer(normalize_text=_lowerCAmelCase )
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''ア''', '''ッ''', '''フ''', '''゚''', '''ル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''\u3000''', '''が''', '''\u3000''', '''\u3000''', '''\u3000''', '''発売''', '''さ''', '''れた''', '''\u3000''', '''。'''] , )
@require_jumanpp
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Optional[Any] = JumanppTokenizer(trim_whitespace=_lowerCAmelCase )
self.assertListEqual(
tokenizer.tokenize(''' \tアップルストアでiPhone8 が \n 発売された 。 ''' ) , ['''アップル''', '''ストア''', '''で''', '''iPhone''', '''8''', '''が''', '''発売''', '''さ''', '''れた''', '''。'''] , )
@require_jumanpp
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: int = JumanppTokenizer()
self.assertListEqual(
tokenizer.tokenize('''ありがとうございますm(_ _)m見つけるのが大変です。''' ) , ['''ありがとう''', '''ございます''', '''m(_ _)m''', '''見つける''', '''の''', '''が''', '''大変です''', '''。'''] , )
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Optional[Any] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''こんにちは''', '''こん''', '''にちは''', '''ばんは''', '''##こん''', '''##にちは''', '''##ばんは''']
__SCREAMING_SNAKE_CASE: Optional[Any] = {}
for i, token in enumerate(_lowerCAmelCase ):
__SCREAMING_SNAKE_CASE: Union[str, Any] = i
__SCREAMING_SNAKE_CASE: List[str] = WordpieceTokenizer(vocab=_lowerCAmelCase , unk_token='''[UNK]''' )
self.assertListEqual(tokenizer.tokenize('''''' ) , [] )
self.assertListEqual(tokenizer.tokenize('''こんにちは''' ) , ['''こんにちは'''] )
self.assertListEqual(tokenizer.tokenize('''こんばんは''' ) , ['''こん''', '''##ばんは'''] )
self.assertListEqual(tokenizer.tokenize('''こんばんは こんばんにちは こんにちは''' ) , ['''こん''', '''##ばんは''', '''[UNK]''', '''こんにちは'''] )
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Any = BertJapaneseTokenizer.from_pretrained('''nlp-waseda/roberta-base-japanese-with-auto-jumanpp''' )
__SCREAMING_SNAKE_CASE: Tuple = tokenizer.subword_tokenizer
__SCREAMING_SNAKE_CASE: Union[str, Any] = subword_tokenizer.tokenize('''国境 の 長い トンネル を 抜ける と 雪国 であった 。''' )
self.assertListEqual(_lowerCAmelCase , ['''▁国境''', '''▁の''', '''▁長い''', '''▁トンネル''', '''▁を''', '''▁抜ける''', '''▁と''', '''▁雪''', '''国''', '''▁であった''', '''▁。'''] )
__SCREAMING_SNAKE_CASE: Dict = subword_tokenizer.tokenize('''こんばんは こんばん にち は こんにちは''' )
self.assertListEqual(_lowerCAmelCase , ['''▁こん''', '''ばん''', '''は''', '''▁こん''', '''ばん''', '''▁に''', '''ち''', '''▁は''', '''▁こんにちは'''] )
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Optional[Any] = self.tokenizer_class.from_pretrained('''cl-tohoku/bert-base-japanese''' )
__SCREAMING_SNAKE_CASE: List[Any] = tokenizer.encode('''ありがとう。''' , add_special_tokens=_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: List[str] = tokenizer.encode('''どういたしまして。''' , add_special_tokens=_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: List[Any] = tokenizer.build_inputs_with_special_tokens(_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: List[Any] = tokenizer.build_inputs_with_special_tokens(_lowerCAmelCase , _lowerCAmelCase )
# 2 is for "[CLS]", 3 is for "[SEP]"
assert encoded_sentence == [2] + text + [3]
assert encoded_pair == [2] + text + [3] + text_a + [3]
@custom_tokenizers
class a ( __lowercase ,unittest.TestCase ):
SCREAMING_SNAKE_CASE__ : Any = BertJapaneseTokenizer
SCREAMING_SNAKE_CASE__ : int = False
def snake_case_ ( self ):
"""simple docstring"""
super().setUp()
__SCREAMING_SNAKE_CASE: str = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''こ''', '''ん''', '''に''', '''ち''', '''は''', '''ば''', '''世''', '''界''', '''、''', '''。''']
__SCREAMING_SNAKE_CASE: Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer:
vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) )
def snake_case_ ( self , **_lowerCAmelCase ):
"""simple docstring"""
return BertJapaneseTokenizer.from_pretrained(self.tmpdirname , subword_tokenizer_type='''character''' , **_lowerCAmelCase )
def snake_case_ ( self , _lowerCAmelCase ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Dict = '''こんにちは、世界。 \nこんばんは、世界。'''
__SCREAMING_SNAKE_CASE: int = '''こ ん に ち は 、 世 界 。 こ ん ば ん は 、 世 界 。'''
return input_text, output_text
def snake_case_ ( self ):
"""simple docstring"""
pass # TODO add if relevant
def snake_case_ ( self ):
"""simple docstring"""
pass # TODO add if relevant
def snake_case_ ( self ):
"""simple docstring"""
pass # TODO add if relevant
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Union[str, Any] = self.tokenizer_class(self.vocab_file , subword_tokenizer_type='''character''' )
__SCREAMING_SNAKE_CASE: Optional[int] = tokenizer.tokenize('''こんにちは、世界。 \nこんばんは、世界。''' )
self.assertListEqual(
_lowerCAmelCase , ['''こ''', '''ん''', '''に''', '''ち''', '''は''', '''、''', '''世''', '''界''', '''。''', '''こ''', '''ん''', '''ば''', '''ん''', '''は''', '''、''', '''世''', '''界''', '''。'''] )
self.assertListEqual(
tokenizer.convert_tokens_to_ids(_lowerCAmelCase ) , [3, 4, 5, 6, 7, 11, 9, 10, 12, 3, 4, 8, 4, 7, 11, 9, 10, 12] )
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Tuple = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''こ''', '''ん''', '''に''', '''ち''', '''は''', '''ば''', '''世''', '''界''', '''、''', '''。''']
__SCREAMING_SNAKE_CASE: Tuple = {}
for i, token in enumerate(_lowerCAmelCase ):
__SCREAMING_SNAKE_CASE: Optional[Any] = i
__SCREAMING_SNAKE_CASE: Any = CharacterTokenizer(vocab=_lowerCAmelCase , unk_token='''[UNK]''' )
self.assertListEqual(tokenizer.tokenize('''''' ) , [] )
self.assertListEqual(tokenizer.tokenize('''こんにちは''' ) , ['''こ''', '''ん''', '''に''', '''ち''', '''は'''] )
self.assertListEqual(tokenizer.tokenize('''こんにちほ''' ) , ['''こ''', '''ん''', '''に''', '''ち''', '''[UNK]'''] )
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Dict = self.tokenizer_class.from_pretrained('''cl-tohoku/bert-base-japanese-char''' )
__SCREAMING_SNAKE_CASE: Optional[Any] = tokenizer.encode('''ありがとう。''' , add_special_tokens=_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: Dict = tokenizer.encode('''どういたしまして。''' , add_special_tokens=_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: str = tokenizer.build_inputs_with_special_tokens(_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: Optional[int] = tokenizer.build_inputs_with_special_tokens(_lowerCAmelCase , _lowerCAmelCase )
# 2 is for "[CLS]", 3 is for "[SEP]"
assert encoded_sentence == [2] + text + [3]
assert encoded_pair == [2] + text + [3] + text_a + [3]
@custom_tokenizers
class a ( unittest.TestCase ):
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Any = '''cl-tohoku/bert-base-japanese'''
__SCREAMING_SNAKE_CASE: Dict = AutoTokenizer.from_pretrained(_lowerCAmelCase )
self.assertIsInstance(_lowerCAmelCase , _lowerCAmelCase )
class a ( unittest.TestCase ):
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Tuple = '''cl-tohoku/bert-base-japanese'''
with self.assertLogs('''transformers''' , level='''WARNING''' ) as cm:
BertTokenizer.from_pretrained(_lowerCAmelCase )
self.assertTrue(
cm.records[0].message.startswith(
'''The tokenizer class you load from this checkpoint is not the same type as the class this function'''
''' is called from.''' ) )
__SCREAMING_SNAKE_CASE: str = '''bert-base-cased'''
with self.assertLogs('''transformers''' , level='''WARNING''' ) as cm:
BertJapaneseTokenizer.from_pretrained(_lowerCAmelCase )
self.assertTrue(
cm.records[0].message.startswith(
'''The tokenizer class you load from this checkpoint is not the same type as the class this function'''
''' is called from.''' ) )
| 202 |
import gc
import unittest
import numpy as np
import torch
from torch.backends.cuda import sdp_kernel
from diffusers import (
CMStochasticIterativeScheduler,
ConsistencyModelPipeline,
UNetaDModel,
)
from diffusers.utils import randn_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu
from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
enable_full_determinism()
class a ( __lowercase ,unittest.TestCase ):
SCREAMING_SNAKE_CASE__ : List[Any] = ConsistencyModelPipeline
SCREAMING_SNAKE_CASE__ : Any = UNCONDITIONAL_IMAGE_GENERATION_PARAMS
SCREAMING_SNAKE_CASE__ : str = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS
# Override required_optional_params to remove num_images_per_prompt
SCREAMING_SNAKE_CASE__ : Optional[int] = frozenset(
[
'''num_inference_steps''',
'''generator''',
'''latents''',
'''output_type''',
'''return_dict''',
'''callback''',
'''callback_steps''',
] )
@property
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: int = UNetaDModel.from_pretrained(
'''diffusers/consistency-models-test''' , subfolder='''test_unet''' , )
return unet
@property
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: List[Any] = UNetaDModel.from_pretrained(
'''diffusers/consistency-models-test''' , subfolder='''test_unet_class_cond''' , )
return unet
def snake_case_ ( self , _lowerCAmelCase=False ):
"""simple docstring"""
if class_cond:
__SCREAMING_SNAKE_CASE: List[Any] = self.dummy_cond_unet
else:
__SCREAMING_SNAKE_CASE: Tuple = self.dummy_uncond_unet
# Default to CM multistep sampler
__SCREAMING_SNAKE_CASE: Tuple = CMStochasticIterativeScheduler(
num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , )
__SCREAMING_SNAKE_CASE: List[str] = {
'''unet''': unet,
'''scheduler''': scheduler,
}
return components
def snake_case_ ( self , _lowerCAmelCase , _lowerCAmelCase=0 ):
"""simple docstring"""
if str(_lowerCAmelCase ).startswith('''mps''' ):
__SCREAMING_SNAKE_CASE: List[str] = torch.manual_seed(_lowerCAmelCase )
else:
__SCREAMING_SNAKE_CASE: List[str] = torch.Generator(device=_lowerCAmelCase ).manual_seed(_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: Union[str, Any] = {
'''batch_size''': 1,
'''num_inference_steps''': None,
'''timesteps''': [22, 0],
'''generator''': generator,
'''output_type''': '''np''',
}
return inputs
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Dict = '''cpu''' # ensure determinism for the device-dependent torch.Generator
__SCREAMING_SNAKE_CASE: Optional[int] = self.get_dummy_components()
__SCREAMING_SNAKE_CASE: Optional[Any] = ConsistencyModelPipeline(**_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: Any = pipe.to(_lowerCAmelCase )
pipe.set_progress_bar_config(disable=_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: Optional[int] = self.get_dummy_inputs(_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: Any = pipe(**_lowerCAmelCase ).images
assert image.shape == (1, 32, 32, 3)
__SCREAMING_SNAKE_CASE: int = image[0, -3:, -3:, -1]
__SCREAMING_SNAKE_CASE: Optional[Any] = np.array([0.3572, 0.6273, 0.4031, 0.3961, 0.4321, 0.5730, 0.5266, 0.4780, 0.5004] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Dict = '''cpu''' # ensure determinism for the device-dependent torch.Generator
__SCREAMING_SNAKE_CASE: str = self.get_dummy_components(class_cond=_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: Any = ConsistencyModelPipeline(**_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: Any = pipe.to(_lowerCAmelCase )
pipe.set_progress_bar_config(disable=_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: Dict = self.get_dummy_inputs(_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: Dict = 0
__SCREAMING_SNAKE_CASE: Optional[Any] = pipe(**_lowerCAmelCase ).images
assert image.shape == (1, 32, 32, 3)
__SCREAMING_SNAKE_CASE: Optional[Any] = image[0, -3:, -3:, -1]
__SCREAMING_SNAKE_CASE: Optional[Any] = np.array([0.3572, 0.6273, 0.4031, 0.3961, 0.4321, 0.5730, 0.5266, 0.4780, 0.5004] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Optional[int] = '''cpu''' # ensure determinism for the device-dependent torch.Generator
__SCREAMING_SNAKE_CASE: Union[str, Any] = self.get_dummy_components()
__SCREAMING_SNAKE_CASE: Tuple = ConsistencyModelPipeline(**_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: List[str] = pipe.to(_lowerCAmelCase )
pipe.set_progress_bar_config(disable=_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: List[Any] = self.get_dummy_inputs(_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: int = 1
__SCREAMING_SNAKE_CASE: Union[str, Any] = None
__SCREAMING_SNAKE_CASE: List[str] = pipe(**_lowerCAmelCase ).images
assert image.shape == (1, 32, 32, 3)
__SCREAMING_SNAKE_CASE: Tuple = image[0, -3:, -3:, -1]
__SCREAMING_SNAKE_CASE: Optional[Any] = np.array([0.5004, 0.5004, 0.4994, 0.5008, 0.4976, 0.5018, 0.4990, 0.4982, 0.4987] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: int = '''cpu''' # ensure determinism for the device-dependent torch.Generator
__SCREAMING_SNAKE_CASE: Optional[Any] = self.get_dummy_components(class_cond=_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: List[Any] = ConsistencyModelPipeline(**_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: List[Any] = pipe.to(_lowerCAmelCase )
pipe.set_progress_bar_config(disable=_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: Tuple = self.get_dummy_inputs(_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: Any = 1
__SCREAMING_SNAKE_CASE: List[Any] = None
__SCREAMING_SNAKE_CASE: Tuple = 0
__SCREAMING_SNAKE_CASE: List[str] = pipe(**_lowerCAmelCase ).images
assert image.shape == (1, 32, 32, 3)
__SCREAMING_SNAKE_CASE: List[Any] = image[0, -3:, -3:, -1]
__SCREAMING_SNAKE_CASE: Any = np.array([0.5004, 0.5004, 0.4994, 0.5008, 0.4976, 0.5018, 0.4990, 0.4982, 0.4987] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
@slow
@require_torch_gpu
class a ( unittest.TestCase ):
def snake_case_ ( self ):
"""simple docstring"""
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def snake_case_ ( self , _lowerCAmelCase=0 , _lowerCAmelCase=False , _lowerCAmelCase="cpu" , _lowerCAmelCase=torch.floataa , _lowerCAmelCase=(1, 3, 64, 64) ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: str = torch.manual_seed(_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: Dict = {
'''num_inference_steps''': None,
'''timesteps''': [22, 0],
'''class_labels''': 0,
'''generator''': generator,
'''output_type''': '''np''',
}
if get_fixed_latents:
__SCREAMING_SNAKE_CASE: Dict = self.get_fixed_latents(seed=_lowerCAmelCase , device=_lowerCAmelCase , dtype=_lowerCAmelCase , shape=_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: Union[str, Any] = latents
return inputs
def snake_case_ ( self , _lowerCAmelCase=0 , _lowerCAmelCase="cpu" , _lowerCAmelCase=torch.floataa , _lowerCAmelCase=(1, 3, 64, 64) ):
"""simple docstring"""
if type(_lowerCAmelCase ) == str:
__SCREAMING_SNAKE_CASE: List[Any] = torch.device(_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: Dict = torch.Generator(device=_lowerCAmelCase ).manual_seed(_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: int = randn_tensor(_lowerCAmelCase , generator=_lowerCAmelCase , device=_lowerCAmelCase , dtype=_lowerCAmelCase )
return latents
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Union[str, Any] = UNetaDModel.from_pretrained('''diffusers/consistency_models''' , subfolder='''diffusers_cd_imagenet64_l2''' )
__SCREAMING_SNAKE_CASE: Union[str, Any] = CMStochasticIterativeScheduler(
num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , )
__SCREAMING_SNAKE_CASE: Optional[int] = ConsistencyModelPipeline(unet=_lowerCAmelCase , scheduler=_lowerCAmelCase )
pipe.to(torch_device=_lowerCAmelCase )
pipe.set_progress_bar_config(disable=_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: int = self.get_inputs()
__SCREAMING_SNAKE_CASE: List[Any] = pipe(**_lowerCAmelCase ).images
assert image.shape == (1, 64, 64, 3)
__SCREAMING_SNAKE_CASE: Dict = image[0, -3:, -3:, -1]
__SCREAMING_SNAKE_CASE: Any = np.array([0.0888, 0.0881, 0.0666, 0.0479, 0.0292, 0.0195, 0.0201, 0.0163, 0.0254] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: List[Any] = UNetaDModel.from_pretrained('''diffusers/consistency_models''' , subfolder='''diffusers_cd_imagenet64_l2''' )
__SCREAMING_SNAKE_CASE: str = CMStochasticIterativeScheduler(
num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , )
__SCREAMING_SNAKE_CASE: Union[str, Any] = ConsistencyModelPipeline(unet=_lowerCAmelCase , scheduler=_lowerCAmelCase )
pipe.to(torch_device=_lowerCAmelCase )
pipe.set_progress_bar_config(disable=_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: List[str] = self.get_inputs()
__SCREAMING_SNAKE_CASE: Union[str, Any] = 1
__SCREAMING_SNAKE_CASE: List[Any] = None
__SCREAMING_SNAKE_CASE: Optional[int] = pipe(**_lowerCAmelCase ).images
assert image.shape == (1, 64, 64, 3)
__SCREAMING_SNAKE_CASE: Dict = image[0, -3:, -3:, -1]
__SCREAMING_SNAKE_CASE: Any = np.array([0.0340, 0.0152, 0.0063, 0.0267, 0.0221, 0.0107, 0.0416, 0.0186, 0.0217] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
@require_torch_a
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Tuple = UNetaDModel.from_pretrained('''diffusers/consistency_models''' , subfolder='''diffusers_cd_imagenet64_l2''' )
__SCREAMING_SNAKE_CASE: Union[str, Any] = CMStochasticIterativeScheduler(
num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , )
__SCREAMING_SNAKE_CASE: List[Any] = ConsistencyModelPipeline(unet=_lowerCAmelCase , scheduler=_lowerCAmelCase )
pipe.to(torch_device=_lowerCAmelCase , torch_dtype=torch.floataa )
pipe.set_progress_bar_config(disable=_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: int = self.get_inputs(get_fixed_latents=_lowerCAmelCase , device=_lowerCAmelCase )
# Ensure usage of flash attention in torch 2.0
with sdp_kernel(enable_flash=_lowerCAmelCase , enable_math=_lowerCAmelCase , enable_mem_efficient=_lowerCAmelCase ):
__SCREAMING_SNAKE_CASE: Dict = pipe(**_lowerCAmelCase ).images
assert image.shape == (1, 64, 64, 3)
__SCREAMING_SNAKE_CASE: List[Any] = image[0, -3:, -3:, -1]
__SCREAMING_SNAKE_CASE: Optional[int] = np.array([0.1875, 0.1428, 0.1289, 0.2151, 0.2092, 0.1477, 0.1877, 0.1641, 0.1353] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
@require_torch_a
def snake_case_ ( self ):
"""simple docstring"""
__SCREAMING_SNAKE_CASE: Optional[Any] = UNetaDModel.from_pretrained('''diffusers/consistency_models''' , subfolder='''diffusers_cd_imagenet64_l2''' )
__SCREAMING_SNAKE_CASE: List[str] = CMStochasticIterativeScheduler(
num_train_timesteps=40 , sigma_min=0.002 , sigma_max=80.0 , )
__SCREAMING_SNAKE_CASE: List[Any] = ConsistencyModelPipeline(unet=_lowerCAmelCase , scheduler=_lowerCAmelCase )
pipe.to(torch_device=_lowerCAmelCase , torch_dtype=torch.floataa )
pipe.set_progress_bar_config(disable=_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: int = self.get_inputs(get_fixed_latents=_lowerCAmelCase , device=_lowerCAmelCase )
__SCREAMING_SNAKE_CASE: Union[str, Any] = 1
__SCREAMING_SNAKE_CASE: List[Any] = None
# Ensure usage of flash attention in torch 2.0
with sdp_kernel(enable_flash=_lowerCAmelCase , enable_math=_lowerCAmelCase , enable_mem_efficient=_lowerCAmelCase ):
__SCREAMING_SNAKE_CASE: Optional[int] = pipe(**_lowerCAmelCase ).images
assert image.shape == (1, 64, 64, 3)
__SCREAMING_SNAKE_CASE: Tuple = image[0, -3:, -3:, -1]
__SCREAMING_SNAKE_CASE: Tuple = np.array([0.1663, 0.1948, 0.2275, 0.1680, 0.1204, 0.1245, 0.1858, 0.1338, 0.2095] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3
| 202 | 1 |
import multiprocessing
from typing import TYPE_CHECKING, Optional, Union
from .. import Dataset, Features, config
from ..formatting import query_table
from ..packaged_modules.sql.sql import Sql
from ..utils import logging
from .abc import AbstractDatasetInputStream
if TYPE_CHECKING:
import sqlitea
import sqlalchemy
class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__):
def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False , **_SCREAMING_SNAKE_CASE , )-> List[Any]:
super().__init__(features=_SCREAMING_SNAKE_CASE , cache_dir=_SCREAMING_SNAKE_CASE , keep_in_memory=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
lowerCamelCase_ =Sql(
cache_dir=_SCREAMING_SNAKE_CASE , features=_SCREAMING_SNAKE_CASE , sql=_SCREAMING_SNAKE_CASE , con=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , )
def _snake_case ( self )-> Optional[Any]:
lowerCamelCase_ =None
lowerCamelCase_ =None
lowerCamelCase_ =None
lowerCamelCase_ =None
self.builder.download_and_prepare(
download_config=_SCREAMING_SNAKE_CASE , download_mode=_SCREAMING_SNAKE_CASE , verification_mode=_SCREAMING_SNAKE_CASE , base_path=_SCREAMING_SNAKE_CASE , )
# Build dataset for splits
lowerCamelCase_ =self.builder.as_dataset(
split="""train""" , verification_mode=_SCREAMING_SNAKE_CASE , in_memory=self.keep_in_memory )
return dataset
class _SCREAMING_SNAKE_CASE :
def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , **_SCREAMING_SNAKE_CASE , )-> List[Any]:
if num_proc is not None and num_proc <= 0:
raise ValueError(f'num_proc {num_proc} must be an integer > 0.' )
lowerCamelCase_ =dataset
lowerCamelCase_ =name
lowerCamelCase_ =con
lowerCamelCase_ =batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE
lowerCamelCase_ =num_proc
lowerCamelCase_ =to_sql_kwargs
def _snake_case ( self )-> int:
lowerCamelCase_ =self.to_sql_kwargs.pop("""sql""" , _SCREAMING_SNAKE_CASE )
lowerCamelCase_ =self.to_sql_kwargs.pop("""con""" , _SCREAMING_SNAKE_CASE )
lowerCamelCase_ =self.to_sql_kwargs.pop("""index""" , _SCREAMING_SNAKE_CASE )
lowerCamelCase_ =self._write(index=_SCREAMING_SNAKE_CASE , **self.to_sql_kwargs )
return written
def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Optional[int]:
lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ =args
lowerCamelCase_ ={**to_sql_kwargs, """if_exists""": """append"""} if offset > 0 else to_sql_kwargs
lowerCamelCase_ =query_table(
table=self.dataset.data , key=slice(_SCREAMING_SNAKE_CASE , offset + self.batch_size ) , indices=self.dataset._indices , )
lowerCamelCase_ =batch.to_pandas()
lowerCamelCase_ =df.to_sql(self.name , self.con , index=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
return num_rows or len(_SCREAMING_SNAKE_CASE )
def _snake_case ( self , _SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )-> int:
lowerCamelCase_ =0
if self.num_proc is None or self.num_proc == 1:
for offset in logging.tqdm(
range(0 , len(self.dataset ) , self.batch_size ) , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ):
written += self._batch_sql((offset, index, to_sql_kwargs) )
else:
lowerCamelCase_ , lowerCamelCase_ =len(self.dataset ), self.batch_size
with multiprocessing.Pool(self.num_proc ) as pool:
for num_rows in logging.tqdm(
pool.imap(
self._batch_sql , [(offset, index, to_sql_kwargs) for offset in range(0 , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )] , ) , total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size , unit="""ba""" , disable=not logging.is_progress_bar_enabled() , desc="""Creating SQL from Arrow format""" , ):
written += num_rows
return written
| 75 |
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 : Tuple = logging.get_logger(__name__)
__A : str = {'vocab_file': 'sentencepiece.model'}
__A : Optional[Any] = {
'vocab_file': {
'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model',
},
}
__A : int = {
'google/rembert': 2_56,
}
class _SCREAMING_SNAKE_CASE ( lowerCAmelCase__):
_UpperCamelCase:List[Any] = VOCAB_FILES_NAMES
_UpperCamelCase:Any = PRETRAINED_VOCAB_FILES_MAP
_UpperCamelCase:Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="[CLS]" , _SCREAMING_SNAKE_CASE="[SEP]" , _SCREAMING_SNAKE_CASE="[UNK]" , _SCREAMING_SNAKE_CASE="[SEP]" , _SCREAMING_SNAKE_CASE="[PAD]" , _SCREAMING_SNAKE_CASE="[CLS]" , _SCREAMING_SNAKE_CASE="[MASK]" , **_SCREAMING_SNAKE_CASE , )-> str:
super().__init__(
do_lower_case=_SCREAMING_SNAKE_CASE , remove_space=_SCREAMING_SNAKE_CASE , keep_accents=_SCREAMING_SNAKE_CASE , bos_token=_SCREAMING_SNAKE_CASE , eos_token=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , sep_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , cls_token=_SCREAMING_SNAKE_CASE , mask_token=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , )
lowerCamelCase_ =do_lower_case
lowerCamelCase_ =remove_space
lowerCamelCase_ =keep_accents
lowerCamelCase_ =vocab_file
lowerCamelCase_ =spm.SentencePieceProcessor()
self.sp_model.Load(_SCREAMING_SNAKE_CASE )
@property
def _snake_case ( self )-> Dict:
return len(self.sp_model )
def _snake_case ( self )-> Optional[int]:
lowerCamelCase_ ={self.convert_ids_to_tokens(_SCREAMING_SNAKE_CASE ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def __getstate__( self )-> Optional[Any]:
lowerCamelCase_ =self.__dict__.copy()
lowerCamelCase_ =None
return state
def __setstate__( self , _SCREAMING_SNAKE_CASE )-> Optional[Any]:
lowerCamelCase_ =d
lowerCamelCase_ =spm.SentencePieceProcessor()
self.sp_model.Load(self.vocab_file )
def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False )-> Union[str, Any]:
lowerCamelCase_ =self.sp_model.EncodeAsPieces(_SCREAMING_SNAKE_CASE )
return pieces
def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Optional[int]:
return self.sp_model.PieceToId(_SCREAMING_SNAKE_CASE )
def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> Union[str, Any]:
return self.sp_model.IdToPiece(_SCREAMING_SNAKE_CASE )
def _snake_case ( self , _SCREAMING_SNAKE_CASE )-> List[str]:
lowerCamelCase_ =self.sp_model.decode_pieces(_SCREAMING_SNAKE_CASE )
return out_string
def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> List[int]:
lowerCamelCase_ =[self.sep_token_id]
lowerCamelCase_ =[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 _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False )-> List[int]:
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(_SCREAMING_SNAKE_CASE )) + [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1]
return [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1]
def _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> List[int]:
lowerCamelCase_ =[self.sep_token_id]
lowerCamelCase_ =[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 _snake_case ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None )-> Tuple[str]:
if not os.path.isdir(_SCREAMING_SNAKE_CASE ):
logger.error("""Vocabulary path ({}) should be a directory""".format(_SCREAMING_SNAKE_CASE ) )
return
lowerCamelCase_ =os.path.join(
_SCREAMING_SNAKE_CASE , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(_SCREAMING_SNAKE_CASE ):
copyfile(self.vocab_file , _SCREAMING_SNAKE_CASE )
return (out_vocab_file,)
| 75 | 1 |
"""simple docstring"""
import warnings
from typing import List, Optional, Union
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class a ( lowerCamelCase_ ):
snake_case__ = ['''image_processor''', '''tokenizer''']
snake_case__ = '''LayoutLMv3ImageProcessor'''
snake_case__ = ('''LayoutLMv3Tokenizer''', '''LayoutLMv3TokenizerFast''')
def __init__( self , _snake_case=None , _snake_case=None , **_snake_case ):
"""simple docstring"""
lowerCAmelCase = None
if "feature_extractor" in kwargs:
warnings.warn(
'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'
' instead.' , _snake_case , )
lowerCAmelCase = kwargs.pop('feature_extractor' )
lowerCAmelCase = 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__(_snake_case , _snake_case )
def __call__( self , _snake_case , _snake_case = None , _snake_case = None , _snake_case = None , _snake_case = None , _snake_case = True , _snake_case = False , _snake_case = None , _snake_case = None , _snake_case = 0 , _snake_case = None , _snake_case = None , _snake_case = None , _snake_case = False , _snake_case = False , _snake_case = False , _snake_case = False , _snake_case = True , _snake_case = None , **_snake_case , ):
"""simple docstring"""
if self.image_processor.apply_ocr and (boxes is not None):
raise ValueError(
'You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True.' )
if self.image_processor.apply_ocr and (word_labels is not None):
raise ValueError(
'You cannot provide word labels if you initialized the image processor with apply_ocr set to True.' )
# first, apply the image processor
lowerCAmelCase = self.image_processor(images=_snake_case , return_tensors=_snake_case )
# second, apply the tokenizer
if text is not None and self.image_processor.apply_ocr and text_pair is None:
if isinstance(_snake_case , _snake_case ):
lowerCAmelCase = [text] # add batch dimension (as the image processor always adds a batch dimension)
lowerCAmelCase = features["words"]
lowerCAmelCase = self.tokenizer(
text=text if text is not None else features['words'] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['boxes'] , word_labels=_snake_case , add_special_tokens=_snake_case , padding=_snake_case , truncation=_snake_case , max_length=_snake_case , stride=_snake_case , pad_to_multiple_of=_snake_case , return_token_type_ids=_snake_case , return_attention_mask=_snake_case , return_overflowing_tokens=_snake_case , return_special_tokens_mask=_snake_case , return_offsets_mapping=_snake_case , return_length=_snake_case , verbose=_snake_case , return_tensors=_snake_case , **_snake_case , )
# add pixel values
lowerCAmelCase = features.pop('pixel_values' )
if return_overflowing_tokens is True:
lowerCAmelCase = self.get_overflowing_images(_snake_case , encoded_inputs['overflow_to_sample_mapping'] )
lowerCAmelCase = images
return encoded_inputs
def UpperCamelCase__ ( self , _snake_case , _snake_case ):
"""simple docstring"""
lowerCAmelCase = []
for sample_idx in overflow_to_sample_mapping:
images_with_overflow.append(images[sample_idx] )
if len(_snake_case ) != len(_snake_case ):
raise ValueError(
'Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got'
F' {len(_snake_case )} and {len(_snake_case )}' )
return images_with_overflow
def UpperCamelCase__ ( self , *_snake_case , **_snake_case ):
"""simple docstring"""
return self.tokenizer.batch_decode(*_snake_case , **_snake_case )
def UpperCamelCase__ ( self , *_snake_case , **_snake_case ):
"""simple docstring"""
return self.tokenizer.decode(*_snake_case , **_snake_case )
@property
def UpperCamelCase__ ( self ):
"""simple docstring"""
return ["input_ids", "bbox", "attention_mask", "pixel_values"]
@property
def UpperCamelCase__ ( self ):
"""simple docstring"""
warnings.warn(
'`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , _snake_case , )
return self.image_processor_class
@property
def UpperCamelCase__ ( self ):
"""simple docstring"""
warnings.warn(
'`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , _snake_case , )
return self.image_processor
| 4 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
lowerCAmelCase_ = {
'configuration_nezha': ['NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'NezhaConfig'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowerCAmelCase_ = [
'NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST',
'NezhaForNextSentencePrediction',
'NezhaForMaskedLM',
'NezhaForPreTraining',
'NezhaForMultipleChoice',
'NezhaForQuestionAnswering',
'NezhaForSequenceClassification',
'NezhaForTokenClassification',
'NezhaModel',
'NezhaPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_nezha import NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP, NezhaConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_nezha import (
NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST,
NezhaForMaskedLM,
NezhaForMultipleChoice,
NezhaForNextSentencePrediction,
NezhaForPreTraining,
NezhaForQuestionAnswering,
NezhaForSequenceClassification,
NezhaForTokenClassification,
NezhaModel,
NezhaPreTrainedModel,
)
else:
import sys
lowerCAmelCase_ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 173 | 0 |
def lowerCAmelCase ( _lowerCAmelCase : int = 100_0000 ):
"""simple docstring"""
UpperCAmelCase__ = limit + 1
UpperCAmelCase__ = [0] * limit
for first_term in range(1 , _lowerCamelCase ):
for n in range(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ):
UpperCAmelCase__ = first_term + n / first_term
if common_difference % 4: # d must be divisble by 4
continue
else:
common_difference /= 4
if (
first_term > common_difference
and first_term < 4 * common_difference
): # since x,y,z are positive integers
frequency[n] += 1 # so z>0 and a>d ,also 4d<a
UpperCAmelCase__ = sum(1 for x in frequency[1:limit] if x == 10 )
return count
if __name__ == "__main__":
print(F'''{solution() = }''')
| 700 |
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 :Any , lowerCamelCase :List[str] , lowerCamelCase :Optional[int]=13 , lowerCamelCase :Optional[Any]=2 , lowerCamelCase :Any=24 , lowerCamelCase :Union[str, Any]=16 , lowerCamelCase :Any=True , lowerCamelCase :int=True , lowerCamelCase :Optional[Any]=32 , lowerCamelCase :Union[str, Any]=5 , lowerCamelCase :Tuple=4 , lowerCamelCase :Optional[Any]=37 , lowerCamelCase :Optional[Any]="gelu" , lowerCamelCase :int=0.1 , lowerCamelCase :Tuple=0.1 , lowerCamelCase :List[str]=10 , lowerCamelCase :Optional[Any]=0.02 , lowerCamelCase :Optional[int]=None , lowerCamelCase :Optional[Any]=2 , lowerCamelCase :List[Any]=2 , ) -> Union[str, Any]:
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 :int ) -> List[str]:
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 :List[Any] ) -> Any:
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=lowerCamelCase , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , )
def UpperCAmelCase_ ( self :List[str] , lowerCamelCase :List[str] , lowerCamelCase :List[str] , lowerCamelCase :List[str] ) -> Optional[Any]:
UpperCAmelCase__ = ASTModel(config=lowerCamelCase )
model.to(lowerCamelCase )
model.eval()
UpperCAmelCase__ = model(lowerCamelCase )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def UpperCAmelCase_ ( self :List[Any] ) -> str:
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 ):
UpperCAmelCase_ = (
(
ASTModel,
ASTForAudioClassification,
)
if is_torch_available()
else ()
)
UpperCAmelCase_ = (
{"""audio-classification""": ASTForAudioClassification, """feature-extraction""": ASTModel}
if is_torch_available()
else {}
)
UpperCAmelCase_ = False
UpperCAmelCase_ = False
UpperCAmelCase_ = False
UpperCAmelCase_ = False
def UpperCAmelCase_ ( self :List[str] , lowerCamelCase :Optional[int] , lowerCamelCase :List[Any] , lowerCamelCase :str , lowerCamelCase :List[Any] , lowerCamelCase :int ) -> str:
if pipeline_test_casse_name == "AudioClassificationPipelineTests":
return True
return False
def UpperCAmelCase_ ( self :List[str] ) -> int:
UpperCAmelCase__ = ASTModelTester(self )
UpperCAmelCase__ = ConfigTester(self , config_class=lowerCamelCase , has_text_modality=lowerCamelCase , hidden_size=37 )
def UpperCAmelCase_ ( self :Tuple ) -> str:
self.config_tester.run_common_tests()
@unittest.skip(reason="AST does not use inputs_embeds" )
def UpperCAmelCase_ ( self :List[str] ) -> Optional[Any]:
pass
def UpperCAmelCase_ ( self :Optional[int] ) -> Any:
UpperCAmelCase__ , UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCAmelCase__ = model_class(lowerCamelCase )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
UpperCAmelCase__ = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(lowerCamelCase , nn.Linear ) )
def UpperCAmelCase_ ( self :Tuple ) -> List[str]:
UpperCAmelCase__ , UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCAmelCase__ = model_class(lowerCamelCase )
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] , lowerCamelCase )
def UpperCAmelCase_ ( self :int ) -> Any:
UpperCAmelCase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowerCamelCase )
@slow
def UpperCAmelCase_ ( self :int ) -> Optional[Any]:
for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
UpperCAmelCase__ = ASTModel.from_pretrained(lowerCamelCase )
self.assertIsNotNone(lowerCamelCase )
def lowerCAmelCase ( ):
"""simple docstring"""
UpperCAmelCase__ = hf_hub_download(
repo_id="nielsr/audio-spectogram-transformer-checkpoint" , filename="sample_audio.flac" , repo_type="dataset" )
UpperCAmelCase__ , UpperCAmelCase__ = torchaudio.load(_lowerCAmelCase )
return audio, sampling_rate
@require_torch
@require_torchaudio
class _UpperCamelCase ( unittest.TestCase ):
@cached_property
def UpperCAmelCase_ ( self :str ) -> Dict:
return (
ASTFeatureExtractor.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593" )
if is_torchaudio_available()
else None
)
@slow
def UpperCAmelCase_ ( self :str ) -> Optional[int]:
UpperCAmelCase__ = self.default_feature_extractor
UpperCAmelCase__ = ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593" ).to(lowerCamelCase )
UpperCAmelCase__ = self.default_feature_extractor
UpperCAmelCase__ , UpperCAmelCase__ = prepare_audio()
UpperCAmelCase__ = audio.squeeze().numpy()
UpperCAmelCase__ = feature_extractor(lowerCamelCase , sampling_rate=lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase )
# forward pass
with torch.no_grad():
UpperCAmelCase__ = model(**lowerCamelCase )
# verify the logits
UpperCAmelCase__ = torch.Size((1, 527) )
self.assertEqual(outputs.logits.shape , lowerCamelCase )
UpperCAmelCase__ = torch.tensor([-0.87_60, -7.00_42, -8.66_02] ).to(lowerCamelCase )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCamelCase , atol=1e-4 ) )
| 364 | 0 |
"""simple docstring"""
def _lowerCAmelCase(a : List[str] ) -> str:
_SCREAMING_SNAKE_CASE =len(a_ )
_SCREAMING_SNAKE_CASE =sum(a_ )
_SCREAMING_SNAKE_CASE =[[False for x in range(s + 1 )] for y in range(n + 1 )]
for i in range(1 , n + 1 ):
_SCREAMING_SNAKE_CASE =True
for i in range(1 , s + 1 ):
_SCREAMING_SNAKE_CASE =False
for i in range(1 , n + 1 ):
for j in range(1 , s + 1 ):
_SCREAMING_SNAKE_CASE =dp[i][j - 1]
if arr[i - 1] <= j:
_SCREAMING_SNAKE_CASE =dp[i][j] or dp[i - 1][j - arr[i - 1]]
for j in range(int(s / 2 ) , -1 , -1 ):
if dp[n][j] is True:
_SCREAMING_SNAKE_CASE =s - 2 * j
break
return diff
| 255 |
from __future__ import annotations
import inspect
import unittest
from math import floor
import numpy as np
from transformers import CvtConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import TFCvtForImageClassification, TFCvtModel
from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import AutoImageProcessor
class UpperCamelCase_ ( snake_case_ ):
'''simple docstring'''
def _UpperCamelCase ( self ) -> Any:
snake_case_ = self.config_class(**self.inputs_dict )
self.parent.assertTrue(hasattr(a , 'embed_dim' ) )
self.parent.assertTrue(hasattr(a , 'num_heads' ) )
class UpperCamelCase_ :
'''simple docstring'''
def __init__( self , a , a=13 , a=64 , a=3 , a=[16, 48, 96] , a=[1, 3, 6] , a=[1, 2, 10] , a=[7, 3, 3] , a=[4, 2, 2] , a=[2, 1, 1] , a=[2, 2, 2] , a=[False, False, True] , a=[0.0, 0.0, 0.0] , a=0.02 , a=1E-12 , a=True , a=True , a=2 , ) -> List[Any]:
snake_case_ = parent
snake_case_ = batch_size
snake_case_ = image_size
snake_case_ = patch_sizes
snake_case_ = patch_stride
snake_case_ = patch_padding
snake_case_ = is_training
snake_case_ = use_labels
snake_case_ = num_labels
snake_case_ = num_channels
snake_case_ = embed_dim
snake_case_ = num_heads
snake_case_ = stride_kv
snake_case_ = depth
snake_case_ = cls_token
snake_case_ = attention_drop_rate
snake_case_ = initializer_range
snake_case_ = layer_norm_eps
def _UpperCamelCase ( self ) -> Dict:
snake_case_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
snake_case_ = None
if self.use_labels:
# create a random int32 tensor of given shape
snake_case_ = ids_tensor([self.batch_size] , self.num_labels )
snake_case_ = self.get_config()
return config, pixel_values, labels
def _UpperCamelCase ( self ) -> Dict:
return CvtConfig(
image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , )
def _UpperCamelCase ( self , a , a , a ) -> int:
snake_case_ = TFCvtModel(config=a )
snake_case_ = model(a , training=a )
snake_case_ = (self.image_size, self.image_size)
snake_case_ , snake_case_ = image_size[0], image_size[1]
for i in range(len(self.depth ) ):
snake_case_ = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 )
snake_case_ = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) )
def _UpperCamelCase ( self , a , a , a ) -> Dict:
snake_case_ = self.num_labels
snake_case_ = TFCvtForImageClassification(a )
snake_case_ = model(a , labels=a , training=a )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def _UpperCamelCase ( self ) -> Tuple:
snake_case_ = self.prepare_config_and_inputs()
snake_case_ , snake_case_ , snake_case_ = config_and_inputs
snake_case_ = {'pixel_values': pixel_values}
return config, inputs_dict
@require_tf
class UpperCamelCase_ ( snake_case_ , snake_case_ , unittest.TestCase ):
'''simple docstring'''
lowerCAmelCase = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else ()
lowerCAmelCase = (
{'''feature-extraction''': TFCvtModel, '''image-classification''': TFCvtForImageClassification}
if is_tf_available()
else {}
)
lowerCAmelCase = False
lowerCAmelCase = False
lowerCAmelCase = False
lowerCAmelCase = False
lowerCAmelCase = False
def _UpperCamelCase ( self ) -> Optional[int]:
snake_case_ = TFCvtModelTester(self )
snake_case_ = TFCvtConfigTester(self , config_class=a , has_text_modality=a , hidden_size=37 )
def _UpperCamelCase ( self ) -> Optional[int]:
self.config_tester.create_and_test_config_common_properties()
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_with_num_labels()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
@unittest.skip(reason='Cvt does not output attentions' )
def _UpperCamelCase ( self ) -> Dict:
pass
@unittest.skip(reason='Cvt does not use inputs_embeds' )
def _UpperCamelCase ( self ) -> List[str]:
pass
@unittest.skip(reason='Cvt does not support input and output embeddings' )
def _UpperCamelCase ( self ) -> Optional[int]:
pass
@unittest.skipIf(
not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0 , reason='TF does not support backprop for grouped convolutions on CPU.' , )
def _UpperCamelCase ( self ) -> Dict:
super().test_dataset_conversion()
@unittest.skipIf(
not is_tf_available() or len(tf.config.list_physical_devices('GPU' ) ) == 0 , reason='TF does not support backprop for grouped convolutions on CPU.' , )
@slow
def _UpperCamelCase ( self ) -> Dict:
super().test_keras_fit()
@unittest.skip(reason='Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8' )
def _UpperCamelCase ( self ) -> List[str]:
snake_case_ = tf.keras.mixed_precision.Policy('mixed_float16' )
tf.keras.mixed_precision.set_global_policy(a )
super().test_keras_fit()
tf.keras.mixed_precision.set_global_policy('float32' )
def _UpperCamelCase ( self ) -> Optional[int]:
snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
snake_case_ = model_class(a )
snake_case_ = inspect.signature(model.call )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
snake_case_ = [*signature.parameters.keys()]
snake_case_ = ['pixel_values']
self.assertListEqual(arg_names[:1] , a )
def _UpperCamelCase ( self ) -> Optional[Any]:
def check_hidden_states_output(a , a , a ):
snake_case_ = model_class(a )
snake_case_ = model(**self._prepare_for_class(a , a ) )
snake_case_ = outputs.hidden_states
snake_case_ = len(self.model_tester.depth )
self.assertEqual(len(a ) , a )
# verify the first hidden states (first block)
self.assertListEqual(
list(hidden_states[0].shape[-3:] ) , [
self.model_tester.embed_dim[0],
self.model_tester.image_size // 4,
self.model_tester.image_size // 4,
] , )
snake_case_ , snake_case_ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
snake_case_ = True
check_hidden_states_output(a , a , a )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
snake_case_ = True
check_hidden_states_output(a , a , a )
def _UpperCamelCase ( self ) -> List[Any]:
snake_case_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*a )
def _UpperCamelCase ( self ) -> List[str]:
snake_case_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*a )
@slow
def _UpperCamelCase ( self ) -> int:
for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
snake_case_ = TFCvtModel.from_pretrained(a )
self.assertIsNotNone(a )
def __UpperCAmelCase ( ):
snake_case_ = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png')
return image
@require_tf
@require_vision
class UpperCamelCase_ ( unittest.TestCase ):
'''simple docstring'''
@cached_property
def _UpperCamelCase ( self ) -> Any:
return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] )
@slow
def _UpperCamelCase ( self ) -> Dict:
snake_case_ = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] )
snake_case_ = self.default_image_processor
snake_case_ = prepare_img()
snake_case_ = image_processor(images=a , return_tensors='tf' )
# forward pass
snake_case_ = model(**a )
# verify the logits
snake_case_ = tf.TensorShape((1, 10_00) )
self.assertEqual(outputs.logits.shape , a )
snake_case_ = tf.constant([0.9_285, 0.9_015, -0.3_150] )
self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , a , atol=1E-4 ) )
| 198 | 0 |
"""simple docstring"""
import gc
import random
import unittest
import numpy as np
import torch
from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel
from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import floats_tensor, load_image, load_numpy, slow
from diffusers.utils.testing_utils import require_torch_gpu, torch_device
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
class SCREAMING_SNAKE_CASE_ ( __lowercase , unittest.TestCase):
'''simple docstring'''
__magic_name__ : Any = ShapEImgaImgPipeline
__magic_name__ : Dict = ['''image''']
__magic_name__ : List[Any] = ['''image''']
__magic_name__ : Any = [
'''num_images_per_prompt''',
'''num_inference_steps''',
'''generator''',
'''latents''',
'''guidance_scale''',
'''frame_size''',
'''output_type''',
'''return_dict''',
]
__magic_name__ : List[str] = False
@property
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
return 32
@property
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
return 32
@property
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
return self.time_input_dim * 4
@property
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
return 8
@property
def UpperCAmelCase ( self) -> List[Any]:
'''simple docstring'''
torch.manual_seed(0)
snake_case__ : Tuple = CLIPVisionConfig(
hidden_size=self.text_embedder_hidden_size , image_size=64 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , )
snake_case__ : str = CLIPVisionModel(lowerCamelCase__)
return model
@property
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
snake_case__ : Any = CLIPImageProcessor(
crop_size=224 , do_center_crop=lowerCamelCase__ , do_normalize=lowerCamelCase__ , do_resize=lowerCamelCase__ , image_mean=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73] , image_std=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11] , resample=3 , size=224 , )
return image_processor
@property
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
torch.manual_seed(0)
snake_case__ : Tuple = {
"num_attention_heads": 2,
"attention_head_dim": 16,
"embedding_dim": self.time_input_dim,
"num_embeddings": 32,
"embedding_proj_dim": self.text_embedder_hidden_size,
"time_embed_dim": self.time_embed_dim,
"num_layers": 1,
"clip_embed_dim": self.time_input_dim * 2,
"additional_embeddings": 0,
"time_embed_act_fn": "gelu",
"norm_in_type": "layer",
"embedding_proj_norm_type": "layer",
"encoder_hid_proj_type": None,
"added_emb_type": None,
}
snake_case__ : Union[str, Any] = PriorTransformer(**lowerCamelCase__)
return model
@property
def UpperCAmelCase ( self) -> Tuple:
'''simple docstring'''
torch.manual_seed(0)
snake_case__ : Optional[Any] = {
"param_shapes": (
(self.renderer_dim, 93),
(self.renderer_dim, 8),
(self.renderer_dim, 8),
(self.renderer_dim, 8),
),
"d_latent": self.time_input_dim,
"d_hidden": self.renderer_dim,
"n_output": 12,
"background": (
0.1,
0.1,
0.1,
),
}
snake_case__ : Any = ShapERenderer(**lowerCamelCase__)
return model
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
snake_case__ : Optional[int] = self.dummy_prior
snake_case__ : Tuple = self.dummy_image_encoder
snake_case__ : List[str] = self.dummy_image_processor
snake_case__ : Optional[Any] = self.dummy_renderer
snake_case__ : str = HeunDiscreteScheduler(
beta_schedule="exp" , num_train_timesteps=1_024 , prediction_type="sample" , use_karras_sigmas=lowerCamelCase__ , clip_sample=lowerCamelCase__ , clip_sample_range=1.0 , )
snake_case__ : List[Any] = {
"prior": prior,
"image_encoder": image_encoder,
"image_processor": image_processor,
"renderer": renderer,
"scheduler": scheduler,
}
return components
def UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__=0) -> Optional[Any]:
'''simple docstring'''
snake_case__ : Any = floats_tensor((1, 3, 64, 64) , rng=random.Random(lowerCamelCase__)).to(lowerCamelCase__)
if str(lowerCamelCase__).startswith("mps"):
snake_case__ : str = torch.manual_seed(lowerCamelCase__)
else:
snake_case__ : str = torch.Generator(device=lowerCamelCase__).manual_seed(lowerCamelCase__)
snake_case__ : Any = {
"image": input_image,
"generator": generator,
"num_inference_steps": 1,
"frame_size": 32,
"output_type": "np",
}
return inputs
def UpperCAmelCase ( self) -> Optional[int]:
'''simple docstring'''
snake_case__ : str = "cpu"
snake_case__ : Optional[Any] = self.get_dummy_components()
snake_case__ : Union[str, Any] = self.pipeline_class(**lowerCamelCase__)
snake_case__ : List[Any] = pipe.to(lowerCamelCase__)
pipe.set_progress_bar_config(disable=lowerCamelCase__)
snake_case__ : List[str] = pipe(**self.get_dummy_inputs(lowerCamelCase__))
snake_case__ : int = output.images[0]
snake_case__ : List[str] = image[0, -3:, -3:, -1]
assert image.shape == (20, 32, 32, 3)
snake_case__ : Optional[int] = np.array(
[
0.00_03_92_16,
0.00_03_92_16,
0.00_03_92_16,
0.00_03_92_16,
0.00_03_92_16,
0.00_03_92_16,
0.00_03_92_16,
0.00_03_92_16,
0.00_03_92_16,
])
assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
def UpperCAmelCase ( self) -> Dict:
'''simple docstring'''
self._test_inference_batch_consistent(batch_sizes=[1, 2])
def UpperCAmelCase ( self) -> Union[str, Any]:
'''simple docstring'''
snake_case__ : List[Any] = torch_device == "cpu"
snake_case__ : Any = True
self._test_inference_batch_single_identical(
batch_size=2 , test_max_difference=lowerCamelCase__ , relax_max_difference=lowerCamelCase__ , )
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
snake_case__ : Dict = self.get_dummy_components()
snake_case__ : Optional[Any] = self.pipeline_class(**lowerCamelCase__)
snake_case__ : Any = pipe.to(lowerCamelCase__)
pipe.set_progress_bar_config(disable=lowerCamelCase__)
snake_case__ : Union[str, Any] = 1
snake_case__ : Optional[Any] = 2
snake_case__ : List[Any] = self.get_dummy_inputs(lowerCamelCase__)
for key in inputs.keys():
if key in self.batch_params:
snake_case__ : Any = batch_size * [inputs[key]]
snake_case__ : Any = pipe(**lowerCamelCase__ , num_images_per_prompt=lowerCamelCase__)[0]
assert images.shape[0] == batch_size * num_images_per_prompt
@slow
@require_torch_gpu
class SCREAMING_SNAKE_CASE_ ( unittest.TestCase):
'''simple docstring'''
def UpperCAmelCase ( self) -> Optional[Any]:
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def UpperCAmelCase ( self) -> Any:
'''simple docstring'''
snake_case__ : List[str] = load_image(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/shap_e/corgi.png")
snake_case__ : Dict = load_numpy(
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
"/shap_e/test_shap_e_img2img_out.npy")
snake_case__ : List[str] = ShapEImgaImgPipeline.from_pretrained("openai/shap-e-img2img")
snake_case__ : int = pipe.to(lowerCamelCase__)
pipe.set_progress_bar_config(disable=lowerCamelCase__)
snake_case__ : Tuple = torch.Generator(device=lowerCamelCase__).manual_seed(0)
snake_case__ : Union[str, Any] = pipe(
lowerCamelCase__ , generator=lowerCamelCase__ , guidance_scale=3.0 , num_inference_steps=64 , frame_size=64 , output_type="np" , ).images[0]
assert images.shape == (20, 64, 64, 3)
assert_mean_pixel_difference(lowerCamelCase__ , lowerCamelCase__)
| 706 |
"""simple docstring"""
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available
lowercase = {
"""configuration_audio_spectrogram_transformer""": [
"""AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""",
"""ASTConfig""",
]
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase = [
"""AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""ASTForAudioClassification""",
"""ASTModel""",
"""ASTPreTrainedModel""",
]
try:
if not is_speech_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase = ["""ASTFeatureExtractor"""]
if TYPE_CHECKING:
from .configuration_audio_spectrogram_transformer import (
AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
ASTConfig,
)
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_audio_spectrogram_transformer import (
AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
ASTForAudioClassification,
ASTModel,
ASTPreTrainedModel,
)
try:
if not is_speech_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor
else:
import sys
lowercase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 150 | 0 |
"""simple docstring"""
import pyarrow.parquet as pq
import pytest
from datasets import Audio, Dataset, DatasetDict, Features, NamedSplit, Sequence, Value, config
from datasets.features.image import Image
from datasets.io.parquet import ParquetDatasetReader, ParquetDatasetWriter, get_writer_batch_size
from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases
def SCREAMING_SNAKE_CASE ( __UpperCAmelCase , __UpperCAmelCase ) -> Optional[Any]:
assert isinstance(__snake_case , __snake_case )
assert dataset.num_rows == 4
assert dataset.num_columns == 3
assert dataset.column_names == ["col_1", "col_2", "col_3"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize("keep_in_memory" , [False, True] )
def SCREAMING_SNAKE_CASE ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Optional[Any]:
SCREAMING_SNAKE_CASE__ = tmp_path / "cache"
SCREAMING_SNAKE_CASE__ = {"col_1": "string", "col_2": "int64", "col_3": "float64"}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
SCREAMING_SNAKE_CASE__ = ParquetDatasetReader(__snake_case , cache_dir=__snake_case , keep_in_memory=__snake_case ).read()
_check_parquet_dataset(__snake_case , __snake_case )
@pytest.mark.parametrize(
"features" , [
None,
{"col_1": "string", "col_2": "int64", "col_3": "float64"},
{"col_1": "string", "col_2": "string", "col_3": "string"},
{"col_1": "int32", "col_2": "int32", "col_3": "int32"},
{"col_1": "float32", "col_2": "float32", "col_3": "float32"},
] , )
def SCREAMING_SNAKE_CASE ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Optional[int]:
SCREAMING_SNAKE_CASE__ = tmp_path / "cache"
SCREAMING_SNAKE_CASE__ = {"col_1": "string", "col_2": "int64", "col_3": "float64"}
SCREAMING_SNAKE_CASE__ = features.copy() if features else default_expected_features
SCREAMING_SNAKE_CASE__ = (
Features({feature: Value(__snake_case ) for feature, dtype in features.items()} ) if features is not None else None
)
SCREAMING_SNAKE_CASE__ = ParquetDatasetReader(__snake_case , features=__snake_case , cache_dir=__snake_case ).read()
_check_parquet_dataset(__snake_case , __snake_case )
@pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] )
def SCREAMING_SNAKE_CASE ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Any:
SCREAMING_SNAKE_CASE__ = tmp_path / "cache"
SCREAMING_SNAKE_CASE__ = {"col_1": "string", "col_2": "int64", "col_3": "float64"}
SCREAMING_SNAKE_CASE__ = ParquetDatasetReader(__snake_case , cache_dir=__snake_case , split=__snake_case ).read()
_check_parquet_dataset(__snake_case , __snake_case )
assert dataset.split == split if split else "train"
@pytest.mark.parametrize("path_type" , [str, list] )
def SCREAMING_SNAKE_CASE ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Any:
if issubclass(__snake_case , __snake_case ):
SCREAMING_SNAKE_CASE__ = parquet_path
elif issubclass(__snake_case , __snake_case ):
SCREAMING_SNAKE_CASE__ = [parquet_path]
SCREAMING_SNAKE_CASE__ = tmp_path / "cache"
SCREAMING_SNAKE_CASE__ = {"col_1": "string", "col_2": "int64", "col_3": "float64"}
SCREAMING_SNAKE_CASE__ = ParquetDatasetReader(__snake_case , cache_dir=__snake_case ).read()
_check_parquet_dataset(__snake_case , __snake_case )
def SCREAMING_SNAKE_CASE ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase=("train",) ) -> List[str]:
assert isinstance(__snake_case , __snake_case )
for split in splits:
SCREAMING_SNAKE_CASE__ = dataset_dict[split]
assert dataset.num_rows == 4
assert dataset.num_columns == 3
assert dataset.column_names == ["col_1", "col_2", "col_3"]
for feature, expected_dtype in expected_features.items():
assert dataset.features[feature].dtype == expected_dtype
@pytest.mark.parametrize("keep_in_memory" , [False, True] )
def SCREAMING_SNAKE_CASE ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Tuple:
SCREAMING_SNAKE_CASE__ = tmp_path / "cache"
SCREAMING_SNAKE_CASE__ = {"col_1": "string", "col_2": "int64", "col_3": "float64"}
with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase():
SCREAMING_SNAKE_CASE__ = ParquetDatasetReader(
{"train": parquet_path} , cache_dir=__snake_case , keep_in_memory=__snake_case ).read()
_check_parquet_datasetdict(__snake_case , __snake_case )
@pytest.mark.parametrize(
"features" , [
None,
{"col_1": "string", "col_2": "int64", "col_3": "float64"},
{"col_1": "string", "col_2": "string", "col_3": "string"},
{"col_1": "int32", "col_2": "int32", "col_3": "int32"},
{"col_1": "float32", "col_2": "float32", "col_3": "float32"},
] , )
def SCREAMING_SNAKE_CASE ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Optional[Any]:
SCREAMING_SNAKE_CASE__ = tmp_path / "cache"
SCREAMING_SNAKE_CASE__ = {"col_1": "string", "col_2": "int64", "col_3": "float64"}
SCREAMING_SNAKE_CASE__ = features.copy() if features else default_expected_features
SCREAMING_SNAKE_CASE__ = (
Features({feature: Value(__snake_case ) for feature, dtype in features.items()} ) if features is not None else None
)
SCREAMING_SNAKE_CASE__ = ParquetDatasetReader({"train": parquet_path} , features=__snake_case , cache_dir=__snake_case ).read()
_check_parquet_datasetdict(__snake_case , __snake_case )
@pytest.mark.parametrize("split" , [None, NamedSplit("train" ), "train", "test"] )
def SCREAMING_SNAKE_CASE ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]:
if split:
SCREAMING_SNAKE_CASE__ = {split: parquet_path}
else:
SCREAMING_SNAKE_CASE__ = "train"
SCREAMING_SNAKE_CASE__ = {"train": parquet_path, "test": parquet_path}
SCREAMING_SNAKE_CASE__ = tmp_path / "cache"
SCREAMING_SNAKE_CASE__ = {"col_1": "string", "col_2": "int64", "col_3": "float64"}
SCREAMING_SNAKE_CASE__ = ParquetDatasetReader(__snake_case , cache_dir=__snake_case ).read()
_check_parquet_datasetdict(__snake_case , __snake_case , splits=list(path.keys() ) )
assert all(dataset[split].split == split for split in path.keys() )
def SCREAMING_SNAKE_CASE ( __UpperCAmelCase , __UpperCAmelCase ) -> Dict:
SCREAMING_SNAKE_CASE__ = ParquetDatasetWriter(__snake_case , tmp_path / "foo.parquet" )
assert writer.write() > 0
SCREAMING_SNAKE_CASE__ = pq.ParquetFile(tmp_path / "foo.parquet" )
SCREAMING_SNAKE_CASE__ = pf.read()
assert dataset.data.table == output_table
def SCREAMING_SNAKE_CASE ( __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]:
SCREAMING_SNAKE_CASE__ = str(shared_datadir / "test_image_rgb.jpg" )
SCREAMING_SNAKE_CASE__ = {"image": [image_path]}
SCREAMING_SNAKE_CASE__ = Features({"image": Image()} )
SCREAMING_SNAKE_CASE__ = Dataset.from_dict(__snake_case , features=__snake_case )
SCREAMING_SNAKE_CASE__ = ParquetDatasetWriter(__snake_case , tmp_path / "foo.parquet" )
assert writer.write() > 0
SCREAMING_SNAKE_CASE__ = Dataset.from_parquet(str(tmp_path / "foo.parquet" ) )
assert dataset.features == reloaded_dataset.features
SCREAMING_SNAKE_CASE__ = ParquetDatasetReader(str(tmp_path / "foo.parquet" ) , streaming=__snake_case ).read()
assert dataset.features == reloaded_iterable_dataset.features
@pytest.mark.parametrize(
"feature, expected" , [
(Features({"foo": Value("int32" )} ), None),
(Features({"image": Image(), "foo": Value("int32" )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS),
(Features({"nested": Sequence(Audio() )} ), config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS),
] , )
def SCREAMING_SNAKE_CASE ( __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]:
assert get_writer_batch_size(__snake_case ) == expected
| 159 |
def _SCREAMING_SNAKE_CASE ( __snake_case = 1_0_0_0 ) -> int:
_UpperCAmelCase , _UpperCAmelCase = 1, 1
_UpperCAmelCase = []
for i in range(1 , n + 1 ):
_UpperCAmelCase = prev_numerator + 2 * prev_denominator
_UpperCAmelCase = prev_numerator + prev_denominator
if len(str(__snake_case ) ) > len(str(__snake_case ) ):
result.append(__snake_case )
_UpperCAmelCase = numerator
_UpperCAmelCase = denominator
return len(__snake_case )
if __name__ == "__main__":
print(F"{solution() = }") | 108 | 0 |
"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging
UpperCamelCase_ : Optional[int] = logging.get_logger(__name__)
UpperCamelCase_ : List[Any] = {
"""studio-ousia/luke-base""": """https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json""",
"""studio-ousia/luke-large""": """https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json""",
}
class _lowercase ( lowerCAmelCase ):
_a : Optional[int] = '''luke'''
def __init__( self : List[Any] , a : int=5_0_2_6_7 , a : Optional[int]=5_0_0_0_0_0 , a : Union[str, Any]=7_6_8 , a : List[str]=2_5_6 , a : Optional[Any]=1_2 , a : Dict=1_2 , a : List[str]=3_0_7_2 , a : List[str]="gelu" , a : Union[str, Any]=0.1 , a : str=0.1 , a : Union[str, Any]=5_1_2 , a : int=2 , a : List[str]=0.0_2 , a : Optional[int]=1e-12 , a : int=True , a : Dict=None , a : Any=1 , a : Any=0 , a : Optional[int]=2 , **a : Optional[Any] , ):
"""simple docstring"""
super().__init__(pad_token_id=a , bos_token_id=a , eos_token_id=a , **a )
__snake_case : Tuple =vocab_size
__snake_case : Dict =entity_vocab_size
__snake_case : str =hidden_size
__snake_case : int =entity_emb_size
__snake_case : List[str] =num_hidden_layers
__snake_case : Any =num_attention_heads
__snake_case : Union[str, Any] =hidden_act
__snake_case : str =intermediate_size
__snake_case : Union[str, Any] =hidden_dropout_prob
__snake_case : List[Any] =attention_probs_dropout_prob
__snake_case : Any =max_position_embeddings
__snake_case : Tuple =type_vocab_size
__snake_case : Tuple =initializer_range
__snake_case : List[str] =layer_norm_eps
__snake_case : Tuple =use_entity_aware_attention
__snake_case : Any =classifier_dropout
| 497 |
"""simple docstring"""
from __future__ import annotations
import json
import requests
from bsa import BeautifulSoup
from fake_useragent import UserAgent
UpperCamelCase_ : Tuple = {"""UserAgent""": UserAgent().random}
def __lowercase ( a : str ) -> dict:
__snake_case : Union[str, Any] =script.contents[0]
__snake_case : List[str] =json.loads(data[data.find('''{"config"''' ) : -1] )
return info["entry_data"]["ProfilePage"][0]["graphql"]["user"]
class _lowercase :
def __init__( self : int , a : Dict ):
"""simple docstring"""
__snake_case : Dict =f'''https://www.instagram.com/{username}/'''
__snake_case : str =self.get_json()
def _UpperCamelCase ( self : Union[str, Any] ):
"""simple docstring"""
__snake_case : List[str] =requests.get(self.url , headers=a ).text
__snake_case : int =BeautifulSoup(a , '''html.parser''' ).find_all('''script''' )
try:
return extract_user_profile(scripts[4] )
except (json.decoder.JSONDecodeError, KeyError):
return extract_user_profile(scripts[3] )
def __repr__( self : int ):
"""simple docstring"""
return f'''{self.__class__.__name__}(\'{self.username}\')'''
def __str__( self : Any ):
"""simple docstring"""
return f'''{self.fullname} ({self.username}) is {self.biography}'''
@property
def _UpperCamelCase ( self : Union[str, Any] ):
"""simple docstring"""
return self.user_data["username"]
@property
def _UpperCamelCase ( self : Dict ):
"""simple docstring"""
return self.user_data["full_name"]
@property
def _UpperCamelCase ( self : List[Any] ):
"""simple docstring"""
return self.user_data["biography"]
@property
def _UpperCamelCase ( self : Dict ):
"""simple docstring"""
return self.user_data["business_email"]
@property
def _UpperCamelCase ( self : Optional[int] ):
"""simple docstring"""
return self.user_data["external_url"]
@property
def _UpperCamelCase ( self : Dict ):
"""simple docstring"""
return self.user_data["edge_followed_by"]["count"]
@property
def _UpperCamelCase ( self : int ):
"""simple docstring"""
return self.user_data["edge_follow"]["count"]
@property
def _UpperCamelCase ( self : Tuple ):
"""simple docstring"""
return self.user_data["edge_owner_to_timeline_media"]["count"]
@property
def _UpperCamelCase ( self : Dict ):
"""simple docstring"""
return self.user_data["profile_pic_url_hd"]
@property
def _UpperCamelCase ( self : str ):
"""simple docstring"""
return self.user_data["is_verified"]
@property
def _UpperCamelCase ( self : Dict ):
"""simple docstring"""
return self.user_data["is_private"]
def __lowercase ( a : str = "github" ) -> None:
import os
if os.environ.get('''CI''' ):
return # test failing on GitHub Actions
__snake_case : Union[str, Any] =InstagramUser(a )
assert instagram_user.user_data
assert isinstance(instagram_user.user_data , a )
assert instagram_user.username == username
if username != "github":
return
assert instagram_user.fullname == "GitHub"
assert instagram_user.biography == "Built for developers."
assert instagram_user.number_of_posts > 150
assert instagram_user.number_of_followers > 120_000
assert instagram_user.number_of_followings > 15
assert instagram_user.email == "support@github.com"
assert instagram_user.website == "https://github.com/readme"
assert instagram_user.profile_picture_url.startswith('''https://instagram.''' )
assert instagram_user.is_verified is True
assert instagram_user.is_private is False
if __name__ == "__main__":
import doctest
doctest.testmod()
UpperCamelCase_ : Optional[int] = InstagramUser("""github""")
print(instagram_user)
print(F'''{instagram_user.number_of_posts = }''')
print(F'''{instagram_user.number_of_followers = }''')
print(F'''{instagram_user.number_of_followings = }''')
print(F'''{instagram_user.email = }''')
print(F'''{instagram_user.website = }''')
print(F'''{instagram_user.profile_picture_url = }''')
print(F'''{instagram_user.is_verified = }''')
print(F'''{instagram_user.is_private = }''')
| 497 | 1 |
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 _lowerCamelCase:
lowercase_ : Tuple = MBartConfig
lowercase_ : Optional[Any] = {}
lowercase_ : List[Any] = """gelu"""
def __init__( self, lowerCamelCase, lowerCamelCase=13, lowerCamelCase=7, lowerCamelCase=True, lowerCamelCase=False, lowerCamelCase=99, lowerCamelCase=32, lowerCamelCase=2, lowerCamelCase=4, lowerCamelCase=37, lowerCamelCase=0.1, lowerCamelCase=0.1, lowerCamelCase=20, lowerCamelCase=2, lowerCamelCase=1, lowerCamelCase=0, ) -> Optional[int]:
"""simple docstring"""
_lowercase : str = parent
_lowercase : str = batch_size
_lowercase : Union[str, Any] = seq_length
_lowercase : Dict = is_training
_lowercase : str = use_labels
_lowercase : List[Any] = vocab_size
_lowercase : Dict = hidden_size
_lowercase : Tuple = num_hidden_layers
_lowercase : int = num_attention_heads
_lowercase : int = intermediate_size
_lowercase : Tuple = hidden_dropout_prob
_lowercase : int = attention_probs_dropout_prob
_lowercase : Union[str, Any] = max_position_embeddings
_lowercase : Optional[Any] = eos_token_id
_lowercase : Optional[int] = pad_token_id
_lowercase : Any = bos_token_id
def UpperCamelCase ( self) -> Optional[Any]:
"""simple docstring"""
_lowercase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length - 1], self.vocab_size)
_lowercase : List[str] = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size), 1)
_lowercase : Optional[int] = tf.concat([input_ids, eos_tensor], axis=1)
_lowercase : Optional[int] = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
_lowercase : Dict = 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, )
_lowercase : str = prepare_mbart_inputs_dict(lowerCamelCase, lowerCamelCase, lowerCamelCase)
return config, inputs_dict
def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase) -> Any:
"""simple docstring"""
_lowercase : str = TFMBartModel(config=lowerCamelCase).get_decoder()
_lowercase : Union[str, Any] = inputs_dict['input_ids']
_lowercase : str = input_ids[:1, :]
_lowercase : Optional[int] = inputs_dict['attention_mask'][:1, :]
_lowercase : Tuple = inputs_dict['head_mask']
_lowercase : Tuple = 1
# first forward pass
_lowercase : Union[str, Any] = model(lowerCamelCase, attention_mask=lowerCamelCase, head_mask=lowerCamelCase, use_cache=lowerCamelCase)
_lowercase , _lowercase : Union[str, Any] = outputs.to_tuple()
_lowercase : Optional[int] = past_key_values[1]
def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=None , lowerCamelCase_=None , lowerCamelCase_=None , lowerCamelCase_=None , lowerCamelCase_=None , ) -> Optional[Any]:
if attention_mask is None:
_lowercase : Dict = tf.cast(tf.math.not_equal(lowerCamelCase_ , config.pad_token_id ) , tf.inta )
if decoder_attention_mask is None:
_lowercase : List[Any] = 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:
_lowercase : List[Any] = tf.ones((config.encoder_layers, config.encoder_attention_heads) )
if decoder_head_mask is None:
_lowercase : int = tf.ones((config.decoder_layers, config.decoder_attention_heads) )
if cross_attn_head_mask is None:
_lowercase : Tuple = 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 _lowerCamelCase( _a, _a, unittest.TestCase ):
lowercase_ : Optional[int] = (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else ()
lowercase_ : Optional[Any] = (TFMBartForConditionalGeneration,) if is_tf_available() else ()
lowercase_ : Optional[int] = (
{
"""conversational""": TFMBartForConditionalGeneration,
"""feature-extraction""": TFMBartModel,
"""summarization""": TFMBartForConditionalGeneration,
"""text2text-generation""": TFMBartForConditionalGeneration,
"""translation""": TFMBartForConditionalGeneration,
}
if is_tf_available()
else {}
)
lowercase_ : Optional[Any] = True
lowercase_ : Union[str, Any] = False
lowercase_ : Dict = False
def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase) -> List[Any]:
"""simple docstring"""
if pipeline_test_casse_name != "FeatureExtractionPipelineTests":
# Exception encountered when calling layer '...'
return True
return False
def UpperCamelCase ( self) -> Any:
"""simple docstring"""
_lowercase : List[str] = TFMBartModelTester(self)
_lowercase : List[Any] = ConfigTester(self, config_class=lowerCamelCase)
def UpperCamelCase ( self) -> Union[str, Any]:
"""simple docstring"""
self.config_tester.run_common_tests()
def UpperCamelCase ( self) -> Tuple:
"""simple docstring"""
_lowercase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.check_decoder_model_past_large_inputs(*lowerCamelCase)
@require_sentencepiece
@require_tokenizers
@require_tf
class _lowerCamelCase( unittest.TestCase ):
lowercase_ : Tuple = [
""" UN Chief Says There Is No Military Solution in Syria""",
]
lowercase_ : int = [
"""Şeful ONU declară că nu există o soluţie militară în Siria""",
]
lowercase_ : Optional[Any] = """facebook/mbart-large-en-ro"""
@cached_property
def UpperCamelCase ( self) -> Any:
"""simple docstring"""
return AutoTokenizer.from_pretrained(self.model_name)
@cached_property
def UpperCamelCase ( self) -> List[Any]:
"""simple docstring"""
_lowercase : Union[str, Any] = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name)
return model
def UpperCamelCase ( self, **lowerCamelCase) -> List[str]:
"""simple docstring"""
_lowercase : str = self.translate_src_text(**lowerCamelCase)
self.assertListEqual(self.expected_text, lowerCamelCase)
def UpperCamelCase ( self, **lowerCamelCase) -> List[str]:
"""simple docstring"""
_lowercase : List[Any] = self.tokenizer(self.src_text, **lowerCamelCase, return_tensors='tf')
_lowercase : int = self.model.generate(
model_inputs.input_ids, attention_mask=model_inputs.attention_mask, num_beams=2)
_lowercase : List[Any] = self.tokenizer.batch_decode(lowerCamelCase, skip_special_tokens=lowerCamelCase)
return generated_words
@slow
def UpperCamelCase ( self) -> Optional[int]:
"""simple docstring"""
self._assert_generated_batch_equal_expected()
| 89 |
'''simple docstring'''
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import symbol_database as _symbol_database
from google.protobuf.internal import builder as _builder
# @@protoc_insertion_point(imports)
__snake_case : Union[str, Any] = _symbol_database.Default()
__snake_case : Union[str, Any] = _descriptor_pool.Default().AddSerializedFile(
b"\n\x19sentencepiece_model.proto\x12\rsentencepiece\"\x80\x0c\n\x0bTrainerSpec\x12\r\n\x05input\x18\x01 \x03(\t\x12\x14\n\x0cinput_format\x18\x07 \x01(\t\x12\x14\n\x0cmodel_prefix\x18\x02 \x01(\t\x12\x41\n\nmodel_type\x18\x03 \x01(\x0e\x32$.sentencepiece.TrainerSpec.ModelType:\x07UNIGRAM\x12\x18\n\nvocab_size\x18\x04 \x01(\x05:\x04\x38\x30\x30\x30\x12\x17\n\x0f\x61\x63\x63\x65pt_language\x18\x05 \x03(\t\x12 \n\x15self_test_sample_size\x18\x06 \x01(\x05:\x01\x30\x12*\n\x1b\x65nable_differential_privacy\x18\x32 \x01(\x08:\x05\x66\x61lse\x12+\n differential_privacy_noise_level\x18\x33 \x01(\x02:\x01\x30\x12\x32\n\'differential_privacy_clipping_threshold\x18\x34 \x01(\x04:\x01\x30\x12\"\n\x12\x63haracter_coverage\x18\n \x01(\x02:\x06\x30.9995\x12\x1e\n\x13input_sentence_size\x18\x0b \x01(\x04:\x01\x30\x12$\n\x16shuffle_input_sentence\x18\x13 \x01(\x08:\x04true\x12 \n\x14mining_sentence_size\x18\x0c \x01(\x05\x42\x02\x18\x01\x12\"\n\x16training_sentence_size\x18\r \x01(\x05\x42\x02\x18\x01\x12(\n\x17seed_sentencepiece_size\x18\x0e \x01(\x05:\x07\x31\x30\x30\x30\x30\x30\x30\x12\x1e\n\x10shrinking_factor\x18\x0f \x01(\x02:\x04\x30.75\x12!\n\x13max_sentence_length\x18\x12 \x01(\x05:\x04\x34\x31\x39\x32\x12\x17\n\x0bnum_threads\x18\x10 \x01(\x05:\x02\x31\x36\x12\x1d\n\x12num_sub_iterations\x18\x11 \x01(\x05:\x01\x32\x12$\n\x18max_sentencepiece_length\x18\x14 \x01(\x05:\x02\x31\x36\x12%\n\x17split_by_unicode_script\x18\x15 \x01(\x08:\x04true\x12\x1d\n\x0fsplit_by_number\x18\x17 \x01(\x08:\x04true\x12!\n\x13split_by_whitespace\x18\x16 \x01(\x08:\x04true\x12)\n\x1atreat_whitespace_as_suffix\x18\x18 \x01(\x08:\x05\x66\x61lse\x12+\n\x1c\x61llow_whitespace_only_pieces\x18\x1a \x01(\x08:\x05\x66\x61lse\x12\x1b\n\x0csplit_digits\x18\x19 \x01(\x08:\x05\x66\x61lse\x12#\n\x19pretokenization_delimiter\x18\x35 \x01(\t:\x00\x12\x17\n\x0f\x63ontrol_symbols\x18\x1e \x03(\t\x12\x1c\n\x14user_defined_symbols\x18\x1f \x03(\t\x12\x16\n\x0erequired_chars\x18$ \x01(\t\x12\x1c\n\rbyte_fallback\x18# \x01(\x08:\x05\x66\x61lse\x12+\n\x1dvocabulary_output_piece_score\x18 \x01(\x08:\x04true\x12\x1e\n\x10hard_vocab_limit\x18! \x01(\x08:\x04true\x12\x1c\n\ruse_all_vocab\x18\" \x01(\x08:\x05\x66\x61lse\x12\x11\n\x06unk_id\x18( \x01(\x05:\x01\x30\x12\x11\n\x06\x62os_id\x18) \x01(\x05:\x01\x31\x12\x11\n\x06\x65os_id\x18* \x01(\x05:\x01\x32\x12\x12\n\x06pad_id\x18+ \x01(\x05:\x02-1\x12\x18\n\tunk_piece\x18- \x01(\t:\x05<unk>\x12\x16\n\tbos_piece\x18. \x01(\t:\x03<s>\x12\x17\n\teos_piece\x18/ \x01(\t:\x04</s>\x12\x18\n\tpad_piece\x18\x30 \x01(\t:\x05<pad>\x12\x1a\n\x0bunk_surface\x18, \x01(\t:\x05 \xe2\x81\x87 \x12+\n\x1ctrain_extremely_large_corpus\x18\x31 \x01(\x08:\x05\x66\x61lse\"5\n\tModelType\x12\x0b\n\x07UNIGRAM\x10\x01\x12\x07\n\x03\x42PE\x10\x02\x12\x08\n\x04WORD\x10\x03\x12\x08\n\x04\x43HAR\x10\x04*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xd1\x01\n\x0eNormalizerSpec\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x1c\n\x14precompiled_charsmap\x18\x02 \x01(\x0c\x12\x1e\n\x10\x61\x64\x64_dummy_prefix\x18\x03 \x01(\x08:\x04true\x12&\n\x18remove_extra_whitespaces\x18\x04 \x01(\x08:\x04true\x12 \n\x12\x65scape_whitespaces\x18\x05 \x01(\x08:\x04true\x12\x1e\n\x16normalization_rule_tsv\x18\x06 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"y\n\x0cSelfTestData\x12\x33\n\x07samples\x18\x01 \x03(\x0b\x32\".sentencepiece.SelfTestData.Sample\x1a)\n\x06Sample\x12\r\n\x05input\x18\x01 \x01(\t\x12\x10\n\x08\x65xpected\x18\x02 \x01(\t*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\"\xfe\x03\n\nModelProto\x12\x37\n\x06pieces\x18\x01 \x03(\x0b\x32\'.sentencepiece.ModelProto.SentencePiece\x12\x30\n\x0ctrainer_spec\x18\x02 \x01(\x0b\x32\x1a.sentencepiece.TrainerSpec\x12\x36\n\x0fnormalizer_spec\x18\x03 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x12\x33\n\x0eself_test_data\x18\x04 \x01(\x0b\x32\x1b.sentencepiece.SelfTestData\x12\x38\n\x11\x64\x65normalizer_spec\x18\x05 \x01(\x0b\x32\x1d.sentencepiece.NormalizerSpec\x1a\xd2\x01\n\rSentencePiece\x12\r\n\x05piece\x18\x01 \x01(\t\x12\r\n\x05score\x18\x02 \x01(\x02\x12\x42\n\x04type\x18\x03 \x01(\x0e\x32,.sentencepiece.ModelProto.SentencePiece.Type:\x06NORMAL\"T\n\x04Type\x12\n\n\x06NORMAL\x10\x01\x12\x0b\n\x07UNKNOWN\x10\x02\x12\x0b\n\x07\x43ONTROL\x10\x03\x12\x10\n\x0cUSER_DEFINED\x10\x04\x12\x08\n\x04\x42YTE\x10\x06\x12\n\n\x06UNUSED\x10\x05*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02*\t\x08\xc8\x01\x10\x80\x80\x80\x80\x02\x42\x02H\x03"
)
__snake_case : Optional[Any] = globals()
_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, "sentencepiece_model_pb2", _globals)
if _descriptor._USE_C_DESCRIPTORS is False:
__snake_case : Optional[int] = None
__snake_case : List[Any] = b"H\003"
# (generated by protobuf compiler, but `_TRAINERSPEC` is not defined)
# _TRAINERSPEC.fields_by_name["mining_sentence_size"]._options = None
# _TRAINERSPEC.fields_by_name["mining_sentence_size"]._serialized_options = b"\030\001"
# _TRAINERSPEC.fields_by_name["training_sentence_size"]._options = None
# _TRAINERSPEC.fields_by_name["training_sentence_size"]._serialized_options = b"\030\001"
__snake_case : int = 45
__snake_case : Any = 1581
__snake_case : str = 1517
__snake_case : Tuple = 1570
__snake_case : List[Any] = 1584
__snake_case : List[str] = 1793
__snake_case : Optional[Any] = 1795
__snake_case : Tuple = 1916
__snake_case : str = 1864
__snake_case : Dict = 1905
__snake_case : str = 1919
__snake_case : int = 2429
__snake_case : str = 2208
__snake_case : Tuple = 2418
__snake_case : List[Any] = 2323
__snake_case : str = 2407
# @@protoc_insertion_point(module_scope)
| 131 | 0 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available
a_ : Optional[int] = {
"configuration_transfo_xl": ["TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP", "TransfoXLConfig"],
"tokenization_transfo_xl": ["TransfoXLCorpus", "TransfoXLTokenizer"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a_ : Tuple = [
"TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST",
"AdaptiveEmbedding",
"TransfoXLForSequenceClassification",
"TransfoXLLMHeadModel",
"TransfoXLModel",
"TransfoXLPreTrainedModel",
"load_tf_weights_in_transfo_xl",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a_ : Dict = [
"TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST",
"TFAdaptiveEmbedding",
"TFTransfoXLForSequenceClassification",
"TFTransfoXLLMHeadModel",
"TFTransfoXLMainLayer",
"TFTransfoXLModel",
"TFTransfoXLPreTrainedModel",
]
if TYPE_CHECKING:
from .configuration_transfo_xl import TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP, TransfoXLConfig
from .tokenization_transfo_xl import TransfoXLCorpus, TransfoXLTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_transfo_xl import (
TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
AdaptiveEmbedding,
TransfoXLForSequenceClassification,
TransfoXLLMHeadModel,
TransfoXLModel,
TransfoXLPreTrainedModel,
load_tf_weights_in_transfo_xl,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_transfo_xl import (
TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
TFAdaptiveEmbedding,
TFTransfoXLForSequenceClassification,
TFTransfoXLLMHeadModel,
TFTransfoXLMainLayer,
TFTransfoXLModel,
TFTransfoXLPreTrainedModel,
)
else:
import sys
a_ : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 701 |
'''simple docstring'''
import logging
import os
from typing import Dict, List, Optional, Union
import torch
import torch.nn as nn
from accelerate.utils.imports import (
is_abit_bnb_available,
is_abit_bnb_available,
is_bnb_available,
)
from ..big_modeling import dispatch_model, init_empty_weights
from .dataclasses import BnbQuantizationConfig
from .modeling import (
find_tied_parameters,
get_balanced_memory,
infer_auto_device_map,
load_checkpoint_in_model,
offload_weight,
set_module_tensor_to_device,
)
if is_bnb_available():
import bitsandbytes as bnb
from copy import deepcopy
a_ : List[str] = logging.getLogger(__name__)
def _A (lowerCAmelCase__ :torch.nn.Module , lowerCAmelCase__ :BnbQuantizationConfig , lowerCAmelCase__ :Union[str, os.PathLike] = None , lowerCAmelCase__ :Optional[Dict[str, Union[int, str, torch.device]]] = None , lowerCAmelCase__ :Optional[List[str]] = None , lowerCAmelCase__ :Optional[Dict[Union[int, str], Union[int, str]]] = None , lowerCAmelCase__ :Optional[Union[str, os.PathLike]] = None , lowerCAmelCase__ :bool = False , ) -> List[str]:
'''simple docstring'''
_a = bnb_quantization_config.load_in_abit
_a = bnb_quantization_config.load_in_abit
if load_in_abit and not is_abit_bnb_available():
raise ImportError(
'You have a version of `bitsandbytes` that is not compatible with 8bit quantization,'
' make sure you have the latest version of `bitsandbytes` installed.' )
if load_in_abit and not is_abit_bnb_available():
raise ValueError(
'You have a version of `bitsandbytes` that is not compatible with 4bit quantization,'
'make sure you have the latest version of `bitsandbytes` installed.' )
_a = []
# custom device map
if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ) and len(device_map.keys() ) > 1:
_a = [key for key, value in device_map.items() if value in ['disk', 'cpu']]
# We keep some modules such as the lm_head in their original dtype for numerical stability reasons
if bnb_quantization_config.skip_modules is None:
_a = get_keys_to_not_convert(lowerCAmelCase__ )
# add cpu modules to skip modules only for 4-bit modules
if load_in_abit:
bnb_quantization_config.skip_modules.extend(lowerCAmelCase__ )
_a = bnb_quantization_config.skip_modules
# We add the modules we want to keep in full precision
if bnb_quantization_config.keep_in_fpaa_modules is None:
_a = []
_a = bnb_quantization_config.keep_in_fpaa_modules
modules_to_not_convert.extend(lowerCAmelCase__ )
# compatibility with peft
_a = load_in_abit
_a = load_in_abit
_a = get_parameter_device(lowerCAmelCase__ )
if model_device.type != "meta":
# quantization of an already loaded model
logger.warning(
'It is not recommended to quantize a loaded model. '
'The model should be instantiated under the `init_empty_weights` context manager.' )
_a = replace_with_bnb_layers(lowerCAmelCase__ , lowerCAmelCase__ , modules_to_not_convert=lowerCAmelCase__ )
# convert param to the right dtype
_a = bnb_quantization_config.torch_dtype
for name, param in model.state_dict().items():
if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ):
param.to(torch.floataa )
if param.dtype != torch.floataa:
_a = name.replace('.weight' , '' ).replace('.bias' , '' )
_a = getattr(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
if param is not None:
param.to(torch.floataa )
elif torch.is_floating_point(lowerCAmelCase__ ):
param.to(lowerCAmelCase__ )
if model_device.type == "cuda":
# move everything to cpu in the first place because we can't do quantization if the weights are already on cuda
model.cuda(torch.cuda.current_device() )
torch.cuda.empty_cache()
elif torch.cuda.is_available():
model.to(torch.cuda.current_device() )
else:
raise RuntimeError('No GPU found. A GPU is needed for quantization.' )
logger.info(
f'The model device type is {model_device.type}. However, cuda is needed for quantization.'
'We move the model to cuda.' )
return model
elif weights_location is None:
raise RuntimeError(
f'`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} ' )
else:
with init_empty_weights():
_a = replace_with_bnb_layers(
lowerCAmelCase__ , lowerCAmelCase__ , modules_to_not_convert=lowerCAmelCase__ )
_a = get_quantized_model_device_map(
lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , max_memory=lowerCAmelCase__ , no_split_module_classes=lowerCAmelCase__ , )
if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
_a = True
_a = any(x in list(device_map.values() ) for x in ['cpu', 'disk'] )
load_checkpoint_in_model(
lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , dtype=bnb_quantization_config.torch_dtype , offload_folder=lowerCAmelCase__ , offload_state_dict=lowerCAmelCase__ , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , )
return dispatch_model(lowerCAmelCase__ , device_map=lowerCAmelCase__ , offload_dir=lowerCAmelCase__ )
def _A (lowerCAmelCase__ :Tuple , lowerCAmelCase__ :Dict , lowerCAmelCase__ :List[Any]=None , lowerCAmelCase__ :Optional[int]=None , lowerCAmelCase__ :List[Any]=None ) -> List[Any]:
'''simple docstring'''
if device_map is None:
if torch.cuda.is_available():
_a = {'': torch.cuda.current_device()}
else:
raise RuntimeError('No GPU found. A GPU is needed for quantization.' )
logger.info('The device_map was not initialized.' 'Setting device_map to `{\'\':torch.cuda.current_device()}`.' )
if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ):
if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
raise ValueError(
'If passing a string for `device_map`, please choose \'auto\', \'balanced\', \'balanced_low_0\' or '
'\'sequential\'.' )
_a = {}
special_dtypes.update(
{
name: bnb_quantization_config.torch_dtype
for name, _ in model.named_parameters()
if any(m in name for m in bnb_quantization_config.skip_modules )
} )
special_dtypes.update(
{
name: torch.floataa
for name, _ in model.named_parameters()
if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules )
} )
_a = {}
_a = special_dtypes
_a = no_split_module_classes
_a = bnb_quantization_config.target_dtype
# get max_memory for each device.
if device_map != "sequential":
_a = get_balanced_memory(
lowerCAmelCase__ , low_zero=(device_map == 'balanced_low_0') , max_memory=lowerCAmelCase__ , **lowerCAmelCase__ , )
_a = max_memory
_a = infer_auto_device_map(lowerCAmelCase__ , **lowerCAmelCase__ )
if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ):
# check if don't have any quantized module on the cpu
_a = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules
_a = {
key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert
}
for device in ["cpu", "disk"]:
if device in device_map_without_some_modules.values():
if bnb_quantization_config.load_in_abit:
raise ValueError(
'\n Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n these modules in `torch_dtype`, you need to pass a custom `device_map` to\n `load_and_quantize_model`. Check\n https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n for more details.\n ' )
else:
logger.info(
'Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit' )
del device_map_without_some_modules
return device_map
def _A (lowerCAmelCase__ :Dict , lowerCAmelCase__ :Optional[Any] , lowerCAmelCase__ :Optional[Any]=None , lowerCAmelCase__ :Any=None ) -> Tuple:
'''simple docstring'''
if modules_to_not_convert is None:
_a = []
_a , _a = _replace_with_bnb_layers(
lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
if not has_been_replaced:
logger.warning(
'You are loading your model in 8bit or 4bit but no linear modules were found in your model.'
' this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.'
' Please double check your model architecture, or submit an issue on github if you think this is'
' a bug.' )
return model
def _A (lowerCAmelCase__ :List[str] , lowerCAmelCase__ :Optional[Any] , lowerCAmelCase__ :Union[str, Any]=None , lowerCAmelCase__ :Optional[Any]=None , ) -> List[Any]:
'''simple docstring'''
_a = False
for name, module in model.named_children():
if current_key_name is None:
_a = []
current_key_name.append(lowerCAmelCase__ )
if isinstance(lowerCAmelCase__ , nn.Linear ) and name not in modules_to_not_convert:
# Check if the current key is not in the `modules_to_not_convert`
_a = '.'.join(lowerCAmelCase__ )
_a = True
for key in modules_to_not_convert:
if (
(key in current_key_name_str) and (key + "." in current_key_name_str)
) or key == current_key_name_str:
_a = False
break
if proceed:
# Load bnb module with empty weight and replace ``nn.Linear` module
if bnb_quantization_config.load_in_abit:
_a = bnb.nn.LinearabitLt(
module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=lowerCAmelCase__ , threshold=bnb_quantization_config.llm_inta_threshold , )
elif bnb_quantization_config.load_in_abit:
_a = bnb.nn.Linearabit(
module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , )
else:
raise ValueError('load_in_8bit and load_in_4bit can\'t be both False' )
_a = module.weight.data
if module.bias is not None:
_a = module.bias.data
bnb_module.requires_grad_(lowerCAmelCase__ )
setattr(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
_a = True
if len(list(module.children() ) ) > 0:
_a , _a = _replace_with_bnb_layers(
lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
_a = has_been_replaced | _has_been_replaced
# Remove the last key for recursion
current_key_name.pop(-1 )
return model, has_been_replaced
def _A (lowerCAmelCase__ :Union[str, Any] ) -> Optional[int]:
'''simple docstring'''
with init_empty_weights():
_a = deepcopy(lowerCAmelCase__ ) # this has 0 cost since it is done inside `init_empty_weights` context manager`
_a = find_tied_parameters(lowerCAmelCase__ )
# For compatibility with Accelerate < 0.18
if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ):
_a = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() )
else:
_a = sum(lowerCAmelCase__ , [] )
_a = len(lowerCAmelCase__ ) > 0
# Check if it is a base model
_a = False
if hasattr(lowerCAmelCase__ , 'base_model_prefix' ):
_a = not hasattr(lowerCAmelCase__ , model.base_model_prefix )
# Ignore this for base models (BertModel, GPT2Model, etc.)
if (not has_tied_params) and is_base_model:
return []
# otherwise they have an attached head
_a = list(model.named_children() )
_a = [list_modules[-1][0]]
# add last module together with tied weights
_a = set(lowerCAmelCase__ ) - set(lowerCAmelCase__ )
_a = list(set(lowerCAmelCase__ ) ) + list(lowerCAmelCase__ )
# remove ".weight" from the keys
_a = ['.weight', '.bias']
_a = []
for name in list_untouched:
for name_to_remove in names_to_remove:
if name_to_remove in name:
_a = name.replace(lowerCAmelCase__ , '' )
filtered_module_names.append(lowerCAmelCase__ )
return filtered_module_names
def _A (lowerCAmelCase__ :List[Any] ) -> List[str]:
'''simple docstring'''
for m in model.modules():
if isinstance(lowerCAmelCase__ , bnb.nn.Linearabit ):
return True
return False
def _A (lowerCAmelCase__ :nn.Module ) -> Union[str, Any]:
'''simple docstring'''
return next(parameter.parameters() ).device
def _A (lowerCAmelCase__ :Any , lowerCAmelCase__ :List[str] , lowerCAmelCase__ :Dict , lowerCAmelCase__ :Any , lowerCAmelCase__ :Any , lowerCAmelCase__ :Dict , lowerCAmelCase__ :Dict ) -> Tuple:
'''simple docstring'''
if fpaa_statistics is None:
set_module_tensor_to_device(lowerCAmelCase__ , lowerCAmelCase__ , 0 , dtype=lowerCAmelCase__ , value=lowerCAmelCase__ )
_a = param_name
_a = model
if "." in tensor_name:
_a = tensor_name.split('.' )
for split in splits[:-1]:
_a = getattr(lowerCAmelCase__ , lowerCAmelCase__ )
if new_module is None:
raise ValueError(f'{module} has no attribute {split}.' )
_a = new_module
_a = splits[-1]
# offload weights
_a = False
offload_weight(module._parameters[tensor_name] , lowerCAmelCase__ , lowerCAmelCase__ , index=lowerCAmelCase__ )
if hasattr(module._parameters[tensor_name] , 'SCB' ):
offload_weight(
module._parameters[tensor_name].SCB , param_name.replace('weight' , 'SCB' ) , lowerCAmelCase__ , index=lowerCAmelCase__ , )
else:
offload_weight(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , index=lowerCAmelCase__ )
offload_weight(lowerCAmelCase__ , param_name.replace('weight' , 'SCB' ) , lowerCAmelCase__ , index=lowerCAmelCase__ )
set_module_tensor_to_device(lowerCAmelCase__ , lowerCAmelCase__ , 'meta' , dtype=lowerCAmelCase__ , value=torch.empty(*param.size() ) )
| 532 | 0 |
from __future__ import annotations
def __snake_case ( lowerCAmelCase_ , lowerCAmelCase_ ) -> list[tuple[int, int]]:
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = position
SCREAMING_SNAKE_CASE__ = [
(y + 1, x + 2),
(y - 1, x + 2),
(y + 1, x - 2),
(y - 1, x - 2),
(y + 2, x + 1),
(y + 2, x - 1),
(y - 2, x + 1),
(y - 2, x - 1),
]
SCREAMING_SNAKE_CASE__ = []
for position in positions:
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = position
if 0 <= y_test < n and 0 <= x_test < n:
permissible_positions.append(lowerCAmelCase_ )
return permissible_positions
def __snake_case ( lowerCAmelCase_ ) -> bool:
return not any(elem == 0 for row in board for elem in row )
def __snake_case ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> bool:
if is_complete(lowerCAmelCase_ ):
return True
for position in get_valid_pos(lowerCAmelCase_ , len(lowerCAmelCase_ ) ):
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = position
if board[y][x] == 0:
SCREAMING_SNAKE_CASE__ = curr + 1
if open_knight_tour_helper(lowerCAmelCase_ , lowerCAmelCase_ , curr + 1 ):
return True
SCREAMING_SNAKE_CASE__ = 0
return False
def __snake_case ( lowerCAmelCase_ ) -> list[list[int]]:
SCREAMING_SNAKE_CASE__ = [[0 for i in range(lowerCAmelCase_ )] for j in range(lowerCAmelCase_ )]
for i in range(lowerCAmelCase_ ):
for j in range(lowerCAmelCase_ ):
SCREAMING_SNAKE_CASE__ = 1
if open_knight_tour_helper(lowerCAmelCase_ , (i, j) , 1 ):
return board
SCREAMING_SNAKE_CASE__ = 0
SCREAMING_SNAKE_CASE__ = f'''Open Kight Tour cannot be performed on a board of size {n}'''
raise ValueError(lowerCAmelCase_ )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 100 |
'''simple docstring'''
import PIL.Image
import PIL.ImageOps
from packaging import version
from PIL import Image
if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('''9.1.0'''):
lowercase_ : Any = {
'''linear''': PIL.Image.Resampling.BILINEAR,
'''bilinear''': PIL.Image.Resampling.BILINEAR,
'''bicubic''': PIL.Image.Resampling.BICUBIC,
'''lanczos''': PIL.Image.Resampling.LANCZOS,
'''nearest''': PIL.Image.Resampling.NEAREST,
}
else:
lowercase_ : str = {
'''linear''': PIL.Image.LINEAR,
'''bilinear''': PIL.Image.BILINEAR,
'''bicubic''': PIL.Image.BICUBIC,
'''lanczos''': PIL.Image.LANCZOS,
'''nearest''': PIL.Image.NEAREST,
}
def SCREAMING_SNAKE_CASE ( lowercase_ : Optional[int] ):
lowercase = (images / 2 + 0.5).clamp(0 , 1 )
lowercase = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy()
lowercase = numpy_to_pil(lowercase_ )
return images
def SCREAMING_SNAKE_CASE ( lowercase_ : List[Any] ):
if images.ndim == 3:
lowercase = images[None, ...]
lowercase = (images * 255).round().astype("""uint8""" )
if images.shape[-1] == 1:
# special case for grayscale (single channel) images
lowercase = [Image.fromarray(image.squeeze() , mode="""L""" ) for image in images]
else:
lowercase = [Image.fromarray(lowercase_ ) for image in images]
return pil_images
| 588 | 0 |
"""simple docstring"""
import gc
import random
import unittest
import numpy as np
import torch
from transformers import XLMRobertaTokenizer
from diffusers import (
AltDiffusionImgaImgPipeline,
AutoencoderKL,
PNDMScheduler,
UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
RobertaSeriesConfig,
RobertaSeriesModelWithTransformation,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
enable_full_determinism()
class UpperCAmelCase_ ( unittest.TestCase):
def _UpperCAmelCase ( self ) -> Tuple:
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
@property
def _UpperCAmelCase ( self ) -> Union[str, Any]:
lowercase__ : Optional[int] = 1
lowercase__ : List[str] = 3
lowercase__ : List[Any] = (3_2, 3_2)
lowercase__ : int = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(a )
return image
@property
def _UpperCAmelCase ( self ) -> List[Any]:
torch.manual_seed(0 )
lowercase__ : List[Any] = UNetaDConditionModel(
block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=3_2 , )
return model
@property
def _UpperCAmelCase ( self ) -> List[Any]:
torch.manual_seed(0 )
lowercase__ : Dict = AutoencoderKL(
block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , )
return model
@property
def _UpperCAmelCase ( self ) -> Tuple:
torch.manual_seed(0 )
lowercase__ : Dict = RobertaSeriesConfig(
hidden_size=3_2 , project_dim=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=5_0_0_6 , )
return RobertaSeriesModelWithTransformation(a )
@property
def _UpperCAmelCase ( self ) -> Any:
def extract(*a , **a ):
class UpperCAmelCase_ :
def __init__( self ) -> Optional[Any]:
lowercase__ : Optional[Any] = torch.ones([0] )
def _UpperCAmelCase ( self , a ) -> str:
self.pixel_values.to(a )
return self
return Out()
return extract
def _UpperCAmelCase ( self ) -> Optional[int]:
lowercase__ : int = 'cpu' # ensure determinism for the device-dependent torch.Generator
lowercase__ : str = self.dummy_cond_unet
lowercase__ : Any = PNDMScheduler(skip_prk_steps=a )
lowercase__ : str = self.dummy_vae
lowercase__ : Union[str, Any] = self.dummy_text_encoder
lowercase__ : Optional[int] = XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta' )
lowercase__ : Any = 7_7
lowercase__ : List[Any] = self.dummy_image.to(a )
lowercase__ : Dict = init_image / 2 + 0.5
# make sure here that pndm scheduler skips prk
lowercase__ : Optional[int] = AltDiffusionImgaImgPipeline(
unet=a , scheduler=a , vae=a , text_encoder=a , tokenizer=a , safety_checker=a , feature_extractor=self.dummy_extractor , )
lowercase__ : Union[str, Any] = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=a )
lowercase__ : Tuple = alt_pipe.to(a )
alt_pipe.set_progress_bar_config(disable=a )
lowercase__ : Tuple = 'A painting of a squirrel eating a burger'
lowercase__ : str = torch.Generator(device=a ).manual_seed(0 )
lowercase__ : List[Any] = alt_pipe(
[prompt] , generator=a , guidance_scale=6.0 , num_inference_steps=2 , output_type='np' , image=a , )
lowercase__ : int = output.images
lowercase__ : List[Any] = torch.Generator(device=a ).manual_seed(0 )
lowercase__ : Dict = alt_pipe(
[prompt] , generator=a , guidance_scale=6.0 , num_inference_steps=2 , output_type='np' , image=a , return_dict=a , )[0]
lowercase__ : Dict = image[0, -3:, -3:, -1]
lowercase__ : List[Any] = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 3_2, 3_2, 3)
lowercase__ : List[str] = np.array([0.4_427, 0.3_731, 0.4_249, 0.4_941, 0.4_546, 0.4_148, 0.4_193, 0.4_666, 0.4_499] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 5e-3
@unittest.skipIf(torch_device != 'cuda' , 'This test requires a GPU' )
def _UpperCAmelCase ( self ) -> List[str]:
lowercase__ : Optional[int] = self.dummy_cond_unet
lowercase__ : Optional[Any] = PNDMScheduler(skip_prk_steps=a )
lowercase__ : Dict = self.dummy_vae
lowercase__ : List[Any] = self.dummy_text_encoder
lowercase__ : Optional[int] = XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta' )
lowercase__ : int = 7_7
lowercase__ : str = self.dummy_image.to(a )
# put models in fp16
lowercase__ : int = unet.half()
lowercase__ : List[str] = vae.half()
lowercase__ : Dict = bert.half()
# make sure here that pndm scheduler skips prk
lowercase__ : List[Any] = AltDiffusionImgaImgPipeline(
unet=a , scheduler=a , vae=a , text_encoder=a , tokenizer=a , safety_checker=a , feature_extractor=self.dummy_extractor , )
lowercase__ : int = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=a )
lowercase__ : Union[str, Any] = alt_pipe.to(a )
alt_pipe.set_progress_bar_config(disable=a )
lowercase__ : Optional[Any] = 'A painting of a squirrel eating a burger'
lowercase__ : Optional[int] = torch.manual_seed(0 )
lowercase__ : List[str] = alt_pipe(
[prompt] , generator=a , num_inference_steps=2 , output_type='np' , image=a , ).images
assert image.shape == (1, 3_2, 3_2, 3)
@unittest.skipIf(torch_device != 'cuda' , 'This test requires a GPU' )
def _UpperCAmelCase ( self ) -> Optional[Any]:
lowercase__ : Dict = load_image(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
'/img2img/sketch-mountains-input.jpg' )
# resize to resolution that is divisible by 8 but not 16 or 32
lowercase__ : Optional[Any] = init_image.resize((7_6_0, 5_0_4) )
lowercase__ : Tuple = 'BAAI/AltDiffusion'
lowercase__ : Tuple = AltDiffusionImgaImgPipeline.from_pretrained(
a , safety_checker=a , )
pipe.to(a )
pipe.set_progress_bar_config(disable=a )
pipe.enable_attention_slicing()
lowercase__ : str = 'A fantasy landscape, trending on artstation'
lowercase__ : Dict = torch.manual_seed(0 )
lowercase__ : List[str] = pipe(
prompt=a , image=a , strength=0.75 , guidance_scale=7.5 , generator=a , output_type='np' , )
lowercase__ : Optional[Any] = output.images[0]
lowercase__ : Optional[Any] = image[2_5_5:2_5_8, 3_8_3:3_8_6, -1]
assert image.shape == (5_0_4, 7_6_0, 3)
lowercase__ : int = np.array([0.9_358, 0.9_397, 0.9_599, 0.9_901, 1.0_000, 1.0_000, 0.9_882, 1.0_000, 1.0_000] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
@slow
@require_torch_gpu
class UpperCAmelCase_ ( unittest.TestCase):
def _UpperCAmelCase ( self ) -> str:
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def _UpperCAmelCase ( self ) -> Optional[Any]:
lowercase__ : Tuple = load_image(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
'/img2img/sketch-mountains-input.jpg' )
lowercase__ : Tuple = init_image.resize((7_6_8, 5_1_2) )
lowercase__ : int = load_numpy(
'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy' )
lowercase__ : Union[str, Any] = 'BAAI/AltDiffusion'
lowercase__ : Union[str, Any] = AltDiffusionImgaImgPipeline.from_pretrained(
a , safety_checker=a , )
pipe.to(a )
pipe.set_progress_bar_config(disable=a )
pipe.enable_attention_slicing()
lowercase__ : Optional[Any] = 'A fantasy landscape, trending on artstation'
lowercase__ : Union[str, Any] = torch.manual_seed(0 )
lowercase__ : Union[str, Any] = pipe(
prompt=a , image=a , strength=0.75 , guidance_scale=7.5 , generator=a , output_type='np' , )
lowercase__ : Union[str, Any] = output.images[0]
assert image.shape == (5_1_2, 7_6_8, 3)
# img2img is flaky across GPUs even in fp32, so using MAE here
assert np.abs(expected_image - image ).max() < 1e-2
| 707 | """simple docstring"""
import unittest
from transformers import is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
if is_torch_available():
import torch
from transformers import AutoModelForImageClassification
if is_vision_available():
from transformers import AutoImageProcessor
@require_torch
@require_vision
class UpperCAmelCase_ ( unittest.TestCase):
@slow
def _UpperCAmelCase ( self ) -> str:
lowercase__ : Optional[Any] = AutoImageProcessor.from_pretrained('microsoft/dit-base-finetuned-rvlcdip' )
lowercase__ : Union[str, Any] = AutoModelForImageClassification.from_pretrained('microsoft/dit-base-finetuned-rvlcdip' )
model.to(a )
from datasets import load_dataset
lowercase__ : str = load_dataset('nielsr/rvlcdip-demo' )
lowercase__ : Tuple = dataset['train'][0]['image'].convert('RGB' )
lowercase__ : int = image_processor(a , return_tensors='pt' ).to(a )
# forward pass
with torch.no_grad():
lowercase__ : List[str] = model(**a )
lowercase__ : List[Any] = outputs.logits
lowercase__ : Union[str, Any] = torch.Size((1, 1_6) )
self.assertEqual(logits.shape , a )
lowercase__ : Tuple = torch.tensor(
[-0.4_158, -0.4_092, -0.4_347] , device=a , dtype=torch.float , )
self.assertTrue(torch.allclose(logits[0, :3] , a , atol=1e-4 ) )
| 645 | 0 |
'''simple docstring'''
import argparse
import json
from collections import OrderedDict
from functools import partial
from pathlib import Path
import timm
import torch
from huggingface_hub import hf_hub_download
from transformers import LevitConfig, LevitForImageClassificationWithTeacher, LevitImageProcessor
from transformers.utils import logging
logging.set_verbosity_info()
lowerCAmelCase__ = logging.get_logger()
def __UpperCAmelCase ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = True) -> Any:
print(f'Converting {name}...')
with torch.no_grad():
if hidden_sizes == 128:
if name[-1] == "S":
UpperCamelCase__ : Any = timm.create_model('levit_128s' , pretrained=_lowerCAmelCase)
else:
UpperCamelCase__ : Tuple = timm.create_model('levit_128' , pretrained=_lowerCAmelCase)
if hidden_sizes == 192:
UpperCamelCase__ : str = timm.create_model('levit_192' , pretrained=_lowerCAmelCase)
if hidden_sizes == 256:
UpperCamelCase__ : str = timm.create_model('levit_256' , pretrained=_lowerCAmelCase)
if hidden_sizes == 384:
UpperCamelCase__ : Tuple = timm.create_model('levit_384' , pretrained=_lowerCAmelCase)
from_model.eval()
UpperCamelCase__ : Any = LevitForImageClassificationWithTeacher(_lowerCAmelCase).eval()
UpperCamelCase__ : Union[str, Any] = OrderedDict()
UpperCamelCase__ : Tuple = from_model.state_dict()
UpperCamelCase__ : Union[str, Any] = list(from_model.state_dict().keys())
UpperCamelCase__ : List[Any] = list(our_model.state_dict().keys())
print(len(_lowerCAmelCase) , len(_lowerCAmelCase))
for i in range(len(_lowerCAmelCase)):
UpperCamelCase__ : str = weights[og_keys[i]]
our_model.load_state_dict(_lowerCAmelCase)
UpperCamelCase__ : str = torch.randn((2, 3, 224, 224))
UpperCamelCase__ : Any = from_model(_lowerCAmelCase)
UpperCamelCase__ : List[Any] = our_model(_lowerCAmelCase).logits
assert torch.allclose(_lowerCAmelCase , _lowerCAmelCase), "The model logits don't match the original one."
UpperCamelCase__ : Dict = name
print(_lowerCAmelCase)
if push_to_hub:
our_model.save_pretrained(save_directory / checkpoint_name)
UpperCamelCase__ : List[str] = LevitImageProcessor()
image_processor.save_pretrained(save_directory / checkpoint_name)
print(f'Pushed {checkpoint_name}')
def __UpperCAmelCase ( lowerCamelCase_ , lowerCamelCase_ = None , lowerCamelCase_ = True) -> int:
UpperCamelCase__ : Union[str, Any] = "imagenet-1k-id2label.json"
UpperCamelCase__ : Union[str, Any] = 1_000
UpperCamelCase__ : str = (1, num_labels)
UpperCamelCase__ : List[str] = "huggingface/label-files"
UpperCamelCase__ : Optional[int] = num_labels
UpperCamelCase__ : List[Any] = json.load(open(hf_hub_download(_lowerCAmelCase , _lowerCAmelCase , repo_type='dataset') , 'r'))
UpperCamelCase__ : Union[str, Any] = {int(_lowerCAmelCase): v for k, v in idalabel.items()}
UpperCamelCase__ : str = idalabel
UpperCamelCase__ : List[str] = {v: k for k, v in idalabel.items()}
UpperCamelCase__ : Any = partial(_lowerCAmelCase , num_labels=_lowerCAmelCase , idalabel=_lowerCAmelCase , labelaid=_lowerCAmelCase)
UpperCamelCase__ : Any = {
"levit-128S": 128,
"levit-128": 128,
"levit-192": 192,
"levit-256": 256,
"levit-384": 384,
}
UpperCamelCase__ : str = {
"levit-128S": ImageNetPreTrainedConfig(
hidden_sizes=[128, 256, 384] , num_attention_heads=[4, 6, 8] , depths=[2, 3, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ),
"levit-128": ImageNetPreTrainedConfig(
hidden_sizes=[128, 256, 384] , num_attention_heads=[4, 8, 12] , depths=[4, 4, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ),
"levit-192": ImageNetPreTrainedConfig(
hidden_sizes=[192, 288, 384] , num_attention_heads=[3, 5, 6] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ),
"levit-256": ImageNetPreTrainedConfig(
hidden_sizes=[256, 384, 512] , num_attention_heads=[4, 6, 8] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ),
"levit-384": ImageNetPreTrainedConfig(
hidden_sizes=[384, 512, 768] , num_attention_heads=[6, 9, 12] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0.1 , ),
}
if model_name:
convert_weight_and_push(
names_to_hidden_sizes[model_name] , _lowerCAmelCase , names_to_config[model_name] , _lowerCAmelCase , _lowerCAmelCase)
else:
for model_name, config in names_to_config.items():
convert_weight_and_push(names_to_hidden_sizes[model_name] , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase)
return config, expected_shape
if __name__ == "__main__":
lowerCAmelCase__ = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--model_name',
default=None,
type=str,
help='The name of the model you wish to convert, it must be one of the supported Levit* architecture,',
)
parser.add_argument(
'--pytorch_dump_folder_path',
default='levit-dump-folder/',
type=Path,
required=False,
help='Path to the output PyTorch model directory.',
)
parser.add_argument('--push_to_hub', action='store_true', help='Push model and image processor to the hub')
parser.add_argument(
'--no-push_to_hub',
dest='push_to_hub',
action='store_false',
help='Do not push model and image processor to the hub',
)
lowerCAmelCase__ = parser.parse_args()
lowerCAmelCase__ = args.pytorch_dump_folder_path
pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True)
convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
| 596 |
'''simple docstring'''
import argparse
import json
import pickle
from pathlib import Path
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, MaskFormerImageProcessor, SwinConfig
from transformers.utils import logging
logging.set_verbosity_info()
UpperCAmelCase_ : Union[str, Any] = logging.get_logger(__name__)
def A_ ( _lowerCAmelCase : str ):
"""simple docstring"""
_lowerCamelCase : Union[str, Any] = SwinConfig.from_pretrained(
"microsoft/swin-tiny-patch4-window7-224" , out_features=["stage1", "stage2", "stage3", "stage4"] )
_lowerCamelCase : Dict = MaskFormerConfig(backbone_config=_lowerCAmelCase )
_lowerCamelCase : Tuple = "huggingface/label-files"
if "ade20k-full" in model_name:
# this should be ok
_lowerCamelCase : List[Any] = 847
_lowerCamelCase : str = "maskformer-ade20k-full-id2label.json"
elif "ade" in model_name:
# this should be ok
_lowerCamelCase : Optional[int] = 150
_lowerCamelCase : Union[str, Any] = "ade20k-id2label.json"
elif "coco-stuff" in model_name:
# this should be ok
_lowerCamelCase : Union[str, Any] = 171
_lowerCamelCase : str = "maskformer-coco-stuff-id2label.json"
elif "coco" in model_name:
# TODO
_lowerCamelCase : Optional[int] = 133
_lowerCamelCase : Any = "coco-panoptic-id2label.json"
elif "cityscapes" in model_name:
# this should be ok
_lowerCamelCase : str = 19
_lowerCamelCase : Tuple = "cityscapes-id2label.json"
elif "vistas" in model_name:
# this should be ok
_lowerCamelCase : List[Any] = 65
_lowerCamelCase : Optional[int] = "mapillary-vistas-id2label.json"
_lowerCamelCase : Any = json.load(open(hf_hub_download(_lowerCAmelCase , _lowerCAmelCase , repo_type="dataset" ) , "r" ) )
_lowerCamelCase : Optional[int] = {int(_lowerCAmelCase ): v for k, v in idalabel.items()}
return config
def A_ ( _lowerCAmelCase : Tuple ):
"""simple docstring"""
_lowerCamelCase : Any = []
# stem
# fmt: off
rename_keys.append(("backbone.patch_embed.proj.weight", "model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.weight") )
rename_keys.append(("backbone.patch_embed.proj.bias", "model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.bias") )
rename_keys.append(("backbone.patch_embed.norm.weight", "model.pixel_level_module.encoder.model.embeddings.norm.weight") )
rename_keys.append(("backbone.patch_embed.norm.bias", "model.pixel_level_module.encoder.model.embeddings.norm.bias") )
# stages
for i in range(len(config.backbone_config.depths ) ):
for j in range(config.backbone_config.depths[i] ):
rename_keys.append((F'backbone.layers.{i}.blocks.{j}.norm1.weight', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight') )
rename_keys.append((F'backbone.layers.{i}.blocks.{j}.norm1.bias', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias') )
rename_keys.append((F'backbone.layers.{i}.blocks.{j}.attn.relative_position_bias_table', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table') )
rename_keys.append((F'backbone.layers.{i}.blocks.{j}.attn.relative_position_index', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index') )
rename_keys.append((F'backbone.layers.{i}.blocks.{j}.attn.proj.weight', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight') )
rename_keys.append((F'backbone.layers.{i}.blocks.{j}.attn.proj.bias', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias') )
rename_keys.append((F'backbone.layers.{i}.blocks.{j}.norm2.weight', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight') )
rename_keys.append((F'backbone.layers.{i}.blocks.{j}.norm2.bias', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias') )
rename_keys.append((F'backbone.layers.{i}.blocks.{j}.mlp.fc1.weight', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight') )
rename_keys.append((F'backbone.layers.{i}.blocks.{j}.mlp.fc1.bias', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias') )
rename_keys.append((F'backbone.layers.{i}.blocks.{j}.mlp.fc2.weight', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.weight') )
rename_keys.append((F'backbone.layers.{i}.blocks.{j}.mlp.fc2.bias', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.bias') )
if i < 3:
rename_keys.append((F'backbone.layers.{i}.downsample.reduction.weight', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.reduction.weight') )
rename_keys.append((F'backbone.layers.{i}.downsample.norm.weight', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.weight') )
rename_keys.append((F'backbone.layers.{i}.downsample.norm.bias', F'model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.bias') )
rename_keys.append((F'backbone.norm{i}.weight', F'model.pixel_level_module.encoder.hidden_states_norms.{i}.weight') )
rename_keys.append((F'backbone.norm{i}.bias', F'model.pixel_level_module.encoder.hidden_states_norms.{i}.bias') )
# FPN
rename_keys.append(("sem_seg_head.layer_4.weight", "model.pixel_level_module.decoder.fpn.stem.0.weight") )
rename_keys.append(("sem_seg_head.layer_4.norm.weight", "model.pixel_level_module.decoder.fpn.stem.1.weight") )
rename_keys.append(("sem_seg_head.layer_4.norm.bias", "model.pixel_level_module.decoder.fpn.stem.1.bias") )
for source_index, target_index in zip(range(3 , 0 , -1 ) , range(0 , 3 ) ):
rename_keys.append((F'sem_seg_head.adapter_{source_index}.weight', F'model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.0.weight') )
rename_keys.append((F'sem_seg_head.adapter_{source_index}.norm.weight', F'model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.weight') )
rename_keys.append((F'sem_seg_head.adapter_{source_index}.norm.bias', F'model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.bias') )
rename_keys.append((F'sem_seg_head.layer_{source_index}.weight', F'model.pixel_level_module.decoder.fpn.layers.{target_index}.block.0.weight') )
rename_keys.append((F'sem_seg_head.layer_{source_index}.norm.weight', F'model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.weight') )
rename_keys.append((F'sem_seg_head.layer_{source_index}.norm.bias', F'model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.bias') )
rename_keys.append(("sem_seg_head.mask_features.weight", "model.pixel_level_module.decoder.mask_projection.weight") )
rename_keys.append(("sem_seg_head.mask_features.bias", "model.pixel_level_module.decoder.mask_projection.bias") )
# Transformer decoder
for idx in range(config.decoder_config.decoder_layers ):
# self-attention out projection
rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.weight', F'model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.weight') )
rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.bias', F'model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.bias') )
# cross-attention out projection
rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.weight', F'model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.weight') )
rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.bias', F'model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.bias') )
# MLP 1
rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.weight', F'model.transformer_module.decoder.layers.{idx}.fc1.weight') )
rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.bias', F'model.transformer_module.decoder.layers.{idx}.fc1.bias') )
# MLP 2
rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.weight', F'model.transformer_module.decoder.layers.{idx}.fc2.weight') )
rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.bias', F'model.transformer_module.decoder.layers.{idx}.fc2.bias') )
# layernorm 1 (self-attention layernorm)
rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.weight', F'model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.weight') )
rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.bias', F'model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.bias') )
# layernorm 2 (cross-attention layernorm)
rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.weight', F'model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.weight') )
rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.bias', F'model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.bias') )
# layernorm 3 (final layernorm)
rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.weight', F'model.transformer_module.decoder.layers.{idx}.final_layer_norm.weight') )
rename_keys.append((F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.bias', F'model.transformer_module.decoder.layers.{idx}.final_layer_norm.bias') )
rename_keys.append(("sem_seg_head.predictor.transformer.decoder.norm.weight", "model.transformer_module.decoder.layernorm.weight") )
rename_keys.append(("sem_seg_head.predictor.transformer.decoder.norm.bias", "model.transformer_module.decoder.layernorm.bias") )
# heads on top
rename_keys.append(("sem_seg_head.predictor.query_embed.weight", "model.transformer_module.queries_embedder.weight") )
rename_keys.append(("sem_seg_head.predictor.input_proj.weight", "model.transformer_module.input_projection.weight") )
rename_keys.append(("sem_seg_head.predictor.input_proj.bias", "model.transformer_module.input_projection.bias") )
rename_keys.append(("sem_seg_head.predictor.class_embed.weight", "class_predictor.weight") )
rename_keys.append(("sem_seg_head.predictor.class_embed.bias", "class_predictor.bias") )
for i in range(3 ):
rename_keys.append((F'sem_seg_head.predictor.mask_embed.layers.{i}.weight', F'mask_embedder.{i}.0.weight') )
rename_keys.append((F'sem_seg_head.predictor.mask_embed.layers.{i}.bias', F'mask_embedder.{i}.0.bias') )
# fmt: on
return rename_keys
def A_ ( _lowerCAmelCase : List[Any] , _lowerCAmelCase : Optional[int] , _lowerCAmelCase : List[str] ):
"""simple docstring"""
_lowerCamelCase : Tuple = dct.pop(_lowerCAmelCase )
_lowerCamelCase : str = val
def A_ ( _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Any ):
"""simple docstring"""
_lowerCamelCase : str = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )]
for i in range(len(backbone_config.depths ) ):
_lowerCamelCase : int = num_features[i]
for j in range(backbone_config.depths[i] ):
# fmt: off
# read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias)
_lowerCamelCase : Union[str, Any] = state_dict.pop(F'backbone.layers.{i}.blocks.{j}.attn.qkv.weight' )
_lowerCamelCase : List[str] = state_dict.pop(F'backbone.layers.{i}.blocks.{j}.attn.qkv.bias' )
# next, add query, keys and values (in that order) to the state dict
_lowerCamelCase : Optional[int] = in_proj_weight[:dim, :]
_lowerCamelCase : Optional[int] = in_proj_bias[: dim]
_lowerCamelCase : List[str] = in_proj_weight[
dim : dim * 2, :
]
_lowerCamelCase : List[Any] = in_proj_bias[
dim : dim * 2
]
_lowerCamelCase : List[Any] = in_proj_weight[
-dim :, :
]
_lowerCamelCase : Union[str, Any] = in_proj_bias[-dim :]
# fmt: on
def A_ ( _lowerCAmelCase : Tuple , _lowerCAmelCase : Any ):
"""simple docstring"""
_lowerCamelCase : int = config.decoder_config.hidden_size
for idx in range(config.decoder_config.decoder_layers ):
# read in weights + bias of self-attention input projection layer (in the original implementation, this is a single matrix + bias)
_lowerCamelCase : Tuple = state_dict.pop(F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_weight' )
_lowerCamelCase : Optional[int] = state_dict.pop(F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_bias' )
# next, add query, keys and values (in that order) to the state dict
_lowerCamelCase : Optional[Any] = in_proj_weight[: hidden_size, :]
_lowerCamelCase : Optional[int] = in_proj_bias[:config.hidden_size]
_lowerCamelCase : str = in_proj_weight[hidden_size : hidden_size * 2, :]
_lowerCamelCase : Dict = in_proj_bias[hidden_size : hidden_size * 2]
_lowerCamelCase : Any = in_proj_weight[-hidden_size :, :]
_lowerCamelCase : Any = in_proj_bias[-hidden_size :]
# read in weights + bias of cross-attention input projection layer (in the original implementation, this is a single matrix + bias)
_lowerCamelCase : Optional[int] = state_dict.pop(F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_weight' )
_lowerCamelCase : List[Any] = state_dict.pop(F'sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_bias' )
# next, add query, keys and values (in that order) to the state dict
_lowerCamelCase : Tuple = in_proj_weight[: hidden_size, :]
_lowerCamelCase : str = in_proj_bias[:config.hidden_size]
_lowerCamelCase : str = in_proj_weight[hidden_size : hidden_size * 2, :]
_lowerCamelCase : Optional[int] = in_proj_bias[hidden_size : hidden_size * 2]
_lowerCamelCase : int = in_proj_weight[-hidden_size :, :]
_lowerCamelCase : Optional[Any] = in_proj_bias[-hidden_size :]
# fmt: on
def A_ ( ):
"""simple docstring"""
_lowerCamelCase : List[Any] = "http://images.cocodataset.org/val2017/000000039769.jpg"
_lowerCamelCase : Optional[Any] = Image.open(requests.get(_lowerCAmelCase , stream=_lowerCAmelCase ).raw )
return im
@torch.no_grad()
def A_ ( _lowerCAmelCase : str , _lowerCAmelCase : str , _lowerCAmelCase : str , _lowerCAmelCase : bool = False ):
"""simple docstring"""
_lowerCamelCase : Tuple = get_maskformer_config(_lowerCAmelCase )
# load original state_dict
with open(_lowerCAmelCase , "rb" ) as f:
_lowerCamelCase : List[Any] = pickle.load(_lowerCAmelCase )
_lowerCamelCase : Optional[Any] = data["model"]
# for name, param in state_dict.items():
# print(name, param.shape)
# rename keys
_lowerCamelCase : List[Any] = create_rename_keys(_lowerCAmelCase )
for src, dest in rename_keys:
rename_key(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase )
read_in_swin_q_k_v(_lowerCAmelCase , config.backbone_config )
read_in_decoder_q_k_v(_lowerCAmelCase , _lowerCAmelCase )
# update to torch tensors
for key, value in state_dict.items():
_lowerCamelCase : Dict = torch.from_numpy(_lowerCAmelCase )
# load 🤗 model
_lowerCamelCase : int = MaskFormerForInstanceSegmentation(_lowerCAmelCase )
model.eval()
for name, param in model.named_parameters():
print(_lowerCAmelCase , param.shape )
_lowerCamelCase , _lowerCamelCase : Union[str, Any] = model.load_state_dict(_lowerCAmelCase , strict=_lowerCAmelCase )
assert missing_keys == [
"model.pixel_level_module.encoder.model.layernorm.weight",
"model.pixel_level_module.encoder.model.layernorm.bias",
]
assert len(_lowerCAmelCase ) == 0, F'Unexpected keys: {unexpected_keys}'
# verify results
_lowerCamelCase : Any = prepare_img()
if "vistas" in model_name:
_lowerCamelCase : Any = 65
elif "cityscapes" in model_name:
_lowerCamelCase : Optional[Any] = 65535
else:
_lowerCamelCase : str = 255
_lowerCamelCase : List[str] = True if "ade" in model_name else False
_lowerCamelCase : Union[str, Any] = MaskFormerImageProcessor(ignore_index=_lowerCAmelCase , reduce_labels=_lowerCAmelCase )
_lowerCamelCase : int = image_processor(_lowerCAmelCase , return_tensors="pt" )
_lowerCamelCase : Tuple = model(**_lowerCAmelCase )
print("Logits:" , outputs.class_queries_logits[0, :3, :3] )
if model_name == "maskformer-swin-tiny-ade":
_lowerCamelCase : Tuple = torch.tensor(
[[3.6_3_5_3, -4.4_7_7_0, -2.6_0_6_5], [0.5_0_8_1, -4.2_3_9_4, -3.5_3_4_3], [2.1_9_0_9, -5.0_3_5_3, -1.9_3_2_3]] )
assert torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCAmelCase , atol=1E-4 )
print("Looks ok!" )
if pytorch_dump_folder_path is not None:
print(F'Saving model and image processor to {pytorch_dump_folder_path}' )
Path(_lowerCAmelCase ).mkdir(exist_ok=_lowerCAmelCase )
model.save_pretrained(_lowerCAmelCase )
image_processor.save_pretrained(_lowerCAmelCase )
if push_to_hub:
print("Pushing model and image processor to the hub..." )
model.push_to_hub(F'nielsr/{model_name}' )
image_processor.push_to_hub(F'nielsr/{model_name}' )
if __name__ == "__main__":
UpperCAmelCase_ : int = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--model_name',
default='maskformer-swin-tiny-ade',
type=str,
help=('Name of the MaskFormer model you\'d like to convert',),
)
parser.add_argument(
'--checkpoint_path',
default='/Users/nielsrogge/Documents/MaskFormer_checkpoints/MaskFormer-Swin-tiny-ADE20k/model.pkl',
type=str,
help='Path to the original state dict (.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.'
)
UpperCAmelCase_ : int = parser.parse_args()
convert_maskformer_checkpoint(
args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub
) | 44 | 0 |
'''simple docstring'''
def lowerCAmelCase_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> int:
"""simple docstring"""
def update_area_of_max_square(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> int:
# BASE CASE
if row >= rows or col >= cols:
return 0
_SCREAMING_SNAKE_CASE = update_area_of_max_square(a_ , col + 1 )
_SCREAMING_SNAKE_CASE = update_area_of_max_square(row + 1 , col + 1 )
_SCREAMING_SNAKE_CASE = update_area_of_max_square(row + 1 , a_ )
if mat[row][col]:
_SCREAMING_SNAKE_CASE = 1 + min([right, diagonal, down] )
_SCREAMING_SNAKE_CASE = max(largest_square_area[0] , a_ )
return sub_problem_sol
else:
return 0
_SCREAMING_SNAKE_CASE = [0]
update_area_of_max_square(0 , 0 )
return largest_square_area[0]
def lowerCAmelCase_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> int:
"""simple docstring"""
def update_area_of_max_square_using_dp_array(
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> int:
if row >= rows or col >= cols:
return 0
if dp_array[row][col] != -1:
return dp_array[row][col]
_SCREAMING_SNAKE_CASE = update_area_of_max_square_using_dp_array(a_ , col + 1 , a_ )
_SCREAMING_SNAKE_CASE = update_area_of_max_square_using_dp_array(row + 1 , col + 1 , a_ )
_SCREAMING_SNAKE_CASE = update_area_of_max_square_using_dp_array(row + 1 , a_ , a_ )
if mat[row][col]:
_SCREAMING_SNAKE_CASE = 1 + min([right, diagonal, down] )
_SCREAMING_SNAKE_CASE = max(largest_square_area[0] , a_ )
_SCREAMING_SNAKE_CASE = sub_problem_sol
return sub_problem_sol
else:
return 0
_SCREAMING_SNAKE_CASE = [0]
_SCREAMING_SNAKE_CASE = [[-1] * cols for _ in range(a_ )]
update_area_of_max_square_using_dp_array(0 , 0 , a_ )
return largest_square_area[0]
def lowerCAmelCase_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> int:
"""simple docstring"""
_SCREAMING_SNAKE_CASE = [[0] * (cols + 1) for _ in range(rows + 1 )]
_SCREAMING_SNAKE_CASE = 0
for row in range(rows - 1 , -1 , -1 ):
for col in range(cols - 1 , -1 , -1 ):
_SCREAMING_SNAKE_CASE = dp_array[row][col + 1]
_SCREAMING_SNAKE_CASE = dp_array[row + 1][col + 1]
_SCREAMING_SNAKE_CASE = dp_array[row + 1][col]
if mat[row][col] == 1:
_SCREAMING_SNAKE_CASE = 1 + min(a_ , a_ , a_ )
_SCREAMING_SNAKE_CASE = max(dp_array[row][col] , a_ )
else:
_SCREAMING_SNAKE_CASE = 0
return largest_square_area
def lowerCAmelCase_ ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) -> int:
"""simple docstring"""
_SCREAMING_SNAKE_CASE = [0] * (cols + 1)
_SCREAMING_SNAKE_CASE = [0] * (cols + 1)
_SCREAMING_SNAKE_CASE = 0
for row in range(rows - 1 , -1 , -1 ):
for col in range(cols - 1 , -1 , -1 ):
_SCREAMING_SNAKE_CASE = current_row[col + 1]
_SCREAMING_SNAKE_CASE = next_row[col + 1]
_SCREAMING_SNAKE_CASE = next_row[col]
if mat[row][col] == 1:
_SCREAMING_SNAKE_CASE = 1 + min(a_ , a_ , a_ )
_SCREAMING_SNAKE_CASE = max(current_row[col] , a_ )
else:
_SCREAMING_SNAKE_CASE = 0
_SCREAMING_SNAKE_CASE = current_row
return largest_square_area
if __name__ == "__main__":
import doctest
doctest.testmod()
print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))
| 712 |
'''simple docstring'''
import os
import unittest
from transformers import MobileBertTokenizer, MobileBertTokenizerFast
from transformers.models.bert.tokenization_bert import (
VOCAB_FILES_NAMES,
BasicTokenizer,
WordpieceTokenizer,
_is_control,
_is_punctuation,
_is_whitespace,
)
from transformers.testing_utils import require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english
@require_tokenizers
class _a (_lowerCamelCase , unittest.TestCase):
"""simple docstring"""
SCREAMING_SNAKE_CASE = MobileBertTokenizer
SCREAMING_SNAKE_CASE = MobileBertTokenizerFast
SCREAMING_SNAKE_CASE = True
SCREAMING_SNAKE_CASE = True
SCREAMING_SNAKE_CASE = filter_non_english
SCREAMING_SNAKE_CASE = 'google/mobilebert-uncased'
def UpperCamelCase ( self ) -> Any:
super().setUp()
_SCREAMING_SNAKE_CASE = [
"""[UNK]""",
"""[CLS]""",
"""[SEP]""",
"""[PAD]""",
"""[MASK]""",
"""want""",
"""##want""",
"""##ed""",
"""wa""",
"""un""",
"""runn""",
"""##ing""",
""",""",
"""low""",
"""lowest""",
]
_SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] )
with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer:
vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) )
_SCREAMING_SNAKE_CASE = [
(tokenizer_def[0], self.pre_trained_model_path, tokenizer_def[2]) # else the 'google/' prefix is stripped
for tokenizer_def in self.tokenizers_list
]
def UpperCamelCase ( self , A__ ) -> List[str]:
_SCREAMING_SNAKE_CASE = """UNwant\u00E9d,running"""
_SCREAMING_SNAKE_CASE = """unwanted, running"""
return input_text, output_text
def UpperCamelCase ( self ) -> Any:
_SCREAMING_SNAKE_CASE = self.tokenizer_class(self.vocab_file )
_SCREAMING_SNAKE_CASE = tokenizer.tokenize("""UNwant\u00E9d,running""" )
self.assertListEqual(A__ , ["""un""", """##want""", """##ed""", """,""", """runn""", """##ing"""] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(A__ ) , [9, 6, 7, 12, 10, 11] )
def UpperCamelCase ( self ) -> Optional[int]:
if not self.test_rust_tokenizer:
return
_SCREAMING_SNAKE_CASE = self.get_tokenizer()
_SCREAMING_SNAKE_CASE = self.get_rust_tokenizer()
_SCREAMING_SNAKE_CASE = """UNwant\u00E9d,running"""
_SCREAMING_SNAKE_CASE = tokenizer.tokenize(A__ )
_SCREAMING_SNAKE_CASE = rust_tokenizer.tokenize(A__ )
self.assertListEqual(A__ , A__ )
_SCREAMING_SNAKE_CASE = tokenizer.encode(A__ , add_special_tokens=A__ )
_SCREAMING_SNAKE_CASE = rust_tokenizer.encode(A__ , add_special_tokens=A__ )
self.assertListEqual(A__ , A__ )
_SCREAMING_SNAKE_CASE = self.get_rust_tokenizer()
_SCREAMING_SNAKE_CASE = tokenizer.encode(A__ )
_SCREAMING_SNAKE_CASE = rust_tokenizer.encode(A__ )
self.assertListEqual(A__ , A__ )
# With lower casing
_SCREAMING_SNAKE_CASE = self.get_tokenizer(do_lower_case=A__ )
_SCREAMING_SNAKE_CASE = self.get_rust_tokenizer(do_lower_case=A__ )
_SCREAMING_SNAKE_CASE = """UNwant\u00E9d,running"""
_SCREAMING_SNAKE_CASE = tokenizer.tokenize(A__ )
_SCREAMING_SNAKE_CASE = rust_tokenizer.tokenize(A__ )
self.assertListEqual(A__ , A__ )
_SCREAMING_SNAKE_CASE = tokenizer.encode(A__ , add_special_tokens=A__ )
_SCREAMING_SNAKE_CASE = rust_tokenizer.encode(A__ , add_special_tokens=A__ )
self.assertListEqual(A__ , A__ )
_SCREAMING_SNAKE_CASE = self.get_rust_tokenizer()
_SCREAMING_SNAKE_CASE = tokenizer.encode(A__ )
_SCREAMING_SNAKE_CASE = rust_tokenizer.encode(A__ )
self.assertListEqual(A__ , A__ )
def UpperCamelCase ( self ) -> Tuple:
_SCREAMING_SNAKE_CASE = BasicTokenizer()
self.assertListEqual(tokenizer.tokenize("""ah\u535A\u63A8zz""" ) , ["""ah""", """\u535A""", """\u63A8""", """zz"""] )
def UpperCamelCase ( self ) -> List[Any]:
_SCREAMING_SNAKE_CASE = BasicTokenizer(do_lower_case=A__ )
self.assertListEqual(
tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] )
self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] )
def UpperCamelCase ( self ) -> Optional[Any]:
_SCREAMING_SNAKE_CASE = BasicTokenizer(do_lower_case=A__ , strip_accents=A__ )
self.assertListEqual(
tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hällo""", """!""", """how""", """are""", """you""", """?"""] )
self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""h\u00E9llo"""] )
def UpperCamelCase ( self ) -> Any:
_SCREAMING_SNAKE_CASE = BasicTokenizer(do_lower_case=A__ , strip_accents=A__ )
self.assertListEqual(
tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] )
self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] )
def UpperCamelCase ( self ) -> Any:
_SCREAMING_SNAKE_CASE = BasicTokenizer(do_lower_case=A__ )
self.assertListEqual(
tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""hallo""", """!""", """how""", """are""", """you""", """?"""] )
self.assertListEqual(tokenizer.tokenize("""H\u00E9llo""" ) , ["""hello"""] )
def UpperCamelCase ( self ) -> str:
_SCREAMING_SNAKE_CASE = BasicTokenizer(do_lower_case=A__ )
self.assertListEqual(
tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] )
def UpperCamelCase ( self ) -> Dict:
_SCREAMING_SNAKE_CASE = BasicTokenizer(do_lower_case=A__ , strip_accents=A__ )
self.assertListEqual(
tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HäLLo""", """!""", """how""", """Are""", """yoU""", """?"""] )
def UpperCamelCase ( self ) -> Union[str, Any]:
_SCREAMING_SNAKE_CASE = BasicTokenizer(do_lower_case=A__ , strip_accents=A__ )
self.assertListEqual(
tokenizer.tokenize(""" \tHäLLo!how \n Are yoU? """ ) , ["""HaLLo""", """!""", """how""", """Are""", """yoU""", """?"""] )
def UpperCamelCase ( self ) -> str:
_SCREAMING_SNAKE_CASE = BasicTokenizer(do_lower_case=A__ , never_split=["""[UNK]"""] )
self.assertListEqual(
tokenizer.tokenize(""" \tHeLLo!how \n Are yoU? [UNK]""" ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?""", """[UNK]"""] )
def UpperCamelCase ( self ) -> Tuple:
_SCREAMING_SNAKE_CASE = ["""[UNK]""", """[CLS]""", """[SEP]""", """want""", """##want""", """##ed""", """wa""", """un""", """runn""", """##ing"""]
_SCREAMING_SNAKE_CASE = {}
for i, token in enumerate(A__ ):
_SCREAMING_SNAKE_CASE = i
_SCREAMING_SNAKE_CASE = WordpieceTokenizer(vocab=A__ , unk_token="""[UNK]""" )
self.assertListEqual(tokenizer.tokenize("""""" ) , [] )
self.assertListEqual(tokenizer.tokenize("""unwanted running""" ) , ["""un""", """##want""", """##ed""", """runn""", """##ing"""] )
self.assertListEqual(tokenizer.tokenize("""unwantedX running""" ) , ["""[UNK]""", """runn""", """##ing"""] )
def UpperCamelCase ( self ) -> str:
self.assertTrue(_is_whitespace(""" """ ) )
self.assertTrue(_is_whitespace("""\t""" ) )
self.assertTrue(_is_whitespace("""\r""" ) )
self.assertTrue(_is_whitespace("""\n""" ) )
self.assertTrue(_is_whitespace("""\u00A0""" ) )
self.assertFalse(_is_whitespace("""A""" ) )
self.assertFalse(_is_whitespace("""-""" ) )
def UpperCamelCase ( self ) -> Union[str, Any]:
self.assertTrue(_is_control("""\u0005""" ) )
self.assertFalse(_is_control("""A""" ) )
self.assertFalse(_is_control(""" """ ) )
self.assertFalse(_is_control("""\t""" ) )
self.assertFalse(_is_control("""\r""" ) )
def UpperCamelCase ( self ) -> Dict:
self.assertTrue(_is_punctuation("""-""" ) )
self.assertTrue(_is_punctuation("""$""" ) )
self.assertTrue(_is_punctuation("""`""" ) )
self.assertTrue(_is_punctuation(""".""" ) )
self.assertFalse(_is_punctuation("""A""" ) )
self.assertFalse(_is_punctuation(""" """ ) )
def UpperCamelCase ( self ) -> str:
_SCREAMING_SNAKE_CASE = self.get_tokenizer()
_SCREAMING_SNAKE_CASE = self.get_rust_tokenizer()
# Example taken from the issue https://github.com/huggingface/tokenizers/issues/340
self.assertListEqual([tokenizer.tokenize(A__ ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] )
self.assertListEqual(
[rust_tokenizer.tokenize(A__ ) for t in ["""Test""", """\xad""", """test"""]] , [["""[UNK]"""], [], ["""[UNK]"""]] )
@slow
def UpperCamelCase ( self ) -> Any:
_SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained("""google/mobilebert-uncased""" )
_SCREAMING_SNAKE_CASE = tokenizer.encode("""sequence builders""" , add_special_tokens=A__ )
_SCREAMING_SNAKE_CASE = tokenizer.encode("""multi-sequence build""" , add_special_tokens=A__ )
_SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(A__ )
_SCREAMING_SNAKE_CASE = tokenizer.build_inputs_with_special_tokens(A__ , A__ )
assert encoded_sentence == [1_01] + text + [1_02]
assert encoded_pair == [1_01] + text + [1_02] + text_a + [1_02]
def UpperCamelCase ( self ) -> List[str]:
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ):
_SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(A__ , **A__ )
_SCREAMING_SNAKE_CASE = F"A, naïve {tokenizer_r.mask_token} AllenNLP sentence."
_SCREAMING_SNAKE_CASE = tokenizer_r.encode_plus(
A__ , return_attention_mask=A__ , return_token_type_ids=A__ , return_offsets_mapping=A__ , add_special_tokens=A__ , )
_SCREAMING_SNAKE_CASE = tokenizer_r.do_lower_case if hasattr(A__ , """do_lower_case""" ) else False
_SCREAMING_SNAKE_CASE = (
[
((0, 0), tokenizer_r.cls_token),
((0, 1), """A"""),
((1, 2), ""","""),
((3, 5), """na"""),
((5, 6), """##ï"""),
((6, 8), """##ve"""),
((9, 15), tokenizer_r.mask_token),
((16, 21), """Allen"""),
((21, 23), """##NL"""),
((23, 24), """##P"""),
((25, 33), """sentence"""),
((33, 34), """."""),
((0, 0), tokenizer_r.sep_token),
]
if not do_lower_case
else [
((0, 0), tokenizer_r.cls_token),
((0, 1), """a"""),
((1, 2), ""","""),
((3, 8), """naive"""),
((9, 15), tokenizer_r.mask_token),
((16, 21), """allen"""),
((21, 23), """##nl"""),
((23, 24), """##p"""),
((25, 33), """sentence"""),
((33, 34), """."""),
((0, 0), tokenizer_r.sep_token),
]
)
self.assertEqual(
[e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens["""input_ids"""] ) )
self.assertEqual([e[0] for e in expected_results] , tokens["""offset_mapping"""] )
def UpperCamelCase ( self ) -> Any:
_SCREAMING_SNAKE_CASE = ["""的""", """人""", """有"""]
_SCREAMING_SNAKE_CASE = """""".join(A__ )
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ):
_SCREAMING_SNAKE_CASE = True
_SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(A__ , **A__ )
_SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(A__ , **A__ )
_SCREAMING_SNAKE_CASE = tokenizer_p.encode(A__ , add_special_tokens=A__ )
_SCREAMING_SNAKE_CASE = tokenizer_r.encode(A__ , add_special_tokens=A__ )
_SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(A__ )
_SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(A__ )
# it is expected that each Chinese character is not preceded by "##"
self.assertListEqual(A__ , A__ )
self.assertListEqual(A__ , A__ )
_SCREAMING_SNAKE_CASE = False
_SCREAMING_SNAKE_CASE = self.rust_tokenizer_class.from_pretrained(A__ , **A__ )
_SCREAMING_SNAKE_CASE = self.tokenizer_class.from_pretrained(A__ , **A__ )
_SCREAMING_SNAKE_CASE = tokenizer_r.encode(A__ , add_special_tokens=A__ )
_SCREAMING_SNAKE_CASE = tokenizer_p.encode(A__ , add_special_tokens=A__ )
_SCREAMING_SNAKE_CASE = tokenizer_r.convert_ids_to_tokens(A__ )
_SCREAMING_SNAKE_CASE = tokenizer_p.convert_ids_to_tokens(A__ )
# it is expected that only the first Chinese character is not preceded by "##".
_SCREAMING_SNAKE_CASE = [
F"##{token}" if idx != 0 else token for idx, token in enumerate(A__ )
]
self.assertListEqual(A__ , A__ )
self.assertListEqual(A__ , A__ )
| 0 | 0 |
import re
import time
from typing import Optional
import IPython.display as disp
from ..trainer_callback import TrainerCallback
from ..trainer_utils import IntervalStrategy, has_length
def UpperCamelCase_( lowerCamelCase_ ) -> int:
_lowercase : List[str] = int(lowerCamelCase_ )
_lowercase , _lowercase , _lowercase : Optional[Any] = t // 3600, (t // 60) % 60, t % 60
return F'''{h}:{m:02d}:{s:02d}''' if h != 0 else F'''{m:02d}:{s:02d}'''
def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_=300 ) -> Dict:
# docstyle-ignore
return F'''
<div>
{prefix}
<progress value=\'{value}\' max=\'{total}\' style=\'width:{width}px; height:20px; vertical-align: middle;\'></progress>
{label}
</div>
'''
def UpperCamelCase_( lowerCamelCase_ ) -> Any:
_lowercase : int = '<table border="1" class="dataframe">\n'
html_code += """ <thead>\n <tr style="text-align: left;">\n"""
for i in items[0]:
html_code += F''' <th>{i}</th>\n'''
html_code += " </tr>\n </thead>\n <tbody>\n"
for line in items[1:]:
html_code += " <tr>\n"
for elt in line:
_lowercase : Any = F'''{elt:.6f}''' if isinstance(lowerCamelCase_ , lowerCamelCase_ ) else str(lowerCamelCase_ )
html_code += F''' <td>{elt}</td>\n'''
html_code += " </tr>\n"
html_code += " </tbody>\n</table><p>"
return html_code
class _lowerCamelCase:
lowercase_ : str = 5
lowercase_ : str = 0.2
def __init__( self, lowerCamelCase, lowerCamelCase = None, lowerCamelCase = True, lowerCamelCase = None, lowerCamelCase = 3_00, ) -> Optional[Any]:
"""simple docstring"""
_lowercase : Optional[int] = total
_lowercase : Optional[int] = '' if prefix is None else prefix
_lowercase : Tuple = leave
_lowercase : str = parent
_lowercase : str = width
_lowercase : List[Any] = None
_lowercase : List[str] = None
_lowercase : Tuple = None
def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase = False, lowerCamelCase = None) -> Dict:
"""simple docstring"""
_lowercase : Any = value
if comment is not None:
_lowercase : Union[str, Any] = comment
if self.last_value is None:
_lowercase : Dict = time.time()
_lowercase : Tuple = value
_lowercase : str = None
_lowercase : Optional[int] = self.warmup
_lowercase : Optional[Any] = 1
self.update_bar(lowerCamelCase)
elif value <= self.last_value and not force_update:
return
elif force_update or self.first_calls > 0 or value >= min(self.last_value + self.wait_for, self.total):
if self.first_calls > 0:
self.first_calls -= 1
_lowercase : List[str] = time.time()
_lowercase : Tuple = current_time - self.start_time
# We could have value = self.start_value if the update is called twixe with the same start value.
if value > self.start_value:
_lowercase : Dict = self.elapsed_time / (value - self.start_value)
else:
_lowercase : int = None
if value >= self.total:
_lowercase : Dict = self.total
_lowercase : List[str] = None
if not self.leave:
self.close()
elif self.average_time_per_item is not None:
_lowercase : Optional[int] = self.average_time_per_item * (self.total - value)
self.update_bar(lowerCamelCase)
_lowercase : int = value
_lowercase : Tuple = current_time
if self.average_time_per_item is None:
_lowercase : str = 1
else:
_lowercase : int = max(int(self.update_every / self.average_time_per_item), 1)
def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase=None) -> Optional[Any]:
"""simple docstring"""
_lowercase : List[Any] = ' ' * (len(str(self.total)) - len(str(lowerCamelCase))) + str(lowerCamelCase)
if self.elapsed_time is None:
_lowercase : int = F'''[{spaced_value}/{self.total} : < :'''
elif self.predicted_remaining is None:
_lowercase : Union[str, Any] = F'''[{spaced_value}/{self.total} {format_time(self.elapsed_time)}'''
else:
_lowercase : Union[str, Any] = (
F'''[{spaced_value}/{self.total} {format_time(self.elapsed_time)} <'''
F''' {format_time(self.predicted_remaining)}'''
)
self.label += F''', {1/self.average_time_per_item:.2f} it/s'''
self.label += "]" if self.comment is None or len(self.comment) == 0 else F''', {self.comment}]'''
self.display()
def UpperCamelCase ( self) -> List[Any]:
"""simple docstring"""
_lowercase : Any = html_progress_bar(self.value, self.total, self.prefix, self.label, self.width)
if self.parent is not None:
# If this is a child bar, the parent will take care of the display.
self.parent.display()
return
if self.output is None:
_lowercase : Optional[Any] = disp.display(disp.HTML(self.html_code), display_id=lowerCamelCase)
else:
self.output.update(disp.HTML(self.html_code))
def UpperCamelCase ( self) -> Optional[Any]:
"""simple docstring"""
if self.parent is None and self.output is not None:
self.output.update(disp.HTML(''))
class _lowerCamelCase( _a ):
def __init__( self, lowerCamelCase, lowerCamelCase=None) -> int:
"""simple docstring"""
super().__init__(lowerCamelCase)
_lowercase : Optional[Any] = None if column_names is None else [column_names]
_lowercase : Any = None
def UpperCamelCase ( self) -> List[Any]:
"""simple docstring"""
_lowercase : Any = html_progress_bar(self.value, self.total, self.prefix, self.label, self.width)
if self.inner_table is not None:
self.html_code += text_to_html_table(self.inner_table)
if self.child_bar is not None:
self.html_code += self.child_bar.html_code
if self.output is None:
_lowercase : Dict = disp.display(disp.HTML(self.html_code), display_id=lowerCamelCase)
else:
self.output.update(disp.HTML(self.html_code))
def UpperCamelCase ( self, lowerCamelCase) -> Dict:
"""simple docstring"""
if self.inner_table is None:
_lowercase : Dict = [list(values.keys()), list(values.values())]
else:
_lowercase : Tuple = self.inner_table[0]
if len(self.inner_table) == 1:
# We give a chance to update the column names at the first iteration
for key in values.keys():
if key not in columns:
columns.append(lowerCamelCase)
_lowercase : str = columns
self.inner_table.append([values[c] for c in columns])
def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase=None, lowerCamelCase=3_00) -> Union[str, Any]:
"""simple docstring"""
_lowercase : List[str] = NotebookProgressBar(lowerCamelCase, prefix=lowerCamelCase, parent=self, width=lowerCamelCase)
return self.child_bar
def UpperCamelCase ( self) -> Union[str, Any]:
"""simple docstring"""
_lowercase : Optional[Any] = None
self.display()
class _lowerCamelCase( _a ):
def __init__( self) -> List[Any]:
"""simple docstring"""
_lowercase : Union[str, Any] = None
_lowercase : Dict = None
_lowercase : Dict = False
def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, **lowerCamelCase) -> Dict:
"""simple docstring"""
_lowercase : Dict = 'Epoch' if args.evaluation_strategy == IntervalStrategy.EPOCH else 'Step'
_lowercase : Dict = 0
_lowercase : Tuple = 0
_lowercase : int = [self.first_column] + ['Training Loss']
if args.evaluation_strategy != IntervalStrategy.NO:
column_names.append('Validation Loss')
_lowercase : Union[str, Any] = NotebookTrainingTracker(state.max_steps, lowerCamelCase)
def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, **lowerCamelCase) -> Union[str, Any]:
"""simple docstring"""
_lowercase : Any = int(state.epoch) if int(state.epoch) == state.epoch else F'''{state.epoch:.2f}'''
self.training_tracker.update(
state.global_step + 1, comment=F'''Epoch {epoch}/{state.num_train_epochs}''', force_update=self._force_next_update, )
_lowercase : str = False
def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase=None, **lowerCamelCase) -> Any:
"""simple docstring"""
if not has_length(lowerCamelCase):
return
if self.prediction_bar is None:
if self.training_tracker is not None:
_lowercase : Optional[int] = self.training_tracker.add_child(len(lowerCamelCase))
else:
_lowercase : Optional[int] = NotebookProgressBar(len(lowerCamelCase))
self.prediction_bar.update(1)
else:
self.prediction_bar.update(self.prediction_bar.value + 1)
def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, **lowerCamelCase) -> Optional[int]:
"""simple docstring"""
if self.prediction_bar is not None:
self.prediction_bar.close()
_lowercase : Any = None
def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase=None, **lowerCamelCase) -> List[Any]:
"""simple docstring"""
if args.evaluation_strategy == IntervalStrategy.NO and "loss" in logs:
_lowercase : Dict = {'Training Loss': logs['loss']}
# First column is necessarily Step sine we're not in epoch eval strategy
_lowercase : List[Any] = state.global_step
self.training_tracker.write_line(lowerCamelCase)
def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase=None, **lowerCamelCase) -> List[str]:
"""simple docstring"""
if self.training_tracker is not None:
_lowercase : Tuple = {'Training Loss': 'No log', 'Validation Loss': 'No log'}
for log in reversed(state.log_history):
if "loss" in log:
_lowercase : int = log['loss']
break
if self.first_column == "Epoch":
_lowercase : Union[str, Any] = int(state.epoch)
else:
_lowercase : Optional[Any] = state.global_step
_lowercase : str = 'eval'
for k in metrics:
if k.endswith('_loss'):
_lowercase : str = re.sub(R'\_loss$', '', lowerCamelCase)
_lowercase : Tuple = metrics.pop('total_flos', lowerCamelCase)
_lowercase : List[str] = metrics.pop('epoch', lowerCamelCase)
_lowercase : List[Any] = metrics.pop(F'''{metric_key_prefix}_runtime''', lowerCamelCase)
_lowercase : Dict = metrics.pop(F'''{metric_key_prefix}_samples_per_second''', lowerCamelCase)
_lowercase : Tuple = metrics.pop(F'''{metric_key_prefix}_steps_per_second''', lowerCamelCase)
_lowercase : List[str] = metrics.pop(F'''{metric_key_prefix}_jit_compilation_time''', lowerCamelCase)
for k, v in metrics.items():
if k == F'''{metric_key_prefix}_loss''':
_lowercase : Union[str, Any] = v
else:
_lowercase : Optional[Any] = k.split('_')
_lowercase : Optional[int] = ' '.join([part.capitalize() for part in splits[1:]])
_lowercase : Tuple = v
self.training_tracker.write_line(lowerCamelCase)
self.training_tracker.remove_child()
_lowercase : str = None
# Evaluation takes a long time so we should force the next update.
_lowercase : Optional[Any] = True
def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, **lowerCamelCase) -> Union[str, Any]:
"""simple docstring"""
self.training_tracker.update(
state.global_step, comment=F'''Epoch {int(state.epoch)}/{state.num_train_epochs}''', force_update=lowerCamelCase)
_lowercase : Any = None
| 89 |
"""simple docstring"""
_snake_case = {'a': ['c', 'b'], 'b': ['d', 'e'], 'c': [], 'd': [], 'e': []}
_snake_case = ['a', 'b', 'c', 'd', 'e']
def lowerCAmelCase__ ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ):
'''simple docstring'''
_a : List[str] = start
# add current to visited
visited.append(UpperCamelCase__ )
_a : List[Any] = edges[current]
for neighbor in neighbors:
# if neighbor not in visited, visit
if neighbor not in visited:
_a : Any = topological_sort(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ )
# if all neighbors visited add current to sort
sort.append(UpperCamelCase__ )
# if all vertices haven't been visited select a new one to visit
if len(UpperCamelCase__ ) != len(UpperCamelCase__ ):
for vertice in vertices:
if vertice not in visited:
_a : Any = topological_sort(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ )
# return sort
return sort
if __name__ == "__main__":
_snake_case = topological_sort('a', [], [])
print(sort)
| 389 | 0 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE__ = {
'''microsoft/biogpt''': '''https://huggingface.co/microsoft/biogpt/resolve/main/config.json''',
# See all BioGPT models at https://huggingface.co/models?filter=biogpt
}
class a__( UpperCAmelCase__ ):
a_ : Tuple = '''biogpt'''
def __init__( self , _UpperCAmelCase=4_2384 , _UpperCAmelCase=1024 , _UpperCAmelCase=24 , _UpperCAmelCase=16 , _UpperCAmelCase=4096 , _UpperCAmelCase="gelu" , _UpperCAmelCase=0.1 , _UpperCAmelCase=0.1 , _UpperCAmelCase=1024 , _UpperCAmelCase=0.02 , _UpperCAmelCase=1E-12 , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=0.0 , _UpperCAmelCase=0.0 , _UpperCAmelCase=1 , _UpperCAmelCase=0 , _UpperCAmelCase=2 , **_UpperCAmelCase , ) -> Optional[int]:
snake_case__ =vocab_size
snake_case__ =max_position_embeddings
snake_case__ =hidden_size
snake_case__ =num_hidden_layers
snake_case__ =num_attention_heads
snake_case__ =intermediate_size
snake_case__ =hidden_act
snake_case__ =hidden_dropout_prob
snake_case__ =attention_probs_dropout_prob
snake_case__ =initializer_range
snake_case__ =layer_norm_eps
snake_case__ =scale_embedding
snake_case__ =use_cache
snake_case__ =layerdrop
snake_case__ =activation_dropout
super().__init__(pad_token_id=__lowerCAmelCase , bos_token_id=__lowerCAmelCase , eos_token_id=__lowerCAmelCase , **__lowerCAmelCase )
| 710 |
'''simple docstring'''
import unittest
import torch
from torch import nn
from accelerate.test_utils import require_cuda
from accelerate.utils.memory import find_executable_batch_size, release_memory
def a ( ) -> Tuple:
raise RuntimeError('CUDA out of memory.' )
class a__( nn.Module ):
def __init__( self ) -> Dict:
super().__init__()
snake_case__ =nn.Linear(3 , 4 )
snake_case__ =nn.BatchNormad(4 )
snake_case__ =nn.Linear(4 , 5 )
def _lowercase ( self , _UpperCAmelCase ) -> Optional[Any]:
return self.lineara(self.batchnorm(self.lineara(_UpperCAmelCase ) ) )
class a__( unittest.TestCase ):
def _lowercase ( self ) -> int:
snake_case__ =[]
@find_executable_batch_size(starting_batch_size=128 )
def mock_training_loop_function(_UpperCAmelCase ):
nonlocal batch_sizes
batch_sizes.append(_UpperCAmelCase )
if batch_size != 8:
raise_fake_out_of_memory()
mock_training_loop_function()
self.assertListEqual(_UpperCAmelCase , [128, 64, 32, 16, 8] )
def _lowercase ( self ) -> Union[str, Any]:
snake_case__ =[]
@find_executable_batch_size(starting_batch_size=128 )
def mock_training_loop_function(_UpperCAmelCase , _UpperCAmelCase ):
nonlocal batch_sizes
batch_sizes.append(_UpperCAmelCase )
if batch_size != 8:
raise_fake_out_of_memory()
return batch_size, arga
snake_case__ , snake_case__ =mock_training_loop_function('hello' )
self.assertListEqual(_UpperCAmelCase , [128, 64, 32, 16, 8] )
self.assertListEqual([bs, arga] , [8, 'hello'] )
def _lowercase ( self ) -> Dict:
@find_executable_batch_size(starting_batch_size=0 )
def mock_training_loop_function(_UpperCAmelCase ):
pass
with self.assertRaises(_UpperCAmelCase ) as cm:
mock_training_loop_function()
self.assertIn('No executable batch size found, reached zero.' , cm.exception.args[0] )
def _lowercase ( self ) -> Optional[int]:
@find_executable_batch_size(starting_batch_size=16 )
def mock_training_loop_function(_UpperCAmelCase ):
if batch_size > 0:
raise_fake_out_of_memory()
pass
with self.assertRaises(_UpperCAmelCase ) as cm:
mock_training_loop_function()
self.assertIn('No executable batch size found, reached zero.' , cm.exception.args[0] )
def _lowercase ( self ) -> Dict:
@find_executable_batch_size(starting_batch_size=128 )
def mock_training_loop_function(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ):
if batch_size != 8:
raise raise_fake_out_of_memory()
with self.assertRaises(_UpperCAmelCase ) as cm:
mock_training_loop_function(128 , 'hello' , 'world' )
self.assertIn('Batch size was passed into `f`' , cm.exception.args[0] )
self.assertIn('`f(arg1=\'hello\', arg2=\'world\')' , cm.exception.args[0] )
def _lowercase ( self ) -> Union[str, Any]:
@find_executable_batch_size(starting_batch_size=16 )
def mock_training_loop_function(_UpperCAmelCase ):
raise ValueError('Oops, we had an error!' )
with self.assertRaises(_UpperCAmelCase ) as cm:
mock_training_loop_function()
self.assertIn('Oops, we had an error!' , cm.exception.args[0] )
@require_cuda
def _lowercase ( self ) -> Optional[int]:
snake_case__ =torch.cuda.memory_allocated()
snake_case__ =ModelForTest()
model.cuda()
self.assertGreater(torch.cuda.memory_allocated() , _UpperCAmelCase )
snake_case__ =release_memory(_UpperCAmelCase )
self.assertEqual(torch.cuda.memory_allocated() , _UpperCAmelCase )
| 581 | 0 |
import numpy
# List of input, output pairs
__snake_case : Dict =(
((5, 2, 3), 1_5),
((6, 5, 9), 2_5),
((1_1, 1_2, 1_3), 4_1),
((1, 1, 1), 8),
((1_1, 1_2, 1_3), 4_1),
)
__snake_case : Optional[Any] =(((5_1_5, 2_2, 1_3), 5_5_5), ((6_1, 3_5, 4_9), 1_5_0))
__snake_case : Optional[int] =[2, 4, 1, 5]
__snake_case : str =len(train_data)
__snake_case : List[str] =0.009
def lowerCAmelCase__ ( lowerCamelCase_ : Tuple ,lowerCamelCase_ : List[Any]="train"):
'''simple docstring'''
return calculate_hypothesis_value(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) - output(
SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)
def lowerCAmelCase__ ( lowerCamelCase_ : Optional[Any]):
'''simple docstring'''
lowerCAmelCase__ : str = 0
for i in range(len(SCREAMING_SNAKE_CASE__) - 1):
hyp_val += data_input_tuple[i] * parameter_vector[i + 1]
hyp_val += parameter_vector[0]
return hyp_val
def lowerCAmelCase__ ( lowerCamelCase_ : Any ,lowerCamelCase_ : Any):
'''simple docstring'''
if data_set == "train":
return train_data[example_no][1]
elif data_set == "test":
return test_data[example_no][1]
return None
def lowerCAmelCase__ ( lowerCamelCase_ : int ,lowerCamelCase_ : Optional[int]):
'''simple docstring'''
if data_set == "train":
return _hypothesis_value(train_data[example_no][0])
elif data_set == "test":
return _hypothesis_value(test_data[example_no][0])
return None
def lowerCAmelCase__ ( lowerCamelCase_ : Any ,lowerCamelCase_ : str=m):
'''simple docstring'''
lowerCAmelCase__ : Any = 0
for i in range(SCREAMING_SNAKE_CASE__):
if index == -1:
summation_value += _error(SCREAMING_SNAKE_CASE__)
else:
summation_value += _error(SCREAMING_SNAKE_CASE__) * train_data[i][0][index]
return summation_value
def lowerCAmelCase__ ( lowerCamelCase_ : List[str]):
'''simple docstring'''
lowerCAmelCase__ : int = summation_of_cost_derivative(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__) / m
return cost_derivative_value
def lowerCAmelCase__ ( ):
'''simple docstring'''
global parameter_vector
# Tune these values to set a tolerance value for predicted output
lowerCAmelCase__ : str = 0.000002
lowerCAmelCase__ : str = 0
lowerCAmelCase__ : Any = 0
while True:
j += 1
lowerCAmelCase__ : str = [0, 0, 0, 0]
for i in range(0 ,len(SCREAMING_SNAKE_CASE__)):
lowerCAmelCase__ : str = get_cost_derivative(i - 1)
lowerCAmelCase__ : Optional[Any] = (
parameter_vector[i] - LEARNING_RATE * cost_derivative
)
if numpy.allclose(
SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,atol=SCREAMING_SNAKE_CASE__ ,rtol=SCREAMING_SNAKE_CASE__ ,):
break
lowerCAmelCase__ : Dict = temp_parameter_vector
print(('''Number of iterations:''', j))
def lowerCAmelCase__ ( ):
'''simple docstring'''
for i in range(len(SCREAMING_SNAKE_CASE__)):
print(('''Actual output value:''', output(SCREAMING_SNAKE_CASE__ ,'''test''')))
print(('''Hypothesis output:''', calculate_hypothesis_value(SCREAMING_SNAKE_CASE__ ,'''test''')))
if __name__ == "__main__":
run_gradient_descent()
print('\nTesting gradient descent for a linear hypothesis function.\n')
test_gradient_descent()
| 647 |
"""simple docstring"""
import argparse
import torch
from transformers import (
WavaVecaConfig,
WavaVecaFeatureExtractor,
WavaVecaForAudioFrameClassification,
WavaVecaForSequenceClassification,
WavaVecaForXVector,
logging,
)
logging.set_verbosity_info()
SCREAMING_SNAKE_CASE_ = logging.get_logger(__name__)
def lowerCAmelCase_ ( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) -> str:
a_ : Tuple = WavaVecaForSequenceClassification.from_pretrained(SCREAMING_SNAKE_CASE__, config=SCREAMING_SNAKE_CASE__ )
a_ : Any = downstream_dict["projector.weight"]
a_ : Dict = downstream_dict["projector.bias"]
a_ : Tuple = downstream_dict["model.post_net.linear.weight"]
a_ : int = downstream_dict["model.post_net.linear.bias"]
return model
def lowerCAmelCase_ ( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) -> List[Any]:
a_ : List[str] = WavaVecaForAudioFrameClassification.from_pretrained(SCREAMING_SNAKE_CASE__, config=SCREAMING_SNAKE_CASE__ )
a_ : List[str] = downstream_dict["model.linear.weight"]
a_ : List[Any] = downstream_dict["model.linear.bias"]
return model
def lowerCAmelCase_ ( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) -> Optional[Any]:
a_ : int = WavaVecaForXVector.from_pretrained(SCREAMING_SNAKE_CASE__, config=SCREAMING_SNAKE_CASE__ )
a_ : Any = downstream_dict["connector.weight"]
a_ : Tuple = downstream_dict["connector.bias"]
for i, kernel_size in enumerate(hf_config.tdnn_kernel ):
a_ : List[str] = downstream_dict[
F"""model.framelevel_feature_extractor.module.{i}.kernel.weight"""
]
a_ : int = downstream_dict[F"""model.framelevel_feature_extractor.module.{i}.kernel.bias"""]
a_ : Any = downstream_dict["model.utterancelevel_feature_extractor.linear1.weight"]
a_ : Union[str, Any] = downstream_dict["model.utterancelevel_feature_extractor.linear1.bias"]
a_ : str = downstream_dict["model.utterancelevel_feature_extractor.linear2.weight"]
a_ : Union[str, Any] = downstream_dict["model.utterancelevel_feature_extractor.linear2.bias"]
a_ : List[str] = downstream_dict["objective.W"]
return model
@torch.no_grad()
def lowerCAmelCase_ ( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) -> Tuple:
a_ : Optional[int] = torch.load(SCREAMING_SNAKE_CASE__, map_location="cpu" )
a_ : List[str] = checkpoint["Downstream"]
a_ : Union[str, Any] = WavaVecaConfig.from_pretrained(SCREAMING_SNAKE_CASE__ )
a_ : Optional[int] = WavaVecaFeatureExtractor.from_pretrained(
SCREAMING_SNAKE_CASE__, return_attention_mask=SCREAMING_SNAKE_CASE__, do_normalize=SCREAMING_SNAKE_CASE__ )
a_ : Tuple = hf_config.architectures[0]
if arch.endswith("ForSequenceClassification" ):
a_ : int = convert_classification(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )
elif arch.endswith("ForAudioFrameClassification" ):
a_ : Any = convert_diarization(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )
elif arch.endswith("ForXVector" ):
a_ : Any = convert_xvector(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ )
else:
raise NotImplementedError(F"""S3PRL weights conversion is not supported for {arch}""" )
if hf_config.use_weighted_layer_sum:
a_ : Tuple = checkpoint["Featurizer"]["weights"]
hf_feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE__ )
hf_model.save_pretrained(SCREAMING_SNAKE_CASE__ )
if __name__ == "__main__":
SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser()
parser.add_argument(
"""--base_model_name""", default=None, type=str, help="""Name of the huggingface pretrained base model."""
)
parser.add_argument("""--config_path""", default=None, type=str, help="""Path to the huggingface classifier config.""")
parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to the s3prl checkpoint.""")
parser.add_argument("""--model_dump_path""", default=None, type=str, help="""Path to the final converted model.""")
SCREAMING_SNAKE_CASE_ = parser.parse_args()
convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path) | 237 | 0 |
import json
import pathlib
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import DetrImageProcessor
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
def __init__( self : str , a__ : List[str] , a__ : Optional[int]=7 , a__ : Optional[Any]=3 , a__ : Union[str, Any]=30 , a__ : Union[str, Any]=400 , a__ : List[Any]=True , a__ : Optional[Any]=None , a__ : str=True , a__ : Any=1 / 255 , a__ : str=True , a__ : List[Any]=[0.5, 0.5, 0.5] , a__ : List[Any]=[0.5, 0.5, 0.5] , a__ : Tuple=True , ):
# by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
__magic_name__ = size if size is not None else {'''shortest_edge''': 18, '''longest_edge''': 1333}
__magic_name__ = parent
__magic_name__ = batch_size
__magic_name__ = num_channels
__magic_name__ = min_resolution
__magic_name__ = max_resolution
__magic_name__ = do_resize
__magic_name__ = size
__magic_name__ = do_rescale
__magic_name__ = rescale_factor
__magic_name__ = do_normalize
__magic_name__ = image_mean
__magic_name__ = image_std
__magic_name__ = do_pad
def snake_case__ ( self : List[Any] ):
return {
"do_resize": self.do_resize,
"size": self.size,
"do_rescale": self.do_rescale,
"rescale_factor": self.rescale_factor,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_pad": self.do_pad,
}
def snake_case__ ( self : Union[str, Any] , a__ : Any , a__ : int=False ):
if not batched:
__magic_name__ = image_inputs[0]
if isinstance(a__ , Image.Image ):
__magic_name__ , __magic_name__ = image.size
else:
__magic_name__ , __magic_name__ = image.shape[1], image.shape[2]
if w < h:
__magic_name__ = int(self.size['''shortest_edge'''] * h / w )
__magic_name__ = self.size['''shortest_edge''']
elif w > h:
__magic_name__ = self.size['''shortest_edge''']
__magic_name__ = int(self.size['''shortest_edge'''] * w / h )
else:
__magic_name__ = self.size['''shortest_edge''']
__magic_name__ = self.size['''shortest_edge''']
else:
__magic_name__ = []
for image in image_inputs:
__magic_name__ , __magic_name__ = self.get_expected_values([image] )
expected_values.append((expected_height, expected_width) )
__magic_name__ = max(a__ , key=lambda a__ : item[0] )[0]
__magic_name__ = max(a__ , key=lambda a__ : item[1] )[1]
return expected_height, expected_width
@require_torch
@require_vision
class _SCREAMING_SNAKE_CASE ( __a ,unittest.TestCase ):
__SCREAMING_SNAKE_CASE :Optional[Any] = DetrImageProcessor if is_vision_available() else None
def snake_case__ ( self : Union[str, Any] ):
__magic_name__ = DetrImageProcessingTester(self )
@property
def snake_case__ ( self : List[str] ):
return self.image_processor_tester.prepare_image_processor_dict()
def snake_case__ ( self : List[str] ):
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(a__ , '''image_mean''' ) )
self.assertTrue(hasattr(a__ , '''image_std''' ) )
self.assertTrue(hasattr(a__ , '''do_normalize''' ) )
self.assertTrue(hasattr(a__ , '''do_rescale''' ) )
self.assertTrue(hasattr(a__ , '''rescale_factor''' ) )
self.assertTrue(hasattr(a__ , '''do_resize''' ) )
self.assertTrue(hasattr(a__ , '''size''' ) )
self.assertTrue(hasattr(a__ , '''do_pad''' ) )
def snake_case__ ( self : int ):
__magic_name__ = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {'''shortest_edge''': 18, '''longest_edge''': 1333} )
self.assertEqual(image_processor.do_pad , a__ )
__magic_name__ = self.image_processing_class.from_dict(
self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=a__ )
self.assertEqual(image_processor.size , {'''shortest_edge''': 42, '''longest_edge''': 84} )
self.assertEqual(image_processor.do_pad , a__ )
def snake_case__ ( self : List[str] ):
pass
def snake_case__ ( self : List[str] ):
# Initialize image_processing
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
__magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=a__ )
for image in image_inputs:
self.assertIsInstance(a__ , Image.Image )
# Test not batched input
__magic_name__ = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
__magic_name__ , __magic_name__ = self.image_processor_tester.get_expected_values(a__ )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__magic_name__ , __magic_name__ = self.image_processor_tester.get_expected_values(a__ , batched=a__ )
__magic_name__ = image_processing(a__ , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def snake_case__ ( self : Optional[int] ):
# Initialize image_processing
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
__magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=a__ , numpify=a__ )
for image in image_inputs:
self.assertIsInstance(a__ , np.ndarray )
# Test not batched input
__magic_name__ = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
__magic_name__ , __magic_name__ = self.image_processor_tester.get_expected_values(a__ )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__magic_name__ = image_processing(a__ , return_tensors='''pt''' ).pixel_values
__magic_name__ , __magic_name__ = self.image_processor_tester.get_expected_values(a__ , batched=a__ )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def snake_case__ ( self : int ):
# Initialize image_processing
__magic_name__ = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
__magic_name__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=a__ , torchify=a__ )
for image in image_inputs:
self.assertIsInstance(a__ , torch.Tensor )
# Test not batched input
__magic_name__ = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
__magic_name__ , __magic_name__ = self.image_processor_tester.get_expected_values(a__ )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
__magic_name__ = image_processing(a__ , return_tensors='''pt''' ).pixel_values
__magic_name__ , __magic_name__ = self.image_processor_tester.get_expected_values(a__ , batched=a__ )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
@slow
def snake_case__ ( self : Dict ):
# prepare image and target
__magic_name__ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f:
__magic_name__ = json.loads(f.read() )
__magic_name__ = {'''image_id''': 3_9769, '''annotations''': target}
# encode them
__magic_name__ = DetrImageProcessor.from_pretrained('''facebook/detr-resnet-50''' )
__magic_name__ = image_processing(images=a__ , annotations=a__ , return_tensors='''pt''' )
# verify pixel values
__magic_name__ = torch.Size([1, 3, 800, 1066] )
self.assertEqual(encoding['''pixel_values'''].shape , a__ )
__magic_name__ = torch.tensor([0.2_796, 0.3_138, 0.3_481] )
self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , a__ , atol=1E-4 ) )
# verify area
__magic_name__ = torch.tensor([5887.9600, 1_1250.2061, 48_9353.8438, 83_7122.7500, 14_7967.5156, 16_5732.3438] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , a__ ) )
# verify boxes
__magic_name__ = torch.Size([6, 4] )
self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , a__ )
__magic_name__ = torch.tensor([0.5_503, 0.2_765, 0.0_604, 0.2_215] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , a__ , atol=1E-3 ) )
# verify image_id
__magic_name__ = torch.tensor([3_9769] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , a__ ) )
# verify is_crowd
__magic_name__ = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , a__ ) )
# verify class_labels
__magic_name__ = torch.tensor([75, 75, 63, 65, 17, 17] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , a__ ) )
# verify orig_size
__magic_name__ = torch.tensor([480, 640] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , a__ ) )
# verify size
__magic_name__ = torch.tensor([800, 1066] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , a__ ) )
@slow
def snake_case__ ( self : Optional[int] ):
# prepare image, target and masks_path
__magic_name__ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f:
__magic_name__ = json.loads(f.read() )
__magic_name__ = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9769, '''segments_info''': target}
__magic_name__ = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' )
# encode them
__magic_name__ = DetrImageProcessor.from_pretrained('''facebook/detr-resnet-50-panoptic''' )
__magic_name__ = image_processing(images=a__ , annotations=a__ , masks_path=a__ , return_tensors='''pt''' )
# verify pixel values
__magic_name__ = torch.Size([1, 3, 800, 1066] )
self.assertEqual(encoding['''pixel_values'''].shape , a__ )
__magic_name__ = torch.tensor([0.2_796, 0.3_138, 0.3_481] )
self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , a__ , atol=1E-4 ) )
# verify area
__magic_name__ = torch.tensor([14_7979.6875, 16_5527.0469, 48_4638.5938, 1_1292.9375, 5879.6562, 7634.1147] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , a__ ) )
# verify boxes
__magic_name__ = torch.Size([6, 4] )
self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , a__ )
__magic_name__ = torch.tensor([0.2_625, 0.5_437, 0.4_688, 0.8_625] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , a__ , atol=1E-3 ) )
# verify image_id
__magic_name__ = torch.tensor([3_9769] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , a__ ) )
# verify is_crowd
__magic_name__ = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , a__ ) )
# verify class_labels
__magic_name__ = torch.tensor([17, 17, 63, 75, 75, 93] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , a__ ) )
# verify masks
__magic_name__ = 82_2873
self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , a__ )
# verify orig_size
__magic_name__ = torch.tensor([480, 640] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , a__ ) )
# verify size
__magic_name__ = torch.tensor([800, 1066] )
self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , a__ ) )
| 717 |
'''simple docstring'''
import json
import sys
import tempfile
import unittest
from pathlib import Path
import transformers
from transformers import (
CONFIG_MAPPING,
IMAGE_PROCESSOR_MAPPING,
AutoConfig,
AutoImageProcessor,
CLIPConfig,
CLIPImageProcessor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER
sys.path.append(str(Path(__file__).parent.parent.parent.parent / "utils"))
from test_module.custom_configuration import CustomConfig # noqa E402
from test_module.custom_image_processing import CustomImageProcessor # noqa E402
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
def snake_case__ ( self : Optional[int] ):
__magic_name__ = 0
def snake_case__ ( self : Any ):
__magic_name__ = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' )
self.assertIsInstance(a__ , a__ )
def snake_case__ ( self : List[Any] ):
with tempfile.TemporaryDirectory() as tmpdirname:
__magic_name__ = Path(a__ ) / '''preprocessor_config.json'''
__magic_name__ = Path(a__ ) / '''config.json'''
json.dump(
{'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(a__ , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(a__ , '''w''' ) )
__magic_name__ = AutoImageProcessor.from_pretrained(a__ )
self.assertIsInstance(a__ , a__ )
def snake_case__ ( self : int ):
# Ensure we can load the image processor from the feature extractor config
with tempfile.TemporaryDirectory() as tmpdirname:
__magic_name__ = Path(a__ ) / '''preprocessor_config.json'''
__magic_name__ = Path(a__ ) / '''config.json'''
json.dump(
{'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(a__ , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(a__ , '''w''' ) )
__magic_name__ = AutoImageProcessor.from_pretrained(a__ )
self.assertIsInstance(a__ , a__ )
def snake_case__ ( self : Dict ):
with tempfile.TemporaryDirectory() as tmpdirname:
__magic_name__ = CLIPConfig()
# Create a dummy config file with image_proceesor_type
__magic_name__ = Path(a__ ) / '''preprocessor_config.json'''
__magic_name__ = Path(a__ ) / '''config.json'''
json.dump(
{'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(a__ , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(a__ , '''w''' ) )
# remove image_processor_type to make sure config.json alone is enough to load image processor locally
__magic_name__ = AutoImageProcessor.from_pretrained(a__ ).to_dict()
config_dict.pop('''image_processor_type''' )
__magic_name__ = CLIPImageProcessor(**a__ )
# save in new folder
model_config.save_pretrained(a__ )
config.save_pretrained(a__ )
__magic_name__ = AutoImageProcessor.from_pretrained(a__ )
# make sure private variable is not incorrectly saved
__magic_name__ = json.loads(config.to_json_string() )
self.assertTrue('''_processor_class''' not in dict_as_saved )
self.assertIsInstance(a__ , a__ )
def snake_case__ ( self : List[Any] ):
with tempfile.TemporaryDirectory() as tmpdirname:
__magic_name__ = Path(a__ ) / '''preprocessor_config.json'''
json.dump(
{'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(a__ , '''w''' ) , )
__magic_name__ = AutoImageProcessor.from_pretrained(a__ )
self.assertIsInstance(a__ , a__ )
def snake_case__ ( self : Dict ):
with self.assertRaisesRegex(
a__ , '''clip-base is not a local folder and is not a valid model identifier''' ):
__magic_name__ = AutoImageProcessor.from_pretrained('''clip-base''' )
def snake_case__ ( self : int ):
with self.assertRaisesRegex(
a__ , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ):
__magic_name__ = AutoImageProcessor.from_pretrained(a__ , revision='''aaaaaa''' )
def snake_case__ ( self : Optional[int] ):
with self.assertRaisesRegex(
a__ , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ):
__magic_name__ = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' )
def snake_case__ ( self : Any ):
# If remote code is not set, we will time out when asking whether to load the model.
with self.assertRaises(a__ ):
__magic_name__ = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' )
# If remote code is disabled, we can't load this config.
with self.assertRaises(a__ ):
__magic_name__ = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=a__ )
__magic_name__ = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=a__ )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
# Test image processor can be reloaded.
with tempfile.TemporaryDirectory() as tmp_dir:
image_processor.save_pretrained(a__ )
__magic_name__ = AutoImageProcessor.from_pretrained(a__ , trust_remote_code=a__ )
self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' )
def snake_case__ ( self : List[Any] ):
try:
AutoConfig.register('''custom''' , a__ )
AutoImageProcessor.register(a__ , a__ )
# Trying to register something existing in the Transformers library will raise an error
with self.assertRaises(a__ ):
AutoImageProcessor.register(a__ , a__ )
with tempfile.TemporaryDirectory() as tmpdirname:
__magic_name__ = Path(a__ ) / '''preprocessor_config.json'''
__magic_name__ = Path(a__ ) / '''config.json'''
json.dump(
{'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(a__ , '''w''' ) , )
json.dump({'''model_type''': '''clip'''} , open(a__ , '''w''' ) )
__magic_name__ = CustomImageProcessor.from_pretrained(a__ )
# Now that the config is registered, it can be used as any other config with the auto-API
with tempfile.TemporaryDirectory() as tmp_dir:
image_processor.save_pretrained(a__ )
__magic_name__ = AutoImageProcessor.from_pretrained(a__ )
self.assertIsInstance(a__ , a__ )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
def snake_case__ ( self : str ):
class _SCREAMING_SNAKE_CASE ( __a ):
__SCREAMING_SNAKE_CASE :Tuple = True
try:
AutoConfig.register('''custom''' , a__ )
AutoImageProcessor.register(a__ , a__ )
# If remote code is not set, the default is to use local
__magic_name__ = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
self.assertTrue(image_processor.is_local )
# If remote code is disabled, we load the local one.
__magic_name__ = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=a__ )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
self.assertTrue(image_processor.is_local )
# If remote is enabled, we load from the Hub
__magic_name__ = AutoImageProcessor.from_pretrained(
'''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=a__ )
self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' )
self.assertTrue(not hasattr(a__ , '''is_local''' ) )
finally:
if "custom" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["custom"]
if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
| 245 | 0 |
'''simple docstring'''
import inspect
import unittest
import warnings
from transformers import DeiTConfig
from transformers.models.auto import get_values
from transformers.testing_utils import (
require_accelerate,
require_torch,
require_torch_gpu,
require_vision,
slow,
torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from torch import nn
from transformers import (
MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
MODEL_MAPPING,
DeiTForImageClassification,
DeiTForImageClassificationWithTeacher,
DeiTForMaskedImageModeling,
DeiTModel,
)
from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import DeiTImageProcessor
class lowerCAmelCase_ :
def __init__( self , _lowerCAmelCase , _lowerCAmelCase=13 , _lowerCAmelCase=30 , _lowerCAmelCase=2 , _lowerCAmelCase=3 , _lowerCAmelCase=True , _lowerCAmelCase=True , _lowerCAmelCase=32 , _lowerCAmelCase=5 , _lowerCAmelCase=4 , _lowerCAmelCase=37 , _lowerCAmelCase="gelu" , _lowerCAmelCase=0.1 , _lowerCAmelCase=0.1 , _lowerCAmelCase=10 , _lowerCAmelCase=0.02 , _lowerCAmelCase=3 , _lowerCAmelCase=None , _lowerCAmelCase=2 , ) -> int:
_lowerCAmelCase = parent
_lowerCAmelCase = batch_size
_lowerCAmelCase = image_size
_lowerCAmelCase = patch_size
_lowerCAmelCase = num_channels
_lowerCAmelCase = is_training
_lowerCAmelCase = use_labels
_lowerCAmelCase = hidden_size
_lowerCAmelCase = num_hidden_layers
_lowerCAmelCase = num_attention_heads
_lowerCAmelCase = intermediate_size
_lowerCAmelCase = hidden_act
_lowerCAmelCase = hidden_dropout_prob
_lowerCAmelCase = attention_probs_dropout_prob
_lowerCAmelCase = type_sequence_label_size
_lowerCAmelCase = initializer_range
_lowerCAmelCase = scope
_lowerCAmelCase = encoder_stride
# in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
_lowerCAmelCase = (image_size // patch_size) ** 2
_lowerCAmelCase = num_patches + 2
def _snake_case ( self ) -> Optional[Any]:
_lowerCAmelCase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
_lowerCAmelCase = None
if self.use_labels:
_lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size )
_lowerCAmelCase = self.get_config()
return config, pixel_values, labels
def _snake_case ( self ) -> Union[str, Any]:
return DeiTConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=_lowerCAmelCase , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , )
def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> List[str]:
_lowerCAmelCase = DeiTModel(config=_lowerCAmelCase )
model.to(_lowerCAmelCase )
model.eval()
_lowerCAmelCase = model(_lowerCAmelCase )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Optional[Any]:
_lowerCAmelCase = DeiTForMaskedImageModeling(config=_lowerCAmelCase )
model.to(_lowerCAmelCase )
model.eval()
_lowerCAmelCase = model(_lowerCAmelCase )
self.parent.assertEqual(
result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) )
# test greyscale images
_lowerCAmelCase = 1
_lowerCAmelCase = DeiTForMaskedImageModeling(_lowerCAmelCase )
model.to(_lowerCAmelCase )
model.eval()
_lowerCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
_lowerCAmelCase = model(_lowerCAmelCase )
self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) )
def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Any:
_lowerCAmelCase = self.type_sequence_label_size
_lowerCAmelCase = DeiTForImageClassification(_lowerCAmelCase )
model.to(_lowerCAmelCase )
model.eval()
_lowerCAmelCase = model(_lowerCAmelCase , labels=_lowerCAmelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
# test greyscale images
_lowerCAmelCase = 1
_lowerCAmelCase = DeiTForImageClassification(_lowerCAmelCase )
model.to(_lowerCAmelCase )
model.eval()
_lowerCAmelCase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
_lowerCAmelCase = model(_lowerCAmelCase , labels=_lowerCAmelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
def _snake_case ( self ) -> Tuple:
_lowerCAmelCase = self.prepare_config_and_inputs()
(
(
_lowerCAmelCase
) , (
_lowerCAmelCase
) , (
_lowerCAmelCase
) ,
) = config_and_inputs
_lowerCAmelCase = {"pixel_values": pixel_values}
return config, inputs_dict
@require_torch
class lowerCAmelCase_ ( __magic_name__ ,__magic_name__ ,unittest.TestCase ):
__lowerCamelCase : Tuple = (
(
DeiTModel,
DeiTForImageClassification,
DeiTForImageClassificationWithTeacher,
DeiTForMaskedImageModeling,
)
if is_torch_available()
else ()
)
__lowerCamelCase : int = (
{
"feature-extraction": DeiTModel,
"image-classification": (DeiTForImageClassification, DeiTForImageClassificationWithTeacher),
}
if is_torch_available()
else {}
)
__lowerCamelCase : Dict = False
__lowerCamelCase : List[Any] = False
__lowerCamelCase : Union[str, Any] = False
def _snake_case ( self ) -> Union[str, Any]:
_lowerCAmelCase = DeiTModelTester(self )
_lowerCAmelCase = ConfigTester(self , config_class=_lowerCAmelCase , has_text_modality=_lowerCAmelCase , hidden_size=37 )
def _snake_case ( self ) -> int:
self.config_tester.run_common_tests()
@unittest.skip(reason="DeiT does not use inputs_embeds" )
def _snake_case ( self ) -> List[Any]:
pass
def _snake_case ( self ) -> Any:
_lowerCAmelCase , _lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_lowerCAmelCase = model_class(_lowerCAmelCase )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
_lowerCAmelCase = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(_lowerCAmelCase , nn.Linear ) )
def _snake_case ( self ) -> Dict:
_lowerCAmelCase , _lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
_lowerCAmelCase = model_class(_lowerCAmelCase )
_lowerCAmelCase = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
_lowerCAmelCase = [*signature.parameters.keys()]
_lowerCAmelCase = ["pixel_values"]
self.assertListEqual(arg_names[:1] , _lowerCAmelCase )
def _snake_case ( self ) -> List[Any]:
_lowerCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*_lowerCAmelCase )
def _snake_case ( self ) -> List[Any]:
_lowerCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_image_modeling(*_lowerCAmelCase )
def _snake_case ( self ) -> Any:
_lowerCAmelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase )
def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=False ) -> int:
_lowerCAmelCase = super()._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase , return_labels=_lowerCAmelCase )
if return_labels:
if model_class.__name__ == "DeiTForImageClassificationWithTeacher":
del inputs_dict["labels"]
return inputs_dict
def _snake_case ( self ) -> Tuple:
if not self.model_tester.is_training:
return
_lowerCAmelCase , _lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common()
_lowerCAmelCase = True
for model_class in self.all_model_classes:
# DeiTForImageClassificationWithTeacher supports inference-only
if (
model_class in get_values(_lowerCAmelCase )
or model_class.__name__ == "DeiTForImageClassificationWithTeacher"
):
continue
_lowerCAmelCase = model_class(_lowerCAmelCase )
model.to(_lowerCAmelCase )
model.train()
_lowerCAmelCase = self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase , return_labels=_lowerCAmelCase )
_lowerCAmelCase = model(**_lowerCAmelCase ).loss
loss.backward()
def _snake_case ( self ) -> int:
_lowerCAmelCase , _lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common()
if not self.model_tester.is_training:
return
_lowerCAmelCase = False
_lowerCAmelCase = True
for model_class in self.all_model_classes:
if model_class in get_values(_lowerCAmelCase ) or not model_class.supports_gradient_checkpointing:
continue
# DeiTForImageClassificationWithTeacher supports inference-only
if model_class.__name__ == "DeiTForImageClassificationWithTeacher":
continue
_lowerCAmelCase = model_class(_lowerCAmelCase )
model.gradient_checkpointing_enable()
model.to(_lowerCAmelCase )
model.train()
_lowerCAmelCase = self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase , return_labels=_lowerCAmelCase )
_lowerCAmelCase = model(**_lowerCAmelCase ).loss
loss.backward()
def _snake_case ( self ) -> int:
_lowerCAmelCase , _lowerCAmelCase = self.model_tester.prepare_config_and_inputs_for_common()
_lowerCAmelCase = [
{"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float},
{"title": "single_label_classification", "num_labels": 1, "dtype": torch.long},
{"title": "regression", "num_labels": 1, "dtype": torch.float},
]
for model_class in self.all_model_classes:
if (
model_class
not in [
*get_values(_lowerCAmelCase ),
*get_values(_lowerCAmelCase ),
]
or model_class.__name__ == "DeiTForImageClassificationWithTeacher"
):
continue
for problem_type in problem_types:
with self.subTest(msg=f'''Testing {model_class} with {problem_type['title']}''' ):
_lowerCAmelCase = problem_type["title"]
_lowerCAmelCase = problem_type["num_labels"]
_lowerCAmelCase = model_class(_lowerCAmelCase )
model.to(_lowerCAmelCase )
model.train()
_lowerCAmelCase = self._prepare_for_class(_lowerCAmelCase , _lowerCAmelCase , return_labels=_lowerCAmelCase )
if problem_type["num_labels"] > 1:
_lowerCAmelCase = inputs["labels"].unsqueeze(1 ).repeat(1 , problem_type["num_labels"] )
_lowerCAmelCase = inputs["labels"].to(problem_type["dtype"] )
# This tests that we do not trigger the warning form PyTorch "Using a target size that is different
# to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure
# they have the same size." which is a symptom something in wrong for the regression problem.
# See https://github.com/huggingface/transformers/issues/11780
with warnings.catch_warnings(record=_lowerCAmelCase ) as warning_list:
_lowerCAmelCase = model(**_lowerCAmelCase ).loss
for w in warning_list:
if "Using a target size that is different to the input size" in str(w.message ):
raise ValueError(
f'''Something is going wrong in the regression problem: intercepted {w.message}''' )
loss.backward()
@slow
def _snake_case ( self ) -> Any:
for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
_lowerCAmelCase = DeiTModel.from_pretrained(_lowerCAmelCase )
self.assertIsNotNone(_lowerCAmelCase )
def __a():
'''simple docstring'''
_lowerCAmelCase = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
return image
@require_torch
@require_vision
class lowerCAmelCase_ ( unittest.TestCase ):
@cached_property
def _snake_case ( self ) -> Any:
return (
DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224" )
if is_vision_available()
else None
)
@slow
def _snake_case ( self ) -> Optional[int]:
_lowerCAmelCase = DeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224" ).to(
_lowerCAmelCase )
_lowerCAmelCase = self.default_image_processor
_lowerCAmelCase = prepare_img()
_lowerCAmelCase = image_processor(images=_lowerCAmelCase , return_tensors="pt" ).to(_lowerCAmelCase )
# forward pass
with torch.no_grad():
_lowerCAmelCase = model(**_lowerCAmelCase )
# verify the logits
_lowerCAmelCase = torch.Size((1, 1000) )
self.assertEqual(outputs.logits.shape , _lowerCAmelCase )
_lowerCAmelCase = torch.tensor([-1.0266, 0.1912, -1.2861] ).to(_lowerCAmelCase )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowerCAmelCase , atol=1E-4 ) )
@slow
@require_accelerate
@require_torch_gpu
def _snake_case ( self ) -> Optional[Any]:
_lowerCAmelCase = DeiTModel.from_pretrained(
"facebook/deit-base-distilled-patch16-224" , torch_dtype=torch.floataa , device_map="auto" )
_lowerCAmelCase = self.default_image_processor
_lowerCAmelCase = prepare_img()
_lowerCAmelCase = image_processor(images=_lowerCAmelCase , return_tensors="pt" )
_lowerCAmelCase = inputs.pixel_values.to(_lowerCAmelCase )
# forward pass to make sure inference works in fp16
with torch.no_grad():
_lowerCAmelCase = model(_lowerCAmelCase )
| 18 |
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING
__lowercase = logging.get_logger(__name__)
__lowercase = {
"""microsoft/table-transformer-detection""": (
"""https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json"""
),
}
class _lowercase ( __lowerCamelCase ):
_lowercase : Any = 'table-transformer'
_lowercase : List[Any] = ['past_key_values']
_lowercase : Union[str, Any] = {
'hidden_size': 'd_model',
'num_attention_heads': 'encoder_attention_heads',
}
def __init__( self : List[Any] , lowerCamelCase__ : Any=True , lowerCamelCase__ : List[Any]=None , lowerCamelCase__ : Any=3 , lowerCamelCase__ : Any=1_0_0 , lowerCamelCase__ : int=6 , lowerCamelCase__ : List[Any]=2_0_4_8 , lowerCamelCase__ : List[str]=8 , lowerCamelCase__ : int=6 , lowerCamelCase__ : List[str]=2_0_4_8 , lowerCamelCase__ : Optional[int]=8 , lowerCamelCase__ : Union[str, Any]=0.0 , lowerCamelCase__ : Any=0.0 , lowerCamelCase__ : str=True , lowerCamelCase__ : Optional[Any]="relu" , lowerCamelCase__ : Optional[int]=2_5_6 , lowerCamelCase__ : List[str]=0.1 , lowerCamelCase__ : str=0.0 , lowerCamelCase__ : Optional[int]=0.0 , lowerCamelCase__ : Dict=0.02 , lowerCamelCase__ : Union[str, Any]=1.0 , lowerCamelCase__ : Union[str, Any]=False , lowerCamelCase__ : Optional[int]="sine" , lowerCamelCase__ : str="resnet50" , lowerCamelCase__ : List[str]=True , lowerCamelCase__ : Optional[Any]=False , lowerCamelCase__ : Any=1 , lowerCamelCase__ : int=5 , lowerCamelCase__ : Union[str, Any]=2 , lowerCamelCase__ : List[str]=1 , lowerCamelCase__ : Union[str, Any]=1 , lowerCamelCase__ : Optional[Any]=5 , lowerCamelCase__ : Tuple=2 , lowerCamelCase__ : List[str]=0.1 , **lowerCamelCase__ : List[str] , ) -> Dict:
"""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.''' )
A_ = CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''] )
elif isinstance(lowerCamelCase__ , lowerCamelCase__ ):
A_ = backbone_config.get('''model_type''' )
A_ = CONFIG_MAPPING[backbone_model_type]
A_ = config_class.from_dict(lowerCamelCase__ )
# set timm attributes to None
A_ ,A_ ,A_ = None, None, None
A_ = use_timm_backbone
A_ = backbone_config
A_ = num_channels
A_ = num_queries
A_ = d_model
A_ = encoder_ffn_dim
A_ = encoder_layers
A_ = encoder_attention_heads
A_ = decoder_ffn_dim
A_ = decoder_layers
A_ = decoder_attention_heads
A_ = dropout
A_ = attention_dropout
A_ = activation_dropout
A_ = activation_function
A_ = init_std
A_ = init_xavier_std
A_ = encoder_layerdrop
A_ = decoder_layerdrop
A_ = encoder_layers
A_ = auxiliary_loss
A_ = position_embedding_type
A_ = backbone
A_ = use_pretrained_backbone
A_ = dilation
# Hungarian matcher
A_ = class_cost
A_ = bbox_cost
A_ = giou_cost
# Loss coefficients
A_ = mask_loss_coefficient
A_ = dice_loss_coefficient
A_ = bbox_loss_coefficient
A_ = giou_loss_coefficient
A_ = eos_coefficient
super().__init__(is_encoder_decoder=lowerCamelCase__ , **lowerCamelCase__ )
@property
def UpperCamelCase ( self : Optional[Any] ) -> int:
"""simple docstring"""
return self.encoder_attention_heads
@property
def UpperCamelCase ( self : Any ) -> int:
"""simple docstring"""
return self.d_model
class _lowercase ( __lowerCamelCase ):
_lowercase : Tuple = version.parse('1.11' )
@property
def UpperCamelCase ( self : Any ) -> 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 : List[Any] ) -> float:
"""simple docstring"""
return 1e-5
@property
def UpperCamelCase ( self : List[Any] ) -> int:
"""simple docstring"""
return 1_2
| 203 | 0 |
'''simple docstring'''
import tempfile
import unittest
from pathlib import Path
from shutil import copyfile
from transformers import BatchEncoding, MarianTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow
from transformers.utils import is_sentencepiece_available, is_tf_available, is_torch_available
if is_sentencepiece_available():
from transformers.models.marian.tokenization_marian import VOCAB_FILES_NAMES, save_json
from ...test_tokenization_common import TokenizerTesterMixin
_UpperCamelCase : List[str] = get_tests_dir("fixtures/test_sentencepiece.model")
_UpperCamelCase : Tuple = {'target_lang': 'fi', 'source_lang': 'en'}
_UpperCamelCase : Dict = '>>zh<<'
_UpperCamelCase : int = 'Helsinki-NLP/'
if is_torch_available():
_UpperCamelCase : List[str] = 'pt'
elif is_tf_available():
_UpperCamelCase : Union[str, Any] = 'tf'
else:
_UpperCamelCase : Union[str, Any] = 'jax'
@require_sentencepiece
class _snake_case ( UpperCamelCase_ , unittest.TestCase ):
SCREAMING_SNAKE_CASE : List[Any] = MarianTokenizer
SCREAMING_SNAKE_CASE : List[Any] = False
SCREAMING_SNAKE_CASE : Any = True
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
super().setUp()
lowerCAmelCase = ['''</s>''', '''<unk>''', '''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''', '''\u0120''', '''<pad>''']
lowerCAmelCase = dict(zip(UpperCamelCase__ , range(len(UpperCamelCase__ ) ) ) )
lowerCAmelCase = Path(self.tmpdirname )
save_json(UpperCamelCase__ , save_dir / VOCAB_FILES_NAMES['vocab'] )
save_json(UpperCamelCase__ , save_dir / VOCAB_FILES_NAMES['tokenizer_config_file'] )
if not (save_dir / VOCAB_FILES_NAMES["source_spm"]).exists():
copyfile(UpperCamelCase__ , save_dir / VOCAB_FILES_NAMES['source_spm'] )
copyfile(UpperCamelCase__ , save_dir / VOCAB_FILES_NAMES['target_spm'] )
lowerCAmelCase = MarianTokenizer.from_pretrained(self.tmpdirname )
tokenizer.save_pretrained(self.tmpdirname )
def _SCREAMING_SNAKE_CASE ( self , **_SCREAMING_SNAKE_CASE ):
'''simple docstring'''
return MarianTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase__ )
def _SCREAMING_SNAKE_CASE ( self , _SCREAMING_SNAKE_CASE ):
'''simple docstring'''
return (
"This is a test",
"This is a test",
)
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
lowerCAmelCase = '''</s>'''
lowerCAmelCase = 0
self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCamelCase__ ) , UpperCamelCase__ )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCamelCase__ ) , UpperCamelCase__ )
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
lowerCAmelCase = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , '</s>' )
self.assertEqual(vocab_keys[1] , '<unk>' )
self.assertEqual(vocab_keys[-1] , '<pad>' )
self.assertEqual(len(UpperCamelCase__ ) , 9 )
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
self.assertEqual(self.get_tokenizer().vocab_size , 9 )
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
lowerCAmelCase = MarianTokenizer.from_pretrained(F'{ORG_NAME}opus-mt-en-de' )
lowerCAmelCase = en_de_tokenizer(['I am a small frog'] , return_tensors=UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
lowerCAmelCase = [38, 1_21, 14, 6_97, 3_88_48, 0]
self.assertListEqual(UpperCamelCase__ , batch.input_ids[0] )
lowerCAmelCase = tempfile.mkdtemp()
en_de_tokenizer.save_pretrained(UpperCamelCase__ )
lowerCAmelCase = [x.name for x in Path(UpperCamelCase__ ).glob('*' )]
self.assertIn('source.spm' , UpperCamelCase__ )
MarianTokenizer.from_pretrained(UpperCamelCase__ )
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
lowerCAmelCase = self.get_tokenizer()
lowerCAmelCase = tok(
['I am a small frog' * 10_00, 'I am a small frog'] , padding=UpperCamelCase__ , truncation=UpperCamelCase__ , return_tensors=UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
self.assertEqual(batch.input_ids.shape , (2, 5_12) )
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
lowerCAmelCase = self.get_tokenizer()
lowerCAmelCase = tok(['I am a tiny frog', 'I am a small frog'] , padding=UpperCamelCase__ , return_tensors=UpperCamelCase__ )
self.assertIsInstance(UpperCamelCase__ , UpperCamelCase__ )
self.assertEqual(batch_smaller.input_ids.shape , (2, 10) )
@slow
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
lowerCAmelCase = {'''input_ids''': [[4_34_95, 4_62, 20, 4_21_64, 13_69, 52, 4_64, 1_32, 17_03, 4_92, 13, 74_91, 3_89_99, 6, 8, 4_64, 1_32, 17_03, 4_92, 13, 46_69, 3_78_67, 13, 75_25, 27, 15_93, 9_88, 13, 3_39_72, 70_29, 6, 20, 82_51, 3_83, 2, 2_70, 58_66, 37_88, 2, 23_53, 82_51, 1_23_38, 2, 1_39_58, 3_87, 2, 36_29, 69_53, 1_88, 29_00, 2, 1_39_58, 80_11, 1_15_01, 23, 84_60, 40_73, 3_40_09, 20, 4_35, 1_14_39, 27, 8, 84_60, 40_73, 60_04, 20, 99_88, 3_75, 27, 33, 2_66, 19_45, 10_76, 13_50, 3_78_67, 32_88, 5, 5_77, 10_76, 43_74, 8, 50_82, 5, 2_64_53, 2_57, 5_56, 4_03, 2, 2_42, 1_32, 3_83, 3_16, 4_92, 8, 1_07_67, 6, 3_16, 3_04, 42_39, 3, 0], [1_48, 1_57_22, 19, 18_39, 12, 13_50, 13, 2_23_27, 50_82, 54_18, 4_75_67, 3_59_38, 59, 3_18, 1_95_52, 1_08, 21_83, 54, 1_49_76, 48_35, 32, 5_47, 11_14, 8, 3_15, 24_17, 5, 92, 1_90_88, 3, 0, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00], [36, 63_95, 1_25_70, 3_91_47, 1_15_97, 6, 2_66, 4, 4_54_05, 72_96, 3, 0, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00, 5_81_00]], '''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, 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], [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, 0]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=UpperCamelCase__ , model_name='Helsinki-NLP/opus-mt-en-de' , revision='1a8c2263da11e68e50938f97e10cd57820bd504c' , decode_kwargs={'use_source_tokenizer': True} , )
def _SCREAMING_SNAKE_CASE ( self ):
'''simple docstring'''
lowerCAmelCase = MarianTokenizer.from_pretrained('hf-internal-testing/test-marian-two-vocabs' )
lowerCAmelCase = '''Tämä on testi'''
lowerCAmelCase = '''This is a test'''
lowerCAmelCase = [76, 7, 20_47, 2]
lowerCAmelCase = [69, 12, 11, 9_40, 2]
lowerCAmelCase = tokenizer(UpperCamelCase__ ).input_ids
self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ )
lowerCAmelCase = tokenizer(text_target=UpperCamelCase__ ).input_ids
self.assertListEqual(UpperCamelCase__ , UpperCamelCase__ )
lowerCAmelCase = tokenizer.decode(UpperCamelCase__ , skip_special_tokens=UpperCamelCase__ )
self.assertEqual(UpperCamelCase__ , UpperCamelCase__ )
| 712 |
'''simple docstring'''
def snake_case ( snake_case : int , snake_case : int ) -> int:
"""simple docstring"""
while a != 0:
lowerCAmelCase , lowerCAmelCase = b % a, a
return b
def snake_case ( snake_case : int , snake_case : int ) -> int:
"""simple docstring"""
if gcd(snake_case , snake_case ) != 1:
lowerCAmelCase = F'mod inverse of {a!r} and {m!r} does not exist'
raise ValueError(snake_case )
lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = 1, 0, a
lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = 0, 1, m
while va != 0:
lowerCAmelCase = ua // va
lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = (ua - q * va), (ua - q * va), (ua - q * va), va, va, va
return ua % m
| 514 | 0 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__magic_name__ : Union[str, Any] = logging.get_logger(__name__)
__magic_name__ : List[str] = {
'''transfo-xl-wt103''': '''https://huggingface.co/transfo-xl-wt103/resolve/main/config.json''',
}
class A__ ( __snake_case ):
'''simple docstring'''
snake_case__ = """transfo-xl"""
snake_case__ = ["""mems"""]
snake_case__ = {
"""n_token""": """vocab_size""",
"""hidden_size""": """d_model""",
"""num_attention_heads""": """n_head""",
"""num_hidden_layers""": """n_layer""",
}
def __init__( self : Any , _SCREAMING_SNAKE_CASE : str=26_7735 , _SCREAMING_SNAKE_CASE : Tuple=[2_0000, 4_0000, 20_0000] , _SCREAMING_SNAKE_CASE : List[str]=1024 , _SCREAMING_SNAKE_CASE : List[str]=1024 , _SCREAMING_SNAKE_CASE : int=16 , _SCREAMING_SNAKE_CASE : Any=64 , _SCREAMING_SNAKE_CASE : Any=4096 , _SCREAMING_SNAKE_CASE : Union[str, Any]=4 , _SCREAMING_SNAKE_CASE : List[Any]=False , _SCREAMING_SNAKE_CASE : Any=18 , _SCREAMING_SNAKE_CASE : Dict=1600 , _SCREAMING_SNAKE_CASE : Dict=1000 , _SCREAMING_SNAKE_CASE : int=True , _SCREAMING_SNAKE_CASE : Optional[Any]=True , _SCREAMING_SNAKE_CASE : int=0 , _SCREAMING_SNAKE_CASE : List[str]=-1 , _SCREAMING_SNAKE_CASE : int=True , _SCREAMING_SNAKE_CASE : Optional[int]=0.1 , _SCREAMING_SNAKE_CASE : Any=0.0 , _SCREAMING_SNAKE_CASE : List[Any]=True , _SCREAMING_SNAKE_CASE : List[str]="normal" , _SCREAMING_SNAKE_CASE : Optional[int]=0.0_1 , _SCREAMING_SNAKE_CASE : List[Any]=0.0_1 , _SCREAMING_SNAKE_CASE : Optional[int]=0.0_2 , _SCREAMING_SNAKE_CASE : List[str]=1E-5 , _SCREAMING_SNAKE_CASE : List[str]=0 , **_SCREAMING_SNAKE_CASE : Optional[int] , ):
"""simple docstring"""
UpperCamelCase = vocab_size
UpperCamelCase = []
self.cutoffs.extend(_SCREAMING_SNAKE_CASE )
if proj_share_all_but_first:
UpperCamelCase = [False] + [True] * len(self.cutoffs )
else:
UpperCamelCase = [False] + [False] * len(self.cutoffs )
UpperCamelCase = d_model
UpperCamelCase = d_embed
UpperCamelCase = d_head
UpperCamelCase = d_inner
UpperCamelCase = div_val
UpperCamelCase = pre_lnorm
UpperCamelCase = n_layer
UpperCamelCase = n_head
UpperCamelCase = mem_len
UpperCamelCase = same_length
UpperCamelCase = attn_type
UpperCamelCase = clamp_len
UpperCamelCase = sample_softmax
UpperCamelCase = adaptive
UpperCamelCase = dropout
UpperCamelCase = dropatt
UpperCamelCase = untie_r
UpperCamelCase = init
UpperCamelCase = init_range
UpperCamelCase = proj_init_std
UpperCamelCase = init_std
UpperCamelCase = layer_norm_epsilon
super().__init__(eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE )
@property
def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ):
"""simple docstring"""
logger.info(f'The model {self.model_type} is one of the few models that has no sequence length limit.' )
return -1
@max_position_embeddings.setter
def _SCREAMING_SNAKE_CASE ( self : Tuple , _SCREAMING_SNAKE_CASE : str ):
"""simple docstring"""
raise NotImplementedError(
f'The model {self.model_type} is one of the few models that has no sequence length limit.' )
| 280 |
import tempfile
import unittest
from pathlib import Path
from shutil import copyfile
from transformers import MaMaaaTokenizer, is_torch_available
from transformers.testing_utils import (
get_tests_dir,
nested_simplify,
require_sentencepiece,
require_tokenizers,
require_torch,
slow,
)
from transformers.utils import is_sentencepiece_available
if is_sentencepiece_available():
from transformers.models.mam_aaa.tokenization_mam_aaa import VOCAB_FILES_NAMES, save_json
from ...test_tokenization_common import TokenizerTesterMixin
if is_sentencepiece_available():
__magic_name__ : Any = get_tests_dir('''fixtures/test_sentencepiece.model''')
if is_torch_available():
from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right
__magic_name__ : Optional[Any] = 12_8022
__magic_name__ : Dict = 12_8028
@require_sentencepiece
class A__ ( __snake_case , unittest.TestCase ):
'''simple docstring'''
snake_case__ = MaMaaaTokenizer
snake_case__ = False
snake_case__ = False
snake_case__ = True
def _SCREAMING_SNAKE_CASE ( self : List[str] ):
"""simple docstring"""
super().setUp()
UpperCamelCase = ['</s>', '<unk>', '▁This', '▁is', '▁a', '▁t', 'est', '\u0120', '<pad>']
UpperCamelCase = dict(zip(_SCREAMING_SNAKE_CASE , range(len(_SCREAMING_SNAKE_CASE ) ) ) )
UpperCamelCase = Path(self.tmpdirname )
save_json(_SCREAMING_SNAKE_CASE , save_dir / VOCAB_FILES_NAMES['vocab_file'] )
if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists():
copyfile(_SCREAMING_SNAKE_CASE , save_dir / VOCAB_FILES_NAMES['spm_file'] )
UpperCamelCase = MaMaaaTokenizer.from_pretrained(self.tmpdirname )
tokenizer.save_pretrained(self.tmpdirname )
def _SCREAMING_SNAKE_CASE ( self : str , **_SCREAMING_SNAKE_CASE : List[str] ):
"""simple docstring"""
return MaMaaaTokenizer.from_pretrained(self.tmpdirname , **_SCREAMING_SNAKE_CASE )
def _SCREAMING_SNAKE_CASE ( self : Optional[int] , _SCREAMING_SNAKE_CASE : Optional[Any] ):
"""simple docstring"""
return (
"This is a test",
"This is a test",
)
def _SCREAMING_SNAKE_CASE ( self : List[Any] ):
"""simple docstring"""
UpperCamelCase = '</s>'
UpperCamelCase = 0
self.assertEqual(self.get_tokenizer()._convert_token_to_id(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE )
def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ):
"""simple docstring"""
UpperCamelCase = self.get_tokenizer()
UpperCamelCase = list(tokenizer.get_vocab().keys() )
self.assertEqual(vocab_keys[0] , '</s>' )
self.assertEqual(vocab_keys[1] , '<unk>' )
self.assertEqual(vocab_keys[-1] , '<s>' )
self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , tokenizer.vocab_size + len(tokenizer.get_added_vocab() ) )
@unittest.skip('Skip this test while all models are still to be uploaded.' )
def _SCREAMING_SNAKE_CASE ( self : str ):
"""simple docstring"""
pass
def _SCREAMING_SNAKE_CASE ( self : Any ):
"""simple docstring"""
UpperCamelCase = self.get_tokenizer()
UpperCamelCase = tokenizer.tokenize('This is a test' )
self.assertListEqual(_SCREAMING_SNAKE_CASE , ['▁This', '▁is', '▁a', '▁t', 'est'] )
self.assertListEqual(
tokenizer.convert_tokens_to_ids(_SCREAMING_SNAKE_CASE ) , [2, 3, 4, 5, 6] , )
UpperCamelCase = tokenizer.convert_ids_to_tokens([2, 3, 4, 5, 6] )
self.assertListEqual(_SCREAMING_SNAKE_CASE , ['▁This', '▁is', '▁a', '▁t', 'est'] )
UpperCamelCase = tokenizer.convert_tokens_to_string(_SCREAMING_SNAKE_CASE )
self.assertEqual(_SCREAMING_SNAKE_CASE , 'This is a test' )
@slow
def _SCREAMING_SNAKE_CASE ( self : str ):
"""simple docstring"""
UpperCamelCase = {'input_ids': [[12_8022, 11_0108, 397, 11, 3_8272, 2247, 12_4811, 285, 1_8105, 1586, 207, 7, 3_9534, 4428, 397, 1019, 1_8105, 1586, 207, 7, 4_1337, 1_6786, 241, 7, 2_0214, 17, 12_5690, 1_0398, 7, 4_4378, 5_8069, 6_8342, 7798, 7343, 11, 299, 3_3310, 4, 158, 3_7350, 9_4077, 4569, 299, 3_3310, 90, 4, 5_2840, 290, 4, 3_1270, 112, 299, 682, 4, 5_2840, 3_9953, 1_4079, 193, 5_2519, 9_0894, 1_7894, 12_0697, 11, 4_0445, 551, 17, 1019, 5_2519, 9_0894, 1_7756, 963, 11, 4_0445, 480, 17, 9792, 1120, 5173, 1393, 6240, 1_6786, 241, 12_0996, 28, 1245, 1393, 11_8240, 1_1123, 1019, 9_3612, 2691, 1_0618, 9_8058, 12_0409, 1928, 279, 4, 4_0683, 367, 178, 207, 1019, 103, 10_3121, 506, 6_5296, 5, 2], [12_8022, 2_1217, 367, 117, 12_5450, 128, 719, 7, 7308, 40, 9_3612, 1_2669, 1116, 1_6704, 71, 1_7785, 3699, 1_5592, 35, 144, 9584, 241, 1_1943, 713, 950, 799, 2247, 8_8427, 150, 149, 11_8813, 12_0706, 1019, 10_6906, 8_1518, 28, 1224, 2_2799, 397, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [12_8022, 1658, 12_3311, 5155, 5578, 4722, 279, 1_4947, 2366, 1120, 1197, 14, 1348, 9232, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], '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, 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], [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, 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=_SCREAMING_SNAKE_CASE , model_name='facebook/m2m100_418M' , revision='c168bae485c864188cf9aa0e4108b0b6934dc91e' , )
@require_torch
@require_sentencepiece
@require_tokenizers
class A__ ( unittest.TestCase ):
'''simple docstring'''
snake_case__ = """facebook/m2m100_418M"""
snake_case__ = [
"""In my opinion, there are two levels of response from the French government.""",
"""NSA Affair Emphasizes Complete Lack of Debate on Intelligence""",
]
snake_case__ = [
"""Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.""",
"""L'affaire NSA souligne l'absence totale de débat sur le renseignement""",
]
# fmt: off
snake_case__ = [EN_CODE, 5_93, 19_49, 11_57_81, 4, 7_15_86, 42_34, 6_06_33, 12_62_33, 4_32, 12_38_08, 1_55_92, 11_97, 11_71_32, 12_06_18, 5, 2]
@classmethod
def _SCREAMING_SNAKE_CASE ( cls : Any ):
"""simple docstring"""
UpperCamelCase = MaMaaaTokenizer.from_pretrained(
cls.checkpoint_name , src_lang='en' , tgt_lang='fr' )
UpperCamelCase = 1
return cls
def _SCREAMING_SNAKE_CASE ( self : str ):
"""simple docstring"""
self.assertEqual(self.tokenizer.get_lang_id('ar' ) , 12_8006 )
self.assertEqual(self.tokenizer.get_lang_id('en' ) , 12_8022 )
self.assertEqual(self.tokenizer.get_lang_id('ro' ) , 12_8076 )
self.assertEqual(self.tokenizer.get_lang_id('mr' ) , 12_8063 )
def _SCREAMING_SNAKE_CASE ( self : Tuple ):
"""simple docstring"""
UpperCamelCase = self.tokenizer.get_vocab()
self.assertEqual(len(_SCREAMING_SNAKE_CASE ) , self.tokenizer.vocab_size )
self.assertEqual(vocab['<unk>'] , 3 )
self.assertIn(self.tokenizer.get_lang_token('en' ) , _SCREAMING_SNAKE_CASE )
def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ):
"""simple docstring"""
UpperCamelCase = 'en'
UpperCamelCase = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0]
self.assertListEqual(self.expected_src_tokens , _SCREAMING_SNAKE_CASE )
def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ):
"""simple docstring"""
self.assertIn(_SCREAMING_SNAKE_CASE , self.tokenizer.all_special_ids )
# fmt: off
UpperCamelCase = [FR_CODE, 5364, 82, 8642, 4, 294, 47, 8, 1_4028, 136, 3286, 9706, 6, 9_0797, 6, 14_4012, 162, 8_8128, 3_0061, 5, 2]
# fmt: on
UpperCamelCase = self.tokenizer.decode(_SCREAMING_SNAKE_CASE , skip_special_tokens=_SCREAMING_SNAKE_CASE )
UpperCamelCase = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=_SCREAMING_SNAKE_CASE )
self.assertEqual(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
self.assertNotIn(self.tokenizer.eos_token , _SCREAMING_SNAKE_CASE )
def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ):
"""simple docstring"""
UpperCamelCase = tempfile.mkdtemp()
UpperCamelCase = self.tokenizer.lang_token_to_id
self.tokenizer.save_pretrained(_SCREAMING_SNAKE_CASE )
UpperCamelCase = MaMaaaTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE )
self.assertDictEqual(new_tok.lang_token_to_id , _SCREAMING_SNAKE_CASE )
@require_torch
def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ):
"""simple docstring"""
UpperCamelCase = 'en'
UpperCamelCase = 'fr'
UpperCamelCase = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=_SCREAMING_SNAKE_CASE , return_tensors='pt' )
UpperCamelCase = shift_tokens_right(
batch['labels'] , self.tokenizer.pad_token_id , self.tokenizer.eos_token_id )
for k in batch:
UpperCamelCase = batch[k].tolist()
# batch = {k: v.tolist() for k,v in batch.items()}
# fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4
# batch.decoder_inputs_ids[0][0] ==
assert batch.input_ids[1][0] == EN_CODE
assert batch.input_ids[1][-1] == 2
assert batch.labels[1][0] == FR_CODE
assert batch.labels[1][-1] == 2
assert batch.decoder_input_ids[1][:2] == [2, FR_CODE]
@require_torch
def _SCREAMING_SNAKE_CASE ( self : Any ):
"""simple docstring"""
UpperCamelCase = 'mr'
self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('mr' )] )
self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] )
UpperCamelCase = 'zh'
self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('zh' )] )
self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] )
@require_torch
def _SCREAMING_SNAKE_CASE ( self : Tuple ):
"""simple docstring"""
UpperCamelCase = 'mr'
self.tokenizer._switch_to_target_mode()
self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('mr' )] )
self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] )
self.tokenizer._switch_to_input_mode()
self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] )
UpperCamelCase = 'zh'
self.tokenizer._switch_to_target_mode()
self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id('zh' )] )
self.assertListEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] )
self.tokenizer._switch_to_input_mode()
self.assertListEqual(self.tokenizer.prefix_tokens , [self.tokenizer.get_lang_id(self.tokenizer.src_lang )] )
@require_torch
def _SCREAMING_SNAKE_CASE ( self : Any ):
"""simple docstring"""
UpperCamelCase = self.tokenizer._build_translation_inputs('A test' , return_tensors='pt' , src_lang='en' , tgt_lang='ar' )
self.assertEqual(
nested_simplify(_SCREAMING_SNAKE_CASE ) , {
# en_XX, A, test, EOS
'input_ids': [[12_8022, 58, 4183, 2]],
'attention_mask': [[1, 1, 1, 1]],
# ar_AR
'forced_bos_token_id': 12_8006,
} , )
| 280 | 1 |
'''simple docstring'''
def lowercase__ ( __UpperCamelCase )-> list:
UpperCamelCase = False
while is_sorted is False: # Until all the indices are traversed keep looping
UpperCamelCase = True
for i in range(0 , len(__UpperCamelCase ) - 1 , 2 ): # iterating over all even indices
if input_list[i] > input_list[i + 1]:
UpperCamelCase ,UpperCamelCase = input_list[i + 1], input_list[i]
# swapping if elements not in order
UpperCamelCase = False
for i in range(1 , len(__UpperCamelCase ) - 1 , 2 ): # iterating over all odd indices
if input_list[i] > input_list[i + 1]:
UpperCamelCase ,UpperCamelCase = input_list[i + 1], input_list[i]
# swapping if elements not in order
UpperCamelCase = False
return input_list
if __name__ == "__main__":
print('Enter list to be sorted')
SCREAMING_SNAKE_CASE__ = [int(x) for x in input().split()]
# inputing elements of the list in one line
SCREAMING_SNAKE_CASE__ = odd_even_sort(input_list)
print('The sorted list is')
print(sorted_list)
| 35 |
'''simple docstring'''
def lowercase__ ( __UpperCamelCase , __UpperCamelCase )-> str:
if not isinstance(__UpperCamelCase , __UpperCamelCase ):
raise ValueError("""iterations must be defined as integers""" )
if not isinstance(__UpperCamelCase , __UpperCamelCase ) or not number >= 1:
raise ValueError(
"""starting number must be
and integer and be more than 0""" )
if not iterations >= 1:
raise ValueError("""Iterations must be done more than 0 times to play FizzBuzz""" )
UpperCamelCase = """"""
while number <= iterations:
if number % 3 == 0:
out += "Fizz"
if number % 5 == 0:
out += "Buzz"
if 0 not in (number % 3, number % 5):
out += str(__UpperCamelCase )
# print(out)
number += 1
out += " "
return out
if __name__ == "__main__":
import doctest
doctest.testmod()
| 35 | 1 |
def lowercase ( __A : int = 100 ) -> int:
'''simple docstring'''
snake_case : Tuple = 0
snake_case : Tuple = 0
for i in range(1 , n + 1 ):
sum_of_squares += i**2
sum_of_ints += i
return sum_of_ints**2 - sum_of_squares
if __name__ == "__main__":
print(f'''{solution() = }''')
| 36 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available
a_ : Optional[Any] = {
"""configuration_ctrl""": ["""CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP""", """CTRLConfig"""],
"""tokenization_ctrl""": ["""CTRLTokenizer"""],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a_ : str = [
"""CTRL_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""CTRLForSequenceClassification""",
"""CTRLLMHeadModel""",
"""CTRLModel""",
"""CTRLPreTrainedModel""",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a_ : List[Any] = [
"""TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""TFCTRLForSequenceClassification""",
"""TFCTRLLMHeadModel""",
"""TFCTRLModel""",
"""TFCTRLPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_ctrl import CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRLConfig
from .tokenization_ctrl import CTRLTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_ctrl import (
CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
CTRLForSequenceClassification,
CTRLLMHeadModel,
CTRLModel,
CTRLPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_ctrl import (
TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
TFCTRLForSequenceClassification,
TFCTRLLMHeadModel,
TFCTRLModel,
TFCTRLPreTrainedModel,
)
else:
import sys
a_ : Optional[int] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 675 | 0 |
import warnings
from ...utils import logging
from .image_processing_owlvit import OwlViTImageProcessor
_lowerCamelCase : Optional[int] = logging.get_logger(__name__)
class snake_case__ ( __snake_case ):
'''simple docstring'''
def __init__( self : List[str] , *lowerCAmelCase_ : Optional[Any] , **lowerCAmelCase_ : Tuple ) -> None:
warnings.warn(
'''The class OwlViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please'''
''' use OwlViTImageProcessor instead.''' , lowerCAmelCase_ , )
super().__init__(*lowerCAmelCase_ , **lowerCAmelCase_ )
| 407 |
from __future__ import annotations
_lowerCamelCase : Dict = 1.6_0_2_1E-1_9 # units = C
def _lowerCAmelCase ( __magic_name__ :float , __magic_name__ :float , __magic_name__ :float , ):
if (conductivity, electron_conc, mobility).count(0 ) != 1:
raise ValueError('''You cannot supply more or less than 2 values''' )
elif conductivity < 0:
raise ValueError('''Conductivity cannot be negative''' )
elif electron_conc < 0:
raise ValueError('''Electron concentration cannot be negative''' )
elif mobility < 0:
raise ValueError('''mobility cannot be negative''' )
elif conductivity == 0:
return (
"conductivity",
mobility * electron_conc * ELECTRON_CHARGE,
)
elif electron_conc == 0:
return (
"electron_conc",
conductivity / (mobility * ELECTRON_CHARGE),
)
else:
return (
"mobility",
conductivity / (electron_conc * ELECTRON_CHARGE),
)
if __name__ == "__main__":
import doctest
doctest.testmod()
| 407 | 1 |
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import LevitImageProcessor
class lowerCamelCase__ ( unittest.TestCase):
"""simple docstring"""
def __init__( self : Union[str, Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Dict=7 , __lowerCAmelCase : Dict=3 , __lowerCAmelCase : List[str]=18 , __lowerCAmelCase : str=30 , __lowerCAmelCase : Tuple=4_00 , __lowerCAmelCase : Union[str, Any]=True , __lowerCAmelCase : str=None , __lowerCAmelCase : Any=True , __lowerCAmelCase : List[Any]=None , __lowerCAmelCase : Optional[Any]=True , __lowerCAmelCase : str=[0.5, 0.5, 0.5] , __lowerCAmelCase : Dict=[0.5, 0.5, 0.5] , ) -> Optional[Any]:
_A = size if size is not None else {'''shortest_edge''': 18}
_A = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}
_A = parent
_A = batch_size
_A = num_channels
_A = image_size
_A = min_resolution
_A = max_resolution
_A = do_resize
_A = size
_A = do_center_crop
_A = crop_size
_A = do_normalize
_A = image_mean
_A = image_std
def snake_case_ ( self : Optional[Any] ) -> Optional[int]:
return {
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_normalize": self.do_normalize,
"do_resize": self.do_resize,
"do_center_crop": self.do_center_crop,
"size": self.size,
"crop_size": self.crop_size,
}
@require_torch
@require_vision
class lowerCamelCase__ ( _A , unittest.TestCase):
"""simple docstring"""
a__ : str = LevitImageProcessor if is_vision_available() else None
def snake_case_ ( self : Optional[Any] ) -> Dict:
_A = LevitImageProcessingTester(self )
@property
def snake_case_ ( self : str ) -> str:
return self.image_processor_tester.prepare_image_processor_dict()
def snake_case_ ( self : Tuple ) -> Optional[int]:
_A = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(__lowerCAmelCase , '''image_mean''' ) )
self.assertTrue(hasattr(__lowerCAmelCase , '''image_std''' ) )
self.assertTrue(hasattr(__lowerCAmelCase , '''do_normalize''' ) )
self.assertTrue(hasattr(__lowerCAmelCase , '''do_resize''' ) )
self.assertTrue(hasattr(__lowerCAmelCase , '''do_center_crop''' ) )
self.assertTrue(hasattr(__lowerCAmelCase , '''size''' ) )
def snake_case_ ( self : Any ) -> Union[str, Any]:
_A = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {'''shortest_edge''': 18} )
self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18} )
_A = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 )
self.assertEqual(image_processor.size , {'''shortest_edge''': 42} )
self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84} )
def snake_case_ ( self : Optional[int] ) -> Dict:
pass
def snake_case_ ( self : List[Any] ) -> Any:
# Initialize image_processing
_A = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
_A = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCAmelCase )
for image in image_inputs:
self.assertIsInstance(__lowerCAmelCase , Image.Image )
# Test not batched input
_A = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
# Test batched
_A = image_processing(__lowerCAmelCase , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
def snake_case_ ( self : Optional[Any] ) -> Tuple:
# Initialize image_processing
_A = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
_A = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCAmelCase , numpify=__lowerCAmelCase )
for image in image_inputs:
self.assertIsInstance(__lowerCAmelCase , np.ndarray )
# Test not batched input
_A = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
# Test batched
_A = image_processing(__lowerCAmelCase , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
def snake_case_ ( self : Union[str, Any] ) -> Dict:
# Initialize image_processing
_A = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
_A = prepare_image_inputs(self.image_processor_tester , equal_resolution=__lowerCAmelCase , torchify=__lowerCAmelCase )
for image in image_inputs:
self.assertIsInstance(__lowerCAmelCase , torch.Tensor )
# Test not batched input
_A = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
# Test batched
_A = image_processing(__lowerCAmelCase , return_tensors='''pt''' ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size['''height'''],
self.image_processor_tester.crop_size['''width'''],
) , )
| 2 |
'''simple docstring'''
import time
import unittest
from transformers import is_torch_available
from transformers.testing_utils import require_torch, torch_device
from ..test_modeling_common import ids_tensor
if is_torch_available():
import torch
from transformers.generation import (
MaxLengthCriteria,
MaxNewTokensCriteria,
MaxTimeCriteria,
StoppingCriteriaList,
validate_stopping_criteria,
)
@require_torch
class UpperCAmelCase ( unittest.TestCase ):
def UpperCAmelCase_ ( self :int , lowercase_ :str )-> Any:
A__ = 3
A__ = 2_50
A__ = ids_tensor((batch_size, length) , lowercase_ )
A__ = torch.ones((batch_size, length) , device=lowercase_ , dtype=torch.float ) / length
return input_ids, scores
def UpperCAmelCase_ ( self :str )-> Dict:
A__, A__ = self._get_tensors(5 )
A__ = StoppingCriteriaList(
[
MaxLengthCriteria(max_length=10 ),
MaxTimeCriteria(max_time=0.1 ),
] )
self.assertFalse(criteria(lowercase_ , lowercase_ ) )
A__, A__ = self._get_tensors(9 )
self.assertFalse(criteria(lowercase_ , lowercase_ ) )
A__, A__ = self._get_tensors(10 )
self.assertTrue(criteria(lowercase_ , lowercase_ ) )
def UpperCAmelCase_ ( self :List[Any] )-> List[Any]:
A__ = MaxLengthCriteria(max_length=10 )
A__, A__ = self._get_tensors(5 )
self.assertFalse(criteria(lowercase_ , lowercase_ ) )
A__, A__ = self._get_tensors(9 )
self.assertFalse(criteria(lowercase_ , lowercase_ ) )
A__, A__ = self._get_tensors(10 )
self.assertTrue(criteria(lowercase_ , lowercase_ ) )
def UpperCAmelCase_ ( self :Tuple )-> int:
A__ = MaxNewTokensCriteria(start_length=5 , max_new_tokens=5 )
A__, A__ = self._get_tensors(5 )
self.assertFalse(criteria(lowercase_ , lowercase_ ) )
A__, A__ = self._get_tensors(9 )
self.assertFalse(criteria(lowercase_ , lowercase_ ) )
A__, A__ = self._get_tensors(10 )
self.assertTrue(criteria(lowercase_ , lowercase_ ) )
A__ = StoppingCriteriaList([criteria] )
self.assertEqual(criteria_list.max_length , 10 )
def UpperCAmelCase_ ( self :Dict )-> int:
A__, A__ = self._get_tensors(5 )
A__ = MaxTimeCriteria(max_time=0.1 )
self.assertFalse(criteria(lowercase_ , lowercase_ ) )
A__ = MaxTimeCriteria(max_time=0.1 , initial_timestamp=time.time() - 0.2 )
self.assertTrue(criteria(lowercase_ , lowercase_ ) )
def UpperCAmelCase_ ( self :Union[str, Any] )-> str:
validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10 )] ) , 10 )
with self.assertWarns(lowercase_ ):
validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(10 )] ) , 11 )
A__ = validate_stopping_criteria(StoppingCriteriaList() , 11 )
self.assertEqual(len(lowercase_ ) , 1 )
| 440 | 0 |
import argparse
import OmegaConf
import torch
from diffusers import DDIMScheduler, LDMPipeline, UNetLDMModel, VQModel
def _UpperCAmelCase ( UpperCAmelCase : List[str] , UpperCAmelCase : Optional[Any] , UpperCAmelCase : str ):
"""simple docstring"""
__lowerCamelCase : Optional[Any] = OmegaConf.load(UpperCAmelCase )
__lowerCamelCase : Union[str, Any] = torch.load(UpperCAmelCase , map_location="""cpu""" )["""model"""]
__lowerCamelCase : str = list(state_dict.keys() )
# extract state_dict for VQVAE
__lowerCamelCase : Dict = {}
__lowerCamelCase : List[Any] = """first_stage_model."""
for key in keys:
if key.startswith(UpperCAmelCase ):
__lowerCamelCase : Tuple = state_dict[key]
# extract state_dict for UNetLDM
__lowerCamelCase : Optional[int] = {}
__lowerCamelCase : Optional[Any] = """model.diffusion_model."""
for key in keys:
if key.startswith(UpperCAmelCase ):
__lowerCamelCase : Optional[int] = state_dict[key]
__lowerCamelCase : Dict = config.model.params.first_stage_config.params
__lowerCamelCase : str = config.model.params.unet_config.params
__lowerCamelCase : Any = VQModel(**UpperCAmelCase ).eval()
vqvae.load_state_dict(UpperCAmelCase )
__lowerCamelCase : List[str] = UNetLDMModel(**UpperCAmelCase ).eval()
unet.load_state_dict(UpperCAmelCase )
__lowerCamelCase : str = DDIMScheduler(
timesteps=config.model.params.timesteps , beta_schedule="""scaled_linear""" , beta_start=config.model.params.linear_start , beta_end=config.model.params.linear_end , clip_sample=UpperCAmelCase , )
__lowerCamelCase : Union[str, Any] = LDMPipeline(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase )
pipeline.save_pretrained(UpperCAmelCase )
if __name__ == "__main__":
__UpperCamelCase : Tuple = argparse.ArgumentParser()
parser.add_argument('--checkpoint_path', type=str, required=True)
parser.add_argument('--config_path', type=str, required=True)
parser.add_argument('--output_path', type=str, required=True)
__UpperCamelCase : List[str] = parser.parse_args()
convert_ldm_original(args.checkpoint_path, args.config_path, args.output_path)
| 715 |
def _UpperCAmelCase ( ):
"""simple docstring"""
__lowerCamelCase : Optional[int] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
__lowerCamelCase : str = 6
__lowerCamelCase : Optional[int] = 1
__lowerCamelCase : Optional[int] = 1_901
__lowerCamelCase : Optional[Any] = 0
while year < 2_001:
day += 7
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
if day > days_per_month[month - 1] and month != 2:
month += 1
__lowerCamelCase : Tuple = day - days_per_month[month - 2]
elif day > 29 and month == 2:
month += 1
__lowerCamelCase : str = day - 29
else:
if day > days_per_month[month - 1]:
month += 1
__lowerCamelCase : Any = day - days_per_month[month - 2]
if month > 12:
year += 1
__lowerCamelCase : Optional[Any] = 1
if year < 2_001 and day == 1:
sundays += 1
return sundays
if __name__ == "__main__":
print(solution())
| 458 | 0 |
import numpy as np
from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey
def lowercase__ ( A_: int , A_: int , A_: int , A_: int , A_: int , A_: int ) -> np.ndarray:
"""simple docstring"""
if (ksize % 2) == 0:
__UpperCAmelCase =ksize + 1
__UpperCAmelCase =np.zeros((ksize, ksize) , dtype=np.floataa )
# each value
for y in range(A_ ):
for x in range(A_ ):
# distance from center
__UpperCAmelCase =x - ksize // 2
__UpperCAmelCase =y - ksize // 2
# degree to radiant
__UpperCAmelCase =theta / 180 * np.pi
__UpperCAmelCase =np.cos(_theta )
__UpperCAmelCase =np.sin(_theta )
# get kernel x
__UpperCAmelCase =cos_theta * px + sin_theta * py
# get kernel y
__UpperCAmelCase =-sin_theta * px + cos_theta * py
# fill kernel
__UpperCAmelCase =np.exp(
-(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi )
return gabor
if __name__ == "__main__":
import doctest
doctest.testmod()
# read original image
__A = imread("../image_data/lena.jpg")
# turn image in gray scale value
__A = cvtColor(img, COLOR_BGR2GRAY)
# Apply multiple Kernel to detect edges
__A = np.zeros(gray.shape[:2])
for theta in [0, 30, 60, 90, 1_20, 1_50]:
__A = gabor_filter_kernel(10, 8, theta, 10, 0, 0)
out += filteraD(gray, CV_8UC3, kernel_aa)
__A = out / out.max() * 2_55
__A = out.astype(np.uinta)
imshow("Original", gray)
imshow("Gabor filter with 20x20 mask and 6 directions", out)
waitKey(0)
| 68 |
import unittest
import numpy as np
def snake_case (UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = None , ) -> np.ndarray:
UpperCamelCase_: str = np.shape(UpperCAmelCase__ )
UpperCamelCase_: str = np.shape(UpperCAmelCase__ )
UpperCamelCase_: List[Any] = np.shape(UpperCAmelCase__ )
if shape_a[0] != shape_b[0]:
UpperCamelCase_: Any = (
'Expected the same number of rows for A and B. '
F'''Instead found A of size {shape_a} and B of size {shape_b}'''
)
raise ValueError(UpperCAmelCase__ )
if shape_b[1] != shape_c[1]:
UpperCamelCase_: int = (
'Expected the same number of columns for B and C. '
F'''Instead found B of size {shape_b} and C of size {shape_c}'''
)
raise ValueError(UpperCAmelCase__ )
UpperCamelCase_: Dict = pseudo_inv
if a_inv is None:
try:
UpperCamelCase_: Optional[Any] = np.linalg.inv(UpperCAmelCase__ )
except np.linalg.LinAlgError:
raise ValueError(
'Input matrix A is not invertible. Cannot compute Schur complement.' )
return mat_c - mat_b.T @ a_inv @ mat_b
class _lowerCAmelCase( unittest.TestCase ):
"""simple docstring"""
def _a ( self ):
UpperCamelCase_: Any = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] )
UpperCamelCase_: Dict = np.array([[0, 3], [3, 0], [2, 3]] )
UpperCamelCase_: Tuple = np.array([[2, 1], [6, 3]] )
UpperCamelCase_: Tuple = schur_complement(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
UpperCamelCase_: Optional[Any] = np.block([[a, b], [b.T, c]] )
UpperCamelCase_: List[str] = np.linalg.det(_lowerCamelCase )
UpperCamelCase_: List[str] = np.linalg.det(_lowerCamelCase )
UpperCamelCase_: Dict = np.linalg.det(_lowerCamelCase )
self.assertAlmostEqual(_lowerCamelCase , det_a * det_s )
def _a ( self ):
UpperCamelCase_: int = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] )
UpperCamelCase_: List[str] = np.array([[0, 3], [3, 0], [2, 3]] )
UpperCamelCase_: List[str] = np.array([[2, 1], [6, 3]] )
with self.assertRaises(_lowerCamelCase ):
schur_complement(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
def _a ( self ):
UpperCamelCase_: List[Any] = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] )
UpperCamelCase_: str = np.array([[0, 3], [3, 0], [2, 3]] )
UpperCamelCase_: List[Any] = np.array([[2, 1, 3], [6, 3, 5]] )
with self.assertRaises(_lowerCamelCase ):
schur_complement(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
if __name__ == "__main__":
import doctest
doctest.testmod()
unittest.main() | 57 | 0 |
'''simple docstring'''
import json
import os
from functools import lru_cache
from typing import Dict, List, Optional, Tuple, Union
import regex as re
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...tokenization_utils_base import BatchEncoding, EncodedInput
from ...utils import PaddingStrategy, logging
__snake_case : Dict = logging.get_logger(__name__)
__snake_case : Any = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt'}
# See all LED models at https://huggingface.co/models?filter=LED
__snake_case : int = {
'vocab_file': {
'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json',
},
'merges_file': {
'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt',
},
'tokenizer_file': {
'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json',
},
}
__snake_case : Dict = {
'allenai/led-base-16384': 16_384,
}
@lru_cache()
# Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode
def _UpperCAmelCase ( ) -> Union[str, Any]:
A_ = (
list(range(ord('''!''' ), ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ), ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ), ord('''ÿ''' ) + 1 ) )
)
A_ = bs[:]
A_ = 0
for b in range(2**8 ):
if b not in bs:
bs.append(_UpperCamelCase )
cs.append(2**8 + n )
n += 1
A_ = [chr(_UpperCamelCase ) for n in cs]
return dict(zip(_UpperCamelCase, _UpperCamelCase ) )
def _UpperCAmelCase ( _UpperCamelCase : Optional[int] ) -> str:
A_ = set()
A_ = word[0]
for char in word[1:]:
pairs.add((prev_char, char) )
A_ = char
return pairs
class __UpperCAmelCase ( _UpperCamelCase ):
'''simple docstring'''
__lowercase : int = VOCAB_FILES_NAMES
__lowercase : str = PRETRAINED_VOCAB_FILES_MAP
__lowercase : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__lowercase : Optional[int] = ['input_ids', 'attention_mask']
def __init__( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE="replace" , _SCREAMING_SNAKE_CASE="<s>" , _SCREAMING_SNAKE_CASE="</s>" , _SCREAMING_SNAKE_CASE="</s>" , _SCREAMING_SNAKE_CASE="<s>" , _SCREAMING_SNAKE_CASE="<unk>" , _SCREAMING_SNAKE_CASE="<pad>" , _SCREAMING_SNAKE_CASE="<mask>" , _SCREAMING_SNAKE_CASE=False , **_SCREAMING_SNAKE_CASE , ) -> Any:
A_ = AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else bos_token
A_ = AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else eos_token
A_ = AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else sep_token
A_ = AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else cls_token
A_ = AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else unk_token
A_ = AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else pad_token
# Mask token behave like a normal word, i.e. include the space before it
A_ = AddedToken(_SCREAMING_SNAKE_CASE , lstrip=_SCREAMING_SNAKE_CASE , rstrip=_SCREAMING_SNAKE_CASE ) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else mask_token
super().__init__(
errors=_SCREAMING_SNAKE_CASE , bos_token=_SCREAMING_SNAKE_CASE , eos_token=_SCREAMING_SNAKE_CASE , unk_token=_SCREAMING_SNAKE_CASE , sep_token=_SCREAMING_SNAKE_CASE , cls_token=_SCREAMING_SNAKE_CASE , pad_token=_SCREAMING_SNAKE_CASE , mask_token=_SCREAMING_SNAKE_CASE , add_prefix_space=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , )
with open(_SCREAMING_SNAKE_CASE , encoding='''utf-8''' ) as vocab_handle:
A_ = json.load(_SCREAMING_SNAKE_CASE )
A_ = {v: k for k, v in self.encoder.items()}
A_ = errors # how to handle errors in decoding
A_ = bytes_to_unicode()
A_ = {v: k for k, v in self.byte_encoder.items()}
with open(_SCREAMING_SNAKE_CASE , encoding='''utf-8''' ) as merges_handle:
A_ = merges_handle.read().split('''\n''' )[1:-1]
A_ = [tuple(merge.split() ) for merge in bpe_merges]
A_ = dict(zip(_SCREAMING_SNAKE_CASE , range(len(_SCREAMING_SNAKE_CASE ) ) ) )
A_ = {}
A_ = add_prefix_space
# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
A_ = re.compile(R'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' )
@property
# Copied from transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size
def __A ( self ) -> Any:
return len(self.encoder )
def __A ( self ) -> str:
return dict(self.encoder , **self.added_tokens_encoder )
def __A ( self , _SCREAMING_SNAKE_CASE ) -> int:
if token in self.cache:
return self.cache[token]
A_ = tuple(_SCREAMING_SNAKE_CASE )
A_ = get_pairs(_SCREAMING_SNAKE_CASE )
if not pairs:
return token
while True:
A_ = min(_SCREAMING_SNAKE_CASE , key=lambda _SCREAMING_SNAKE_CASE : self.bpe_ranks.get(_SCREAMING_SNAKE_CASE , float('''inf''' ) ) )
if bigram not in self.bpe_ranks:
break
A_ ,A_ = bigram
A_ = []
A_ = 0
while i < len(_SCREAMING_SNAKE_CASE ):
try:
A_ = word.index(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
except ValueError:
new_word.extend(word[i:] )
break
else:
new_word.extend(word[i:j] )
A_ = j
if word[i] == first and i < len(_SCREAMING_SNAKE_CASE ) - 1 and word[i + 1] == second:
new_word.append(first + second )
i += 2
else:
new_word.append(word[i] )
i += 1
A_ = tuple(_SCREAMING_SNAKE_CASE )
A_ = new_word
if len(_SCREAMING_SNAKE_CASE ) == 1:
break
else:
A_ = get_pairs(_SCREAMING_SNAKE_CASE )
A_ = ''' '''.join(_SCREAMING_SNAKE_CASE )
A_ = word
return word
def __A ( self , _SCREAMING_SNAKE_CASE ) -> Optional[Any]:
A_ = []
for token in re.findall(self.pat , _SCREAMING_SNAKE_CASE ):
A_ = ''''''.join(
self.byte_encoder[b] for b in token.encode('''utf-8''' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_SCREAMING_SNAKE_CASE ).split(''' ''' ) )
return bpe_tokens
def __A ( self , _SCREAMING_SNAKE_CASE ) -> Optional[Any]:
return self.encoder.get(_SCREAMING_SNAKE_CASE , self.encoder.get(self.unk_token ) )
def __A ( self , _SCREAMING_SNAKE_CASE ) -> Any:
return self.decoder.get(_SCREAMING_SNAKE_CASE )
def __A ( self , _SCREAMING_SNAKE_CASE ) -> Optional[int]:
A_ = ''''''.join(_SCREAMING_SNAKE_CASE )
A_ = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''' , errors=self.errors )
return text
def __A ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> Tuple[str]:
if not os.path.isdir(_SCREAMING_SNAKE_CASE ):
logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' )
return
A_ = os.path.join(
_SCREAMING_SNAKE_CASE , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )
A_ = os.path.join(
_SCREAMING_SNAKE_CASE , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] )
with open(_SCREAMING_SNAKE_CASE , '''w''' , encoding='''utf-8''' ) as f:
f.write(json.dumps(self.encoder , indent=2 , sort_keys=_SCREAMING_SNAKE_CASE , ensure_ascii=_SCREAMING_SNAKE_CASE ) + '''\n''' )
A_ = 0
with open(_SCREAMING_SNAKE_CASE , '''w''' , encoding='''utf-8''' ) as writer:
writer.write('''#version: 0.2\n''' )
for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda _SCREAMING_SNAKE_CASE : kv[1] ):
if index != token_index:
logger.warning(
F'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.'''
''' Please check that the tokenizer is not corrupted!''' )
A_ = token_index
writer.write(''' '''.join(_SCREAMING_SNAKE_CASE ) + '''\n''' )
index += 1
return vocab_file, merge_file
def __A ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> List[int]:
if token_ids_a is None:
return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
A_ = [self.cls_token_id]
A_ = [self.sep_token_id]
return cls + token_ids_a + sep + sep + token_ids_a + sep
def __A ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = False ) -> List[int]:
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=_SCREAMING_SNAKE_CASE , token_ids_a=_SCREAMING_SNAKE_CASE , already_has_special_tokens=_SCREAMING_SNAKE_CASE )
if token_ids_a is None:
return [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1]
return [1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1, 1] + ([0] * len(_SCREAMING_SNAKE_CASE )) + [1]
def __A ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None ) -> List[int]:
A_ = [self.sep_token_id]
A_ = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
def __A ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=False , **_SCREAMING_SNAKE_CASE ) -> Any:
A_ = kwargs.pop('''add_prefix_space''' , self.add_prefix_space )
if (is_split_into_words or add_prefix_space) and (len(_SCREAMING_SNAKE_CASE ) > 0 and not text[0].isspace()):
A_ = ''' ''' + text
return (text, kwargs)
def __A ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = PaddingStrategy.DO_NOT_PAD , _SCREAMING_SNAKE_CASE = None , _SCREAMING_SNAKE_CASE = None , ) -> dict:
A_ = super()._pad(
encoded_inputs=_SCREAMING_SNAKE_CASE , max_length=_SCREAMING_SNAKE_CASE , padding_strategy=_SCREAMING_SNAKE_CASE , pad_to_multiple_of=_SCREAMING_SNAKE_CASE , return_attention_mask=_SCREAMING_SNAKE_CASE , )
# Load from model defaults
if return_attention_mask is None:
A_ = '''attention_mask''' in self.model_input_names
if return_attention_mask and "global_attention_mask" in encoded_inputs:
A_ = encoded_inputs[self.model_input_names[0]]
# `global_attention_mask` need to have the same length as other (sequential) inputs.
A_ = len(encoded_inputs['''global_attention_mask'''] ) != len(_SCREAMING_SNAKE_CASE )
if needs_to_be_padded:
A_ = len(_SCREAMING_SNAKE_CASE ) - len(encoded_inputs['''global_attention_mask'''] )
if self.padding_side == "right":
# Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend`
A_ = (
encoded_inputs['''global_attention_mask'''] + [-1] * difference
)
elif self.padding_side == "left":
A_ = [-1] * difference + encoded_inputs[
'''global_attention_mask'''
]
else:
raise ValueError('''Invalid padding strategy:''' + str(self.padding_side ) )
return encoded_inputs
| 174 | '''simple docstring'''
import gc
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMScheduler,
EulerAncestralDiscreteScheduler,
LMSDiscreteScheduler,
PNDMScheduler,
StableDiffusionPanoramaPipeline,
UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps
from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin
enable_full_determinism()
@skip_mps
class __UpperCAmelCase ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ):
'''simple docstring'''
__lowercase : Optional[Any] = StableDiffusionPanoramaPipeline
__lowercase : Optional[Any] = TEXT_TO_IMAGE_PARAMS
__lowercase : Optional[int] = TEXT_TO_IMAGE_BATCH_PARAMS
__lowercase : Dict = TEXT_TO_IMAGE_IMAGE_PARAMS
__lowercase : str = TEXT_TO_IMAGE_IMAGE_PARAMS
def __A ( self ) -> int:
torch.manual_seed(0 )
A_ = UNetaDConditionModel(
block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , )
A_ = DDIMScheduler()
torch.manual_seed(0 )
A_ = AutoencoderKL(
block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , )
torch.manual_seed(0 )
A_ = CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , )
A_ = CLIPTextModel(_SCREAMING_SNAKE_CASE )
A_ = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' )
A_ = {
'''unet''': unet,
'''scheduler''': scheduler,
'''vae''': vae,
'''text_encoder''': text_encoder,
'''tokenizer''': tokenizer,
'''safety_checker''': None,
'''feature_extractor''': None,
}
return components
def __A ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=0 ) -> str:
A_ = torch.manual_seed(_SCREAMING_SNAKE_CASE )
A_ = {
'''prompt''': '''a photo of the dolomites''',
'''generator''': generator,
# Setting height and width to None to prevent OOMs on CPU.
'''height''': None,
'''width''': None,
'''num_inference_steps''': 1,
'''guidance_scale''': 6.0,
'''output_type''': '''numpy''',
}
return inputs
def __A ( self ) -> List[Any]:
A_ = '''cpu''' # ensure determinism for the device-dependent torch.Generator
A_ = self.get_dummy_components()
A_ = StableDiffusionPanoramaPipeline(**_SCREAMING_SNAKE_CASE )
A_ = sd_pipe.to(_SCREAMING_SNAKE_CASE )
sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE )
A_ = self.get_dummy_inputs(_SCREAMING_SNAKE_CASE )
A_ = sd_pipe(**_SCREAMING_SNAKE_CASE ).images
A_ = image[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
A_ = np.array([0.6_186, 0.5_374, 0.4_915, 0.4_135, 0.4_114, 0.4_563, 0.5_128, 0.4_977, 0.4_757] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def __A ( self ) -> str:
super().test_inference_batch_consistent(batch_sizes=[1, 2] )
def __A ( self ) -> Union[str, Any]:
super().test_inference_batch_single_identical(batch_size=2 , expected_max_diff=3.25E-3 )
def __A ( self ) -> Union[str, Any]:
A_ = '''cpu''' # ensure determinism for the device-dependent torch.Generator
A_ = self.get_dummy_components()
A_ = StableDiffusionPanoramaPipeline(**_SCREAMING_SNAKE_CASE )
A_ = sd_pipe.to(_SCREAMING_SNAKE_CASE )
sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE )
A_ = self.get_dummy_inputs(_SCREAMING_SNAKE_CASE )
A_ = '''french fries'''
A_ = sd_pipe(**_SCREAMING_SNAKE_CASE , negative_prompt=_SCREAMING_SNAKE_CASE )
A_ = output.images
A_ = image[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
A_ = np.array([0.6_187, 0.5_375, 0.4_915, 0.4_136, 0.4_114, 0.4_563, 0.5_128, 0.4_976, 0.4_757] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def __A ( self ) -> Tuple:
A_ = '''cpu''' # ensure determinism for the device-dependent torch.Generator
A_ = self.get_dummy_components()
A_ = StableDiffusionPanoramaPipeline(**_SCREAMING_SNAKE_CASE )
A_ = sd_pipe.to(_SCREAMING_SNAKE_CASE )
sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE )
A_ = self.get_dummy_inputs(_SCREAMING_SNAKE_CASE )
A_ = sd_pipe(**_SCREAMING_SNAKE_CASE , view_batch_size=2 )
A_ = output.images
A_ = image[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
A_ = np.array([0.6_187, 0.5_375, 0.4_915, 0.4_136, 0.4_114, 0.4_563, 0.5_128, 0.4_976, 0.4_757] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def __A ( self ) -> Any:
A_ = '''cpu''' # ensure determinism for the device-dependent torch.Generator
A_ = self.get_dummy_components()
A_ = EulerAncestralDiscreteScheduler(
beta_start=0.00_085 , beta_end=0.012 , beta_schedule='''scaled_linear''' )
A_ = StableDiffusionPanoramaPipeline(**_SCREAMING_SNAKE_CASE )
A_ = sd_pipe.to(_SCREAMING_SNAKE_CASE )
sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE )
A_ = self.get_dummy_inputs(_SCREAMING_SNAKE_CASE )
A_ = sd_pipe(**_SCREAMING_SNAKE_CASE ).images
A_ = image[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
A_ = np.array([0.4_024, 0.6_510, 0.4_901, 0.5_378, 0.5_813, 0.5_622, 0.4_795, 0.4_467, 0.4_952] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def __A ( self ) -> str:
A_ = '''cpu''' # ensure determinism for the device-dependent torch.Generator
A_ = self.get_dummy_components()
A_ = PNDMScheduler(
beta_start=0.00_085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , skip_prk_steps=_SCREAMING_SNAKE_CASE )
A_ = StableDiffusionPanoramaPipeline(**_SCREAMING_SNAKE_CASE )
A_ = sd_pipe.to(_SCREAMING_SNAKE_CASE )
sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE )
A_ = self.get_dummy_inputs(_SCREAMING_SNAKE_CASE )
A_ = sd_pipe(**_SCREAMING_SNAKE_CASE ).images
A_ = image[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
A_ = np.array([0.6_391, 0.6_291, 0.4_861, 0.5_134, 0.5_552, 0.4_578, 0.5_032, 0.5_023, 0.4_539] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
@slow
@require_torch_gpu
class __UpperCAmelCase ( unittest.TestCase ):
'''simple docstring'''
def __A ( self ) -> Union[str, Any]:
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def __A ( self , _SCREAMING_SNAKE_CASE=0 ) -> List[Any]:
A_ = torch.manual_seed(_SCREAMING_SNAKE_CASE )
A_ = {
'''prompt''': '''a photo of the dolomites''',
'''generator''': generator,
'''num_inference_steps''': 3,
'''guidance_scale''': 7.5,
'''output_type''': '''numpy''',
}
return inputs
def __A ( self ) -> List[Any]:
A_ = '''stabilityai/stable-diffusion-2-base'''
A_ = DDIMScheduler.from_pretrained(_SCREAMING_SNAKE_CASE , subfolder='''scheduler''' )
A_ = StableDiffusionPanoramaPipeline.from_pretrained(_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE , safety_checker=_SCREAMING_SNAKE_CASE )
pipe.to(_SCREAMING_SNAKE_CASE )
pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE )
pipe.enable_attention_slicing()
A_ = self.get_inputs()
A_ = pipe(**_SCREAMING_SNAKE_CASE ).images
A_ = image[0, -3:, -3:, -1].flatten()
assert image.shape == (1, 512, 2048, 3)
A_ = np.array(
[
0.36_968_392,
0.27_025_372,
0.32_446_766,
0.28_379_387,
0.36_363_274,
0.30_733_347,
0.27_100_027,
0.27_054_125,
0.25_536_096,
] )
assert np.abs(expected_slice - image_slice ).max() < 1E-2
def __A ( self ) -> Optional[int]:
A_ = StableDiffusionPanoramaPipeline.from_pretrained(
'''stabilityai/stable-diffusion-2-base''' , safety_checker=_SCREAMING_SNAKE_CASE )
A_ = LMSDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.to(_SCREAMING_SNAKE_CASE )
pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE )
pipe.enable_attention_slicing()
A_ = self.get_inputs()
A_ = pipe(**_SCREAMING_SNAKE_CASE ).images
A_ = image[0, -3:, -3:, -1].flatten()
assert image.shape == (1, 512, 2048, 3)
A_ = np.array(
[
[
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
]
] )
assert np.abs(expected_slice - image_slice ).max() < 1E-3
def __A ( self ) -> List[str]:
A_ = 0
def callback_fn(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> None:
A_ = True
nonlocal number_of_steps
number_of_steps += 1
if step == 1:
A_ = latents.detach().cpu().numpy()
assert latents.shape == (1, 4, 64, 256)
A_ = latents[0, -3:, -3:, -1]
A_ = np.array(
[
0.18_681_869,
0.33_907_816,
0.5_361_276,
0.14_432_865,
-0.02_856_611,
-0.73_941_123,
0.23_397_987,
0.47_322_682,
-0.37_823_164,
] )
assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2
elif step == 2:
A_ = latents.detach().cpu().numpy()
assert latents.shape == (1, 4, 64, 256)
A_ = latents[0, -3:, -3:, -1]
A_ = np.array(
[
0.18_539_645,
0.33_987_248,
0.5_378_559,
0.14_437_142,
-0.02_455_261,
-0.7_338_317,
0.23_990_755,
0.47_356_272,
-0.3_786_505,
] )
assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2
A_ = False
A_ = '''stabilityai/stable-diffusion-2-base'''
A_ = DDIMScheduler.from_pretrained(_SCREAMING_SNAKE_CASE , subfolder='''scheduler''' )
A_ = StableDiffusionPanoramaPipeline.from_pretrained(_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE , safety_checker=_SCREAMING_SNAKE_CASE )
A_ = pipe.to(_SCREAMING_SNAKE_CASE )
pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE )
pipe.enable_attention_slicing()
A_ = self.get_inputs()
pipe(**_SCREAMING_SNAKE_CASE , callback=_SCREAMING_SNAKE_CASE , callback_steps=1 )
assert callback_fn.has_been_called
assert number_of_steps == 3
def __A ( self ) -> str:
torch.cuda.empty_cache()
torch.cuda.reset_max_memory_allocated()
torch.cuda.reset_peak_memory_stats()
A_ = '''stabilityai/stable-diffusion-2-base'''
A_ = DDIMScheduler.from_pretrained(_SCREAMING_SNAKE_CASE , subfolder='''scheduler''' )
A_ = StableDiffusionPanoramaPipeline.from_pretrained(_SCREAMING_SNAKE_CASE , scheduler=_SCREAMING_SNAKE_CASE , safety_checker=_SCREAMING_SNAKE_CASE )
A_ = pipe.to(_SCREAMING_SNAKE_CASE )
pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE )
pipe.enable_attention_slicing(1 )
pipe.enable_sequential_cpu_offload()
A_ = self.get_inputs()
A_ = pipe(**_SCREAMING_SNAKE_CASE )
A_ = torch.cuda.max_memory_allocated()
# make sure that less than 5.2 GB is allocated
assert mem_bytes < 5.5 * 10**9
| 174 | 1 |
import random
import unittest
import numpy as np
from diffusers import (
DPMSolverMultistepScheduler,
EulerAncestralDiscreteScheduler,
EulerDiscreteScheduler,
LMSDiscreteScheduler,
OnnxStableDiffusionImgaImgPipeline,
PNDMScheduler,
)
from diffusers.utils import floats_tensor
from diffusers.utils.testing_utils import (
is_onnx_available,
load_image,
nightly,
require_onnxruntime,
require_torch_gpu,
)
from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin
if is_onnx_available():
import onnxruntime as ort
class _A ( UpperCamelCase , unittest.TestCase ):
"""simple docstring"""
lowerCamelCase : List[Any] = 'hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline'
def _a ( self : Optional[int] , __SCREAMING_SNAKE_CASE : str=0 ) -> Any:
__UpperCAmelCase =floats_tensor((1, 3, 128, 128) , rng=random.Random(__SCREAMING_SNAKE_CASE ) )
__UpperCAmelCase =np.random.RandomState(__SCREAMING_SNAKE_CASE )
__UpperCAmelCase ={
"""prompt""": """A painting of a squirrel eating a burger""",
"""image""": image,
"""generator""": generator,
"""num_inference_steps""": 3,
"""strength""": 0.75,
"""guidance_scale""": 7.5,
"""output_type""": """numpy""",
}
return inputs
def _a ( self : Optional[Any] ) -> int:
__UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" )
pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE )
__UpperCAmelCase =self.get_dummy_inputs()
__UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images
__UpperCAmelCase =image[0, -3:, -3:, -1].flatten()
assert image.shape == (1, 128, 128, 3)
__UpperCAmelCase =np.array([0.69_643, 0.58_484, 0.50_314, 0.58_760, 0.55_368, 0.59_643, 0.51_529, 0.41_217, 0.49_087] )
assert np.abs(image_slice - expected_slice ).max() < 1e-1
def _a ( self : Union[str, Any] ) -> Union[str, Any]:
__UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" )
__UpperCAmelCase =PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=__SCREAMING_SNAKE_CASE )
pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE )
__UpperCAmelCase =self.get_dummy_inputs()
__UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images
__UpperCAmelCase =image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
__UpperCAmelCase =np.array([0.61_737, 0.54_642, 0.53_183, 0.54_465, 0.52_742, 0.60_525, 0.49_969, 0.40_655, 0.48_154] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
def _a ( self : Optional[Any] ) -> Dict:
__UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" )
__UpperCAmelCase =LMSDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE )
# warmup pass to apply optimizations
__UpperCAmelCase =pipe(**self.get_dummy_inputs() )
__UpperCAmelCase =self.get_dummy_inputs()
__UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images
__UpperCAmelCase =image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
__UpperCAmelCase =np.array([0.52_761, 0.59_977, 0.49_033, 0.49_619, 0.54_282, 0.50_311, 0.47_600, 0.40_918, 0.45_203] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
def _a ( self : List[Any] ) -> List[str]:
__UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" )
__UpperCAmelCase =EulerDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE )
__UpperCAmelCase =self.get_dummy_inputs()
__UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images
__UpperCAmelCase =image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
__UpperCAmelCase =np.array([0.52_911, 0.60_004, 0.49_229, 0.49_805, 0.54_502, 0.50_680, 0.47_777, 0.41_028, 0.45_304] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
def _a ( self : Union[str, Any] ) -> Optional[Any]:
__UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" )
__UpperCAmelCase =EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE )
__UpperCAmelCase =self.get_dummy_inputs()
__UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images
__UpperCAmelCase =image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
__UpperCAmelCase =np.array([0.52_911, 0.60_004, 0.49_229, 0.49_805, 0.54_502, 0.50_680, 0.47_777, 0.41_028, 0.45_304] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
def _a ( self : Union[str, Any] ) -> Dict:
__UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider="""CPUExecutionProvider""" )
__UpperCAmelCase =DPMSolverMultistepScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE )
__UpperCAmelCase =self.get_dummy_inputs()
__UpperCAmelCase =pipe(**__SCREAMING_SNAKE_CASE ).images
__UpperCAmelCase =image[0, -3:, -3:, -1]
assert image.shape == (1, 128, 128, 3)
__UpperCAmelCase =np.array([0.65_331, 0.58_277, 0.48_204, 0.56_059, 0.53_665, 0.56_235, 0.50_969, 0.40_009, 0.46_552] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1
@nightly
@require_onnxruntime
@require_torch_gpu
class _A ( unittest.TestCase ):
"""simple docstring"""
@property
def _a ( self : List[str] ) -> Optional[int]:
return (
"CUDAExecutionProvider",
{
"gpu_mem_limit": "15000000000", # 15GB
"arena_extend_strategy": "kSameAsRequested",
},
)
@property
def _a ( self : Dict ) -> int:
__UpperCAmelCase =ort.SessionOptions()
__UpperCAmelCase =False
return options
def _a ( self : Dict ) -> Any:
__UpperCAmelCase =load_image(
"""https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
"""/img2img/sketch-mountains-input.jpg""" )
__UpperCAmelCase =init_image.resize((768, 512) )
# using the PNDM scheduler by default
__UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(
"""CompVis/stable-diffusion-v1-4""" , revision="""onnx""" , safety_checker=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE , provider=self.gpu_provider , sess_options=self.gpu_options , )
pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE )
__UpperCAmelCase ="""A fantasy landscape, trending on artstation"""
__UpperCAmelCase =np.random.RandomState(0 )
__UpperCAmelCase =pipe(
prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , strength=0.75 , guidance_scale=7.5 , num_inference_steps=10 , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , )
__UpperCAmelCase =output.images
__UpperCAmelCase =images[0, 255:258, 383:386, -1]
assert images.shape == (1, 512, 768, 3)
__UpperCAmelCase =np.array([0.4_909, 0.5_059, 0.5_372, 0.4_623, 0.4_876, 0.5_049, 0.4_820, 0.4_956, 0.5_019] )
# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues
assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
def _a ( self : List[str] ) -> str:
__UpperCAmelCase =load_image(
"""https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
"""/img2img/sketch-mountains-input.jpg""" )
__UpperCAmelCase =init_image.resize((768, 512) )
__UpperCAmelCase =LMSDiscreteScheduler.from_pretrained(
"""runwayml/stable-diffusion-v1-5""" , subfolder="""scheduler""" , revision="""onnx""" )
__UpperCAmelCase =OnnxStableDiffusionImgaImgPipeline.from_pretrained(
"""runwayml/stable-diffusion-v1-5""" , revision="""onnx""" , scheduler=__SCREAMING_SNAKE_CASE , safety_checker=__SCREAMING_SNAKE_CASE , feature_extractor=__SCREAMING_SNAKE_CASE , provider=self.gpu_provider , sess_options=self.gpu_options , )
pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE )
__UpperCAmelCase ="""A fantasy landscape, trending on artstation"""
__UpperCAmelCase =np.random.RandomState(0 )
__UpperCAmelCase =pipe(
prompt=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , strength=0.75 , guidance_scale=7.5 , num_inference_steps=20 , generator=__SCREAMING_SNAKE_CASE , output_type="""np""" , )
__UpperCAmelCase =output.images
__UpperCAmelCase =images[0, 255:258, 383:386, -1]
assert images.shape == (1, 512, 768, 3)
__UpperCAmelCase =np.array([0.8_043, 0.926, 0.9_581, 0.8_119, 0.8_954, 0.913, 0.7_209, 0.7_463, 0.7_431] )
# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues
assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
| 68 | """simple docstring"""
import unittest
import numpy as np
import timeout_decorator # noqa
from transformers import BlenderbotSmallConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor
if is_flax_available():
import os
# The slow tests are often failing with OOM error on GPU
# This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
# but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
SCREAMING_SNAKE_CASE__:List[Any] = """platform"""
import jax
import jax.numpy as jnp
from transformers.models.blenderbot_small.modeling_flax_blenderbot_small import (
FlaxBlenderbotSmallForConditionalGeneration,
FlaxBlenderbotSmallModel,
shift_tokens_right,
)
def _lowerCamelCase( a , a , a=None , a=None , a=None , a=None , a=None , a=None , ):
if attention_mask is None:
__a = np.where(input_ids != config.pad_token_id , 1 , 0 )
if decoder_attention_mask is None:
__a = np.where(decoder_input_ids != config.pad_token_id , 1 , 0 )
if head_mask is None:
__a = np.ones((config.encoder_layers, config.encoder_attention_heads) )
if decoder_head_mask is None:
__a = np.ones((config.decoder_layers, config.decoder_attention_heads) )
if cross_attn_head_mask is None:
__a = np.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": attention_mask,
}
class snake_case__ :
def __init__( self , lowerCamelCase , lowerCamelCase=13 , lowerCamelCase=7 , lowerCamelCase=True , lowerCamelCase=False , lowerCamelCase=99 , lowerCamelCase=16 , lowerCamelCase=2 , lowerCamelCase=4 , lowerCamelCase=4 , lowerCamelCase="gelu" , lowerCamelCase=0.1 , lowerCamelCase=0.1 , lowerCamelCase=32 , lowerCamelCase=2 , lowerCamelCase=1 , lowerCamelCase=0 , lowerCamelCase=0.02 , ):
__a = parent
__a = batch_size
__a = seq_length
__a = is_training
__a = use_labels
__a = vocab_size
__a = hidden_size
__a = num_hidden_layers
__a = num_attention_heads
__a = intermediate_size
__a = hidden_act
__a = hidden_dropout_prob
__a = attention_probs_dropout_prob
__a = max_position_embeddings
__a = eos_token_id
__a = pad_token_id
__a = bos_token_id
__a = initializer_range
def a__ ( self ):
__a = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size )
__a = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 )
__a = shift_tokens_right(lowerCamelCase , 1 , 2 )
__a = BlenderbotSmallConfig(
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_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=lowerCamelCase , )
__a = prepare_blenderbot_inputs_dict(lowerCamelCase , lowerCamelCase , lowerCamelCase )
return config, inputs_dict
def a__ ( self ):
__a , __a = self.prepare_config_and_inputs()
return config, inputs_dict
def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ):
__a = 20
__a = model_class_name(lowerCamelCase )
__a = model.encode(inputs_dict["input_ids"] )
__a , __a = (
inputs_dict["decoder_input_ids"],
inputs_dict["decoder_attention_mask"],
)
__a = model.init_cache(decoder_input_ids.shape[0] , lowerCamelCase , lowerCamelCase )
__a = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype="i4" )
__a = jnp.broadcast_to(
jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , )
__a = model.decode(
decoder_input_ids[:, :-1] , lowerCamelCase , decoder_attention_mask=lowerCamelCase , past_key_values=lowerCamelCase , decoder_position_ids=lowerCamelCase , )
__a = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" )
__a = model.decode(
decoder_input_ids[:, -1:] , lowerCamelCase , decoder_attention_mask=lowerCamelCase , past_key_values=outputs_cache.past_key_values , decoder_position_ids=lowerCamelCase , )
__a = model.decode(lowerCamelCase , lowerCamelCase )
__a = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) )
self.parent.assertTrue(diff < 1E-3 , msg=F"Max diff is {diff}" )
def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ):
__a = 20
__a = model_class_name(lowerCamelCase )
__a = model.encode(inputs_dict["input_ids"] )
__a , __a = (
inputs_dict["decoder_input_ids"],
inputs_dict["decoder_attention_mask"],
)
__a = jnp.concatenate(
[
decoder_attention_mask,
jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ),
] , axis=-1 , )
__a = model.init_cache(decoder_input_ids.shape[0] , lowerCamelCase , lowerCamelCase )
__a = jnp.broadcast_to(
jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , )
__a = model.decode(
decoder_input_ids[:, :-1] , lowerCamelCase , decoder_attention_mask=lowerCamelCase , past_key_values=lowerCamelCase , decoder_position_ids=lowerCamelCase , )
__a = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype="i4" )
__a = model.decode(
decoder_input_ids[:, -1:] , lowerCamelCase , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=lowerCamelCase , decoder_position_ids=lowerCamelCase , )
__a = model.decode(lowerCamelCase , lowerCamelCase , decoder_attention_mask=lowerCamelCase )
__a = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) )
self.parent.assertTrue(diff < 1E-3 , msg=F"Max diff is {diff}" )
@require_flax
class snake_case__ ( unittest.TestCase ):
_snake_case : Dict = 99
def a__ ( self ):
__a = np.array(
[
[71, 82, 18, 33, 46, 91, 2],
[68, 34, 26, 58, 30, 82, 2],
[5, 97, 17, 39, 94, 40, 2],
[76, 83, 94, 25, 70, 78, 2],
[87, 59, 41, 35, 48, 66, 2],
[55, 13, 16, 58, 5, 2, 1], # note padding
[64, 27, 31, 51, 12, 75, 2],
[52, 64, 86, 17, 83, 39, 2],
[48, 61, 9, 24, 71, 82, 2],
[26, 1, 60, 48, 22, 13, 2],
[21, 5, 62, 28, 14, 76, 2],
[45, 98, 37, 86, 59, 48, 2],
[70, 70, 50, 9, 28, 0, 2],
] , dtype=np.intaa , )
__a = input_ids.shape[0]
__a = BlenderbotSmallConfig(
vocab_size=self.vocab_size , d_model=24 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=32 , decoder_ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , )
return config, input_ids, batch_size
def a__ ( self ):
__a , __a , __a = self._get_config_and_data()
__a = FlaxBlenderbotSmallForConditionalGeneration(lowerCamelCase )
__a = lm_model(input_ids=lowerCamelCase )
__a = (batch_size, input_ids.shape[1], config.vocab_size)
self.assertEqual(outputs["logits"].shape , lowerCamelCase )
def a__ ( self ):
__a = BlenderbotSmallConfig(
vocab_size=self.vocab_size , d_model=14 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=48 , )
__a = FlaxBlenderbotSmallForConditionalGeneration(lowerCamelCase )
__a = np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]] , dtype=np.intaa )
__a = np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]] , dtype=np.intaa )
__a = lm_model(input_ids=lowerCamelCase , decoder_input_ids=lowerCamelCase )
__a = (*summary.shape, config.vocab_size)
self.assertEqual(outputs["logits"].shape , lowerCamelCase )
def a__ ( self ):
__a = np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]] , dtype=np.intaa )
__a = shift_tokens_right(lowerCamelCase , 1 , 2 )
__a = np.equal(lowerCamelCase , 1 ).astype(np.floataa ).sum()
__a = np.equal(lowerCamelCase , 1 ).astype(np.floataa ).sum()
self.assertEqual(shifted.shape , input_ids.shape )
self.assertEqual(lowerCamelCase , n_pad_before - 1 )
self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() )
@require_flax
class snake_case__ ( snake_case_, unittest.TestCase, snake_case_ ):
_snake_case : Any = True
_snake_case : int = (
(
FlaxBlenderbotSmallModel,
FlaxBlenderbotSmallForConditionalGeneration,
)
if is_flax_available()
else ()
)
_snake_case : str = (FlaxBlenderbotSmallForConditionalGeneration,) if is_flax_available() else ()
def a__ ( self ):
__a = FlaxBlenderbotSmallModelTester(self )
def a__ ( self ):
__a , __a = self.model_tester.prepare_config_and_inputs()
for model_class in self.all_model_classes:
self.model_tester.check_use_cache_forward(lowerCamelCase , lowerCamelCase , lowerCamelCase )
def a__ ( self ):
__a , __a = self.model_tester.prepare_config_and_inputs()
for model_class in self.all_model_classes:
self.model_tester.check_use_cache_forward_with_attn_mask(lowerCamelCase , lowerCamelCase , lowerCamelCase )
def a__ ( self ):
__a , __a = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
with self.subTest(model_class.__name__ ):
__a = self._prepare_for_class(lowerCamelCase , lowerCamelCase )
__a = model_class(lowerCamelCase )
@jax.jit
def encode_jitted(lowerCamelCase , lowerCamelCase=None , **lowerCamelCase ):
return model.encode(input_ids=lowerCamelCase , attention_mask=lowerCamelCase )
with self.subTest("JIT Enabled" ):
__a = encode_jitted(**lowerCamelCase ).to_tuple()
with self.subTest("JIT Disabled" ):
with jax.disable_jit():
__a = encode_jitted(**lowerCamelCase ).to_tuple()
self.assertEqual(len(lowerCamelCase ) , len(lowerCamelCase ) )
for jitted_output, output in zip(lowerCamelCase , lowerCamelCase ):
self.assertEqual(jitted_output.shape , output.shape )
def a__ ( self ):
__a , __a = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
with self.subTest(model_class.__name__ ):
__a = model_class(lowerCamelCase )
__a = model.encode(inputs_dict["input_ids"] , inputs_dict["attention_mask"] )
__a = {
"decoder_input_ids": inputs_dict["decoder_input_ids"],
"decoder_attention_mask": inputs_dict["decoder_attention_mask"],
"encoder_outputs": encoder_outputs,
}
@jax.jit
def decode_jitted(lowerCamelCase , lowerCamelCase , lowerCamelCase ):
return model.decode(
decoder_input_ids=lowerCamelCase , decoder_attention_mask=lowerCamelCase , encoder_outputs=lowerCamelCase , )
with self.subTest("JIT Enabled" ):
__a = decode_jitted(**lowerCamelCase ).to_tuple()
with self.subTest("JIT Disabled" ):
with jax.disable_jit():
__a = decode_jitted(**lowerCamelCase ).to_tuple()
self.assertEqual(len(lowerCamelCase ) , len(lowerCamelCase ) )
for jitted_output, output in zip(lowerCamelCase , lowerCamelCase ):
self.assertEqual(jitted_output.shape , output.shape )
@slow
def a__ ( self ):
for model_class_name in self.all_model_classes:
__a = model_class_name.from_pretrained("facebook/blenderbot_small-90M" )
# FlaxBlenderbotForSequenceClassification expects eos token in input_ids
__a = np.ones((1, 1) ) * model.config.eos_token_id
__a = model(lowerCamelCase )
self.assertIsNotNone(lowerCamelCase )
| 528 | 0 |
"""simple docstring"""
def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase ):
"""simple docstring"""
return [sentence[i : i + ngram_size] for i in range(len(__UpperCamelCase ) - ngram_size + 1 )]
if __name__ == "__main__":
from doctest import testmod
testmod()
| 215 |
"""simple docstring"""
lowercase_ = {'a': ['c', 'b'], 'b': ['d', 'e'], 'c': [], 'd': [], 'e': []}
lowercase_ = ['a', 'b', 'c', 'd', 'e']
def lowerCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ):
"""simple docstring"""
__A = start
# add current to visited
visited.append(__UpperCamelCase )
__A = edges[current]
for neighbor in neighbors:
# if neighbor not in visited, visit
if neighbor not in visited:
__A = topological_sort(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
# if all neighbors visited add current to sort
sort.append(__UpperCamelCase )
# if all vertices haven't been visited select a new one to visit
if len(__UpperCamelCase ) != len(__UpperCamelCase ):
for vertice in vertices:
if vertice not in visited:
__A = topological_sort(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase )
# return sort
return sort
if __name__ == "__main__":
lowercase_ = topological_sort('a', [], [])
print(sort)
| 215 | 1 |
import json
import multiprocessing as mp
import re
from collections import defaultdict
from functools import partial
from typing import Dict, List, Optional, Set, Tuple, Type
from datasets import Dataset
from datasketch import MinHash, MinHashLSH
from dpu_utils.utils.iterators import ThreadedIterator
from tqdm import tqdm
lowerCAmelCase_ = re.compile('''[^A-Za-z_0-9]''')
# parameters used in DuplicationIndex
lowerCAmelCase_ = 1_0
lowerCAmelCase_ = 2_5_6
def lowerCamelCase_ ( _UpperCamelCase ) -> Optional[MinHash]:
"""simple docstring"""
if len(_UpperCamelCase ) < MIN_NUM_TOKENS:
return None
snake_case_ : Optional[int] = MinHash(num_perm=_UpperCamelCase )
for token in set(_UpperCamelCase ):
min_hash.update(token.encode() )
return min_hash
def lowerCamelCase_ ( _UpperCamelCase ) -> Set[str]:
"""simple docstring"""
return {t for t in NON_ALPHA.split(_UpperCamelCase ) if len(t.strip() ) > 0}
class __lowerCAmelCase :
def __init__(self , *,
__magic_name__ = 0.85 , ) -> int:
'''simple docstring'''
snake_case_ : int = duplication_jaccard_threshold
snake_case_ : Tuple = NUM_PERM
snake_case_ : Dict = MinHashLSH(threshold=self._duplication_jaccard_threshold , num_perm=self._num_perm )
snake_case_ : Dict = defaultdict(__magic_name__ )
def lowerCamelCase (self , __magic_name__ , __magic_name__ ) -> None:
'''simple docstring'''
snake_case_ : str = self._index.query(__magic_name__ )
if code_key in self._index.keys:
print(F'''Duplicate key {code_key}''' )
return
self._index.insert(__magic_name__ , __magic_name__ )
if len(__magic_name__ ) > 0:
for base_duplicate in close_duplicates:
if base_duplicate in self._duplicate_clusters:
self._duplicate_clusters[base_duplicate].add(__magic_name__ )
break
else:
self._duplicate_clusters[close_duplicates[0]].add(__magic_name__ )
def lowerCamelCase (self ) -> List[List[Dict]]:
'''simple docstring'''
snake_case_ : List[Any] = []
for base, duplicates in self._duplicate_clusters.items():
snake_case_ : List[str] = [base] + list(__magic_name__ )
# reformat the cluster to be a list of dict
snake_case_ : int = [{'''base_index''': el[0], '''repo_name''': el[1], '''path''': el[2]} for el in cluster]
duplicate_clusters.append(__magic_name__ )
return duplicate_clusters
def lowerCamelCase (self , __magic_name__ ) -> None:
'''simple docstring'''
snake_case_ : Optional[Any] = self.get_duplicate_clusters()
with open(__magic_name__ , '''w''' ) as f:
json.dump(__magic_name__ , __magic_name__ )
def lowerCamelCase_ ( _UpperCamelCase ) -> str:
"""simple docstring"""
snake_case_ , snake_case_ : Any = element
snake_case_ : Tuple = get_min_hash([t for t in NON_ALPHA.split(data['''content'''] ) if len(t.strip() ) > 0] )
if min_hash is not None:
return (index, data["repo_name"], data["path"]), min_hash
def lowerCamelCase_ ( _UpperCamelCase ) -> Union[str, Any]:
"""simple docstring"""
with mp.Pool() as pool:
for data in pool.imap_unordered(
_compute_min_hash , ThreadedIterator(_UpperCamelCase , max_queue_size=10_000 ) , chunksize=100 , ):
if data is not None:
yield data
def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Union[str, Any]:
"""simple docstring"""
snake_case_ : Union[str, Any] = DuplicationIndex(duplication_jaccard_threshold=_UpperCamelCase )
for filename, min_hash in tqdm(ThreadedIterator(minhash_iter(enumerate(_UpperCamelCase ) ) , max_queue_size=100 ) ):
di.add(_UpperCamelCase , _UpperCamelCase )
# Returns a List[Cluster] where Cluster is List[str] with the filenames.
return di.get_duplicate_clusters()
def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> float:
"""simple docstring"""
snake_case_ : str = get_tokens(_UpperCamelCase )
snake_case_ : Optional[int] = get_tokens(_UpperCamelCase )
return len(tokensa & tokensa ) / len(tokensa | tokensa )
lowerCAmelCase_ = None
def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Tuple:
"""simple docstring"""
snake_case_ : Dict = []
for elementa in cluster:
snake_case_ : int = _shared_dataset[elementa['''base_index''']]['''content''']
for elementa in extremes:
snake_case_ : Dict = _shared_dataset[elementa['''base_index''']]['''content''']
if jaccard_similarity(_UpperCamelCase , _UpperCamelCase ) >= jaccard_threshold:
elementa["copies"] += 1
break
else:
snake_case_ : Optional[Any] = 1
extremes.append(_UpperCamelCase )
return extremes
def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> List[Any]:
"""simple docstring"""
global _shared_dataset
snake_case_ : Optional[Any] = dataset
snake_case_ : Union[str, Any] = []
snake_case_ : Any = partial(_find_cluster_extremes_shared , jaccard_threshold=_UpperCamelCase )
with mp.Pool() as pool:
for extremes in tqdm(
pool.imap_unordered(
_UpperCamelCase , _UpperCamelCase , ) , total=len(_UpperCamelCase ) , ):
extremes_list.append(_UpperCamelCase )
return extremes_list
def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase = 0.85 ) -> Tuple[Type[Dataset], List[List[Dict]]]:
"""simple docstring"""
snake_case_ : Optional[int] = make_duplicate_clusters(_UpperCamelCase , _UpperCamelCase )
snake_case_ : Union[str, Any] = {x['''base_index'''] for cluster in duplicate_clusters for x in cluster}
snake_case_ : Optional[Any] = {}
snake_case_ : str = find_extremes(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase )
for extremes in extremes_clusters:
for element in extremes:
snake_case_ : Dict = element
snake_case_ : List[Any] = duplicate_indices - set(extreme_dict.keys() )
snake_case_ : str = dataset.filter(lambda _UpperCamelCase , _UpperCamelCase : idx not in remove_indices , with_indices=_UpperCamelCase )
# update duplicate_clusters
for cluster in duplicate_clusters:
for element in cluster:
snake_case_ : str = element['''base_index'''] in extreme_dict
if element["is_extreme"]:
snake_case_ : Union[str, Any] = extreme_dict[element['''base_index''']]['''copies''']
print(f'''Original dataset size: {len(_UpperCamelCase )}''' )
print(f'''Number of duplicate clusters: {len(_UpperCamelCase )}''' )
print(f'''Files in duplicate cluster: {len(_UpperCamelCase )}''' )
print(f'''Unique files in duplicate cluster: {len(_UpperCamelCase )}''' )
print(f'''Filtered dataset size: {len(_UpperCamelCase )}''' )
return ds_filter, duplicate_clusters
| 60 | """simple docstring"""
import unittest
from transformers import GPTSwaTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
_a : int = get_tests_dir('fixtures/test_sentencepiece_with_bytefallback.model')
@require_sentencepiece
@require_tokenizers
class __A ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ):
_UpperCamelCase : str = GPTSwaTokenizer
_UpperCamelCase : Tuple = False
_UpperCamelCase : Union[str, Any] = True
_UpperCamelCase : Union[str, Any] = False
def __A ( self ):
super().setUp()
# We have a SentencePiece fixture for testing
_lowerCAmelCase : Any = GPTSwaTokenizer(a__ , eos_token="""<unk>""" , bos_token="""<unk>""" , pad_token="""<unk>""" )
tokenizer.save_pretrained(self.tmpdirname )
def __A ( self , a__ ):
_lowerCAmelCase : Optional[int] = """This is a test"""
_lowerCAmelCase : Optional[int] = """This is a test"""
return input_text, output_text
def __A ( self ):
_lowerCAmelCase : List[Any] = """<s>"""
_lowerCAmelCase : Any = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(a__ ) , a__ )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(a__ ) , a__ )
def __A ( self ):
_lowerCAmelCase : Any = 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__ ) , 2000 )
def __A ( self ):
self.assertEqual(self.get_tokenizer().vocab_size , 2000 )
def __A ( self ):
_lowerCAmelCase : Any = GPTSwaTokenizer(a__ )
_lowerCAmelCase : Optional[int] = tokenizer.tokenize("""This is a test""" )
self.assertListEqual(a__ , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(a__ ) , [465, 287, 265, 631, 842] )
_lowerCAmelCase : Tuple = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" )
# fmt: off
self.assertListEqual(
a__ , ["""▁I""", """▁was""", """▁bor""", """n""", """▁in""", """▁""", """<0x39>""", """2""", """0""", """0""", """0""", """,""", """▁and""", """▁this""", """▁is""", """▁f""", """al""", """s""", """<0xC3>""", """<0xA9>""", """."""] , )
# fmt: on
_lowerCAmelCase : List[str] = tokenizer.convert_tokens_to_ids(a__ )
self.assertListEqual(
a__ , [262, 272, 1525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260] , )
_lowerCAmelCase : Union[str, Any] = tokenizer.convert_ids_to_tokens(a__ )
# fmt: off
self.assertListEqual(
a__ , ["""▁I""", """▁was""", """▁bor""", """n""", """▁in""", """▁""", """<0x39>""", """2""", """0""", """0""", """0""", """,""", """▁and""", """▁this""", """▁is""", """▁f""", """al""", """s""", """<0xC3>""", """<0xA9>""", """."""] )
# fmt: on
def __A ( self ):
_lowerCAmelCase : Optional[Any] = GPTSwaTokenizer(a__ )
_lowerCAmelCase : str = ["""This is a test""", """I was born in 92000, and this is falsé."""]
_lowerCAmelCase : List[Any] = [
[465, 287, 265, 631, 842],
[262, 272, 1525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260],
]
# Test that encode_fast returns the same as tokenize + convert_tokens_to_ids
for text, expected_ids in zip(a__ , a__ ):
self.assertListEqual(tokenizer.encode_fast(a__ ) , a__ )
# Test that decode_fast returns the input text
for text, token_ids in zip(a__ , a__ ):
self.assertEqual(tokenizer.decode_fast(a__ ) , a__ )
@slow
def __A ( self ):
_lowerCAmelCase : str = [
"""<|python|>def fibonacci(n)\n if n < 0:\n print('Incorrect input')""",
"""Hey there, how are you doing this fine day?""",
"""This is a text with a trailing spaces followed by a dot .""",
"""Häj sväjs lillebrör! =)""",
"""Det är inget fel på Mr. Cool""",
]
# fmt: off
_lowerCAmelCase : List[Any] = {"""input_ids""": [[63423, 5, 6811, 14954, 282, 816, 3821, 63466, 63425, 63462, 18, 63978, 678, 301, 1320, 63423, 63455, 63458, 18, 63982, 4246, 3940, 1901, 47789, 5547, 18994], [19630, 1100, 63446, 1342, 633, 544, 4488, 593, 5102, 2416, 63495, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1652, 428, 268, 1936, 515, 268, 58593, 22413, 9106, 546, 268, 33213, 63979, 698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [55130, 63450, 924, 63449, 2249, 4062, 1558, 318, 63504, 21498, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [509, 377, 2827, 2559, 332, 6575, 63443, 26801, 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]], """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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [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]]}
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=a__ , model_name="""AI-Sweden/gpt-sw3-126m""" , sequences=a__ , )
| 213 | 0 |
from typing import Any
def _UpperCamelCase (a__ :list ):
"""simple docstring"""
if not input_list:
return []
UpperCamelCase__ = [input_list.count(a__ ) for value in input_list]
UpperCamelCase__ = max(a__ ) # Gets the maximum count in the input list.
# Gets values of modes
return sorted({input_list[i] for i, value in enumerate(a__ ) if value == y} )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 548 |
import os
import pytest
import yaml
from datasets.features.features import Features, Value
from datasets.info import DatasetInfo, DatasetInfosDict
@pytest.mark.parametrize(
"""files""" , [
["""full:README.md""", """dataset_infos.json"""],
["""empty:README.md""", """dataset_infos.json"""],
["""dataset_infos.json"""],
["""full:README.md"""],
] , )
def _UpperCamelCase (a__ :Any , a__ :Union[str, Any] ):
"""simple docstring"""
UpperCamelCase__ = tmp_path_factory.mktemp("""dset_infos_dir""" )
if "full:README.md" in files:
with open(dataset_infos_dir / """README.md""" , """w""" ) as f:
f.write("""---\ndataset_info:\n dataset_size: 42\n---""" )
if "empty:README.md" in files:
with open(dataset_infos_dir / """README.md""" , """w""" ) as f:
f.write("""""" )
# we want to support dataset_infos.json for backward compatibility
if "dataset_infos.json" in files:
with open(dataset_infos_dir / """dataset_infos.json""" , """w""" ) as f:
f.write("""{\"default\": {\"dataset_size\": 42}}""" )
UpperCamelCase__ = DatasetInfosDict.from_directory(a__ )
assert dataset_infos
assert dataset_infos["default"].dataset_size == 42
@pytest.mark.parametrize(
"""dataset_info""" , [
DatasetInfo(),
DatasetInfo(
description="""foo""" , features=Features({"""a""": Value("""int32""" )} ) , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train"""}] , download_size=42 , ),
] , )
def _UpperCamelCase (a__ :Optional[int] , a__ :DatasetInfo ):
"""simple docstring"""
UpperCamelCase__ = str(a__ )
dataset_info.write_to_directory(a__ )
UpperCamelCase__ = DatasetInfo.from_directory(a__ )
assert dataset_info == reloaded
assert os.path.exists(os.path.join(a__ , """dataset_info.json""" ) )
def _UpperCamelCase ():
"""simple docstring"""
UpperCamelCase__ = DatasetInfo(
description="""foo""" , citation="""bar""" , homepage="""https://foo.bar""" , license="""CC0""" , features=Features({"""a""": Value("""int32""" )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train""", """num_examples""": 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , )
UpperCamelCase__ = dataset_info._to_yaml_dict()
assert sorted(a__ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML )
for key in DatasetInfo._INCLUDED_INFO_IN_YAML:
assert key in dataset_info_yaml_dict
assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) )
UpperCamelCase__ = yaml.safe_dump(a__ )
UpperCamelCase__ = yaml.safe_load(a__ )
assert dataset_info_yaml_dict == reloaded
def _UpperCamelCase ():
"""simple docstring"""
UpperCamelCase__ = DatasetInfo()
UpperCamelCase__ = dataset_info._to_yaml_dict()
assert dataset_info_yaml_dict == {}
@pytest.mark.parametrize(
"""dataset_infos_dict""" , [
DatasetInfosDict(),
DatasetInfosDict({"""default""": DatasetInfo()} ),
DatasetInfosDict({"""my_config_name""": DatasetInfo()} ),
DatasetInfosDict(
{
"""default""": DatasetInfo(
description="""foo""" , features=Features({"""a""": Value("""int32""" )} ) , builder_name="""builder""" , config_name="""config""" , version="""1.0.0""" , splits=[{"""name""": """train"""}] , download_size=42 , )
} ),
DatasetInfosDict(
{
"""v1""": DatasetInfo(dataset_size=42 ),
"""v2""": DatasetInfo(dataset_size=1337 ),
} ),
] , )
def _UpperCamelCase (a__ :int , a__ :DatasetInfosDict ):
"""simple docstring"""
UpperCamelCase__ = str(a__ )
dataset_infos_dict.write_to_directory(a__ )
UpperCamelCase__ = DatasetInfosDict.from_directory(a__ )
# the config_name of the dataset_infos_dict take over the attribute
for config_name, dataset_info in dataset_infos_dict.items():
UpperCamelCase__ = config_name
# the yaml representation doesn't include fields like description or citation
# so we just test that we can recover what we can from the yaml
UpperCamelCase__ = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() )
assert dataset_infos_dict == reloaded
if dataset_infos_dict:
assert os.path.exists(os.path.join(a__ , """README.md""" ) )
| 548 | 1 |
"""simple docstring"""
import unittest
from transformers import is_flax_available
from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow
if is_flax_available():
import optax
from flax.training.common_utils import onehot
from transformers import AutoTokenizer, FlaxMTaForConditionalGeneration
from transformers.models.ta.modeling_flax_ta import shift_tokens_right
@require_torch
@require_sentencepiece
@require_tokenizers
@require_flax
class __A ( unittest.TestCase ):
'''simple docstring'''
@slow
def UpperCAmelCase ( self : Optional[int] ) -> Union[str, Any]:
"""simple docstring"""
lowercase__ : List[str] = FlaxMTaForConditionalGeneration.from_pretrained('''google/mt5-small''' )
lowercase__ : Tuple = AutoTokenizer.from_pretrained('''google/mt5-small''' )
lowercase__ : Optional[Any] = tokenizer('''Hello there''' ,return_tensors='''np''' ).input_ids
lowercase__ : str = tokenizer('''Hi I am''' ,return_tensors='''np''' ).input_ids
lowercase__ : Optional[Any] = shift_tokens_right(_snake_case ,model.config.pad_token_id ,model.config.decoder_start_token_id )
lowercase__ : List[str] = model(_snake_case ,decoder_input_ids=_snake_case ).logits
lowercase__ : Optional[Any] = optax.softmax_cross_entropy(_snake_case ,onehot(_snake_case ,logits.shape[-1] ) ).mean()
lowercase__ : Tuple = -(labels.shape[-1] * loss.item())
lowercase__ : List[Any] = -84.9127
self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )
| 560 |
"""simple docstring"""
from __future__ import annotations
from collections import namedtuple
from dataclasses import dataclass
@dataclass
class __A :
'''simple docstring'''
lowerCAmelCase : int
lowerCAmelCase : TreeNode | None = None
lowerCAmelCase : TreeNode | None = None
lowerCAmelCase_ = namedtuple('CoinsDistribResult', 'moves excess')
def __UpperCAmelCase ( __lowerCamelCase ) -> int:
if root is None:
return 0
# Validation
def count_nodes(__lowerCamelCase ) -> int:
if node is None:
return 0
return count_nodes(node.left ) + count_nodes(node.right ) + 1
def count_coins(__lowerCamelCase ) -> int:
if node is None:
return 0
return count_coins(node.left ) + count_coins(node.right ) + node.data
if count_nodes(__lowerCamelCase ) != count_coins(__lowerCamelCase ):
raise ValueError('''The nodes number should be same as the number of coins''' )
# Main calculation
def get_distrib(__lowerCamelCase ) -> CoinsDistribResult:
if node is None:
return CoinsDistribResult(0 , 1 )
lowercase__ , lowercase__ : Optional[Any] = get_distrib(node.left )
lowercase__ , lowercase__ : Tuple = get_distrib(node.right )
lowercase__ : List[Any] = 1 - left_distrib_excess
lowercase__ : Any = 1 - right_distrib_excess
lowercase__ : List[str] = (
left_distrib_moves
+ right_distrib_moves
+ abs(__lowerCamelCase )
+ abs(__lowerCamelCase )
)
lowercase__ : List[Any] = node.data - coins_to_left - coins_to_right
return CoinsDistribResult(__lowerCamelCase , __lowerCamelCase )
return get_distrib(__lowerCamelCase )[0]
if __name__ == "__main__":
import doctest
doctest.testmod()
| 560 | 1 |
import argparse
import json
import gdown
import numpy as np
import torch
from huggingface_hub import hf_hub_download
from transformers import (
VideoMAEConfig,
VideoMAEForPreTraining,
VideoMAEForVideoClassification,
VideoMAEImageProcessor,
)
def UpperCAmelCase_ ( __UpperCamelCase ):
SCREAMING_SNAKE_CASE__ =VideoMAEConfig()
set_architecture_configs(__UpperCamelCase, __UpperCamelCase )
if "finetuned" not in model_name:
SCREAMING_SNAKE_CASE__ =False
if "finetuned" in model_name:
SCREAMING_SNAKE_CASE__ ="""huggingface/label-files"""
if "kinetics" in model_name:
SCREAMING_SNAKE_CASE__ =400
SCREAMING_SNAKE_CASE__ ="""kinetics400-id2label.json"""
elif "ssv2" in model_name:
SCREAMING_SNAKE_CASE__ =174
SCREAMING_SNAKE_CASE__ ="""something-something-v2-id2label.json"""
else:
raise ValueError("""Model name should either contain 'kinetics' or 'ssv2' in case it's fine-tuned.""" )
SCREAMING_SNAKE_CASE__ =json.load(open(hf_hub_download(__UpperCamelCase, __UpperCamelCase, repo_type="""dataset""" ), """r""" ) )
SCREAMING_SNAKE_CASE__ ={int(__UpperCamelCase ): v for k, v in idalabel.items()}
SCREAMING_SNAKE_CASE__ =idalabel
SCREAMING_SNAKE_CASE__ ={v: k for k, v in idalabel.items()}
return config
def UpperCAmelCase_ ( __UpperCamelCase, __UpperCamelCase ):
if "small" in model_name:
SCREAMING_SNAKE_CASE__ =384
SCREAMING_SNAKE_CASE__ =1_536
SCREAMING_SNAKE_CASE__ =12
SCREAMING_SNAKE_CASE__ =16
SCREAMING_SNAKE_CASE__ =12
SCREAMING_SNAKE_CASE__ =3
SCREAMING_SNAKE_CASE__ =192
SCREAMING_SNAKE_CASE__ =768
elif "large" in model_name:
SCREAMING_SNAKE_CASE__ =1_024
SCREAMING_SNAKE_CASE__ =4_096
SCREAMING_SNAKE_CASE__ =24
SCREAMING_SNAKE_CASE__ =16
SCREAMING_SNAKE_CASE__ =12
SCREAMING_SNAKE_CASE__ =8
SCREAMING_SNAKE_CASE__ =512
SCREAMING_SNAKE_CASE__ =2_048
elif "huge" in model_name:
SCREAMING_SNAKE_CASE__ =1_280
SCREAMING_SNAKE_CASE__ =5_120
SCREAMING_SNAKE_CASE__ =32
SCREAMING_SNAKE_CASE__ =16
SCREAMING_SNAKE_CASE__ =12
SCREAMING_SNAKE_CASE__ =8
SCREAMING_SNAKE_CASE__ =640
SCREAMING_SNAKE_CASE__ =2_560
elif "base" not in model_name:
raise ValueError("""Model name should include either \"small\", \"base\", \"large\", or \"huge\"""" )
def UpperCAmelCase_ ( __UpperCamelCase ):
if "encoder." in name:
SCREAMING_SNAKE_CASE__ =name.replace("""encoder.""", """""" )
if "cls_token" in name:
SCREAMING_SNAKE_CASE__ =name.replace("""cls_token""", """videomae.embeddings.cls_token""" )
if "decoder_pos_embed" in name:
SCREAMING_SNAKE_CASE__ =name.replace("""decoder_pos_embed""", """decoder.decoder_pos_embed""" )
if "pos_embed" in name and "decoder" not in name:
SCREAMING_SNAKE_CASE__ =name.replace("""pos_embed""", """videomae.embeddings.position_embeddings""" )
if "patch_embed.proj" in name:
SCREAMING_SNAKE_CASE__ =name.replace("""patch_embed.proj""", """videomae.embeddings.patch_embeddings.projection""" )
if "patch_embed.norm" in name:
SCREAMING_SNAKE_CASE__ =name.replace("""patch_embed.norm""", """videomae.embeddings.norm""" )
if "decoder.blocks" in name:
SCREAMING_SNAKE_CASE__ =name.replace("""decoder.blocks""", """decoder.decoder_layers""" )
if "blocks" in name:
SCREAMING_SNAKE_CASE__ =name.replace("""blocks""", """videomae.encoder.layer""" )
if "attn.proj" in name:
SCREAMING_SNAKE_CASE__ =name.replace("""attn.proj""", """attention.output.dense""" )
if "attn" in name and "bias" not in name:
SCREAMING_SNAKE_CASE__ =name.replace("""attn""", """attention.self""" )
if "attn" in name:
SCREAMING_SNAKE_CASE__ =name.replace("""attn""", """attention.attention""" )
if "norm1" in name:
SCREAMING_SNAKE_CASE__ =name.replace("""norm1""", """layernorm_before""" )
if "norm2" in name:
SCREAMING_SNAKE_CASE__ =name.replace("""norm2""", """layernorm_after""" )
if "mlp.fc1" in name:
SCREAMING_SNAKE_CASE__ =name.replace("""mlp.fc1""", """intermediate.dense""" )
if "mlp.fc2" in name:
SCREAMING_SNAKE_CASE__ =name.replace("""mlp.fc2""", """output.dense""" )
if "decoder_embed" in name:
SCREAMING_SNAKE_CASE__ =name.replace("""decoder_embed""", """decoder.decoder_embed""" )
if "decoder_norm" in name:
SCREAMING_SNAKE_CASE__ =name.replace("""decoder_norm""", """decoder.decoder_norm""" )
if "decoder_pred" in name:
SCREAMING_SNAKE_CASE__ =name.replace("""decoder_pred""", """decoder.decoder_pred""" )
if "norm.weight" in name and "decoder" not in name and "fc" not in name:
SCREAMING_SNAKE_CASE__ =name.replace("""norm.weight""", """videomae.layernorm.weight""" )
if "norm.bias" in name and "decoder" not in name and "fc" not in name:
SCREAMING_SNAKE_CASE__ =name.replace("""norm.bias""", """videomae.layernorm.bias""" )
if "head" in name and "decoder" not in name:
SCREAMING_SNAKE_CASE__ =name.replace("""head""", """classifier""" )
return name
def UpperCAmelCase_ ( __UpperCamelCase, __UpperCamelCase ):
for key in orig_state_dict.copy().keys():
SCREAMING_SNAKE_CASE__ =orig_state_dict.pop(__UpperCamelCase )
if key.startswith("""encoder.""" ):
SCREAMING_SNAKE_CASE__ =key.replace("""encoder.""", """""" )
if "qkv" in key:
SCREAMING_SNAKE_CASE__ =key.split(""".""" )
if key.startswith("""decoder.blocks""" ):
SCREAMING_SNAKE_CASE__ =config.decoder_hidden_size
SCREAMING_SNAKE_CASE__ =int(key_split[2] )
SCREAMING_SNAKE_CASE__ ="""decoder.decoder_layers."""
if "weight" in key:
SCREAMING_SNAKE_CASE__ =val[:dim, :]
SCREAMING_SNAKE_CASE__ =val[dim : dim * 2, :]
SCREAMING_SNAKE_CASE__ =val[-dim:, :]
else:
SCREAMING_SNAKE_CASE__ =config.hidden_size
SCREAMING_SNAKE_CASE__ =int(key_split[1] )
SCREAMING_SNAKE_CASE__ ="""videomae.encoder.layer."""
if "weight" in key:
SCREAMING_SNAKE_CASE__ =val[:dim, :]
SCREAMING_SNAKE_CASE__ =val[dim : dim * 2, :]
SCREAMING_SNAKE_CASE__ =val[-dim:, :]
else:
SCREAMING_SNAKE_CASE__ =val
return orig_state_dict
def UpperCAmelCase_ ( ):
SCREAMING_SNAKE_CASE__ =hf_hub_download(
repo_id="""hf-internal-testing/spaghetti-video""", filename="""eating_spaghetti.npy""", repo_type="""dataset""" )
SCREAMING_SNAKE_CASE__ =np.load(__UpperCamelCase )
return list(__UpperCamelCase )
def UpperCAmelCase_ ( __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase ):
SCREAMING_SNAKE_CASE__ =get_videomae_config(__UpperCamelCase )
if "finetuned" in model_name:
SCREAMING_SNAKE_CASE__ =VideoMAEForVideoClassification(__UpperCamelCase )
else:
SCREAMING_SNAKE_CASE__ =VideoMAEForPreTraining(__UpperCamelCase )
# download original checkpoint, hosted on Google Drive
SCREAMING_SNAKE_CASE__ ="""pytorch_model.bin"""
gdown.cached_download(__UpperCamelCase, __UpperCamelCase, quiet=__UpperCamelCase )
SCREAMING_SNAKE_CASE__ =torch.load(__UpperCamelCase, map_location="""cpu""" )
if "model" in files:
SCREAMING_SNAKE_CASE__ =files["""model"""]
else:
SCREAMING_SNAKE_CASE__ =files["""module"""]
SCREAMING_SNAKE_CASE__ =convert_state_dict(__UpperCamelCase, __UpperCamelCase )
model.load_state_dict(__UpperCamelCase )
model.eval()
# verify model on basic input
SCREAMING_SNAKE_CASE__ =VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5], image_std=[0.5, 0.5, 0.5] )
SCREAMING_SNAKE_CASE__ =prepare_video()
SCREAMING_SNAKE_CASE__ =image_processor(__UpperCamelCase, return_tensors="""pt""" )
if "finetuned" not in model_name:
SCREAMING_SNAKE_CASE__ =hf_hub_download(repo_id="""hf-internal-testing/bool-masked-pos""", filename="""bool_masked_pos.pt""" )
SCREAMING_SNAKE_CASE__ =torch.load(__UpperCamelCase )
SCREAMING_SNAKE_CASE__ =model(**__UpperCamelCase )
SCREAMING_SNAKE_CASE__ =outputs.logits
SCREAMING_SNAKE_CASE__ =[
"""videomae-small-finetuned-kinetics""",
"""videomae-small-finetuned-ssv2""",
# Kinetics-400 checkpoints (short = pretrained only for 800 epochs instead of 1600)
"""videomae-base-short""",
"""videomae-base-short-finetuned-kinetics""",
"""videomae-base""",
"""videomae-base-finetuned-kinetics""",
"""videomae-large""",
"""videomae-large-finetuned-kinetics""",
"""videomae-huge-finetuned-kinetics""",
# Something-Something-v2 checkpoints (short = pretrained only for 800 epochs instead of 2400)
"""videomae-base-short-ssv2""",
"""videomae-base-short-finetuned-ssv2""",
"""videomae-base-ssv2""",
"""videomae-base-finetuned-ssv2""",
]
# NOTE: logits were tested with image_mean and image_std equal to [0.5, 0.5, 0.5] and [0.5, 0.5, 0.5]
if model_name == "videomae-small-finetuned-kinetics":
SCREAMING_SNAKE_CASE__ =torch.Size([1, 400] )
SCREAMING_SNAKE_CASE__ =torch.tensor([-0.9291, -0.4061, -0.9307] )
elif model_name == "videomae-small-finetuned-ssv2":
SCREAMING_SNAKE_CASE__ =torch.Size([1, 174] )
SCREAMING_SNAKE_CASE__ =torch.tensor([0.2671, -0.4689, -0.8235] )
elif model_name == "videomae-base":
SCREAMING_SNAKE_CASE__ =torch.Size([1, 1_408, 1_536] )
SCREAMING_SNAKE_CASE__ =torch.tensor([[0.7739, 0.7968, 0.7089], [0.6701, 0.7487, 0.6209], [0.4287, 0.5158, 0.4773]] )
elif model_name == "videomae-base-short":
SCREAMING_SNAKE_CASE__ =torch.Size([1, 1_408, 1_536] )
SCREAMING_SNAKE_CASE__ =torch.tensor([[0.7994, 0.9612, 0.8508], [0.7401, 0.8958, 0.8302], [0.5862, 0.7468, 0.7325]] )
# we verified the loss both for normalized and unnormalized targets for this one
SCREAMING_SNAKE_CASE__ =torch.tensor([0.5142] ) if config.norm_pix_loss else torch.tensor([0.6469] )
elif model_name == "videomae-large":
SCREAMING_SNAKE_CASE__ =torch.Size([1, 1_408, 1_536] )
SCREAMING_SNAKE_CASE__ =torch.tensor([[0.7149, 0.7997, 0.6966], [0.6768, 0.7869, 0.6948], [0.5139, 0.6221, 0.5605]] )
elif model_name == "videomae-large-finetuned-kinetics":
SCREAMING_SNAKE_CASE__ =torch.Size([1, 400] )
SCREAMING_SNAKE_CASE__ =torch.tensor([0.0771, 0.0011, -0.3625] )
elif model_name == "videomae-huge-finetuned-kinetics":
SCREAMING_SNAKE_CASE__ =torch.Size([1, 400] )
SCREAMING_SNAKE_CASE__ =torch.tensor([0.2433, 0.1632, -0.4894] )
elif model_name == "videomae-base-short-finetuned-kinetics":
SCREAMING_SNAKE_CASE__ =torch.Size([1, 400] )
SCREAMING_SNAKE_CASE__ =torch.tensor([0.6588, 0.0990, -0.2493] )
elif model_name == "videomae-base-finetuned-kinetics":
SCREAMING_SNAKE_CASE__ =torch.Size([1, 400] )
SCREAMING_SNAKE_CASE__ =torch.tensor([0.3669, -0.0688, -0.2421] )
elif model_name == "videomae-base-short-ssv2":
SCREAMING_SNAKE_CASE__ =torch.Size([1, 1_408, 1_536] )
SCREAMING_SNAKE_CASE__ =torch.tensor([[0.4712, 0.5296, 0.5786], [0.2278, 0.2729, 0.4026], [0.0352, 0.0730, 0.2506]] )
elif model_name == "videomae-base-short-finetuned-ssv2":
SCREAMING_SNAKE_CASE__ =torch.Size([1, 174] )
SCREAMING_SNAKE_CASE__ =torch.tensor([-0.0537, -0.1539, -0.3266] )
elif model_name == "videomae-base-ssv2":
SCREAMING_SNAKE_CASE__ =torch.Size([1, 1_408, 1_536] )
SCREAMING_SNAKE_CASE__ =torch.tensor([[0.8131, 0.8727, 0.8546], [0.7366, 0.9377, 0.8870], [0.5935, 0.8874, 0.8564]] )
elif model_name == "videomae-base-finetuned-ssv2":
SCREAMING_SNAKE_CASE__ =torch.Size([1, 174] )
SCREAMING_SNAKE_CASE__ =torch.tensor([0.1961, -0.8337, -0.6389] )
else:
raise ValueError(f"""Model name not supported. Should be one of {model_names}""" )
# verify logits
assert logits.shape == expected_shape
if "finetuned" in model_name:
assert torch.allclose(logits[0, :3], __UpperCamelCase, atol=1E-4 )
else:
print("""Logits:""", logits[0, :3, :3] )
assert torch.allclose(logits[0, :3, :3], __UpperCamelCase, atol=1E-4 )
print("""Logits ok!""" )
# verify loss, if applicable
if model_name == "videomae-base-short":
SCREAMING_SNAKE_CASE__ =outputs.loss
assert torch.allclose(__UpperCamelCase, __UpperCamelCase, atol=1E-4 )
print("""Loss ok!""" )
if pytorch_dump_folder_path is not None:
print(f"""Saving model and image processor to {pytorch_dump_folder_path}""" )
image_processor.save_pretrained(__UpperCamelCase )
model.save_pretrained(__UpperCamelCase )
if push_to_hub:
print("""Pushing to the hub...""" )
model.push_to_hub(__UpperCamelCase, organization="""nielsr""" )
if __name__ == "__main__":
lowerCamelCase_ = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--checkpoint_url",
default="https://drive.google.com/u/1/uc?id=1tEhLyskjb755TJ65ptsrafUG2llSwQE1&export=download&confirm=t&uuid=aa3276eb-fb7e-482a-adec-dc7171df14c4",
type=str,
help=(
"URL of the original PyTorch checkpoint (on Google Drive) you'd like to convert. Should be a direct"
" download link."
),
)
parser.add_argument(
"--pytorch_dump_folder_path",
default="/Users/nielsrogge/Documents/VideoMAE/Test",
type=str,
help="Path to the output PyTorch model directory.",
)
parser.add_argument("--model_name", default="videomae-base", type=str, help="Name of the model.")
parser.add_argument(
"--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub."
)
lowerCamelCase_ = parser.parse_args()
convert_videomae_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
| 711 |
from __future__ import annotations
import math
from collections.abc import Callable
def UpperCAmelCase_ ( __UpperCamelCase, __UpperCamelCase, __UpperCamelCase, __UpperCamelCase = 100, ):
SCREAMING_SNAKE_CASE__ =x_start
SCREAMING_SNAKE_CASE__ =fnc(__UpperCamelCase )
SCREAMING_SNAKE_CASE__ =0.0
for _ in range(__UpperCamelCase ):
# Approximates curve as a sequence of linear lines and sums their length
SCREAMING_SNAKE_CASE__ =(x_end - x_start) / steps + xa
SCREAMING_SNAKE_CASE__ =fnc(__UpperCamelCase )
length += math.hypot(xa - xa, fxa - fxa )
# Increment step
SCREAMING_SNAKE_CASE__ =xa
SCREAMING_SNAKE_CASE__ =fxa
return length
if __name__ == "__main__":
def UpperCAmelCase_ ( __UpperCamelCase ):
return math.sin(10 * x )
print("f(x) = sin(10 * x)")
print("The length of the curve from x = -10 to x = 10 is:")
lowerCamelCase_ = 10
while i <= 100000:
print(f"""With {i} steps: {line_length(f, -10, 10, i)}""")
i *= 10
| 588 | 0 |
'''simple docstring'''
import unittest
import numpy as np
import torch
from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device
enable_full_determinism()
class __lowerCAmelCase ( unittest.TestCase ):
"""simple docstring"""
@property
def snake_case__ ( self : Tuple ) -> Tuple:
'''simple docstring'''
torch.manual_seed(0 )
_UpperCamelCase = UNetaDModel(
block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , )
return model
def snake_case__ ( self : Tuple ) -> Optional[Any]:
'''simple docstring'''
_UpperCamelCase = self.dummy_uncond_unet
_UpperCamelCase = PNDMScheduler()
_UpperCamelCase = PNDMPipeline(unet=lowerCAmelCase__ , scheduler=lowerCAmelCase__ )
pndm.to(lowerCAmelCase__ )
pndm.set_progress_bar_config(disable=lowerCAmelCase__ )
_UpperCamelCase = torch.manual_seed(0 )
_UpperCamelCase = pndm(generator=lowerCAmelCase__ , num_inference_steps=20 , output_type='''numpy''' ).images
_UpperCamelCase = torch.manual_seed(0 )
_UpperCamelCase = pndm(generator=lowerCAmelCase__ , num_inference_steps=20 , output_type='''numpy''' , return_dict=lowerCAmelCase__ )[0]
_UpperCamelCase = image[0, -3:, -3:, -1]
_UpperCamelCase = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 32, 32, 3)
_UpperCamelCase = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2
@slow
@require_torch
class __lowerCAmelCase ( unittest.TestCase ):
"""simple docstring"""
def snake_case__ ( self : Any ) -> Optional[int]:
'''simple docstring'''
_UpperCamelCase = '''google/ddpm-cifar10-32'''
_UpperCamelCase = UNetaDModel.from_pretrained(lowerCAmelCase__ )
_UpperCamelCase = PNDMScheduler()
_UpperCamelCase = PNDMPipeline(unet=lowerCAmelCase__ , scheduler=lowerCAmelCase__ )
pndm.to(lowerCAmelCase__ )
pndm.set_progress_bar_config(disable=lowerCAmelCase__ )
_UpperCamelCase = torch.manual_seed(0 )
_UpperCamelCase = pndm(generator=lowerCAmelCase__ , output_type='''numpy''' ).images
_UpperCamelCase = image[0, -3:, -3:, -1]
assert image.shape == (1, 32, 32, 3)
_UpperCamelCase = np.array([0.1564, 0.14645, 0.1406, 0.14715, 0.12425, 0.14045, 0.13115, 0.12175, 0.125] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
| 98 |
import os
from math import logaa
def A_ ( A__ = "base_exp.txt" ) -> int:
a__ : float = 0
a__ : Optional[Any] = 0
for i, line in enumerate(open(os.path.join(os.path.dirname(A__ ) , A__ ) ) ):
a__ , a__ : List[str] = list(map(A__ , line.split(',' ) ) )
if x * logaa(A__ ) > largest:
a__ : Dict = x * logaa(A__ )
a__ : List[Any] = i + 1
return result
if __name__ == "__main__":
print(solution())
| 302 | 0 |
import unittest
from transformers import DebertaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
DebertaForMaskedLM,
DebertaForQuestionAnswering,
DebertaForSequenceClassification,
DebertaForTokenClassification,
DebertaModel,
)
from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST
class __SCREAMING_SNAKE_CASE( a_ ):
def __init__( self: List[Any] , UpperCamelCase: Optional[int] , UpperCamelCase: Union[str, Any]=13 , UpperCamelCase: List[Any]=7 , UpperCamelCase: Optional[int]=True , UpperCamelCase: Dict=True , UpperCamelCase: int=True , UpperCamelCase: Tuple=True , UpperCamelCase: Any=99 , UpperCamelCase: Tuple=32 , UpperCamelCase: List[str]=5 , UpperCamelCase: Dict=4 , UpperCamelCase: Dict=37 , UpperCamelCase: Union[str, Any]="gelu" , UpperCamelCase: Union[str, Any]=0.1 , UpperCamelCase: Tuple=0.1 , UpperCamelCase: Optional[Any]=5_12 , UpperCamelCase: Optional[Any]=16 , UpperCamelCase: Tuple=2 , UpperCamelCase: List[Any]=0.02 , UpperCamelCase: Optional[int]=False , UpperCamelCase: int=True , UpperCamelCase: Union[str, Any]="None" , UpperCamelCase: List[Any]=3 , UpperCamelCase: int=4 , UpperCamelCase: List[str]=None , ) -> Union[str, Any]:
snake_case__ = parent
snake_case__ = batch_size
snake_case__ = seq_length
snake_case__ = is_training
snake_case__ = use_input_mask
snake_case__ = use_token_type_ids
snake_case__ = use_labels
snake_case__ = vocab_size
snake_case__ = hidden_size
snake_case__ = num_hidden_layers
snake_case__ = num_attention_heads
snake_case__ = intermediate_size
snake_case__ = hidden_act
snake_case__ = hidden_dropout_prob
snake_case__ = attention_probs_dropout_prob
snake_case__ = max_position_embeddings
snake_case__ = type_vocab_size
snake_case__ = type_sequence_label_size
snake_case__ = initializer_range
snake_case__ = num_labels
snake_case__ = num_choices
snake_case__ = relative_attention
snake_case__ = position_biased_input
snake_case__ = pos_att_type
snake_case__ = scope
def lowerCAmelCase_ ( self: int ) -> List[str]:
snake_case__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
snake_case__ = None
if self.use_input_mask:
snake_case__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 )
snake_case__ = None
if self.use_token_type_ids:
snake_case__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
snake_case__ = None
snake_case__ = None
snake_case__ = None
if self.use_labels:
snake_case__ = ids_tensor([self.batch_size] , self.type_sequence_label_size )
snake_case__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
snake_case__ = ids_tensor([self.batch_size] , self.num_choices )
snake_case__ = self.get_config()
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def lowerCAmelCase_ ( self: List[Any] ) -> Any:
return DebertaConfig(
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 , relative_attention=self.relative_attention , position_biased_input=self.position_biased_input , pos_att_type=self.pos_att_type , )
def lowerCAmelCase_ ( self: str ) -> Dict:
snake_case__ = self.get_config()
snake_case__ = 3_00
return config
def lowerCAmelCase_ ( self: str , UpperCamelCase: Tuple ) -> str:
self.parent.assertListEqual(list(result.loss.size() ) , [] )
def lowerCAmelCase_ ( self: List[str] , UpperCamelCase: Optional[Any] , UpperCamelCase: str , UpperCamelCase: int , UpperCamelCase: Tuple , UpperCamelCase: Any , UpperCamelCase: Tuple , UpperCamelCase: List[Any] ) -> Optional[int]:
snake_case__ = DebertaModel(config=UpperCamelCase )
model.to(UpperCamelCase )
model.eval()
snake_case__ = model(UpperCamelCase , attention_mask=UpperCamelCase , token_type_ids=UpperCamelCase )[0]
snake_case__ = model(UpperCamelCase , token_type_ids=UpperCamelCase )[0]
snake_case__ = model(UpperCamelCase )[0]
self.parent.assertListEqual(list(sequence_output.size() ) , [self.batch_size, self.seq_length, self.hidden_size] )
def lowerCAmelCase_ ( self: str , UpperCamelCase: Dict , UpperCamelCase: int , UpperCamelCase: List[str] , UpperCamelCase: Tuple , UpperCamelCase: str , UpperCamelCase: Union[str, Any] , UpperCamelCase: Dict ) -> Optional[int]:
snake_case__ = DebertaForMaskedLM(config=UpperCamelCase )
model.to(UpperCamelCase )
model.eval()
snake_case__ = model(UpperCamelCase , attention_mask=UpperCamelCase , token_type_ids=UpperCamelCase , labels=UpperCamelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def lowerCAmelCase_ ( self: List[Any] , UpperCamelCase: Optional[Any] , UpperCamelCase: List[str] , UpperCamelCase: Tuple , UpperCamelCase: List[str] , UpperCamelCase: Any , UpperCamelCase: Any , UpperCamelCase: Any ) -> Optional[Any]:
snake_case__ = self.num_labels
snake_case__ = DebertaForSequenceClassification(UpperCamelCase )
model.to(UpperCamelCase )
model.eval()
snake_case__ = model(UpperCamelCase , attention_mask=UpperCamelCase , token_type_ids=UpperCamelCase , labels=UpperCamelCase )
self.parent.assertListEqual(list(result.logits.size() ) , [self.batch_size, self.num_labels] )
self.check_loss_output(UpperCamelCase )
def lowerCAmelCase_ ( self: Union[str, Any] , UpperCamelCase: Optional[Any] , UpperCamelCase: Any , UpperCamelCase: List[Any] , UpperCamelCase: Any , UpperCamelCase: Union[str, Any] , UpperCamelCase: str , UpperCamelCase: int ) -> Optional[int]:
snake_case__ = self.num_labels
snake_case__ = DebertaForTokenClassification(config=UpperCamelCase )
model.to(UpperCamelCase )
model.eval()
snake_case__ = model(UpperCamelCase , attention_mask=UpperCamelCase , token_type_ids=UpperCamelCase , labels=UpperCamelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def lowerCAmelCase_ ( self: List[str] , UpperCamelCase: List[Any] , UpperCamelCase: List[str] , UpperCamelCase: Dict , UpperCamelCase: Tuple , UpperCamelCase: Optional[int] , UpperCamelCase: List[Any] , UpperCamelCase: Union[str, Any] ) -> int:
snake_case__ = DebertaForQuestionAnswering(config=UpperCamelCase )
model.to(UpperCamelCase )
model.eval()
snake_case__ = model(
UpperCamelCase , attention_mask=UpperCamelCase , token_type_ids=UpperCamelCase , start_positions=UpperCamelCase , end_positions=UpperCamelCase , )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def lowerCAmelCase_ ( self: str ) -> Any:
snake_case__ = self.prepare_config_and_inputs()
(
snake_case__
) = config_and_inputs
snake_case__ = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
return config, inputs_dict
@require_torch
class __SCREAMING_SNAKE_CASE( a_ , a_ , unittest.TestCase ):
_UpperCAmelCase = (
(
DebertaModel,
DebertaForMaskedLM,
DebertaForSequenceClassification,
DebertaForTokenClassification,
DebertaForQuestionAnswering,
)
if is_torch_available()
else ()
)
_UpperCAmelCase = (
{
"feature-extraction": DebertaModel,
"fill-mask": DebertaForMaskedLM,
"question-answering": DebertaForQuestionAnswering,
"text-classification": DebertaForSequenceClassification,
"token-classification": DebertaForTokenClassification,
"zero-shot": DebertaForSequenceClassification,
}
if is_torch_available()
else {}
)
_UpperCAmelCase = True
_UpperCAmelCase = False
_UpperCAmelCase = False
_UpperCAmelCase = False
_UpperCAmelCase = False
def lowerCAmelCase_ ( self: str ) -> List[str]:
snake_case__ = DebertaModelTester(self )
snake_case__ = ConfigTester(self , config_class=UpperCamelCase , hidden_size=37 )
def lowerCAmelCase_ ( self: str ) -> List[Any]:
self.config_tester.run_common_tests()
def lowerCAmelCase_ ( self: Optional[int] ) -> Optional[int]:
snake_case__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_deberta_model(*UpperCamelCase )
def lowerCAmelCase_ ( self: Tuple ) -> int:
snake_case__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_deberta_for_sequence_classification(*UpperCamelCase )
def lowerCAmelCase_ ( self: Union[str, Any] ) -> List[Any]:
snake_case__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_deberta_for_masked_lm(*UpperCamelCase )
def lowerCAmelCase_ ( self: Optional[int] ) -> List[Any]:
snake_case__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_deberta_for_question_answering(*UpperCamelCase )
def lowerCAmelCase_ ( self: List[str] ) -> Optional[int]:
snake_case__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_deberta_for_token_classification(*UpperCamelCase )
@slow
def lowerCAmelCase_ ( self: List[str] ) -> Union[str, Any]:
for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
snake_case__ = DebertaModel.from_pretrained(UpperCamelCase )
self.assertIsNotNone(UpperCamelCase )
@require_torch
@require_sentencepiece
@require_tokenizers
class __SCREAMING_SNAKE_CASE( unittest.TestCase ):
@unittest.skip(reason='Model not available yet' )
def lowerCAmelCase_ ( self: Union[str, Any] ) -> Optional[Any]:
pass
@slow
def lowerCAmelCase_ ( self: Optional[Any] ) -> List[Any]:
snake_case__ = DebertaModel.from_pretrained('microsoft/deberta-base' )
snake_case__ = torch.tensor([[0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 4_60_78, 15_88, 2]] )
snake_case__ = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] )
with torch.no_grad():
snake_case__ = model(UpperCamelCase , attention_mask=UpperCamelCase )[0]
# compare the actual values for a slice.
snake_case__ = torch.tensor(
[[[-0.5_986, -0.8_055, -0.8_462], [1.4_484, -0.9_348, -0.8_059], [0.3_123, 0.0_032, -1.4_131]]] )
self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , UpperCamelCase , atol=1e-4 ) , F'''{output[:, 1:4, 1:4]}''' )
| 703 |
import qiskit
def a_ ( _A = 2 ) -> qiskit.result.counts.Counts:
"""simple docstring"""
snake_case__ = qubits
# Using Aer's simulator
snake_case__ = qiskit.Aer.get_backend('aer_simulator' )
# Creating a Quantum Circuit acting on the q register
snake_case__ = qiskit.QuantumCircuit(_A , _A )
# Adding a H gate on qubit 0 (now q0 in superposition)
circuit.h(0 )
for i in range(1 , _A ):
# Adding CX (CNOT) gate
circuit.cx(i - 1 , _A )
# Mapping the quantum measurement to the classical bits
circuit.measure(list(range(_A ) ) , list(range(_A ) ) )
# Now measuring any one qubit would affect other qubits to collapse
# their super position and have same state as the measured one.
# Executing the circuit on the simulator
snake_case__ = qiskit.execute(_A , _A , shots=1000 )
return job.result().get_counts(_A )
if __name__ == "__main__":
print(f'''Total count for various states are: {quantum_entanglement(3)}''')
| 372 | 0 |
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
SCREAMING_SNAKE_CASE__ : Optional[int] = logging.get_logger(__name__)
def __magic_name__ ( __lowerCAmelCase : str , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Tuple ) -> str:
return [
int(1000 * (box[0] / width) ),
int(1000 * (box[1] / height) ),
int(1000 * (box[2] / width) ),
int(1000 * (box[3] / height) ),
]
def __magic_name__ ( __lowerCAmelCase : np.ndarray , __lowerCAmelCase : Optional[str] , __lowerCAmelCase : Optional[str] ) -> Dict:
__lowerCamelCase = to_pil_image(__snake_case )
__lowerCamelCase = pil_image.size
__lowerCamelCase = pytesseract.image_to_data(__snake_case , lang=__snake_case , output_type='''dict''' , config=__snake_case )
__lowerCamelCase = data["text"], data["left"], data["top"], data["width"], data["height"]
# filter empty words and corresponding coordinates
__lowerCamelCase = [idx for idx, word in enumerate(__snake_case ) if not word.strip()]
__lowerCamelCase = [word for idx, word in enumerate(__snake_case ) if idx not in irrelevant_indices]
__lowerCamelCase = [coord for idx, coord in enumerate(__snake_case ) if idx not in irrelevant_indices]
__lowerCamelCase = [coord for idx, coord in enumerate(__snake_case ) if idx not in irrelevant_indices]
__lowerCamelCase = [coord for idx, coord in enumerate(__snake_case ) if idx not in irrelevant_indices]
__lowerCamelCase = [coord for idx, coord in enumerate(__snake_case ) if idx not in irrelevant_indices]
# turn coordinates into (left, top, left+width, top+height) format
__lowerCamelCase = []
for x, y, w, h in zip(__snake_case , __snake_case , __snake_case , __snake_case ):
__lowerCamelCase = [x, y, x + w, y + h]
actual_boxes.append(__snake_case )
# finally, normalize the bounding boxes
__lowerCamelCase = []
for box in actual_boxes:
normalized_boxes.append(normalize_box(__snake_case , __snake_case , __snake_case ) )
assert len(__snake_case ) == len(__snake_case ), "Not as many words as there are bounding boxes"
return words, normalized_boxes
class lowerCAmelCase__ ( _A ):
a__ : Optional[int] = ["""pixel_values"""]
def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any = True , SCREAMING_SNAKE_CASE__ : Tuple = None , SCREAMING_SNAKE_CASE__ : Union[str, Any] = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : Optional[Any] = True , SCREAMING_SNAKE_CASE__ : Optional[int] = 1 / 2_55 , SCREAMING_SNAKE_CASE__ : Optional[Any] = True , SCREAMING_SNAKE_CASE__ : Tuple = None , SCREAMING_SNAKE_CASE__ : int = None , SCREAMING_SNAKE_CASE__ : Union[str, Any] = True , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : Tuple = "" , **SCREAMING_SNAKE_CASE__ : Any , ) -> None:
super().__init__(**SCREAMING_SNAKE_CASE__ )
__lowerCamelCase = size if size is not None else {"height": 2_24, "width": 2_24}
__lowerCamelCase = get_size_dict(SCREAMING_SNAKE_CASE__ )
__lowerCamelCase = do_resize
__lowerCamelCase = size
__lowerCamelCase = resample
__lowerCamelCase = do_rescale
__lowerCamelCase = rescale_value
__lowerCamelCase = do_normalize
__lowerCamelCase = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
__lowerCamelCase = image_std if image_std is not None else IMAGENET_STANDARD_STD
__lowerCamelCase = apply_ocr
__lowerCamelCase = ocr_lang
__lowerCamelCase = tesseract_config
def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Tuple = PILImageResampling.BILINEAR , SCREAMING_SNAKE_CASE__ : Tuple = None , **SCREAMING_SNAKE_CASE__ : Optional[int] , ) -> np.ndarray:
__lowerCamelCase = 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()}''' )
__lowerCamelCase = (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 __A ( self : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : str = None , **SCREAMING_SNAKE_CASE__ : str , ) -> np.ndarray:
return rescale(SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
def __A ( self : Any , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any] = None , **SCREAMING_SNAKE_CASE__ : Any , ) -> np.ndarray:
return normalize(SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ , data_format=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Any = None , SCREAMING_SNAKE_CASE__ : Dict = None , SCREAMING_SNAKE_CASE__ : int=None , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : Tuple = None , SCREAMING_SNAKE_CASE__ : List[str] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Dict = None , SCREAMING_SNAKE_CASE__ : List[Any] = None , SCREAMING_SNAKE_CASE__ : Any = None , SCREAMING_SNAKE_CASE__ : List[Any] = None , SCREAMING_SNAKE_CASE__ : List[Any] = None , SCREAMING_SNAKE_CASE__ : Optional[int] = ChannelDimension.FIRST , **SCREAMING_SNAKE_CASE__ : Tuple , ) -> PIL.Image.Image:
__lowerCamelCase = do_resize if do_resize is not None else self.do_resize
__lowerCamelCase = size if size is not None else self.size
__lowerCamelCase = get_size_dict(SCREAMING_SNAKE_CASE__ )
__lowerCamelCase = resample if resample is not None else self.resample
__lowerCamelCase = do_rescale if do_rescale is not None else self.do_rescale
__lowerCamelCase = rescale_factor if rescale_factor is not None else self.rescale_factor
__lowerCamelCase = do_normalize if do_normalize is not None else self.do_normalize
__lowerCamelCase = image_mean if image_mean is not None else self.image_mean
__lowerCamelCase = image_std if image_std is not None else self.image_std
__lowerCamelCase = apply_ocr if apply_ocr is not None else self.apply_ocr
__lowerCamelCase = ocr_lang if ocr_lang is not None else self.ocr_lang
__lowerCamelCase = tesseract_config if tesseract_config is not None else self.tesseract_config
__lowerCamelCase = 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.
__lowerCamelCase = [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''' )
__lowerCamelCase = []
__lowerCamelCase = []
for image in images:
__lowerCamelCase = 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:
__lowerCamelCase = [self.resize(image=SCREAMING_SNAKE_CASE__ , size=SCREAMING_SNAKE_CASE__ , resample=SCREAMING_SNAKE_CASE__ ) for image in images]
if do_rescale:
__lowerCamelCase = [self.rescale(image=SCREAMING_SNAKE_CASE__ , scale=SCREAMING_SNAKE_CASE__ ) for image in images]
if do_normalize:
__lowerCamelCase = [self.normalize(image=SCREAMING_SNAKE_CASE__ , mean=SCREAMING_SNAKE_CASE__ , std=SCREAMING_SNAKE_CASE__ ) for image in images]
__lowerCamelCase = [to_channel_dimension_format(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for image in images]
__lowerCamelCase = BatchFeature(data={'''pixel_values''': images} , tensor_type=SCREAMING_SNAKE_CASE__ )
if apply_ocr:
__lowerCamelCase = words_batch
__lowerCamelCase = boxes_batch
return data
| 298 |
import argparse
import intel_extension_for_pytorch as ipex
import torch
from diffusers import DPMSolverMultistepScheduler, StableDiffusionPipeline
__UpperCAmelCase : Optional[Any] = argparse.ArgumentParser("Stable Diffusion script with intel optimization", add_help=False)
parser.add_argument("--dpm", action="store_true", help="Enable DPMSolver or not")
parser.add_argument("--steps", default=None, type=int, help="Num inference steps")
__UpperCAmelCase : Any = parser.parse_args()
__UpperCAmelCase : str = "cpu"
__UpperCAmelCase : str = "a lovely <dicoo> in red dress and hat, in the snowly and brightly night, with many brighly buildings"
__UpperCAmelCase : Optional[Any] = "path-to-your-trained-model"
__UpperCAmelCase : Dict = StableDiffusionPipeline.from_pretrained(model_id)
if args.dpm:
__UpperCAmelCase : str = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
__UpperCAmelCase : Optional[Any] = pipe.to(device)
# to channels last
__UpperCAmelCase : Optional[int] = pipe.unet.to(memory_format=torch.channels_last)
__UpperCAmelCase : List[Any] = pipe.vae.to(memory_format=torch.channels_last)
__UpperCAmelCase : int = pipe.text_encoder.to(memory_format=torch.channels_last)
if pipe.requires_safety_checker:
__UpperCAmelCase : Union[str, Any] = pipe.safety_checker.to(memory_format=torch.channels_last)
# optimize with ipex
__UpperCAmelCase : List[str] = torch.randn(2, 4, 6_4, 6_4)
__UpperCAmelCase : Optional[int] = torch.rand(1) * 9_9_9
__UpperCAmelCase : Any = torch.randn(2, 7_7, 7_6_8)
__UpperCAmelCase : List[Any] = (sample, timestep, encoder_hidden_status)
try:
__UpperCAmelCase : Optional[int] = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True, sample_input=input_example)
except Exception:
__UpperCAmelCase : Tuple = ipex.optimize(pipe.unet.eval(), dtype=torch.bfloataa, inplace=True)
__UpperCAmelCase : List[str] = ipex.optimize(pipe.vae.eval(), dtype=torch.bfloataa, inplace=True)
__UpperCAmelCase : Union[str, Any] = ipex.optimize(pipe.text_encoder.eval(), dtype=torch.bfloataa, inplace=True)
if pipe.requires_safety_checker:
__UpperCAmelCase : str = ipex.optimize(pipe.safety_checker.eval(), dtype=torch.bfloataa, inplace=True)
# compute
__UpperCAmelCase : Dict = 6_6_6
__UpperCAmelCase : List[Any] = torch.Generator(device).manual_seed(seed)
__UpperCAmelCase : List[str] = {"generator": generator}
if args.steps is not None:
__UpperCAmelCase : Union[str, Any] = args.steps
with torch.cpu.amp.autocast(enabled=True, dtype=torch.bfloataa):
__UpperCAmelCase : int = pipe(prompt, **generate_kwargs).images[0]
# save image
image.save("generated.png") | 241 | 0 |
import json
import os
import tempfile
from transformers.testing_utils import check_json_file_has_correct_format
class snake_case__ :
_lowerCAmelCase =None
def UpperCAmelCase__ ( self : List[Any] ):
snake_case__ : Dict = self.feature_extraction_class(**self.feat_extract_dict )
snake_case__ : Any = json.loads(feat_extract.to_json_string() )
for key, value in self.feat_extract_dict.items():
self.assertEqual(obj[key] , _lowerCamelCase )
def UpperCAmelCase__ ( self : Optional[Any] ):
snake_case__ : List[Any] = self.feature_extraction_class(**self.feat_extract_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
snake_case__ : Union[str, Any] = os.path.join(_lowerCamelCase , 'feat_extract.json' )
feat_extract_first.to_json_file(_lowerCamelCase )
snake_case__ : Optional[Any] = self.feature_extraction_class.from_json_file(_lowerCamelCase )
self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() )
def UpperCAmelCase__ ( self : Any ):
snake_case__ : int = self.feature_extraction_class(**self.feat_extract_dict )
with tempfile.TemporaryDirectory() as tmpdirname:
snake_case__ : Union[str, Any] = feat_extract_first.save_pretrained(_lowerCamelCase )[0]
check_json_file_has_correct_format(_lowerCamelCase )
snake_case__ : Any = self.feature_extraction_class.from_pretrained(_lowerCamelCase )
self.assertEqual(feat_extract_second.to_dict() , feat_extract_first.to_dict() )
def UpperCAmelCase__ ( self : Optional[Any] ):
snake_case__ : str = self.feature_extraction_class()
self.assertIsNotNone(_lowerCamelCase )
| 303 |
import logging
import re
import pytorch_quantization
import pytorch_quantization.nn as quant_nn
import torch
from pytorch_quantization import calib
from pytorch_quantization.tensor_quant import QuantDescriptor
lowerCamelCase : Tuple = logging.getLogger(__name__)
lowerCamelCase : Union[str, Any] = 5_0 # max width of layer names
lowerCamelCase : Any = 7_0 # max width of quantizer names
def lowercase__( A ):
snake_case__ : Optional[int] = parser.add_argument_group('quant_trainer arguments' )
group.add_argument('--wprec' , type=A , default=8 , help='weight precision' )
group.add_argument('--aprec' , type=A , default=8 , help='activation precision' )
group.add_argument('--quant-per-tensor' , action='store_true' , help='per tensor weight scaling' )
group.add_argument('--quant-disable' , action='store_true' , help='disable all quantizers' )
group.add_argument('--quant-disable-embeddings' , action='store_true' , help='disable all embeddings quantizers' )
group.add_argument('--quant-disable-keyword' , type=A , nargs='+' , help='disable quantizers by keyword' )
group.add_argument('--quant-disable-layer-module' , type=A , help='disable quantizers by keyword under layer.' )
group.add_argument('--quant-enable-layer-module' , type=A , help='enable quantizers by keyword under layer' )
group.add_argument('--calibrator' , default='max' , help='which quantization range calibrator to use' )
group.add_argument('--percentile' , default=A , type=A , help='percentile for PercentileCalibrator' )
group.add_argument('--fuse-qkv' , action='store_true' , help='use the same scale factor for qkv' )
group.add_argument('--clip-gelu' , metavar='N' , type=A , help='clip gelu output maximum value to N' )
group.add_argument(
'--recalibrate-weights' , action='store_true' , help=(
'recalibrate weight amaxes by taking the max of the weights.'
' amaxes will be computed with the current quantization granularity (axis).'
) , )
def lowercase__( A ):
if args.calibrator == "max":
snake_case__ : Any = 'max'
elif args.calibrator == "percentile":
if args.percentile is None:
raise ValueError('Specify --percentile when using percentile calibrator' )
snake_case__ : List[Any] = 'histogram'
elif args.calibrator == "mse":
snake_case__ : str = 'histogram'
else:
raise ValueError(f'''Invalid calibrator {args.calibrator}''' )
snake_case__ : Union[str, Any] = QuantDescriptor(num_bits=args.aprec , calib_method=A )
snake_case__ : List[Any] = QuantDescriptor(num_bits=args.wprec , axis=(None if args.quant_per_tensor else (0,)) )
quant_nn.QuantLinear.set_default_quant_desc_input(A )
quant_nn.QuantLinear.set_default_quant_desc_weight(A )
def lowercase__( A , A , A=False , A=False ):
logger.info('Configuring Model for Quantization' )
logger.info(f'''using quantization package {pytorch_quantization.__file__}''' )
if not calib:
if args.quant_disable_embeddings:
set_quantizer_by_name(A , ['embeddings'] , which='weight' , _disabled=A )
if args.quant_disable:
set_quantizer_by_name(A , [''] , _disabled=A )
if args.quant_disable_keyword:
set_quantizer_by_name(A , args.quant_disable_keyword , _disabled=A )
if args.quant_disable_layer_module:
set_quantizer_by_name(A , [R'layer.\d+.' + args.quant_disable_layer_module] , _disabled=A )
if args.quant_enable_layer_module:
set_quantizer_by_name(A , [R'layer.\d+.' + args.quant_enable_layer_module] , _disabled=A )
if args.recalibrate_weights:
recalibrate_weights(A )
if args.fuse_qkv:
fuse_qkv(A , A )
if args.clip_gelu:
clip_gelu(A , args.clip_gelu )
# if args.local_rank in [-1, 0] and not calib:
print_quant_summary(A )
def lowercase__( A ):
logger.info('Enabling Calibration' )
for name, module in model.named_modules():
if name.endswith('_quantizer' ):
if module._calibrator is not None:
module.disable_quant()
module.enable_calib()
else:
module.disable()
logger.info(f'''{name:80}: {module}''' )
def lowercase__( A , A ):
logger.info('Loading calibrated amax' )
for name, module in model.named_modules():
if name.endswith('_quantizer' ):
if module._calibrator is not None:
if isinstance(module._calibrator , calib.MaxCalibrator ):
module.load_calib_amax()
else:
module.load_calib_amax('percentile' , percentile=args.percentile )
module.enable_quant()
module.disable_calib()
else:
module.enable()
model.cuda()
print_quant_summary(A )
def lowercase__( A , A ):
def fusea(A , A , A ):
for mod in [qq, qk, qv]:
if not hasattr(A , '_amax' ):
print(' WARNING: NO AMAX BUFFER' )
return
snake_case__ : Optional[int] = qq._amax.detach().item()
snake_case__ : Union[str, Any] = qk._amax.detach().item()
snake_case__ : Dict = qv._amax.detach().item()
snake_case__ : Optional[int] = max(A , A , A )
qq._amax.fill_(A )
qk._amax.fill_(A )
qv._amax.fill_(A )
logger.info(f''' q={q:5.2f} k={k:5.2f} v={v:5.2f} -> {amax:5.2f}''' )
for name, mod in model.named_modules():
if name.endswith('.attention.self' ):
logger.info(f'''FUSE_QKV: {name:{name_width}}''' )
fusea(mod.matmul_q_input_quantizer , mod.matmul_k_input_quantizer , mod.matmul_v_input_quantizer )
if args.quant_per_tensor:
fusea(mod.query._weight_quantizer , mod.key._weight_quantizer , mod.value._weight_quantizer )
def lowercase__( A , A ):
for name, mod in model.named_modules():
if name.endswith('.output.dense' ) and not name.endswith('attention.output.dense' ):
snake_case__ : List[str] = mod._input_quantizer._amax.data.detach().item()
mod._input_quantizer._amax.data.detach().clamp_(max=A )
snake_case__ : Optional[int] = mod._input_quantizer._amax.data.detach().item()
logger.info(f'''CLIP_GELU: {name:{name_width}} amax: {amax_init:5.2f} -> {amax:5.2f}''' )
def lowercase__( A ):
for name, mod in model.named_modules():
if hasattr(A , '_weight_quantizer' ) and mod._weight_quantizer.axis is not None:
snake_case__ : str = mod.weight.shape[0]
snake_case__ : List[Any] = mod._weight_quantizer._amax.detach()
snake_case__ : int = torch.ones(A , dtype=amax.dtype , device=amax.device ) * amax
print(f'''expanding {name} {amax} -> {mod._weight_quantizer._amax}''' )
def lowercase__( A ):
for name, mod in model.named_modules():
if hasattr(A , '_weight_quantizer' ):
if not hasattr(mod.weight_quantizer , '_amax' ):
print('RECALIB: {name:{name_width}} WARNING: NO AMAX BUFFER' )
continue
# determine which axes to reduce across
# e.g. a 4D tensor quantized per axis 0 should reduce over (1,2,3)
snake_case__ : int = set() if mod._weight_quantizer.axis is None else set(mod._weight_quantizer.axis )
snake_case__ : int = set(range(len(mod.weight.size() ) ) ) - axis_set
snake_case__ : Optional[Any] = pytorch_quantization.utils.reduce_amax(mod.weight , axis=A , keepdims=A ).detach()
logger.info(f'''RECALIB: {name:{name_width}} {mod._weight_quantizer._amax.flatten()} -> {amax.flatten()}''' )
snake_case__ : str = amax
def lowercase__( A , A=2_5 , A=1_8_0 , A=None ):
if ignore is None:
snake_case__ : List[str] = []
elif not isinstance(A , A ):
snake_case__ : Optional[int] = [ignore]
snake_case__ : List[Any] = 0
for name, mod in model.named_modules():
if not hasattr(A , 'weight' ):
continue
snake_case__ : int = max(A , len(A ) )
for name, mod in model.named_modules():
snake_case__ : Optional[int] = getattr(A , '_input_quantizer' , A )
snake_case__ : Tuple = getattr(A , '_weight_quantizer' , A )
if not hasattr(A , 'weight' ):
continue
if type(A ) in ignore:
continue
if [True for s in ignore if type(A ) is str and s in name]:
continue
snake_case__ : Dict = f'''Act:{input_q.extra_repr()}'''
snake_case__ : str = f'''Wgt:{weight_q.extra_repr()}'''
snake_case__ : Any = f'''{name:{name_width}} {act_str} {wgt_str}'''
if len(A ) <= line_width:
logger.info(A )
else:
logger.info(f'''{name:{name_width}} {act_str}''' )
logger.info(f'''{" ":{name_width}} {wgt_str}''' )
def lowercase__( A ):
snake_case__ : Optional[Any] = 0
for name, mod in model.named_modules():
if isinstance(A , pytorch_quantization.nn.TensorQuantizer ):
print(f'''{name:80} {mod}''' )
count += 1
print(f'''{count} TensorQuantizers found in model''' )
def lowercase__( A , A , A , A , A ):
snake_case__ : str = getattr(A , A , A )
if quantizer_mod is not None:
assert hasattr(A , A )
setattr(A , A , A )
else:
logger.warning(f'''{name} has no {quantizer}''' )
def lowercase__( A , A , A="both" , **A ):
snake_case__ : Union[str, Any] = f'''Warning: changing {which} quantizers of {name:{qname_width}}'''
for k, v in kwargs.items():
s += f''' {k}={v}'''
if which in ["input", "both"]:
set_quantizer(A , A , '_input_quantizer' , A , A )
if which in ["weight", "both"]:
set_quantizer(A , A , '_weight_quantizer' , A , A )
logger.info(A )
def lowercase__( A , A , **A ):
for name, mod in model.named_modules():
if hasattr(A , '_input_quantizer' ) or hasattr(A , '_weight_quantizer' ):
for n in names:
if re.search(A , A ):
set_quantizers(A , A , **A )
elif name.endswith('_quantizer' ):
for n in names:
if re.search(A , A ):
snake_case__ : Any = f'''Warning: changing {name:{name_width}}'''
for k, v in kwargs.items():
s += f''' {k}={v}'''
setattr(A , A , A )
logger.info(A )
| 303 | 1 |
import time
from dataclasses import dataclass
from multiprocessing import Pool
from unittest import TestCase
from unittest.mock import patch
import multiprocess
import numpy as np
import pytest
from datasets.utils.py_utils import (
NestedDataStructure,
asdict,
iflatmap_unordered,
map_nested,
temp_seed,
temporary_assignment,
zip_dict,
)
from .utils import require_tf, require_torch
def __lowerCamelCase ( A__ : Optional[int] ) -> int: # picklable for multiprocessing
return x.sum()
def __lowerCamelCase ( A__ : int ) -> Optional[int]: # picklable for multiprocessing
return i + 1
@dataclass
class SCREAMING_SNAKE_CASE_ :
'''simple docstring'''
_a = 42
_a = 42
class SCREAMING_SNAKE_CASE_ (a__ ):
'''simple docstring'''
def _lowerCAmelCase ( self : Dict ) ->List[str]:
lowerCamelCase_ : List[str] = {}
lowerCamelCase_ : Union[str, Any] = []
lowerCamelCase_ : Optional[Any] = 1
lowerCamelCase_ : List[Any] = [1, 2]
lowerCamelCase_ : Any = {"""a""": 1, """b""": 2}
lowerCamelCase_ : Tuple = {"""a""": [1, 2], """b""": [3, 4]}
lowerCamelCase_ : List[str] = {"""a""": {"""1""": 1}, """b""": 2}
lowerCamelCase_ : Union[str, Any] = {"""a""": 1, """b""": 2, """c""": 3, """d""": 4}
lowerCamelCase_ : List[str] = {}
lowerCamelCase_ : Dict = []
lowerCamelCase_ : List[Any] = 2
lowerCamelCase_ : Optional[int] = [2, 3]
lowerCamelCase_ : Union[str, Any] = {"""a""": 2, """b""": 3}
lowerCamelCase_ : Any = {"""a""": [2, 3], """b""": [4, 5]}
lowerCamelCase_ : Dict = {"""a""": {"""1""": 2}, """b""": 3}
lowerCamelCase_ : Dict = {"""a""": 2, """b""": 3, """c""": 4, """d""": 5}
self.assertEqual(map_nested(__a , __a ) , __a )
self.assertEqual(map_nested(__a , __a ) , __a )
self.assertEqual(map_nested(__a , __a ) , __a )
self.assertEqual(map_nested(__a , __a ) , __a )
self.assertEqual(map_nested(__a , __a ) , __a )
self.assertEqual(map_nested(__a , __a ) , __a )
self.assertEqual(map_nested(__a , __a ) , __a )
self.assertEqual(map_nested(__a , __a ) , __a )
lowerCamelCase_ : List[str] = 2
self.assertEqual(map_nested(__a , __a , num_proc=__a ) , __a )
self.assertEqual(map_nested(__a , __a , num_proc=__a ) , __a )
self.assertEqual(map_nested(__a , __a , num_proc=__a ) , __a )
self.assertEqual(map_nested(__a , __a , num_proc=__a ) , __a )
self.assertEqual(map_nested(__a , __a , num_proc=__a ) , __a )
self.assertEqual(map_nested(__a , __a , num_proc=__a ) , __a )
self.assertEqual(map_nested(__a , __a , num_proc=__a ) , __a )
self.assertEqual(map_nested(__a , __a , num_proc=__a ) , __a )
lowerCamelCase_ : Optional[Any] = {"""a""": np.eye(2 ), """b""": np.zeros(3 ), """c""": np.ones(2 )}
lowerCamelCase_ : Any = {"""a""": 2, """b""": 0, """c""": 2}
lowerCamelCase_ : Tuple = {
"""a""": np.eye(2 ).astype(__a ),
"""b""": np.zeros(3 ).astype(__a ),
"""c""": np.ones(2 ).astype(__a ),
}
self.assertEqual(map_nested(__a , __a , map_numpy=__a ) , __a )
self.assertEqual(
{k: v.tolist() for k, v in map_nested(__a , __a , map_numpy=__a ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , )
self.assertEqual(map_nested(__a , __a , map_numpy=__a , num_proc=__a ) , __a )
self.assertEqual(
{k: v.tolist() for k, v in map_nested(__a , __a , map_numpy=__a , num_proc=__a ).items()} , {k: v.tolist() for k, v in expected_map_nested_sna_int.items()} , )
with self.assertRaises(__a ): # can't pickle a local lambda
map_nested(lambda __a : x + 1 , __a , num_proc=__a )
def _lowerCAmelCase ( self : str ) ->List[Any]:
lowerCamelCase_ : Tuple = {"""a""": 1, """b""": 2}
lowerCamelCase_ : List[str] = {"""a""": 3, """b""": 4}
lowerCamelCase_ : List[Any] = {"""a""": 5, """b""": 6}
lowerCamelCase_ : Any = sorted([("""a""", (1, 3, 5)), ("""b""", (2, 4, 6))] )
self.assertEqual(sorted(zip_dict(__a , __a , __a ) ) , __a )
def _lowerCAmelCase ( self : Dict ) ->str:
class SCREAMING_SNAKE_CASE_ :
'''simple docstring'''
_a = "bar"
lowerCamelCase_ : Any = Foo()
self.assertEqual(foo.my_attr , """bar""" )
with temporary_assignment(__a , """my_attr""" , """BAR""" ):
self.assertEqual(foo.my_attr , """BAR""" )
self.assertEqual(foo.my_attr , """bar""" )
@pytest.mark.parametrize(
"""iterable_length, num_proc, expected_num_proc""" , [
(1, None, 1),
(1, 1, 1),
(2, None, 1),
(2, 1, 1),
(2, 2, 1),
(2, 3, 1),
(3, 2, 1),
(16, 16, 16),
(16, 17, 16),
(17, 16, 16),
] , )
def __lowerCamelCase ( A__ : str , A__ : List[Any] , A__ : Optional[Any] ) -> int:
with patch("""datasets.utils.py_utils._single_map_nested""" ) as mock_single_map_nested, patch(
"""datasets.parallel.parallel.Pool""" ) as mock_multiprocessing_pool:
lowerCamelCase_ : Dict = {f'''{i}''': i for i in range(A__ )}
lowerCamelCase_ : Union[str, Any] = map_nested(lambda A__ : x + 10 , A__ , num_proc=A__ , parallel_min_length=16 )
if expected_num_proc == 1:
assert mock_single_map_nested.called
assert not mock_multiprocessing_pool.called
else:
assert not mock_single_map_nested.called
assert mock_multiprocessing_pool.called
assert mock_multiprocessing_pool.call_args[0][0] == expected_num_proc
class SCREAMING_SNAKE_CASE_ (a__ ):
'''simple docstring'''
@require_tf
def _lowerCAmelCase ( self : List[str] ) ->Dict:
import tensorflow as tf
from tensorflow.keras import layers
lowerCamelCase_ : List[str] = layers.Dense(2 )
def gen_random_output():
lowerCamelCase_ : Any = tf.random.uniform((1, 3) )
return model(__a ).numpy()
with temp_seed(42 , set_tensorflow=__a ):
lowerCamelCase_ : int = gen_random_output()
with temp_seed(42 , set_tensorflow=__a ):
lowerCamelCase_ : List[str] = gen_random_output()
lowerCamelCase_ : Union[str, Any] = gen_random_output()
np.testing.assert_equal(__a , __a )
self.assertGreater(np.abs(outa - outa ).sum() , 0 )
@require_torch
def _lowerCAmelCase ( self : List[str] ) ->List[str]:
import torch
def gen_random_output():
lowerCamelCase_ : Optional[Any] = torch.nn.Linear(3 , 2 )
lowerCamelCase_ : str = torch.rand(1 , 3 )
return model(__a ).detach().numpy()
with temp_seed(42 , set_pytorch=__a ):
lowerCamelCase_ : int = gen_random_output()
with temp_seed(42 , set_pytorch=__a ):
lowerCamelCase_ : Union[str, Any] = gen_random_output()
lowerCamelCase_ : Tuple = gen_random_output()
np.testing.assert_equal(__a , __a )
self.assertGreater(np.abs(outa - outa ).sum() , 0 )
def _lowerCAmelCase ( self : Optional[Any] ) ->List[Any]:
def gen_random_output():
return np.random.rand(1 , 3 )
with temp_seed(42 ):
lowerCamelCase_ : int = gen_random_output()
with temp_seed(42 ):
lowerCamelCase_ : Any = gen_random_output()
lowerCamelCase_ : Tuple = gen_random_output()
np.testing.assert_equal(__a , __a )
self.assertGreater(np.abs(outa - outa ).sum() , 0 )
@pytest.mark.parametrize("""input_data""" , [{}] )
def __lowerCamelCase ( A__ : int ) -> List[Any]:
lowerCamelCase_ : Optional[int] = NestedDataStructure(A__ ).data
assert output_data == input_data
@pytest.mark.parametrize(
"""data, expected_output""" , [
({}, []),
([], []),
("""foo""", ["""foo"""]),
(["""foo""", """bar"""], ["""foo""", """bar"""]),
([["""foo""", """bar"""]], ["""foo""", """bar"""]),
([[["""foo"""], ["""bar"""]]], ["""foo""", """bar"""]),
([[["""foo"""], """bar"""]], ["""foo""", """bar"""]),
({"""a""": 1, """b""": 2}, [1, 2]),
({"""a""": [1, 2], """b""": [3, 4]}, [1, 2, 3, 4]),
({"""a""": [[1, 2]], """b""": [[3, 4]]}, [1, 2, 3, 4]),
({"""a""": [[1, 2]], """b""": [3, 4]}, [1, 2, 3, 4]),
({"""a""": [[[1], [2]]], """b""": [[[3], [4]]]}, [1, 2, 3, 4]),
({"""a""": [[[1], [2]]], """b""": [[3, 4]]}, [1, 2, 3, 4]),
({"""a""": [[[1], [2]]], """b""": [3, 4]}, [1, 2, 3, 4]),
({"""a""": [[[1], [2]]], """b""": [3, [4]]}, [1, 2, 3, 4]),
({"""a""": {"""1""": 1}, """b""": 2}, [1, 2]),
({"""a""": {"""1""": [1]}, """b""": 2}, [1, 2]),
({"""a""": {"""1""": [1]}, """b""": [2]}, [1, 2]),
] , )
def __lowerCamelCase ( A__ : Optional[Any] , A__ : int ) -> Optional[Any]:
lowerCamelCase_ : int = NestedDataStructure(A__ ).flatten()
assert output == expected_output
def __lowerCamelCase ( ) -> Optional[Any]:
lowerCamelCase_ : Any = A(x=1 , y="""foobar""" )
lowerCamelCase_ : List[Any] = {"""x""": 1, """y""": """foobar"""}
assert asdict(A__ ) == expected_output
lowerCamelCase_ : Tuple = {"""a""": {"""b""": A(x=10 , y="""foo""" )}, """c""": [A(x=20 , y="""bar""" )]}
lowerCamelCase_ : Dict = {"""a""": {"""b""": {"""x""": 10, """y""": """foo"""}}, """c""": [{"""x""": 20, """y""": """bar"""}]}
assert asdict(A__ ) == expected_output
with pytest.raises(A__ ):
asdict([1, A(x=10 , y="""foo""" )] )
def __lowerCamelCase ( A__ : str ) -> Any:
return text.split()
def __lowerCamelCase ( A__ : str ) -> List[Any]:
yield (time.time(), content)
time.sleep(2 )
yield (time.time(), content)
def __lowerCamelCase ( ) -> List[str]:
with Pool(2 ) as pool:
lowerCamelCase_ : Dict = list(iflatmap_unordered(A__ , _split_text , kwargs_iterable=[{"""text""": """hello there"""}] * 10 ) )
assert out.count("""hello""" ) == 10
assert out.count("""there""" ) == 10
assert len(A__ ) == 20
# check multiprocess from pathos (uses dill for pickling)
with multiprocess.Pool(2 ) as pool:
lowerCamelCase_ : List[str] = list(iflatmap_unordered(A__ , _split_text , kwargs_iterable=[{"""text""": """hello there"""}] * 10 ) )
assert out.count("""hello""" ) == 10
assert out.count("""there""" ) == 10
assert len(A__ ) == 20
# check that we get items as fast as possible
with Pool(2 ) as pool:
lowerCamelCase_ : Optional[int] = []
for yield_time, content in iflatmap_unordered(
A__ , _aseconds_generator_of_aitems_with_timing , kwargs_iterable=[{"""content""": """a"""}, {"""content""": """b"""}] ):
assert yield_time < time.time() + 0.1, "we should each item directly after it was yielded"
out.append(A__ )
assert out.count("""a""" ) == 2
assert out.count("""b""" ) == 2
assert len(A__ ) == 4
| 278 |
from typing import Dict, List, Optional, Union
import numpy as np
from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
center_crop,
convert_to_rgb,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
OPENAI_CLIP_MEAN,
OPENAI_CLIP_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, is_vision_available, logging
snake_case__ : Tuple = logging.get_logger(__name__)
if is_vision_available():
import PIL
class SCREAMING_SNAKE_CASE_ (a__ ):
'''simple docstring'''
_a = ["pixel_values"]
def __init__( self : List[str] , __a : bool = True , __a : Dict[str, int] = None , __a : PILImageResampling = PILImageResampling.BICUBIC , __a : bool = True , __a : Dict[str, int] = None , __a : bool = True , __a : Union[int, float] = 1 / 255 , __a : bool = True , __a : Optional[Union[float, List[float]]] = None , __a : Optional[Union[float, List[float]]] = None , __a : bool = True , **__a : str , ) ->None:
super().__init__(**__a )
lowerCamelCase_ : Any = size if size is not None else {"""shortest_edge""": 224}
lowerCamelCase_ : List[Any] = get_size_dict(__a , default_to_square=__a )
lowerCamelCase_ : List[str] = crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
lowerCamelCase_ : Any = get_size_dict(__a , default_to_square=__a , param_name="""crop_size""" )
lowerCamelCase_ : List[Any] = do_resize
lowerCamelCase_ : str = size
lowerCamelCase_ : Any = resample
lowerCamelCase_ : List[Any] = do_center_crop
lowerCamelCase_ : Any = crop_size
lowerCamelCase_ : List[Any] = do_rescale
lowerCamelCase_ : Tuple = rescale_factor
lowerCamelCase_ : Dict = do_normalize
lowerCamelCase_ : Any = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
lowerCamelCase_ : int = image_std if image_std is not None else OPENAI_CLIP_STD
lowerCamelCase_ : Tuple = do_convert_rgb
def _lowerCAmelCase ( self : int , __a : np.ndarray , __a : Dict[str, int] , __a : PILImageResampling = PILImageResampling.BICUBIC , __a : Optional[Union[str, ChannelDimension]] = None , **__a : Dict , ) ->np.ndarray:
lowerCamelCase_ : Optional[Any] = get_size_dict(__a , default_to_square=__a )
if "shortest_edge" not in size:
raise ValueError(F'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' )
lowerCamelCase_ : Dict = get_resize_output_image_size(__a , size=size["""shortest_edge"""] , default_to_square=__a )
return resize(__a , size=__a , resample=__a , data_format=__a , **__a )
def _lowerCAmelCase ( self : Union[str, Any] , __a : np.ndarray , __a : Dict[str, int] , __a : Optional[Union[str, ChannelDimension]] = None , **__a : List[Any] , ) ->np.ndarray:
lowerCamelCase_ : List[Any] = get_size_dict(__a )
if "height" not in size or "width" not in size:
raise ValueError(F'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' )
return center_crop(__a , size=(size["""height"""], size["""width"""]) , data_format=__a , **__a )
def _lowerCAmelCase ( self : Optional[Any] , __a : np.ndarray , __a : Union[int, float] , __a : Optional[Union[str, ChannelDimension]] = None , **__a : Dict , ) ->Dict:
return rescale(__a , scale=__a , data_format=__a , **__a )
def _lowerCAmelCase ( self : List[Any] , __a : np.ndarray , __a : Union[float, List[float]] , __a : Union[float, List[float]] , __a : Optional[Union[str, ChannelDimension]] = None , **__a : List[str] , ) ->np.ndarray:
return normalize(__a , mean=__a , std=__a , data_format=__a , **__a )
def _lowerCAmelCase ( self : str , __a : ImageInput , __a : bool = None , __a : Dict[str, int] = None , __a : PILImageResampling = None , __a : bool = None , __a : int = None , __a : bool = None , __a : float = None , __a : bool = None , __a : Optional[Union[float, List[float]]] = None , __a : Optional[Union[float, List[float]]] = None , __a : bool = None , __a : Optional[Union[str, TensorType]] = None , __a : Optional[ChannelDimension] = ChannelDimension.FIRST , **__a : List[str] , ) ->PIL.Image.Image:
lowerCamelCase_ : List[Any] = do_resize if do_resize is not None else self.do_resize
lowerCamelCase_ : Any = size if size is not None else self.size
lowerCamelCase_ : str = get_size_dict(__a , param_name="""size""" , default_to_square=__a )
lowerCamelCase_ : List[str] = resample if resample is not None else self.resample
lowerCamelCase_ : List[str] = do_center_crop if do_center_crop is not None else self.do_center_crop
lowerCamelCase_ : List[Any] = crop_size if crop_size is not None else self.crop_size
lowerCamelCase_ : Optional[int] = get_size_dict(__a , param_name="""crop_size""" , default_to_square=__a )
lowerCamelCase_ : List[Any] = do_rescale if do_rescale is not None else self.do_rescale
lowerCamelCase_ : List[str] = rescale_factor if rescale_factor is not None else self.rescale_factor
lowerCamelCase_ : Dict = do_normalize if do_normalize is not None else self.do_normalize
lowerCamelCase_ : Dict = image_mean if image_mean is not None else self.image_mean
lowerCamelCase_ : Tuple = image_std if image_std is not None else self.image_std
lowerCamelCase_ : Union[str, Any] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
lowerCamelCase_ : Union[str, Any] = 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:
raise ValueError("""Size must be specified if do_resize is True.""" )
if do_center_crop and crop_size is None:
raise ValueError("""Crop size must be specified if do_center_crop is True.""" )
if do_rescale and rescale_factor is None:
raise ValueError("""Rescale factor must be specified if do_rescale is True.""" )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError("""Image mean and std must be specified if do_normalize is True.""" )
# PIL RGBA images are converted to RGB
if do_convert_rgb:
lowerCamelCase_ : str = [convert_to_rgb(__a ) for image in images]
# All transformations expect numpy arrays.
lowerCamelCase_ : str = [to_numpy_array(__a ) for image in images]
if do_resize:
lowerCamelCase_ : int = [self.resize(image=__a , size=__a , resample=__a ) for image in images]
if do_center_crop:
lowerCamelCase_ : Dict = [self.center_crop(image=__a , size=__a ) for image in images]
if do_rescale:
lowerCamelCase_ : List[str] = [self.rescale(image=__a , scale=__a ) for image in images]
if do_normalize:
lowerCamelCase_ : Tuple = [self.normalize(image=__a , mean=__a , std=__a ) for image in images]
lowerCamelCase_ : Tuple = [to_channel_dimension_format(__a , __a ) for image in images]
lowerCamelCase_ : Tuple = {"""pixel_values""": images}
return BatchFeature(data=__a , tensor_type=__a )
| 278 | 1 |
'''simple docstring'''
snake_case_ = [
9_99,
8_00,
7_99,
6_00,
5_99,
5_00,
4_00,
3_99,
3_77,
3_55,
3_33,
3_11,
2_88,
2_66,
2_44,
2_22,
2_00,
1_99,
1_77,
1_55,
1_33,
1_11,
88,
66,
44,
22,
0,
]
snake_case_ = [
9_99,
9_76,
9_52,
9_28,
9_05,
8_82,
8_58,
8_57,
8_10,
7_62,
7_15,
7_14,
5_72,
4_29,
4_28,
2_86,
2_85,
2_38,
1_90,
1_43,
1_42,
1_18,
95,
71,
47,
24,
0,
]
snake_case_ = [
9_99,
9_88,
9_77,
9_66,
9_55,
9_44,
9_33,
9_22,
9_11,
9_00,
8_99,
8_79,
8_59,
8_40,
8_20,
8_00,
7_99,
7_66,
7_33,
7_00,
6_99,
6_50,
6_00,
5_99,
5_00,
4_99,
4_00,
3_99,
3_50,
3_00,
2_99,
2_66,
2_33,
2_00,
1_99,
1_79,
1_59,
1_40,
1_20,
1_00,
99,
88,
77,
66,
55,
44,
33,
22,
11,
0,
]
snake_case_ = [
9_99,
9_95,
9_92,
9_89,
9_85,
9_81,
9_78,
9_75,
9_71,
9_67,
9_64,
9_61,
9_57,
9_56,
9_51,
9_47,
9_42,
9_37,
9_33,
9_28,
9_23,
9_19,
9_14,
9_13,
9_08,
9_03,
8_97,
8_92,
8_87,
8_81,
8_76,
8_71,
8_70,
8_64,
8_58,
8_52,
8_46,
8_40,
8_34,
8_28,
8_27,
8_20,
8_13,
8_06,
7_99,
7_92,
7_85,
7_84,
7_77,
7_70,
7_63,
7_56,
7_49,
7_42,
7_41,
7_33,
7_24,
7_16,
7_07,
6_99,
6_98,
6_88,
6_77,
6_66,
6_56,
6_55,
6_45,
6_34,
6_23,
6_13,
6_12,
5_98,
5_84,
5_70,
5_69,
5_55,
5_41,
5_27,
5_26,
5_05,
4_84,
4_83,
4_62,
4_40,
4_39,
3_96,
3_95,
3_52,
3_51,
3_08,
3_07,
2_64,
2_63,
2_20,
2_19,
1_76,
1_32,
88,
44,
0,
]
snake_case_ = [
9_99,
9_97,
9_95,
9_92,
9_90,
9_88,
9_86,
9_84,
9_81,
9_79,
9_77,
9_75,
9_72,
9_70,
9_68,
9_66,
9_64,
9_61,
9_59,
9_57,
9_56,
9_54,
9_51,
9_49,
9_46,
9_44,
9_41,
9_39,
9_36,
9_34,
9_31,
9_29,
9_26,
9_24,
9_21,
9_19,
9_16,
9_14,
9_13,
9_10,
9_07,
9_05,
9_02,
8_99,
8_96,
8_93,
8_91,
8_88,
8_85,
8_82,
8_79,
8_77,
8_74,
8_71,
8_70,
8_67,
8_64,
8_61,
8_58,
8_55,
8_52,
8_49,
8_46,
8_43,
8_40,
8_37,
8_34,
8_31,
8_28,
8_27,
8_24,
8_21,
8_17,
8_14,
8_11,
8_08,
8_04,
8_01,
7_98,
7_95,
7_91,
7_88,
7_85,
7_84,
7_80,
7_77,
7_74,
7_70,
7_66,
7_63,
7_60,
7_56,
7_52,
7_49,
7_46,
7_42,
7_41,
7_37,
7_33,
7_30,
7_26,
7_22,
7_18,
7_14,
7_10,
7_07,
7_03,
6_99,
6_98,
6_94,
6_90,
6_85,
6_81,
6_77,
6_73,
6_69,
6_64,
6_60,
6_56,
6_55,
6_50,
6_46,
6_41,
6_36,
6_32,
6_27,
6_22,
6_18,
6_13,
6_12,
6_07,
6_02,
5_96,
5_91,
5_86,
5_80,
5_75,
5_70,
5_69,
5_63,
5_57,
5_51,
5_45,
5_39,
5_33,
5_27,
5_26,
5_19,
5_12,
5_05,
4_98,
4_91,
4_84,
4_83,
4_74,
4_66,
4_57,
4_49,
4_40,
4_39,
4_28,
4_18,
4_07,
3_96,
3_95,
3_81,
3_66,
3_52,
3_51,
3_30,
3_08,
3_07,
2_86,
2_64,
2_63,
2_42,
2_20,
2_19,
1_76,
1_75,
1_32,
1_31,
88,
44,
0,
]
snake_case_ = [
9_99,
9_91,
9_82,
9_74,
9_66,
9_58,
9_50,
9_41,
9_33,
9_25,
9_16,
9_08,
9_00,
8_99,
8_74,
8_50,
8_25,
8_00,
7_99,
7_00,
6_00,
5_00,
4_00,
3_00,
2_00,
1_00,
0,
]
snake_case_ = [
9_99,
9_92,
9_85,
9_78,
9_71,
9_64,
9_57,
9_49,
9_42,
9_35,
9_28,
9_21,
9_14,
9_07,
9_00,
8_99,
8_79,
8_59,
8_40,
8_20,
8_00,
7_99,
7_66,
7_33,
7_00,
6_99,
6_50,
6_00,
5_99,
5_00,
4_99,
4_00,
3_99,
3_00,
2_99,
2_00,
1_99,
1_00,
99,
0,
]
snake_case_ = [
9_99,
9_96,
9_92,
9_89,
9_85,
9_82,
9_79,
9_75,
9_72,
9_68,
9_65,
9_61,
9_58,
9_55,
9_51,
9_48,
9_44,
9_41,
9_38,
9_34,
9_31,
9_27,
9_24,
9_20,
9_17,
9_14,
9_10,
9_07,
9_03,
9_00,
8_99,
8_91,
8_84,
8_76,
8_69,
8_61,
8_53,
8_46,
8_38,
8_30,
8_23,
8_15,
8_08,
8_00,
7_99,
7_88,
7_77,
7_66,
7_55,
7_44,
7_33,
7_22,
7_11,
7_00,
6_99,
6_88,
6_77,
6_66,
6_55,
6_44,
6_33,
6_22,
6_11,
6_00,
5_99,
5_85,
5_71,
5_57,
5_42,
5_28,
5_14,
5_00,
4_99,
4_85,
4_71,
4_57,
4_42,
4_28,
4_14,
4_00,
3_99,
3_79,
3_59,
3_40,
3_20,
3_00,
2_99,
2_79,
2_59,
2_40,
2_20,
2_00,
1_99,
1_66,
1_33,
1_00,
99,
66,
33,
0,
]
| 537 |
'''simple docstring'''
import argparse
import os
import re
import numpy as np
import PIL
import torch
from timm import create_model
from torch.optim.lr_scheduler import OneCycleLR
from torch.utils.data import DataLoader, Dataset
from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor
from accelerate import Accelerator
def _lowerCamelCase( UpperCamelCase__ : Dict ) -> Union[str, Any]:
A : Optional[Any] = fname.split(os.path.sep )[-1]
return re.search(R'''^(.*)_\d+\.jpg$''' , UpperCamelCase__ ).groups()[0]
class _lowercase ( a ):
def __init__( self , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None ):
A : str = file_names
A : Optional[int] = image_transform
A : str = label_to_id
def __len__( self ):
return len(self.file_names )
def __getitem__( self , _UpperCAmelCase ):
A : int = self.file_names[idx]
A : int = PIL.Image.open(_UpperCAmelCase )
A : str = raw_image.convert('''RGB''' )
if self.image_transform is not None:
A : Dict = self.image_transform(_UpperCAmelCase )
A : Tuple = extract_label(_UpperCAmelCase )
if self.label_to_id is not None:
A : Optional[Any] = self.label_to_id[label]
return {"image": image, "label": label}
def _lowerCamelCase( UpperCamelCase__ : List[Any] , UpperCamelCase__ : int ) -> Any:
# Initialize accelerator
if args.with_tracking:
A : Union[str, Any] = Accelerator(
cpu=args.cpu , mixed_precision=args.mixed_precision , log_with='''all''' , project_dir=args.project_dir )
else:
A : Dict = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision )
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
A : List[str] = config['''lr''']
A : int = int(config['''num_epochs'''] )
A : List[str] = int(config['''seed'''] )
A : Any = int(config['''batch_size'''] )
A : List[str] = config['''image_size''']
if not isinstance(UpperCamelCase__ , (list, tuple) ):
A : List[str] = (image_size, image_size)
# Parse out whether we are saving every epoch or after a certain number of batches
if hasattr(args.checkpointing_steps , '''isdigit''' ):
if args.checkpointing_steps == "epoch":
A : List[Any] = args.checkpointing_steps
elif args.checkpointing_steps.isdigit():
A : Optional[Any] = int(args.checkpointing_steps )
else:
raise ValueError(
F'''Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed.''' )
else:
A : Optional[Any] = None
# We need to initialize the trackers we use, and also store our configuration
if args.with_tracking:
A : Any = os.path.split(UpperCamelCase__ )[-1].split('''.''' )[0]
accelerator.init_trackers(UpperCamelCase__ , UpperCamelCase__ )
# Grab all the image filenames
A : int = [os.path.join(args.data_dir , UpperCamelCase__ ) for fname in os.listdir(args.data_dir ) if fname.endswith('''.jpg''' )]
# Build the label correspondences
A : int = [extract_label(UpperCamelCase__ ) for fname in file_names]
A : str = list(set(UpperCamelCase__ ) )
id_to_label.sort()
A : Dict = {lbl: i for i, lbl in enumerate(UpperCamelCase__ )}
# Set the seed before splitting the data.
np.random.seed(UpperCamelCase__ )
torch.manual_seed(UpperCamelCase__ )
torch.cuda.manual_seed_all(UpperCamelCase__ )
# Split our filenames between train and validation
A : Dict = np.random.permutation(len(UpperCamelCase__ ) )
A : str = int(0.8 * len(UpperCamelCase__ ) )
A : Tuple = random_perm[:cut]
A : List[Any] = random_perm[cut:]
# For training we use a simple RandomResizedCrop
A : Any = Compose([RandomResizedCrop(UpperCamelCase__ , scale=(0.5, 1.0) ), ToTensor()] )
A : List[Any] = PetsDataset(
[file_names[i] for i in train_split] , image_transform=UpperCamelCase__ , label_to_id=UpperCamelCase__ )
# For evaluation, we use a deterministic Resize
A : Optional[Any] = Compose([Resize(UpperCamelCase__ ), ToTensor()] )
A : List[Any] = PetsDataset([file_names[i] for i in eval_split] , image_transform=UpperCamelCase__ , label_to_id=UpperCamelCase__ )
# Instantiate dataloaders.
A : List[str] = DataLoader(UpperCamelCase__ , shuffle=UpperCamelCase__ , batch_size=UpperCamelCase__ , num_workers=4 )
A : Tuple = DataLoader(UpperCamelCase__ , shuffle=UpperCamelCase__ , batch_size=UpperCamelCase__ , num_workers=4 )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
A : Union[str, Any] = create_model('''resnet50d''' , pretrained=UpperCamelCase__ , num_classes=len(UpperCamelCase__ ) )
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
A : Optional[int] = model.to(accelerator.device )
# Freezing the base model
for param in model.parameters():
A : Union[str, Any] = False
for param in model.get_classifier().parameters():
A : Any = True
# We normalize the batches of images to be a bit faster.
A : Dict = torch.tensor(model.default_cfg['''mean'''] )[None, :, None, None].to(accelerator.device )
A : str = torch.tensor(model.default_cfg['''std'''] )[None, :, None, None].to(accelerator.device )
# Instantiate optimizer
A : List[Any] = torch.optim.Adam(params=model.parameters() , lr=lr / 25 )
# Instantiate learning rate scheduler
A : int = OneCycleLR(optimizer=UpperCamelCase__ , max_lr=UpperCamelCase__ , epochs=UpperCamelCase__ , steps_per_epoch=len(UpperCamelCase__ ) )
# 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.
A, A, A, A, A : Optional[int] = accelerator.prepare(
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ )
# We need to keep track of how many total steps we have iterated over
A : Dict = 0
# We also need to keep track of the starting epoch so files are named properly
A : str = 0
# Potentially load in the weights and states from a previous save
if args.resume_from_checkpoint:
if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
accelerator.print(F'''Resumed from checkpoint: {args.resume_from_checkpoint}''' )
accelerator.load_state(args.resume_from_checkpoint )
A : Optional[int] = os.path.basename(args.resume_from_checkpoint )
else:
# Get the most recent checkpoint
A : Dict = [f.name for f in os.scandir(os.getcwd() ) if f.is_dir()]
dirs.sort(key=os.path.getctime )
A : Optional[int] = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
# Extract `epoch_{i}` or `step_{i}`
A : Optional[int] = os.path.splitext(UpperCamelCase__ )[0]
if "epoch" in training_difference:
A : Tuple = int(training_difference.replace('''epoch_''' , '''''' ) ) + 1
A : Union[str, Any] = None
else:
A : int = int(training_difference.replace('''step_''' , '''''' ) )
A : str = resume_step // len(UpperCamelCase__ )
resume_step -= starting_epoch * len(UpperCamelCase__ )
# Now we train the model
for epoch in range(UpperCamelCase__ , UpperCamelCase__ ):
model.train()
if args.with_tracking:
A : int = 0
if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
# We need to skip steps until we reach the resumed step
A : str = accelerator.skip_first_batches(UpperCamelCase__ , UpperCamelCase__ )
overall_step += resume_step
else:
# After the first iteration though, we need to go back to the original dataloader
A : int = train_dataloader
for batch in active_dataloader:
# We could avoid this line since we set the accelerator with `device_placement=True`.
A : Any = {k: v.to(accelerator.device ) for k, v in batch.items()}
A : Optional[int] = (batch['''image'''] - mean) / std
A : int = model(UpperCamelCase__ )
A : List[Any] = torch.nn.functional.cross_entropy(UpperCamelCase__ , batch['''label'''] )
# We keep track of the loss at each epoch
if args.with_tracking:
total_loss += loss.detach().float()
accelerator.backward(UpperCamelCase__ )
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
overall_step += 1
if isinstance(UpperCamelCase__ , UpperCamelCase__ ):
A : List[Any] = F'''step_{overall_step}'''
if overall_step % checkpointing_steps == 0:
if args.output_dir is not None:
A : Dict = os.path.join(args.output_dir , UpperCamelCase__ )
accelerator.save_state(UpperCamelCase__ )
model.eval()
A : Optional[int] = 0
A : int = 0
for step, batch in enumerate(UpperCamelCase__ ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
A : Any = {k: v.to(accelerator.device ) for k, v in batch.items()}
A : Any = (batch['''image'''] - mean) / std
with torch.no_grad():
A : Union[str, Any] = model(UpperCamelCase__ )
A : Tuple = outputs.argmax(dim=-1 )
A, A : List[Any] = accelerator.gather_for_metrics((predictions, batch['''label''']) )
A : Any = predictions == references
num_elems += accurate_preds.shape[0]
accurate += accurate_preds.long().sum()
A : str = accurate.item() / num_elems
# Use accelerator.print to print only on the main process.
accelerator.print(F'''epoch {epoch}: {100 * eval_metric:.2f}''' )
if args.with_tracking:
accelerator.log(
{
'''accuracy''': 100 * eval_metric,
'''train_loss''': total_loss.item() / len(UpperCamelCase__ ),
'''epoch''': epoch,
} , step=UpperCamelCase__ , )
if checkpointing_steps == "epoch":
A : Dict = F'''epoch_{epoch}'''
if args.output_dir is not None:
A : Dict = os.path.join(args.output_dir , UpperCamelCase__ )
accelerator.save_state(UpperCamelCase__ )
if args.with_tracking:
accelerator.end_training()
def _lowerCamelCase( ) -> int:
A : List[str] = argparse.ArgumentParser(description='''Simple example of training script.''' )
parser.add_argument('''--data_dir''' , required=UpperCamelCase__ , help='''The data folder on disk.''' )
parser.add_argument('''--fp16''' , action='''store_true''' , help='''If passed, will use FP16 training.''' )
parser.add_argument(
'''--mixed_precision''' , type=UpperCamelCase__ , default=UpperCamelCase__ , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose'''
'''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.'''
'''and an Nvidia Ampere GPU.''' , )
parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' )
parser.add_argument(
'''--checkpointing_steps''' , type=UpperCamelCase__ , default=UpperCamelCase__ , help='''Whether the various states should be saved at the end of every n steps, or \'epoch\' for each epoch.''' , )
parser.add_argument(
'''--output_dir''' , type=UpperCamelCase__ , default='''.''' , help='''Optional save directory where all checkpoint folders will be stored. Default is the current working directory.''' , )
parser.add_argument(
'''--resume_from_checkpoint''' , type=UpperCamelCase__ , default=UpperCamelCase__ , help='''If the training should continue from a checkpoint folder.''' , )
parser.add_argument(
'''--with_tracking''' , action='''store_true''' , help='''Whether to load in all available experiment trackers from the environment and use them for logging.''' , )
parser.add_argument(
'''--project_dir''' , type=UpperCamelCase__ , default='''logs''' , help='''Location on where to store experiment tracking logs` and relevent project information''' , )
A : Tuple = parser.parse_args()
A : List[str] = {'''lr''': 3e-2, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 64, '''image_size''': 224}
training_function(UpperCamelCase__ , UpperCamelCase__ )
if __name__ == "__main__":
main()
| 537 | 1 |
import copy
import unittest
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
MODEL_FOR_QUESTION_ANSWERING_MAPPING,
MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
LayoutLMvaConfig,
LayoutLMvaForQuestionAnswering,
LayoutLMvaForSequenceClassification,
LayoutLMvaForTokenClassification,
LayoutLMvaModel,
)
from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import LayoutLMvaImageProcessor
class __lowercase :
"""simple docstring"""
def __init__( self , lowerCAmelCase__ , lowerCAmelCase__=2 , lowerCAmelCase__=3 , lowerCAmelCase__=4 , lowerCAmelCase__=2 , lowerCAmelCase__=7 , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=True , lowerCAmelCase__=9_9 , lowerCAmelCase__=3_6 , lowerCAmelCase__=3 , lowerCAmelCase__=4 , lowerCAmelCase__=3_7 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=5_1_2 , lowerCAmelCase__=1_6 , lowerCAmelCase__=2 , lowerCAmelCase__=0.02 , lowerCAmelCase__=6 , lowerCAmelCase__=6 , lowerCAmelCase__=3 , lowerCAmelCase__=4 , lowerCAmelCase__=None , lowerCAmelCase__=1_0_0_0 , ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Optional[int] = parent
SCREAMING_SNAKE_CASE_ : Tuple = batch_size
SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_channels
SCREAMING_SNAKE_CASE_ : Any = image_size
SCREAMING_SNAKE_CASE_ : int = patch_size
SCREAMING_SNAKE_CASE_ : int = text_seq_length
SCREAMING_SNAKE_CASE_ : Optional[Any] = is_training
SCREAMING_SNAKE_CASE_ : Optional[Any] = use_input_mask
SCREAMING_SNAKE_CASE_ : List[Any] = use_token_type_ids
SCREAMING_SNAKE_CASE_ : int = use_labels
SCREAMING_SNAKE_CASE_ : Optional[Any] = vocab_size
SCREAMING_SNAKE_CASE_ : List[str] = hidden_size
SCREAMING_SNAKE_CASE_ : Union[str, Any] = num_hidden_layers
SCREAMING_SNAKE_CASE_ : List[str] = num_attention_heads
SCREAMING_SNAKE_CASE_ : Union[str, Any] = intermediate_size
SCREAMING_SNAKE_CASE_ : int = hidden_act
SCREAMING_SNAKE_CASE_ : Optional[Any] = hidden_dropout_prob
SCREAMING_SNAKE_CASE_ : int = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE_ : Dict = max_position_embeddings
SCREAMING_SNAKE_CASE_ : Tuple = type_vocab_size
SCREAMING_SNAKE_CASE_ : str = type_sequence_label_size
SCREAMING_SNAKE_CASE_ : int = initializer_range
SCREAMING_SNAKE_CASE_ : Union[str, Any] = coordinate_size
SCREAMING_SNAKE_CASE_ : Union[str, Any] = shape_size
SCREAMING_SNAKE_CASE_ : Optional[Any] = num_labels
SCREAMING_SNAKE_CASE_ : int = num_choices
SCREAMING_SNAKE_CASE_ : Dict = scope
SCREAMING_SNAKE_CASE_ : str = range_bbox
# LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
SCREAMING_SNAKE_CASE_ : List[Any] = text_seq_length
SCREAMING_SNAKE_CASE_ : List[Any] = (image_size // patch_size) ** 2 + 1
SCREAMING_SNAKE_CASE_ : int = self.text_seq_length + self.image_seq_length
def UpperCamelCase__ ( self ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Tuple = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size )
SCREAMING_SNAKE_CASE_ : Optional[int] = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox )
# Ensure that bbox is legal
for i in range(bbox.shape[0] ):
for j in range(bbox.shape[1] ):
if bbox[i, j, 3] < bbox[i, j, 1]:
SCREAMING_SNAKE_CASE_ : List[Any] = bbox[i, j, 3]
SCREAMING_SNAKE_CASE_ : Dict = bbox[i, j, 1]
SCREAMING_SNAKE_CASE_ : str = t
if bbox[i, j, 2] < bbox[i, j, 0]:
SCREAMING_SNAKE_CASE_ : Optional[Any] = bbox[i, j, 2]
SCREAMING_SNAKE_CASE_ : int = bbox[i, j, 0]
SCREAMING_SNAKE_CASE_ : Optional[int] = t
SCREAMING_SNAKE_CASE_ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
SCREAMING_SNAKE_CASE_ : List[Any] = None
if self.use_input_mask:
SCREAMING_SNAKE_CASE_ : Dict = random_attention_mask([self.batch_size, self.text_seq_length] )
SCREAMING_SNAKE_CASE_ : Optional[int] = None
if self.use_token_type_ids:
SCREAMING_SNAKE_CASE_ : Dict = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size )
SCREAMING_SNAKE_CASE_ : List[Any] = None
SCREAMING_SNAKE_CASE_ : str = None
if self.use_labels:
SCREAMING_SNAKE_CASE_ : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size )
SCREAMING_SNAKE_CASE_ : Optional[int] = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels )
SCREAMING_SNAKE_CASE_ : int = LayoutLMvaConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , )
return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels
def UpperCamelCase__ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : List[str] = LayoutLMvaModel(config=lowerCAmelCase__ )
model.to(lowerCAmelCase__ )
model.eval()
# text + image
SCREAMING_SNAKE_CASE_ : Optional[Any] = model(lowerCAmelCase__ , pixel_values=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : Optional[int] = model(
lowerCAmelCase__ , bbox=lowerCAmelCase__ , pixel_values=lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : str = model(lowerCAmelCase__ , bbox=lowerCAmelCase__ , pixel_values=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : Dict = model(lowerCAmelCase__ , bbox=lowerCAmelCase__ , pixel_values=lowerCAmelCase__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
# text only
SCREAMING_SNAKE_CASE_ : List[str] = model(lowerCAmelCase__ )
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) )
# image only
SCREAMING_SNAKE_CASE_ : str = model(pixel_values=lowerCAmelCase__ )
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) )
def UpperCamelCase__ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Tuple = self.num_labels
SCREAMING_SNAKE_CASE_ : Any = LayoutLMvaForSequenceClassification(lowerCAmelCase__ )
model.to(lowerCAmelCase__ )
model.eval()
SCREAMING_SNAKE_CASE_ : Any = model(
lowerCAmelCase__ , bbox=lowerCAmelCase__ , pixel_values=lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ , labels=lowerCAmelCase__ , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def UpperCamelCase__ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Dict = self.num_labels
SCREAMING_SNAKE_CASE_ : Any = LayoutLMvaForTokenClassification(config=lowerCAmelCase__ )
model.to(lowerCAmelCase__ )
model.eval()
SCREAMING_SNAKE_CASE_ : int = model(
lowerCAmelCase__ , bbox=lowerCAmelCase__ , pixel_values=lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ , labels=lowerCAmelCase__ , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) )
def UpperCamelCase__ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : str = LayoutLMvaForQuestionAnswering(config=lowerCAmelCase__ )
model.to(lowerCAmelCase__ )
model.eval()
SCREAMING_SNAKE_CASE_ : List[str] = model(
lowerCAmelCase__ , bbox=lowerCAmelCase__ , pixel_values=lowerCAmelCase__ , attention_mask=lowerCAmelCase__ , token_type_ids=lowerCAmelCase__ , start_positions=lowerCAmelCase__ , end_positions=lowerCAmelCase__ , )
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 ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Optional[Any] = self.prepare_config_and_inputs()
(
(
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) , (
SCREAMING_SNAKE_CASE_
) ,
) : Dict = config_and_inputs
SCREAMING_SNAKE_CASE_ : Any = {
'input_ids': input_ids,
'bbox': bbox,
'pixel_values': pixel_values,
'token_type_ids': token_type_ids,
'attention_mask': input_mask,
}
return config, inputs_dict
@require_torch
class __lowercase (__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ):
"""simple docstring"""
_UpperCAmelCase = False
_UpperCAmelCase = False
_UpperCAmelCase = False
_UpperCAmelCase = (
(
LayoutLMvaModel,
LayoutLMvaForSequenceClassification,
LayoutLMvaForTokenClassification,
LayoutLMvaForQuestionAnswering,
)
if is_torch_available()
else ()
)
_UpperCAmelCase = (
{"""document-question-answering""": LayoutLMvaForQuestionAnswering, """feature-extraction""": LayoutLMvaModel}
if is_torch_available()
else {}
)
def UpperCamelCase__ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ):
"""simple docstring"""
return True
def UpperCamelCase__ ( self ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Optional[Any] = LayoutLMvaModelTester(self )
SCREAMING_SNAKE_CASE_ : Any = ConfigTester(self , config_class=lowerCAmelCase__ , hidden_size=3_7 )
def UpperCamelCase__ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=False ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Union[str, Any] = copy.deepcopy(lowerCAmelCase__ )
if model_class in get_values(lowerCAmelCase__ ):
SCREAMING_SNAKE_CASE_ : Dict = {
k: v.unsqueeze(1 ).expand(-1 , self.model_tester.num_choices , -1 ).contiguous()
if isinstance(lowerCAmelCase__ , torch.Tensor ) and v.ndim > 1
else v
for k, v in inputs_dict.items()
}
if return_labels:
if model_class in get_values(lowerCAmelCase__ ):
SCREAMING_SNAKE_CASE_ : List[Any] = torch.ones(self.model_tester.batch_size , dtype=torch.long , device=lowerCAmelCase__ )
elif model_class in get_values(lowerCAmelCase__ ):
SCREAMING_SNAKE_CASE_ : int = torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : Tuple = torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=lowerCAmelCase__ )
elif model_class in [
*get_values(lowerCAmelCase__ ),
]:
SCREAMING_SNAKE_CASE_ : Tuple = torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=lowerCAmelCase__ )
elif model_class in [
*get_values(lowerCAmelCase__ ),
]:
SCREAMING_SNAKE_CASE_ : Any = torch.zeros(
(self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=torch.long , device=lowerCAmelCase__ , )
return inputs_dict
def UpperCamelCase__ ( self ):
"""simple docstring"""
self.config_tester.run_common_tests()
def UpperCamelCase__ ( self ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowerCAmelCase__ )
def UpperCamelCase__ ( self ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Tuple = self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
SCREAMING_SNAKE_CASE_ : int = type
self.model_tester.create_and_check_model(*lowerCAmelCase__ )
def UpperCamelCase__ ( self ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*lowerCAmelCase__ )
def UpperCamelCase__ ( self ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*lowerCAmelCase__ )
def UpperCamelCase__ ( self ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Tuple = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*lowerCAmelCase__ )
@slow
def UpperCamelCase__ ( self ):
"""simple docstring"""
for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
SCREAMING_SNAKE_CASE_ : Optional[Any] = LayoutLMvaModel.from_pretrained(lowerCAmelCase__ )
self.assertIsNotNone(lowerCAmelCase__ )
def a__ ( ):
SCREAMING_SNAKE_CASE_ : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' )
return image
@require_torch
class __lowercase (unittest.TestCase ):
"""simple docstring"""
@cached_property
def UpperCamelCase__ ( self ):
"""simple docstring"""
return LayoutLMvaImageProcessor(apply_ocr=lowerCAmelCase__ ) if is_vision_available() else None
@slow
def UpperCamelCase__ ( self ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Optional[Any] = LayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base' ).to(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : Tuple = self.default_image_processor
SCREAMING_SNAKE_CASE_ : Tuple = prepare_img()
SCREAMING_SNAKE_CASE_ : Dict = image_processor(images=lowerCAmelCase__ , return_tensors='pt' ).pixel_values.to(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : List[Any] = torch.tensor([[1, 2]] )
SCREAMING_SNAKE_CASE_ : List[str] = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]] ).unsqueeze(0 )
# forward pass
SCREAMING_SNAKE_CASE_ : List[Any] = model(
input_ids=input_ids.to(lowerCAmelCase__ ) , bbox=bbox.to(lowerCAmelCase__ ) , pixel_values=pixel_values.to(lowerCAmelCase__ ) , )
# verify the logits
SCREAMING_SNAKE_CASE_ : str = torch.Size((1, 1_9_9, 7_6_8) )
self.assertEqual(outputs.last_hidden_state.shape , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE_ : str = torch.tensor(
[[-0.0_529, 0.3_618, 0.1_632], [-0.1_587, -0.1_667, -0.0_400], [-0.1_557, -0.1_671, -0.0_505]] ).to(lowerCAmelCase__ )
self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , lowerCAmelCase__ , atol=1E-4 ) )
| 101 |
"""simple docstring"""
def __snake_case ( ) -> Union[str, Any]:
lowercase : str = 0
for i in range(1 ,1001 ):
total += i**i
return str(__A )[-10:]
if __name__ == "__main__":
print(solution())
| 607 | 0 |
import torch
from diffusers import EulerDiscreteScheduler
from diffusers.utils import torch_device
from .test_schedulers import SchedulerCommonTest
class a__ ( UpperCamelCase_ ):
A__ : Optional[Any] = (EulerDiscreteScheduler,)
A__ : Tuple = 10
def __SCREAMING_SNAKE_CASE ( self , **UpperCAmelCase ) -> Any:
__a = {
"""num_train_timesteps""": 1_1_0_0,
"""beta_start""": 0.0_001,
"""beta_end""": 0.02,
"""beta_schedule""": """linear""",
}
config.update(**_a )
return config
def __SCREAMING_SNAKE_CASE ( self ) -> Optional[int]:
for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]:
self.check_over_configs(num_train_timesteps=_a )
def __SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]:
for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ):
self.check_over_configs(beta_start=_a , beta_end=_a )
def __SCREAMING_SNAKE_CASE ( self ) -> List[Any]:
for schedule in ["linear", "scaled_linear"]:
self.check_over_configs(beta_schedule=_a )
def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]:
for prediction_type in ["epsilon", "v_prediction"]:
self.check_over_configs(prediction_type=_a )
def __SCREAMING_SNAKE_CASE ( self ) -> List[Any]:
__a = self.scheduler_classes[0]
__a = self.get_scheduler_config()
__a = scheduler_class(**_a )
scheduler.set_timesteps(self.num_inference_steps )
__a = torch.manual_seed(0 )
__a = self.dummy_model()
__a = self.dummy_sample_deter * scheduler.init_noise_sigma
__a = sample.to(_a )
for i, t in enumerate(scheduler.timesteps ):
__a = scheduler.scale_model_input(_a , _a )
__a = model(_a , _a )
__a = scheduler.step(_a , _a , _a , generator=_a )
__a = output.prev_sample
__a = torch.sum(torch.abs(_a ) )
__a = torch.mean(torch.abs(_a ) )
assert abs(result_sum.item() - 10.0_807 ) < 1e-2
assert abs(result_mean.item() - 0.0_131 ) < 1e-3
def __SCREAMING_SNAKE_CASE ( self ) -> int:
__a = self.scheduler_classes[0]
__a = self.get_scheduler_config(prediction_type='v_prediction' )
__a = scheduler_class(**_a )
scheduler.set_timesteps(self.num_inference_steps )
__a = torch.manual_seed(0 )
__a = self.dummy_model()
__a = self.dummy_sample_deter * scheduler.init_noise_sigma
__a = sample.to(_a )
for i, t in enumerate(scheduler.timesteps ):
__a = scheduler.scale_model_input(_a , _a )
__a = model(_a , _a )
__a = scheduler.step(_a , _a , _a , generator=_a )
__a = output.prev_sample
__a = torch.sum(torch.abs(_a ) )
__a = torch.mean(torch.abs(_a ) )
assert abs(result_sum.item() - 0.0_002 ) < 1e-2
assert abs(result_mean.item() - 2.2676e-06 ) < 1e-3
def __SCREAMING_SNAKE_CASE ( self ) -> Dict:
__a = self.scheduler_classes[0]
__a = self.get_scheduler_config()
__a = scheduler_class(**_a )
scheduler.set_timesteps(self.num_inference_steps , device=_a )
__a = torch.manual_seed(0 )
__a = self.dummy_model()
__a = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu()
__a = sample.to(_a )
for t in scheduler.timesteps:
__a = scheduler.scale_model_input(_a , _a )
__a = model(_a , _a )
__a = scheduler.step(_a , _a , _a , generator=_a )
__a = output.prev_sample
__a = torch.sum(torch.abs(_a ) )
__a = torch.mean(torch.abs(_a ) )
assert abs(result_sum.item() - 10.0_807 ) < 1e-2
assert abs(result_mean.item() - 0.0_131 ) < 1e-3
def __SCREAMING_SNAKE_CASE ( self ) -> List[Any]:
__a = self.scheduler_classes[0]
__a = self.get_scheduler_config()
__a = scheduler_class(**_a , use_karras_sigmas=_a )
scheduler.set_timesteps(self.num_inference_steps , device=_a )
__a = torch.manual_seed(0 )
__a = self.dummy_model()
__a = self.dummy_sample_deter * scheduler.init_noise_sigma.cpu()
__a = sample.to(_a )
for t in scheduler.timesteps:
__a = scheduler.scale_model_input(_a , _a )
__a = model(_a , _a )
__a = scheduler.step(_a , _a , _a , generator=_a )
__a = output.prev_sample
__a = torch.sum(torch.abs(_a ) )
__a = torch.mean(torch.abs(_a ) )
assert abs(result_sum.item() - 124.52_299_499_511_719 ) < 1e-2
assert abs(result_mean.item() - 0.16_213_932_633_399_963 ) < 1e-3
| 712 | def lowerCAmelCase( __lowerCamelCase ):
__a = len(__lowerCamelCase )
while cur > 1:
# Find the maximum number in arr
__a = arr.index(max(arr[0:cur] ) )
# Reverse from 0 to mi
__a = arr[mi::-1] + arr[mi + 1 : len(__lowerCamelCase )]
# Reverse whole list
__a = arr[cur - 1 :: -1] + arr[cur : len(__lowerCamelCase )]
cur -= 1
return arr
if __name__ == "__main__":
lowerCamelCase_ : Optional[Any] = input("""Enter numbers separated by a comma:\n""").strip()
lowerCamelCase_ : Optional[int] = [int(item) for item in user_input.split(""",""")]
print(pancake_sort(unsorted))
| 246 | 0 |
import unittest
from transformers import GPTNeoXJapaneseConfig, is_torch_available
from transformers.models.gpt_neox_japanese.tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer
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 GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseModel
class __UpperCAmelCase :
"""simple docstring"""
def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE=13 , SCREAMING_SNAKE_CASE=7 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=99 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=5 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE="gelu" , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.1 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=512 , SCREAMING_SNAKE_CASE=16 , SCREAMING_SNAKE_CASE=2 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=3 , SCREAMING_SNAKE_CASE=4 , SCREAMING_SNAKE_CASE=None , ) -> 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 = hidden_size
UpperCamelCase = num_hidden_layers
UpperCamelCase = num_attention_heads
UpperCamelCase = intermediate_multiple_size
UpperCamelCase = hidden_act
UpperCamelCase = hidden_dropout
UpperCamelCase = attention_dropout
UpperCamelCase = weight_tying
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 __lowerCAmelCase ( self ) -> Any:
"""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_labels:
UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
UpperCamelCase = self.get_config()
return config, input_ids, input_mask, token_labels
def __lowerCAmelCase ( self ) -> Tuple:
"""simple docstring"""
return GPTNeoXJapaneseConfig(
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_multiple_size=self.intermediate_multiple_size , hidden_act=self.hidden_act , hidden_dropout=self.hidden_dropout , attention_dropout=self.attention_dropout , weight_tying=self.weight_tying , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , )
def __lowerCAmelCase ( self ) -> Union[str, Any]:
"""simple docstring"""
UpperCamelCase = self.prepare_config_and_inputs()
UpperCamelCase = True
return config, input_ids, input_mask, token_labels
def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> List[Any]:
"""simple docstring"""
UpperCamelCase = GPTNeoXJapaneseModel(config=SCREAMING_SNAKE_CASE )
model.to(SCREAMING_SNAKE_CASE )
model.eval()
UpperCamelCase = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE )
UpperCamelCase = model(SCREAMING_SNAKE_CASE )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Union[str, Any]:
"""simple docstring"""
UpperCamelCase = True
UpperCamelCase = GPTNeoXJapaneseModel(SCREAMING_SNAKE_CASE )
model.to(SCREAMING_SNAKE_CASE )
model.eval()
UpperCamelCase = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[Any]:
"""simple docstring"""
UpperCamelCase = GPTNeoXJapaneseForCausalLM(config=SCREAMING_SNAKE_CASE )
model.to(SCREAMING_SNAKE_CASE )
model.eval()
UpperCamelCase = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , labels=SCREAMING_SNAKE_CASE )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[Any]:
"""simple docstring"""
UpperCamelCase = True
UpperCamelCase = GPTNeoXJapaneseForCausalLM(config=SCREAMING_SNAKE_CASE )
model.to(SCREAMING_SNAKE_CASE )
model.eval()
# first forward pass
UpperCamelCase = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , use_cache=SCREAMING_SNAKE_CASE )
UpperCamelCase = outputs.past_key_values
# create hypothetical multiple next token and extent to next_input_ids
UpperCamelCase = ids_tensor((self.batch_size, 3) , config.vocab_size )
UpperCamelCase = ids_tensor((self.batch_size, 3) , vocab_size=2 )
# append to next input_ids and
UpperCamelCase = torch.cat([input_ids, next_tokens] , dim=-1 )
UpperCamelCase = torch.cat([input_mask, next_mask] , dim=-1 )
UpperCamelCase = model(SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE )
UpperCamelCase = output_from_no_past['''hidden_states'''][0]
UpperCamelCase = model(
SCREAMING_SNAKE_CASE , attention_mask=SCREAMING_SNAKE_CASE , past_key_values=SCREAMING_SNAKE_CASE , output_hidden_states=SCREAMING_SNAKE_CASE , )['''hidden_states'''][0]
# select random slice
UpperCamelCase = ids_tensor((1,) , output_from_past.shape[-1] ).item()
UpperCamelCase = output_from_no_past[:, -3:, random_slice_idx].detach()
UpperCamelCase = output_from_past[:, :, random_slice_idx].detach()
self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] )
# test that outputs are equal for slice
self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , atol=1e-3 ) )
def __lowerCAmelCase ( self ) -> Tuple:
"""simple docstring"""
UpperCamelCase = self.prepare_config_and_inputs()
UpperCamelCase = config_and_inputs
UpperCamelCase = {'''input_ids''': input_ids, '''attention_mask''': input_mask}
return config, inputs_dict
@require_torch
class __UpperCAmelCase ( snake_case__ , snake_case__ , unittest.TestCase ):
"""simple docstring"""
lowercase = (GPTNeoXJapaneseModel, GPTNeoXJapaneseForCausalLM) if is_torch_available() else ()
lowercase = (GPTNeoXJapaneseForCausalLM,) if is_torch_available() else ()
lowercase = (
{'''feature-extraction''': GPTNeoXJapaneseModel, '''text-generation''': GPTNeoXJapaneseForCausalLM}
if is_torch_available()
else {}
)
lowercase = False
lowercase = False
lowercase = False
lowercase = False
def __lowerCAmelCase ( self ) -> int:
"""simple docstring"""
UpperCamelCase = GPTNeoXJapaneseModelTester(self )
UpperCamelCase = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE , hidden_size=37 )
def __lowerCAmelCase ( self ) -> Tuple:
"""simple docstring"""
self.config_tester.run_common_tests()
def __lowerCAmelCase ( self ) -> Optional[Any]:
"""simple docstring"""
UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
def __lowerCAmelCase ( self ) -> Any:
"""simple docstring"""
UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_decoder()
self.model_tester.create_and_check_model_as_decoder(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
def __lowerCAmelCase ( self ) -> str:
"""simple docstring"""
UpperCamelCase = self.model_tester.prepare_config_and_inputs_for_decoder()
UpperCamelCase = None
self.model_tester.create_and_check_model_as_decoder(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
def __lowerCAmelCase ( self ) -> List[Any]:
"""simple docstring"""
UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_decoder_model_past_large_inputs(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
def __lowerCAmelCase ( self ) -> Union[str, Any]:
"""simple docstring"""
UpperCamelCase = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_causal_lm(*SCREAMING_SNAKE_CASE )
@slow
def __lowerCAmelCase ( self ) -> Dict:
"""simple docstring"""
UpperCamelCase = '''abeja/gpt-neox-japanese-2.7b'''
UpperCamelCase = ['''データサイエンティストとは、''', '''100年後に必要とされる会社は、''', '''フルリモートの環境で働くために必要なことは、''', '''国境の長いトンネルを抜けると''', '''美味しい日本食といえば、''']
UpperCamelCase = [
'''データサイエンティストとは、データを分析し、ビジネスに役立つ知見を導き出す専門家のことです。''',
'''100年後に必要とされる会社は、「人」が中心の会社です。''',
'''フルリモートの環境で働くために必要なことは、「自分の時間をコントロールする」ことです。''',
'''国境の長いトンネルを抜けると、そこは雪国だった。''',
'''美味しい日本食といえば、やっぱりお寿司ですよね。''',
]
UpperCamelCase = GPTNeoXJapaneseTokenizer.from_pretrained(SCREAMING_SNAKE_CASE )
UpperCamelCase = GPTNeoXJapaneseForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE )
UpperCamelCase = []
for prompt in prompts:
UpperCamelCase = tokenizer(SCREAMING_SNAKE_CASE , return_tensors="pt" ).input_ids
UpperCamelCase = model.generate(SCREAMING_SNAKE_CASE , max_length=50 )
UpperCamelCase = tokenizer.batch_decode(SCREAMING_SNAKE_CASE , skip_special_tokens=SCREAMING_SNAKE_CASE )
predicted_outputs += generated_string
self.assertListEqual(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
| 606 |
'''simple docstring'''
from collections import defaultdict
from math import gcd
def A_ ( __SCREAMING_SNAKE_CASE : int = 1_50_00_00 ) -> int:
__SCREAMING_SNAKE_CASE : defaultdict = defaultdict(__SCREAMING_SNAKE_CASE )
__SCREAMING_SNAKE_CASE : Union[str, Any] = 2
while 2 * euclid_m * (euclid_m + 1) <= limit:
for euclid_n in range((euclid_m % 2) + 1 , __SCREAMING_SNAKE_CASE , 2 ):
if gcd(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) > 1:
continue
__SCREAMING_SNAKE_CASE : Dict = 2 * euclid_m * (euclid_m + euclid_n)
for perimeter in range(__SCREAMING_SNAKE_CASE , limit + 1 , __SCREAMING_SNAKE_CASE ):
frequencies[perimeter] += 1
euclid_m += 1
return sum(1 for frequency in frequencies.values() if frequency == 1 )
if __name__ == "__main__":
print(f'{solution() = }')
| 158 | 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
lowerCamelCase_ : Optional[Any] = '''\
@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}
}
'''
lowerCamelCase_ : List[Any] = '''\
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).
'''
lowerCamelCase_ : Optional[Any] = '''
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}
'''
lowerCamelCase_ : Tuple = '''
################################################################################
!!!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"
################################################################################\
'''
lowerCamelCase_ : List[Any] = '''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 _SCREAMING_SNAKE_CASE ( datasets.Metric ):
'''simple docstring'''
def A ( self : Optional[Any] ) -> Tuple:
'''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 A ( self : List[str] , lowercase : int , lowercase : Any , lowercase : List[Any]=[1, 1_0, 1_0_0] , lowercase : Optional[Any]=4 , lowercase : Optional[Any]=3.0 ) -> str:
'''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=lowercase ) as executor:
UpperCamelCase__ = []
UpperCamelCase__ = Counter()
UpperCamelCase__ = 0
UpperCamelCase__ = defaultdict(lowercase )
for task_id, (candidates, test_case) in enumerate(zip(lowercase , lowercase ) ):
for candidate in candidates:
UpperCamelCase__ = candidate + """\n""" + test_case
UpperCamelCase__ = (test_program, timeout, task_id, completion_id[task_id])
UpperCamelCase__ = executor.submit(lowercase , *lowercase )
futures.append(lowercase )
completion_id[task_id] += 1
n_samples += 1
for future in as_completed(lowercase ):
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(lowercase ) )
correct.append(sum(lowercase ) )
UpperCamelCase__ = np.array(lowercase )
UpperCamelCase__ = np.array(lowercase )
UpperCamelCase__ = k
UpperCamelCase__ = {f"pass@{k}": estimate_pass_at_k(lowercase , lowercase , lowercase ).mean() for k in ks if (total >= k).all()}
return pass_at_k, results
def __magic_name__( _A , _A , _A ):
'''simple docstring'''
def estimator(_A , _A , _A ) -> 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(_A , _A ):
UpperCamelCase__ = itertools.repeat(_A , len(_A ) )
else:
assert len(_A ) == len(_A )
UpperCamelCase__ = iter(_A )
return np.array([estimator(int(_A ) , int(_A ) , _A ) for n, c in zip(_A , _A )] )
| 265 |
'''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.
import torch
from ..models.speechta import SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaProcessor
from ..utils import is_datasets_available
from .base import PipelineTool
if is_datasets_available():
from datasets import load_dataset
class _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE ):
'''simple docstring'''
__a : int = "microsoft/speecht5_tts"
__a : int = (
"This is a tool that reads an English text out loud. It takes an input named `text` which should contain the "
"text to read (in English) and returns a waveform object containing the sound."
)
__a : Optional[Any] = "text_reader"
__a : Tuple = SpeechTaProcessor
__a : int = SpeechTaForTextToSpeech
__a : int = SpeechTaHifiGan
__a : Optional[int] = ["text"]
__a : Union[str, Any] = ["audio"]
def A ( self : str ) -> Optional[int]:
'''simple docstring'''
if self.post_processor is None:
UpperCamelCase__ = """microsoft/speecht5_hifigan"""
super().setup()
def A ( self : List[Any] , lowercase : Any , lowercase : Union[str, Any]=None ) -> Tuple:
'''simple docstring'''
UpperCamelCase__ = self.pre_processor(text=lowercase , return_tensors="""pt""" , truncation=lowercase )
if speaker_embeddings is None:
if not is_datasets_available():
raise ImportError("""Datasets needs to be installed if not passing speaker embeddings.""" )
UpperCamelCase__ = load_dataset("""Matthijs/cmu-arctic-xvectors""" , split="""validation""" )
UpperCamelCase__ = torch.tensor(embeddings_dataset[7_3_0_5]["""xvector"""] ).unsqueeze(0 )
return {"input_ids": inputs["input_ids"], "speaker_embeddings": speaker_embeddings}
def A ( self : Union[str, Any] , lowercase : Optional[int] ) -> int:
'''simple docstring'''
with torch.no_grad():
return self.model.generate_speech(**lowercase )
def A ( self : str , lowercase : Union[str, Any] ) -> Tuple:
'''simple docstring'''
with torch.no_grad():
return self.post_processor(lowercase ).cpu().detach()
| 265 | 1 |
from collections.abc import Sequence
from queue import Queue
class _lowerCAmelCase:
"""simple docstring"""
def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=None , _lowerCamelCase=None ):
UpperCamelCase_: Tuple = start
UpperCamelCase_: Tuple = end
UpperCamelCase_: Optional[Any] = val
UpperCamelCase_: List[str] = (start + end) // 2
UpperCamelCase_: List[str] = left
UpperCamelCase_: List[Any] = right
def __repr__( self ):
return f'''SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})'''
class _lowerCAmelCase:
"""simple docstring"""
def __init__( self , _lowerCamelCase , _lowerCamelCase ):
UpperCamelCase_: str = collection
UpperCamelCase_: Optional[Any] = function
if self.collection:
UpperCamelCase_: str = self._build_tree(0 , len(_lowerCamelCase ) - 1 )
def _a ( self , _lowerCamelCase , _lowerCamelCase ):
self._update_tree(self.root , _lowerCamelCase , _lowerCamelCase )
def _a ( self , _lowerCamelCase , _lowerCamelCase ):
return self._query_range(self.root , _lowerCamelCase , _lowerCamelCase )
def _a ( self , _lowerCamelCase , _lowerCamelCase ):
if start == end:
return SegmentTreeNode(_lowerCamelCase , _lowerCamelCase , self.collection[start] )
UpperCamelCase_: int = (start + end) // 2
UpperCamelCase_: List[str] = self._build_tree(_lowerCamelCase , _lowerCamelCase )
UpperCamelCase_: Any = self._build_tree(mid + 1 , _lowerCamelCase )
return SegmentTreeNode(_lowerCamelCase , _lowerCamelCase , self.fn(left.val , right.val ) , _lowerCamelCase , _lowerCamelCase )
def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ):
if node.start == i and node.end == i:
UpperCamelCase_: List[Any] = val
return
if i <= node.mid:
self._update_tree(node.left , _lowerCamelCase , _lowerCamelCase )
else:
self._update_tree(node.right , _lowerCamelCase , _lowerCamelCase )
UpperCamelCase_: Any = self.fn(node.left.val , node.right.val )
def _a ( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ):
if node.start == i and node.end == j:
return node.val
if i <= node.mid:
if j <= node.mid:
# range in left child tree
return self._query_range(node.left , _lowerCamelCase , _lowerCamelCase )
else:
# range in left child tree and right child tree
return self.fn(
self._query_range(node.left , _lowerCamelCase , node.mid ) , self._query_range(node.right , node.mid + 1 , _lowerCamelCase ) , )
else:
# range in right child tree
return self._query_range(node.right , _lowerCamelCase , _lowerCamelCase )
def _a ( self ):
if self.root is not None:
UpperCamelCase_: Union[str, Any] = Queue()
queue.put(self.root )
while not queue.empty():
UpperCamelCase_: List[str] = queue.get()
yield node
if node.left is not None:
queue.put(node.left )
if node.right is not None:
queue.put(node.right )
if __name__ == "__main__":
import operator
for fn in [operator.add, max, min]:
print('*' * 50)
A_ : List[str] = SegmentTree([2, 1, 5, 3, 4], fn)
for node in arr.traverse():
print(node)
print()
arr.update(1, 5)
for node in arr.traverse():
print(node)
print()
print(arr.query_range(3, 4)) # 7
print(arr.query_range(2, 2)) # 5
print(arr.query_range(1, 3)) # 13
print() | 57 |
import copy
import inspect
import unittest
from transformers import AutoBackbone
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import require_timm, require_torch, torch_device
from transformers.utils.import_utils import is_torch_available
from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor
if is_torch_available():
import torch
from transformers import TimmBackbone, TimmBackboneConfig
from ...test_pipeline_mixin import PipelineTesterMixin
class __a :
def __init__( self : Union[str, Any] , snake_case_ : Dict , snake_case_ : Tuple=None , snake_case_ : List[str]=None , snake_case_ : Union[str, Any]=None , snake_case_ : str="resnet50" , snake_case_ : List[Any]=3 , snake_case_ : Optional[int]=32 , snake_case_ : Union[str, Any]=3 , snake_case_ : Tuple=True , snake_case_ : List[str]=True , )-> Optional[Any]:
__lowerCAmelCase =parent
__lowerCAmelCase =out_indices if out_indices is not None else [4]
__lowerCAmelCase =stage_names
__lowerCAmelCase =out_features
__lowerCAmelCase =backbone
__lowerCAmelCase =batch_size
__lowerCAmelCase =image_size
__lowerCAmelCase =num_channels
__lowerCAmelCase =use_pretrained_backbone
__lowerCAmelCase =is_training
def UpperCamelCase ( self : int)-> Dict:
__lowerCAmelCase =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
__lowerCAmelCase =self.get_config()
return config, pixel_values
def UpperCamelCase ( self : Optional[int])-> Optional[int]:
return TimmBackboneConfig(
image_size=self.image_size , num_channels=self.num_channels , out_features=self.out_features , out_indices=self.out_indices , stage_names=self.stage_names , use_pretrained_backbone=self.use_pretrained_backbone , backbone=self.backbone , )
def UpperCamelCase ( self : str , snake_case_ : int , snake_case_ : Union[str, Any])-> str:
__lowerCAmelCase =TimmBackbone(config=snake_case_)
model.to(snake_case_)
model.eval()
with torch.no_grad():
__lowerCAmelCase =model(snake_case_)
self.parent.assertEqual(
result.feature_map[-1].shape , (self.batch_size, model.channels[-1], 14, 14) , )
def UpperCamelCase ( self : List[str])-> Union[str, Any]:
__lowerCAmelCase =self.prepare_config_and_inputs()
__lowerCAmelCase , __lowerCAmelCase =config_and_inputs
__lowerCAmelCase ={"""pixel_values""": pixel_values}
return config, inputs_dict
@require_torch
@require_timm
class __a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ):
SCREAMING_SNAKE_CASE = (TimmBackbone,) if is_torch_available() else ()
SCREAMING_SNAKE_CASE = {"feature-extraction": TimmBackbone} if is_torch_available() else {}
SCREAMING_SNAKE_CASE = False
SCREAMING_SNAKE_CASE = False
SCREAMING_SNAKE_CASE = False
SCREAMING_SNAKE_CASE = False
def UpperCamelCase ( self : Union[str, Any])-> str:
__lowerCAmelCase =TimmBackboneModelTester(self)
__lowerCAmelCase =ConfigTester(self , config_class=snake_case_ , has_text_modality=snake_case_)
def UpperCamelCase ( self : Tuple)-> Optional[Any]:
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_with_num_labels()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
def UpperCamelCase ( self : Any)-> Dict:
__lowerCAmelCase ="""resnet18"""
__lowerCAmelCase ="""microsoft/resnet-18"""
__lowerCAmelCase =AutoBackbone.from_pretrained(snake_case_ , use_timm_backbone=snake_case_)
__lowerCAmelCase =AutoBackbone.from_pretrained(snake_case_)
self.assertEqual(len(timm_model.out_features) , len(transformers_model.out_features))
self.assertEqual(len(timm_model.stage_names) , len(transformers_model.stage_names))
self.assertEqual(timm_model.channels , transformers_model.channels)
# Out indices are set to the last layer by default. For timm models, we don't know
# the number of layers in advance, so we set it to (-1,), whereas for transformers
# models, we set it to [len(stage_names) - 1] (kept for backward compatibility).
self.assertEqual(timm_model.out_indices , (-1,))
self.assertEqual(transformers_model.out_indices , [len(timm_model.stage_names) - 1])
__lowerCAmelCase =AutoBackbone.from_pretrained(snake_case_ , use_timm_backbone=snake_case_ , out_indices=[1, 2, 3])
__lowerCAmelCase =AutoBackbone.from_pretrained(snake_case_ , out_indices=[1, 2, 3])
self.assertEqual(timm_model.out_indices , transformers_model.out_indices)
self.assertEqual(len(timm_model.out_features) , len(transformers_model.out_features))
self.assertEqual(timm_model.channels , transformers_model.channels)
@unittest.skip("""TimmBackbone doesn't support feed forward chunking""")
def UpperCamelCase ( self : Dict)-> Any:
pass
@unittest.skip("""TimmBackbone doesn't have num_hidden_layers attribute""")
def UpperCamelCase ( self : Tuple)-> Dict:
pass
@unittest.skip("""TimmBackbone initialization is managed on the timm side""")
def UpperCamelCase ( self : Union[str, Any])-> List[str]:
pass
@unittest.skip("""TimmBackbone models doesn't have inputs_embeds""")
def UpperCamelCase ( self : List[str])-> List[str]:
pass
@unittest.skip("""TimmBackbone models doesn't have inputs_embeds""")
def UpperCamelCase ( self : int)-> int:
pass
@unittest.skip("""TimmBackbone model cannot be created without specifying a backbone checkpoint""")
def UpperCamelCase ( self : Dict)-> int:
pass
@unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone""")
def UpperCamelCase ( self : Any)-> Dict:
pass
@unittest.skip("""model weights aren't tied in TimmBackbone.""")
def UpperCamelCase ( self : int)-> Tuple:
pass
@unittest.skip("""model weights aren't tied in TimmBackbone.""")
def UpperCamelCase ( self : Optional[int])-> Union[str, Any]:
pass
@unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone""")
def UpperCamelCase ( self : Optional[Any])-> Optional[Any]:
pass
@unittest.skip("""Only checkpoints on timm can be loaded into TimmBackbone""")
def UpperCamelCase ( self : Any)-> List[Any]:
pass
@unittest.skip("""TimmBackbone doesn't have hidden size info in its configuration.""")
def UpperCamelCase ( self : Any)-> Tuple:
pass
@unittest.skip("""TimmBackbone doesn't support output_attentions.""")
def UpperCamelCase ( self : List[Any])-> str:
pass
@unittest.skip("""Safetensors is not supported by timm.""")
def UpperCamelCase ( self : Dict)-> Optional[int]:
pass
@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""")
def UpperCamelCase ( self : Optional[int])-> Tuple:
pass
def UpperCamelCase ( self : int)-> Union[str, Any]:
__lowerCAmelCase , __lowerCAmelCase =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__lowerCAmelCase =model_class(snake_case_)
__lowerCAmelCase =inspect.signature(model.forward)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__lowerCAmelCase =[*signature.parameters.keys()]
__lowerCAmelCase =["""pixel_values"""]
self.assertListEqual(arg_names[:1] , snake_case_)
def UpperCamelCase ( self : Dict)-> Optional[Any]:
__lowerCAmelCase , __lowerCAmelCase =self.model_tester.prepare_config_and_inputs_for_common()
__lowerCAmelCase =True
__lowerCAmelCase =self.has_attentions
# no need to test all models as different heads yield the same functionality
__lowerCAmelCase =self.all_model_classes[0]
__lowerCAmelCase =model_class(snake_case_)
model.to(snake_case_)
__lowerCAmelCase =self._prepare_for_class(snake_case_ , snake_case_)
__lowerCAmelCase =model(**snake_case_)
__lowerCAmelCase =outputs[0][-1]
# Encoder-/Decoder-only models
__lowerCAmelCase =outputs.hidden_states[0]
hidden_states.retain_grad()
if self.has_attentions:
__lowerCAmelCase =outputs.attentions[0]
attentions.retain_grad()
output.flatten()[0].backward(retain_graph=snake_case_)
self.assertIsNotNone(hidden_states.grad)
if self.has_attentions:
self.assertIsNotNone(attentions.grad)
def UpperCamelCase ( self : Tuple)-> List[Any]:
__lowerCAmelCase , __lowerCAmelCase =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__lowerCAmelCase =model_class(snake_case_)
model.to(snake_case_)
model.eval()
__lowerCAmelCase =model(**snake_case_)
self.assertEqual(len(result.feature_maps) , len(config.out_indices))
self.assertEqual(len(model.channels) , len(config.out_indices))
# Check output of last stage is taken if out_features=None, out_indices=None
__lowerCAmelCase =copy.deepcopy(snake_case_)
__lowerCAmelCase =None
__lowerCAmelCase =model_class(snake_case_)
model.to(snake_case_)
model.eval()
__lowerCAmelCase =model(**snake_case_)
self.assertEqual(len(result.feature_maps) , 1)
self.assertEqual(len(model.channels) , 1)
# Check backbone can be initialized with fresh weights
__lowerCAmelCase =copy.deepcopy(snake_case_)
__lowerCAmelCase =False
__lowerCAmelCase =model_class(snake_case_)
model.to(snake_case_)
model.eval()
__lowerCAmelCase =model(**snake_case_)
| 354 | 0 |
"""simple docstring"""
from transformers import HfArgumentParser, TensorFlowBenchmark, TensorFlowBenchmarkArguments
def snake_case ():
'''simple docstring'''
a : List[str] = HfArgumentParser(A_ )
a : str = parser.parse_args_into_dataclasses()[0]
a : Dict = TensorFlowBenchmark(args=A_ )
try:
a : List[str] = parser.parse_args_into_dataclasses()[0]
except ValueError as e:
a : Optional[int] = 'Arg --no_{0} is no longer used, please use --no-{0} instead.'
a : Union[str, Any] = ' '.join(str(A_ ).split(' ' )[:-1] )
a : Any = ''
a : Tuple = eval(str(A_ ).split(' ' )[-1] )
a : List[str] = []
for arg in depreciated_args:
# arg[2:] removes '--'
if arg[2:] in TensorFlowBenchmark.deprecated_args:
# arg[5:] removes '--no_'
full_error_msg += arg_error_msg.format(arg[5:] )
else:
wrong_args.append(A_ )
if len(A_ ) > 0:
a : Dict = full_error_msg + begin_error_msg + str(A_ )
raise ValueError(A_ )
benchmark.run()
if __name__ == "__main__":
main()
| 118 |
"""simple docstring"""
import os
def snake_case ():
'''simple docstring'''
a : str = os.path.join(os.path.dirname(A_ ) , 'num.txt' )
with open(A_ ) as file_hand:
return str(sum(int(A_ ) for line in file_hand ) )[:1_0]
if __name__ == "__main__":
print(solution())
| 118 | 1 |
'''simple docstring'''
import socket
def lowerCAmelCase__ ( ):
__a : int = socket.socket(socket.AF_INET , socket.SOCK_STREAM )
__a : Tuple = socket.gethostname()
__a : Union[str, Any] = 12312
sock.connect((host, port) )
sock.send(B'Hello server!' )
with open('Received_file' , 'wb' ) as out_file:
print('File opened' )
print('Receiving data...' )
while True:
__a : str = sock.recv(1024 )
if not data:
break
out_file.write(SCREAMING_SNAKE_CASE__ )
print('Successfully received the file' )
sock.close()
print('Connection closed' )
if __name__ == "__main__":
main()
| 597 |
'''simple docstring'''
import unittest
from transformers import GPTNeoXJapaneseConfig, is_torch_available
from transformers.models.gpt_neox_japanese.tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer
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 GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseModel
class lowerCAmelCase :
"""simple docstring"""
def __init__( self , _A , _A=13 , _A=7 , _A=True , _A=True , _A=True , _A=True , _A=99 , _A=32 , _A=5 , _A=4 , _A=4 , _A="gelu" , _A=0.0 , _A=0.1 , _A=True , _A=512 , _A=16 , _A=2 , _A=0.02 , _A=3 , _A=4 , _A=None , ) -> List[Any]:
__a : Dict = parent
__a : str = batch_size
__a : Any = seq_length
__a : int = is_training
__a : List[Any] = use_input_mask
__a : List[Any] = use_token_type_ids
__a : Optional[Any] = use_labels
__a : Tuple = vocab_size
__a : List[str] = hidden_size
__a : Optional[int] = num_hidden_layers
__a : int = num_attention_heads
__a : str = intermediate_multiple_size
__a : Tuple = hidden_act
__a : str = hidden_dropout
__a : Tuple = attention_dropout
__a : str = weight_tying
__a : Any = max_position_embeddings
__a : Optional[int] = type_vocab_size
__a : Optional[int] = type_sequence_label_size
__a : List[Any] = initializer_range
__a : List[Any] = num_labels
__a : Dict = num_choices
__a : List[Any] = scope
def __magic_name__ ( self ) -> Any:
__a : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__a : str = None
if self.use_input_mask:
__a : List[str] = random_attention_mask([self.batch_size, self.seq_length] )
__a : str = None
if self.use_labels:
__a : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
__a : List[Any] = self.get_config()
return config, input_ids, input_mask, token_labels
def __magic_name__ ( self ) -> List[str]:
return GPTNeoXJapaneseConfig(
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_multiple_size=self.intermediate_multiple_size , hidden_act=self.hidden_act , hidden_dropout=self.hidden_dropout , attention_dropout=self.attention_dropout , weight_tying=self.weight_tying , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_A , initializer_range=self.initializer_range , )
def __magic_name__ ( self ) -> Dict:
__a , __a , __a , __a : Any = self.prepare_config_and_inputs()
__a : List[Any] = True
return config, input_ids, input_mask, token_labels
def __magic_name__ ( self , _A , _A , _A ) -> Optional[int]:
__a : str = GPTNeoXJapaneseModel(config=_A )
model.to(_A )
model.eval()
__a : Optional[Any] = model(_A , attention_mask=_A )
__a : Any = model(_A )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def __magic_name__ ( self , _A , _A , _A ) -> List[str]:
__a : int = True
__a : Union[str, Any] = GPTNeoXJapaneseModel(_A )
model.to(_A )
model.eval()
__a : Optional[int] = model(_A , attention_mask=_A )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def __magic_name__ ( self , _A , _A , _A , _A ) -> List[Any]:
__a : Optional[Any] = GPTNeoXJapaneseForCausalLM(config=_A )
model.to(_A )
model.eval()
__a : Tuple = model(_A , attention_mask=_A , labels=_A )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def __magic_name__ ( self , _A , _A , _A ) -> Tuple:
__a : str = True
__a : Optional[Any] = GPTNeoXJapaneseForCausalLM(config=_A )
model.to(_A )
model.eval()
# first forward pass
__a : int = model(_A , attention_mask=_A , use_cache=_A )
__a : int = outputs.past_key_values
# create hypothetical multiple next token and extent to next_input_ids
__a : Dict = ids_tensor((self.batch_size, 3) , config.vocab_size )
__a : str = ids_tensor((self.batch_size, 3) , vocab_size=2 )
# append to next input_ids and
__a : Tuple = torch.cat([input_ids, next_tokens] , dim=-1 )
__a : List[str] = torch.cat([input_mask, next_mask] , dim=-1 )
__a : Tuple = model(_A , attention_mask=_A , output_hidden_states=_A )
__a : Optional[int] = output_from_no_past['hidden_states'][0]
__a : Optional[int] = model(
_A , attention_mask=_A , past_key_values=_A , output_hidden_states=_A , )['hidden_states'][0]
# select random slice
__a : Union[str, Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item()
__a : str = output_from_no_past[:, -3:, random_slice_idx].detach()
__a : str = output_from_past[:, :, random_slice_idx].detach()
self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] )
# test that outputs are equal for slice
self.parent.assertTrue(torch.allclose(_A , _A , atol=1E-3 ) )
def __magic_name__ ( self ) -> Any:
__a : int = self.prepare_config_and_inputs()
__a , __a , __a , __a : Dict = config_and_inputs
__a : int = {'input_ids': input_ids, 'attention_mask': input_mask}
return config, inputs_dict
@require_torch
class lowerCAmelCase ( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ):
"""simple docstring"""
_A = (GPTNeoXJapaneseModel, GPTNeoXJapaneseForCausalLM) if is_torch_available() else ()
_A = (GPTNeoXJapaneseForCausalLM,) if is_torch_available() else ()
_A = (
{'feature-extraction': GPTNeoXJapaneseModel, 'text-generation': GPTNeoXJapaneseForCausalLM}
if is_torch_available()
else {}
)
_A = False
_A = False
_A = False
_A = False
def __magic_name__ ( self ) -> Optional[int]:
__a : Union[str, Any] = GPTNeoXJapaneseModelTester(self )
__a : List[str] = ConfigTester(self , config_class=_A , hidden_size=37 )
def __magic_name__ ( self ) -> Tuple:
self.config_tester.run_common_tests()
def __magic_name__ ( self ) -> Dict:
__a , __a , __a , __a : Union[str, Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(_A , _A , _A )
def __magic_name__ ( self ) -> Tuple:
__a , __a , __a , __a : Dict = self.model_tester.prepare_config_and_inputs_for_decoder()
self.model_tester.create_and_check_model_as_decoder(_A , _A , _A )
def __magic_name__ ( self ) -> Any:
# This regression test was failing with PyTorch < 1.3
__a , __a , __a , __a : str = self.model_tester.prepare_config_and_inputs_for_decoder()
__a : Union[str, Any] = None
self.model_tester.create_and_check_model_as_decoder(_A , _A , _A )
def __magic_name__ ( self ) -> Tuple:
__a , __a , __a , __a : Optional[int] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_decoder_model_past_large_inputs(_A , _A , _A )
def __magic_name__ ( self ) -> str:
__a : List[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_causal_lm(*_A )
@slow
def __magic_name__ ( self ) -> List[str]:
__a : Any = 'abeja/gpt-neox-japanese-2.7b'
__a : List[str] = ['データサイエンティストとは、', '100年後に必要とされる会社は、', 'フルリモートの環境で働くために必要なことは、', '国境の長いトンネルを抜けると', '美味しい日本食といえば、']
__a : Union[str, Any] = [
'データサイエンティストとは、データを分析し、ビジネスに役立つ知見を導き出す専門家のことです。',
'100年後に必要とされる会社は、「人」が中心の会社です。',
'フルリモートの環境で働くために必要なことは、「自分の時間をコントロールする」ことです。',
'国境の長いトンネルを抜けると、そこは雪国だった。',
'美味しい日本食といえば、やっぱりお寿司ですよね。',
]
__a : List[str] = GPTNeoXJapaneseTokenizer.from_pretrained(_A )
__a : Optional[int] = GPTNeoXJapaneseForCausalLM.from_pretrained(_A )
__a : Any = []
for prompt in prompts:
__a : Tuple = tokenizer(_A , return_tensors='pt' ).input_ids
__a : Optional[Any] = model.generate(_A , max_length=50 )
__a : Optional[Any] = tokenizer.batch_decode(_A , skip_special_tokens=_A )
predicted_outputs += generated_string
self.assertListEqual(_A , _A )
| 597 | 1 |
'''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 : int = logging.get_logger(__name__)
a : Optional[int] = {
'artists_file': 'artists.json',
'lyrics_file': 'lyrics.json',
'genres_file': 'genres.json',
}
a : str = {
'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 : List[Any] = {
'jukebox': 512,
}
class SCREAMING_SNAKE_CASE__ ( snake_case__ ):
__SCREAMING_SNAKE_CASE = VOCAB_FILES_NAMES
__SCREAMING_SNAKE_CASE = PRETRAINED_VOCAB_FILES_MAP
__SCREAMING_SNAKE_CASE = PRETRAINED_LYRIC_TOKENS_SIZES
__SCREAMING_SNAKE_CASE = ["""input_ids""", """attention_mask"""]
def __init__( self : Optional[Any] , a_ : Dict , a_ : Optional[Any] , a_ : str , a_ : Optional[Any]=["v3", "v2", "v2"] , a_ : Union[str, Any]=512 , a_ : Dict=5 , a_ : List[str]="<|endoftext|>" , **a_ : List[str] , ):
"""simple docstring"""
__snake_case = AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else unk_token
super().__init__(
unk_token=UpperCAmelCase_ , n_genres=UpperCAmelCase_ , version=UpperCAmelCase_ , max_n_lyric_tokens=UpperCAmelCase_ , **UpperCAmelCase_ , )
__snake_case = version
__snake_case = max_n_lyric_tokens
__snake_case = n_genres
with open(UpperCAmelCase_ , encoding="utf-8" ) as vocab_handle:
__snake_case = json.load(UpperCAmelCase_ )
with open(UpperCAmelCase_ , encoding="utf-8" ) as vocab_handle:
__snake_case = json.load(UpperCAmelCase_ )
with open(UpperCAmelCase_ , encoding="utf-8" ) as vocab_handle:
__snake_case = json.load(UpperCAmelCase_ )
__snake_case = 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:
__snake_case = oov.replace(r"\-'" , r"\-+'" )
__snake_case = regex.compile(UpperCAmelCase_ )
__snake_case = {v: k for k, v in self.artists_encoder.items()}
__snake_case = {v: k for k, v in self.genres_encoder.items()}
__snake_case = {v: k for k, v in self.lyrics_encoder.items()}
@property
def A ( self : Union[str, Any] ):
"""simple docstring"""
return len(self.artists_encoder ) + len(self.genres_encoder ) + len(self.lyrics_encoder )
def A ( self : Tuple ):
"""simple docstring"""
return dict(self.artists_encoder , self.genres_encoder , self.lyrics_encoder )
def A ( self : Dict , a_ : Tuple , a_ : str , a_ : List[str] ):
"""simple docstring"""
__snake_case = [self.artists_encoder.get(UpperCAmelCase_ , 0 ) for artist in list_artists]
for genres in range(len(UpperCAmelCase_ ) ):
__snake_case = [self.genres_encoder.get(UpperCAmelCase_ , 0 ) for genre in list_genres[genres]]
__snake_case = list_genres[genres] + [-1] * (self.n_genres - len(list_genres[genres] ))
__snake_case = [[self.lyrics_encoder.get(UpperCAmelCase_ , 0 ) for character in list_lyrics[0]], [], []]
return artists_id, list_genres, lyric_ids
def A ( self : Dict , a_ : List[str] ):
"""simple docstring"""
return list(UpperCAmelCase_ )
def A ( self : List[str] , a_ : str , a_ : int , a_ : List[Any] , **a_ : Optional[Any] ):
"""simple docstring"""
__snake_case , __snake_case , __snake_case = self.prepare_for_tokenization(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )
__snake_case = self._tokenize(UpperCAmelCase_ )
return artist, genre, lyrics
def A ( self : List[str] , a_ : str , a_ : str , a_ : str , a_ : bool = False ):
"""simple docstring"""
for idx in range(len(self.version ) ):
if self.version[idx] == "v3":
__snake_case = artists[idx].lower()
__snake_case = [genres[idx].lower()]
else:
__snake_case = self._normalize(artists[idx] ) + ".v2"
__snake_case = [
self._normalize(UpperCAmelCase_ ) + ".v2" for genre in genres[idx].split("_" )
] # split is for the full dictionary with combined genres
if self.version[0] == "v2":
__snake_case = regex.compile(r"[^A-Za-z0-9.,:;!?\-'\"()\[\] \t\n]+" )
__snake_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-+'\"()[] \t\n"
__snake_case = {vocab[index]: index + 1 for index in range(len(UpperCAmelCase_ ) )}
__snake_case = 0
__snake_case = len(UpperCAmelCase_ ) + 1
__snake_case = self.vocab
__snake_case = {v: k for k, v in self.vocab.items()}
__snake_case = ""
else:
__snake_case = regex.compile(r"[^A-Za-z0-9.,:;!?\-+'\"()\[\] \t\n]+" )
__snake_case = self._run_strip_accents(UpperCAmelCase_ )
__snake_case = lyrics.replace("\\" , "\n" )
__snake_case = self.out_of_vocab.sub("" , UpperCAmelCase_ ), [], []
return artists, genres, lyrics
def A ( self : Tuple , a_ : List[str] ):
"""simple docstring"""
__snake_case = unicodedata.normalize("NFD" , UpperCAmelCase_ )
__snake_case = []
for char in text:
__snake_case = unicodedata.category(UpperCAmelCase_ )
if cat == "Mn":
continue
output.append(UpperCAmelCase_ )
return "".join(UpperCAmelCase_ )
def A ( self : List[Any] , a_ : str ):
"""simple docstring"""
__snake_case = (
[chr(UpperCAmelCase_ ) for i in range(ord("a" ) , ord("z" ) + 1 )]
+ [chr(UpperCAmelCase_ ) for i in range(ord("A" ) , ord("Z" ) + 1 )]
+ [chr(UpperCAmelCase_ ) for i in range(ord("0" ) , ord("9" ) + 1 )]
+ ["."]
)
__snake_case = frozenset(UpperCAmelCase_ )
__snake_case = re.compile(r"_+" )
__snake_case = "".join([c if c in accepted else "_" for c in text.lower()] )
__snake_case = pattern.sub("_" , UpperCAmelCase_ ).strip("_" )
return text
def A ( self : List[Any] , a_ : List[str] ):
"""simple docstring"""
return " ".join(UpperCAmelCase_ )
def A ( self : Tuple , a_ : str , a_ : Optional[Union[str, TensorType]] = None , a_ : bool = False ):
"""simple docstring"""
if not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ):
__snake_case = TensorType(UpperCAmelCase_ )
# 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
__snake_case = tf.constant
__snake_case = 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
__snake_case = torch.tensor
__snake_case = 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
__snake_case = jnp.array
__snake_case = _is_jax
else:
__snake_case = np.asarray
__snake_case = _is_numpy
# Do the tensor conversion in batch
try:
if prepend_batch_axis:
__snake_case = [inputs]
if not is_tensor(UpperCAmelCase_ ):
__snake_case = as_tensor(UpperCAmelCase_ )
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 : Any , a_ : List[str] , a_ : List[str] , a_ : List[Any]="" , a_ : List[Any]="pt" ):
"""simple docstring"""
__snake_case = [0, 0, 0]
__snake_case = [artist] * len(self.version )
__snake_case = [genres] * len(self.version )
__snake_case , __snake_case , __snake_case = self.tokenize(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )
__snake_case , __snake_case , __snake_case = self._convert_token_to_id(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )
__snake_case = [-INFINITY] * len(full_tokens[-1] )
__snake_case = [
self.convert_to_tensors(
[input_ids + [artists_id[i]] + genres_ids[i] + full_tokens[i]] , tensor_type=UpperCAmelCase_ )
for i in range(len(self.version ) )
]
return BatchEncoding({"input_ids": input_ids, "attention_masks": attention_masks} )
def A ( self : Optional[Any] , a_ : str , a_ : Optional[str] = None ):
"""simple docstring"""
if not os.path.isdir(UpperCAmelCase_ ):
logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' )
return
__snake_case = os.path.join(
UpperCAmelCase_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["artists_file"] )
with open(UpperCAmelCase_ , "w" , encoding="utf-8" ) as f:
f.write(json.dumps(self.artists_encoder , ensure_ascii=UpperCAmelCase_ ) )
__snake_case = os.path.join(
UpperCAmelCase_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["genres_file"] )
with open(UpperCAmelCase_ , "w" , encoding="utf-8" ) as f:
f.write(json.dumps(self.genres_encoder , ensure_ascii=UpperCAmelCase_ ) )
__snake_case = os.path.join(
UpperCAmelCase_ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["lyrics_file"] )
with open(UpperCAmelCase_ , "w" , encoding="utf-8" ) as f:
f.write(json.dumps(self.lyrics_encoder , ensure_ascii=UpperCAmelCase_ ) )
return (artists_file, genres_file, lyrics_file)
def A ( self : Union[str, Any] , a_ : List[str] , a_ : Dict , a_ : List[Any] ):
"""simple docstring"""
__snake_case = self.artists_decoder.get(UpperCAmelCase_ )
__snake_case = [self.genres_decoder.get(UpperCAmelCase_ ) for genre in genres_index]
__snake_case = [self.lyrics_decoder.get(UpperCAmelCase_ ) for character in lyric_index]
return artist, genres, lyrics
| 702 |
'''simple docstring'''
import os
import torch
from ..logging import get_logger
from .constants import FSDP_PYTORCH_VERSION, MODEL_NAME, OPTIMIZER_NAME
from .versions import is_torch_version
if is_torch_version('''>=''', FSDP_PYTORCH_VERSION):
import torch.distributed.checkpoint as dist_cp
from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner, DefaultSavePlanner
from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict
from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP
from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType
a : Any = get_logger(__name__)
def __UpperCAmelCase ( _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : str , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : int , _UpperCAmelCase : Union[str, Any]=0 ) -> Any:
os.makedirs(_UpperCAmelCase , exist_ok=_UpperCAmelCase )
with FSDP.state_dict_type(
_UpperCAmelCase , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ):
__snake_case = model.state_dict()
if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
__snake_case = F'''{MODEL_NAME}.bin''' if model_index == 0 else F'''{MODEL_NAME}_{model_index}.bin'''
__snake_case = os.path.join(_UpperCAmelCase , _UpperCAmelCase )
if accelerator.process_index == 0:
logger.info(F'''Saving model to {output_model_file}''' )
torch.save(_UpperCAmelCase , _UpperCAmelCase )
logger.info(F'''Model saved to {output_model_file}''' )
elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
__snake_case = (
F'''{MODEL_NAME}_rank{accelerator.process_index}.bin'''
if model_index == 0
else F'''{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin'''
)
__snake_case = os.path.join(_UpperCAmelCase , _UpperCAmelCase )
logger.info(F'''Saving model to {output_model_file}''' )
torch.save(_UpperCAmelCase , _UpperCAmelCase )
logger.info(F'''Model saved to {output_model_file}''' )
elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT:
__snake_case = os.path.join(_UpperCAmelCase , F'''{MODEL_NAME}_{model_index}''' )
os.makedirs(_UpperCAmelCase , exist_ok=_UpperCAmelCase )
logger.info(F'''Saving model to {ckpt_dir}''' )
__snake_case = {"model": state_dict}
dist_cp.save_state_dict(
state_dict=_UpperCAmelCase , storage_writer=dist_cp.FileSystemWriter(_UpperCAmelCase ) , planner=DefaultSavePlanner() , )
logger.info(F'''Model saved to {ckpt_dir}''' )
def __UpperCAmelCase ( _UpperCAmelCase : int , _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : str , _UpperCAmelCase : Tuple , _UpperCAmelCase : str=0 ) -> List[str]:
accelerator.wait_for_everyone()
with FSDP.state_dict_type(
_UpperCAmelCase , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ):
if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
if type(_UpperCAmelCase ) != FSDP and accelerator.process_index != 0:
if not fsdp_plugin.sync_module_states:
raise ValueError(
"Set the `sync_module_states` flag to `True` so that model states are synced across processes when "
"initializing FSDP object" )
return
__snake_case = F'''{MODEL_NAME}.bin''' if model_index == 0 else F'''{MODEL_NAME}_{model_index}.bin'''
__snake_case = os.path.join(_UpperCAmelCase , _UpperCAmelCase )
logger.info(F'''Loading model from {input_model_file}''' )
__snake_case = torch.load(_UpperCAmelCase )
logger.info(F'''Model loaded from {input_model_file}''' )
elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT:
__snake_case = (
F'''{MODEL_NAME}_rank{accelerator.process_index}.bin'''
if model_index == 0
else F'''{MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin'''
)
__snake_case = os.path.join(_UpperCAmelCase , _UpperCAmelCase )
logger.info(F'''Loading model from {input_model_file}''' )
__snake_case = torch.load(_UpperCAmelCase )
logger.info(F'''Model loaded from {input_model_file}''' )
elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT:
__snake_case = (
os.path.join(_UpperCAmelCase , F'''{MODEL_NAME}_{model_index}''' )
if F'''{MODEL_NAME}''' not in input_dir
else input_dir
)
logger.info(F'''Loading model from {ckpt_dir}''' )
__snake_case = {"model": model.state_dict()}
dist_cp.load_state_dict(
state_dict=_UpperCAmelCase , storage_reader=dist_cp.FileSystemReader(_UpperCAmelCase ) , planner=DefaultLoadPlanner() , )
__snake_case = state_dict["model"]
logger.info(F'''Model loaded from {ckpt_dir}''' )
model.load_state_dict(_UpperCAmelCase )
def __UpperCAmelCase ( _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Dict , _UpperCAmelCase : str , _UpperCAmelCase : int , _UpperCAmelCase : Optional[int] , _UpperCAmelCase : Tuple=0 ) -> Union[str, Any]:
os.makedirs(_UpperCAmelCase , exist_ok=_UpperCAmelCase )
with FSDP.state_dict_type(
_UpperCAmelCase , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ):
__snake_case = FSDP.optim_state_dict(_UpperCAmelCase , _UpperCAmelCase )
if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
if accelerator.process_index == 0:
__snake_case = (
F'''{OPTIMIZER_NAME}.bin''' if optimizer_index == 0 else F'''{OPTIMIZER_NAME}_{optimizer_index}.bin'''
)
__snake_case = os.path.join(_UpperCAmelCase , _UpperCAmelCase )
logger.info(F'''Saving Optimizer state to {output_optimizer_file}''' )
torch.save(_UpperCAmelCase , _UpperCAmelCase )
logger.info(F'''Optimizer state saved in {output_optimizer_file}''' )
else:
__snake_case = os.path.join(_UpperCAmelCase , F'''{OPTIMIZER_NAME}_{optimizer_index}''' )
os.makedirs(_UpperCAmelCase , exist_ok=_UpperCAmelCase )
logger.info(F'''Saving Optimizer state to {ckpt_dir}''' )
dist_cp.save_state_dict(
state_dict={"optimizer": optim_state} , storage_writer=dist_cp.FileSystemWriter(_UpperCAmelCase ) , planner=DefaultSavePlanner() , )
logger.info(F'''Optimizer state saved in {ckpt_dir}''' )
def __UpperCAmelCase ( _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : Tuple , _UpperCAmelCase : Optional[int] , _UpperCAmelCase : Optional[Any] , _UpperCAmelCase : Optional[int]=0 ) -> Union[str, Any]:
accelerator.wait_for_everyone()
with FSDP.state_dict_type(
_UpperCAmelCase , fsdp_plugin.state_dict_type , fsdp_plugin.state_dict_config , fsdp_plugin.optim_state_dict_config ):
if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT:
__snake_case = None
# below check should work but currently it isn't working (mostly opytorch issue),
# in the meantime disabling it at the cost of excess memory usage
# if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only:
__snake_case = (
F'''{OPTIMIZER_NAME}.bin''' if optimizer_index == 0 else F'''{OPTIMIZER_NAME}_{optimizer_index}.bin'''
)
__snake_case = os.path.join(_UpperCAmelCase , _UpperCAmelCase )
logger.info(F'''Loading Optimizer state from {input_optimizer_file}''' )
__snake_case = torch.load(_UpperCAmelCase )
logger.info(F'''Optimizer state loaded from {input_optimizer_file}''' )
else:
__snake_case = (
os.path.join(_UpperCAmelCase , F'''{OPTIMIZER_NAME}_{optimizer_index}''' )
if F'''{OPTIMIZER_NAME}''' not in input_dir
else input_dir
)
logger.info(F'''Loading Optimizer from {ckpt_dir}''' )
__snake_case = load_sharded_optimizer_state_dict(
model_state_dict=model.state_dict() , optimizer_key="optimizer" , storage_reader=dist_cp.FileSystemReader(_UpperCAmelCase ) , )
__snake_case = optim_state["optimizer"]
logger.info(F'''Optimizer loaded from {ckpt_dir}''' )
__snake_case = FSDP.optim_state_dict_to_load(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase )
optimizer.load_state_dict(_UpperCAmelCase )
| 680 | 0 |
import argparse
import ast
import logging
import os
import sys
import pandas as pd
import torch
from tqdm import tqdm
from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration
from transformers import logging as transformers_logging
sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # isort:skip
from utils_rag import exact_match_score, fa_score # noqa: E402 # isort:skip
lowerCamelCase : int = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
transformers_logging.set_verbosity_info()
def snake_case_ ( lowerCAmelCase_ : Union[str, Any] ):
if "token" in model_name_or_path:
return "rag_token"
if "sequence" in model_name_or_path:
return "rag_sequence"
if "bart" in model_name_or_path:
return "bart"
return None
def snake_case_ ( lowerCAmelCase_ : str , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Tuple ):
return max(metric_fn(lowerCAmelCase_ , lowerCAmelCase_ ) for gt in ground_truths )
def snake_case_ ( lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : List[str] ):
__lowercase : List[str] = [line.strip() for line in open(lowerCAmelCase_ , """r""" ).readlines()]
__lowercase : Any = []
if args.gold_data_mode == "qa":
__lowercase : List[str] = pd.read_csv(lowerCAmelCase_ , sep="""\t""" , header=lowerCAmelCase_ )
for answer_list in data[1]:
__lowercase : List[str] = ast.literal_eval(lowerCAmelCase_ )
answers.append(lowerCAmelCase_ )
else:
__lowercase : List[Any] = [line.strip() for line in open(lowerCAmelCase_ , """r""" ).readlines()]
__lowercase : str = [[reference] for reference in references]
__lowercase : Union[str, Any] = 0
for prediction, ground_truths in zip(lowerCAmelCase_ , lowerCAmelCase_ ):
total += 1
em += metric_max_over_ground_truths(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
fa += metric_max_over_ground_truths(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
__lowercase : Tuple = 100.0 * em / total
__lowercase : List[Any] = 100.0 * fa / total
logger.info(F"F1: {fa:.2f}" )
logger.info(F"EM: {em:.2f}" )
def snake_case_ ( lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : str , lowerCAmelCase_ : Any ):
__lowercase : Dict = args.k
__lowercase : Optional[int] = [line.strip() for line in open(lowerCAmelCase_ , """r""" ).readlines()]
__lowercase : Optional[int] = [line.strip() for line in open(lowerCAmelCase_ , """r""" ).readlines()]
__lowercase : Dict = 0
for hypo, reference in zip(lowerCAmelCase_ , lowerCAmelCase_ ):
__lowercase : List[Any] = set(hypo.split("""\t""" )[:k] )
__lowercase : int = set(reference.split("""\t""" ) )
total += 1
em += len(hypo_provenance & ref_provenance ) / k
__lowercase : List[str] = 100.0 * em / total
logger.info(F"Precision@{k}: {em: .2f}" )
def snake_case_ ( lowerCAmelCase_ : str , lowerCAmelCase_ : Any , lowerCAmelCase_ : Tuple ):
def strip_title(lowerCAmelCase_ : List[str] ):
if title.startswith("""\"""" ):
__lowercase : str = title[1:]
if title.endswith("""\"""" ):
__lowercase : int = title[:-1]
return title
__lowercase : Union[str, Any] = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus(
lowerCAmelCase_ , return_tensors="""pt""" , padding=lowerCAmelCase_ , truncation=lowerCAmelCase_ , )["""input_ids"""].to(args.device )
__lowercase : List[str] = rag_model.rag.question_encoder(lowerCAmelCase_ )
__lowercase : List[str] = question_enc_outputs[0]
__lowercase : Tuple = rag_model.retriever(
lowerCAmelCase_ , question_enc_pool_output.cpu().detach().to(torch.floataa ).numpy() , prefix=rag_model.rag.generator.config.prefix , n_docs=rag_model.config.n_docs , return_tensors="""pt""" , )
__lowercase : int = rag_model.retriever.index.get_doc_dicts(result.doc_ids )
__lowercase : str = []
for docs in all_docs:
__lowercase : Tuple = [strip_title(lowerCAmelCase_ ) for title in docs["""title"""]]
provenance_strings.append("""\t""".join(lowerCAmelCase_ ) )
return provenance_strings
def snake_case_ ( lowerCAmelCase_ : List[str] , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Optional[Any] ):
with torch.no_grad():
__lowercase : Union[str, Any] = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus(
lowerCAmelCase_ , return_tensors="""pt""" , padding=lowerCAmelCase_ , truncation=lowerCAmelCase_ )
__lowercase : str = inputs_dict.input_ids.to(args.device )
__lowercase : Union[str, Any] = inputs_dict.attention_mask.to(args.device )
__lowercase : str = rag_model.generate( # rag_model overwrites generate
lowerCAmelCase_ , attention_mask=lowerCAmelCase_ , num_beams=args.num_beams , min_length=args.min_length , max_length=args.max_length , early_stopping=lowerCAmelCase_ , num_return_sequences=1 , bad_words_ids=[[0, 0]] , )
__lowercase : List[Any] = rag_model.retriever.generator_tokenizer.batch_decode(lowerCAmelCase_ , skip_special_tokens=lowerCAmelCase_ )
if args.print_predictions:
for q, a in zip(lowerCAmelCase_ , lowerCAmelCase_ ):
logger.info("""Q: {} - A: {}""".format(lowerCAmelCase_ , lowerCAmelCase_ ) )
return answers
def snake_case_ ( ):
__lowercase : Optional[Any] = argparse.ArgumentParser()
parser.add_argument(
"""--model_type""" , choices=["""rag_sequence""", """rag_token""", """bart"""] , type=lowerCAmelCase_ , help=(
"""RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the"""
""" model_name_or_path"""
) , )
parser.add_argument(
"""--index_name""" , default=lowerCAmelCase_ , choices=["""exact""", """compressed""", """legacy"""] , type=lowerCAmelCase_ , help="""RAG model retriever type""" , )
parser.add_argument(
"""--index_path""" , default=lowerCAmelCase_ , type=lowerCAmelCase_ , help="""Path to the retrieval index""" , )
parser.add_argument("""--n_docs""" , default=5 , type=lowerCAmelCase_ , help="""Number of retrieved docs""" )
parser.add_argument(
"""--model_name_or_path""" , default=lowerCAmelCase_ , type=lowerCAmelCase_ , required=lowerCAmelCase_ , help="""Path to pretrained checkpoints or model identifier from huggingface.co/models""" , )
parser.add_argument(
"""--eval_mode""" , choices=["""e2e""", """retrieval"""] , default="""e2e""" , type=lowerCAmelCase_ , help=(
"""Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates"""
""" precision@k."""
) , )
parser.add_argument("""--k""" , default=1 , type=lowerCAmelCase_ , help="""k for the precision@k calculation""" )
parser.add_argument(
"""--evaluation_set""" , default=lowerCAmelCase_ , type=lowerCAmelCase_ , required=lowerCAmelCase_ , help="""Path to a file containing evaluation samples""" , )
parser.add_argument(
"""--gold_data_path""" , default=lowerCAmelCase_ , type=lowerCAmelCase_ , required=lowerCAmelCase_ , help="""Path to a tab-separated file with gold samples""" , )
parser.add_argument(
"""--gold_data_mode""" , default="""qa""" , type=lowerCAmelCase_ , choices=["""qa""", """ans"""] , help=(
"""Format of the gold data file"""
"""qa - a single line in the following format: question [tab] answer_list"""
"""ans - a single line of the gold file contains the expected answer string"""
) , )
parser.add_argument(
"""--predictions_path""" , type=lowerCAmelCase_ , default="""predictions.txt""" , help="""Name of the predictions file, to be stored in the checkpoints directory""" , )
parser.add_argument(
"""--eval_all_checkpoints""" , action="""store_true""" , help="""Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number""" , )
parser.add_argument(
"""--eval_batch_size""" , default=8 , type=lowerCAmelCase_ , help="""Batch size per GPU/CPU for evaluation.""" , )
parser.add_argument(
"""--recalculate""" , help="""Recalculate predictions even if the prediction file exists""" , action="""store_true""" , )
parser.add_argument(
"""--num_beams""" , default=4 , type=lowerCAmelCase_ , help="""Number of beams to be used when generating answers""" , )
parser.add_argument("""--min_length""" , default=1 , type=lowerCAmelCase_ , help="""Min length of the generated answers""" )
parser.add_argument("""--max_length""" , default=50 , type=lowerCAmelCase_ , help="""Max length of the generated answers""" )
parser.add_argument(
"""--print_predictions""" , action="""store_true""" , help="""If True, prints predictions while evaluating.""" , )
parser.add_argument(
"""--print_docs""" , action="""store_true""" , help="""If True, prints docs retried while generating.""" , )
__lowercase : Union[str, Any] = parser.parse_args()
__lowercase : Dict = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" )
return args
def snake_case_ ( lowerCAmelCase_ : Any ):
__lowercase : List[str] = {}
if args.model_type is None:
__lowercase : List[Any] = infer_model_type(args.model_name_or_path )
assert args.model_type is not None
if args.model_type.startswith("""rag""" ):
__lowercase : Dict = RagTokenForGeneration if args.model_type == """rag_token""" else RagSequenceForGeneration
__lowercase : int = args.n_docs
if args.index_name is not None:
__lowercase : Tuple = args.index_name
if args.index_path is not None:
__lowercase : Tuple = args.index_path
else:
__lowercase : Dict = BartForConditionalGeneration
__lowercase : str = (
[f.path for f in os.scandir(args.model_name_or_path ) if f.is_dir()]
if args.eval_all_checkpoints
else [args.model_name_or_path]
)
logger.info("""Evaluate the following checkpoints: %s""" , lowerCAmelCase_ )
__lowercase : Optional[int] = get_scores if args.eval_mode == """e2e""" else get_precision_at_k
__lowercase : Any = evaluate_batch_eae if args.eval_mode == """e2e""" else evaluate_batch_retrieval
for checkpoint in checkpoints:
if os.path.exists(args.predictions_path ) and (not args.recalculate):
logger.info("""Calculating metrics based on an existing predictions file: {}""".format(args.predictions_path ) )
score_fn(lowerCAmelCase_ , args.predictions_path , args.gold_data_path )
continue
logger.info("""***** Running evaluation for {} *****""".format(lowerCAmelCase_ ) )
logger.info(""" Batch size = %d""" , args.eval_batch_size )
logger.info(""" Predictions will be stored under {}""".format(args.predictions_path ) )
if args.model_type.startswith("""rag""" ):
__lowercase : int = RagRetriever.from_pretrained(lowerCAmelCase_ , **lowerCAmelCase_ )
__lowercase : int = model_class.from_pretrained(lowerCAmelCase_ , retriever=lowerCAmelCase_ , **lowerCAmelCase_ )
model.retriever.init_retrieval()
else:
__lowercase : int = model_class.from_pretrained(lowerCAmelCase_ , **lowerCAmelCase_ )
model.to(args.device )
with open(args.evaluation_set , """r""" ) as eval_file, open(args.predictions_path , """w""" ) as preds_file:
__lowercase : List[str] = []
for line in tqdm(lowerCAmelCase_ ):
questions.append(line.strip() )
if len(lowerCAmelCase_ ) == args.eval_batch_size:
__lowercase : int = evaluate_batch_fn(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
preds_file.write("""\n""".join(lowerCAmelCase_ ) + """\n""" )
preds_file.flush()
__lowercase : Union[str, Any] = []
if len(lowerCAmelCase_ ) > 0:
__lowercase : Union[str, Any] = evaluate_batch_fn(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
preds_file.write("""\n""".join(lowerCAmelCase_ ) )
preds_file.flush()
score_fn(lowerCAmelCase_ , args.predictions_path , args.gold_data_path )
if __name__ == "__main__":
lowerCamelCase : Optional[int] = get_args()
main(args) | 149 |
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import flax
import jax.numpy as jnp
from jax import random
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .scheduling_utils_flax import FlaxSchedulerMixin
@flax.struct.dataclass
class lowerCAmelCase :
'''simple docstring'''
_A : Optional[int] = None
_A : Optional[jnp.ndarray] = None
_A : Optional[jnp.ndarray] = None # sigma(t_i)
@classmethod
def lowerCAmelCase ( cls : int ) -> Optional[int]:
"""simple docstring"""
return cls()
@dataclass
class lowerCAmelCase ( __a ):
'''simple docstring'''
_A : jnp.ndarray
_A : jnp.ndarray
_A : KarrasVeSchedulerState
class lowerCAmelCase ( __a , __a ):
'''simple docstring'''
@property
def lowerCAmelCase ( self : Union[str, Any] ) -> Tuple:
"""simple docstring"""
return True
@register_to_config
def __init__( self : Optional[Any] , __a : float = 0.02 , __a : float = 100 , __a : float = 1.007 , __a : float = 80 , __a : float = 0.05 , __a : float = 50 , ) -> str:
"""simple docstring"""
pass
def lowerCAmelCase ( self : Dict ) -> int:
"""simple docstring"""
return KarrasVeSchedulerState.create()
def lowerCAmelCase ( self : Union[str, Any] , __a : KarrasVeSchedulerState , __a : int , __a : Tuple = () ) -> KarrasVeSchedulerState:
"""simple docstring"""
__lowercase : Dict = jnp.arange(0 , __a )[::-1].copy()
__lowercase : Dict = [
(
self.config.sigma_max**2
* (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1))
)
for i in timesteps
]
return state.replace(
num_inference_steps=__a , schedule=jnp.array(__a , dtype=jnp.floataa ) , timesteps=__a , )
def lowerCAmelCase ( self : Optional[Any] , __a : KarrasVeSchedulerState , __a : jnp.ndarray , __a : float , __a : random.KeyArray , ) -> Tuple[jnp.ndarray, float]:
"""simple docstring"""
if self.config.s_min <= sigma <= self.config.s_max:
__lowercase : Tuple = min(self.config.s_churn / state.num_inference_steps , 2**0.5 - 1 )
else:
__lowercase : List[str] = 0
# sample eps ~ N(0, S_noise^2 * I)
__lowercase : str = random.split(__a , num=1 )
__lowercase : List[Any] = self.config.s_noise * random.normal(key=__a , shape=sample.shape )
__lowercase : str = sigma + gamma * sigma
__lowercase : Union[str, Any] = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps)
return sample_hat, sigma_hat
def lowerCAmelCase ( self : List[Any] , __a : KarrasVeSchedulerState , __a : jnp.ndarray , __a : float , __a : float , __a : jnp.ndarray , __a : bool = True , ) -> Union[FlaxKarrasVeOutput, Tuple]:
"""simple docstring"""
__lowercase : List[str] = sample_hat + sigma_hat * model_output
__lowercase : List[Any] = (sample_hat - pred_original_sample) / sigma_hat
__lowercase : Dict = sample_hat + (sigma_prev - sigma_hat) * derivative
if not return_dict:
return (sample_prev, derivative, state)
return FlaxKarrasVeOutput(prev_sample=__a , derivative=__a , state=__a )
def lowerCAmelCase ( self : Any , __a : KarrasVeSchedulerState , __a : jnp.ndarray , __a : float , __a : float , __a : jnp.ndarray , __a : jnp.ndarray , __a : jnp.ndarray , __a : bool = True , ) -> Union[FlaxKarrasVeOutput, Tuple]:
"""simple docstring"""
__lowercase : str = sample_prev + sigma_prev * model_output
__lowercase : Optional[int] = (sample_prev - pred_original_sample) / sigma_prev
__lowercase : Any = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr)
if not return_dict:
return (sample_prev, derivative, state)
return FlaxKarrasVeOutput(prev_sample=__a , derivative=__a , state=__a )
def lowerCAmelCase ( self : int , __a : KarrasVeSchedulerState , __a : Dict , __a : Any , __a : Optional[Any] ) -> int:
"""simple docstring"""
raise NotImplementedError() | 149 | 1 |
"""simple docstring"""
import argparse
import pathlib
import fairseq
import torch
from fairseq.models.roberta import RobertaModel as FairseqRobertaModel
from fairseq.modules import TransformerSentenceEncoderLayer
from packaging import version
from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM, XLMRobertaXLForSequenceClassification
from transformers.models.bert.modeling_bert import (
BertIntermediate,
BertLayer,
BertOutput,
BertSelfAttention,
BertSelfOutput,
)
from transformers.models.roberta.modeling_roberta import RobertaAttention
from transformers.utils import logging
if version.parse(fairseq.__version__) < version.parse('''1.0.0a'''):
raise Exception('''requires fairseq >= 1.0.0a''')
logging.set_verbosity_info()
lowerCamelCase : Optional[Any] =logging.get_logger(__name__)
lowerCamelCase : int ='''Hello world! cécé herlolip'''
def _lowercase ( _SCREAMING_SNAKE_CASE : str , _SCREAMING_SNAKE_CASE : Dict , _SCREAMING_SNAKE_CASE : List[str] ) -> Dict:
'''simple docstring'''
__A : Union[str, Any] = FairseqRobertaModel.from_pretrained(__SCREAMING_SNAKE_CASE )
roberta.eval() # disable dropout
__A : List[Any] = roberta.model.encoder.sentence_encoder
__A : Any = XLMRobertaConfig(
vocab_size=roberta_sent_encoder.embed_tokens.num_embeddings , hidden_size=roberta.cfg.model.encoder_embed_dim , num_hidden_layers=roberta.cfg.model.encoder_layers , num_attention_heads=roberta.cfg.model.encoder_attention_heads , intermediate_size=roberta.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=514 , type_vocab_size=1 , layer_norm_eps=1E-5 , )
if classification_head:
__A : Union[str, Any] = roberta.model.classification_heads['mnli'].out_proj.weight.shape[0]
print('Our RoBERTa config:' , __SCREAMING_SNAKE_CASE )
__A : Dict = XLMRobertaXLForSequenceClassification(__SCREAMING_SNAKE_CASE ) if classification_head else XLMRobertaXLForMaskedLM(__SCREAMING_SNAKE_CASE )
model.eval()
# Now let's copy all the weights.
# Embeddings
__A : Any = roberta_sent_encoder.embed_tokens.weight
__A : Dict = roberta_sent_encoder.embed_positions.weight
__A : List[Any] = torch.zeros_like(
model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c RoBERTa doesn't use them.
__A : int = roberta_sent_encoder.layer_norm.weight
__A : Optional[int] = roberta_sent_encoder.layer_norm.bias
for i in range(config.num_hidden_layers ):
# Encoder: start of layer
__A : Tuple = model.roberta.encoder.layer[i]
__A : Dict = roberta_sent_encoder.layers[i]
__A : Union[str, Any] = layer.attention
__A : Dict = roberta_layer.self_attn_layer_norm.weight
__A : List[Any] = roberta_layer.self_attn_layer_norm.bias
# self attention
__A : List[Any] = layer.attention.self
assert (
roberta_layer.self_attn.k_proj.weight.data.shape
== roberta_layer.self_attn.q_proj.weight.data.shape
== roberta_layer.self_attn.v_proj.weight.data.shape
== torch.Size((config.hidden_size, config.hidden_size) )
)
__A : Optional[Any] = roberta_layer.self_attn.q_proj.weight
__A : Optional[int] = roberta_layer.self_attn.q_proj.bias
__A : List[Any] = roberta_layer.self_attn.k_proj.weight
__A : Dict = roberta_layer.self_attn.k_proj.bias
__A : int = roberta_layer.self_attn.v_proj.weight
__A : Dict = roberta_layer.self_attn.v_proj.bias
# self-attention output
__A : List[Any] = layer.attention.output
assert self_output.dense.weight.shape == roberta_layer.self_attn.out_proj.weight.shape
__A : Union[str, Any] = roberta_layer.self_attn.out_proj.weight
__A : int = roberta_layer.self_attn.out_proj.bias
# this one is final layer norm
__A : Optional[Any] = roberta_layer.final_layer_norm.weight
__A : Optional[Any] = roberta_layer.final_layer_norm.bias
# intermediate
__A : Union[str, Any] = layer.intermediate
assert intermediate.dense.weight.shape == roberta_layer.fca.weight.shape
__A : Tuple = roberta_layer.fca.weight
__A : Optional[int] = roberta_layer.fca.bias
# output
__A : List[str] = layer.output
assert bert_output.dense.weight.shape == roberta_layer.fca.weight.shape
__A : Dict = roberta_layer.fca.weight
__A : Dict = roberta_layer.fca.bias
# end of layer
if classification_head:
__A : Any = roberta.model.classification_heads['mnli'].dense.weight
__A : Tuple = roberta.model.classification_heads['mnli'].dense.bias
__A : str = roberta.model.classification_heads['mnli'].out_proj.weight
__A : Optional[Any] = roberta.model.classification_heads['mnli'].out_proj.bias
else:
# LM Head
__A : int = roberta.model.encoder.lm_head.dense.weight
__A : Union[str, Any] = roberta.model.encoder.lm_head.dense.bias
__A : Any = roberta.model.encoder.lm_head.layer_norm.weight
__A : Optional[Any] = roberta.model.encoder.lm_head.layer_norm.bias
__A : Optional[int] = roberta.model.encoder.lm_head.weight
__A : List[Any] = roberta.model.encoder.lm_head.bias
# Let's check that we get the same results.
__A : Union[str, Any] = roberta.encode(__SCREAMING_SNAKE_CASE ).unsqueeze(0 ) # batch of size 1
__A : List[Any] = model(__SCREAMING_SNAKE_CASE )[0]
if classification_head:
__A : str = roberta.model.classification_heads['mnli'](roberta.extract_features(__SCREAMING_SNAKE_CASE ) )
else:
__A : Dict = roberta.model(__SCREAMING_SNAKE_CASE )[0]
print(our_output.shape , their_output.shape )
__A : Union[str, Any] = torch.max(torch.abs(our_output - their_output ) ).item()
print(F'max_absolute_diff = {max_absolute_diff}' ) # ~ 1e-7
__A : Dict = torch.allclose(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , atol=1E-3 )
print('Do both models output the same tensors?' , '🔥' if success else '💩' )
if not success:
raise Exception('Something went wRoNg' )
pathlib.Path(__SCREAMING_SNAKE_CASE ).mkdir(parents=__SCREAMING_SNAKE_CASE , exist_ok=__SCREAMING_SNAKE_CASE )
print(F'Saving model to {pytorch_dump_folder_path}' )
model.save_pretrained(__SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
lowerCamelCase : Optional[Any] =argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--roberta_checkpoint_path''', default=None, type=str, required=True, help='''Path the official PyTorch dump.'''
)
parser.add_argument(
'''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
)
parser.add_argument(
'''--classification_head''', action='''store_true''', help='''Whether to convert a final classification head.'''
)
lowerCamelCase : Dict =parser.parse_args()
convert_xlm_roberta_xl_checkpoint_to_pytorch(
args.roberta_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
)
| 701 | """simple docstring"""
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxSeqaSeqConfigWithPast
from ...utils import logging
lowerCamelCase : Tuple =logging.get_logger(__name__)
lowerCamelCase : Union[str, Any] ={
'''google/umt5-small''': '''https://huggingface.co/google/umt5-small/resolve/main/config.json''',
# See all umt5 models at https://huggingface.co/models?filter=umt5
}
class __snake_case( A_ ):
'''simple docstring'''
_UpperCAmelCase = "umt5"
_UpperCAmelCase = ["past_key_values"]
def __init__( self , __lowerCamelCase=250112 , __lowerCamelCase=512 , __lowerCamelCase=64 , __lowerCamelCase=1024 , __lowerCamelCase=8 , __lowerCamelCase=None , __lowerCamelCase=6 , __lowerCamelCase=32 , __lowerCamelCase=128 , __lowerCamelCase=0.1 , __lowerCamelCase=1e-6 , __lowerCamelCase=1.0 , __lowerCamelCase="gated-gelu" , __lowerCamelCase=True , __lowerCamelCase=True , __lowerCamelCase="T5Tokenizer" , __lowerCamelCase=True , __lowerCamelCase=0 , __lowerCamelCase=1 , __lowerCamelCase=0 , **__lowerCamelCase , ):
'''simple docstring'''
super().__init__(
is_encoder_decoder=__lowerCamelCase , tokenizer_class=__lowerCamelCase , tie_word_embeddings=__lowerCamelCase , pad_token_id=__lowerCamelCase , eos_token_id=__lowerCamelCase , decoder_start_token_id=__lowerCamelCase , **__lowerCamelCase , )
__A : Union[str, Any] = vocab_size
__A : Any = d_model
__A : str = d_kv
__A : List[Any] = d_ff
__A : Union[str, Any] = num_layers
__A : Tuple = (
num_decoder_layers if num_decoder_layers is not None else self.num_layers
) # default = symmetry
__A : Union[str, Any] = num_heads
__A : str = relative_attention_num_buckets
__A : Union[str, Any] = relative_attention_max_distance
__A : int = dropout_rate
__A : int = layer_norm_epsilon
__A : int = initializer_factor
__A : List[Any] = feed_forward_proj
__A : str = use_cache
__A : str = self.feed_forward_proj.split('-' )
__A : str = act_info[-1]
__A : Any = act_info[0] == 'gated'
if len(__lowerCamelCase ) > 1 and act_info[0] != "gated" or len(__lowerCamelCase ) > 2:
raise ValueError(
F'`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.'
'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. '
'\'gated-gelu\' or \'relu\'' )
if feed_forward_proj == "gated-gelu":
__A : Optional[int] = 'gelu_new'
@property
def _a ( self ):
'''simple docstring'''
return self.d_model
@property
def _a ( self ):
'''simple docstring'''
return self.num_heads
@property
def _a ( self ):
'''simple docstring'''
return self.num_layers
class __snake_case( A_ ):
'''simple docstring'''
@property
# Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs
def _a ( self ):
'''simple docstring'''
__A : List[Any] = {
'input_ids': {0: 'batch', 1: 'encoder_sequence'},
'attention_mask': {0: 'batch', 1: 'encoder_sequence'},
}
if self.use_past:
__A : int = 'past_encoder_sequence + sequence'
__A : List[str] = {0: 'batch'}
__A : Dict = {0: 'batch', 1: 'past_decoder_sequence + sequence'}
else:
__A : List[str] = {0: 'batch', 1: 'decoder_sequence'}
__A : str = {0: 'batch', 1: 'decoder_sequence'}
if self.use_past:
self.fill_with_past_key_values_(__lowerCamelCase , direction='inputs' )
return common_inputs
@property
# Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset
def _a ( self ):
'''simple docstring'''
return 13
@property
def _a ( self ):
'''simple docstring'''
return 5e-4
| 237 | 0 |
from collections.abc import Sequence
from queue import Queue
class __UpperCamelCase :
def __init__( self : Optional[Any] , _lowerCAmelCase : Tuple , _lowerCAmelCase : List[Any] , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : Any=None , _lowerCAmelCase : Dict=None ) -> List[Any]:
"""simple docstring"""
__lowercase = start
__lowercase = end
__lowercase = val
__lowercase = (start + end) // 2
__lowercase = left
__lowercase = right
def __repr__( self : List[Any] ) -> List[Any]:
"""simple docstring"""
return F'SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})'
class __UpperCamelCase :
def __init__( self : Dict , _lowerCAmelCase : Sequence , _lowerCAmelCase : str ) -> Union[str, Any]:
"""simple docstring"""
__lowercase = collection
__lowercase = function
if self.collection:
__lowercase = self._build_tree(0 , len(_lowerCAmelCase ) - 1 )
def _a ( self : int , _lowerCAmelCase : List[Any] , _lowerCAmelCase : List[str] ) -> Tuple:
"""simple docstring"""
self._update_tree(self.root , _lowerCAmelCase , _lowerCAmelCase )
def _a ( self : Any , _lowerCAmelCase : List[Any] , _lowerCAmelCase : Tuple ) -> List[Any]:
"""simple docstring"""
return self._query_range(self.root , _lowerCAmelCase , _lowerCAmelCase )
def _a ( self : Any , _lowerCAmelCase : str , _lowerCAmelCase : str ) -> str:
"""simple docstring"""
if start == end:
return SegmentTreeNode(_lowerCAmelCase , _lowerCAmelCase , self.collection[start] )
__lowercase = (start + end) // 2
__lowercase = self._build_tree(_lowerCAmelCase , _lowerCAmelCase )
__lowercase = self._build_tree(mid + 1 , _lowerCAmelCase )
return SegmentTreeNode(_lowerCAmelCase , _lowerCAmelCase , self.fn(left.val , right.val ) , _lowerCAmelCase , _lowerCAmelCase )
def _a ( self : List[str] , _lowerCAmelCase : List[Any] , _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Union[str, Any] ) -> Tuple:
"""simple docstring"""
if node.start == i and node.end == i:
__lowercase = val
return
if i <= node.mid:
self._update_tree(node.left , _lowerCAmelCase , _lowerCAmelCase )
else:
self._update_tree(node.right , _lowerCAmelCase , _lowerCAmelCase )
__lowercase = self.fn(node.left.val , node.right.val )
def _a ( self : Optional[Any] , _lowerCAmelCase : Tuple , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : List[Any] ) -> Optional[int]:
"""simple docstring"""
if node.start == i and node.end == j:
return node.val
if i <= node.mid:
if j <= node.mid:
# range in left child tree
return self._query_range(node.left , _lowerCAmelCase , _lowerCAmelCase )
else:
# range in left child tree and right child tree
return self.fn(
self._query_range(node.left , _lowerCAmelCase , node.mid ) , self._query_range(node.right , node.mid + 1 , _lowerCAmelCase ) , )
else:
# range in right child tree
return self._query_range(node.right , _lowerCAmelCase , _lowerCAmelCase )
def _a ( self : List[Any] ) -> Tuple:
"""simple docstring"""
if self.root is not None:
__lowercase = Queue()
queue.put(self.root )
while not queue.empty():
__lowercase = queue.get()
yield node
if node.left is not None:
queue.put(node.left )
if node.right is not None:
queue.put(node.right )
if __name__ == "__main__":
import operator
for fn in [operator.add, max, min]:
print("""*""" * 50)
__UpperCamelCase : Union[str, Any] = SegmentTree([2, 1, 5, 3, 4], fn)
for node in arr.traverse():
print(node)
print()
arr.update(1, 5)
for node in arr.traverse():
print(node)
print()
print(arr.query_range(3, 4)) # 7
print(arr.query_range(2, 2)) # 5
print(arr.query_range(1, 3)) # 13
print()
| 80 |
from collections import OrderedDict
from ...utils import logging
from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update
from .configuration_auto import CONFIG_MAPPING_NAMES
__UpperCamelCase : List[str] = logging.get_logger(__name__)
__UpperCamelCase : List[str] = OrderedDict(
[
# Base model mapping
("""albert""", """FlaxAlbertModel"""),
("""bart""", """FlaxBartModel"""),
("""beit""", """FlaxBeitModel"""),
("""bert""", """FlaxBertModel"""),
("""big_bird""", """FlaxBigBirdModel"""),
("""blenderbot""", """FlaxBlenderbotModel"""),
("""blenderbot-small""", """FlaxBlenderbotSmallModel"""),
("""clip""", """FlaxCLIPModel"""),
("""distilbert""", """FlaxDistilBertModel"""),
("""electra""", """FlaxElectraModel"""),
("""gpt-sw3""", """FlaxGPT2Model"""),
("""gpt2""", """FlaxGPT2Model"""),
("""gpt_neo""", """FlaxGPTNeoModel"""),
("""gptj""", """FlaxGPTJModel"""),
("""longt5""", """FlaxLongT5Model"""),
("""marian""", """FlaxMarianModel"""),
("""mbart""", """FlaxMBartModel"""),
("""mt5""", """FlaxMT5Model"""),
("""opt""", """FlaxOPTModel"""),
("""pegasus""", """FlaxPegasusModel"""),
("""regnet""", """FlaxRegNetModel"""),
("""resnet""", """FlaxResNetModel"""),
("""roberta""", """FlaxRobertaModel"""),
("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormModel"""),
("""roformer""", """FlaxRoFormerModel"""),
("""t5""", """FlaxT5Model"""),
("""vision-text-dual-encoder""", """FlaxVisionTextDualEncoderModel"""),
("""vit""", """FlaxViTModel"""),
("""wav2vec2""", """FlaxWav2Vec2Model"""),
("""whisper""", """FlaxWhisperModel"""),
("""xglm""", """FlaxXGLMModel"""),
("""xlm-roberta""", """FlaxXLMRobertaModel"""),
]
)
__UpperCamelCase : Tuple = OrderedDict(
[
# Model for pre-training mapping
("""albert""", """FlaxAlbertForPreTraining"""),
("""bart""", """FlaxBartForConditionalGeneration"""),
("""bert""", """FlaxBertForPreTraining"""),
("""big_bird""", """FlaxBigBirdForPreTraining"""),
("""electra""", """FlaxElectraForPreTraining"""),
("""longt5""", """FlaxLongT5ForConditionalGeneration"""),
("""mbart""", """FlaxMBartForConditionalGeneration"""),
("""mt5""", """FlaxMT5ForConditionalGeneration"""),
("""roberta""", """FlaxRobertaForMaskedLM"""),
("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""),
("""roformer""", """FlaxRoFormerForMaskedLM"""),
("""t5""", """FlaxT5ForConditionalGeneration"""),
("""wav2vec2""", """FlaxWav2Vec2ForPreTraining"""),
("""whisper""", """FlaxWhisperForConditionalGeneration"""),
("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""),
]
)
__UpperCamelCase : Optional[Any] = OrderedDict(
[
# Model for Masked LM mapping
("""albert""", """FlaxAlbertForMaskedLM"""),
("""bart""", """FlaxBartForConditionalGeneration"""),
("""bert""", """FlaxBertForMaskedLM"""),
("""big_bird""", """FlaxBigBirdForMaskedLM"""),
("""distilbert""", """FlaxDistilBertForMaskedLM"""),
("""electra""", """FlaxElectraForMaskedLM"""),
("""mbart""", """FlaxMBartForConditionalGeneration"""),
("""roberta""", """FlaxRobertaForMaskedLM"""),
("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMaskedLM"""),
("""roformer""", """FlaxRoFormerForMaskedLM"""),
("""xlm-roberta""", """FlaxXLMRobertaForMaskedLM"""),
]
)
__UpperCamelCase : Optional[Any] = OrderedDict(
[
# Model for Seq2Seq Causal LM mapping
("""bart""", """FlaxBartForConditionalGeneration"""),
("""blenderbot""", """FlaxBlenderbotForConditionalGeneration"""),
("""blenderbot-small""", """FlaxBlenderbotSmallForConditionalGeneration"""),
("""encoder-decoder""", """FlaxEncoderDecoderModel"""),
("""longt5""", """FlaxLongT5ForConditionalGeneration"""),
("""marian""", """FlaxMarianMTModel"""),
("""mbart""", """FlaxMBartForConditionalGeneration"""),
("""mt5""", """FlaxMT5ForConditionalGeneration"""),
("""pegasus""", """FlaxPegasusForConditionalGeneration"""),
("""t5""", """FlaxT5ForConditionalGeneration"""),
]
)
__UpperCamelCase : int = OrderedDict(
[
# Model for Image-classsification
("""beit""", """FlaxBeitForImageClassification"""),
("""regnet""", """FlaxRegNetForImageClassification"""),
("""resnet""", """FlaxResNetForImageClassification"""),
("""vit""", """FlaxViTForImageClassification"""),
]
)
__UpperCamelCase : List[Any] = OrderedDict(
[
("""vision-encoder-decoder""", """FlaxVisionEncoderDecoderModel"""),
]
)
__UpperCamelCase : List[Any] = OrderedDict(
[
# Model for Causal LM mapping
("""bart""", """FlaxBartForCausalLM"""),
("""bert""", """FlaxBertForCausalLM"""),
("""big_bird""", """FlaxBigBirdForCausalLM"""),
("""electra""", """FlaxElectraForCausalLM"""),
("""gpt-sw3""", """FlaxGPT2LMHeadModel"""),
("""gpt2""", """FlaxGPT2LMHeadModel"""),
("""gpt_neo""", """FlaxGPTNeoForCausalLM"""),
("""gptj""", """FlaxGPTJForCausalLM"""),
("""opt""", """FlaxOPTForCausalLM"""),
("""roberta""", """FlaxRobertaForCausalLM"""),
("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForCausalLM"""),
("""xglm""", """FlaxXGLMForCausalLM"""),
("""xlm-roberta""", """FlaxXLMRobertaForCausalLM"""),
]
)
__UpperCamelCase : List[str] = OrderedDict(
[
# Model for Sequence Classification mapping
("""albert""", """FlaxAlbertForSequenceClassification"""),
("""bart""", """FlaxBartForSequenceClassification"""),
("""bert""", """FlaxBertForSequenceClassification"""),
("""big_bird""", """FlaxBigBirdForSequenceClassification"""),
("""distilbert""", """FlaxDistilBertForSequenceClassification"""),
("""electra""", """FlaxElectraForSequenceClassification"""),
("""mbart""", """FlaxMBartForSequenceClassification"""),
("""roberta""", """FlaxRobertaForSequenceClassification"""),
("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForSequenceClassification"""),
("""roformer""", """FlaxRoFormerForSequenceClassification"""),
("""xlm-roberta""", """FlaxXLMRobertaForSequenceClassification"""),
]
)
__UpperCamelCase : List[str] = OrderedDict(
[
# Model for Question Answering mapping
("""albert""", """FlaxAlbertForQuestionAnswering"""),
("""bart""", """FlaxBartForQuestionAnswering"""),
("""bert""", """FlaxBertForQuestionAnswering"""),
("""big_bird""", """FlaxBigBirdForQuestionAnswering"""),
("""distilbert""", """FlaxDistilBertForQuestionAnswering"""),
("""electra""", """FlaxElectraForQuestionAnswering"""),
("""mbart""", """FlaxMBartForQuestionAnswering"""),
("""roberta""", """FlaxRobertaForQuestionAnswering"""),
("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForQuestionAnswering"""),
("""roformer""", """FlaxRoFormerForQuestionAnswering"""),
("""xlm-roberta""", """FlaxXLMRobertaForQuestionAnswering"""),
]
)
__UpperCamelCase : int = OrderedDict(
[
# Model for Token Classification mapping
("""albert""", """FlaxAlbertForTokenClassification"""),
("""bert""", """FlaxBertForTokenClassification"""),
("""big_bird""", """FlaxBigBirdForTokenClassification"""),
("""distilbert""", """FlaxDistilBertForTokenClassification"""),
("""electra""", """FlaxElectraForTokenClassification"""),
("""roberta""", """FlaxRobertaForTokenClassification"""),
("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForTokenClassification"""),
("""roformer""", """FlaxRoFormerForTokenClassification"""),
("""xlm-roberta""", """FlaxXLMRobertaForTokenClassification"""),
]
)
__UpperCamelCase : Dict = OrderedDict(
[
# Model for Multiple Choice mapping
("""albert""", """FlaxAlbertForMultipleChoice"""),
("""bert""", """FlaxBertForMultipleChoice"""),
("""big_bird""", """FlaxBigBirdForMultipleChoice"""),
("""distilbert""", """FlaxDistilBertForMultipleChoice"""),
("""electra""", """FlaxElectraForMultipleChoice"""),
("""roberta""", """FlaxRobertaForMultipleChoice"""),
("""roberta-prelayernorm""", """FlaxRobertaPreLayerNormForMultipleChoice"""),
("""roformer""", """FlaxRoFormerForMultipleChoice"""),
("""xlm-roberta""", """FlaxXLMRobertaForMultipleChoice"""),
]
)
__UpperCamelCase : str = OrderedDict(
[
("""bert""", """FlaxBertForNextSentencePrediction"""),
]
)
__UpperCamelCase : Optional[int] = OrderedDict(
[
("""speech-encoder-decoder""", """FlaxSpeechEncoderDecoderModel"""),
("""whisper""", """FlaxWhisperForConditionalGeneration"""),
]
)
__UpperCamelCase : Dict = OrderedDict(
[
("""whisper""", """FlaxWhisperForAudioClassification"""),
]
)
__UpperCamelCase : List[Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES)
__UpperCamelCase : str = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES)
__UpperCamelCase : Optional[int] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES)
__UpperCamelCase : Dict = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES
)
__UpperCamelCase : Dict = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES
)
__UpperCamelCase : int = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES)
__UpperCamelCase : Optional[Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES)
__UpperCamelCase : Tuple = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES
)
__UpperCamelCase : Any = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES
)
__UpperCamelCase : Union[str, Any] = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES
)
__UpperCamelCase : Tuple = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES
)
__UpperCamelCase : str = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES
)
__UpperCamelCase : List[str] = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES
)
__UpperCamelCase : Optional[Any] = _LazyAutoMapping(
CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES
)
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :Tuple = FLAX_MODEL_MAPPING
__UpperCamelCase : Tuple = auto_class_update(FlaxAutoModel)
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :Union[str, Any] = FLAX_MODEL_FOR_PRETRAINING_MAPPING
__UpperCamelCase : List[Any] = auto_class_update(FlaxAutoModelForPreTraining, head_doc="""pretraining""")
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :Dict = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING
__UpperCamelCase : Union[str, Any] = auto_class_update(FlaxAutoModelForCausalLM, head_doc="""causal language modeling""")
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :List[Any] = FLAX_MODEL_FOR_MASKED_LM_MAPPING
__UpperCamelCase : Dict = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="""masked language modeling""")
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :Optional[Any] = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
__UpperCamelCase : Optional[Any] = auto_class_update(
FlaxAutoModelForSeqaSeqLM, head_doc="""sequence-to-sequence language modeling""", checkpoint_for_example="""t5-base"""
)
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :Optional[Any] = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
__UpperCamelCase : Optional[int] = auto_class_update(
FlaxAutoModelForSequenceClassification, head_doc="""sequence classification"""
)
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :Optional[Any] = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING
__UpperCamelCase : Union[str, Any] = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="""question answering""")
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :List[Any] = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING
__UpperCamelCase : Optional[int] = auto_class_update(
FlaxAutoModelForTokenClassification, head_doc="""token classification"""
)
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :Optional[int] = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING
__UpperCamelCase : int = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="""multiple choice""")
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :str = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING
__UpperCamelCase : int = auto_class_update(
FlaxAutoModelForNextSentencePrediction, head_doc="""next sentence prediction"""
)
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :Dict = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
__UpperCamelCase : Optional[Any] = auto_class_update(
FlaxAutoModelForImageClassification, head_doc="""image classification"""
)
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :Dict = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING
__UpperCamelCase : Tuple = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc="""vision-to-text modeling""")
class __UpperCamelCase ( _BaseAutoModelClass ):
__snake_case :Optional[Any] = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING
__UpperCamelCase : str = auto_class_update(
FlaxAutoModelForSpeechSeqaSeq, head_doc="""sequence-to-sequence speech-to-text modeling"""
)
| 80 | 1 |
from collections.abc import Callable
import numpy as np
def A__ ( __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase ):
"""simple docstring"""
_lowerCAmelCase = int(np.ceil((x_end - xa) / step_size ) )
_lowerCAmelCase = np.zeros((n + 1,) )
_lowerCAmelCase = ya
_lowerCAmelCase = xa
for k in range(__lowerCamelCase ):
_lowerCAmelCase = y[k] + step_size * ode_func(__lowerCamelCase, y[k] )
x += step_size
return y
if __name__ == "__main__":
import doctest
doctest.testmod()
| 711 |
"""simple docstring"""
import argparse
from collections import defaultdict
import yaml
a__ : List[str] = """docs/source/en/_toctree.yml"""
def A__ ( __lowerCamelCase ):
"""simple docstring"""
_lowerCAmelCase = defaultdict(__lowerCamelCase )
for doc in model_doc:
counts[doc["local"]] += 1
_lowerCAmelCase = [key for key, value in counts.items() if value > 1]
_lowerCAmelCase = []
for duplicate_key in duplicates:
_lowerCAmelCase = list({doc['title'] for doc in model_doc if doc['local'] == duplicate_key} )
if len(__lowerCamelCase ) > 1:
raise ValueError(
F'''{duplicate_key} is present several times in the documentation table of content at '''
'`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the '
'others.' )
# Only add this once
new_doc.append({'local': duplicate_key, 'title': titles[0]} )
# Add none duplicate-keys
new_doc.extend([doc for doc in model_doc if counts[doc['local']] == 1] )
# Sort
return sorted(__lowerCamelCase, key=lambda __lowerCamelCase : s["title"].lower() )
def A__ ( __lowerCamelCase=False ):
"""simple docstring"""
with open(__lowerCamelCase, encoding='utf-8' ) as f:
_lowerCAmelCase = yaml.safe_load(f.read() )
# Get to the API doc
_lowerCAmelCase = 0
while content[api_idx]["title"] != "API":
api_idx += 1
_lowerCAmelCase = content[api_idx]['sections']
# Then to the model doc
_lowerCAmelCase = 0
while api_doc[model_idx]["title"] != "Models":
model_idx += 1
_lowerCAmelCase = api_doc[model_idx]['sections']
_lowerCAmelCase = [(idx, section) for idx, section in enumerate(__lowerCamelCase ) if 'sections' in section]
_lowerCAmelCase = False
for idx, modality_doc in modalities_docs:
_lowerCAmelCase = modality_doc['sections']
_lowerCAmelCase = clean_model_doc_toc(__lowerCamelCase )
if old_modality_doc != new_modality_doc:
_lowerCAmelCase = True
if overwrite:
_lowerCAmelCase = new_modality_doc
if diff:
if overwrite:
_lowerCAmelCase = model_doc
_lowerCAmelCase = api_doc
with open(__lowerCamelCase, 'w', encoding='utf-8' ) as f:
f.write(yaml.dump(__lowerCamelCase, allow_unicode=__lowerCamelCase ) )
else:
raise ValueError(
'The model doc part of the table of content is not properly sorted, run `make style` to fix this.' )
if __name__ == "__main__":
a__ : Dict = argparse.ArgumentParser()
parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""")
a__ : str = parser.parse_args()
check_model_doc(args.fix_and_overwrite)
| 309 | 0 |
"""simple docstring"""
import json
import pathlib
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision, slow
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import DeformableDetrImageProcessor
class __lowerCAmelCase ( unittest.TestCase ):
"""simple docstring"""
def __init__( self : List[Any] , _snake_case : List[str] , _snake_case : Any=7 , _snake_case : str=3 , _snake_case : Any=30 , _snake_case : Optional[int]=400 , _snake_case : Any=True , _snake_case : Any=None , _snake_case : str=True , _snake_case : Dict=[0.5, 0.5, 0.5] , _snake_case : int=[0.5, 0.5, 0.5] , _snake_case : Tuple=True , _snake_case : Dict=1 / 255 , _snake_case : Tuple=True , ) -> int:
"""simple docstring"""
A_ = size if size is not None else {"shortest_edge": 18, "longest_edge": 1_333}
A_ = parent
A_ = batch_size
A_ = num_channels
A_ = min_resolution
A_ = max_resolution
A_ = do_resize
A_ = size
A_ = do_normalize
A_ = image_mean
A_ = image_std
A_ = do_rescale
A_ = rescale_factor
A_ = do_pad
def lowerCamelCase__ ( self : Optional[int] ) -> int:
"""simple docstring"""
return {
"do_resize": self.do_resize,
"size": self.size,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_rescale": self.do_rescale,
"rescale_factor": self.rescale_factor,
"do_pad": self.do_pad,
}
def lowerCamelCase__ ( self : List[str] , _snake_case : Tuple , _snake_case : Dict=False ) -> Any:
"""simple docstring"""
if not batched:
A_ = image_inputs[0]
if isinstance(snake_case__ , Image.Image ):
A_ = image.size
else:
A_ = image.shape[1], image.shape[2]
if w < h:
A_ = int(self.size["shortest_edge"] * h / w )
A_ = self.size["shortest_edge"]
elif w > h:
A_ = self.size["shortest_edge"]
A_ = int(self.size["shortest_edge"] * w / h )
else:
A_ = self.size["shortest_edge"]
A_ = self.size["shortest_edge"]
else:
A_ = []
for image in image_inputs:
A_ = self.get_expected_values([image] )
expected_values.append((expected_height, expected_width) )
A_ = max(snake_case__ , key=lambda _snake_case : item[0] )[0]
A_ = max(snake_case__ , key=lambda _snake_case : item[1] )[1]
return expected_height, expected_width
@require_torch
@require_vision
class __lowerCAmelCase ( _lowercase , unittest.TestCase ):
"""simple docstring"""
snake_case = DeformableDetrImageProcessor if is_vision_available() else None
def lowerCamelCase__ ( self : List[str] ) -> Union[str, Any]:
"""simple docstring"""
A_ = DeformableDetrImageProcessingTester(self )
@property
def lowerCamelCase__ ( self : Optional[int] ) -> Tuple:
"""simple docstring"""
return self.image_processor_tester.prepare_image_processor_dict()
def lowerCamelCase__ ( self : str ) -> List[str]:
"""simple docstring"""
A_ = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(snake_case__ , "image_mean" ) )
self.assertTrue(hasattr(snake_case__ , "image_std" ) )
self.assertTrue(hasattr(snake_case__ , "do_normalize" ) )
self.assertTrue(hasattr(snake_case__ , "do_resize" ) )
self.assertTrue(hasattr(snake_case__ , "do_rescale" ) )
self.assertTrue(hasattr(snake_case__ , "do_pad" ) )
self.assertTrue(hasattr(snake_case__ , "size" ) )
def lowerCamelCase__ ( self : int ) -> str:
"""simple docstring"""
A_ = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {"shortest_edge": 18, "longest_edge": 1_333} )
self.assertEqual(image_processor.do_pad , snake_case__ )
A_ = self.image_processing_class.from_dict(
self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=snake_case__ )
self.assertEqual(image_processor.size , {"shortest_edge": 42, "longest_edge": 84} )
self.assertEqual(image_processor.do_pad , snake_case__ )
def lowerCamelCase__ ( self : List[str] ) -> List[str]:
"""simple docstring"""
pass
def lowerCamelCase__ ( self : Any ) -> Any:
"""simple docstring"""
A_ = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
A_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case__ )
for image in image_inputs:
self.assertIsInstance(snake_case__ , Image.Image )
# Test not batched input
A_ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
A_ = self.image_processor_tester.get_expected_values(snake_case__ )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
A_ = self.image_processor_tester.get_expected_values(snake_case__ , batched=snake_case__ )
A_ = image_processing(snake_case__ , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def lowerCamelCase__ ( self : List[Any] ) -> Tuple:
"""simple docstring"""
A_ = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
A_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case__ , numpify=snake_case__ )
for image in image_inputs:
self.assertIsInstance(snake_case__ , np.ndarray )
# Test not batched input
A_ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
A_ = self.image_processor_tester.get_expected_values(snake_case__ )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
A_ = image_processing(snake_case__ , return_tensors="pt" ).pixel_values
A_ = self.image_processor_tester.get_expected_values(snake_case__ , batched=snake_case__ )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
def lowerCamelCase__ ( self : Dict ) -> int:
"""simple docstring"""
A_ = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
A_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case__ , torchify=snake_case__ )
for image in image_inputs:
self.assertIsInstance(snake_case__ , torch.Tensor )
# Test not batched input
A_ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
A_ = self.image_processor_tester.get_expected_values(snake_case__ )
self.assertEqual(
encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , )
# Test batched
A_ = image_processing(snake_case__ , return_tensors="pt" ).pixel_values
A_ = self.image_processor_tester.get_expected_values(snake_case__ , batched=snake_case__ )
self.assertEqual(
encoded_images.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
expected_height,
expected_width,
) , )
@slow
def lowerCamelCase__ ( self : Union[str, Any] ) -> Tuple:
"""simple docstring"""
A_ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f:
A_ = json.loads(f.read() )
A_ = {"image_id": 39_769, "annotations": target}
# encode them
A_ = DeformableDetrImageProcessor()
A_ = image_processing(images=snake_case__ , annotations=snake_case__ , return_tensors="pt" )
# verify pixel values
A_ = torch.Size([1, 3, 800, 1_066] )
self.assertEqual(encoding["pixel_values"].shape , snake_case__ )
A_ = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] )
self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , snake_case__ , atol=1e-4 ) )
# verify area
A_ = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] )
self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , snake_case__ ) )
# verify boxes
A_ = torch.Size([6, 4] )
self.assertEqual(encoding["labels"][0]["boxes"].shape , snake_case__ )
A_ = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] )
self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , snake_case__ , atol=1e-3 ) )
# verify image_id
A_ = torch.tensor([39_769] )
self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , snake_case__ ) )
# verify is_crowd
A_ = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , snake_case__ ) )
# verify class_labels
A_ = torch.tensor([75, 75, 63, 65, 17, 17] )
self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , snake_case__ ) )
# verify orig_size
A_ = torch.tensor([480, 640] )
self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , snake_case__ ) )
# verify size
A_ = torch.tensor([800, 1_066] )
self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , snake_case__ ) )
@slow
def lowerCamelCase__ ( self : str ) -> int:
"""simple docstring"""
A_ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f:
A_ = json.loads(f.read() )
A_ = {"file_name": "000000039769.png", "image_id": 39_769, "segments_info": target}
A_ = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" )
# encode them
A_ = DeformableDetrImageProcessor(format="coco_panoptic" )
A_ = image_processing(images=snake_case__ , annotations=snake_case__ , masks_path=snake_case__ , return_tensors="pt" )
# verify pixel values
A_ = torch.Size([1, 3, 800, 1_066] )
self.assertEqual(encoding["pixel_values"].shape , snake_case__ )
A_ = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] )
self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , snake_case__ , atol=1e-4 ) )
# verify area
A_ = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] )
self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , snake_case__ ) )
# verify boxes
A_ = torch.Size([6, 4] )
self.assertEqual(encoding["labels"][0]["boxes"].shape , snake_case__ )
A_ = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] )
self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , snake_case__ , atol=1e-3 ) )
# verify image_id
A_ = torch.tensor([39_769] )
self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , snake_case__ ) )
# verify is_crowd
A_ = torch.tensor([0, 0, 0, 0, 0, 0] )
self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , snake_case__ ) )
# verify class_labels
A_ = torch.tensor([17, 17, 63, 75, 75, 93] )
self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , snake_case__ ) )
# verify masks
A_ = 822_873
self.assertEqual(encoding["labels"][0]["masks"].sum().item() , snake_case__ )
# verify orig_size
A_ = torch.tensor([480, 640] )
self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , snake_case__ ) )
# verify size
A_ = torch.tensor([800, 1_066] )
self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , snake_case__ ) )
| 115 |
"""simple docstring"""
# This is the module that test_patching.py uses to test patch_submodule()
import os # noqa: this is just for tests
import os as renamed_os # noqa: this is just for tests
from os import path # noqa: this is just for tests
from os import path as renamed_path # noqa: this is just for tests
from os.path import join # noqa: this is just for tests
from os.path import join as renamed_join # noqa: this is just for tests
lowerCAmelCase__ = open # noqa: we just need to have a builtin inside this module to test it properly
| 645 | 0 |
print((lambda quine: quine % quine)('''print((lambda quine: quine %% quine)(%r))''')) | 649 |
import logging
import os
import threading
import time
try:
import warnings
except ImportError:
lowerCamelCase : Any = None
try:
import msvcrt
except ImportError:
lowerCamelCase : str = None
try:
import fcntl
except ImportError:
lowerCamelCase : Optional[Any] = None
# Backward compatibility
# ------------------------------------------------
try:
TimeoutError
except NameError:
lowerCamelCase : Union[str, Any] = OSError
# Data
# ------------------------------------------------
lowerCamelCase : Tuple = [
'''Timeout''',
'''BaseFileLock''',
'''WindowsFileLock''',
'''UnixFileLock''',
'''SoftFileLock''',
'''FileLock''',
]
lowerCamelCase : Tuple = '''3.0.12'''
lowerCamelCase : Any = None
def snake_case_ ( ):
global _logger
__lowercase : List[str] = _logger or logging.getLogger(__name__ )
return _logger
class lowerCAmelCase ( __a ):
'''simple docstring'''
def __init__( self : Any , __a : Any ) -> List[Any]:
"""simple docstring"""
__lowercase : List[str] = lock_file
return None
def __str__( self : str ) -> Any:
"""simple docstring"""
__lowercase : Any = F"The file lock '{self.lock_file}' could not be acquired."
return temp
class lowerCAmelCase :
'''simple docstring'''
def __init__( self : List[Any] , __a : Optional[int] ) -> int:
"""simple docstring"""
__lowercase : Optional[Any] = lock
return None
def __enter__( self : Dict ) -> Dict:
"""simple docstring"""
return self.lock
def __exit__( self : Optional[int] , __a : Dict , __a : Any , __a : Tuple ) -> Optional[Any]:
"""simple docstring"""
self.lock.release()
return None
class lowerCAmelCase :
'''simple docstring'''
def __init__( self : Tuple , __a : Any , __a : Dict=-1 , __a : Optional[Any]=None ) -> Any:
"""simple docstring"""
__lowercase : Optional[int] = max_filename_length if max_filename_length is not None else 255
# Hash the filename if it's too long
__lowercase : Dict = self.hash_filename_if_too_long(__a , __a )
# The path to the lock file.
__lowercase : Optional[Any] = lock_file
# The file descriptor for the *_lock_file* as it is returned by the
# os.open() function.
# This file lock is only NOT None, if the object currently holds the
# lock.
__lowercase : int = None
# The default timeout value.
__lowercase : Optional[int] = timeout
# We use this lock primarily for the lock counter.
__lowercase : Optional[Any] = threading.Lock()
# The lock counter is used for implementing the nested locking
# mechanism. Whenever the lock is acquired, the counter is increased and
# the lock is only released, when this value is 0 again.
__lowercase : Union[str, Any] = 0
return None
@property
def lowerCAmelCase ( self : Optional[Any] ) -> Optional[int]:
"""simple docstring"""
return self._lock_file
@property
def lowerCAmelCase ( self : Optional[int] ) -> Optional[Any]:
"""simple docstring"""
return self._timeout
@timeout.setter
def lowerCAmelCase ( self : Tuple , __a : Tuple ) -> Dict:
"""simple docstring"""
__lowercase : Tuple = float(__a )
return None
def lowerCAmelCase ( self : Dict ) -> Tuple:
"""simple docstring"""
raise NotImplementedError()
def lowerCAmelCase ( self : Dict ) -> Any:
"""simple docstring"""
raise NotImplementedError()
@property
def lowerCAmelCase ( self : Dict ) -> List[Any]:
"""simple docstring"""
return self._lock_file_fd is not None
def lowerCAmelCase ( self : Any , __a : Optional[Any]=None , __a : Union[str, Any]=0.05 ) -> List[str]:
"""simple docstring"""
if timeout is None:
__lowercase : Union[str, Any] = self.timeout
# Increment the number right at the beginning.
# We can still undo it, if something fails.
with self._thread_lock:
self._lock_counter += 1
__lowercase : int = id(self )
__lowercase : Optional[Any] = self._lock_file
__lowercase : List[str] = time.time()
try:
while True:
with self._thread_lock:
if not self.is_locked:
logger().debug(F"Attempting to acquire lock {lock_id} on {lock_filename}" )
self._acquire()
if self.is_locked:
logger().debug(F"Lock {lock_id} acquired on {lock_filename}" )
break
elif timeout >= 0 and time.time() - start_time > timeout:
logger().debug(F"Timeout on acquiring lock {lock_id} on {lock_filename}" )
raise Timeout(self._lock_file )
else:
logger().debug(
F"Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ..." )
time.sleep(__a )
except: # noqa
# Something did go wrong, so decrement the counter.
with self._thread_lock:
__lowercase : Optional[int] = max(0 , self._lock_counter - 1 )
raise
return _Acquire_ReturnProxy(lock=self )
def lowerCAmelCase ( self : Union[str, Any] , __a : Optional[Any]=False ) -> Optional[Any]:
"""simple docstring"""
with self._thread_lock:
if self.is_locked:
self._lock_counter -= 1
if self._lock_counter == 0 or force:
__lowercase : Optional[Any] = id(self )
__lowercase : str = self._lock_file
logger().debug(F"Attempting to release lock {lock_id} on {lock_filename}" )
self._release()
__lowercase : List[str] = 0
logger().debug(F"Lock {lock_id} released on {lock_filename}" )
return None
def __enter__( self : Any ) -> Optional[Any]:
"""simple docstring"""
self.acquire()
return self
def __exit__( self : List[str] , __a : str , __a : int , __a : List[Any] ) -> Tuple:
"""simple docstring"""
self.release()
return None
def __del__( self : Optional[int] ) -> Optional[int]:
"""simple docstring"""
self.release(force=__a )
return None
def lowerCAmelCase ( self : Tuple , __a : str , __a : int ) -> str:
"""simple docstring"""
__lowercase : List[Any] = os.path.basename(__a )
if len(__a ) > max_length and max_length > 0:
__lowercase : int = os.path.dirname(__a )
__lowercase : List[str] = str(hash(__a ) )
__lowercase : Optional[Any] = filename[: max_length - len(__a ) - 8] + """...""" + hashed_filename + """.lock"""
return os.path.join(__a , __a )
else:
return path
class lowerCAmelCase ( __a ):
'''simple docstring'''
def __init__( self : Union[str, Any] , __a : List[Any] , __a : Optional[int]=-1 , __a : Tuple=None ) -> List[Any]:
"""simple docstring"""
from .file_utils import relative_to_absolute_path
super().__init__(__a , timeout=__a , max_filename_length=__a )
__lowercase : Tuple = """\\\\?\\""" + relative_to_absolute_path(self.lock_file )
def lowerCAmelCase ( self : Dict ) -> Union[str, Any]:
"""simple docstring"""
__lowercase : List[str] = os.O_RDWR | os.O_CREAT | os.O_TRUNC
try:
__lowercase : Tuple = os.open(self._lock_file , __a )
except OSError:
pass
else:
try:
msvcrt.locking(__a , msvcrt.LK_NBLCK , 1 )
except OSError:
os.close(__a )
else:
__lowercase : Union[str, Any] = fd
return None
def lowerCAmelCase ( self : Any ) -> List[Any]:
"""simple docstring"""
__lowercase : Optional[Any] = self._lock_file_fd
__lowercase : int = None
msvcrt.locking(__a , msvcrt.LK_UNLCK , 1 )
os.close(__a )
try:
os.remove(self._lock_file )
# Probably another instance of the application
# that acquired the file lock.
except OSError:
pass
return None
class lowerCAmelCase ( __a ):
'''simple docstring'''
def __init__( self : List[str] , __a : Optional[Any] , __a : str=-1 , __a : List[str]=None ) -> Any:
"""simple docstring"""
__lowercase : Dict = os.statvfs(os.path.dirname(__a ) ).f_namemax
super().__init__(__a , timeout=__a , max_filename_length=__a )
def lowerCAmelCase ( self : Optional[Any] ) -> Dict:
"""simple docstring"""
__lowercase : List[Any] = os.O_RDWR | os.O_CREAT | os.O_TRUNC
__lowercase : List[str] = os.open(self._lock_file , __a )
try:
fcntl.flock(__a , fcntl.LOCK_EX | fcntl.LOCK_NB )
except OSError:
os.close(__a )
else:
__lowercase : str = fd
return None
def lowerCAmelCase ( self : List[Any] ) -> Optional[int]:
"""simple docstring"""
__lowercase : Any = self._lock_file_fd
__lowercase : List[str] = None
fcntl.flock(__a , fcntl.LOCK_UN )
os.close(__a )
return None
class lowerCAmelCase ( __a ):
'''simple docstring'''
def lowerCAmelCase ( self : List[str] ) -> Union[str, Any]:
"""simple docstring"""
__lowercase : Tuple = os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC
try:
__lowercase : Union[str, Any] = os.open(self._lock_file , __a )
except OSError:
pass
else:
__lowercase : Optional[int] = fd
return None
def lowerCAmelCase ( self : List[str] ) -> Tuple:
"""simple docstring"""
os.close(self._lock_file_fd )
__lowercase : int = None
try:
os.remove(self._lock_file )
# The file is already deleted and that's what we want.
except OSError:
pass
return None
lowerCamelCase : Optional[Any] = None
if msvcrt:
lowerCamelCase : List[Any] = WindowsFileLock
elif fcntl:
lowerCamelCase : List[Any] = UnixFileLock
else:
lowerCamelCase : Union[str, Any] = SoftFileLock
if warnings is not None:
warnings.warn('''only soft file lock is available''') | 649 | 1 |
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class __lowercase (__SCREAMING_SNAKE_CASE ):
"""simple docstring"""
_UpperCAmelCase = """ClapFeatureExtractor"""
_UpperCAmelCase = ("""RobertaTokenizer""", """RobertaTokenizerFast""")
def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ ):
"""simple docstring"""
super().__init__(lowerCAmelCase__ , lowerCAmelCase__ )
def __call__( self , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__=None , **lowerCAmelCase__ ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Any = kwargs.pop('sampling_rate' , lowerCAmelCase__ )
if text is None and audios is None:
raise ValueError('You have to specify either text or audios. Both cannot be none.' )
if text is not None:
SCREAMING_SNAKE_CASE_ : Union[str, Any] = self.tokenizer(lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , **lowerCAmelCase__ )
if audios is not None:
SCREAMING_SNAKE_CASE_ : Tuple = self.feature_extractor(
lowerCAmelCase__ , sampling_rate=lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , **lowerCAmelCase__ )
if text is not None and audios is not None:
SCREAMING_SNAKE_CASE_ : Union[str, Any] = audio_features.input_features
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**lowerCAmelCase__ ) , tensor_type=lowerCAmelCase__ )
def UpperCamelCase__ ( self , *lowerCAmelCase__ , **lowerCAmelCase__ ):
"""simple docstring"""
return self.tokenizer.batch_decode(*lowerCAmelCase__ , **lowerCAmelCase__ )
def UpperCamelCase__ ( self , *lowerCAmelCase__ , **lowerCAmelCase__ ):
"""simple docstring"""
return self.tokenizer.decode(*lowerCAmelCase__ , **lowerCAmelCase__ )
@property
def UpperCamelCase__ ( self ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : str = self.tokenizer.model_input_names
SCREAMING_SNAKE_CASE_ : List[str] = self.feature_extractor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names ) )
| 101 |
import os
import unittest
from transformers import MobileBertTokenizer, MobileBertTokenizerFast
from transformers.models.bert.tokenization_bert import (
VOCAB_FILES_NAMES,
BasicTokenizer,
WordpieceTokenizer,
_is_control,
_is_punctuation,
_is_whitespace,
)
from transformers.testing_utils import require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english
@require_tokenizers
class lowerCamelCase_ ( lowerCamelCase , unittest.TestCase ):
a__ = MobileBertTokenizer
a__ = MobileBertTokenizerFast
a__ = True
a__ = True
a__ = filter_non_english
a__ = '''google/mobilebert-uncased'''
def A ( self ):
"""simple docstring"""
super().setUp()
__magic_name__ :Tuple = [
'''[UNK]''',
'''[CLS]''',
'''[SEP]''',
'''[PAD]''',
'''[MASK]''',
'''want''',
'''##want''',
'''##ed''',
'''wa''',
'''un''',
'''runn''',
'''##ing''',
''',''',
'''low''',
'''lowest''',
]
__magic_name__ :Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer:
vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) )
__magic_name__ :List[str] = [
(tokenizer_def[0], self.pre_trained_model_path, tokenizer_def[2]) # else the 'google/' prefix is stripped
for tokenizer_def in self.tokenizers_list
]
def A ( self , __lowerCAmelCase ):
"""simple docstring"""
__magic_name__ :Union[str, Any] = '''UNwant\u00E9d,running'''
__magic_name__ :int = '''unwanted, running'''
return input_text, output_text
def A ( self ):
"""simple docstring"""
__magic_name__ :Optional[int] = self.tokenizer_class(self.vocab_file )
__magic_name__ :List[Any] = tokenizer.tokenize('''UNwant\u00E9d,running''' )
self.assertListEqual(__lowerCAmelCase , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCAmelCase ) , [9, 6, 7, 1_2, 1_0, 1_1] )
def A ( self ):
"""simple docstring"""
if not self.test_rust_tokenizer:
return
__magic_name__ :int = self.get_tokenizer()
__magic_name__ :Tuple = self.get_rust_tokenizer()
__magic_name__ :List[str] = '''UNwant\u00E9d,running'''
__magic_name__ :Optional[Any] = tokenizer.tokenize(__lowerCAmelCase )
__magic_name__ :List[Any] = rust_tokenizer.tokenize(__lowerCAmelCase )
self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase )
__magic_name__ :int = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase )
__magic_name__ :str = rust_tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase )
self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase )
__magic_name__ :List[Any] = self.get_rust_tokenizer()
__magic_name__ :Any = tokenizer.encode(__lowerCAmelCase )
__magic_name__ :Any = rust_tokenizer.encode(__lowerCAmelCase )
self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase )
# With lower casing
__magic_name__ :Any = self.get_tokenizer(do_lower_case=__lowerCAmelCase )
__magic_name__ :List[Any] = self.get_rust_tokenizer(do_lower_case=__lowerCAmelCase )
__magic_name__ :Dict = '''UNwant\u00E9d,running'''
__magic_name__ :Tuple = tokenizer.tokenize(__lowerCAmelCase )
__magic_name__ :Union[str, Any] = rust_tokenizer.tokenize(__lowerCAmelCase )
self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase )
__magic_name__ :Optional[Any] = tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase )
__magic_name__ :Dict = rust_tokenizer.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase )
self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase )
__magic_name__ :Tuple = self.get_rust_tokenizer()
__magic_name__ :Dict = tokenizer.encode(__lowerCAmelCase )
__magic_name__ :List[Any] = rust_tokenizer.encode(__lowerCAmelCase )
self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase )
def A ( self ):
"""simple docstring"""
__magic_name__ :Optional[int] = BasicTokenizer()
self.assertListEqual(tokenizer.tokenize('''ah\u535A\u63A8zz''' ) , ['''ah''', '''\u535A''', '''\u63A8''', '''zz'''] )
def A ( self ):
"""simple docstring"""
__magic_name__ :List[Any] = BasicTokenizer(do_lower_case=__lowerCAmelCase )
self.assertListEqual(
tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] )
self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] )
def A ( self ):
"""simple docstring"""
__magic_name__ :Union[str, Any] = BasicTokenizer(do_lower_case=__lowerCAmelCase , strip_accents=__lowerCAmelCase )
self.assertListEqual(
tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hällo''', '''!''', '''how''', '''are''', '''you''', '''?'''] )
self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''h\u00E9llo'''] )
def A ( self ):
"""simple docstring"""
__magic_name__ :Dict = BasicTokenizer(do_lower_case=__lowerCAmelCase , strip_accents=__lowerCAmelCase )
self.assertListEqual(
tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] )
self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] )
def A ( self ):
"""simple docstring"""
__magic_name__ :Optional[int] = BasicTokenizer(do_lower_case=__lowerCAmelCase )
self.assertListEqual(
tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''hallo''', '''!''', '''how''', '''are''', '''you''', '''?'''] )
self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''hello'''] )
def A ( self ):
"""simple docstring"""
__magic_name__ :List[str] = BasicTokenizer(do_lower_case=__lowerCAmelCase )
self.assertListEqual(
tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] )
def A ( self ):
"""simple docstring"""
__magic_name__ :int = BasicTokenizer(do_lower_case=__lowerCAmelCase , strip_accents=__lowerCAmelCase )
self.assertListEqual(
tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HäLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] )
def A ( self ):
"""simple docstring"""
__magic_name__ :Optional[int] = BasicTokenizer(do_lower_case=__lowerCAmelCase , strip_accents=__lowerCAmelCase )
self.assertListEqual(
tokenizer.tokenize(''' \tHäLLo!how \n Are yoU? ''' ) , ['''HaLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] )
def A ( self ):
"""simple docstring"""
__magic_name__ :Optional[Any] = BasicTokenizer(do_lower_case=__lowerCAmelCase , never_split=['''[UNK]'''] )
self.assertListEqual(
tokenizer.tokenize(''' \tHeLLo!how \n Are yoU? [UNK]''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?''', '''[UNK]'''] )
def A ( self ):
"""simple docstring"""
__magic_name__ :int = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''']
__magic_name__ :Union[str, Any] = {}
for i, token in enumerate(__lowerCAmelCase ):
__magic_name__ :Tuple = i
__magic_name__ :List[Any] = WordpieceTokenizer(vocab=__lowerCAmelCase , unk_token='''[UNK]''' )
self.assertListEqual(tokenizer.tokenize('''''' ) , [] )
self.assertListEqual(tokenizer.tokenize('''unwanted running''' ) , ['''un''', '''##want''', '''##ed''', '''runn''', '''##ing'''] )
self.assertListEqual(tokenizer.tokenize('''unwantedX running''' ) , ['''[UNK]''', '''runn''', '''##ing'''] )
def A ( self ):
"""simple docstring"""
self.assertTrue(_is_whitespace(''' ''' ) )
self.assertTrue(_is_whitespace('''\t''' ) )
self.assertTrue(_is_whitespace('''\r''' ) )
self.assertTrue(_is_whitespace('''\n''' ) )
self.assertTrue(_is_whitespace('''\u00A0''' ) )
self.assertFalse(_is_whitespace('''A''' ) )
self.assertFalse(_is_whitespace('''-''' ) )
def A ( self ):
"""simple docstring"""
self.assertTrue(_is_control('''\u0005''' ) )
self.assertFalse(_is_control('''A''' ) )
self.assertFalse(_is_control(''' ''' ) )
self.assertFalse(_is_control('''\t''' ) )
self.assertFalse(_is_control('''\r''' ) )
def A ( self ):
"""simple docstring"""
self.assertTrue(_is_punctuation('''-''' ) )
self.assertTrue(_is_punctuation('''$''' ) )
self.assertTrue(_is_punctuation('''`''' ) )
self.assertTrue(_is_punctuation('''.''' ) )
self.assertFalse(_is_punctuation('''A''' ) )
self.assertFalse(_is_punctuation(''' ''' ) )
def A ( self ):
"""simple docstring"""
__magic_name__ :Any = self.get_tokenizer()
__magic_name__ :Any = self.get_rust_tokenizer()
# Example taken from the issue https://github.com/huggingface/tokenizers/issues/340
self.assertListEqual([tokenizer.tokenize(__lowerCAmelCase ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] )
self.assertListEqual(
[rust_tokenizer.tokenize(__lowerCAmelCase ) for t in ['''Test''', '''\xad''', '''test''']] , [['''[UNK]'''], [], ['''[UNK]''']] )
@slow
def A ( self ):
"""simple docstring"""
__magic_name__ :Optional[int] = self.tokenizer_class.from_pretrained('''google/mobilebert-uncased''' )
__magic_name__ :Optional[int] = tokenizer.encode('''sequence builders''' , add_special_tokens=__lowerCAmelCase )
__magic_name__ :List[Any] = tokenizer.encode('''multi-sequence build''' , add_special_tokens=__lowerCAmelCase )
__magic_name__ :Union[str, Any] = tokenizer.build_inputs_with_special_tokens(__lowerCAmelCase )
__magic_name__ :List[Any] = tokenizer.build_inputs_with_special_tokens(__lowerCAmelCase , __lowerCAmelCase )
assert encoded_sentence == [1_0_1] + text + [1_0_2]
assert encoded_pair == [1_0_1] + text + [1_0_2] + text_a + [1_0_2]
def A ( self ):
"""simple docstring"""
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ):
__magic_name__ :Optional[Any] = self.rust_tokenizer_class.from_pretrained(__lowerCAmelCase , **__lowerCAmelCase )
__magic_name__ :Optional[int] = F'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.'''
__magic_name__ :Optional[Any] = tokenizer_r.encode_plus(
__lowerCAmelCase , return_attention_mask=__lowerCAmelCase , return_token_type_ids=__lowerCAmelCase , return_offsets_mapping=__lowerCAmelCase , add_special_tokens=__lowerCAmelCase , )
__magic_name__ :Any = tokenizer_r.do_lower_case if hasattr(__lowerCAmelCase , '''do_lower_case''' ) else False
__magic_name__ :Optional[int] = (
[
((0, 0), tokenizer_r.cls_token),
((0, 1), '''A'''),
((1, 2), ''','''),
((3, 5), '''na'''),
((5, 6), '''##ï'''),
((6, 8), '''##ve'''),
((9, 1_5), tokenizer_r.mask_token),
((1_6, 2_1), '''Allen'''),
((2_1, 2_3), '''##NL'''),
((2_3, 2_4), '''##P'''),
((2_5, 3_3), '''sentence'''),
((3_3, 3_4), '''.'''),
((0, 0), tokenizer_r.sep_token),
]
if not do_lower_case
else [
((0, 0), tokenizer_r.cls_token),
((0, 1), '''a'''),
((1, 2), ''','''),
((3, 8), '''naive'''),
((9, 1_5), tokenizer_r.mask_token),
((1_6, 2_1), '''allen'''),
((2_1, 2_3), '''##nl'''),
((2_3, 2_4), '''##p'''),
((2_5, 3_3), '''sentence'''),
((3_3, 3_4), '''.'''),
((0, 0), tokenizer_r.sep_token),
]
)
self.assertEqual(
[e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens['''input_ids'''] ) )
self.assertEqual([e[0] for e in expected_results] , tokens['''offset_mapping'''] )
def A ( self ):
"""simple docstring"""
__magic_name__ :Dict = ['''的''', '''人''', '''有''']
__magic_name__ :Any = ''''''.join(__lowerCAmelCase )
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ):
__magic_name__ :Optional[Any] = True
__magic_name__ :Optional[int] = self.tokenizer_class.from_pretrained(__lowerCAmelCase , **__lowerCAmelCase )
__magic_name__ :Tuple = self.rust_tokenizer_class.from_pretrained(__lowerCAmelCase , **__lowerCAmelCase )
__magic_name__ :Dict = tokenizer_p.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase )
__magic_name__ :List[str] = tokenizer_r.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase )
__magic_name__ :Dict = tokenizer_r.convert_ids_to_tokens(__lowerCAmelCase )
__magic_name__ :Union[str, Any] = tokenizer_p.convert_ids_to_tokens(__lowerCAmelCase )
# it is expected that each Chinese character is not preceded by "##"
self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase )
self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase )
__magic_name__ :List[str] = False
__magic_name__ :Tuple = self.rust_tokenizer_class.from_pretrained(__lowerCAmelCase , **__lowerCAmelCase )
__magic_name__ :List[str] = self.tokenizer_class.from_pretrained(__lowerCAmelCase , **__lowerCAmelCase )
__magic_name__ :Optional[Any] = tokenizer_r.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase )
__magic_name__ :Union[str, Any] = tokenizer_p.encode(__lowerCAmelCase , add_special_tokens=__lowerCAmelCase )
__magic_name__ :List[str] = tokenizer_r.convert_ids_to_tokens(__lowerCAmelCase )
__magic_name__ :Optional[int] = tokenizer_p.convert_ids_to_tokens(__lowerCAmelCase )
# it is expected that only the first Chinese character is not preceded by "##".
__magic_name__ :Dict = [
F'''##{token}''' if idx != 0 else token for idx, token in enumerate(__lowerCAmelCase )
]
self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase )
self.assertListEqual(__lowerCAmelCase , __lowerCAmelCase )
| 0 | 0 |
from __future__ import annotations
import inspect
import unittest
from typing import List, Tuple
from transformers import RegNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel
if is_vision_available():
from PIL import Image
from transformers import AutoImageProcessor
class _a :
'''simple docstring'''
def __init__( self , __UpperCAmelCase , __UpperCAmelCase=3 , __UpperCAmelCase=32 , __UpperCAmelCase=3 , __UpperCAmelCase=10 , __UpperCAmelCase=[10, 20, 30, 40] , __UpperCAmelCase=[1, 1, 2, 1] , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase="relu" , __UpperCAmelCase=3 , __UpperCAmelCase=None , ):
__A : List[str] = parent
__A : Any = batch_size
__A : List[str] = image_size
__A : List[str] = num_channels
__A : Dict = embeddings_size
__A : int = hidden_sizes
__A : str = depths
__A : Tuple = is_training
__A : Union[str, Any] = use_labels
__A : Any = hidden_act
__A : int = num_labels
__A : str = scope
__A : Any = len(__UpperCAmelCase )
def __UpperCAmelCase( self ):
__A : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
__A : Union[str, Any] = None
if self.use_labels:
__A : Optional[int] = ids_tensor([self.batch_size] , self.num_labels )
__A : int = self.get_config()
return config, pixel_values, labels
def __UpperCAmelCase( self ):
return RegNetConfig(
num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , )
def __UpperCAmelCase( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ):
__A : Optional[Any] = TFRegNetModel(config=__UpperCAmelCase )
__A : int = model(__UpperCAmelCase , training=__UpperCAmelCase )
# expected last hidden states: B, C, H // 32, W // 32
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , )
def __UpperCAmelCase( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ):
__A : Optional[int] = self.num_labels
__A : Optional[int] = TFRegNetForImageClassification(__UpperCAmelCase )
__A : int = model(__UpperCAmelCase , labels=__UpperCAmelCase , training=__UpperCAmelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def __UpperCAmelCase( self ):
__A : int = self.prepare_config_and_inputs()
__A : str = config_and_inputs
__A : str = {"pixel_values": pixel_values}
return config, inputs_dict
@require_tf
class _a ( lowerCAmelCase__ , lowerCAmelCase__ , unittest.TestCase ):
'''simple docstring'''
lowerCamelCase_ : List[str] = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
lowerCamelCase_ : Optional[Any] = (
{"""feature-extraction""": TFRegNetModel, """image-classification""": TFRegNetForImageClassification}
if is_tf_available()
else {}
)
lowerCamelCase_ : List[str] = False
lowerCamelCase_ : List[Any] = False
lowerCamelCase_ : Dict = False
lowerCamelCase_ : Optional[int] = False
lowerCamelCase_ : Optional[int] = False
def __UpperCAmelCase( self ):
__A : Any = TFRegNetModelTester(self )
__A : Optional[int] = ConfigTester(self , config_class=__UpperCAmelCase , has_text_modality=__UpperCAmelCase )
def __UpperCAmelCase( self ):
return
@unittest.skip(reason="RegNet does not use inputs_embeds" )
def __UpperCAmelCase( self ):
pass
@unittest.skipIf(
not is_tf_available() or len(tf.config.list_physical_devices("GPU" ) ) == 0 , reason="TF does not support backprop for grouped convolutions on CPU." , )
@slow
def __UpperCAmelCase( self ):
super().test_keras_fit()
@unittest.skip(reason="RegNet does not support input and output embeddings" )
def __UpperCAmelCase( self ):
pass
def __UpperCAmelCase( self ):
__A : Dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__A : List[str] = model_class(__UpperCAmelCase )
__A : List[Any] = inspect.signature(model.call )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__A : Optional[int] = [*signature.parameters.keys()]
__A : Tuple = ["pixel_values"]
self.assertListEqual(arg_names[:1] , __UpperCAmelCase )
def __UpperCAmelCase( self ):
__A : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*__UpperCAmelCase )
def __UpperCAmelCase( self ):
def check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ):
__A : Any = model_class(__UpperCAmelCase )
__A : int = model(**self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase ) , training=__UpperCAmelCase )
__A : str = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
__A : List[Any] = self.model_tester.num_stages
self.assertEqual(len(__UpperCAmelCase ) , expected_num_stages + 1 )
# RegNet's feature maps are of shape (batch_size, num_channels, height, width)
self.assertListEqual(
list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , )
__A : Any = self.model_tester.prepare_config_and_inputs_for_common()
__A : List[str] = ["basic", "bottleneck"]
for model_class in self.all_model_classes:
for layer_type in layers_type:
__A : Union[str, Any] = layer_type
__A : str = True
check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
__A : Optional[int] = True
check_hidden_states_output(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
def __UpperCAmelCase( self ):
__A : Any = self.model_tester.prepare_config_and_inputs_for_common()
def check_equivalence(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase={} ):
__A : Optional[int] = model(__UpperCAmelCase , return_dict=__UpperCAmelCase , **__UpperCAmelCase )
__A : int = model(__UpperCAmelCase , return_dict=__UpperCAmelCase , **__UpperCAmelCase ).to_tuple()
def recursive_check(__UpperCAmelCase , __UpperCAmelCase ):
if isinstance(__UpperCAmelCase , (List, Tuple) ):
for tuple_iterable_value, dict_iterable_value in zip(__UpperCAmelCase , __UpperCAmelCase ):
recursive_check(__UpperCAmelCase , __UpperCAmelCase )
elif tuple_object is None:
return
else:
self.assertTrue(
all(tf.equal(__UpperCAmelCase , __UpperCAmelCase ) ) , msg=(
"Tuple and dict output are not equal. Difference:"
F" {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}"
) , )
recursive_check(__UpperCAmelCase , __UpperCAmelCase )
for model_class in self.all_model_classes:
__A : Union[str, Any] = model_class(__UpperCAmelCase )
__A : Union[str, Any] = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase )
__A : Dict = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase )
check_equivalence(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
__A : int = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase , return_labels=__UpperCAmelCase )
__A : Optional[Any] = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase , return_labels=__UpperCAmelCase )
check_equivalence(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
__A : str = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase )
__A : List[str] = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase )
check_equivalence(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , {"output_hidden_states": True} )
__A : Tuple = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase , return_labels=__UpperCAmelCase )
__A : str = self._prepare_for_class(__UpperCAmelCase , __UpperCAmelCase , return_labels=__UpperCAmelCase )
check_equivalence(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , {"output_hidden_states": True} )
def __UpperCAmelCase( self ):
__A : List[str] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase )
@slow
def __UpperCAmelCase( self ):
for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__A : Optional[Any] = TFRegNetModel.from_pretrained(__UpperCAmelCase )
self.assertIsNotNone(__UpperCAmelCase )
def lowerCamelCase_ ( ) -> Optional[Any]:
__A : List[str] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
return image
@require_tf
@require_vision
class _a ( unittest.TestCase ):
'''simple docstring'''
@cached_property
def __UpperCAmelCase( self ):
return (
AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] )
if is_vision_available()
else None
)
@slow
def __UpperCAmelCase( self ):
__A : Tuple = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] )
__A : str = self.default_image_processor
__A : List[str] = prepare_img()
__A : Any = image_processor(images=__UpperCAmelCase , return_tensors="tf" )
# forward pass
__A : Tuple = model(**__UpperCAmelCase , training=__UpperCAmelCase )
# verify the logits
__A : List[Any] = tf.TensorShape((1, 1_000) )
self.assertEqual(outputs.logits.shape , __UpperCAmelCase )
__A : Tuple = tf.constant([-0.41_80, -1.50_51, -3.48_36] )
tf.debugging.assert_near(outputs.logits[0, :3] , __UpperCAmelCase , atol=1e-4 )
| 714 | import inspect
from typing import Callable, List, Optional, Union
import torch
from transformers import (
CLIPImageProcessor,
CLIPTextModel,
CLIPTokenizer,
WhisperForConditionalGeneration,
WhisperProcessor,
)
from diffusers import (
AutoencoderKL,
DDIMScheduler,
DiffusionPipeline,
LMSDiscreteScheduler,
PNDMScheduler,
UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.utils import logging
UpperCamelCase = logging.get_logger(__name__) # pylint: disable=invalid-name
class _a ( lowerCAmelCase__ ):
'''simple docstring'''
def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ):
super().__init__()
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(
speech_model=__UpperCAmelCase , speech_processor=__UpperCAmelCase , vae=__UpperCAmelCase , text_encoder=__UpperCAmelCase , tokenizer=__UpperCAmelCase , unet=__UpperCAmelCase , scheduler=__UpperCAmelCase , feature_extractor=__UpperCAmelCase , )
def __UpperCAmelCase( self , __UpperCAmelCase = "auto" ):
if slice_size == "auto":
__A : int = self.unet.config.attention_head_dim // 2
self.unet.set_attention_slice(__UpperCAmelCase )
def __UpperCAmelCase( self ):
self.enable_attention_slicing(__UpperCAmelCase )
@torch.no_grad()
def __call__( self , __UpperCAmelCase , __UpperCAmelCase=16_000 , __UpperCAmelCase = 512 , __UpperCAmelCase = 512 , __UpperCAmelCase = 50 , __UpperCAmelCase = 7.5 , __UpperCAmelCase = None , __UpperCAmelCase = 1 , __UpperCAmelCase = 0.0 , __UpperCAmelCase = None , __UpperCAmelCase = None , __UpperCAmelCase = "pil" , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = 1 , **__UpperCAmelCase , ):
__A : List[str] = self.speech_processor.feature_extractor(
__UpperCAmelCase , return_tensors="pt" , sampling_rate=__UpperCAmelCase ).input_features.to(self.device )
__A : Any = self.speech_model.generate(__UpperCAmelCase , max_length=480_000 )
__A : List[str] = self.speech_processor.tokenizer.batch_decode(__UpperCAmelCase , skip_special_tokens=__UpperCAmelCase , normalize=__UpperCAmelCase )[
0
]
if isinstance(__UpperCAmelCase , __UpperCAmelCase ):
__A : Optional[Any] = 1
elif isinstance(__UpperCAmelCase , __UpperCAmelCase ):
__A : Dict = len(__UpperCAmelCase )
else:
raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(__UpperCAmelCase )}" )
if height % 8 != 0 or width % 8 != 0:
raise ValueError(F"`height` and `width` have to be divisible by 8 but are {height} and {width}." )
if (callback_steps is None) or (
callback_steps is not None and (not isinstance(__UpperCAmelCase , __UpperCAmelCase ) or callback_steps <= 0)
):
raise ValueError(
F"`callback_steps` has to be a positive integer but is {callback_steps} of type"
F" {type(__UpperCAmelCase )}." )
# get prompt text embeddings
__A : Optional[int] = self.tokenizer(
__UpperCAmelCase , padding="max_length" , max_length=self.tokenizer.model_max_length , return_tensors="pt" , )
__A : int = text_inputs.input_ids
if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
__A : List[str] = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] )
logger.warning(
"The following part of your input was truncated because CLIP can only handle sequences up to"
F" {self.tokenizer.model_max_length} tokens: {removed_text}" )
__A : Dict = text_input_ids[:, : self.tokenizer.model_max_length]
__A : int = self.text_encoder(text_input_ids.to(self.device ) )[0]
# duplicate text embeddings for each generation per prompt, using mps friendly method
__A , __A , __A : str = text_embeddings.shape
__A : Optional[int] = text_embeddings.repeat(1 , __UpperCAmelCase , 1 )
__A : List[str] = text_embeddings.view(bs_embed * num_images_per_prompt , __UpperCAmelCase , -1 )
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
# corresponds to doing no classifier free guidance.
__A : Dict = guidance_scale > 1.0
# get unconditional embeddings for classifier free guidance
if do_classifier_free_guidance:
__A : List[str]
if negative_prompt is None:
__A : Dict = [""] * batch_size
elif type(__UpperCAmelCase ) is not type(__UpperCAmelCase ):
raise TypeError(
F"`negative_prompt` should be the same type to `prompt`, but got {type(__UpperCAmelCase )} !="
F" {type(__UpperCAmelCase )}." )
elif isinstance(__UpperCAmelCase , __UpperCAmelCase ):
__A : Any = [negative_prompt]
elif batch_size != len(__UpperCAmelCase ):
raise ValueError(
F"`negative_prompt`: {negative_prompt} has batch size {len(__UpperCAmelCase )}, but `prompt`:"
F" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
" the batch size of `prompt`." )
else:
__A : int = negative_prompt
__A : int = text_input_ids.shape[-1]
__A : Any = self.tokenizer(
__UpperCAmelCase , padding="max_length" , max_length=__UpperCAmelCase , truncation=__UpperCAmelCase , return_tensors="pt" , )
__A : int = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0]
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
__A : Union[str, Any] = uncond_embeddings.shape[1]
__A : List[str] = uncond_embeddings.repeat(1 , __UpperCAmelCase , 1 )
__A : int = uncond_embeddings.view(batch_size * num_images_per_prompt , __UpperCAmelCase , -1 )
# For classifier free guidance, we need to do two forward passes.
# Here we concatenate the unconditional and text embeddings into a single batch
# to avoid doing two forward passes
__A : Optional[int] = torch.cat([uncond_embeddings, text_embeddings] )
# get the initial random noise unless the user supplied it
# Unlike in other pipelines, latents need to be generated in the target device
# for 1-to-1 results reproducibility with the CompVis implementation.
# However this currently doesn't work in `mps`.
__A : Dict = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
__A : Any = text_embeddings.dtype
if latents is None:
if self.device.type == "mps":
# randn does not exist on mps
__A : Tuple = torch.randn(__UpperCAmelCase , generator=__UpperCAmelCase , device="cpu" , dtype=__UpperCAmelCase ).to(
self.device )
else:
__A : List[Any] = torch.randn(__UpperCAmelCase , generator=__UpperCAmelCase , device=self.device , dtype=__UpperCAmelCase )
else:
if latents.shape != latents_shape:
raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {latents_shape}" )
__A : Tuple = latents.to(self.device )
# set timesteps
self.scheduler.set_timesteps(__UpperCAmelCase )
# Some schedulers like PNDM have timesteps as arrays
# It's more optimized to move all timesteps to correct device beforehand
__A : Optional[int] = self.scheduler.timesteps.to(self.device )
# scale the initial noise by the standard deviation required by the scheduler
__A : Tuple = latents * self.scheduler.init_noise_sigma
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
# and should be between [0, 1]
__A : Any = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() )
__A : List[str] = {}
if accepts_eta:
__A : Tuple = eta
for i, t in enumerate(self.progress_bar(__UpperCAmelCase ) ):
# expand the latents if we are doing classifier free guidance
__A : Union[str, Any] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents
__A : Dict = self.scheduler.scale_model_input(__UpperCAmelCase , __UpperCAmelCase )
# predict the noise residual
__A : List[Any] = self.unet(__UpperCAmelCase , __UpperCAmelCase , encoder_hidden_states=__UpperCAmelCase ).sample
# perform guidance
if do_classifier_free_guidance:
__A , __A : str = noise_pred.chunk(2 )
__A : str = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
# compute the previous noisy sample x_t -> x_t-1
__A : Union[str, Any] = self.scheduler.step(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase ).prev_sample
# call the callback, if provided
if callback is not None and i % callback_steps == 0:
callback(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
__A : int = 1 / 0.1_82_15 * latents
__A : Union[str, Any] = self.vae.decode(__UpperCAmelCase ).sample
__A : Tuple = (image / 2 + 0.5).clamp(0 , 1 )
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
__A : List[Any] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy()
if output_type == "pil":
__A : List[str] = self.numpy_to_pil(__UpperCAmelCase )
if not return_dict:
return image
return StableDiffusionPipelineOutput(images=__UpperCAmelCase , nsfw_content_detected=__UpperCAmelCase )
| 387 | 0 |
import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
UpperCAmelCase__ = logging.get_logger(__name__)
UpperCAmelCase__ = {'''vocab_file''': '''spiece.model'''}
UpperCAmelCase__ = {
'''vocab_file''': {
'''bert_for_seq_generation''': (
'''https://huggingface.co/google/bert_for_seq_generation_L-24_bbc_encoder/resolve/main/spiece.model'''
),
}
}
UpperCAmelCase__ = {'''bert_for_seq_generation''': 512}
class snake_case_ ( __UpperCamelCase ):
"""simple docstring"""
snake_case__ = VOCAB_FILES_NAMES
snake_case__ = PRETRAINED_VOCAB_FILES_MAP
snake_case__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
snake_case__ = []
snake_case__ = ["""input_ids""", """attention_mask"""]
def __init__(self: Optional[Any] , __UpperCAmelCase: List[str] , __UpperCAmelCase: List[Any]="<s>" , __UpperCAmelCase: str="</s>" , __UpperCAmelCase: int="<unk>" , __UpperCAmelCase: Dict="<pad>" , __UpperCAmelCase: str="<::::>" , __UpperCAmelCase: Optional[Dict[str, Any]] = None , **__UpperCAmelCase: Optional[int] , ) -> None:
'''simple docstring'''
__a : Optional[Any] = {} if sp_model_kwargs is None else sp_model_kwargs
# Add extra_ids to the special token list
super().__init__(
bos_token=__UpperCAmelCase , eos_token=__UpperCAmelCase , unk_token=__UpperCAmelCase , pad_token=__UpperCAmelCase , sep_token=__UpperCAmelCase , sp_model_kwargs=self.sp_model_kwargs , **__UpperCAmelCase , )
__a : Dict = vocab_file
__a : str = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(__UpperCAmelCase )
@property
def UpperCAmelCase__ (self: Any ) -> Optional[Any]:
'''simple docstring'''
return self.sp_model.get_piece_size()
def UpperCAmelCase__ (self: Any ) -> List[Any]:
'''simple docstring'''
__a : Tuple = {self.convert_ids_to_tokens(__UpperCAmelCase ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def __getstate__(self: List[str] ) -> List[str]:
'''simple docstring'''
__a : Union[str, Any] = self.__dict__.copy()
__a : Dict = None
return state
def __setstate__(self: Any , __UpperCAmelCase: Union[str, Any] ) -> Any:
'''simple docstring'''
__a : Union[str, Any] = d
# for backward compatibility
if not hasattr(self , "sp_model_kwargs" ):
__a : Dict = {}
__a : Tuple = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(self.vocab_file )
def UpperCAmelCase__ (self: List[Any] , __UpperCAmelCase: str ) -> List[str]:
'''simple docstring'''
return self.sp_model.encode(__UpperCAmelCase , out_type=__UpperCAmelCase )
def UpperCAmelCase__ (self: int , __UpperCAmelCase: Optional[Any] ) -> Union[str, Any]:
'''simple docstring'''
return self.sp_model.piece_to_id(__UpperCAmelCase )
def UpperCAmelCase__ (self: Union[str, Any] , __UpperCAmelCase: Optional[Any] ) -> Union[str, Any]:
'''simple docstring'''
__a : Union[str, Any] = self.sp_model.IdToPiece(__UpperCAmelCase )
return token
def UpperCAmelCase__ (self: List[Any] , __UpperCAmelCase: Dict ) -> Any:
'''simple docstring'''
__a : List[Any] = []
__a : Union[str, Any] = ""
for token in tokens:
# make sure that special tokens are not decoded using sentencepiece model
if token in self.all_special_tokens:
out_string += self.sp_model.decode(__UpperCAmelCase ) + token
__a : Optional[Any] = []
else:
current_sub_tokens.append(__UpperCAmelCase )
out_string += self.sp_model.decode(__UpperCAmelCase )
return out_string.strip()
def UpperCAmelCase__ (self: List[str] , __UpperCAmelCase: str , __UpperCAmelCase: Optional[str] = None ) -> Tuple[str]:
'''simple docstring'''
if not os.path.isdir(__UpperCAmelCase ):
logger.error(f'Vocabulary path ({save_directory}) should be a directory' )
return
__a : List[str] = os.path.join(
__UpperCAmelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCAmelCase ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file , __UpperCAmelCase )
elif not os.path.isfile(self.vocab_file ):
with open(__UpperCAmelCase , "wb" ) as fi:
__a : Dict = self.sp_model.serialized_model_proto()
fi.write(__UpperCAmelCase )
return (out_vocab_file,)
| 351 |
import json
import os
import unittest
from transformers import BatchEncoding, MvpTokenizer, MvpTokenizerFast
from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, require_torch
from transformers.utils import cached_property
from ...test_tokenization_common import TokenizerTesterMixin, filter_roberta_detectors
@require_tokenizers
class snake_case_ ( __UpperCamelCase , unittest.TestCase ):
"""simple docstring"""
snake_case__ = MvpTokenizer
snake_case__ = MvpTokenizerFast
snake_case__ = True
snake_case__ = filter_roberta_detectors
def UpperCAmelCase__ (self: List[str] ) -> Any:
'''simple docstring'''
super().setUp()
__a : Dict = [
"l",
"o",
"w",
"e",
"r",
"s",
"t",
"i",
"d",
"n",
"\u0120",
"\u0120l",
"\u0120n",
"\u0120lo",
"\u0120low",
"er",
"\u0120lowest",
"\u0120newer",
"\u0120wider",
"<unk>",
]
__a : Optional[int] = dict(zip(__UpperCAmelCase , range(len(__UpperCAmelCase ) ) ) )
__a : Dict = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
__a : Optional[int] = {"unk_token": "<unk>"}
__a : Tuple = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] )
__a : List[str] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["merges_file"] )
with open(self.vocab_file , "w" , encoding="utf-8" ) as fp:
fp.write(json.dumps(__UpperCAmelCase ) + "\n" )
with open(self.merges_file , "w" , encoding="utf-8" ) as fp:
fp.write("\n".join(__UpperCAmelCase ) )
def UpperCAmelCase__ (self: List[Any] , **__UpperCAmelCase: Dict ) -> int:
'''simple docstring'''
kwargs.update(self.special_tokens_map )
return self.tokenizer_class.from_pretrained(self.tmpdirname , **__UpperCAmelCase )
def UpperCAmelCase__ (self: str , **__UpperCAmelCase: Tuple ) -> Tuple:
'''simple docstring'''
kwargs.update(self.special_tokens_map )
return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **__UpperCAmelCase )
def UpperCAmelCase__ (self: Any , __UpperCAmelCase: int ) -> List[str]:
'''simple docstring'''
return "lower newer", "lower newer"
@cached_property
def UpperCAmelCase__ (self: List[Any] ) -> Union[str, Any]:
'''simple docstring'''
return MvpTokenizer.from_pretrained("RUCAIBox/mvp" )
@cached_property
def UpperCAmelCase__ (self: str ) -> List[Any]:
'''simple docstring'''
return MvpTokenizerFast.from_pretrained("RUCAIBox/mvp" )
@require_torch
def UpperCAmelCase__ (self: Dict ) -> List[Any]:
'''simple docstring'''
__a : Union[str, Any] = ["A long paragraph for summarization.", "Another paragraph for summarization."]
__a : List[Any] = [0, 250, 251, 17818, 13, 39186, 1938, 4, 2]
for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
__a : Optional[Any] = tokenizer(__UpperCAmelCase , max_length=len(__UpperCAmelCase ) , padding=__UpperCAmelCase , return_tensors="pt" )
self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase )
self.assertEqual((2, 9) , batch.input_ids.shape )
self.assertEqual((2, 9) , batch.attention_mask.shape )
__a : Optional[int] = batch.input_ids.tolist()[0]
self.assertListEqual(__UpperCAmelCase , __UpperCAmelCase )
# Test that special tokens are reset
@require_torch
def UpperCAmelCase__ (self: Optional[int] ) -> List[Any]:
'''simple docstring'''
__a : int = ["A long paragraph for summarization.", "Another paragraph for summarization."]
for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
__a : int = tokenizer(__UpperCAmelCase , padding=__UpperCAmelCase , return_tensors="pt" )
# check if input_ids are returned and no labels
self.assertIn("input_ids" , __UpperCAmelCase )
self.assertIn("attention_mask" , __UpperCAmelCase )
self.assertNotIn("labels" , __UpperCAmelCase )
self.assertNotIn("decoder_attention_mask" , __UpperCAmelCase )
@require_torch
def UpperCAmelCase__ (self: Any ) -> Union[str, Any]:
'''simple docstring'''
__a : List[Any] = [
"Summary of the text.",
"Another summary.",
]
for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
__a : int = tokenizer(text_target=__UpperCAmelCase , max_length=32 , padding="max_length" , return_tensors="pt" )
self.assertEqual(32 , targets["input_ids"].shape[1] )
@require_torch
def UpperCAmelCase__ (self: int ) -> Union[str, Any]:
'''simple docstring'''
for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
__a : str = tokenizer(
["I am a small frog" * 1024, "I am a small frog"] , padding=__UpperCAmelCase , truncation=__UpperCAmelCase , return_tensors="pt" )
self.assertIsInstance(__UpperCAmelCase , __UpperCAmelCase )
self.assertEqual(batch.input_ids.shape , (2, 1024) )
@require_torch
def UpperCAmelCase__ (self: str ) -> Any:
'''simple docstring'''
__a : Optional[int] = ["A long paragraph for summarization."]
__a : Tuple = [
"Summary of the text.",
]
for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
__a : Dict = tokenizer(__UpperCAmelCase , text_target=__UpperCAmelCase , return_tensors="pt" )
__a : str = inputs["input_ids"]
__a : Optional[Any] = inputs["labels"]
self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item() )
self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item() )
self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item() )
self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item() )
def UpperCAmelCase__ (self: Dict ) -> str:
'''simple docstring'''
pass
def UpperCAmelCase__ (self: Any ) -> Optional[Any]:
'''simple docstring'''
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(f'{tokenizer.__class__.__name__} ({pretrained_name})' ):
__a : Tuple = self.rust_tokenizer_class.from_pretrained(__UpperCAmelCase , **__UpperCAmelCase )
__a : List[Any] = self.tokenizer_class.from_pretrained(__UpperCAmelCase , **__UpperCAmelCase )
__a : Tuple = "A, <mask> AllenNLP sentence."
__a : Dict = tokenizer_r.encode_plus(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase , return_token_type_ids=__UpperCAmelCase )
__a : List[Any] = tokenizer_p.encode_plus(__UpperCAmelCase , add_special_tokens=__UpperCAmelCase , return_token_type_ids=__UpperCAmelCase )
# token_type_ids should put 0 everywhere
self.assertEqual(sum(tokens_r["token_type_ids"] ) , sum(tokens_p["token_type_ids"] ) )
# attention_mask should put 1 everywhere, so sum over length should be 1
self.assertEqual(
sum(tokens_r["attention_mask"] ) / len(tokens_r["attention_mask"] ) , sum(tokens_p["attention_mask"] ) / len(tokens_p["attention_mask"] ) , )
__a : Optional[int] = tokenizer_r.convert_ids_to_tokens(tokens_r["input_ids"] )
__a : Union[str, Any] = tokenizer_p.convert_ids_to_tokens(tokens_p["input_ids"] )
# Rust correctly handles the space before the mask while python doesnt
self.assertSequenceEqual(tokens_p["input_ids"] , [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2] )
self.assertSequenceEqual(tokens_r["input_ids"] , [0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2] )
self.assertSequenceEqual(
__UpperCAmelCase , ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] )
self.assertSequenceEqual(
__UpperCAmelCase , ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] )
| 351 | 1 |
'''simple docstring'''
from typing import List
import jiwer
import jiwer.transforms as tr
from packaging import version
import datasets
from datasets.config import PY_VERSION
if PY_VERSION < version.parse("""3.8"""):
import importlib_metadata
else:
import importlib.metadata as importlib_metadata
A : Tuple = """"""
if version.parse(importlib_metadata.version("""jiwer""")) < version.parse("""2.3.0"""):
class lowerCAmelCase_ ( tr.AbstractTransform ):
def __init__( self : List[Any], _snake_case : str = " " ):
'''simple docstring'''
snake_case : List[Any] =sentence_delimiter
def __snake_case ( self : Any, _snake_case : str ):
'''simple docstring'''
return list(_snake_case )
def __snake_case ( self : Tuple, _snake_case : List[str] ):
'''simple docstring'''
snake_case : List[str] =[]
for sent_idx, sentence in enumerate(_snake_case ):
chars.extend(self.process_string(_snake_case ) )
if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(_snake_case ) - 1:
chars.append(self.sentence_delimiter )
return chars
A : List[str] = tr.Compose(
[tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)]
)
else:
A : Union[str, Any] = tr.Compose(
[
tr.RemoveMultipleSpaces(),
tr.Strip(),
tr.ReduceToSingleSentence(SENTENCE_DELIMITER),
tr.ReduceToListOfListOfChars(),
]
)
A : Optional[Any] = """\
@inproceedings{inproceedings,
author = {Morris, Andrew and Maier, Viktoria and Green, Phil},
year = {2004},
month = {01},
pages = {},
title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}
}
"""
A : Optional[int] = """\
Character error rate (CER) is a common metric of the performance of an automatic speech recognition system.
CER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.
Character error rate can be computed as:
CER = (S + D + I) / N = (S + D + I) / (S + D + C)
where
S is the number of substitutions,
D is the number of deletions,
I is the number of insertions,
C is the number of correct characters,
N is the number of characters in the reference (N=S+D+C).
CER's output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the
performance of the ASR system with a CER of 0 being a perfect score.
"""
A : List[str] = """
Computes CER score of transcribed segments against references.
Args:
references: list of references for each speech input.
predictions: list of transcribtions to score.
concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.
Returns:
(float): the character error rate
Examples:
>>> predictions = [\"this is the prediction\", \"there is an other sample\"]
>>> references = [\"this is the reference\", \"there is another one\"]
>>> cer = datasets.load_metric(\"cer\")
>>> cer_score = cer.compute(predictions=predictions, references=references)
>>> print(cer_score)
0.34146341463414637
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class lowerCAmelCase_ ( datasets.Metric ):
def __snake_case ( self : Union[str, Any] ):
'''simple docstring'''
return datasets.MetricInfo(
description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features(
{
'''predictions''': datasets.Value('''string''', id='''sequence''' ),
'''references''': datasets.Value('''string''', id='''sequence''' ),
} ), codebase_urls=['''https://github.com/jitsi/jiwer/'''], reference_urls=[
'''https://en.wikipedia.org/wiki/Word_error_rate''',
'''https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates''',
], )
def __snake_case ( self : str, _snake_case : List[str], _snake_case : Dict, _snake_case : str=False ):
'''simple docstring'''
if concatenate_texts:
return jiwer.compute_measures(
_snake_case, _snake_case, truth_transform=_snake_case, hypothesis_transform=_snake_case, )["wer"]
snake_case : List[str] =0
snake_case : Optional[Any] =0
for prediction, reference in zip(_snake_case, _snake_case ):
snake_case : Union[str, Any] =jiwer.compute_measures(
_snake_case, _snake_case, truth_transform=_snake_case, hypothesis_transform=_snake_case, )
incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"]
total += measures["substitutions"] + measures["deletions"] + measures["hits"]
return incorrect / total
| 136 |
'''simple docstring'''
from ...configuration_utils import PretrainedConfig
from ...utils import logging
A : Any = logging.get_logger(__name__)
A : Optional[Any] = {}
class lowerCAmelCase_ ( a_ ):
__UpperCAmelCase = 'llama'
__UpperCAmelCase = ['past_key_values']
def __init__( self : Dict, _snake_case : Union[str, Any]=32_000, _snake_case : int=4_096, _snake_case : Dict=11_008, _snake_case : Union[str, Any]=32, _snake_case : int=32, _snake_case : List[Any]=None, _snake_case : Union[str, Any]="silu", _snake_case : Dict=2_048, _snake_case : List[str]=0.02, _snake_case : int=1E-6, _snake_case : Any=True, _snake_case : Tuple=0, _snake_case : Tuple=1, _snake_case : List[Any]=2, _snake_case : int=1, _snake_case : Optional[int]=False, _snake_case : Union[str, Any]=None, **_snake_case : List[str], ):
'''simple docstring'''
snake_case : List[Any] =vocab_size
snake_case : Union[str, Any] =max_position_embeddings
snake_case : Union[str, Any] =hidden_size
snake_case : Optional[Any] =intermediate_size
snake_case : List[str] =num_hidden_layers
snake_case : Optional[int] =num_attention_heads
# for backward compatibility
if num_key_value_heads is None:
snake_case : Optional[Any] =num_attention_heads
snake_case : List[Any] =num_key_value_heads
snake_case : Any =hidden_act
snake_case : Optional[Any] =initializer_range
snake_case : List[str] =rms_norm_eps
snake_case : Optional[Any] =pretraining_tp
snake_case : Dict =use_cache
snake_case : Union[str, Any] =rope_scaling
self._rope_scaling_validation()
super().__init__(
pad_token_id=_snake_case, bos_token_id=_snake_case, eos_token_id=_snake_case, tie_word_embeddings=_snake_case, **_snake_case, )
def __snake_case ( self : Optional[int] ):
'''simple docstring'''
if self.rope_scaling is None:
return
if not isinstance(self.rope_scaling, _snake_case ) or len(self.rope_scaling ) != 2:
raise ValueError(
'''`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, '''
f'''got {self.rope_scaling}''' )
snake_case : Tuple =self.rope_scaling.get('''type''', _snake_case )
snake_case : str =self.rope_scaling.get('''factor''', _snake_case )
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
raise ValueError(
f'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' )
if rope_scaling_factor is None or not isinstance(_snake_case, _snake_case ) or rope_scaling_factor <= 1.0:
raise ValueError(f'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
| 136 | 1 |
'''simple docstring'''
import math
import torch
from torch import nn
from ..configuration_utils import ConfigMixin, register_to_config
from .attention_processor import Attention
from .embeddings import get_timestep_embedding
from .modeling_utils import ModelMixin
class __UpperCamelCase ( lowerCamelCase__ , lowerCamelCase__ ):
@register_to_config
def __init__( self, lowerCAmelCase = 128, lowerCAmelCase = 256, lowerCAmelCase = 2_0_0_0.0, lowerCAmelCase = 768, lowerCAmelCase = 12, lowerCAmelCase = 12, lowerCAmelCase = 64, lowerCAmelCase = 2_048, lowerCAmelCase = 0.1, ):
"""simple docstring"""
super().__init__()
lowerCamelCase_ =nn.Sequential(
nn.Linear(lowerCAmelCase, d_model * 4, bias=lowerCAmelCase ), nn.SiLU(), nn.Linear(d_model * 4, d_model * 4, bias=lowerCAmelCase ), nn.SiLU(), )
lowerCamelCase_ =nn.Embedding(lowerCAmelCase, lowerCAmelCase )
lowerCamelCase_ =False
lowerCamelCase_ =nn.Linear(lowerCAmelCase, lowerCAmelCase, bias=lowerCAmelCase )
lowerCamelCase_ =nn.Dropout(p=lowerCAmelCase )
lowerCamelCase_ =nn.ModuleList()
for lyr_num in range(lowerCAmelCase ):
# FiLM conditional T5 decoder
lowerCamelCase_ =DecoderLayer(d_model=lowerCAmelCase, d_kv=lowerCAmelCase, num_heads=lowerCAmelCase, d_ff=lowerCAmelCase, dropout_rate=lowerCAmelCase )
self.decoders.append(lowerCAmelCase )
lowerCamelCase_ =TaLayerNorm(lowerCAmelCase )
lowerCamelCase_ =nn.Dropout(p=lowerCAmelCase )
lowerCamelCase_ =nn.Linear(lowerCAmelCase, lowerCAmelCase, bias=lowerCAmelCase )
def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase ):
"""simple docstring"""
lowerCamelCase_ =torch.mul(query_input.unsqueeze(-1 ), key_input.unsqueeze(-2 ) )
return mask.unsqueeze(-3 )
def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase ):
"""simple docstring"""
lowerCamelCase_, lowerCamelCase_, lowerCamelCase_ =decoder_input_tokens.shape
assert decoder_noise_time.shape == (batch,)
# decoder_noise_time is in [0, 1), so rescale to expected timing range.
lowerCamelCase_ =get_timestep_embedding(
decoder_noise_time * self.config.max_decoder_noise_time, embedding_dim=self.config.d_model, max_period=self.config.max_decoder_noise_time, ).to(dtype=self.dtype )
lowerCamelCase_ =self.conditioning_emb(lowerCAmelCase ).unsqueeze(1 )
assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4)
lowerCamelCase_ =decoder_input_tokens.shape[1]
# If we want to use relative positions for audio context, we can just offset
# this sequence by the length of encodings_and_masks.
lowerCamelCase_ =torch.broadcast_to(
torch.arange(lowerCAmelCase, device=decoder_input_tokens.device ), (batch, seq_length), )
lowerCamelCase_ =self.position_encoding(lowerCAmelCase )
lowerCamelCase_ =self.continuous_inputs_projection(lowerCAmelCase )
inputs += position_encodings
lowerCamelCase_ =self.dropout(lowerCAmelCase )
# decoder: No padding present.
lowerCamelCase_ =torch.ones(
decoder_input_tokens.shape[:2], device=decoder_input_tokens.device, dtype=inputs.dtype )
# Translate encoding masks to encoder-decoder masks.
lowerCamelCase_ =[(x, self.encoder_decoder_mask(lowerCAmelCase, lowerCAmelCase )) for x, y in encodings_and_masks]
# cross attend style: concat encodings
lowerCamelCase_ =torch.cat([x[0] for x in encodings_and_encdec_masks], dim=1 )
lowerCamelCase_ =torch.cat([x[1] for x in encodings_and_encdec_masks], dim=-1 )
for lyr in self.decoders:
lowerCamelCase_ =lyr(
lowerCAmelCase, conditioning_emb=lowerCAmelCase, encoder_hidden_states=lowerCAmelCase, encoder_attention_mask=lowerCAmelCase, )[0]
lowerCamelCase_ =self.decoder_norm(lowerCAmelCase )
lowerCamelCase_ =self.post_dropout(lowerCAmelCase )
lowerCamelCase_ =self.spec_out(lowerCAmelCase )
return spec_out
class __UpperCamelCase ( nn.Module ):
def __init__( self, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase=1e-6 ):
"""simple docstring"""
super().__init__()
lowerCamelCase_ =nn.ModuleList()
# cond self attention: layer 0
self.layer.append(
TaLayerSelfAttentionCond(d_model=lowerCAmelCase, d_kv=lowerCAmelCase, num_heads=lowerCAmelCase, dropout_rate=lowerCAmelCase ) )
# cross attention: layer 1
self.layer.append(
TaLayerCrossAttention(
d_model=lowerCAmelCase, d_kv=lowerCAmelCase, num_heads=lowerCAmelCase, dropout_rate=lowerCAmelCase, layer_norm_epsilon=lowerCAmelCase, ) )
# Film Cond MLP + dropout: last layer
self.layer.append(
TaLayerFFCond(d_model=lowerCAmelCase, d_ff=lowerCAmelCase, dropout_rate=lowerCAmelCase, layer_norm_epsilon=lowerCAmelCase ) )
def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase=None, lowerCAmelCase=None, lowerCAmelCase=None, lowerCAmelCase=None, lowerCAmelCase=None, ):
"""simple docstring"""
lowerCamelCase_ =self.layer[0](
lowerCAmelCase, conditioning_emb=lowerCAmelCase, attention_mask=lowerCAmelCase, )
if encoder_hidden_states is not None:
lowerCamelCase_ =torch.where(encoder_attention_mask > 0, 0, -1e10 ).to(
encoder_hidden_states.dtype )
lowerCamelCase_ =self.layer[1](
lowerCAmelCase, key_value_states=lowerCAmelCase, attention_mask=lowerCAmelCase, )
# Apply Film Conditional Feed Forward layer
lowerCamelCase_ =self.layer[-1](lowerCAmelCase, lowerCAmelCase )
return (hidden_states,)
class __UpperCamelCase ( nn.Module ):
def __init__( self, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase ):
"""simple docstring"""
super().__init__()
lowerCamelCase_ =TaLayerNorm(lowerCAmelCase )
lowerCamelCase_ =TaFiLMLayer(in_features=d_model * 4, out_features=lowerCAmelCase )
lowerCamelCase_ =Attention(query_dim=lowerCAmelCase, heads=lowerCAmelCase, dim_head=lowerCAmelCase, out_bias=lowerCAmelCase, scale_qk=lowerCAmelCase )
lowerCamelCase_ =nn.Dropout(lowerCAmelCase )
def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase=None, lowerCAmelCase=None, ):
"""simple docstring"""
lowerCamelCase_ =self.layer_norm(lowerCAmelCase )
if conditioning_emb is not None:
lowerCamelCase_ =self.FiLMLayer(lowerCAmelCase, lowerCAmelCase )
# Self-attention block
lowerCamelCase_ =self.attention(lowerCAmelCase )
lowerCamelCase_ =hidden_states + self.dropout(lowerCAmelCase )
return hidden_states
class __UpperCamelCase ( nn.Module ):
def __init__( self, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase ):
"""simple docstring"""
super().__init__()
lowerCamelCase_ =Attention(query_dim=lowerCAmelCase, heads=lowerCAmelCase, dim_head=lowerCAmelCase, out_bias=lowerCAmelCase, scale_qk=lowerCAmelCase )
lowerCamelCase_ =TaLayerNorm(lowerCAmelCase, eps=lowerCAmelCase )
lowerCamelCase_ =nn.Dropout(lowerCAmelCase )
def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase=None, lowerCAmelCase=None, ):
"""simple docstring"""
lowerCamelCase_ =self.layer_norm(lowerCAmelCase )
lowerCamelCase_ =self.attention(
lowerCAmelCase, encoder_hidden_states=lowerCAmelCase, attention_mask=attention_mask.squeeze(1 ), )
lowerCamelCase_ =hidden_states + self.dropout(lowerCAmelCase )
return layer_output
class __UpperCamelCase ( nn.Module ):
def __init__( self, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase ):
"""simple docstring"""
super().__init__()
lowerCamelCase_ =TaDenseGatedActDense(d_model=lowerCAmelCase, d_ff=lowerCAmelCase, dropout_rate=lowerCAmelCase )
lowerCamelCase_ =TaFiLMLayer(in_features=d_model * 4, out_features=lowerCAmelCase )
lowerCamelCase_ =TaLayerNorm(lowerCAmelCase, eps=lowerCAmelCase )
lowerCamelCase_ =nn.Dropout(lowerCAmelCase )
def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase=None ):
"""simple docstring"""
lowerCamelCase_ =self.layer_norm(lowerCAmelCase )
if conditioning_emb is not None:
lowerCamelCase_ =self.film(lowerCAmelCase, lowerCAmelCase )
lowerCamelCase_ =self.DenseReluDense(lowerCAmelCase )
lowerCamelCase_ =hidden_states + self.dropout(lowerCAmelCase )
return hidden_states
class __UpperCamelCase ( nn.Module ):
def __init__( self, lowerCAmelCase, lowerCAmelCase, lowerCAmelCase ):
"""simple docstring"""
super().__init__()
lowerCamelCase_ =nn.Linear(lowerCAmelCase, lowerCAmelCase, bias=lowerCAmelCase )
lowerCamelCase_ =nn.Linear(lowerCAmelCase, lowerCAmelCase, bias=lowerCAmelCase )
lowerCamelCase_ =nn.Linear(lowerCAmelCase, lowerCAmelCase, bias=lowerCAmelCase )
lowerCamelCase_ =nn.Dropout(lowerCAmelCase )
lowerCamelCase_ =NewGELUActivation()
def lowercase__ ( self, lowerCAmelCase ):
"""simple docstring"""
lowerCamelCase_ =self.act(self.wi_a(lowerCAmelCase ) )
lowerCamelCase_ =self.wi_a(lowerCAmelCase )
lowerCamelCase_ =hidden_gelu * hidden_linear
lowerCamelCase_ =self.dropout(lowerCAmelCase )
lowerCamelCase_ =self.wo(lowerCAmelCase )
return hidden_states
class __UpperCamelCase ( nn.Module ):
def __init__( self, lowerCAmelCase, lowerCAmelCase=1e-6 ):
"""simple docstring"""
super().__init__()
lowerCamelCase_ =nn.Parameter(torch.ones(lowerCAmelCase ) )
lowerCamelCase_ =eps
def lowercase__ ( self, lowerCAmelCase ):
"""simple docstring"""
lowerCamelCase_ =hidden_states.to(torch.floataa ).pow(2 ).mean(-1, keepdim=lowerCAmelCase )
lowerCamelCase_ =hidden_states * torch.rsqrt(variance + self.variance_epsilon )
# convert into half-precision if necessary
if self.weight.dtype in [torch.floataa, torch.bfloataa]:
lowerCamelCase_ =hidden_states.to(self.weight.dtype )
return self.weight * hidden_states
class __UpperCamelCase ( nn.Module ):
def lowercase__ ( self, lowerCAmelCase ):
"""simple docstring"""
return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi ) * (input + 0.0_4_4_7_1_5 * torch.pow(lowerCAmelCase, 3.0 )) ))
class __UpperCamelCase ( nn.Module ):
def __init__( self, lowerCAmelCase, lowerCAmelCase ):
"""simple docstring"""
super().__init__()
lowerCamelCase_ =nn.Linear(lowerCAmelCase, out_features * 2, bias=lowerCAmelCase )
def lowercase__ ( self, lowerCAmelCase, lowerCAmelCase ):
"""simple docstring"""
lowerCamelCase_ =self.scale_bias(lowerCAmelCase )
lowerCamelCase_, lowerCamelCase_ =torch.chunk(lowerCAmelCase, 2, -1 )
lowerCamelCase_ =x * (1 + scale) + shift
return x
| 676 |
'''simple docstring'''
def a_ ( __snake_case : int , __snake_case : int ) -> str:
"""simple docstring"""
if not isinstance(__snake_case , __snake_case ):
raise ValueError('''iterations must be defined as integers''' )
if not isinstance(__snake_case , __snake_case ) or not number >= 1:
raise ValueError(
'''starting number must be
and integer and be more than 0''' )
if not iterations >= 1:
raise ValueError('''Iterations must be done more than 0 times to play FizzBuzz''' )
lowerCamelCase_ =''''''
while number <= iterations:
if number % 3 == 0:
out += "Fizz"
if number % 5 == 0:
out += "Buzz"
if 0 not in (number % 3, number % 5):
out += str(__snake_case )
# print(out)
number += 1
out += " "
return out
if __name__ == "__main__":
import doctest
doctest.testmod()
| 676 | 1 |
"""simple docstring"""
import argparse
import torch
from datasets import load_dataset
from donut import DonutModel
from transformers import (
DonutImageProcessor,
DonutProcessor,
DonutSwinConfig,
DonutSwinModel,
MBartConfig,
MBartForCausalLM,
VisionEncoderDecoderModel,
XLMRobertaTokenizerFast,
)
def __snake_case ( UpperCamelCase ) -> Any:
"""simple docstring"""
a__ = model.config
a__ = DonutSwinConfig(
image_size=original_config.input_size , patch_size=4 , depths=original_config.encoder_layer , num_heads=[4, 8, 16, 32] , window_size=original_config.window_size , embed_dim=128 , )
a__ = MBartConfig(
is_decoder=UpperCamelCase , is_encoder_decoder=UpperCamelCase , add_cross_attention=UpperCamelCase , decoder_layers=original_config.decoder_layer , max_position_embeddings=original_config.max_position_embeddings , vocab_size=len(
model.decoder.tokenizer ) , scale_embedding=UpperCamelCase , add_final_layer_norm=UpperCamelCase , )
return encoder_config, decoder_config
def __snake_case ( UpperCamelCase ) -> Tuple:
"""simple docstring"""
if "encoder.model" in name:
a__ = name.replace('''encoder.model''' , '''encoder''' )
if "decoder.model" in name:
a__ = name.replace('''decoder.model''' , '''decoder''' )
if "patch_embed.proj" in name:
a__ = name.replace('''patch_embed.proj''' , '''embeddings.patch_embeddings.projection''' )
if "patch_embed.norm" in name:
a__ = name.replace('''patch_embed.norm''' , '''embeddings.norm''' )
if name.startswith('''encoder''' ):
if "layers" in name:
a__ = '''encoder.''' + name
if "attn.proj" in name:
a__ = name.replace('''attn.proj''' , '''attention.output.dense''' )
if "attn" in name and "mask" not in name:
a__ = name.replace('''attn''' , '''attention.self''' )
if "norm1" in name:
a__ = name.replace('''norm1''' , '''layernorm_before''' )
if "norm2" in name:
a__ = name.replace('''norm2''' , '''layernorm_after''' )
if "mlp.fc1" in name:
a__ = name.replace('''mlp.fc1''' , '''intermediate.dense''' )
if "mlp.fc2" in name:
a__ = name.replace('''mlp.fc2''' , '''output.dense''' )
if name == "encoder.norm.weight":
a__ = '''encoder.layernorm.weight'''
if name == "encoder.norm.bias":
a__ = '''encoder.layernorm.bias'''
return name
def __snake_case ( UpperCamelCase , UpperCamelCase ) -> Optional[Any]:
"""simple docstring"""
for key in orig_state_dict.copy().keys():
a__ = orig_state_dict.pop(UpperCamelCase )
if "qkv" in key:
a__ = key.split('''.''' )
a__ = int(key_split[3] )
a__ = int(key_split[5] )
a__ = model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size
if "weight" in key:
a__ = val[:dim, :]
a__ = val[dim : dim * 2, :]
a__ = val[-dim:, :]
else:
a__ = val[:dim]
a__ = val[dim : dim * 2]
a__ = val[-dim:]
elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]:
# HuggingFace implementation doesn't use attn_mask buffer
# and model doesn't use final LayerNorms for the encoder
pass
else:
a__ = val
return orig_state_dict
def __snake_case ( UpperCamelCase , UpperCamelCase=None , UpperCamelCase=False ) -> str:
"""simple docstring"""
a__ = DonutModel.from_pretrained(UpperCamelCase ).eval()
# load HuggingFace model
a__ , a__ = get_configs(UpperCamelCase )
a__ = DonutSwinModel(UpperCamelCase )
a__ = MBartForCausalLM(UpperCamelCase )
a__ = VisionEncoderDecoderModel(encoder=UpperCamelCase , decoder=UpperCamelCase )
model.eval()
a__ = original_model.state_dict()
a__ = convert_state_dict(UpperCamelCase , UpperCamelCase )
model.load_state_dict(UpperCamelCase )
# verify results on scanned document
a__ = load_dataset('''hf-internal-testing/example-documents''' )
a__ = dataset['''test'''][0]['''image'''].convert('''RGB''' )
a__ = XLMRobertaTokenizerFast.from_pretrained(UpperCamelCase , from_slow=UpperCamelCase )
a__ = DonutImageProcessor(
do_align_long_axis=original_model.config.align_long_axis , size=original_model.config.input_size[::-1] )
a__ = DonutProcessor(UpperCamelCase , UpperCamelCase )
a__ = processor(UpperCamelCase , return_tensors='''pt''' ).pixel_values
if model_name == "naver-clova-ix/donut-base-finetuned-docvqa":
a__ = '''<s_docvqa><s_question>{user_input}</s_question><s_answer>'''
a__ = '''When is the coffee break?'''
a__ = task_prompt.replace('''{user_input}''' , UpperCamelCase )
elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip":
a__ = '''<s_rvlcdip>'''
elif model_name in [
"naver-clova-ix/donut-base-finetuned-cord-v1",
"naver-clova-ix/donut-base-finetuned-cord-v1-2560",
]:
a__ = '''<s_cord>'''
elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2":
a__ = '''s_cord-v2>'''
elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket":
a__ = '''<s_zhtrainticket>'''
elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]:
# use a random prompt
a__ = '''hello world'''
else:
raise ValueError('''Model name not supported''' )
a__ = original_model.decoder.tokenizer(UpperCamelCase , add_special_tokens=UpperCamelCase , return_tensors='''pt''' )[
'''input_ids'''
]
a__ = original_model.encoder.model.patch_embed(UpperCamelCase )
a__ , a__ = model.encoder.embeddings(UpperCamelCase )
assert torch.allclose(UpperCamelCase , UpperCamelCase , atol=1E-3 )
# verify encoder hidden states
a__ = original_model.encoder(UpperCamelCase )
a__ = model.encoder(UpperCamelCase ).last_hidden_state
assert torch.allclose(UpperCamelCase , UpperCamelCase , atol=1E-2 )
# verify decoder hidden states
a__ = original_model(UpperCamelCase , UpperCamelCase , UpperCamelCase ).logits
a__ = model(UpperCamelCase , decoder_input_ids=UpperCamelCase ).logits
assert torch.allclose(UpperCamelCase , UpperCamelCase , atol=1E-3 )
print('''Looks ok!''' )
if pytorch_dump_folder_path is not None:
print(f"Saving model and processor to {pytorch_dump_folder_path}" )
model.save_pretrained(UpperCamelCase )
processor.save_pretrained(UpperCamelCase )
if push_to_hub:
model.push_to_hub('''nielsr/''' + model_name.split('''/''' )[-1] , commit_message='''Update model''' )
processor.push_to_hub('''nielsr/''' + model_name.split('''/''' )[-1] , commit_message='''Update model''' )
if __name__ == "__main__":
__lowerCAmelCase : int = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--model_name''',
default='''naver-clova-ix/donut-base-finetuned-docvqa''',
required=False,
type=str,
help='''Name of the original model you\'d like to convert.''',
)
parser.add_argument(
'''--pytorch_dump_folder_path''',
default=None,
required=False,
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 and processor to the 🤗 hub.''',
)
__lowerCAmelCase : Union[str, Any] = parser.parse_args()
convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
| 158 |
"""simple docstring"""
from __future__ import annotations
from random import choice
def __snake_case ( UpperCamelCase ) -> List[str]:
"""simple docstring"""
return choice(UpperCamelCase )
def __snake_case ( UpperCamelCase , UpperCamelCase ) -> int:
"""simple docstring"""
a__ = random_pivot(UpperCamelCase )
# partition based on pivot
# linear time
a__ = [e for e in lst if e < pivot]
a__ = [e for e in lst if e > pivot]
# if we get lucky, pivot might be the element we want.
# we can easily see this:
# small (elements smaller than k)
# + pivot (kth element)
# + big (elements larger than k)
if len(UpperCamelCase ) == k - 1:
return pivot
# pivot is in elements bigger than k
elif len(UpperCamelCase ) < k - 1:
return kth_number(UpperCamelCase , k - len(UpperCamelCase ) - 1 )
# pivot is in elements smaller than k
else:
return kth_number(UpperCamelCase , UpperCamelCase )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 158 | 1 |
'''simple docstring'''
def UpperCamelCase ( lowercase_ : Optional[int] ) -> bool:
'''simple docstring'''
if num < 0:
return False
lowercase =num
lowercase =0
while num > 0:
lowercase =rev_num * 1_0 + (num % 1_0)
num //= 1_0
return num_copy == rev_num
if __name__ == "__main__":
import doctest
doctest.testmod()
| 72 |
import coval # From: git+https://github.com/ns-moosavi/coval.git # noqa: F401
from coval.conll import reader, util
from coval.eval import evaluator
import datasets
__a = datasets.logging.get_logger(__name__)
__a = """\
@InProceedings{moosavi2019minimum,
author = { Nafise Sadat Moosavi, Leo Born, Massimo Poesio and Michael Strube},
title = {Using Automatically Extracted Minimum Spans to Disentangle Coreference Evaluation from Boundary Detection},
year = {2019},
booktitle = {Proceedings of the 57th Annual Meeting of
the Association for Computational Linguistics (Volume 1: Long Papers)},
publisher = {Association for Computational Linguistics},
address = {Florence, Italy},
}
@inproceedings{10.3115/1072399.1072405,
author = {Vilain, Marc and Burger, John and Aberdeen, John and Connolly, Dennis and Hirschman, Lynette},
title = {A Model-Theoretic Coreference Scoring Scheme},
year = {1995},
isbn = {1558604022},
publisher = {Association for Computational Linguistics},
address = {USA},
url = {https://doi.org/10.3115/1072399.1072405},
doi = {10.3115/1072399.1072405},
booktitle = {Proceedings of the 6th Conference on Message Understanding},
pages = {45–52},
numpages = {8},
location = {Columbia, Maryland},
series = {MUC6 ’95}
}
@INPROCEEDINGS{Bagga98algorithmsfor,
author = {Amit Bagga and Breck Baldwin},
title = {Algorithms for Scoring Coreference Chains},
booktitle = {In The First International Conference on Language Resources and Evaluation Workshop on Linguistics Coreference},
year = {1998},
pages = {563--566}
}
@INPROCEEDINGS{Luo05oncoreference,
author = {Xiaoqiang Luo},
title = {On coreference resolution performance metrics},
booktitle = {In Proc. of HLT/EMNLP},
year = {2005},
pages = {25--32},
publisher = {URL}
}
@inproceedings{moosavi-strube-2016-coreference,
title = \"Which Coreference Evaluation Metric Do You Trust? A Proposal for a Link-based Entity Aware Metric\",
author = \"Moosavi, Nafise Sadat and
Strube, Michael\",
booktitle = \"Proceedings of the 54th Annual Meeting of the Association for Computational Linguistics (Volume 1: Long Papers)\",
month = aug,
year = \"2016\",
address = \"Berlin, Germany\",
publisher = \"Association for Computational Linguistics\",
url = \"https://www.aclweb.org/anthology/P16-1060\",
doi = \"10.18653/v1/P16-1060\",
pages = \"632--642\",
}
"""
__a = """\
CoVal is a coreference evaluation tool for the CoNLL and ARRAU datasets which
implements of the common evaluation metrics including MUC [Vilain et al, 1995],
B-cubed [Bagga and Baldwin, 1998], CEAFe [Luo et al., 2005],
LEA [Moosavi and Strube, 2016] and the averaged CoNLL score
(the average of the F1 values of MUC, B-cubed and CEAFe)
[Denis and Baldridge, 2009a; Pradhan et al., 2011].
This wrapper of CoVal currently only work with CoNLL line format:
The CoNLL format has one word per line with all the annotation for this word in column separated by spaces:
Column Type Description
1 Document ID This is a variation on the document filename
2 Part number Some files are divided into multiple parts numbered as 000, 001, 002, ... etc.
3 Word number
4 Word itself This is the token as segmented/tokenized in the Treebank. Initially the *_skel file contain the placeholder [WORD] which gets replaced by the actual token from the Treebank which is part of the OntoNotes release.
5 Part-of-Speech
6 Parse bit This is the bracketed structure broken before the first open parenthesis in the parse, and the word/part-of-speech leaf replaced with a *. The full parse can be created by substituting the asterix with the \"([pos] [word])\" string (or leaf) and concatenating the items in the rows of that column.
7 Predicate lemma The predicate lemma is mentioned for the rows for which we have semantic role information. All other rows are marked with a \"-\"
8 Predicate Frameset ID This is the PropBank frameset ID of the predicate in Column 7.
9 Word sense This is the word sense of the word in Column 3.
10 Speaker/Author This is the speaker or author name where available. Mostly in Broadcast Conversation and Web Log data.
11 Named Entities These columns identifies the spans representing various named entities.
12:N Predicate Arguments There is one column each of predicate argument structure information for the predicate mentioned in Column 7.
N Coreference Coreference chain information encoded in a parenthesis structure.
More informations on the format can be found here (section \"*_conll File Format\"): http://www.conll.cemantix.org/2012/data.html
Details on the evaluation on CoNLL can be found here: https://github.com/ns-moosavi/coval/blob/master/conll/README.md
CoVal code was written by @ns-moosavi.
Some parts are borrowed from https://github.com/clarkkev/deep-coref/blob/master/evaluation.py
The test suite is taken from https://github.com/conll/reference-coreference-scorers/
Mention evaluation and the test suite are added by @andreasvc.
Parsing CoNLL files is developed by Leo Born.
"""
__a = """
Calculates coreference evaluation metrics.
Args:
predictions: list of sentences. Each sentence is a list of word predictions to score in the CoNLL format.
Each prediction is a word with its annotations as a string made of columns joined with spaces.
Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)
See the details on the format in the description of the metric.
references: list of sentences. Each sentence is a list of word reference to score in the CoNLL format.
Each reference is a word with its annotations as a string made of columns joined with spaces.
Only columns 4, 5, 6 and the last column are used (word, POS, Pars and coreference annotation)
See the details on the format in the description of the metric.
keep_singletons: After extracting all mentions of key or system files,
mentions whose corresponding coreference chain is of size one,
are considered as singletons. The default evaluation mode will include
singletons in evaluations if they are included in the key or the system files.
By setting 'keep_singletons=False', all singletons in the key and system files
will be excluded from the evaluation.
NP_only: Most of the recent coreference resolvers only resolve NP mentions and
leave out the resolution of VPs. By setting the 'NP_only' option, the scorer will only evaluate the resolution of NPs.
min_span: By setting 'min_span', the scorer reports the results based on automatically detected minimum spans.
Minimum spans are determined using the MINA algorithm.
Returns:
'mentions': mentions
'muc': MUC metric [Vilain et al, 1995]
'bcub': B-cubed [Bagga and Baldwin, 1998]
'ceafe': CEAFe [Luo et al., 2005]
'lea': LEA [Moosavi and Strube, 2016]
'conll_score': averaged CoNLL score (the average of the F1 values of MUC, B-cubed and CEAFe)
Examples:
>>> coval = datasets.load_metric('coval')
>>> words = ['bc/cctv/00/cctv_0005 0 0 Thank VBP (TOP(S(VP* thank 01 1 Xu_li * (V*) * -',
... 'bc/cctv/00/cctv_0005 0 1 you PRP (NP*) - - - Xu_li * (ARG1*) (ARG0*) (116)',
... 'bc/cctv/00/cctv_0005 0 2 everyone NN (NP*) - - - Xu_li * (ARGM-DIS*) * (116)',
... 'bc/cctv/00/cctv_0005 0 3 for IN (PP* - - - Xu_li * (ARG2* * -',
... 'bc/cctv/00/cctv_0005 0 4 watching VBG (S(VP*)))) watch 01 1 Xu_li * *) (V*) -',
... 'bc/cctv/00/cctv_0005 0 5 . . *)) - - - Xu_li * * * -']
>>> references = [words]
>>> predictions = [words]
>>> results = coval.compute(predictions=predictions, references=references)
>>> print(results) # doctest:+ELLIPSIS
{'mentions/recall': 1.0,[...] 'conll_score': 100.0}
"""
def _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=False , lowerCAmelCase_=False , lowerCAmelCase_=True , lowerCAmelCase_=False , lowerCAmelCase_="dummy_doc" ) ->Optional[Any]:
UpperCAmelCase = {doc: key_lines}
UpperCAmelCase = {doc: sys_lines}
UpperCAmelCase = {}
UpperCAmelCase = 0
UpperCAmelCase = 0
UpperCAmelCase = 0
UpperCAmelCase = 0
UpperCAmelCase = 0
UpperCAmelCase = 0
UpperCAmelCase , UpperCAmelCase = reader.get_doc_mentions(lowerCAmelCase_ , key_doc_lines[doc] , lowerCAmelCase_ )
key_singletons_num += singletons_num
if NP_only or min_span:
UpperCAmelCase = reader.set_annotated_parse_trees(lowerCAmelCase_ , key_doc_lines[doc] , lowerCAmelCase_ , lowerCAmelCase_ )
UpperCAmelCase , UpperCAmelCase = reader.get_doc_mentions(lowerCAmelCase_ , sys_doc_lines[doc] , lowerCAmelCase_ )
sys_singletons_num += singletons_num
if NP_only or min_span:
UpperCAmelCase = reader.set_annotated_parse_trees(lowerCAmelCase_ , key_doc_lines[doc] , lowerCAmelCase_ , lowerCAmelCase_ )
if remove_nested:
UpperCAmelCase , UpperCAmelCase = reader.remove_nested_coref_mentions(lowerCAmelCase_ , lowerCAmelCase_ )
key_nested_coref_num += nested_mentions
key_removed_nested_clusters += removed_clusters
UpperCAmelCase , UpperCAmelCase = reader.remove_nested_coref_mentions(lowerCAmelCase_ , lowerCAmelCase_ )
sys_nested_coref_num += nested_mentions
sys_removed_nested_clusters += removed_clusters
UpperCAmelCase = reader.get_mention_assignments(lowerCAmelCase_ , lowerCAmelCase_ )
UpperCAmelCase = reader.get_mention_assignments(lowerCAmelCase_ , lowerCAmelCase_ )
UpperCAmelCase = (key_clusters, sys_clusters, key_mention_sys_cluster, sys_mention_key_cluster)
if remove_nested:
logger.info(
"""Number of removed nested coreferring mentions in the key """
F"""annotation: {key_nested_coref_num}; and system annotation: {sys_nested_coref_num}""" )
logger.info(
"""Number of resulting singleton clusters in the key """
F"""annotation: {key_removed_nested_clusters}; and system annotation: {sys_removed_nested_clusters}""" )
if not keep_singletons:
logger.info(
F"""{key_singletons_num:d} and {sys_singletons_num:d} singletons are removed from the key and system """
"""files, respectively""" )
return doc_coref_infos
def _UpperCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) ->int:
UpperCAmelCase = get_coref_infos(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ )
UpperCAmelCase = {}
UpperCAmelCase = 0
UpperCAmelCase = 0
for name, metric in metrics:
UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = evaluator.evaluate_documents(lowerCAmelCase_ , lowerCAmelCase_ , beta=1 )
if name in ["muc", "bcub", "ceafe"]:
conll += fa
conll_subparts_num += 1
output_scores.update({F"""{name}/recall""": recall, F"""{name}/precision""": precision, F"""{name}/f1""": fa} )
logger.info(
name.ljust(1_0 ) , F"""Recall: {recall * 1_0_0:.2f}""" , F""" Precision: {precision * 1_0_0:.2f}""" , F""" F1: {fa * 1_0_0:.2f}""" , )
if conll_subparts_num == 3:
UpperCAmelCase = (conll / 3) * 1_0_0
logger.info(F"""CoNLL score: {conll:.2f}""" )
output_scores.update({"""conll_score""": conll} )
return output_scores
def _UpperCamelCase ( lowerCAmelCase_ ) ->List[Any]:
UpperCAmelCase = False
for line in key_lines:
if not line.startswith("""#""" ):
if len(line.split() ) > 6:
UpperCAmelCase = line.split()[5]
if not parse_col == "-":
UpperCAmelCase = True
break
else:
break
return has_gold_parse
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class __lowercase ( datasets.Metric ):
def _lowercase ( self : int ) -> str:
"""simple docstring"""
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"""predictions""": datasets.Sequence(datasets.Value("""string""" ) ),
"""references""": datasets.Sequence(datasets.Value("""string""" ) ),
} ) , codebase_urls=["""https://github.com/ns-moosavi/coval"""] , reference_urls=[
"""https://github.com/ns-moosavi/coval""",
"""https://www.aclweb.org/anthology/P16-1060""",
"""http://www.conll.cemantix.org/2012/data.html""",
] , )
def _lowercase ( self : Union[str, Any] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Optional[Any] , __lowerCamelCase : Optional[int]=True , __lowerCamelCase : Any=False , __lowerCamelCase : List[Any]=False , __lowerCamelCase : List[Any]=False ) -> List[Any]:
"""simple docstring"""
UpperCAmelCase = [
("""mentions""", evaluator.mentions),
("""muc""", evaluator.muc),
("""bcub""", evaluator.b_cubed),
("""ceafe""", evaluator.ceafe),
("""lea""", evaluator.lea),
]
if min_span:
UpperCAmelCase = util.check_gold_parse_annotation(__lowerCamelCase )
if not has_gold_parse:
raise NotImplementedError("""References should have gold parse annotation to use 'min_span'.""" )
# util.parse_key_file(key_file)
# key_file = key_file + ".parsed"
UpperCAmelCase = evaluate(
key_lines=__lowerCamelCase , sys_lines=__lowerCamelCase , metrics=__lowerCamelCase , NP_only=__lowerCamelCase , remove_nested=__lowerCamelCase , keep_singletons=__lowerCamelCase , min_span=__lowerCamelCase , )
return score
| 377 | 0 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import _LazyModule
__A ={"processing_wav2vec2_with_lm": ["Wav2Vec2ProcessorWithLM"]}
if TYPE_CHECKING:
from .processing_wavaveca_with_lm import WavaVecaProcessorWithLM
else:
import sys
__A =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__) | 718 |
'''simple docstring'''
from typing import Callable, Dict, Optional, Tuple
import torch
from torch import nn
from torch.distributions import (
AffineTransform,
Distribution,
Independent,
NegativeBinomial,
Normal,
StudentT,
TransformedDistribution,
)
class _snake_case ( a__ ):
def __init__( self , _lowerCamelCase , _lowerCamelCase=None , _lowerCamelCase=None , _lowerCamelCase=0):
UpperCAmelCase__ : Dict = 1.0 if scale is None else scale
UpperCAmelCase__ : Dict = 0.0 if loc is None else loc
super().__init__(_lowerCamelCase , [AffineTransform(loc=self.loc , scale=self.scale , event_dim=_lowerCamelCase)])
@property
def snake_case__ ( self):
return self.base_dist.mean * self.scale + self.loc
@property
def snake_case__ ( self):
return self.base_dist.variance * self.scale**2
@property
def snake_case__ ( self):
return self.variance.sqrt()
class _snake_case ( nn.Module ):
def __init__( self , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase):
super().__init__(**_lowerCamelCase)
UpperCAmelCase__ : int = args_dim
UpperCAmelCase__ : Optional[int] = nn.ModuleList([nn.Linear(_lowerCamelCase , _lowerCamelCase) for dim in args_dim.values()])
UpperCAmelCase__ : Optional[Any] = domain_map
def snake_case__ ( self , _lowerCamelCase):
UpperCAmelCase__ : Optional[int] = [proj(_lowerCamelCase) for proj in self.proj]
return self.domain_map(*_lowerCamelCase)
class _snake_case ( nn.Module ):
def __init__( self , _lowerCamelCase):
super().__init__()
UpperCAmelCase__ : Optional[int] = function
def snake_case__ ( self , _lowerCamelCase , *_lowerCamelCase):
return self.function(_lowerCamelCase , *_lowerCamelCase)
class _snake_case :
lowerCAmelCase :type
lowerCAmelCase :int
lowerCAmelCase :Dict[str, int]
def __init__( self , _lowerCamelCase = 1):
UpperCAmelCase__ : Optional[Any] = dim
UpperCAmelCase__ : int = {k: dim * self.args_dim[k] for k in self.args_dim}
def snake_case__ ( self , _lowerCamelCase):
if self.dim == 1:
return self.distribution_class(*_lowerCamelCase)
else:
return Independent(self.distribution_class(*_lowerCamelCase) , 1)
def snake_case__ ( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = None , ):
UpperCAmelCase__ : Dict = self._base_distribution(_lowerCamelCase)
if loc is None and scale is None:
return distr
else:
return AffineTransformed(_lowerCamelCase , loc=_lowerCamelCase , scale=_lowerCamelCase , event_dim=self.event_dim)
@property
def snake_case__ ( self):
return () if self.dim == 1 else (self.dim,)
@property
def snake_case__ ( self):
return len(self.event_shape)
@property
def snake_case__ ( self):
return 0.0
def snake_case__ ( self , _lowerCamelCase):
return ParameterProjection(
in_features=_lowerCamelCase , args_dim=self.args_dim , domain_map=LambdaLayer(self.domain_map) , )
def snake_case__ ( self , *_lowerCamelCase):
raise NotImplementedError()
@staticmethod
def snake_case__ ( _lowerCamelCase):
return (x + torch.sqrt(torch.square(_lowerCamelCase) + 4.0)) / 2.0
class _snake_case ( a__ ):
lowerCAmelCase :Dict[str, int] = {"df": 1, "loc": 1, "scale": 1}
lowerCAmelCase :type = StudentT
@classmethod
def snake_case__ ( cls , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase):
UpperCAmelCase__ : Optional[Any] = cls.squareplus(_lowerCamelCase).clamp_min(torch.finfo(scale.dtype).eps)
UpperCAmelCase__ : Any = 2.0 + cls.squareplus(_lowerCamelCase)
return df.squeeze(-1), loc.squeeze(-1), scale.squeeze(-1)
class _snake_case ( a__ ):
lowerCAmelCase :Dict[str, int] = {"loc": 1, "scale": 1}
lowerCAmelCase :type = Normal
@classmethod
def snake_case__ ( cls , _lowerCamelCase , _lowerCamelCase):
UpperCAmelCase__ : str = cls.squareplus(_lowerCamelCase).clamp_min(torch.finfo(scale.dtype).eps)
return loc.squeeze(-1), scale.squeeze(-1)
class _snake_case ( a__ ):
lowerCAmelCase :Dict[str, int] = {"total_count": 1, "logits": 1}
lowerCAmelCase :type = NegativeBinomial
@classmethod
def snake_case__ ( cls , _lowerCamelCase , _lowerCamelCase):
UpperCAmelCase__ : str = cls.squareplus(_lowerCamelCase)
return total_count.squeeze(-1), logits.squeeze(-1)
def snake_case__ ( self , _lowerCamelCase):
UpperCAmelCase__ , UpperCAmelCase__ : Tuple = distr_args
if self.dim == 1:
return self.distribution_class(total_count=_lowerCamelCase , logits=_lowerCamelCase)
else:
return Independent(self.distribution_class(total_count=_lowerCamelCase , logits=_lowerCamelCase) , 1)
def snake_case__ ( self , _lowerCamelCase , _lowerCamelCase = None , _lowerCamelCase = None):
UpperCAmelCase__ , UpperCAmelCase__ : Any = distr_args
if scale is not None:
# See scaling property of Gamma.
logits += scale.log()
return self._base_distribution((total_count, logits)) | 113 | 0 |
def a ( A__ ) -> int:
'''simple docstring'''
if a < 0:
raise ValueError('''Input value must be a positive integer''' )
elif isinstance(A__ , A__ ):
raise TypeError('''Input value must be a \'int\' type''' )
return bin(A__ ).count('''1''' )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 35 |
import os
import unittest
from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast
from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class lowercase ( _UpperCAmelCase , unittest.TestCase ):
lowerCamelCase : Tuple = LayoutLMTokenizer
lowerCamelCase : Any = LayoutLMTokenizerFast
lowerCamelCase : Tuple = True
lowerCamelCase : List[Any] = True
def lowercase__ ( self : Optional[int] ):
super().setUp()
SCREAMING_SNAKE_CASE__ : Optional[int] = [
'''[UNK]''',
'''[CLS]''',
'''[SEP]''',
'''want''',
'''##want''',
'''##ed''',
'''wa''',
'''un''',
'''runn''',
'''##ing''',
''',''',
'''low''',
'''lowest''',
]
SCREAMING_SNAKE_CASE__ : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer:
vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) )
def lowercase__ ( self : Optional[int] , **_lowercase : str ):
return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **_lowercase )
def lowercase__ ( self : Optional[Any] , _lowercase : Any ):
SCREAMING_SNAKE_CASE__ : str = '''UNwant\u00E9d,running'''
SCREAMING_SNAKE_CASE__ : Any = '''unwanted, running'''
return input_text, output_text
def lowercase__ ( self : str ):
SCREAMING_SNAKE_CASE__ : List[str] = self.tokenizer_class(self.vocab_file )
SCREAMING_SNAKE_CASE__ : Any = tokenizer.tokenize('''UNwant\u00E9d,running''' )
self.assertListEqual(_lowercase , ['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowercase ) , [7, 4, 5, 10, 8, 9] )
def lowercase__ ( self : str ):
pass
| 35 | 1 |
import re
def lowerCAmelCase_ ( __lowerCamelCase ):
return [char.split() for char in re.split(R"[^ a-z A-Z 0-9 \s]" , str_ )]
def lowerCAmelCase_ ( __lowerCamelCase ):
__snake_case : int = split_input(str_ )
return "".join(
["".join([char.capitalize() for char in sub_str] ) for sub_str in string_split] )
def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase , __lowerCamelCase ):
try:
__snake_case : Union[str, Any] = split_input(__lowerCamelCase )
if upper:
__snake_case : Optional[Any] = "".join(
[
separator.join([char.upper() for char in sub_str] )
for sub_str in string_split
] )
else:
__snake_case : List[Any] = "".join(
[
separator.join([char.lower() for char in sub_str] )
for sub_str in string_split
] )
return res_str
except IndexError:
return "not valid string"
def lowerCAmelCase_ ( __lowerCamelCase ):
return to_simple_case(__lowerCamelCase )
def lowerCAmelCase_ ( __lowerCamelCase ):
try:
__snake_case : Optional[Any] = to_simple_case(__lowerCamelCase )
return res_str[0].lower() + res_str[1:]
except IndexError:
return "not valid string"
def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase ):
return to_complex_case(__lowerCamelCase , __lowerCamelCase , "_" )
def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase ):
return to_complex_case(__lowerCamelCase , __lowerCamelCase , "-" )
if __name__ == "__main__":
__import__("doctest").testmod()
| 203 |
def lowerCAmelCase_ ( __lowerCamelCase , __lowerCamelCase ):
return int((input_a, input_a).count(0 ) == 0 )
def lowerCAmelCase_ ( ):
assert and_gate(0 , 0 ) == 0
assert and_gate(0 , 1 ) == 0
assert and_gate(1 , 0 ) == 0
assert and_gate(1 , 1 ) == 1
if __name__ == "__main__":
test_and_gate()
print(and_gate(1, 0))
print(and_gate(0, 0))
print(and_gate(0, 1))
print(and_gate(1, 1))
| 203 | 1 |
from typing import Union
from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging
from .base import PIPELINE_INIT_ARGS, Pipeline
if is_vision_available():
from PIL import Image
from ..image_utils import load_image
if is_torch_available():
from ..models.auto.modeling_auto import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING
__SCREAMING_SNAKE_CASE : Optional[int] =logging.get_logger(__name__)
@add_end_docstrings(__a )
class A_ ( __a ):
def __init__( self : List[Any] , *snake_case__ : List[Any] , **snake_case__ : Union[str, Any] ):
super().__init__(*snake_case__ , **snake_case__ )
self.check_model_type(snake_case__ )
def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] , snake_case__ : Tuple=None , snake_case__ : Tuple=None , snake_case__ : Optional[Any]=None , **snake_case__ : Any ):
lowercase , lowercase = {}, {}
if padding is not None:
lowercase = padding
if truncation is not None:
lowercase = truncation
if top_k is not None:
lowercase = top_k
return preprocess_params, {}, postprocess_params
def __call__( self : List[str] , snake_case__ : Union["Image.Image", str] , snake_case__ : str = None , **snake_case__ : Union[str, Any] ):
if isinstance(snake_case__ , (Image.Image, str) ) and isinstance(snake_case__ , snake_case__ ):
lowercase = {"""image""": image, """question""": question}
else:
lowercase = image
lowercase = super().__call__(snake_case__ , **snake_case__ )
return results
def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , snake_case__ : Dict , snake_case__ : Union[str, Any]=False , snake_case__ : List[Any]=False ):
lowercase = load_image(inputs["""image"""] )
lowercase = self.tokenizer(
inputs["""question"""] , return_tensors=self.framework , padding=snake_case__ , truncation=snake_case__ )
lowercase = self.image_processor(images=snake_case__ , return_tensors=self.framework )
model_inputs.update(snake_case__ )
return model_inputs
def SCREAMING_SNAKE_CASE__ ( self : str , snake_case__ : str ):
lowercase = self.model(**snake_case__ )
return model_outputs
def SCREAMING_SNAKE_CASE__ ( self : List[Any] , snake_case__ : Any , snake_case__ : Optional[Any]=5 ):
if top_k > self.model.config.num_labels:
lowercase = self.model.config.num_labels
if self.framework == "pt":
lowercase = model_outputs.logits.sigmoid()[0]
lowercase , lowercase = probs.topk(snake_case__ )
else:
raise ValueError(F"""Unsupported framework: {self.framework}""" )
lowercase = scores.tolist()
lowercase = ids.tolist()
return [{"score": score, "answer": self.model.config.idalabel[_id]} for score, _id in zip(snake_case__ , snake_case__ )]
| 428 |
import unittest
from transformers import is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow
if is_torch_available():
import torch
from transformers import XLMRobertaModel
@require_sentencepiece
@require_tokenizers
@require_torch
class A_ ( unittest.TestCase ):
@slow
def SCREAMING_SNAKE_CASE__ ( self : str ):
lowercase = XLMRobertaModel.from_pretrained("""xlm-roberta-base""" )
lowercase = torch.tensor([[0, 5_81, 1_02_69, 83, 9_99_42, 1_36, 6_07_42, 23, 70, 8_05_83, 1_82_76, 2]] )
# The dog is cute and lives in the garden house
lowercase = torch.Size((1, 12, 7_68) ) # batch_size, sequence_length, embedding_vector_dim
lowercase = torch.tensor(
[[-0.0_101, 0.1_218, -0.0_803, 0.0_801, 0.1_327, 0.0_776, -0.1_215, 0.2_383, 0.3_338, 0.3_106, 0.0_300, 0.0_252]] )
# xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base')
# xlmr.eval()
# expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1]
with torch.no_grad():
lowercase = model(snake_case__ )["""last_hidden_state"""].detach()
self.assertEqual(output.shape , snake_case__ )
# compare the actual values for a slice of last dim
self.assertTrue(torch.allclose(output[:, :, -1] , snake_case__ , atol=1E-3 ) )
@slow
def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ):
lowercase = XLMRobertaModel.from_pretrained("""xlm-roberta-large""" )
lowercase = torch.tensor([[0, 5_81, 1_02_69, 83, 9_99_42, 1_36, 6_07_42, 23, 70, 8_05_83, 1_82_76, 2]] )
# The dog is cute and lives in the garden house
lowercase = torch.Size((1, 12, 10_24) ) # batch_size, sequence_length, embedding_vector_dim
lowercase = torch.tensor(
[[-0.0_699, -0.0_318, 0.0_705, -0.1_241, 0.0_999, -0.0_520, 0.1_004, -0.1_838, -0.4_704, 0.1_437, 0.0_821, 0.0_126]] )
# xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.large')
# xlmr.eval()
# expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1]
with torch.no_grad():
lowercase = model(snake_case__ )["""last_hidden_state"""].detach()
self.assertEqual(output.shape , snake_case__ )
# compare the actual values for a slice of last dim
self.assertTrue(torch.allclose(output[:, :, -1] , snake_case__ , atol=1E-3 ) )
| 428 | 1 |
from math import factorial, pi
def lowercase ( a , a = 30 ):
'''simple docstring'''
if not isinstance(a , (int, float) ):
raise ValueError("maclaurin_sin() requires either an int or float for theta" )
if not isinstance(a , a ) or accuracy <= 0:
raise ValueError("maclaurin_sin() requires a positive int for accuracy" )
SCREAMING_SNAKE_CASE_ :Optional[int] = float(a )
SCREAMING_SNAKE_CASE_ :Optional[int] = theta // (2 * pi)
theta -= 2 * div * pi
return sum(
(-1) ** r * theta ** (2 * r + 1) / factorial(2 * r + 1 ) for r in range(a ) )
def lowercase ( a , a = 30 ):
'''simple docstring'''
if not isinstance(a , (int, float) ):
raise ValueError("maclaurin_cos() requires either an int or float for theta" )
if not isinstance(a , a ) or accuracy <= 0:
raise ValueError("maclaurin_cos() requires a positive int for accuracy" )
SCREAMING_SNAKE_CASE_ :Union[str, Any] = float(a )
SCREAMING_SNAKE_CASE_ :List[Any] = theta // (2 * pi)
theta -= 2 * div * pi
return sum((-1) ** r * theta ** (2 * r) / factorial(2 * r ) for r in range(a ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
print(maclaurin_sin(10))
print(maclaurin_sin(-10))
print(maclaurin_sin(10, 15))
print(maclaurin_sin(-10, 15))
print(maclaurin_cos(5))
print(maclaurin_cos(-5))
print(maclaurin_cos(10, 15))
print(maclaurin_cos(-10, 15))
| 713 |
from math import cos, sin, sqrt, tau
from audio_filters.iir_filter import IIRFilter
def lowercase ( a , a , a = 1 / sqrt(2 ) ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ :Tuple = tau * frequency / samplerate
SCREAMING_SNAKE_CASE_ :List[str] = sin(a )
SCREAMING_SNAKE_CASE_ :Tuple = cos(a )
SCREAMING_SNAKE_CASE_ :Dict = _sin / (2 * q_factor)
SCREAMING_SNAKE_CASE_ :Optional[int] = (1 - _cos) / 2
SCREAMING_SNAKE_CASE_ :Dict = 1 - _cos
SCREAMING_SNAKE_CASE_ :Tuple = 1 + alpha
SCREAMING_SNAKE_CASE_ :Optional[Any] = -2 * _cos
SCREAMING_SNAKE_CASE_ :Dict = 1 - alpha
SCREAMING_SNAKE_CASE_ :Tuple = IIRFilter(2 )
filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] )
return filt
def lowercase ( a , a , a = 1 / sqrt(2 ) ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ :List[str] = tau * frequency / samplerate
SCREAMING_SNAKE_CASE_ :Optional[int] = sin(a )
SCREAMING_SNAKE_CASE_ :int = cos(a )
SCREAMING_SNAKE_CASE_ :str = _sin / (2 * q_factor)
SCREAMING_SNAKE_CASE_ :Optional[int] = (1 + _cos) / 2
SCREAMING_SNAKE_CASE_ :int = -1 - _cos
SCREAMING_SNAKE_CASE_ :Any = 1 + alpha
SCREAMING_SNAKE_CASE_ :Any = -2 * _cos
SCREAMING_SNAKE_CASE_ :Optional[Any] = 1 - alpha
SCREAMING_SNAKE_CASE_ :Union[str, Any] = IIRFilter(2 )
filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] )
return filt
def lowercase ( a , a , a = 1 / sqrt(2 ) ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ :Any = tau * frequency / samplerate
SCREAMING_SNAKE_CASE_ :str = sin(a )
SCREAMING_SNAKE_CASE_ :Optional[int] = cos(a )
SCREAMING_SNAKE_CASE_ :Optional[Any] = _sin / (2 * q_factor)
SCREAMING_SNAKE_CASE_ :Any = _sin / 2
SCREAMING_SNAKE_CASE_ :Optional[int] = 0
SCREAMING_SNAKE_CASE_ :str = -ba
SCREAMING_SNAKE_CASE_ :str = 1 + alpha
SCREAMING_SNAKE_CASE_ :Union[str, Any] = -2 * _cos
SCREAMING_SNAKE_CASE_ :Tuple = 1 - alpha
SCREAMING_SNAKE_CASE_ :Union[str, Any] = IIRFilter(2 )
filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] )
return filt
def lowercase ( a , a , a = 1 / sqrt(2 ) ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ :Any = tau * frequency / samplerate
SCREAMING_SNAKE_CASE_ :Optional[Any] = sin(a )
SCREAMING_SNAKE_CASE_ :str = cos(a )
SCREAMING_SNAKE_CASE_ :Any = _sin / (2 * q_factor)
SCREAMING_SNAKE_CASE_ :Optional[Any] = 1 - alpha
SCREAMING_SNAKE_CASE_ :int = -2 * _cos
SCREAMING_SNAKE_CASE_ :Tuple = 1 + alpha
SCREAMING_SNAKE_CASE_ :Any = IIRFilter(2 )
filt.set_coefficients([ba, ba, ba] , [ba, ba, ba] )
return filt
def lowercase ( a , a , a , a = 1 / sqrt(2 ) , ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ :List[str] = tau * frequency / samplerate
SCREAMING_SNAKE_CASE_ :Any = sin(a )
SCREAMING_SNAKE_CASE_ :Any = cos(a )
SCREAMING_SNAKE_CASE_ :List[str] = _sin / (2 * q_factor)
SCREAMING_SNAKE_CASE_ :str = 10 ** (gain_db / 40)
SCREAMING_SNAKE_CASE_ :str = 1 + alpha * big_a
SCREAMING_SNAKE_CASE_ :int = -2 * _cos
SCREAMING_SNAKE_CASE_ :List[Any] = 1 - alpha * big_a
SCREAMING_SNAKE_CASE_ :Optional[Any] = 1 + alpha / big_a
SCREAMING_SNAKE_CASE_ :Optional[Any] = -2 * _cos
SCREAMING_SNAKE_CASE_ :Any = 1 - alpha / big_a
SCREAMING_SNAKE_CASE_ :Union[str, Any] = IIRFilter(2 )
filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] )
return filt
def lowercase ( a , a , a , a = 1 / sqrt(2 ) , ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ :List[Any] = tau * frequency / samplerate
SCREAMING_SNAKE_CASE_ :Optional[int] = sin(a )
SCREAMING_SNAKE_CASE_ :Union[str, Any] = cos(a )
SCREAMING_SNAKE_CASE_ :str = _sin / (2 * q_factor)
SCREAMING_SNAKE_CASE_ :Union[str, Any] = 10 ** (gain_db / 40)
SCREAMING_SNAKE_CASE_ :Optional[int] = (big_a + 1) - (big_a - 1) * _cos
SCREAMING_SNAKE_CASE_ :Tuple = (big_a + 1) + (big_a - 1) * _cos
SCREAMING_SNAKE_CASE_ :List[Any] = (big_a - 1) - (big_a + 1) * _cos
SCREAMING_SNAKE_CASE_ :Union[str, Any] = (big_a - 1) + (big_a + 1) * _cos
SCREAMING_SNAKE_CASE_ :Optional[Any] = 2 * sqrt(a ) * alpha
SCREAMING_SNAKE_CASE_ :Optional[Any] = big_a * (pmc + aaa)
SCREAMING_SNAKE_CASE_ :str = 2 * big_a * mpc
SCREAMING_SNAKE_CASE_ :List[Any] = big_a * (pmc - aaa)
SCREAMING_SNAKE_CASE_ :Optional[int] = ppmc + aaa
SCREAMING_SNAKE_CASE_ :Dict = -2 * pmpc
SCREAMING_SNAKE_CASE_ :str = ppmc - aaa
SCREAMING_SNAKE_CASE_ :Optional[Any] = IIRFilter(2 )
filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] )
return filt
def lowercase ( a , a , a , a = 1 / sqrt(2 ) , ):
'''simple docstring'''
SCREAMING_SNAKE_CASE_ :Optional[Any] = tau * frequency / samplerate
SCREAMING_SNAKE_CASE_ :Any = sin(a )
SCREAMING_SNAKE_CASE_ :Tuple = cos(a )
SCREAMING_SNAKE_CASE_ :Tuple = _sin / (2 * q_factor)
SCREAMING_SNAKE_CASE_ :Any = 10 ** (gain_db / 40)
SCREAMING_SNAKE_CASE_ :Dict = (big_a + 1) - (big_a - 1) * _cos
SCREAMING_SNAKE_CASE_ :Union[str, Any] = (big_a + 1) + (big_a - 1) * _cos
SCREAMING_SNAKE_CASE_ :List[str] = (big_a - 1) - (big_a + 1) * _cos
SCREAMING_SNAKE_CASE_ :Tuple = (big_a - 1) + (big_a + 1) * _cos
SCREAMING_SNAKE_CASE_ :Dict = 2 * sqrt(a ) * alpha
SCREAMING_SNAKE_CASE_ :int = big_a * (ppmc + aaa)
SCREAMING_SNAKE_CASE_ :Union[str, Any] = -2 * big_a * pmpc
SCREAMING_SNAKE_CASE_ :Any = big_a * (ppmc - aaa)
SCREAMING_SNAKE_CASE_ :List[str] = pmc + aaa
SCREAMING_SNAKE_CASE_ :Optional[int] = 2 * mpc
SCREAMING_SNAKE_CASE_ :Union[str, Any] = pmc - aaa
SCREAMING_SNAKE_CASE_ :Tuple = IIRFilter(2 )
filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] )
return filt
| 140 | 0 |
import math
def a ( snake_case__: int ):
'''simple docstring'''
return math.sqrt(snake_case__ ) * math.sqrt(snake_case__ ) == num
def a ( snake_case__: int ):
'''simple docstring'''
lowercase_ = 0
lowercase_ = n
while left <= right:
lowercase_ = (left + right) // 2
if mid**2 == n:
return True
elif mid**2 > n:
lowercase_ = mid - 1
else:
lowercase_ = mid + 1
return False
if __name__ == "__main__":
import doctest
doctest.testmod()
| 97 |
import math
def __lowercase ( _UpperCamelCase, _UpperCamelCase ) ->float:
"""simple docstring"""
if (
not isinstance(_UpperCamelCase, (int, float) )
or power_factor < -1
or power_factor > 1
):
raise ValueError('''power_factor must be a valid float value between -1 and 1.''' )
return apparent_power * power_factor
def __lowercase ( _UpperCamelCase, _UpperCamelCase ) ->float:
"""simple docstring"""
if (
not isinstance(_UpperCamelCase, (int, float) )
or power_factor < -1
or power_factor > 1
):
raise ValueError('''power_factor must be a valid float value between -1 and 1.''' )
return apparent_power * math.sqrt(1 - power_factor**2 )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 319 | 0 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
_UpperCAmelCase : str = logging.get_logger(__name__)
_UpperCAmelCase : Optional[int] = {
"sayakpaul/vit-msn-base": "https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json",
# See all ViT MSN models at https://huggingface.co/models?filter=vit_msn
}
class __lowerCAmelCase ( lowerCAmelCase):
'''simple docstring'''
_a = '''vit_msn'''
def __init__( self: List[Any] , _lowerCAmelCase: Any=7_68 , _lowerCAmelCase: Optional[int]=12 , _lowerCAmelCase: List[Any]=12 , _lowerCAmelCase: str=30_72 , _lowerCAmelCase: List[Any]="gelu" , _lowerCAmelCase: List[Any]=0.0 , _lowerCAmelCase: Dict=0.0 , _lowerCAmelCase: Optional[Any]=0.02 , _lowerCAmelCase: str=1e-0_6 , _lowerCAmelCase: Any=2_24 , _lowerCAmelCase: Dict=16 , _lowerCAmelCase: Optional[int]=3 , _lowerCAmelCase: str=True , **_lowerCAmelCase: Any , ):
super().__init__(**_lowerCAmelCase )
lowercase :str = hidden_size
lowercase :Union[str, Any] = num_hidden_layers
lowercase :int = num_attention_heads
lowercase :Dict = intermediate_size
lowercase :int = hidden_act
lowercase :Optional[Any] = hidden_dropout_prob
lowercase :Dict = attention_probs_dropout_prob
lowercase :Tuple = initializer_range
lowercase :Any = layer_norm_eps
lowercase :str = image_size
lowercase :Tuple = patch_size
lowercase :List[str] = num_channels
lowercase :Optional[int] = qkv_bias
| 705 |
import string
def UpperCAmelCase__ ( lowerCamelCase ):
lowercase :Optional[int] = ""
for i in sequence:
lowercase :Optional[Any] = ord(lowerCamelCase )
if 65 <= extract <= 90:
output += chr(155 - extract )
elif 97 <= extract <= 122:
output += chr(219 - extract )
else:
output += i
return output
def UpperCAmelCase__ ( lowerCamelCase ):
lowercase :Union[str, Any] = string.ascii_letters
lowercase :Dict = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1]
return "".join(
letters_reversed[letters.index(lowerCamelCase )] if c in letters else c for c in sequence )
def UpperCAmelCase__ ( ):
from timeit import timeit
print("Running performance benchmarks..." )
lowercase :Dict = "from string import printable ; from __main__ import atbash, atbash_slow"
print(F"> atbash_slow(): {timeit('atbash_slow(printable)', setup=lowerCamelCase )} seconds" )
print(F"> atbash(): {timeit('atbash(printable)', setup=lowerCamelCase )} seconds" )
if __name__ == "__main__":
for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"):
print(f'''{example} encrypted in atbash: {atbash(example)}''')
benchmark()
| 453 | 0 |
import os
import time
import warnings
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional, Union
import torch
from filelock import FileLock
from torch.utils.data import Dataset
from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import logging
from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors
from ..processors.utils import InputFeatures
__a: Union[str, Any] = logging.get_logger(__name__)
@dataclass
class SCREAMING_SNAKE_CASE__ :
'''simple docstring'''
_lowerCamelCase = field(metadata={'''help''': '''The name of the task to train on: ''' + ''', '''.join(glue_processors.keys() )} )
_lowerCamelCase = field(
metadata={'''help''': '''The input data dir. Should contain the .tsv files (or other data files) for the task.'''} )
_lowerCamelCase = field(
default=128 , metadata={
'''help''': (
'''The maximum total input sequence length after tokenization. Sequences longer '''
'''than this will be truncated, sequences shorter will be padded.'''
)
} , )
_lowerCamelCase = field(
default=UpperCAmelCase , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} )
def lowerCamelCase ( self : Optional[int] ) -> int:
"""simple docstring"""
_UpperCAmelCase = self.task_name.lower()
class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase ):
'''simple docstring'''
_lowerCamelCase = '''train'''
_lowerCamelCase = '''dev'''
_lowerCamelCase = '''test'''
class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase ):
'''simple docstring'''
_lowerCamelCase = 42
_lowerCamelCase = 42
_lowerCamelCase = 42
def __init__( self : Any , lowerCamelCase : GlueDataTrainingArguments , lowerCamelCase : PreTrainedTokenizerBase , lowerCamelCase : Optional[int] = None , lowerCamelCase : Union[str, Split] = Split.train , lowerCamelCase : Optional[str] = None , ) -> int:
"""simple docstring"""
warnings.warn(
"""This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets """
"""library. You can have a look at this example script for pointers: """
"""https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py""" , lowerCamelCase , )
_UpperCAmelCase = args
_UpperCAmelCase = glue_processors[args.task_name]()
_UpperCAmelCase = glue_output_modes[args.task_name]
if isinstance(lowerCamelCase , lowerCamelCase ):
try:
_UpperCAmelCase = Split[mode]
except KeyError:
raise KeyError("""mode is not a valid split name""" )
# Load data features from cache or dataset file
_UpperCAmelCase = os.path.join(
cache_dir if cache_dir is not None else args.data_dir , f"""cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}""" , )
_UpperCAmelCase = self.processor.get_labels()
if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in (
"RobertaTokenizer",
"RobertaTokenizerFast",
"XLMRobertaTokenizer",
"BartTokenizer",
"BartTokenizerFast",
):
# HACK(label indices are swapped in RoBERTa pretrained model)
_UpperCAmelCase , _UpperCAmelCase = label_list[2], label_list[1]
_UpperCAmelCase = label_list
# 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 args.overwrite_cache:
_UpperCAmelCase = time.time()
_UpperCAmelCase = torch.load(lowerCamelCase )
logger.info(
f"""Loading features from cached file {cached_features_file} [took %.3f s]""" , time.time() - start )
else:
logger.info(f"""Creating features from dataset file at {args.data_dir}""" )
if mode == Split.dev:
_UpperCAmelCase = self.processor.get_dev_examples(args.data_dir )
elif mode == Split.test:
_UpperCAmelCase = self.processor.get_test_examples(args.data_dir )
else:
_UpperCAmelCase = self.processor.get_train_examples(args.data_dir )
if limit_length is not None:
_UpperCAmelCase = examples[:limit_length]
_UpperCAmelCase = glue_convert_examples_to_features(
lowerCamelCase , lowerCamelCase , max_length=args.max_seq_length , label_list=lowerCamelCase , output_mode=self.output_mode , )
_UpperCAmelCase = time.time()
torch.save(self.features , lowerCamelCase )
# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
logger.info(
f"""Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]""" )
def __len__( self : Union[str, Any] ) -> Any:
"""simple docstring"""
return len(self.features )
def __getitem__( self : str , lowerCamelCase : Any ) -> InputFeatures:
"""simple docstring"""
return self.features[i]
def lowerCamelCase ( self : int ) -> List[Any]:
"""simple docstring"""
return self.label_list | 108 |
import shutil
import tempfile
import unittest
import numpy as np
from transformers.testing_utils import (
is_pt_tf_cross_test,
require_tf,
require_torch,
require_torchvision,
require_vision,
)
from transformers.utils import is_tf_available, is_torch_available, is_vision_available
if is_vision_available():
from PIL import Image
from transformers import AutoProcessor, SamImageProcessor, SamProcessor
if is_torch_available():
import torch
if is_tf_available():
import tensorflow as tf
@require_vision
@require_torchvision
class lowercase__ ( unittest.TestCase ):
def _UpperCAmelCase ( self : Any ):
"""simple docstring"""
UpperCAmelCase__ = tempfile.mkdtemp()
UpperCAmelCase__ = SamImageProcessor()
UpperCAmelCase__ = SamProcessor(_lowercase )
processor.save_pretrained(self.tmpdirname )
def _UpperCAmelCase ( self : Optional[int] , **_lowercase : str ):
"""simple docstring"""
return AutoProcessor.from_pretrained(self.tmpdirname , **_lowercase ).image_processor
def _UpperCAmelCase ( self : Optional[int] ):
"""simple docstring"""
shutil.rmtree(self.tmpdirname )
def _UpperCAmelCase ( self : List[str] ):
"""simple docstring"""
UpperCAmelCase__ = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )]
UpperCAmelCase__ = [Image.fromarray(np.moveaxis(_lowercase , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def _UpperCAmelCase ( self : Dict ):
"""simple docstring"""
UpperCAmelCase__ = SamProcessor(image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
UpperCAmelCase__ = self.get_image_processor(do_normalize=_lowercase , padding_value=1.0 )
UpperCAmelCase__ = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_lowercase , padding_value=1.0 )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , _lowercase )
def _UpperCAmelCase ( self : List[str] ):
"""simple docstring"""
UpperCAmelCase__ = self.get_image_processor()
UpperCAmelCase__ = SamProcessor(image_processor=_lowercase )
UpperCAmelCase__ = self.prepare_image_inputs()
UpperCAmelCase__ = image_processor(_lowercase , return_tensors="np" )
UpperCAmelCase__ = processor(images=_lowercase , return_tensors="np" )
input_feat_extract.pop("original_sizes" ) # pop original_sizes as it is popped in the processor
input_feat_extract.pop("reshaped_input_sizes" ) # pop original_sizes as it is popped in the processor
for key in input_feat_extract.keys():
self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 )
@require_torch
def _UpperCAmelCase ( self : List[str] ):
"""simple docstring"""
UpperCAmelCase__ = self.get_image_processor()
UpperCAmelCase__ = SamProcessor(image_processor=_lowercase )
UpperCAmelCase__ = [torch.ones((1, 3, 5, 5) )]
UpperCAmelCase__ = [[17_64, 26_46]]
UpperCAmelCase__ = [[6_83, 10_24]]
UpperCAmelCase__ = processor.post_process_masks(_lowercase , _lowercase , _lowercase )
self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) )
UpperCAmelCase__ = processor.post_process_masks(
_lowercase , torch.tensor(_lowercase ) , torch.tensor(_lowercase ) )
self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) )
# should also work with np
UpperCAmelCase__ = [np.ones((1, 3, 5, 5) )]
UpperCAmelCase__ = processor.post_process_masks(_lowercase , np.array(_lowercase ) , np.array(_lowercase ) )
self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) )
UpperCAmelCase__ = [[1, 0], [0, 1]]
with self.assertRaises(_lowercase ):
UpperCAmelCase__ = processor.post_process_masks(_lowercase , np.array(_lowercase ) , np.array(_lowercase ) )
@require_vision
@require_tf
class lowercase__ ( unittest.TestCase ):
def _UpperCAmelCase ( self : Optional[int] ):
"""simple docstring"""
UpperCAmelCase__ = tempfile.mkdtemp()
UpperCAmelCase__ = SamImageProcessor()
UpperCAmelCase__ = SamProcessor(_lowercase )
processor.save_pretrained(self.tmpdirname )
def _UpperCAmelCase ( self : Union[str, Any] , **_lowercase : int ):
"""simple docstring"""
return AutoProcessor.from_pretrained(self.tmpdirname , **_lowercase ).image_processor
def _UpperCAmelCase ( self : Dict ):
"""simple docstring"""
shutil.rmtree(self.tmpdirname )
def _UpperCAmelCase ( self : Optional[int] ):
"""simple docstring"""
UpperCAmelCase__ = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )]
UpperCAmelCase__ = [Image.fromarray(np.moveaxis(_lowercase , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def _UpperCAmelCase ( self : Optional[Any] ):
"""simple docstring"""
UpperCAmelCase__ = SamProcessor(image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
UpperCAmelCase__ = self.get_image_processor(do_normalize=_lowercase , padding_value=1.0 )
UpperCAmelCase__ = SamProcessor.from_pretrained(self.tmpdirname , do_normalize=_lowercase , padding_value=1.0 )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , _lowercase )
def _UpperCAmelCase ( self : Any ):
"""simple docstring"""
UpperCAmelCase__ = self.get_image_processor()
UpperCAmelCase__ = SamProcessor(image_processor=_lowercase )
UpperCAmelCase__ = self.prepare_image_inputs()
UpperCAmelCase__ = image_processor(_lowercase , return_tensors="np" )
UpperCAmelCase__ = processor(images=_lowercase , return_tensors="np" )
input_feat_extract.pop("original_sizes" ) # pop original_sizes as it is popped in the processor
input_feat_extract.pop("reshaped_input_sizes" ) # pop reshaped_input_sizes as it is popped in the processor
for key in input_feat_extract.keys():
self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 )
@require_tf
def _UpperCAmelCase ( self : Any ):
"""simple docstring"""
UpperCAmelCase__ = self.get_image_processor()
UpperCAmelCase__ = SamProcessor(image_processor=_lowercase )
UpperCAmelCase__ = [tf.ones((1, 3, 5, 5) )]
UpperCAmelCase__ = [[17_64, 26_46]]
UpperCAmelCase__ = [[6_83, 10_24]]
UpperCAmelCase__ = processor.post_process_masks(_lowercase , _lowercase , _lowercase , return_tensors="tf" )
self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) )
UpperCAmelCase__ = processor.post_process_masks(
_lowercase , tf.convert_to_tensor(_lowercase ) , tf.convert_to_tensor(_lowercase ) , return_tensors="tf" , )
self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) )
# should also work with np
UpperCAmelCase__ = [np.ones((1, 3, 5, 5) )]
UpperCAmelCase__ = processor.post_process_masks(
_lowercase , np.array(_lowercase ) , np.array(_lowercase ) , return_tensors="tf" )
self.assertEqual(masks[0].shape , (1, 3, 17_64, 26_46) )
UpperCAmelCase__ = [[1, 0], [0, 1]]
with self.assertRaises(tf.errors.InvalidArgumentError ):
UpperCAmelCase__ = processor.post_process_masks(
_lowercase , np.array(_lowercase ) , np.array(_lowercase ) , return_tensors="tf" )
@require_vision
@require_torchvision
class lowercase__ ( unittest.TestCase ):
def _UpperCAmelCase ( self : Union[str, Any] ):
"""simple docstring"""
UpperCAmelCase__ = tempfile.mkdtemp()
UpperCAmelCase__ = SamImageProcessor()
UpperCAmelCase__ = SamProcessor(_lowercase )
processor.save_pretrained(self.tmpdirname )
def _UpperCAmelCase ( self : str , **_lowercase : Optional[int] ):
"""simple docstring"""
return AutoProcessor.from_pretrained(self.tmpdirname , **_lowercase ).image_processor
def _UpperCAmelCase ( self : str ):
"""simple docstring"""
shutil.rmtree(self.tmpdirname )
def _UpperCAmelCase ( self : str ):
"""simple docstring"""
UpperCAmelCase__ = [np.random.randint(2_55 , size=(3, 30, 4_00) , dtype=np.uinta )]
UpperCAmelCase__ = [Image.fromarray(np.moveaxis(_lowercase , 0 , -1 ) ) for x in image_inputs]
return image_inputs
@is_pt_tf_cross_test
def _UpperCAmelCase ( self : List[str] ):
"""simple docstring"""
UpperCAmelCase__ = self.get_image_processor()
UpperCAmelCase__ = SamProcessor(image_processor=_lowercase )
UpperCAmelCase__ = np.random.randint(0 , 2 , size=(1, 3, 5, 5) ).astype(np.floataa )
UpperCAmelCase__ = [tf.convert_to_tensor(_lowercase )]
UpperCAmelCase__ = [torch.tensor(_lowercase )]
UpperCAmelCase__ = [[17_64, 26_46]]
UpperCAmelCase__ = [[6_83, 10_24]]
UpperCAmelCase__ = processor.post_process_masks(
_lowercase , _lowercase , _lowercase , return_tensors="tf" )
UpperCAmelCase__ = processor.post_process_masks(
_lowercase , _lowercase , _lowercase , return_tensors="pt" )
self.assertTrue(np.all(tf_masks[0].numpy() == pt_masks[0].numpy() ) )
@is_pt_tf_cross_test
def _UpperCAmelCase ( self : Optional[int] ):
"""simple docstring"""
UpperCAmelCase__ = self.get_image_processor()
UpperCAmelCase__ = SamProcessor(image_processor=_lowercase )
UpperCAmelCase__ = self.prepare_image_inputs()
UpperCAmelCase__ = image_processor(_lowercase , return_tensors="pt" )["pixel_values"].numpy()
UpperCAmelCase__ = processor(images=_lowercase , return_tensors="pt" )["pixel_values"].numpy()
UpperCAmelCase__ = image_processor(_lowercase , return_tensors="tf" )["pixel_values"].numpy()
UpperCAmelCase__ = processor(images=_lowercase , return_tensors="tf" )["pixel_values"].numpy()
self.assertTrue(np.allclose(_lowercase , _lowercase ) )
self.assertTrue(np.allclose(_lowercase , _lowercase ) )
self.assertTrue(np.allclose(_lowercase , _lowercase ) )
| 475 | 0 |
import os
import unittest
from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer
from ...test_tokenization_common import TokenizerTesterMixin
class A_ ( a_ , unittest.TestCase ):
_SCREAMING_SNAKE_CASE = TransfoXLTokenizer
_SCREAMING_SNAKE_CASE = False
_SCREAMING_SNAKE_CASE = False
def _UpperCAmelCase ( self : Tuple ):
super().setUp()
__a = [
"<unk>",
"[CLS]",
"[SEP]",
"want",
"unwanted",
"wa",
"un",
"running",
",",
"low",
"l",
]
__a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] )
with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer:
vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) )
def _UpperCAmelCase ( self : Union[str, Any] , **__SCREAMING_SNAKE_CASE : Dict ):
__a = True
return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **__SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( self : List[str] , __SCREAMING_SNAKE_CASE : List[str] ):
__a = "<unk> UNwanted , running"
__a = "<unk> unwanted, running"
return input_text, output_text
def _UpperCAmelCase ( self : Tuple ):
__a = TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=__SCREAMING_SNAKE_CASE )
__a = tokenizer.tokenize("<unk> UNwanted , running" )
self.assertListEqual(__SCREAMING_SNAKE_CASE , ["<unk>", "unwanted", ",", "running"] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(__SCREAMING_SNAKE_CASE ) , [0, 4, 8, 7] )
def _UpperCAmelCase ( self : Union[str, Any] ):
__a = TransfoXLTokenizer(lower_case=__SCREAMING_SNAKE_CASE )
self.assertListEqual(
tokenizer.tokenize(" \tHeLLo ! how \n Are yoU ? " ) , ["hello", "!", "how", "are", "you", "?"] )
def _UpperCAmelCase ( self : Union[str, Any] ):
__a = TransfoXLTokenizer(lower_case=__SCREAMING_SNAKE_CASE )
self.assertListEqual(
tokenizer.tokenize(" \tHeLLo ! how \n Are yoU ? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] )
def _UpperCAmelCase ( self : str ):
__a = TransfoXLTokenizer(lower_case=__SCREAMING_SNAKE_CASE )
__a = "Hello (bracket) and side-scrolled [and] Henry's $5,000 with 3.34 m. What's up!?"
__a = [
"Hello",
"(",
"bracket",
")",
"and",
"side",
"@-@",
"scrolled",
"[",
"and",
"]",
"Henry",
"'s",
"$",
"5",
"@,@",
"000",
"with",
"3",
"@.@",
"34",
"m",
".",
"What",
"'s",
"up",
"!",
"?",
]
self.assertListEqual(tokenizer.tokenize(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE )
self.assertEqual(tokenizer.convert_tokens_to_string(__SCREAMING_SNAKE_CASE ) , __SCREAMING_SNAKE_CASE )
def _UpperCAmelCase ( self : str ):
__a = self.get_tokenizer()
__a = len(__SCREAMING_SNAKE_CASE )
tokenizer.add_tokens(["new1", "new2"] )
tokenizer.move_added_token("new1" , 1 )
# Check that moved token is not copied (duplicate)
self.assertEqual(len(__SCREAMING_SNAKE_CASE ) , original_len + 2 )
# Check that token is moved to specified id
self.assertEqual(tokenizer.encode("new1" ) , [1] )
self.assertEqual(tokenizer.decode([1] ) , "new1" )
| 525 | from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
SCREAMING_SNAKE_CASE : Dict = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE : List[str] = {
"""facebook/xlm-roberta-xl""": """https://huggingface.co/facebook/xlm-roberta-xl/resolve/main/config.json""",
"""facebook/xlm-roberta-xxl""": """https://huggingface.co/facebook/xlm-roberta-xxl/resolve/main/config.json""",
# See all XLM-RoBERTa-XL models at https://huggingface.co/models?filter=xlm-roberta-xl
}
class A_ ( a_ ):
_SCREAMING_SNAKE_CASE = """xlm-roberta-xl"""
def __init__( self : str , __SCREAMING_SNAKE_CASE : int=25_08_80 , __SCREAMING_SNAKE_CASE : Dict=25_60 , __SCREAMING_SNAKE_CASE : List[str]=36 , __SCREAMING_SNAKE_CASE : int=32 , __SCREAMING_SNAKE_CASE : int=1_02_40 , __SCREAMING_SNAKE_CASE : Optional[int]="gelu" , __SCREAMING_SNAKE_CASE : int=0.1 , __SCREAMING_SNAKE_CASE : Union[str, Any]=0.1 , __SCREAMING_SNAKE_CASE : int=5_14 , __SCREAMING_SNAKE_CASE : List[Any]=1 , __SCREAMING_SNAKE_CASE : Any=0.02 , __SCREAMING_SNAKE_CASE : Optional[int]=1E-05 , __SCREAMING_SNAKE_CASE : str=1 , __SCREAMING_SNAKE_CASE : Optional[Any]=0 , __SCREAMING_SNAKE_CASE : Optional[Any]=2 , __SCREAMING_SNAKE_CASE : Optional[int]="absolute" , __SCREAMING_SNAKE_CASE : str=True , __SCREAMING_SNAKE_CASE : str=None , **__SCREAMING_SNAKE_CASE : str , ):
super().__init__(pad_token_id=__SCREAMING_SNAKE_CASE , bos_token_id=__SCREAMING_SNAKE_CASE , eos_token_id=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE )
__a = vocab_size
__a = hidden_size
__a = num_hidden_layers
__a = num_attention_heads
__a = hidden_act
__a = intermediate_size
__a = hidden_dropout_prob
__a = attention_probs_dropout_prob
__a = max_position_embeddings
__a = type_vocab_size
__a = initializer_range
__a = layer_norm_eps
__a = position_embedding_type
__a = use_cache
__a = classifier_dropout
class A_ ( a_ ):
@property
def _UpperCAmelCase ( self : List[str] ):
if self.task == "multiple-choice":
__a = {0: "batch", 1: "choice", 2: "sequence"}
else:
__a = {0: "batch", 1: "sequence"}
return OrderedDict(
[
("input_ids", dynamic_axis),
("attention_mask", dynamic_axis),
] )
| 525 | 1 |
import importlib
import sys
from argparse import REMAINDER, ArgumentParser
from pathlib import Path
import torch_xla.distributed.xla_multiprocessing as xmp
def lowerCamelCase_ ( ):
_a : Optional[int] = ArgumentParser(
description=(
'''PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes'''
) )
# Optional arguments for the launch helper
parser.add_argument('''--num_cores''' , type=UpperCamelCase_ , default=1 , help='''Number of TPU cores to use (1 or 8).''' )
# positional
parser.add_argument(
'''training_script''' , type=UpperCamelCase_ , help=(
'''The full path to the single TPU training '''
'''program/script to be launched in parallel, '''
'''followed by all the arguments for the '''
'''training script'''
) , )
# rest from the training program
parser.add_argument('''training_script_args''' , nargs=UpperCamelCase_ )
return parser.parse_args()
def lowerCamelCase_ ( ):
_a : List[str] = parse_args()
# Import training_script as a module.
_a : str = Path(args.training_script )
sys.path.append(str(script_fpath.parent.resolve() ) )
_a : Optional[Any] = script_fpath.stem
_a : Union[str, Any] = importlib.import_module(UpperCamelCase_ )
# Patch sys.argv
_a : Union[str, Any] = [args.training_script] + args.training_script_args + ['''--tpu_num_cores''', str(args.num_cores )]
xmp.spawn(mod._mp_fn , args=() , nprocs=args.num_cores )
if __name__ == "__main__":
main()
| 471 |
from math import sqrt
import numpy as np
from sympy import symbols
# Coefficient
# Speed of light (m/s)
__UpperCAmelCase : Union[str, Any] = 299_792_458
# Symbols
__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase : Any = symbols('ct x y z')
def lowerCamelCase_ ( UpperCamelCase_ ):
if velocity > c:
raise ValueError('''Speed must not exceed light speed 299,792,458 [m/s]!''' )
elif velocity < 1:
# Usually the speed should be much higher than 1 (c order of magnitude)
raise ValueError('''Speed must be greater than or equal to 1!''' )
return velocity / c
def lowerCamelCase_ ( UpperCamelCase_ ):
return 1 / sqrt(1 - beta(UpperCamelCase_ ) ** 2 )
def lowerCamelCase_ ( UpperCamelCase_ ):
return np.array(
[
[gamma(UpperCamelCase_ ), -gamma(UpperCamelCase_ ) * beta(UpperCamelCase_ ), 0, 0],
[-gamma(UpperCamelCase_ ) * beta(UpperCamelCase_ ), gamma(UpperCamelCase_ ), 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
] )
def lowerCamelCase_ ( UpperCamelCase_ , UpperCamelCase_ = None ):
# Ensure event is not empty
if event is None:
_a : Dict = np.array([ct, x, y, z] ) # Symbolic four vector
else:
event[0] *= c # x0 is ct (speed of light * time)
return transformation_matrix(UpperCamelCase_ ) @ event
if __name__ == "__main__":
import doctest
doctest.testmod()
# Example of symbolic vector:
__UpperCAmelCase : Union[str, Any] = transform(29_979_245)
print('Example of four vector: ')
print(f'''ct\' = {four_vector[0]}''')
print(f'''x\' = {four_vector[1]}''')
print(f'''y\' = {four_vector[2]}''')
print(f'''z\' = {four_vector[3]}''')
# Substitute symbols with numerical values
__UpperCAmelCase : Tuple = {ct: c, x: 1, y: 1, z: 1}
__UpperCAmelCase : str = [four_vector[i].subs(sub_dict) for i in range(4)]
print(f'''\n{numerical_vector}''')
| 471 | 1 |
import os
A__ = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
def _lowercase ( a_ : str ) -> int:
'''simple docstring'''
__magic_name__ = 0
__magic_name__ = 0
while index < len(a_ ) - 1:
__magic_name__ = SYMBOLS[numerals[index]]
__magic_name__ = SYMBOLS[numerals[index + 1]]
if current_value < next_value:
total_value -= current_value
else:
total_value += current_value
index += 1
total_value += SYMBOLS[numerals[index]]
return total_value
def _lowercase ( a_ : int ) -> str:
'''simple docstring'''
__magic_name__ = ''
__magic_name__ = num // 1_0_0_0
numerals += m_count * "M"
num %= 1_0_0_0
__magic_name__ = num // 1_0_0
if c_count == 9:
numerals += "CM"
c_count -= 9
elif c_count == 4:
numerals += "CD"
c_count -= 4
if c_count >= 5:
numerals += "D"
c_count -= 5
numerals += c_count * "C"
num %= 1_0_0
__magic_name__ = num // 1_0
if x_count == 9:
numerals += "XC"
x_count -= 9
elif x_count == 4:
numerals += "XL"
x_count -= 4
if x_count >= 5:
numerals += "L"
x_count -= 5
numerals += x_count * "X"
num %= 1_0
if num == 9:
numerals += "IX"
num -= 9
elif num == 4:
numerals += "IV"
num -= 4
if num >= 5:
numerals += "V"
num -= 5
numerals += num * "I"
return numerals
def _lowercase ( a_ : str = "/p089_roman.txt" ) -> int:
'''simple docstring'''
__magic_name__ = 0
with open(os.path.dirname(a_ ) + roman_numerals_filename ) as filea:
__magic_name__ = filea.readlines()
for line in lines:
__magic_name__ = line.strip()
__magic_name__ = parse_roman_numerals(a_ )
__magic_name__ = generate_roman_numerals(a_ )
savings += len(a_ ) - len(a_ )
return savings
if __name__ == "__main__":
print(f'''{solution() = }''')
| 184 |
import unittest
from diffusers.models.unet_ad_blocks import * # noqa F403
from diffusers.utils import torch_device
from .test_unet_blocks_common import UNetBlockTesterMixin
class __UpperCamelCase ( SCREAMING_SNAKE_CASE , unittest.TestCase ):
_lowercase : str = DownBlockaD # noqa F405
_lowercase : Union[str, Any] = "down"
def _SCREAMING_SNAKE_CASE ( self: List[str] ):
'''simple docstring'''
__magic_name__ = [-0.0232, -0.9869, 0.8054, -0.0637, -0.1688, -1.4264, 0.4470, -1.3394, 0.0904]
super().test_output(__UpperCamelCase )
class __UpperCamelCase ( SCREAMING_SNAKE_CASE , unittest.TestCase ):
_lowercase : List[str] = ResnetDownsampleBlockaD # noqa F405
_lowercase : Union[str, Any] = "down"
def _SCREAMING_SNAKE_CASE ( self: int ):
'''simple docstring'''
__magic_name__ = [0.0710, 0.2410, -0.7320, -1.0757, -1.1343, 0.3540, -0.0133, -0.2576, 0.0948]
super().test_output(__UpperCamelCase )
class __UpperCamelCase ( SCREAMING_SNAKE_CASE , unittest.TestCase ):
_lowercase : Dict = AttnDownBlockaD # noqa F405
_lowercase : List[Any] = "down"
def _SCREAMING_SNAKE_CASE ( self: Any ):
'''simple docstring'''
__magic_name__ = [0.0636, 0.8964, -0.6234, -1.0131, 0.0844, 0.4935, 0.3437, 0.0911, -0.2957]
super().test_output(__UpperCamelCase )
class __UpperCamelCase ( SCREAMING_SNAKE_CASE , unittest.TestCase ):
_lowercase : int = CrossAttnDownBlockaD # noqa F405
_lowercase : Any = "down"
def _SCREAMING_SNAKE_CASE ( self: int ):
'''simple docstring'''
__magic_name__, __magic_name__ = super().prepare_init_args_and_inputs_for_common()
__magic_name__ = 32
return init_dict, inputs_dict
def _SCREAMING_SNAKE_CASE ( self: str ):
'''simple docstring'''
__magic_name__ = [0.2238, -0.7396, -0.2255, -0.3829, 0.1925, 1.1665, 0.0603, -0.7295, 0.1983]
super().test_output(__UpperCamelCase )
class __UpperCamelCase ( SCREAMING_SNAKE_CASE , unittest.TestCase ):
_lowercase : Union[str, Any] = SimpleCrossAttnDownBlockaD # noqa F405
_lowercase : List[str] = "down"
@property
def _SCREAMING_SNAKE_CASE ( self: Any ):
'''simple docstring'''
return super().get_dummy_input(include_encoder_hidden_states=__UpperCamelCase )
def _SCREAMING_SNAKE_CASE ( self: List[Any] ):
'''simple docstring'''
__magic_name__, __magic_name__ = super().prepare_init_args_and_inputs_for_common()
__magic_name__ = 32
return init_dict, inputs_dict
@unittest.skipIf(torch_device == 'mps' , 'MPS result is not consistent' )
def _SCREAMING_SNAKE_CASE ( self: List[Any] ):
'''simple docstring'''
__magic_name__ = [0.7921, -0.0992, -0.1962, -0.7695, -0.4242, 0.7804, 0.4737, 0.2765, 0.3338]
super().test_output(__UpperCamelCase )
class __UpperCamelCase ( SCREAMING_SNAKE_CASE , unittest.TestCase ):
_lowercase : str = SkipDownBlockaD # noqa F405
_lowercase : Union[str, Any] = "down"
@property
def _SCREAMING_SNAKE_CASE ( self: Optional[int] ):
'''simple docstring'''
return super().get_dummy_input(include_skip_sample=__UpperCamelCase )
def _SCREAMING_SNAKE_CASE ( self: List[str] ):
'''simple docstring'''
__magic_name__ = [-0.0845, -0.2087, -0.2465, 0.0971, 0.1900, -0.0484, 0.2664, 0.4179, 0.5069]
super().test_output(__UpperCamelCase )
class __UpperCamelCase ( SCREAMING_SNAKE_CASE , unittest.TestCase ):
_lowercase : Tuple = AttnSkipDownBlockaD # noqa F405
_lowercase : str = "down"
@property
def _SCREAMING_SNAKE_CASE ( self: List[Any] ):
'''simple docstring'''
return super().get_dummy_input(include_skip_sample=__UpperCamelCase )
def _SCREAMING_SNAKE_CASE ( self: Dict ):
'''simple docstring'''
__magic_name__ = [0.5539, 0.1609, 0.4924, 0.0537, -0.1995, 0.4050, 0.0979, -0.2721, -0.0642]
super().test_output(__UpperCamelCase )
class __UpperCamelCase ( SCREAMING_SNAKE_CASE , unittest.TestCase ):
_lowercase : Optional[int] = DownEncoderBlockaD # noqa F405
_lowercase : List[str] = "down"
@property
def _SCREAMING_SNAKE_CASE ( self: Union[str, Any] ):
'''simple docstring'''
return super().get_dummy_input(include_temb=__UpperCamelCase )
def _SCREAMING_SNAKE_CASE ( self: Dict ):
'''simple docstring'''
__magic_name__ = {
'in_channels': 32,
'out_channels': 32,
}
__magic_name__ = self.dummy_input
return init_dict, inputs_dict
def _SCREAMING_SNAKE_CASE ( self: List[str] ):
'''simple docstring'''
__magic_name__ = [1.1102, 0.5302, 0.4872, -0.0023, -0.8042, 0.0483, -0.3489, -0.5632, 0.7626]
super().test_output(__UpperCamelCase )
class __UpperCamelCase ( SCREAMING_SNAKE_CASE , unittest.TestCase ):
_lowercase : List[Any] = AttnDownEncoderBlockaD # noqa F405
_lowercase : Optional[Any] = "down"
@property
def _SCREAMING_SNAKE_CASE ( self: List[Any] ):
'''simple docstring'''
return super().get_dummy_input(include_temb=__UpperCamelCase )
def _SCREAMING_SNAKE_CASE ( self: Optional[Any] ):
'''simple docstring'''
__magic_name__ = {
'in_channels': 32,
'out_channels': 32,
}
__magic_name__ = self.dummy_input
return init_dict, inputs_dict
def _SCREAMING_SNAKE_CASE ( self: Dict ):
'''simple docstring'''
__magic_name__ = [0.8966, -0.1486, 0.8568, 0.8141, -0.9046, -0.1342, -0.0972, -0.7417, 0.1538]
super().test_output(__UpperCamelCase )
class __UpperCamelCase ( SCREAMING_SNAKE_CASE , unittest.TestCase ):
_lowercase : List[Any] = UNetMidBlockaD # noqa F405
_lowercase : Any = "mid"
def _SCREAMING_SNAKE_CASE ( self: List[str] ):
'''simple docstring'''
__magic_name__ = {
'in_channels': 32,
'temb_channels': 1_28,
}
__magic_name__ = self.dummy_input
return init_dict, inputs_dict
def _SCREAMING_SNAKE_CASE ( self: str ):
'''simple docstring'''
__magic_name__ = [-0.1062, 1.7248, 0.3494, 1.4569, -0.0910, -1.2421, -0.9984, 0.6736, 1.0028]
super().test_output(__UpperCamelCase )
class __UpperCamelCase ( SCREAMING_SNAKE_CASE , unittest.TestCase ):
_lowercase : str = UNetMidBlockaDCrossAttn # noqa F405
_lowercase : int = "mid"
def _SCREAMING_SNAKE_CASE ( self: List[Any] ):
'''simple docstring'''
__magic_name__, __magic_name__ = super().prepare_init_args_and_inputs_for_common()
__magic_name__ = 32
return init_dict, inputs_dict
def _SCREAMING_SNAKE_CASE ( self: Tuple ):
'''simple docstring'''
__magic_name__ = [0.0187, 2.4220, 0.4484, 1.1203, -0.6121, -1.5122, -0.8270, 0.7851, 1.8335]
super().test_output(__UpperCamelCase )
class __UpperCamelCase ( SCREAMING_SNAKE_CASE , unittest.TestCase ):
_lowercase : Tuple = UNetMidBlockaDSimpleCrossAttn # noqa F405
_lowercase : str = "mid"
@property
def _SCREAMING_SNAKE_CASE ( self: Any ):
'''simple docstring'''
return super().get_dummy_input(include_encoder_hidden_states=__UpperCamelCase )
def _SCREAMING_SNAKE_CASE ( self: Tuple ):
'''simple docstring'''
__magic_name__, __magic_name__ = super().prepare_init_args_and_inputs_for_common()
__magic_name__ = 32
return init_dict, inputs_dict
def _SCREAMING_SNAKE_CASE ( self: Any ):
'''simple docstring'''
__magic_name__ = [0.7143, 1.9974, 0.5448, 1.3977, 0.1282, -1.1237, -1.4238, 0.5530, 0.8880]
super().test_output(__UpperCamelCase )
class __UpperCamelCase ( SCREAMING_SNAKE_CASE , unittest.TestCase ):
_lowercase : List[Any] = UpBlockaD # noqa F405
_lowercase : List[Any] = "up"
@property
def _SCREAMING_SNAKE_CASE ( self: Tuple ):
'''simple docstring'''
return super().get_dummy_input(include_res_hidden_states_tuple=__UpperCamelCase )
def _SCREAMING_SNAKE_CASE ( self: Any ):
'''simple docstring'''
__magic_name__ = [-0.2041, -0.4165, -0.3022, 0.0041, -0.6628, -0.7053, 0.1928, -0.0325, 0.0523]
super().test_output(__UpperCamelCase )
class __UpperCamelCase ( SCREAMING_SNAKE_CASE , unittest.TestCase ):
_lowercase : List[Any] = ResnetUpsampleBlockaD # noqa F405
_lowercase : Dict = "up"
@property
def _SCREAMING_SNAKE_CASE ( self: Optional[int] ):
'''simple docstring'''
return super().get_dummy_input(include_res_hidden_states_tuple=__UpperCamelCase )
def _SCREAMING_SNAKE_CASE ( self: Dict ):
'''simple docstring'''
__magic_name__ = [0.2287, 0.3549, -0.1346, 0.4797, -0.1715, -0.9649, 0.7305, -0.5864, -0.6244]
super().test_output(__UpperCamelCase )
class __UpperCamelCase ( SCREAMING_SNAKE_CASE , unittest.TestCase ):
_lowercase : Any = CrossAttnUpBlockaD # noqa F405
_lowercase : Union[str, Any] = "up"
@property
def _SCREAMING_SNAKE_CASE ( self: Optional[int] ):
'''simple docstring'''
return super().get_dummy_input(include_res_hidden_states_tuple=__UpperCamelCase )
def _SCREAMING_SNAKE_CASE ( self: str ):
'''simple docstring'''
__magic_name__, __magic_name__ = super().prepare_init_args_and_inputs_for_common()
__magic_name__ = 32
return init_dict, inputs_dict
def _SCREAMING_SNAKE_CASE ( self: Any ):
'''simple docstring'''
__magic_name__ = [-0.1403, -0.3515, -0.0420, -0.1425, 0.3167, 0.5094, -0.2181, 0.5931, 0.5582]
super().test_output(__UpperCamelCase )
class __UpperCamelCase ( SCREAMING_SNAKE_CASE , unittest.TestCase ):
_lowercase : str = SimpleCrossAttnUpBlockaD # noqa F405
_lowercase : Tuple = "up"
@property
def _SCREAMING_SNAKE_CASE ( self: List[str] ):
'''simple docstring'''
return super().get_dummy_input(include_res_hidden_states_tuple=__UpperCamelCase , include_encoder_hidden_states=__UpperCamelCase )
def _SCREAMING_SNAKE_CASE ( self: Union[str, Any] ):
'''simple docstring'''
__magic_name__, __magic_name__ = super().prepare_init_args_and_inputs_for_common()
__magic_name__ = 32
return init_dict, inputs_dict
def _SCREAMING_SNAKE_CASE ( self: List[Any] ):
'''simple docstring'''
__magic_name__ = [0.2645, 0.1480, 0.0909, 0.8044, -0.9758, -0.9083, 0.0994, -1.1453, -0.7402]
super().test_output(__UpperCamelCase )
class __UpperCamelCase ( SCREAMING_SNAKE_CASE , unittest.TestCase ):
_lowercase : Optional[Any] = AttnUpBlockaD # noqa F405
_lowercase : Optional[int] = "up"
@property
def _SCREAMING_SNAKE_CASE ( self: str ):
'''simple docstring'''
return super().get_dummy_input(include_res_hidden_states_tuple=__UpperCamelCase )
@unittest.skipIf(torch_device == 'mps' , 'MPS result is not consistent' )
def _SCREAMING_SNAKE_CASE ( self: Union[str, Any] ):
'''simple docstring'''
__magic_name__ = [0.0979, 0.1326, 0.0021, 0.0659, 0.2249, 0.0059, 0.1132, 0.5952, 0.1033]
super().test_output(__UpperCamelCase )
class __UpperCamelCase ( SCREAMING_SNAKE_CASE , unittest.TestCase ):
_lowercase : Union[str, Any] = SkipUpBlockaD # noqa F405
_lowercase : int = "up"
@property
def _SCREAMING_SNAKE_CASE ( self: Union[str, Any] ):
'''simple docstring'''
return super().get_dummy_input(include_res_hidden_states_tuple=__UpperCamelCase )
def _SCREAMING_SNAKE_CASE ( self: Union[str, Any] ):
'''simple docstring'''
__magic_name__ = [-0.0893, -0.1234, -0.1506, -0.0332, 0.0123, -0.0211, 0.0566, 0.0143, 0.0362]
super().test_output(__UpperCamelCase )
class __UpperCamelCase ( SCREAMING_SNAKE_CASE , unittest.TestCase ):
_lowercase : Union[str, Any] = AttnSkipUpBlockaD # noqa F405
_lowercase : Optional[Any] = "up"
@property
def _SCREAMING_SNAKE_CASE ( self: Optional[Any] ):
'''simple docstring'''
return super().get_dummy_input(include_res_hidden_states_tuple=__UpperCamelCase )
def _SCREAMING_SNAKE_CASE ( self: Tuple ):
'''simple docstring'''
__magic_name__ = [0.0361, 0.0617, 0.2787, -0.0350, 0.0342, 0.3421, -0.0843, 0.0913, 0.3015]
super().test_output(__UpperCamelCase )
class __UpperCamelCase ( SCREAMING_SNAKE_CASE , unittest.TestCase ):
_lowercase : List[str] = UpDecoderBlockaD # noqa F405
_lowercase : List[str] = "up"
@property
def _SCREAMING_SNAKE_CASE ( self: List[Any] ):
'''simple docstring'''
return super().get_dummy_input(include_temb=__UpperCamelCase )
def _SCREAMING_SNAKE_CASE ( self: List[Any] ):
'''simple docstring'''
__magic_name__ = {'in_channels': 32, 'out_channels': 32}
__magic_name__ = self.dummy_input
return init_dict, inputs_dict
def _SCREAMING_SNAKE_CASE ( self: Optional[Any] ):
'''simple docstring'''
__magic_name__ = [0.4404, 0.1998, -0.9886, -0.3320, -0.3128, -0.7034, -0.6955, -0.2338, -0.3137]
super().test_output(__UpperCamelCase )
class __UpperCamelCase ( SCREAMING_SNAKE_CASE , unittest.TestCase ):
_lowercase : Optional[Any] = AttnUpDecoderBlockaD # noqa F405
_lowercase : Any = "up"
@property
def _SCREAMING_SNAKE_CASE ( self: Dict ):
'''simple docstring'''
return super().get_dummy_input(include_temb=__UpperCamelCase )
def _SCREAMING_SNAKE_CASE ( self: str ):
'''simple docstring'''
__magic_name__ = {'in_channels': 32, 'out_channels': 32}
__magic_name__ = self.dummy_input
return init_dict, inputs_dict
def _SCREAMING_SNAKE_CASE ( self: List[Any] ):
'''simple docstring'''
__magic_name__ = [0.6738, 0.4491, 0.1055, 1.0710, 0.7316, 0.3339, 0.3352, 0.1023, 0.3568]
super().test_output(__UpperCamelCase )
| 184 | 1 |
import re
from flax.core.frozen_dict import freeze
from flax.traverse_util import flatten_dict, unflatten_dict
from jax.experimental import PartitionSpec as P
# Sentinels
lowerCamelCase_ : str = object()
# For specifying empty leaf dict `{}`
lowerCamelCase_ : List[Any] = object()
def A__ ( lowerCamelCase , lowerCamelCase ) -> Optional[int]:
UpperCamelCase_: int = tuple((re.compile(x + """$""" ) for x in qs) )
for i in range(len(lowerCamelCase ) - len(lowerCamelCase ) + 1 ):
UpperCamelCase_: Dict = [x.match(lowerCamelCase ) for x, y in zip(lowerCamelCase , ks[i:] )]
if matches and all(lowerCamelCase ):
return True
return False
def A__ ( lowerCamelCase ) -> Optional[int]:
def replace(lowerCamelCase , lowerCamelCase ):
for rule, replacement in rules:
if _match(lowerCamelCase , lowerCamelCase ):
return replacement
return val
return replace
def A__ ( ) -> Dict:
return [
# embeddings
(("transformer", "wpe", "embedding"), P("""mp""" , lowerCamelCase )),
(("transformer", "wte", "embedding"), P("""mp""" , lowerCamelCase )),
# atention
(("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(lowerCamelCase , """mp""" )),
(("attention", "out_proj", "kernel"), P("""mp""" , lowerCamelCase )),
(("attention", "out_proj", "bias"), None),
# mlp
(("mlp", "c_fc", "kernel"), P(lowerCamelCase , """mp""" )),
(("mlp", "c_fc", "bias"), P("""mp""" )),
(("mlp", "c_proj", "kernel"), P("""mp""" , lowerCamelCase )),
(("mlp", "c_proj", "bias"), None),
# layer norms
((r"ln_\d+", "bias"), None),
((r"\d+", r"ln_\d+", "scale"), None),
(("ln_f", "bias"), None),
(("ln_f", "scale"), None),
]
def A__ ( lowerCamelCase ) -> List[Any]:
UpperCamelCase_: Optional[Any] = _get_partition_rules()
UpperCamelCase_: Optional[int] = _replacement_rules(lowerCamelCase )
UpperCamelCase_: List[str] = {k: _unmatched for k in flatten_dict(lowerCamelCase )}
UpperCamelCase_: List[str] = {k: replace(lowerCamelCase , lowerCamelCase ) for k, v in initd.items()}
assert _unmatched not in result.values(), "Incomplete partition spec."
return freeze(unflatten_dict(lowerCamelCase ) )
| 548 |
import argparse
from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection
from diffusers import UnCLIPImageVariationPipeline, UnCLIPPipeline
if __name__ == "__main__":
lowerCamelCase_ : int = argparse.ArgumentParser()
parser.add_argument("""--dump_path""", default=None, type=str, required=True, help="""Path to the output model.""")
parser.add_argument(
"""--txt2img_unclip""",
default="""kakaobrain/karlo-v1-alpha""",
type=str,
required=False,
help="""The pretrained txt2img unclip.""",
)
lowerCamelCase_ : Dict = parser.parse_args()
lowerCamelCase_ : str = UnCLIPPipeline.from_pretrained(args.txtaimg_unclip)
lowerCamelCase_ : int = CLIPImageProcessor()
lowerCamelCase_ : Any = CLIPVisionModelWithProjection.from_pretrained("""openai/clip-vit-large-patch14""")
lowerCamelCase_ : Union[str, Any] = UnCLIPImageVariationPipeline(
decoder=txtaimg.decoder,
text_encoder=txtaimg.text_encoder,
tokenizer=txtaimg.tokenizer,
text_proj=txtaimg.text_proj,
feature_extractor=feature_extractor,
image_encoder=image_encoder,
super_res_first=txtaimg.super_res_first,
super_res_last=txtaimg.super_res_last,
decoder_scheduler=txtaimg.decoder_scheduler,
super_res_scheduler=txtaimg.super_res_scheduler,
)
imgaimg.save_pretrained(args.dump_path)
| 548 | 1 |
import functools
def a__ (__lowercase :str , __lowercase :str ) -> int:
_A : Dict = len(__lowercase )
_A : int = len(__lowercase )
@functools.cache
def min_distance(__lowercase :int , __lowercase :int ) -> 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
_A : Any = int(worda[indexa] != worda[indexa] ) # current letters not identical
return min(
1 + min_distance(indexa + 1 , __lowercase ) , 1 + min_distance(__lowercase , indexa + 1 ) , diff + min_distance(indexa + 1 , indexa + 1 ) , )
return min_distance(0 , 0 )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 713 |
from collections import OrderedDict
from typing import Mapping
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
_UpperCamelCase : Dict =logging.get_logger(__name__)
_UpperCamelCase : Optional[Any] ={
'facebook/xmod-base': 'https://huggingface.co/facebook/xmod-base/resolve/main/config.json',
'facebook/xmod-large-prenorm': 'https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json',
'facebook/xmod-base-13-125k': 'https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json',
'facebook/xmod-base-30-125k': 'https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json',
'facebook/xmod-base-30-195k': 'https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json',
'facebook/xmod-base-60-125k': 'https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json',
'facebook/xmod-base-60-265k': 'https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json',
'facebook/xmod-base-75-125k': 'https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json',
'facebook/xmod-base-75-269k': 'https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json',
}
class UpperCAmelCase__ ( __snake_case ):
__snake_case : Any = "xmod"
def __init__( self ,A__=30522 ,A__=768 ,A__=12 ,A__=12 ,A__=3072 ,A__="gelu" ,A__=0.1 ,A__=0.1 ,A__=512 ,A__=2 ,A__=0.02 ,A__=1E-12 ,A__=1 ,A__=0 ,A__=2 ,A__="absolute" ,A__=True ,A__=None ,A__=False ,A__=2 ,A__=False ,A__=True ,A__=True ,A__=("en_XX",) ,A__=None ,**A__ ,):
super().__init__(pad_token_id=A__ ,bos_token_id=A__ ,eos_token_id=A__ ,**A__ )
_A : Union[str, Any] = vocab_size
_A : List[str] = hidden_size
_A : Union[str, Any] = num_hidden_layers
_A : str = num_attention_heads
_A : Tuple = hidden_act
_A : Optional[int] = intermediate_size
_A : List[str] = hidden_dropout_prob
_A : str = attention_probs_dropout_prob
_A : Dict = max_position_embeddings
_A : Optional[int] = type_vocab_size
_A : List[str] = initializer_range
_A : Tuple = layer_norm_eps
_A : int = position_embedding_type
_A : str = use_cache
_A : int = classifier_dropout
_A : Optional[Any] = pre_norm
_A : Dict = adapter_reduction_factor
_A : List[Any] = adapter_layer_norm
_A : Optional[Any] = adapter_reuse_layer_norm
_A : Optional[Any] = ln_before_adapter
_A : int = list(A__ )
_A : str = default_language
class UpperCAmelCase__ ( __snake_case ):
@property
def A__ ( self ):
if self.task == "multiple-choice":
_A : Tuple = {0: '''batch''', 1: '''choice''', 2: '''sequence'''}
else:
_A : Union[str, Any] = {0: '''batch''', 1: '''sequence'''}
return OrderedDict(
[
('''input_ids''', dynamic_axis),
('''attention_mask''', dynamic_axis),
] )
| 332 | 0 |
'''simple docstring'''
import unittest
from transformers import DebertaVaTokenizer, DebertaVaTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin
UpperCamelCase__ : Union[str, Any] = get_tests_dir('fixtures/spiece.model')
@require_sentencepiece
@require_tokenizers
class _lowercase ( lowerCAmelCase ,unittest.TestCase ):
'''simple docstring'''
UpperCAmelCase_ : str = DebertaVaTokenizer
UpperCAmelCase_ : Union[str, Any] = DebertaVaTokenizerFast
UpperCAmelCase_ : Union[str, Any] = True
UpperCAmelCase_ : Dict = True
def lowerCAmelCase__ ( self ) -> int:
'''simple docstring'''
super().setUp()
# We have a SentencePiece fixture for testing
UpperCAmelCase__ : Union[str, Any] = DebertaVaTokenizer(lowerCamelCase_ ,unk_token='''<unk>''' )
tokenizer.save_pretrained(self.tmpdirname )
def lowerCAmelCase__ ( self ,lowerCamelCase_ ) -> List[Any]:
'''simple docstring'''
UpperCAmelCase__ : Optional[int] = '''this is a test'''
UpperCAmelCase__ : List[Any] = '''this is a test'''
return input_text, output_text
def lowerCAmelCase__ ( self ) -> Dict:
'''simple docstring'''
UpperCAmelCase__ : int = '''<pad>'''
UpperCAmelCase__ : Dict = 0
self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCamelCase_ ) ,lowerCamelCase_ )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCamelCase_ ) ,lowerCamelCase_ )
def lowerCAmelCase__ ( self ) -> Optional[int]:
'''simple docstring'''
UpperCAmelCase__ : List[Any] = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] ,'''<pad>''' )
self.assertEqual(vocab_keys[1] ,'''<unk>''' )
self.assertEqual(vocab_keys[-1] ,'''[PAD]''' )
self.assertEqual(len(lowerCamelCase_ ) ,30001 )
def lowerCAmelCase__ ( self ) -> str:
'''simple docstring'''
self.assertEqual(self.get_tokenizer().vocab_size ,30000 )
def lowerCAmelCase__ ( self ) -> Union[str, Any]:
'''simple docstring'''
UpperCAmelCase__ : Optional[int] = ''' \tHeLLo!how \n Are yoU? '''
UpperCAmelCase__ : List[str] = ['''▁hello''', '''!''', '''how''', '''▁are''', '''▁you''', '''?''']
# fmt: on
UpperCAmelCase__ : Optional[Any] = DebertaVaTokenizer(lowerCamelCase_ ,do_lower_case=lowerCamelCase_ )
UpperCAmelCase__ : List[Any] = tokenizer.convert_ids_to_tokens(tokenizer.encode(lowerCamelCase_ ,add_special_tokens=lowerCamelCase_ ) )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
UpperCAmelCase__ : int = DebertaVaTokenizerFast(lowerCamelCase_ ,do_lower_case=lowerCamelCase_ )
UpperCAmelCase__ : List[Any] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(lowerCamelCase_ ,add_special_tokens=lowerCamelCase_ ) )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
@unittest.skip('''There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.''' )
def lowerCAmelCase__ ( self ) -> str:
'''simple docstring'''
pass
@unittest.skip('''There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.''' )
def lowerCAmelCase__ ( self ) -> Any:
'''simple docstring'''
pass
def lowerCAmelCase__ ( self ) -> Any:
'''simple docstring'''
UpperCAmelCase__ : int = '''I was born in 92000, and this is falsé.'''
UpperCAmelCase__ : Optional[Any] = ['''▁''', '''<unk>''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', '''▁''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''▁''', '''.''', ]
# fmt: on
UpperCAmelCase__ : str = DebertaVaTokenizer(lowerCamelCase_ ,split_by_punct=lowerCamelCase_ )
UpperCAmelCase__ : Optional[int] = tokenizer.convert_ids_to_tokens(tokenizer.encode(lowerCamelCase_ ,add_special_tokens=lowerCamelCase_ ) )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
UpperCAmelCase__ : Any = DebertaVaTokenizerFast(lowerCamelCase_ ,split_by_punct=lowerCamelCase_ )
UpperCAmelCase__ : List[str] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(lowerCamelCase_ ,add_special_tokens=lowerCamelCase_ ) )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
def lowerCAmelCase__ ( self ) -> Any:
'''simple docstring'''
UpperCAmelCase__ : Optional[int] = '''I was born in 92000, and this is falsé.'''
UpperCAmelCase__ : Optional[Any] = ['''▁i''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', '''▁''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''▁''', '''.''', ]
# fmt: on
UpperCAmelCase__ : List[str] = DebertaVaTokenizer(lowerCamelCase_ ,do_lower_case=lowerCamelCase_ ,split_by_punct=lowerCamelCase_ )
UpperCAmelCase__ : Optional[Any] = tokenizer.convert_ids_to_tokens(tokenizer.encode(lowerCamelCase_ ,add_special_tokens=lowerCamelCase_ ) )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
UpperCAmelCase__ : int = DebertaVaTokenizerFast(lowerCamelCase_ ,do_lower_case=lowerCamelCase_ ,split_by_punct=lowerCamelCase_ )
UpperCAmelCase__ : List[str] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(lowerCamelCase_ ,add_special_tokens=lowerCamelCase_ ) )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
def lowerCAmelCase__ ( self ) -> List[Any]:
'''simple docstring'''
UpperCAmelCase__ : str = '''I was born in 92000, and this is falsé.'''
UpperCAmelCase__ : Optional[Any] = ['''▁i''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''.''', ]
# fmt: on
UpperCAmelCase__ : str = DebertaVaTokenizer(lowerCamelCase_ ,do_lower_case=lowerCamelCase_ ,split_by_punct=lowerCamelCase_ )
UpperCAmelCase__ : Union[str, Any] = tokenizer.convert_ids_to_tokens(tokenizer.encode(lowerCamelCase_ ,add_special_tokens=lowerCamelCase_ ) )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
UpperCAmelCase__ : Any = DebertaVaTokenizerFast(lowerCamelCase_ ,do_lower_case=lowerCamelCase_ ,split_by_punct=lowerCamelCase_ )
UpperCAmelCase__ : Optional[Any] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(lowerCamelCase_ ,add_special_tokens=lowerCamelCase_ ) )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
def lowerCAmelCase__ ( self ) -> List[str]:
'''simple docstring'''
UpperCAmelCase__ : Dict = '''I was born in 92000, and this is falsé.'''
UpperCAmelCase__ : str = ['''▁''', '''<unk>''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', '''▁''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''▁''', '''.''', ]
# fmt: on
UpperCAmelCase__ : Any = DebertaVaTokenizer(lowerCamelCase_ ,do_lower_case=lowerCamelCase_ ,split_by_punct=lowerCamelCase_ )
UpperCAmelCase__ : str = tokenizer.convert_ids_to_tokens(tokenizer.encode(lowerCamelCase_ ,add_special_tokens=lowerCamelCase_ ) )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
UpperCAmelCase__ : List[str] = DebertaVaTokenizerFast(lowerCamelCase_ ,do_lower_case=lowerCamelCase_ ,split_by_punct=lowerCamelCase_ )
UpperCAmelCase__ : Optional[int] = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(lowerCamelCase_ ,add_special_tokens=lowerCamelCase_ ) )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
def lowerCAmelCase__ ( self ) -> int:
'''simple docstring'''
UpperCAmelCase__ : Optional[int] = ''' \tHeLLo!how \n Are yoU? '''
UpperCAmelCase__ : Dict = ['''▁''', '''<unk>''', '''e''', '''<unk>''', '''o''', '''!''', '''how''', '''▁''', '''<unk>''', '''re''', '''▁yo''', '''<unk>''', '''?''']
# fmt: on
UpperCAmelCase__ : Optional[Any] = DebertaVaTokenizer(lowerCamelCase_ ,do_lower_case=lowerCamelCase_ ,split_by_punct=lowerCamelCase_ )
UpperCAmelCase__ : Dict = tokenizer.convert_ids_to_tokens(tokenizer.encode(lowerCamelCase_ ,add_special_tokens=lowerCamelCase_ ) )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
UpperCAmelCase__ : int = DebertaVaTokenizerFast(lowerCamelCase_ ,do_lower_case=lowerCamelCase_ ,split_by_punct=lowerCamelCase_ )
UpperCAmelCase__ : int = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(lowerCamelCase_ ,add_special_tokens=lowerCamelCase_ ) )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
def lowerCAmelCase__ ( self ) -> int:
'''simple docstring'''
UpperCAmelCase__ : Optional[int] = self.get_tokenizer()
UpperCAmelCase__ : Dict = self.get_rust_tokenizer()
UpperCAmelCase__ : List[str] = '''I was born in 92000, and this is falsé.'''
UpperCAmelCase__ : List[str] = tokenizer.convert_ids_to_tokens(tokenizer.encode(lowerCamelCase_ ,add_special_tokens=lowerCamelCase_ ) )
UpperCAmelCase__ : Any = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(lowerCamelCase_ ,add_special_tokens=lowerCamelCase_ ) )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
UpperCAmelCase__ : List[Any] = tokenizer.encode(lowerCamelCase_ ,add_special_tokens=lowerCamelCase_ )
UpperCAmelCase__ : List[str] = rust_tokenizer.encode(lowerCamelCase_ ,add_special_tokens=lowerCamelCase_ )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
UpperCAmelCase__ : Optional[int] = self.get_rust_tokenizer()
UpperCAmelCase__ : int = tokenizer.encode(lowerCamelCase_ )
UpperCAmelCase__ : Union[str, Any] = rust_tokenizer.encode(lowerCamelCase_ )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
def lowerCAmelCase__ ( self ) -> Optional[int]:
'''simple docstring'''
UpperCAmelCase__ : Tuple = '''This is a test'''
UpperCAmelCase__ : Any = [13, 1, 4398, 25, 21, 1289]
UpperCAmelCase__ : int = ['''▁''', '''T''', '''his''', '''▁is''', '''▁a''', '''▁test''']
UpperCAmelCase__ : Optional[int] = ['''▁''', '''<unk>''', '''his''', '''▁is''', '''▁a''', '''▁test''']
UpperCAmelCase__ : Union[str, Any] = DebertaVaTokenizer(lowerCamelCase_ ,keep_accents=lowerCamelCase_ )
UpperCAmelCase__ : Any = DebertaVaTokenizerFast(lowerCamelCase_ ,keep_accents=lowerCamelCase_ )
UpperCAmelCase__ : List[Any] = tokenizer.encode(lowerCamelCase_ ,add_special_tokens=lowerCamelCase_ )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
UpperCAmelCase__ : Any = tokenizer.tokenize(lowerCamelCase_ )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
UpperCAmelCase__ : int = tokenizer.convert_ids_to_tokens(lowerCamelCase_ )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
UpperCAmelCase__ : str = rust_tokenizer.encode(lowerCamelCase_ ,add_special_tokens=lowerCamelCase_ )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
UpperCAmelCase__ : List[str] = rust_tokenizer.tokenize(lowerCamelCase_ )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
UpperCAmelCase__ : List[str] = rust_tokenizer.convert_ids_to_tokens(lowerCamelCase_ )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
# fmt: off
UpperCAmelCase__ : Tuple = '''I was born in 92000, and this is falsé.'''
UpperCAmelCase__ : Dict = [13, 1, 23, 386, 19, 561, 3050, 15, 17, 48, 25, 8256, 18, 1, 9]
UpperCAmelCase__ : Union[str, Any] = ['''▁''', '''I''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''é''', '''.''', ]
UpperCAmelCase__ : Any = ['''▁''', '''<unk>''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''.''', ]
# fmt: on
UpperCAmelCase__ : Tuple = tokenizer.encode(lowerCamelCase_ ,add_special_tokens=lowerCamelCase_ )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
UpperCAmelCase__ : List[Any] = tokenizer.tokenize(lowerCamelCase_ )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
UpperCAmelCase__ : int = tokenizer.convert_ids_to_tokens(lowerCamelCase_ )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
UpperCAmelCase__ : str = rust_tokenizer.encode(lowerCamelCase_ ,add_special_tokens=lowerCamelCase_ )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
UpperCAmelCase__ : int = rust_tokenizer.tokenize(lowerCamelCase_ )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
UpperCAmelCase__ : Optional[Any] = rust_tokenizer.convert_ids_to_tokens(lowerCamelCase_ )
self.assertListEqual(lowerCamelCase_ ,lowerCamelCase_ )
def lowerCAmelCase__ ( self ) -> Any:
'''simple docstring'''
UpperCAmelCase__ : Union[str, Any] = DebertaVaTokenizer(lowerCamelCase_ )
UpperCAmelCase__ : List[Any] = tokenizer.encode('''sequence builders''' )
UpperCAmelCase__ : str = tokenizer.encode('''multi-sequence build''' )
UpperCAmelCase__ : Tuple = tokenizer.build_inputs_with_special_tokens(lowerCamelCase_ )
UpperCAmelCase__ : Any = tokenizer.build_inputs_with_special_tokens(lowerCamelCase_ ,lowerCamelCase_ )
self.assertEqual([tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] ,lowerCamelCase_ )
self.assertEqual(
[tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [tokenizer.sep_token_id] ,lowerCamelCase_ ,)
@slow
def lowerCAmelCase__ ( self ) -> List[Any]:
'''simple docstring'''
UpperCAmelCase__ : Optional[Any] = {'''input_ids''': [[1, 39867, 36, 19390, 486, 27, 35052, 81436, 18, 60685, 1225, 7, 35052, 81436, 18, 9367, 16899, 18, 15937, 53, 594, 773, 18, 16287, 30465, 36, 15937, 6, 41139, 38, 36979, 60763, 191, 6, 34132, 99, 6, 50538, 390, 43230, 6, 34132, 2779, 20850, 14, 699, 1072, 1194, 36, 382, 10901, 53, 7, 699, 1072, 2084, 36, 20422, 630, 53, 19, 105, 3049, 1896, 1053, 16899, 1506, 11, 37978, 4243, 7, 1237, 31869, 200, 16566, 654, 6, 35052, 81436, 7, 55630, 13593, 4, 2], [1, 26, 15011, 13, 667, 8, 1053, 18, 23611, 1237, 72356, 12820, 34, 104134, 1209, 35, 13313, 6627, 21, 202, 347, 7, 164, 2399, 11, 46, 4485, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 1232, 2864, 15785, 14951, 105, 5, 8581, 1250, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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]], '''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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=lowerCamelCase_ ,model_name='''microsoft/deberta-v2-xlarge''' ,revision='''ad6e42c1532ddf3a15c39246b63f5559d558b670''' ,)
| 614 | '''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
UpperCamelCase__ : str = {
'configuration_git': ['GIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GitConfig', 'GitVisionConfig'],
'processing_git': ['GitProcessor'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
UpperCamelCase__ : str = [
'GIT_PRETRAINED_MODEL_ARCHIVE_LIST',
'GitForCausalLM',
'GitModel',
'GitPreTrainedModel',
'GitVisionModel',
]
if TYPE_CHECKING:
from .configuration_git import GIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GitConfig, GitVisionConfig
from .processing_git import GitProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_git import (
GIT_PRETRAINED_MODEL_ARCHIVE_LIST,
GitForCausalLM,
GitModel,
GitPreTrainedModel,
GitVisionModel,
)
else:
import sys
UpperCamelCase__ : Tuple = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 614 | 1 |
"""simple docstring"""
from __future__ import annotations
import time
UpperCamelCase = list[tuple[int, int]]
UpperCamelCase = [
[0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0],
]
UpperCamelCase = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right
class lowercase_ :
def __init__( self , a_ , a_ , a_ , a_ , a_ ) ->str:
'''simple docstring'''
_a = pos_x
_a = pos_y
_a = (pos_y, pos_x)
_a = goal_x
_a = goal_y
_a = parent
class lowercase_ :
def __init__( self , a_ , a_ ) ->Any:
'''simple docstring'''
_a = Node(start[1] , start[0] , goal[1] , goal[0] , a_ )
_a = Node(goal[1] , goal[0] , goal[1] , goal[0] , a_ )
_a = [self.start]
_a = False
def lowerCamelCase__ ( self ) ->Path | None:
'''simple docstring'''
while self.node_queue:
_a = self.node_queue.pop(0 )
if current_node.pos == self.target.pos:
_a = True
return self.retrace_path(a_ )
_a = self.get_successors(a_ )
for node in successors:
self.node_queue.append(a_ )
if not self.reached:
return [self.start.pos]
return None
def lowerCamelCase__ ( self , a_ ) ->list[Node]:
'''simple docstring'''
_a = []
for action in delta:
_a = parent.pos_x + action[1]
_a = parent.pos_y + action[0]
if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(a_ ) - 1):
continue
if grid[pos_y][pos_x] != 0:
continue
successors.append(
Node(a_ , a_ , self.target.pos_y , self.target.pos_x , a_ ) )
return successors
def lowerCamelCase__ ( self , a_ ) ->Path:
'''simple docstring'''
_a = node
_a = []
while current_node is not None:
path.append((current_node.pos_y, current_node.pos_x) )
_a = current_node.parent
path.reverse()
return path
class lowercase_ :
def __init__( self , a_ , a_ ) ->Any:
'''simple docstring'''
_a = BreadthFirstSearch(a_ , a_ )
_a = BreadthFirstSearch(a_ , a_ )
_a = False
def lowerCamelCase__ ( self ) ->Path | None:
'''simple docstring'''
while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue:
_a = self.fwd_bfs.node_queue.pop(0 )
_a = self.bwd_bfs.node_queue.pop(0 )
if current_bwd_node.pos == current_fwd_node.pos:
_a = True
return self.retrace_bidirectional_path(
a_ , a_ )
_a = current_bwd_node
_a = current_fwd_node
_a = {
self.fwd_bfs: self.fwd_bfs.get_successors(a_ ),
self.bwd_bfs: self.bwd_bfs.get_successors(a_ ),
}
for bfs in [self.fwd_bfs, self.bwd_bfs]:
for node in successors[bfs]:
bfs.node_queue.append(a_ )
if not self.reached:
return [self.fwd_bfs.start.pos]
return None
def lowerCamelCase__ ( self , a_ , a_ ) ->Path:
'''simple docstring'''
_a = self.fwd_bfs.retrace_path(a_ )
_a = self.bwd_bfs.retrace_path(a_ )
bwd_path.pop()
bwd_path.reverse()
_a = fwd_path + bwd_path
return path
if __name__ == "__main__":
# all coordinates are given in format [y,x]
import doctest
doctest.testmod()
UpperCamelCase = (0, 0)
UpperCamelCase = (len(grid) - 1, len(grid[0]) - 1)
for elem in grid:
print(elem)
UpperCamelCase = time.time()
UpperCamelCase = BreadthFirstSearch(init, goal)
UpperCamelCase = bfs.search()
UpperCamelCase = time.time() - start_bfs_time
print("""Unidirectional BFS computation time : """, bfs_time)
UpperCamelCase = time.time()
UpperCamelCase = BidirectionalBreadthFirstSearch(init, goal)
UpperCamelCase = bd_bfs.search()
UpperCamelCase = time.time() - start_bd_bfs_time
print("""Bidirectional BFS computation time : """, bd_bfs_time)
| 612 |
"""simple docstring"""
import torch
from diffusers import KDPMaDiscreteScheduler
from diffusers.utils import torch_device
from .test_schedulers import SchedulerCommonTest
class lowercase_ (_UpperCAmelCase ):
A__ : Tuple = (KDPMaDiscreteScheduler,)
A__ : Tuple = 10
def lowerCamelCase__ ( self , **a_ ) ->List[str]:
'''simple docstring'''
_a = {
"num_train_timesteps": 1_1_0_0,
"beta_start": 0.0_001,
"beta_end": 0.02,
"beta_schedule": "linear",
}
config.update(**a_ )
return config
def lowerCamelCase__ ( self ) ->Tuple:
'''simple docstring'''
for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]:
self.check_over_configs(num_train_timesteps=a_ )
def lowerCamelCase__ ( self ) ->List[Any]:
'''simple docstring'''
for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ):
self.check_over_configs(beta_start=a_ , beta_end=a_ )
def lowerCamelCase__ ( self ) ->Any:
'''simple docstring'''
for schedule in ["linear", "scaled_linear"]:
self.check_over_configs(beta_schedule=a_ )
def lowerCamelCase__ ( self ) ->int:
'''simple docstring'''
for prediction_type in ["epsilon", "v_prediction"]:
self.check_over_configs(prediction_type=a_ )
def lowerCamelCase__ ( self ) ->Union[str, Any]:
'''simple docstring'''
_a = self.scheduler_classes[0]
_a = self.get_scheduler_config(prediction_type="v_prediction" )
_a = scheduler_class(**a_ )
scheduler.set_timesteps(self.num_inference_steps )
_a = self.dummy_model()
_a = self.dummy_sample_deter * scheduler.init_noise_sigma
_a = sample.to(a_ )
for i, t in enumerate(scheduler.timesteps ):
_a = scheduler.scale_model_input(a_ , a_ )
_a = model(a_ , a_ )
_a = scheduler.step(a_ , a_ , a_ )
_a = output.prev_sample
_a = torch.sum(torch.abs(a_ ) )
_a = torch.mean(torch.abs(a_ ) )
if torch_device in ["cpu", "mps"]:
assert abs(result_sum.item() - 4.6_934E-07 ) < 1E-2
assert abs(result_mean.item() - 6.1_112E-10 ) < 1E-3
else:
# CUDA
assert abs(result_sum.item() - 4.693_428_650_170_972E-07 ) < 1E-2
assert abs(result_mean.item() - 0.0_002 ) < 1E-3
def lowerCamelCase__ ( self ) ->Any:
'''simple docstring'''
if torch_device == "mps":
return
_a = self.scheduler_classes[0]
_a = self.get_scheduler_config()
_a = scheduler_class(**a_ )
scheduler.set_timesteps(self.num_inference_steps )
_a = self.dummy_model()
_a = self.dummy_sample_deter * scheduler.init_noise_sigma
_a = sample.to(a_ )
for i, t in enumerate(scheduler.timesteps ):
_a = scheduler.scale_model_input(a_ , a_ )
_a = model(a_ , a_ )
_a = scheduler.step(a_ , a_ , a_ )
_a = output.prev_sample
_a = torch.sum(torch.abs(a_ ) )
_a = torch.mean(torch.abs(a_ ) )
if torch_device in ["cpu", "mps"]:
assert abs(result_sum.item() - 20.4_125 ) < 1E-2
assert abs(result_mean.item() - 0.0_266 ) < 1E-3
else:
# CUDA
assert abs(result_sum.item() - 20.4_125 ) < 1E-2
assert abs(result_mean.item() - 0.0_266 ) < 1E-3
def lowerCamelCase__ ( self ) ->int:
'''simple docstring'''
if torch_device == "mps":
return
_a = self.scheduler_classes[0]
_a = self.get_scheduler_config()
_a = scheduler_class(**a_ )
scheduler.set_timesteps(self.num_inference_steps , device=a_ )
_a = self.dummy_model()
_a = self.dummy_sample_deter.to(a_ ) * scheduler.init_noise_sigma
for t in scheduler.timesteps:
_a = scheduler.scale_model_input(a_ , a_ )
_a = model(a_ , a_ )
_a = scheduler.step(a_ , a_ , a_ )
_a = output.prev_sample
_a = torch.sum(torch.abs(a_ ) )
_a = torch.mean(torch.abs(a_ ) )
if str(a_ ).startswith("cpu" ):
# The following sum varies between 148 and 156 on mps. Why?
assert abs(result_sum.item() - 20.4_125 ) < 1E-2
assert abs(result_mean.item() - 0.0_266 ) < 1E-3
else:
# CUDA
assert abs(result_sum.item() - 20.4_125 ) < 1E-2
assert abs(result_mean.item() - 0.0_266 ) < 1E-3
| 612 | 1 |
from abc import ABC, abstractmethod
from typing import List, Optional
class lowerCamelCase__ ( _A):
"""simple docstring"""
def __init__( self : Dict ) -> Tuple:
# test for the above condition
self.test()
def snake_case_ ( self : List[str] ) -> Dict:
_A = 0
_A = False
while not completed:
if counter == 1:
self.reset()
_A = self.advance()
if not self.does_advance(__lowerCAmelCase ):
raise Exception(
'''Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.''' )
_A , _A , _A = self.update(__lowerCAmelCase )
counter += 1
if counter > 1_00_00:
raise Exception('''update() does not fulfill the constraint.''' )
if self.remaining() != 0:
raise Exception('''Custom Constraint is not defined correctly.''' )
@abstractmethod
def snake_case_ ( self : Dict ) -> str:
raise NotImplementedError(
f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' )
@abstractmethod
def snake_case_ ( self : List[Any] , __lowerCAmelCase : int ) -> Any:
raise NotImplementedError(
f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' )
@abstractmethod
def snake_case_ ( self : Union[str, Any] , __lowerCAmelCase : int ) -> Tuple:
raise NotImplementedError(
f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' )
@abstractmethod
def snake_case_ ( self : List[str] ) -> Optional[int]:
raise NotImplementedError(
f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' )
@abstractmethod
def snake_case_ ( self : List[Any] ) -> int:
raise NotImplementedError(
f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' )
@abstractmethod
def snake_case_ ( self : Tuple , __lowerCAmelCase : Union[str, Any]=False ) -> Optional[Any]:
raise NotImplementedError(
f'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' )
class lowerCamelCase__ ( _A):
"""simple docstring"""
def __init__( self : List[Any] , __lowerCAmelCase : List[int] ) -> Any:
super(__lowerCAmelCase , self ).__init__()
if not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or len(__lowerCAmelCase ) == 0:
raise ValueError(f'''`token_ids` has to be a non-empty list, but is {token_ids}.''' )
if any((not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or token_id < 0) for token_id in token_ids ):
raise ValueError(f'''Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.''' )
_A = token_ids
_A = len(self.token_ids )
_A = -1 # the index of the currently fulfilled step
_A = False
def snake_case_ ( self : Optional[int] ) -> str:
if self.completed:
return None
return self.token_ids[self.fulfilled_idx + 1]
def snake_case_ ( self : Optional[Any] , __lowerCAmelCase : int ) -> str:
if not isinstance(__lowerCAmelCase , __lowerCAmelCase ):
raise ValueError(f'''`token_id` has to be an `int`, but is {token_id} of type {type(__lowerCAmelCase )}''' )
if self.completed:
return False
return token_id == self.token_ids[self.fulfilled_idx + 1]
def snake_case_ ( self : Dict , __lowerCAmelCase : int ) -> str:
if not isinstance(__lowerCAmelCase , __lowerCAmelCase ):
raise ValueError(f'''`token_id` has to be an `int`, but is {token_id} of type {type(__lowerCAmelCase )}''' )
_A = False
_A = False
_A = False
if self.does_advance(__lowerCAmelCase ):
self.fulfilled_idx += 1
_A = True
if self.fulfilled_idx == (self.seqlen - 1):
_A = True
_A = completed
else:
# failed to make progress.
_A = True
self.reset()
return stepped, completed, reset
def snake_case_ ( self : Union[str, Any] ) -> int:
_A = False
_A = 0
def snake_case_ ( self : Union[str, Any] ) -> Any:
return self.seqlen - (self.fulfilled_idx + 1)
def snake_case_ ( self : Optional[int] , __lowerCAmelCase : Dict=False ) -> str:
_A = PhrasalConstraint(self.token_ids )
if stateful:
_A = self.seqlen
_A = self.fulfilled_idx
_A = self.completed
return new_constraint
class lowerCamelCase__ :
"""simple docstring"""
def __init__( self : Union[str, Any] , __lowerCAmelCase : List[List[int]] , __lowerCAmelCase : Optional[Any]=True ) -> Any:
_A = max([len(__lowerCAmelCase ) for one in nested_token_ids] )
_A = {}
for token_ids in nested_token_ids:
_A = root
for tidx, token_id in enumerate(__lowerCAmelCase ):
if token_id not in level:
_A = {}
_A = level[token_id]
if no_subsets and self.has_subsets(__lowerCAmelCase , __lowerCAmelCase ):
raise ValueError(
'''Each list in `nested_token_ids` can\'t be a complete subset of another list, but is'''
f''' {nested_token_ids}.''' )
_A = root
def snake_case_ ( self : Dict , __lowerCAmelCase : str ) -> List[str]:
_A = self.trie
for current_token in current_seq:
_A = start[current_token]
_A = list(start.keys() )
return next_tokens
def snake_case_ ( self : List[str] , __lowerCAmelCase : str ) -> int:
_A = self.next_tokens(__lowerCAmelCase )
return len(__lowerCAmelCase ) == 0
def snake_case_ ( self : List[str] , __lowerCAmelCase : int ) -> Optional[Any]:
_A = list(root.values() )
if len(__lowerCAmelCase ) == 0:
return 1
else:
return sum([self.count_leaves(__lowerCAmelCase ) for nn in next_nodes] )
def snake_case_ ( self : Optional[Any] , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : str ) -> int:
_A = self.count_leaves(__lowerCAmelCase )
return len(__lowerCAmelCase ) != leaf_count
class lowerCamelCase__ ( _A):
"""simple docstring"""
def __init__( self : Optional[int] , __lowerCAmelCase : List[List[int]] ) -> Union[str, Any]:
super(__lowerCAmelCase , self ).__init__()
if not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or len(__lowerCAmelCase ) == 0:
raise ValueError(f'''`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.''' )
if any(not isinstance(__lowerCAmelCase , __lowerCAmelCase ) for token_ids in nested_token_ids ):
raise ValueError(f'''`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.''' )
if any(
any((not isinstance(__lowerCAmelCase , __lowerCAmelCase ) or token_id < 0) for token_id in token_ids )
for token_ids in nested_token_ids ):
raise ValueError(
f'''Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.''' )
_A = DisjunctiveTrie(__lowerCAmelCase )
_A = nested_token_ids
_A = self.trie.max_height
_A = []
_A = False
def snake_case_ ( self : str ) -> str:
_A = self.trie.next_tokens(self.current_seq )
if len(__lowerCAmelCase ) == 0:
return None
else:
return token_list
def snake_case_ ( self : List[Any] , __lowerCAmelCase : int ) -> List[str]:
if not isinstance(__lowerCAmelCase , __lowerCAmelCase ):
raise ValueError(f'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(__lowerCAmelCase )}''' )
_A = self.trie.next_tokens(self.current_seq )
return token_id in next_tokens
def snake_case_ ( self : List[Any] , __lowerCAmelCase : int ) -> Tuple:
if not isinstance(__lowerCAmelCase , __lowerCAmelCase ):
raise ValueError(f'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(__lowerCAmelCase )}''' )
_A = False
_A = False
_A = False
if self.does_advance(__lowerCAmelCase ):
self.current_seq.append(__lowerCAmelCase )
_A = True
else:
_A = True
self.reset()
_A = self.trie.reached_leaf(self.current_seq )
_A = completed
return stepped, completed, reset
def snake_case_ ( self : Tuple ) -> int:
_A = False
_A = []
def snake_case_ ( self : Any ) -> List[str]:
if self.completed:
# since this can be completed without reaching max height
return 0
else:
return self.seqlen - len(self.current_seq )
def snake_case_ ( self : str , __lowerCAmelCase : Dict=False ) -> Optional[int]:
_A = DisjunctiveConstraint(self.token_ids )
if stateful:
_A = self.seqlen
_A = self.current_seq
_A = self.completed
return new_constraint
class lowerCamelCase__ :
"""simple docstring"""
def __init__( self : Union[str, Any] , __lowerCAmelCase : List[Constraint] ) -> Optional[Any]:
_A = constraints
# max # of steps required to fulfill a given constraint
_A = max([c.seqlen for c in constraints] )
_A = len(__lowerCAmelCase )
_A = False
self.init_state()
def snake_case_ ( self : int ) -> str:
_A = []
_A = None
_A = [constraint.copy(stateful=__lowerCAmelCase ) for constraint in self.constraints]
def snake_case_ ( self : int ) -> Any:
_A = 0
if self.inprogress_constraint:
# extra points for having a constraint mid-fulfilled
add += self.max_seqlen - self.inprogress_constraint.remaining()
return (len(self.complete_constraints ) * self.max_seqlen) + add
def snake_case_ ( self : Any ) -> str:
_A = []
if self.inprogress_constraint is None:
for constraint in self.pending_constraints: # "pending" == "unfulfilled yet"
_A = constraint.advance()
if isinstance(__lowerCAmelCase , __lowerCAmelCase ):
token_list.append(__lowerCAmelCase )
elif isinstance(__lowerCAmelCase , __lowerCAmelCase ):
token_list.extend(__lowerCAmelCase )
else:
_A = self.inprogress_constraint.advance()
if isinstance(__lowerCAmelCase , __lowerCAmelCase ):
token_list.append(__lowerCAmelCase )
elif isinstance(__lowerCAmelCase , __lowerCAmelCase ):
token_list.extend(__lowerCAmelCase )
if len(__lowerCAmelCase ) == 0:
return None
else:
return token_list
def snake_case_ ( self : List[str] , __lowerCAmelCase : Optional[List[int]] ) -> Dict:
self.init_state()
if token_ids is not None:
for token in token_ids:
# completes or steps **one** constraint
_A , _A = self.add(__lowerCAmelCase )
# the entire list of constraints are fulfilled
if self.completed:
break
def snake_case_ ( self : Any , __lowerCAmelCase : int ) -> Optional[int]:
if not isinstance(__lowerCAmelCase , __lowerCAmelCase ):
raise ValueError(f'''`token_id` should be an `int`, but is `{token_id}`.''' )
_A , _A = False, False
if self.completed:
_A = True
_A = False
return complete, stepped
if self.inprogress_constraint is not None:
# In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current
# job, simply update the state
_A , _A , _A = self.inprogress_constraint.update(__lowerCAmelCase )
if reset:
# 1. If the next token breaks the progress, then we must restart.
# e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books".
# But that doesn't mean we self.init_state(), since we only reset the state for this particular
# constraint, not the full list of constraints.
self.pending_constraints.append(self.inprogress_constraint.copy(stateful=__lowerCAmelCase ) )
_A = None
if complete:
# 2. If the next token completes the constraint, move it to completed list, set
# inprogress to None. If there are no pending constraints either, then this full list of constraints
# is complete.
self.complete_constraints.append(self.inprogress_constraint )
_A = None
if len(self.pending_constraints ) == 0:
# we're done!
_A = True
else:
# Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list
# of constraints?
for cidx, pending_constraint in enumerate(self.pending_constraints ):
if pending_constraint.does_advance(__lowerCAmelCase ):
_A , _A , _A = pending_constraint.update(__lowerCAmelCase )
if not stepped:
raise Exception(
'''`constraint.update(token_id)` is not yielding incremental progress, '''
'''even though `constraint.does_advance(token_id)` is true.''' )
if complete:
self.complete_constraints.append(__lowerCAmelCase )
_A = None
if not complete and stepped:
_A = pending_constraint
if complete or stepped:
# If we made any progress at all, then it's at least not a "pending constraint".
_A = (
self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :]
)
if len(self.pending_constraints ) == 0 and self.inprogress_constraint is None:
# If there's no longer any pending after this and no inprogress either, then we must be
# complete.
_A = True
break # prevent accidentally stepping through multiple constraints with just one token.
return complete, stepped
def snake_case_ ( self : Tuple , __lowerCAmelCase : Union[str, Any]=True ) -> Optional[Any]:
_A = ConstraintListState(self.constraints ) # we actually never though self.constraints objects
# throughout this process. So it's at initialization state.
if stateful:
_A = [
constraint.copy(stateful=__lowerCAmelCase ) for constraint in self.complete_constraints
]
if self.inprogress_constraint is not None:
_A = self.inprogress_constraint.copy(stateful=__lowerCAmelCase )
_A = [constraint.copy() for constraint in self.pending_constraints]
return new_state
| 2 |
'''simple docstring'''
import importlib
import torch
import yaml
from omegaconf import OmegaConf
from taming.models.vqgan import VQModel
def lowercase_ ( _lowercase , _lowercase=False ) -> Dict:
'''simple docstring'''
lowerCamelCase_ : Tuple = OmegaConf.load(_lowercase )
if display:
print(yaml.dump(OmegaConf.to_container(_lowercase ) ) )
return config
def lowercase_ ( _lowercase , _lowercase=None , _lowercase=None ) -> Optional[int]:
'''simple docstring'''
if conf_path is None:
lowerCamelCase_ : int = '''./model_checkpoints/vqgan_only.yaml'''
lowerCamelCase_ : Dict = load_config(_lowercase , display=_lowercase )
lowerCamelCase_ : List[str] = VQModel(**config.model.params )
if ckpt_path is None:
lowerCamelCase_ : int = '''./model_checkpoints/vqgan_only.pt'''
lowerCamelCase_ : Union[str, Any] = torch.load(_lowercase , map_location=_lowercase )
if ".ckpt" in ckpt_path:
lowerCamelCase_ : str = sd['''state_dict''']
model.load_state_dict(_lowercase , strict=_lowercase )
model.to(_lowercase )
del sd
return model
def lowercase_ ( _lowercase , _lowercase ) -> List[str]:
'''simple docstring'''
lowerCamelCase_, lowerCamelCase_, lowerCamelCase_ : Any = model.encode(_lowercase )
print(F"""VQGAN --- {model.__class__.__name__}: latent shape: {z.shape[2:]}""" )
lowerCamelCase_ : Any = model.decode(_lowercase )
return xrec
def lowercase_ ( _lowercase , _lowercase=False ) -> Any:
'''simple docstring'''
lowerCamelCase_, lowerCamelCase_ : Any = string.rsplit('''.''' , 1 )
if reload:
lowerCamelCase_ : int = importlib.import_module(_lowercase )
importlib.reload(_lowercase )
return getattr(importlib.import_module(_lowercase , package=_lowercase ) , cls )
def lowercase_ ( _lowercase ) -> List[str]:
'''simple docstring'''
if "target" not in config:
raise KeyError('''Expected key `target` to instantiate.''' )
return get_obj_from_str(config['''target'''] )(**config.get('''params''' , {} ) )
def lowercase_ ( _lowercase , _lowercase , _lowercase=True , _lowercase=True ) -> Any:
'''simple docstring'''
lowerCamelCase_ : int = instantiate_from_config(_lowercase )
if sd is not None:
model.load_state_dict(_lowercase )
if gpu:
model.cuda()
if eval_mode:
model.eval()
return {"model": model}
def lowercase_ ( _lowercase , _lowercase , _lowercase , _lowercase ) -> Tuple:
'''simple docstring'''
if ckpt:
lowerCamelCase_ : List[Any] = torch.load(_lowercase , map_location='''cpu''' )
lowerCamelCase_ : int = pl_sd['''global_step''']
print(F"""loaded model from global step {global_step}.""" )
else:
lowerCamelCase_ : Optional[int] = {'''state_dict''': None}
lowerCamelCase_ : str = None
lowerCamelCase_ : Any = load_model_from_config(config.model , pl_sd['''state_dict'''] , gpu=_lowercase , eval_mode=_lowercase )['''model''']
return model, global_step
| 422 | 0 |
from __future__ import annotations
from random import random
from typing import Generic, TypeVar
__A : int = TypeVar('KT')
__A : List[str] = TypeVar('VT')
class _SCREAMING_SNAKE_CASE ( Generic[KT, VT] ):
'''simple docstring'''
def __init__( self : Any , __lowerCamelCase : KT | str = "root" , __lowerCamelCase : VT | None = None ):
SCREAMING_SNAKE_CASE = key
SCREAMING_SNAKE_CASE = value
SCREAMING_SNAKE_CASE = []
def __repr__( self : Optional[Any] ):
return f"Node({self.key}: {self.value})"
@property
def _snake_case ( self : Optional[Any] ):
return len(self.forward )
class _SCREAMING_SNAKE_CASE ( Generic[KT, VT] ):
'''simple docstring'''
def __init__( self : Any , __lowerCamelCase : float = 0.5 , __lowerCamelCase : int = 16 ):
SCREAMING_SNAKE_CASE = Node[KT, VT]()
SCREAMING_SNAKE_CASE = 0
SCREAMING_SNAKE_CASE = p
SCREAMING_SNAKE_CASE = max_level
def __str__( self : int ):
SCREAMING_SNAKE_CASE = list(self )
if len(__lowerCamelCase ) == 0:
return f"SkipList(level={self.level})"
SCREAMING_SNAKE_CASE = max((len(str(__lowerCamelCase ) ) for item in items) , default=4 )
SCREAMING_SNAKE_CASE = max(__lowerCamelCase , 4 ) + 4
SCREAMING_SNAKE_CASE = self.head
SCREAMING_SNAKE_CASE = []
SCREAMING_SNAKE_CASE = node.forward.copy()
lines.append(f"[{node.key}]".ljust(__lowerCamelCase , "-" ) + "* " * len(__lowerCamelCase ) )
lines.append(" " * label_size + "| " * len(__lowerCamelCase ) )
while len(node.forward ) != 0:
SCREAMING_SNAKE_CASE = node.forward[0]
lines.append(
f"[{node.key}]".ljust(__lowerCamelCase , "-" )
+ " ".join(str(n.key ) if n.key == node.key else "|" for n in forwards ) )
lines.append(" " * label_size + "| " * len(__lowerCamelCase ) )
SCREAMING_SNAKE_CASE = node.forward
lines.append("None".ljust(__lowerCamelCase ) + "* " * len(__lowerCamelCase ) )
return f"SkipList(level={self.level})\n" + "\n".join(__lowerCamelCase )
def __iter__( self : Optional[Any] ):
SCREAMING_SNAKE_CASE = self.head
while len(node.forward ) != 0:
yield node.forward[0].key
SCREAMING_SNAKE_CASE = node.forward[0]
def _snake_case ( self : str ):
SCREAMING_SNAKE_CASE = 1
while random() < self.p and level < self.max_level:
level += 1
return level
def _snake_case ( self : int , __lowerCamelCase : Optional[Any] ):
SCREAMING_SNAKE_CASE = []
SCREAMING_SNAKE_CASE = self.head
for i in reversed(range(self.level ) ):
# i < node.level - When node level is lesser than `i` decrement `i`.
# node.forward[i].key < key - Jumping to node with key value higher
# or equal to searched key would result
# in skipping searched key.
while i < node.level and node.forward[i].key < key:
SCREAMING_SNAKE_CASE = node.forward[i]
# Each leftmost node (relative to searched node) will potentially have to
# be updated.
update_vector.append(__lowerCamelCase )
update_vector.reverse() # Note that we were inserting values in reverse order.
# len(node.forward) != 0 - If current node doesn't contain any further
# references then searched key is not present.
# node.forward[0].key == key - Next node key should be equal to search key
# if key is present.
if len(node.forward ) != 0 and node.forward[0].key == key:
return node.forward[0], update_vector
else:
return None, update_vector
def _snake_case ( self : List[str] , __lowerCamelCase : KT ):
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._locate_node(__lowerCamelCase )
if node is not None:
for i, update_node in enumerate(__lowerCamelCase ):
# Remove or replace all references to removed node.
if update_node.level > i and update_node.forward[i].key == key:
if node.level > i:
SCREAMING_SNAKE_CASE = node.forward[i]
else:
SCREAMING_SNAKE_CASE = update_node.forward[:i]
def _snake_case ( self : Optional[int] , __lowerCamelCase : KT , __lowerCamelCase : VT ):
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._locate_node(__lowerCamelCase )
if node is not None:
SCREAMING_SNAKE_CASE = value
else:
SCREAMING_SNAKE_CASE = self.random_level()
if level > self.level:
# After level increase we have to add additional nodes to head.
for _ in range(self.level - 1 , __lowerCamelCase ):
update_vector.append(self.head )
SCREAMING_SNAKE_CASE = level
SCREAMING_SNAKE_CASE = Node(__lowerCamelCase , __lowerCamelCase )
for i, update_node in enumerate(update_vector[:level] ):
# Change references to pass through new node.
if update_node.level > i:
new_node.forward.append(update_node.forward[i] )
if update_node.level < i + 1:
update_node.forward.append(__lowerCamelCase )
else:
SCREAMING_SNAKE_CASE = new_node
def _snake_case ( self : int , __lowerCamelCase : VT ):
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self._locate_node(__lowerCamelCase )
if node is not None:
return node.value
return None
def __a ( ):
SCREAMING_SNAKE_CASE = SkipList()
skip_list.insert("Key1" , 3 )
skip_list.insert("Key2" , 12 )
skip_list.insert("Key3" , 41 )
skip_list.insert("Key4" , -19 )
SCREAMING_SNAKE_CASE = skip_list.head
SCREAMING_SNAKE_CASE = {}
while node.level != 0:
SCREAMING_SNAKE_CASE = node.forward[0]
SCREAMING_SNAKE_CASE = node.value
assert len(A__ ) == 4
assert all_values["Key1"] == 3
assert all_values["Key2"] == 12
assert all_values["Key3"] == 41
assert all_values["Key4"] == -19
def __a ( ):
SCREAMING_SNAKE_CASE = SkipList()
skip_list.insert("Key1" , 10 )
skip_list.insert("Key1" , 12 )
skip_list.insert("Key5" , 7 )
skip_list.insert("Key7" , 10 )
skip_list.insert("Key10" , 5 )
skip_list.insert("Key7" , 7 )
skip_list.insert("Key5" , 5 )
skip_list.insert("Key10" , 10 )
SCREAMING_SNAKE_CASE = skip_list.head
SCREAMING_SNAKE_CASE = {}
while node.level != 0:
SCREAMING_SNAKE_CASE = node.forward[0]
SCREAMING_SNAKE_CASE = node.value
if len(A__ ) != 4:
print()
assert len(A__ ) == 4
assert all_values["Key1"] == 12
assert all_values["Key7"] == 7
assert all_values["Key5"] == 5
assert all_values["Key10"] == 10
def __a ( ):
SCREAMING_SNAKE_CASE = SkipList()
assert skip_list.find("Some key" ) is None
def __a ( ):
SCREAMING_SNAKE_CASE = SkipList()
skip_list.insert("Key2" , 20 )
assert skip_list.find("Key2" ) == 20
skip_list.insert("Some Key" , 10 )
skip_list.insert("Key2" , 8 )
skip_list.insert("V" , 13 )
assert skip_list.find("Y" ) is None
assert skip_list.find("Key2" ) == 8
assert skip_list.find("Some Key" ) == 10
assert skip_list.find("V" ) == 13
def __a ( ):
SCREAMING_SNAKE_CASE = SkipList()
skip_list.delete("Some key" )
assert len(skip_list.head.forward ) == 0
def __a ( ):
SCREAMING_SNAKE_CASE = SkipList()
skip_list.insert("Key1" , 12 )
skip_list.insert("V" , 13 )
skip_list.insert("X" , 14 )
skip_list.insert("Key2" , 15 )
skip_list.delete("V" )
skip_list.delete("Key2" )
assert skip_list.find("V" ) is None
assert skip_list.find("Key2" ) is None
def __a ( ):
SCREAMING_SNAKE_CASE = SkipList()
skip_list.insert("Key1" , 12 )
skip_list.insert("V" , 13 )
skip_list.insert("X" , 14 )
skip_list.insert("Key2" , 15 )
skip_list.delete("V" )
assert skip_list.find("V" ) is None
assert skip_list.find("X" ) == 14
assert skip_list.find("Key1" ) == 12
assert skip_list.find("Key2" ) == 15
skip_list.delete("X" )
assert skip_list.find("V" ) is None
assert skip_list.find("X" ) is None
assert skip_list.find("Key1" ) == 12
assert skip_list.find("Key2" ) == 15
skip_list.delete("Key1" )
assert skip_list.find("V" ) is None
assert skip_list.find("X" ) is None
assert skip_list.find("Key1" ) is None
assert skip_list.find("Key2" ) == 15
skip_list.delete("Key2" )
assert skip_list.find("V" ) is None
assert skip_list.find("X" ) is None
assert skip_list.find("Key1" ) is None
assert skip_list.find("Key2" ) is None
def __a ( ):
SCREAMING_SNAKE_CASE = SkipList()
skip_list.insert("Key1" , 12 )
skip_list.insert("V" , 13 )
skip_list.insert("X" , 142 )
skip_list.insert("Key2" , 15 )
skip_list.delete("X" )
def traverse_keys(A__ : Dict ):
yield node.key
for forward_node in node.forward:
yield from traverse_keys(A__ )
assert len(set(traverse_keys(skip_list.head ) ) ) == 4
def __a ( ):
def is_sorted(A__ : Dict ):
return all(next_item >= item for item, next_item in zip(A__ , lst[1:] ) )
SCREAMING_SNAKE_CASE = SkipList()
for i in range(10 ):
skip_list.insert(A__ , A__ )
assert is_sorted(list(A__ ) )
skip_list.delete(5 )
skip_list.delete(8 )
skip_list.delete(2 )
assert is_sorted(list(A__ ) )
skip_list.insert(-12 , -12 )
skip_list.insert(77 , 77 )
assert is_sorted(list(A__ ) )
def __a ( ):
for _ in range(100 ):
# Repeat test 100 times due to the probabilistic nature of skip list
# random values == random bugs
test_insert()
test_insert_overrides_existing_value()
test_searching_empty_list_returns_none()
test_search()
test_deleting_item_from_empty_list_do_nothing()
test_deleted_items_are_not_founded_by_find_method()
test_delete_removes_only_given_key()
test_delete_doesnt_leave_dead_nodes()
test_iter_always_yields_sorted_values()
def __a ( ):
SCREAMING_SNAKE_CASE = SkipList()
skip_list.insert(2 , "2" )
skip_list.insert(4 , "4" )
skip_list.insert(6 , "4" )
skip_list.insert(4 , "5" )
skip_list.insert(8 , "4" )
skip_list.insert(9 , "4" )
skip_list.delete(4 )
print(A__ )
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
| 710 |
from manim import *
class _SCREAMING_SNAKE_CASE ( __snake_case ):
'''simple docstring'''
def _snake_case ( self : List[Any] ):
SCREAMING_SNAKE_CASE = Rectangle(height=0.5 , width=0.5 )
SCREAMING_SNAKE_CASE = Rectangle(height=0.46 , width=0.46 ).set_stroke(width=0 )
SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )]
SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )]
SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 )
SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 )
SCREAMING_SNAKE_CASE = VGroup(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0 )
SCREAMING_SNAKE_CASE = Text("CPU" , font_size=24 )
SCREAMING_SNAKE_CASE = Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0.5 , aligned_edge=__lowerCamelCase )
cpu.move_to([-2.5, -0.5, 0] )
self.add(__lowerCamelCase )
SCREAMING_SNAKE_CASE = [mem.copy() for i in range(4 )]
SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 )
SCREAMING_SNAKE_CASE = Text("GPU" , font_size=24 )
SCREAMING_SNAKE_CASE = Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0.5 , aligned_edge=__lowerCamelCase )
gpu.move_to([-1, -1, 0] )
self.add(__lowerCamelCase )
SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )]
SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 )
SCREAMING_SNAKE_CASE = Text("Model" , font_size=24 )
SCREAMING_SNAKE_CASE = Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , buff=0.5 , aligned_edge=__lowerCamelCase )
model.move_to([3, -1.0, 0] )
self.add(__lowerCamelCase )
SCREAMING_SNAKE_CASE = []
for i, rect in enumerate(__lowerCamelCase ):
rect.set_stroke(__lowerCamelCase )
# target = fill.copy().set_fill(YELLOW, opacity=0.7)
# target.move_to(rect)
# self.add(target)
SCREAMING_SNAKE_CASE = Rectangle(height=0.46 / 4 , width=0.46 / 3 ).set_stroke(width=0.0 ).set_fill(__lowerCamelCase , opacity=0.7 )
if i == 0:
cpu_target.next_to(cpu_left_col_base[0].get_corner(DOWN + LEFT ) , buff=0.02 , direction=__lowerCamelCase )
cpu_target.set_x(cpu_target.get_x() + 0.1 )
elif i == 3:
cpu_target.next_to(cpu_targs[0] , direction=__lowerCamelCase , buff=0.0 )
else:
cpu_target.next_to(cpu_targs[i - 1] , direction=__lowerCamelCase , buff=0.0 )
self.add(__lowerCamelCase )
cpu_targs.append(__lowerCamelCase )
SCREAMING_SNAKE_CASE = [mem.copy() for i in range(6 )]
SCREAMING_SNAKE_CASE = VGroup(*__lowerCamelCase ).arrange(__lowerCamelCase , buff=0 )
SCREAMING_SNAKE_CASE = Text("Loaded Checkpoint" , font_size=24 )
SCREAMING_SNAKE_CASE = Group(__lowerCamelCase , __lowerCamelCase ).arrange(__lowerCamelCase , aligned_edge=__lowerCamelCase , buff=0.4 )
checkpoint.move_to([3, 0.5, 0] )
SCREAMING_SNAKE_CASE = Square(side_length=2.2 )
key.move_to([-5, 2, 0] )
SCREAMING_SNAKE_CASE = MarkupText(
f"<b>Key:</b>\n\n<span fgcolor='{YELLOW}'>●</span> Empty Model" , font_size=18 , )
key_text.move_to([-5, 2.4, 0] )
self.add(__lowerCamelCase , __lowerCamelCase )
SCREAMING_SNAKE_CASE = MarkupText(
f"<span fgcolor='{BLUE}'>●</span> Checkpoint" , font_size=18 , )
blue_text.next_to(__lowerCamelCase , DOWN * 2.4 , aligned_edge=key_text.get_left() )
SCREAMING_SNAKE_CASE = MarkupText(
f"Next, a <i><span fgcolor=\"{BLUE}\">second</span></i> model is loaded into memory,\nwith the weights of a <span fgcolor=\"{BLUE}\">single shard</span>." , font_size=24 , )
step_a.move_to([2, 2, 0] )
self.play(Write(__lowerCamelCase ) , Write(__lowerCamelCase ) )
self.play(Write(__lowerCamelCase , run_time=1 ) , Create(__lowerCamelCase , run_time=1 ) )
SCREAMING_SNAKE_CASE = []
SCREAMING_SNAKE_CASE = []
for i, rect in enumerate(__lowerCamelCase ):
SCREAMING_SNAKE_CASE = fill.copy().set_fill(__lowerCamelCase , opacity=0.7 )
target.move_to(__lowerCamelCase )
first_animations.append(GrowFromCenter(__lowerCamelCase , run_time=1 ) )
SCREAMING_SNAKE_CASE = target.copy()
cpu_target.generate_target()
if i < 5:
cpu_target.target.move_to(cpu_left_col_base[i + 1] )
else:
cpu_target.target.move_to(cpu_right_col_base[i - 5] )
second_animations.append(MoveToTarget(__lowerCamelCase , run_time=1.5 ) )
self.play(*__lowerCamelCase )
self.play(*__lowerCamelCase )
self.wait() | 698 | 0 |
"""simple docstring"""
def A__ ( __lowerCamelCase, __lowerCamelCase ):
"""simple docstring"""
_validate_point(__snake_case )
_validate_point(__snake_case )
if len(__snake_case ) != len(__snake_case ):
raise ValueError('Both points must be in the same n-dimensional space' )
return float(sum(abs(a - b ) for a, b in zip(__snake_case, __snake_case ) ) )
def A__ ( __lowerCamelCase ):
"""simple docstring"""
if point:
if isinstance(__snake_case, __snake_case ):
for item in point:
if not isinstance(__snake_case, (int, float) ):
_lowerCAmelCase = (
'Expected a list of numbers as input, found '
F'''{type(__snake_case ).__name__}'''
)
raise TypeError(__snake_case )
else:
_lowerCAmelCase = F'''Expected a list of numbers as input, found {type(__snake_case ).__name__}'''
raise TypeError(__snake_case )
else:
raise ValueError('Missing an input' )
def A__ ( __lowerCamelCase, __lowerCamelCase ):
"""simple docstring"""
_validate_point(__snake_case )
_validate_point(__snake_case )
if len(__snake_case ) != len(__snake_case ):
raise ValueError('Both points must be in the same n-dimensional space' )
return float(sum(abs(x - y ) for x, y in zip(__snake_case, __snake_case ) ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 589 |
from typing import List, Optional, Union
from ...configuration_utils import PretrainedConfig
from ...utils import logging
__UpperCAmelCase = logging.get_logger(__name__)
__UpperCAmelCase = {
'huggingface/time-series-transformer-tourism-monthly': (
'https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json'
),
# See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer
}
class lowerCamelCase (_snake_case ):
'''simple docstring'''
_snake_case : Union[str, Any] = '''time_series_transformer'''
_snake_case : str = {
'''hidden_size''': '''d_model''',
'''num_attention_heads''': '''encoder_attention_heads''',
'''num_hidden_layers''': '''encoder_layers''',
}
def __init__( self , _UpperCamelCase = None , _UpperCamelCase = None , _UpperCamelCase = "student_t" , _UpperCamelCase = "nll" , _UpperCamelCase = 1 , _UpperCamelCase = [1, 2, 3, 4, 5, 6, 7] , _UpperCamelCase = "mean" , _UpperCamelCase = 0 , _UpperCamelCase = 0 , _UpperCamelCase = 0 , _UpperCamelCase = 0 , _UpperCamelCase = None , _UpperCamelCase = None , _UpperCamelCase = 3_2 , _UpperCamelCase = 3_2 , _UpperCamelCase = 2 , _UpperCamelCase = 2 , _UpperCamelCase = 2 , _UpperCamelCase = 2 , _UpperCamelCase = True , _UpperCamelCase = "gelu" , _UpperCamelCase = 6_4 , _UpperCamelCase = 0.1 , _UpperCamelCase = 0.1 , _UpperCamelCase = 0.1 , _UpperCamelCase = 0.1 , _UpperCamelCase = 0.1 , _UpperCamelCase = 1_0_0 , _UpperCamelCase = 0.02 , _UpperCamelCase=True , **_UpperCamelCase , ) -> str:
# time series specific configuration
UpperCAmelCase_ : Optional[Any] = prediction_length
UpperCAmelCase_ : List[str] = context_length or prediction_length
UpperCAmelCase_ : List[str] = distribution_output
UpperCAmelCase_ : List[Any] = loss
UpperCAmelCase_ : Tuple = input_size
UpperCAmelCase_ : int = num_time_features
UpperCAmelCase_ : List[Any] = lags_sequence
UpperCAmelCase_ : str = scaling
UpperCAmelCase_ : List[str] = num_dynamic_real_features
UpperCAmelCase_ : Optional[Any] = num_static_real_features
UpperCAmelCase_ : int = num_static_categorical_features
if cardinality and num_static_categorical_features > 0:
if len(_UpperCamelCase ) != num_static_categorical_features:
raise ValueError(
'The cardinality should be a list of the same length as `num_static_categorical_features`' )
UpperCAmelCase_ : List[Any] = cardinality
else:
UpperCAmelCase_ : Optional[Any] = [0]
if embedding_dimension and num_static_categorical_features > 0:
if len(_UpperCamelCase ) != num_static_categorical_features:
raise ValueError(
'The embedding dimension should be a list of the same length as `num_static_categorical_features`' )
UpperCAmelCase_ : Optional[Any] = embedding_dimension
else:
UpperCAmelCase_ : Optional[int] = [min(5_0 , (cat + 1) // 2 ) for cat in self.cardinality]
UpperCAmelCase_ : Optional[Any] = num_parallel_samples
# Transformer architecture configuration
UpperCAmelCase_ : List[Any] = input_size * len(_UpperCamelCase ) + self._number_of_features
UpperCAmelCase_ : Tuple = d_model
UpperCAmelCase_ : List[Any] = encoder_attention_heads
UpperCAmelCase_ : Tuple = decoder_attention_heads
UpperCAmelCase_ : Union[str, Any] = encoder_ffn_dim
UpperCAmelCase_ : Optional[int] = decoder_ffn_dim
UpperCAmelCase_ : Any = encoder_layers
UpperCAmelCase_ : List[str] = decoder_layers
UpperCAmelCase_ : List[str] = dropout
UpperCAmelCase_ : Tuple = attention_dropout
UpperCAmelCase_ : Optional[int] = activation_dropout
UpperCAmelCase_ : str = encoder_layerdrop
UpperCAmelCase_ : Optional[int] = decoder_layerdrop
UpperCAmelCase_ : Optional[int] = activation_function
UpperCAmelCase_ : str = init_std
UpperCAmelCase_ : int = use_cache
super().__init__(is_encoder_decoder=_UpperCamelCase , **_UpperCamelCase )
@property
def __UpperCAmelCase ( self ) -> int:
return (
sum(self.embedding_dimension )
+ self.num_dynamic_real_features
+ self.num_time_features
+ self.num_static_real_features
+ self.input_size * 2 # the log1p(abs(loc)) and log(scale) features
)
| 406 | 0 |
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 numpy as np
import tensorflow as tf
from transformers import TFCamembertModel
@require_tf
@require_sentencepiece
@require_tokenizers
class UpperCamelCase ( unittest.TestCase ):
'''simple docstring'''
@slow
def UpperCamelCase_ ( self ) -> Dict:
"""simple docstring"""
_lowerCamelCase = TFCamembertModel.from_pretrained('''jplu/tf-camembert-base''' )
_lowerCamelCase = tf.convert_to_tensor(
[[5, 1_21, 11, 6_60, 16, 7_30, 2_55_43, 1_10, 83, 6]] , dtype=tf.intaa , ) # J'aime le camembert !"
_lowerCamelCase = model(A_ )['''last_hidden_state''']
_lowerCamelCase = tf.TensorShape((1, 10, 7_68) )
self.assertEqual(output.shape , A_ )
# compare the actual values for a slice.
_lowerCamelCase = tf.convert_to_tensor(
[[[-0.0254, 0.0235, 0.1027], [0.0606, -0.1811, -0.0418], [-0.1561, -0.1127, 0.2687]]] , dtype=tf.floataa , )
# camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0')
# camembert.eval()
# expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach()
self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) ) | 638 | import argparse
import json
from pathlib import Path
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel
from transformers.utils import logging
logging.set_verbosity_info()
snake_case__ = logging.get_logger(__name__)
def __magic_name__( __UpperCAmelCase , __UpperCAmelCase=False ) -> List[Any]:
'''simple docstring'''
_lowerCamelCase = []
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'''),
] )
# if just the base model, we should remove "vit" from all keys that start with "vit"
_lowerCamelCase = [(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 __magic_name__( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase=False ) -> str:
'''simple docstring'''
for i in range(config.num_hidden_layers ):
if base_model:
_lowerCamelCase = ''''''
else:
_lowerCamelCase = '''vit.'''
# read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
_lowerCamelCase = state_dict.pop(F'blocks.{i}.attn.qkv.weight' )
_lowerCamelCase = state_dict.pop(F'blocks.{i}.attn.qkv.bias' )
# next, add query, keys and values (in that order) to the state dict
_lowerCamelCase = in_proj_weight[
: config.hidden_size, :
]
_lowerCamelCase = in_proj_bias[: config.hidden_size]
_lowerCamelCase = in_proj_weight[
config.hidden_size : config.hidden_size * 2, :
]
_lowerCamelCase = in_proj_bias[
config.hidden_size : config.hidden_size * 2
]
_lowerCamelCase = in_proj_weight[
-config.hidden_size :, :
]
_lowerCamelCase = in_proj_bias[-config.hidden_size :]
def __magic_name__( __UpperCAmelCase ) -> Dict:
'''simple docstring'''
_lowerCamelCase = ['''head.weight''', '''head.bias''']
for k in ignore_keys:
state_dict.pop(__UpperCAmelCase , __UpperCAmelCase )
def __magic_name__( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> List[Any]:
'''simple docstring'''
_lowerCamelCase = dct.pop(__UpperCAmelCase )
_lowerCamelCase = val
def __magic_name__( ) -> List[str]:
'''simple docstring'''
_lowerCamelCase = '''http://images.cocodataset.org/val2017/000000039769.jpg'''
_lowerCamelCase = Image.open(requests.get(__UpperCAmelCase , stream=__UpperCAmelCase ).raw )
return im
@torch.no_grad()
def __magic_name__( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase=True ) -> str:
'''simple docstring'''
_lowerCamelCase = ViTConfig()
# patch_size
if model_name[-1] == "8":
_lowerCamelCase = 8
# set labels if required
if not base_model:
_lowerCamelCase = 1000
_lowerCamelCase = '''huggingface/label-files'''
_lowerCamelCase = '''imagenet-1k-id2label.json'''
_lowerCamelCase = json.load(open(hf_hub_download(__UpperCAmelCase , __UpperCAmelCase , repo_type='''dataset''' ) , '''r''' ) )
_lowerCamelCase = {int(__UpperCAmelCase ): v for k, v in idalabel.items()}
_lowerCamelCase = idalabel
_lowerCamelCase = {v: k for k, v in idalabel.items()}
# size of the architecture
if model_name in ["dino_vits8", "dino_vits16"]:
_lowerCamelCase = 384
_lowerCamelCase = 1536
_lowerCamelCase = 12
_lowerCamelCase = 6
# load original model from torch hub
_lowerCamelCase = torch.hub.load('''facebookresearch/dino:main''' , __UpperCAmelCase )
original_model.eval()
# load state_dict of original model, remove and rename some keys
_lowerCamelCase = original_model.state_dict()
if base_model:
remove_classification_head_(__UpperCAmelCase )
_lowerCamelCase = create_rename_keys(__UpperCAmelCase , base_model=__UpperCAmelCase )
for src, dest in rename_keys:
rename_key(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
read_in_q_k_v(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
# load HuggingFace model
if base_model:
_lowerCamelCase = ViTModel(__UpperCAmelCase , add_pooling_layer=__UpperCAmelCase ).eval()
else:
_lowerCamelCase = ViTForImageClassification(__UpperCAmelCase ).eval()
model.load_state_dict(__UpperCAmelCase )
# Check outputs on an image, prepared by ViTImageProcessor
_lowerCamelCase = ViTImageProcessor()
_lowerCamelCase = image_processor(images=prepare_img() , return_tensors='''pt''' )
_lowerCamelCase = encoding['''pixel_values''']
_lowerCamelCase = model(__UpperCAmelCase )
if base_model:
_lowerCamelCase = original_model(__UpperCAmelCase )
assert torch.allclose(__UpperCAmelCase , outputs.last_hidden_state[:, 0, :] , atol=1E-1 )
else:
_lowerCamelCase = original_model(__UpperCAmelCase )
assert logits.shape == outputs.logits.shape
assert torch.allclose(__UpperCAmelCase , outputs.logits , atol=1E-3 )
Path(__UpperCAmelCase ).mkdir(exist_ok=__UpperCAmelCase )
print(F'Saving model {model_name} to {pytorch_dump_folder_path}' )
model.save_pretrained(__UpperCAmelCase )
print(F'Saving image processor to {pytorch_dump_folder_path}' )
image_processor.save_pretrained(__UpperCAmelCase )
if __name__ == "__main__":
snake_case__ = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'--model_name',
default='dino_vitb16',
type=str,
help='Name of the model trained with DINO you\'d like to convert.',
)
parser.add_argument(
'--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.'
)
parser.add_argument(
'--base_model',
action='store_true',
help='Whether to only convert the base model (no projection head weights).',
)
parser.set_defaults(base_model=True)
snake_case__ = parser.parse_args()
convert_vit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.base_model) | 638 | 1 |
from __future__ import annotations
import csv
import requests
from bsa import BeautifulSoup
def lowerCamelCase_ ( lowerCAmelCase: str = "" )-> List[Any]:
_snake_case : int = url or 'https://www.imdb.com/chart/top/?ref_=nv_mv_250'
_snake_case : List[Any] = BeautifulSoup(requests.get(lowerCAmelCase ).text , 'html.parser' )
_snake_case : Tuple = soup.find_all('td' , attrs='titleColumn' )
_snake_case : str = soup.find_all('td' , class_='ratingColumn imdbRating' )
return {
title.a.text: float(rating.strong.text )
for title, rating in zip(lowerCAmelCase , lowerCAmelCase )
}
def lowerCamelCase_ ( lowerCAmelCase: str = "IMDb_Top_250_Movies.csv" )-> List[Any]:
_snake_case : Union[str, Any] = get_imdb_top_aaa_movies()
with open(lowerCAmelCase , 'w' , newline='' ) as out_file:
_snake_case : Optional[Any] = csv.writer(lowerCAmelCase )
writer.writerow(['Movie title', 'IMDb rating'] )
for title, rating in movies.items():
writer.writerow([title, rating] )
if __name__ == "__main__":
write_movies()
| 411 |
'''simple docstring'''
import json
import os
import unittest
from transformers.models.roc_bert.tokenization_roc_bert import (
VOCAB_FILES_NAMES,
RoCBertBasicTokenizer,
RoCBertTokenizer,
RoCBertWordpieceTokenizer,
_is_control,
_is_punctuation,
_is_whitespace,
)
from transformers.testing_utils import require_tokenizers, slow
from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english
@require_tokenizers
class UpperCAmelCase_ ( __lowercase , unittest.TestCase ):
lowerCamelCase : List[str] = RoCBertTokenizer
lowerCamelCase : str = None
lowerCamelCase : Dict = False
lowerCamelCase : Dict = True
lowerCamelCase : Any = filter_non_english
def __UpperCAmelCase ( self : Optional[int] ) -> str:
super().setUp()
lowerCAmelCase = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', '你', '好', '是', '谁', 'a', 'b', 'c', 'd']
lowerCAmelCase = {}
lowerCAmelCase = {}
for i, value in enumerate(UpperCAmelCase__ ):
lowerCAmelCase = i
lowerCAmelCase = i
lowerCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] )
lowerCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['word_shape_file'] )
lowerCAmelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['word_pronunciation_file'] )
with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer:
vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) )
with open(self.word_shape_file , 'w' , encoding='utf-8' ) as word_shape_writer:
json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ )
with open(self.word_pronunciation_file , 'w' , encoding='utf-8' ) as word_pronunciation_writer:
json.dump(UpperCAmelCase__ , UpperCAmelCase__ , ensure_ascii=UpperCAmelCase__ )
def __UpperCAmelCase ( self : List[Any] ) -> int:
lowerCAmelCase = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file )
lowerCAmelCase = tokenizer.tokenize('你好[SEP]你是谁' )
self.assertListEqual(UpperCAmelCase__ , ['你', '好', '[SEP]', '你', '是', '谁'] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] )
self.assertListEqual(tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] )
self.assertListEqual(tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ ) , [5, 6, 2, 5, 7, 8] )
def __UpperCAmelCase ( self : int ) -> str:
lowerCAmelCase = RoCBertBasicTokenizer()
self.assertListEqual(tokenizer.tokenize('ah\u535A\u63A8zz' ) , ['ah', '\u535A', '\u63A8', 'zz'] )
def __UpperCAmelCase ( self : Optional[int] ) -> List[Any]:
lowerCAmelCase = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ )
self.assertListEqual(
tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['hello', '!', 'how', 'are', 'you', '?'] )
self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] )
def __UpperCAmelCase ( self : Tuple ) -> Tuple:
lowerCAmelCase = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ )
self.assertListEqual(
tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hällo', '!', 'how', 'are', 'you', '?'] )
self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['h\u00E9llo'] )
def __UpperCAmelCase ( self : Union[str, Any] ) -> Optional[int]:
lowerCAmelCase = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ )
self.assertListEqual(
tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] )
self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] )
def __UpperCAmelCase ( self : Optional[int] ) -> Optional[Any]:
lowerCAmelCase = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ )
self.assertListEqual(
tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['hallo', '!', 'how', 'are', 'you', '?'] )
self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['hello'] )
def __UpperCAmelCase ( self : Any ) -> Dict:
lowerCAmelCase = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ )
self.assertListEqual(
tokenizer.tokenize(' \tHeLLo!how \n Are yoU? ' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?'] )
def __UpperCAmelCase ( self : Tuple ) -> Dict:
lowerCAmelCase = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ )
self.assertListEqual(
tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HäLLo', '!', 'how', 'Are', 'yoU', '?'] )
def __UpperCAmelCase ( self : Union[str, Any] ) -> Dict:
lowerCAmelCase = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , strip_accents=UpperCAmelCase__ )
self.assertListEqual(
tokenizer.tokenize(' \tHäLLo!how \n Are yoU? ' ) , ['HaLLo', '!', 'how', 'Are', 'yoU', '?'] )
def __UpperCAmelCase ( self : Tuple ) -> Tuple:
lowerCAmelCase = RoCBertBasicTokenizer(do_lower_case=UpperCAmelCase__ , never_split=['[UNK]'] )
self.assertListEqual(
tokenizer.tokenize(' \tHeLLo!how \n Are yoU? [UNK]' ) , ['HeLLo', '!', 'how', 'Are', 'yoU', '?', '[UNK]'] )
def __UpperCAmelCase ( self : str ) -> Optional[int]:
lowerCAmelCase = ['[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing']
lowerCAmelCase = {}
for i, token in enumerate(UpperCAmelCase__ ):
lowerCAmelCase = i
lowerCAmelCase = RoCBertWordpieceTokenizer(vocab=UpperCAmelCase__ , unk_token='[UNK]' )
self.assertListEqual(tokenizer.tokenize('' ) , [] )
self.assertListEqual(tokenizer.tokenize('unwanted running' ) , ['un', '##want', '##ed', 'runn', '##ing'] )
self.assertListEqual(tokenizer.tokenize('unwantedX running' ) , ['[UNK]', 'runn', '##ing'] )
def __UpperCAmelCase ( self : List[str] ) -> Tuple:
self.assertTrue(_is_whitespace(' ' ) )
self.assertTrue(_is_whitespace('\t' ) )
self.assertTrue(_is_whitespace('\r' ) )
self.assertTrue(_is_whitespace('\n' ) )
self.assertTrue(_is_whitespace('\u00A0' ) )
self.assertFalse(_is_whitespace('A' ) )
self.assertFalse(_is_whitespace('-' ) )
def __UpperCAmelCase ( self : Tuple ) -> Tuple:
self.assertTrue(_is_control('\u0005' ) )
self.assertFalse(_is_control('A' ) )
self.assertFalse(_is_control(' ' ) )
self.assertFalse(_is_control('\t' ) )
self.assertFalse(_is_control('\r' ) )
def __UpperCAmelCase ( self : List[Any] ) -> Optional[int]:
self.assertTrue(_is_punctuation('-' ) )
self.assertTrue(_is_punctuation('$' ) )
self.assertTrue(_is_punctuation('`' ) )
self.assertTrue(_is_punctuation('.' ) )
self.assertFalse(_is_punctuation('A' ) )
self.assertFalse(_is_punctuation(' ' ) )
def __UpperCAmelCase ( self : Dict ) -> int:
lowerCAmelCase = self.get_tokenizer()
# Example taken from the issue https://github.com/huggingface/tokenizers/issues/340
self.assertListEqual([tokenizer.tokenize(UpperCAmelCase__ ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] )
if self.test_rust_tokenizer:
lowerCAmelCase = self.get_rust_tokenizer()
self.assertListEqual(
[rust_tokenizer.tokenize(UpperCAmelCase__ ) for t in ['Test', '\xad', 'test']] , [['[UNK]'], [], ['[UNK]']] )
def __UpperCAmelCase ( self : Optional[int] ) -> List[Any]:
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ):
lowerCAmelCase = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ )
lowerCAmelCase = F'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.'''
lowerCAmelCase = tokenizer_r.encode_plus(
UpperCAmelCase__ , return_attention_mask=UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ , return_offsets_mapping=UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ , )
lowerCAmelCase = tokenizer_r.do_lower_case if hasattr(UpperCAmelCase__ , 'do_lower_case' ) else False
lowerCAmelCase = (
[
((0, 0), tokenizer_r.cls_token),
((0, 1), 'A'),
((1, 2), ','),
((3, 5), 'na'),
((5, 6), '##ï'),
((6, 8), '##ve'),
((9, 1_5), tokenizer_r.mask_token),
((1_6, 2_1), 'Allen'),
((2_1, 2_3), '##NL'),
((2_3, 2_4), '##P'),
((2_5, 3_3), 'sentence'),
((3_3, 3_4), '.'),
((0, 0), tokenizer_r.sep_token),
]
if not do_lower_case
else [
((0, 0), tokenizer_r.cls_token),
((0, 1), 'a'),
((1, 2), ','),
((3, 8), 'naive'),
((9, 1_5), tokenizer_r.mask_token),
((1_6, 2_1), 'allen'),
((2_1, 2_3), '##nl'),
((2_3, 2_4), '##p'),
((2_5, 3_3), 'sentence'),
((3_3, 3_4), '.'),
((0, 0), tokenizer_r.sep_token),
]
)
self.assertEqual(
[e[1] for e in expected_results] , tokenizer_r.convert_ids_to_tokens(tokens['input_ids'] ) )
self.assertEqual([e[0] for e in expected_results] , tokens['offset_mapping'] )
def __UpperCAmelCase ( self : List[Any] ) -> List[str]:
lowerCAmelCase = ['的', '人', '有']
lowerCAmelCase = ''.join(UpperCAmelCase__ )
for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ):
lowerCAmelCase = True
lowerCAmelCase = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ )
lowerCAmelCase = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ )
lowerCAmelCase = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ )
lowerCAmelCase = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ )
lowerCAmelCase = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ )
lowerCAmelCase = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ )
# it is expected that each Chinese character is not preceded by "##"
self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ )
self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ )
lowerCAmelCase = False
lowerCAmelCase = self.rust_tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ )
lowerCAmelCase = self.tokenizer_class.from_pretrained(UpperCAmelCase__ , **UpperCAmelCase__ )
lowerCAmelCase = tokenizer_r.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ )
lowerCAmelCase = tokenizer_p.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ )
lowerCAmelCase = tokenizer_r.convert_ids_to_tokens(UpperCAmelCase__ )
lowerCAmelCase = tokenizer_p.convert_ids_to_tokens(UpperCAmelCase__ )
# it is expected that only the first Chinese character is not preceded by "##".
lowerCAmelCase = [
F'''##{token}''' if idx != 0 else token for idx, token in enumerate(UpperCAmelCase__ )
]
self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ )
self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ )
@slow
def __UpperCAmelCase ( self : Union[str, Any] ) -> Dict:
lowerCAmelCase = self.tokenizer_class(self.vocab_file , self.word_shape_file , self.word_pronunciation_file )
lowerCAmelCase = tokenizer.encode('你好' , add_special_tokens=UpperCAmelCase__ )
lowerCAmelCase = tokenizer.encode('你是谁' , add_special_tokens=UpperCAmelCase__ )
lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ )
lowerCAmelCase = tokenizer.build_inputs_with_special_tokens(UpperCAmelCase__ , UpperCAmelCase__ )
assert encoded_sentence == [1] + text + [2]
assert encoded_pair == [1] + text + [2] + text_a + [2]
def __UpperCAmelCase ( self : Optional[Any] ) -> Tuple:
lowerCAmelCase = self.get_tokenizers(do_lower_case=UpperCAmelCase__ )
for tokenizer in tokenizers:
with self.subTest(F'''{tokenizer.__class__.__name__}''' ):
lowerCAmelCase = '你好,你是谁'
lowerCAmelCase = tokenizer.tokenize(UpperCAmelCase__ )
lowerCAmelCase = tokenizer.convert_tokens_to_ids(UpperCAmelCase__ )
lowerCAmelCase = tokenizer.convert_tokens_to_shape_ids(UpperCAmelCase__ )
lowerCAmelCase = tokenizer.convert_tokens_to_pronunciation_ids(UpperCAmelCase__ )
lowerCAmelCase = tokenizer.prepare_for_model(
UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ )
lowerCAmelCase = tokenizer.encode_plus(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ )
self.assertEqual(UpperCAmelCase__ , UpperCAmelCase__ )
| 133 | 0 |
"""simple docstring"""
import argparse
from pathlib import Path
import fairseq
import torch
from fairseq.models.xmod import XMODModel as FairseqXmodModel
from packaging import version
from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification
from transformers.utils import logging
if version.parse(fairseq.__version__) < version.parse('''0.12.2'''):
raise Exception('''requires fairseq >= 0.12.2''')
if version.parse(fairseq.__version__) > version.parse('''2'''):
raise Exception('''requires fairseq < v2''')
logging.set_verbosity_info()
a : str = logging.get_logger(__name__)
a : Tuple = '''Hello, World!'''
a : Optional[Any] = '''en_XX'''
def _UpperCamelCase ( _A , _A , _A ) -> Optional[Any]:
"""simple docstring"""
_UpperCAmelCase = Path("""data_bin""" )
_UpperCAmelCase = FairseqXmodModel.from_pretrained(
model_name_or_path=str(Path(_A ).parent ) , checkpoint_file=Path(_A ).name , _name="""xmod_base""" , arch="""xmod_base""" , task="""multilingual_masked_lm""" , data_name_or_path=str(_A ) , bpe="""sentencepiece""" , sentencepiece_model=str(Path(_A ).parent / """sentencepiece.bpe.model""" ) , src_dict=str(data_dir / """dict.txt""" ) , )
xmod.eval() # disable dropout
print(_A )
_UpperCAmelCase = xmod.model.encoder.sentence_encoder
_UpperCAmelCase = XmodConfig(
vocab_size=xmod_sent_encoder.embed_tokens.num_embeddings , hidden_size=xmod.cfg.model.encoder_embed_dim , num_hidden_layers=xmod.cfg.model.encoder_layers , num_attention_heads=xmod.cfg.model.encoder_attention_heads , intermediate_size=xmod.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=5_1_4 , type_vocab_size=1 , layer_norm_eps=1e-5 , pre_norm=xmod.cfg.model.encoder_normalize_before , adapter_reduction_factor=getattr(xmod.cfg.model , """bottleneck""" , 2 ) , adapter_layer_norm=xmod.cfg.model.adapter_layer_norm , adapter_reuse_layer_norm=xmod.cfg.model.adapter_reuse_layer_norm , ln_before_adapter=xmod.cfg.model.ln_before_adapter , languages=xmod.cfg.model.languages , )
if classification_head:
_UpperCAmelCase = xmod.model.classification_heads["""mnli"""].out_proj.weight.shape[0]
print("""Our X-MOD config:""" , _A )
_UpperCAmelCase = XmodForSequenceClassification(_A ) if classification_head else XmodForMaskedLM(_A )
model.eval()
# Now let's copy all the weights.
# Embeddings
_UpperCAmelCase = xmod_sent_encoder.embed_tokens.weight
_UpperCAmelCase = xmod_sent_encoder.embed_positions.weight
_UpperCAmelCase = torch.zeros_like(
model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c xmod doesn't use them.
_UpperCAmelCase = xmod_sent_encoder.layernorm_embedding.weight
_UpperCAmelCase = xmod_sent_encoder.layernorm_embedding.bias
for i in range(config.num_hidden_layers ):
# Encoder: start of layer
_UpperCAmelCase = model.roberta.encoder.layer[i]
_UpperCAmelCase = xmod_sent_encoder.layers[i]
# self attention
_UpperCAmelCase = layer.attention.self
if not (
xmod_layer.self_attn.k_proj.weight.data.shape
== xmod_layer.self_attn.q_proj.weight.data.shape
== xmod_layer.self_attn.v_proj.weight.data.shape
== torch.Size((config.hidden_size, config.hidden_size) )
):
raise AssertionError("""Dimensions of self-attention weights do not match.""" )
_UpperCAmelCase = xmod_layer.self_attn.q_proj.weight
_UpperCAmelCase = xmod_layer.self_attn.q_proj.bias
_UpperCAmelCase = xmod_layer.self_attn.k_proj.weight
_UpperCAmelCase = xmod_layer.self_attn.k_proj.bias
_UpperCAmelCase = xmod_layer.self_attn.v_proj.weight
_UpperCAmelCase = xmod_layer.self_attn.v_proj.bias
# self-attention output
_UpperCAmelCase = layer.attention.output
if self_output.dense.weight.shape != xmod_layer.self_attn.out_proj.weight.shape:
raise AssertionError("""Dimensions of self-attention output weights do not match.""" )
_UpperCAmelCase = xmod_layer.self_attn.out_proj.weight
_UpperCAmelCase = xmod_layer.self_attn.out_proj.bias
_UpperCAmelCase = xmod_layer.self_attn_layer_norm.weight
_UpperCAmelCase = xmod_layer.self_attn_layer_norm.bias
# intermediate
_UpperCAmelCase = layer.intermediate
if intermediate.dense.weight.shape != xmod_layer.fca.weight.shape:
raise AssertionError("""Dimensions of intermediate weights do not match.""" )
_UpperCAmelCase = xmod_layer.fca.weight
_UpperCAmelCase = xmod_layer.fca.bias
# output
_UpperCAmelCase = layer.output
if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape:
raise AssertionError("""Dimensions of feed-forward weights do not match.""" )
_UpperCAmelCase = xmod_layer.fca.weight
_UpperCAmelCase = xmod_layer.fca.bias
_UpperCAmelCase = xmod_layer.final_layer_norm.weight
_UpperCAmelCase = xmod_layer.final_layer_norm.bias
if bert_output.adapter_layer_norm is not None:
_UpperCAmelCase = xmod_layer.adapter_layer_norm.weight
_UpperCAmelCase = xmod_layer.adapter_layer_norm.bias
if sorted(bert_output.adapter_modules.keys() ) != sorted(xmod_layer.adapter_modules.keys() ):
raise AssertionError("""Lists of language adapters do not match.""" )
for lang_code, adapter in xmod_layer.adapter_modules.items():
_UpperCAmelCase = bert_output.adapter_modules[lang_code]
_UpperCAmelCase = xmod_layer.adapter_modules[lang_code]
_UpperCAmelCase = from_adapter.fca.weight
_UpperCAmelCase = from_adapter.fca.bias
_UpperCAmelCase = from_adapter.fca.weight
_UpperCAmelCase = from_adapter.fca.bias
# end of layer
if xmod_sent_encoder.layer_norm is not None:
_UpperCAmelCase = xmod_sent_encoder.layer_norm.weight
_UpperCAmelCase = xmod_sent_encoder.layer_norm.bias
if classification_head:
_UpperCAmelCase = xmod.model.classification_heads["""mnli"""].dense.weight
_UpperCAmelCase = xmod.model.classification_heads["""mnli"""].dense.bias
_UpperCAmelCase = xmod.model.classification_heads["""mnli"""].out_proj.weight
_UpperCAmelCase = xmod.model.classification_heads["""mnli"""].out_proj.bias
else:
# LM Head
_UpperCAmelCase = xmod.model.encoder.lm_head.dense.weight
_UpperCAmelCase = xmod.model.encoder.lm_head.dense.bias
_UpperCAmelCase = xmod.model.encoder.lm_head.layer_norm.weight
_UpperCAmelCase = xmod.model.encoder.lm_head.layer_norm.bias
_UpperCAmelCase = xmod.model.encoder.lm_head.weight
_UpperCAmelCase = xmod.model.encoder.lm_head.bias
# Let's check that we get the same results.
_UpperCAmelCase = xmod.encode(_A ).unsqueeze(0 ) # batch of size 1
model.roberta.set_default_language(_A )
_UpperCAmelCase = model(_A )[0]
if classification_head:
_UpperCAmelCase = xmod.model.classification_heads["""mnli"""](xmod.extract_features(_A ) )
else:
_UpperCAmelCase = xmod.model(_A , lang_id=[SAMPLE_LANGUAGE] )[0]
print(our_output.shape , their_output.shape )
_UpperCAmelCase = torch.max(torch.abs(our_output - their_output ) ).item()
print(F"""max_absolute_diff = {max_absolute_diff}""" ) # ~ 1e-7
_UpperCAmelCase = torch.allclose(_A , _A , atol=1e-3 )
print("""Do both models output the same tensors?""" , """🔥""" if success else """💩""" )
if not success:
raise Exception("""Something went wRoNg""" )
Path(_A ).mkdir(parents=_A , exist_ok=_A )
print(F"""Saving model to {pytorch_dump_folder_path}""" )
model.save_pretrained(_A )
if __name__ == "__main__":
a : List[str] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
'''--xmod_checkpoint_path''', default=None, type=str, required=True, help='''Path the official PyTorch dump.'''
)
parser.add_argument(
'''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
)
parser.add_argument(
'''--classification_head''', action='''store_true''', help='''Whether to convert a final classification head.'''
)
a : List[Any] = parser.parse_args()
convert_xmod_checkpoint_to_pytorch(
args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head
) | 19 |
"""simple docstring"""
from __future__ import annotations
def _UpperCamelCase ( _A ) -> None:
"""simple docstring"""
create_state_space_tree(_A , [] , 0 , [0 for i in range(len(_A ) )] )
def _UpperCamelCase ( _A , _A , _A , _A , ) -> None:
"""simple docstring"""
if index == len(_A ):
print(_A )
return
for i in range(len(_A ) ):
if not index_used[i]:
current_sequence.append(sequence[i] )
_UpperCAmelCase = True
create_state_space_tree(_A , _A , index + 1 , _A )
current_sequence.pop()
_UpperCAmelCase = False
a : list[int | str] = [3, 1, 2, 4]
generate_all_permutations(sequence)
a : list[int | str] = ["A", "B", "C"]
generate_all_permutations(sequence_a) | 19 | 1 |
import numpy as np
import skfuzzy as fuzz
if __name__ == "__main__":
# Create universe of discourse in Python using linspace ()
lowerCamelCase__ : List[str] = np.linspace(start=0, stop=7_5, num=7_5, endpoint=True, retstep=False)
# Create two fuzzy sets by defining any membership function
# (trapmf(), gbellmf(), gaussmf(), etc).
lowerCamelCase__ : List[str] = [0, 2_5, 5_0]
lowerCamelCase__ : Any = [2_5, 5_0, 7_5]
lowerCamelCase__ : Optional[int] = fuzz.membership.trimf(X, abca)
lowerCamelCase__ : Optional[Any] = fuzz.membership.trimf(X, abca)
# Compute the different operations using inbuilt functions.
lowerCamelCase__ : List[Any] = np.ones(7_5)
lowerCamelCase__ : Dict = np.zeros((7_5,))
# 1. Union = max(µA(x), µB(x))
lowerCamelCase__ : List[Any] = fuzz.fuzzy_or(X, young, X, middle_aged)[1]
# 2. Intersection = min(µA(x), µB(x))
lowerCamelCase__ : int = fuzz.fuzzy_and(X, young, X, middle_aged)[1]
# 3. Complement (A) = (1- min(µA(x))
lowerCamelCase__ : Dict = fuzz.fuzzy_not(young)
# 4. Difference (A/B) = min(µA(x),(1- µB(x)))
lowerCamelCase__ : str = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1]
# 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))]
lowerCamelCase__ : str = young + middle_aged - (young * middle_aged)
# 6. Algebraic Product = (µA(x) * µB(x))
lowerCamelCase__ : Union[str, Any] = young * middle_aged
# 7. Bounded Sum = min[1,(µA(x), µB(x))]
lowerCamelCase__ : List[Any] = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1]
# 8. Bounded difference = min[0,(µA(x), µB(x))]
lowerCamelCase__ : Any = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1]
# max-min composition
# max-product composition
# Plot each set A, set B and each operation result using plot() and subplot().
from matplotlib import pyplot as plt
plt.figure()
plt.subplot(4, 3, 1)
plt.plot(X, young)
plt.title("""Young""")
plt.grid(True)
plt.subplot(4, 3, 2)
plt.plot(X, middle_aged)
plt.title("""Middle aged""")
plt.grid(True)
plt.subplot(4, 3, 3)
plt.plot(X, union)
plt.title("""union""")
plt.grid(True)
plt.subplot(4, 3, 4)
plt.plot(X, intersection)
plt.title("""intersection""")
plt.grid(True)
plt.subplot(4, 3, 5)
plt.plot(X, complement_a)
plt.title("""complement_a""")
plt.grid(True)
plt.subplot(4, 3, 6)
plt.plot(X, difference)
plt.title("""difference a/b""")
plt.grid(True)
plt.subplot(4, 3, 7)
plt.plot(X, alg_sum)
plt.title("""alg_sum""")
plt.grid(True)
plt.subplot(4, 3, 8)
plt.plot(X, alg_product)
plt.title("""alg_product""")
plt.grid(True)
plt.subplot(4, 3, 9)
plt.plot(X, bdd_sum)
plt.title("""bdd_sum""")
plt.grid(True)
plt.subplot(4, 3, 1_0)
plt.plot(X, bdd_difference)
plt.title("""bdd_difference""")
plt.grid(True)
plt.subplots_adjust(hspace=0.5)
plt.show()
| 33 |
import gc
import unittest
from diffusers import FlaxDPMSolverMultistepScheduler, FlaxStableDiffusionPipeline
from diffusers.utils import is_flax_available, slow
from diffusers.utils.testing_utils import require_flax
if is_flax_available():
import jax
import jax.numpy as jnp
from flax.jax_utils import replicate
from flax.training.common_utils import shard
@slow
@require_flax
class lowerCAmelCase ( unittest.TestCase ):
'''simple docstring'''
def lowerCamelCase__ ( self : int ) -> Dict:
'''simple docstring'''
super().tearDown()
gc.collect()
def lowerCamelCase__ ( self : int ) -> str:
'''simple docstring'''
lowerCamelCase , lowerCamelCase = FlaxStableDiffusionPipeline.from_pretrained(
'stabilityai/stable-diffusion-2' , revision='bf16' , dtype=jnp.bfloataa , )
lowerCamelCase = 'A painting of a squirrel eating a burger'
lowerCamelCase = jax.device_count()
lowerCamelCase = num_samples * [prompt]
lowerCamelCase = sd_pipe.prepare_inputs(__snake_case )
lowerCamelCase = replicate(__snake_case )
lowerCamelCase = shard(__snake_case )
lowerCamelCase = jax.random.PRNGKey(0 )
lowerCamelCase = jax.random.split(__snake_case , jax.device_count() )
lowerCamelCase = sd_pipe(__snake_case , __snake_case , __snake_case , num_inference_steps=25 , jit=__snake_case )[0]
assert images.shape == (jax.device_count(), 1, 768, 768, 3)
lowerCamelCase = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] )
lowerCamelCase = images[0, 253:256, 253:256, -1]
lowerCamelCase = jnp.asarray(jax.device_get(image_slice.flatten() ) )
lowerCamelCase = jnp.array([0.4238, 0.4414, 0.4395, 0.4453, 0.4629, 0.4590, 0.4531, 0.4_5508, 0.4512] )
print(F'''output_slice: {output_slice}''' )
assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
def lowerCamelCase__ ( self : str ) -> Optional[int]:
'''simple docstring'''
lowerCamelCase = 'stabilityai/stable-diffusion-2'
lowerCamelCase , lowerCamelCase = FlaxDPMSolverMultistepScheduler.from_pretrained(__snake_case , subfolder='scheduler' )
lowerCamelCase , lowerCamelCase = FlaxStableDiffusionPipeline.from_pretrained(
__snake_case , scheduler=__snake_case , revision='bf16' , dtype=jnp.bfloataa , )
lowerCamelCase = scheduler_params
lowerCamelCase = 'A painting of a squirrel eating a burger'
lowerCamelCase = jax.device_count()
lowerCamelCase = num_samples * [prompt]
lowerCamelCase = sd_pipe.prepare_inputs(__snake_case )
lowerCamelCase = replicate(__snake_case )
lowerCamelCase = shard(__snake_case )
lowerCamelCase = jax.random.PRNGKey(0 )
lowerCamelCase = jax.random.split(__snake_case , jax.device_count() )
lowerCamelCase = sd_pipe(__snake_case , __snake_case , __snake_case , num_inference_steps=25 , jit=__snake_case )[0]
assert images.shape == (jax.device_count(), 1, 768, 768, 3)
lowerCamelCase = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] )
lowerCamelCase = images[0, 253:256, 253:256, -1]
lowerCamelCase = jnp.asarray(jax.device_get(image_slice.flatten() ) )
lowerCamelCase = jnp.array([0.4336, 0.4_2969, 0.4453, 0.4199, 0.4297, 0.4531, 0.4434, 0.4434, 0.4297] )
print(F'''output_slice: {output_slice}''' )
assert jnp.abs(output_slice - expected_slice ).max() < 1e-2
| 246 | 0 |
"""simple docstring"""
import unittest
from diffusers.pipelines.pipeline_utils import is_safetensors_compatible
class snake_case__ ( unittest.TestCase ):
def __lowerCAmelCase ( self : Any ):
'''simple docstring'''
UpperCAmelCase : Union[str, Any] = [
"safety_checker/pytorch_model.bin",
"safety_checker/model.safetensors",
"vae/diffusion_pytorch_model.bin",
"vae/diffusion_pytorch_model.safetensors",
"text_encoder/pytorch_model.bin",
"text_encoder/model.safetensors",
"unet/diffusion_pytorch_model.bin",
"unet/diffusion_pytorch_model.safetensors",
]
self.assertTrue(is_safetensors_compatible(lowercase ) )
def __lowerCAmelCase ( self : int ):
'''simple docstring'''
UpperCAmelCase : List[str] = [
"unet/diffusion_pytorch_model.bin",
"unet/diffusion_pytorch_model.safetensors",
]
self.assertTrue(is_safetensors_compatible(lowercase ) )
def __lowerCAmelCase ( self : List[Any] ):
'''simple docstring'''
UpperCAmelCase : int = [
"safety_checker/pytorch_model.bin",
"safety_checker/model.safetensors",
"vae/diffusion_pytorch_model.bin",
"vae/diffusion_pytorch_model.safetensors",
"text_encoder/pytorch_model.bin",
"text_encoder/model.safetensors",
"unet/diffusion_pytorch_model.bin",
# Removed: 'unet/diffusion_pytorch_model.safetensors',
]
self.assertFalse(is_safetensors_compatible(lowercase ) )
def __lowerCAmelCase ( self : List[Any] ):
'''simple docstring'''
UpperCAmelCase : Any = [
"text_encoder/pytorch_model.bin",
"text_encoder/model.safetensors",
]
self.assertTrue(is_safetensors_compatible(lowercase ) )
def __lowerCAmelCase ( self : Any ):
'''simple docstring'''
UpperCAmelCase : Union[str, Any] = [
"safety_checker/pytorch_model.bin",
"safety_checker/model.safetensors",
"vae/diffusion_pytorch_model.bin",
"vae/diffusion_pytorch_model.safetensors",
"text_encoder/pytorch_model.bin",
# Removed: 'text_encoder/model.safetensors',
"unet/diffusion_pytorch_model.bin",
"unet/diffusion_pytorch_model.safetensors",
]
self.assertFalse(is_safetensors_compatible(lowercase ) )
def __lowerCAmelCase ( self : Tuple ):
'''simple docstring'''
UpperCAmelCase : Union[str, Any] = [
"safety_checker/pytorch_model.fp16.bin",
"safety_checker/model.fp16.safetensors",
"vae/diffusion_pytorch_model.fp16.bin",
"vae/diffusion_pytorch_model.fp16.safetensors",
"text_encoder/pytorch_model.fp16.bin",
"text_encoder/model.fp16.safetensors",
"unet/diffusion_pytorch_model.fp16.bin",
"unet/diffusion_pytorch_model.fp16.safetensors",
]
UpperCAmelCase : Optional[Any] = "fp16"
self.assertTrue(is_safetensors_compatible(lowercase , variant=lowercase ) )
def __lowerCAmelCase ( self : List[str] ):
'''simple docstring'''
UpperCAmelCase : Tuple = [
"unet/diffusion_pytorch_model.fp16.bin",
"unet/diffusion_pytorch_model.fp16.safetensors",
]
UpperCAmelCase : Any = "fp16"
self.assertTrue(is_safetensors_compatible(lowercase , variant=lowercase ) )
def __lowerCAmelCase ( self : str ):
'''simple docstring'''
UpperCAmelCase : List[str] = [
"unet/diffusion_pytorch_model.bin",
"unet/diffusion_pytorch_model.safetensors",
]
UpperCAmelCase : List[Any] = "fp16"
self.assertTrue(is_safetensors_compatible(lowercase , variant=lowercase ) )
def __lowerCAmelCase ( self : Tuple ):
'''simple docstring'''
UpperCAmelCase : int = [
"safety_checker/pytorch_model.fp16.bin",
"safety_checker/model.fp16.safetensors",
"vae/diffusion_pytorch_model.fp16.bin",
"vae/diffusion_pytorch_model.fp16.safetensors",
"text_encoder/pytorch_model.fp16.bin",
"text_encoder/model.fp16.safetensors",
"unet/diffusion_pytorch_model.fp16.bin",
# Removed: 'unet/diffusion_pytorch_model.fp16.safetensors',
]
UpperCAmelCase : List[str] = "fp16"
self.assertFalse(is_safetensors_compatible(lowercase , variant=lowercase ) )
def __lowerCAmelCase ( self : Tuple ):
'''simple docstring'''
UpperCAmelCase : int = [
"text_encoder/pytorch_model.fp16.bin",
"text_encoder/model.fp16.safetensors",
]
UpperCAmelCase : Tuple = "fp16"
self.assertTrue(is_safetensors_compatible(lowercase , variant=lowercase ) )
def __lowerCAmelCase ( self : List[str] ):
'''simple docstring'''
UpperCAmelCase : Dict = [
"text_encoder/pytorch_model.bin",
"text_encoder/model.safetensors",
]
UpperCAmelCase : Optional[Any] = "fp16"
self.assertTrue(is_safetensors_compatible(lowercase , variant=lowercase ) )
def __lowerCAmelCase ( self : List[str] ):
'''simple docstring'''
UpperCAmelCase : Union[str, Any] = [
"safety_checker/pytorch_model.fp16.bin",
"safety_checker/model.fp16.safetensors",
"vae/diffusion_pytorch_model.fp16.bin",
"vae/diffusion_pytorch_model.fp16.safetensors",
"text_encoder/pytorch_model.fp16.bin",
# 'text_encoder/model.fp16.safetensors',
"unet/diffusion_pytorch_model.fp16.bin",
"unet/diffusion_pytorch_model.fp16.safetensors",
]
UpperCAmelCase : Dict = "fp16"
self.assertFalse(is_safetensors_compatible(lowercase , variant=lowercase ) )
| 292 |
"""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 snake_case__ :
def __init__( self : Optional[Any] , lowercase : int , lowercase : List[Any]=13 , lowercase : List[str]=2 , lowercase : Tuple=24 , lowercase : Dict=16 , lowercase : Optional[int]=True , lowercase : Any=True , lowercase : Dict=32 , lowercase : List[str]=5 , lowercase : Union[str, Any]=4 , lowercase : Tuple=37 , lowercase : Tuple="gelu" , lowercase : Dict=0.1 , lowercase : Any=0.1 , lowercase : Any=10 , lowercase : List[str]=0.0_2 , lowercase : int=None , lowercase : Optional[Any]=2 , lowercase : str=2 , ):
'''simple docstring'''
UpperCAmelCase : int = parent
UpperCAmelCase : Optional[int] = batch_size
UpperCAmelCase : str = patch_size
UpperCAmelCase : Dict = max_length
UpperCAmelCase : Dict = num_mel_bins
UpperCAmelCase : Optional[Any] = is_training
UpperCAmelCase : str = use_labels
UpperCAmelCase : Dict = hidden_size
UpperCAmelCase : Tuple = num_hidden_layers
UpperCAmelCase : Tuple = num_attention_heads
UpperCAmelCase : Optional[Any] = intermediate_size
UpperCAmelCase : Tuple = hidden_act
UpperCAmelCase : Optional[int] = hidden_dropout_prob
UpperCAmelCase : Optional[Any] = attention_probs_dropout_prob
UpperCAmelCase : Any = type_sequence_label_size
UpperCAmelCase : Dict = initializer_range
UpperCAmelCase : Optional[int] = scope
UpperCAmelCase : List[Any] = frequency_stride
UpperCAmelCase : Tuple = time_stride
# in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
UpperCAmelCase : List[str] = (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1
UpperCAmelCase : List[str] = (self.max_length - self.patch_size) // self.time_stride + 1
UpperCAmelCase : Dict = frequency_out_dimension * time_out_dimension
UpperCAmelCase : int = num_patches + 2
def __lowerCAmelCase ( self : Optional[Any] ):
'''simple docstring'''
UpperCAmelCase : List[str] = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins] )
UpperCAmelCase : Optional[Any] = None
if self.use_labels:
UpperCAmelCase : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size )
UpperCAmelCase : List[str] = self.get_config()
return config, input_values, labels
def __lowerCAmelCase ( self : str ):
'''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=lowercase , initializer_range=self.initializer_range , frequency_stride=self.frequency_stride , time_stride=self.time_stride , )
def __lowerCAmelCase ( self : List[Any] , lowercase : Optional[int] , lowercase : Any , lowercase : List[str] ):
'''simple docstring'''
UpperCAmelCase : Tuple = ASTModel(config=lowercase )
model.to(lowercase )
model.eval()
UpperCAmelCase : Optional[int] = model(lowercase )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def __lowerCAmelCase ( self : Dict ):
'''simple docstring'''
UpperCAmelCase : Union[str, Any] = self.prepare_config_and_inputs()
(
(
UpperCAmelCase
) , (
UpperCAmelCase
) , (
UpperCAmelCase
) ,
) : Tuple = config_and_inputs
UpperCAmelCase : int = {"input_values": input_values}
return config, inputs_dict
@require_torch
class snake_case__ ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ):
SCREAMING_SNAKE_CASE__ = (
(
ASTModel,
ASTForAudioClassification,
)
if is_torch_available()
else ()
)
SCREAMING_SNAKE_CASE__ = (
{'''audio-classification''': ASTForAudioClassification, '''feature-extraction''': ASTModel}
if is_torch_available()
else {}
)
SCREAMING_SNAKE_CASE__ = False
SCREAMING_SNAKE_CASE__ = False
SCREAMING_SNAKE_CASE__ = False
SCREAMING_SNAKE_CASE__ = False
def __lowerCAmelCase ( self : Optional[Any] , lowercase : Optional[Any] , lowercase : Union[str, Any] , lowercase : List[str] , lowercase : Any , lowercase : str ):
'''simple docstring'''
if pipeline_test_casse_name == "AudioClassificationPipelineTests":
return True
return False
def __lowerCAmelCase ( self : str ):
'''simple docstring'''
UpperCAmelCase : int = ASTModelTester(self )
UpperCAmelCase : Union[str, Any] = ConfigTester(self , config_class=lowercase , has_text_modality=lowercase , hidden_size=37 )
def __lowerCAmelCase ( self : str ):
'''simple docstring'''
self.config_tester.run_common_tests()
@unittest.skip(reason="AST does not use inputs_embeds" )
def __lowerCAmelCase ( self : List[str] ):
'''simple docstring'''
pass
def __lowerCAmelCase ( self : Dict ):
'''simple docstring'''
UpperCAmelCase , UpperCAmelCase : str = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCAmelCase : Dict = model_class(lowercase )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
UpperCAmelCase : List[Any] = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(lowercase , nn.Linear ) )
def __lowerCAmelCase ( self : List[Any] ):
'''simple docstring'''
UpperCAmelCase , UpperCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
UpperCAmelCase : Dict = model_class(lowercase )
UpperCAmelCase : Any = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
UpperCAmelCase : List[str] = [*signature.parameters.keys()]
UpperCAmelCase : List[str] = ["input_values"]
self.assertListEqual(arg_names[:1] , lowercase )
def __lowerCAmelCase ( self : Optional[int] ):
'''simple docstring'''
UpperCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowercase )
@slow
def __lowerCAmelCase ( self : str ):
'''simple docstring'''
for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
UpperCAmelCase : Dict = ASTModel.from_pretrained(lowercase )
self.assertIsNotNone(lowercase )
def lowercase_ ( ):
'''simple docstring'''
UpperCAmelCase : List[str] = hf_hub_download(
repo_id="nielsr/audio-spectogram-transformer-checkpoint" , filename="sample_audio.flac" , repo_type="dataset" )
UpperCAmelCase , UpperCAmelCase : str = torchaudio.load(_lowercase )
return audio, sampling_rate
@require_torch
@require_torchaudio
class snake_case__ ( unittest.TestCase ):
@cached_property
def __lowerCAmelCase ( self : List[Any] ):
'''simple docstring'''
return (
ASTFeatureExtractor.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593" )
if is_torchaudio_available()
else None
)
@slow
def __lowerCAmelCase ( self : Union[str, Any] ):
'''simple docstring'''
UpperCAmelCase : Union[str, Any] = self.default_feature_extractor
UpperCAmelCase : Union[str, Any] = ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593" ).to(lowercase )
UpperCAmelCase : Any = self.default_feature_extractor
UpperCAmelCase , UpperCAmelCase : Optional[int] = prepare_audio()
UpperCAmelCase : str = audio.squeeze().numpy()
UpperCAmelCase : List[Any] = feature_extractor(lowercase , sampling_rate=lowercase , return_tensors="pt" ).to(lowercase )
# forward pass
with torch.no_grad():
UpperCAmelCase : Dict = model(**lowercase )
# verify the logits
UpperCAmelCase : Dict = torch.Size((1, 5_27) )
self.assertEqual(outputs.logits.shape , lowercase )
UpperCAmelCase : Optional[Any] = torch.tensor([-0.8_7_6_0, -7.0_0_4_2, -8.6_6_0_2] ).to(lowercase )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowercase , atol=1E-4 ) )
| 292 | 1 |
'''simple docstring'''
from __future__ import annotations
import os
import tempfile
import unittest
from transformers import ConvBertConfig, is_tf_available
from transformers.testing_utils import require_tf, slow
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
TFConvBertForMaskedLM,
TFConvBertForMultipleChoice,
TFConvBertForQuestionAnswering,
TFConvBertForSequenceClassification,
TFConvBertForTokenClassification,
TFConvBertModel,
)
class _SCREAMING_SNAKE_CASE :
def __init__( self : Tuple , a__ : Any , a__ : Optional[int]=13 , a__ : Optional[int]=7 , a__ : int=True , a__ : List[str]=True , a__ : Union[str, Any]=True , a__ : str=True , a__ : str=99 , a__ : Dict=32 , a__ : List[Any]=2 , a__ : Any=4 , a__ : str=37 , a__ : Tuple="gelu" , a__ : List[str]=0.1 , a__ : Union[str, Any]=0.1 , a__ : List[str]=512 , a__ : Any=16 , a__ : Union[str, Any]=2 , a__ : Optional[Any]=0.02 , a__ : Any=3 , a__ : Union[str, Any]=4 , a__ : Tuple=None , ):
__magic_name__ = parent
__magic_name__ = 13
__magic_name__ = 7
__magic_name__ = True
__magic_name__ = True
__magic_name__ = True
__magic_name__ = True
__magic_name__ = 99
__magic_name__ = 384
__magic_name__ = 2
__magic_name__ = 4
__magic_name__ = 37
__magic_name__ = 'gelu'
__magic_name__ = 0.1
__magic_name__ = 0.1
__magic_name__ = 512
__magic_name__ = 16
__magic_name__ = 2
__magic_name__ = 0.02
__magic_name__ = 3
__magic_name__ = 4
__magic_name__ = 128
__magic_name__ = 2
__magic_name__ = 9
__magic_name__ = 1
__magic_name__ = None
def snake_case__ ( self : Tuple ):
__magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
__magic_name__ = None
if self.use_input_mask:
__magic_name__ = random_attention_mask([self.batch_size, self.seq_length] )
__magic_name__ = None
if self.use_token_type_ids:
__magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
__magic_name__ = None
__magic_name__ = None
__magic_name__ = None
if self.use_labels:
__magic_name__ = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
__magic_name__ = ids_tensor([self.batch_size] , self.num_choices )
__magic_name__ = ConvBertConfig(
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 , return_dict=a__ , )
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
def snake_case__ ( self : Dict , a__ : Dict , a__ : Tuple , a__ : Union[str, Any] , a__ : Optional[Any] , a__ : str , a__ : str , a__ : Optional[int] ):
__magic_name__ = TFConvBertModel(config=a__ )
__magic_name__ = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids}
__magic_name__ = [input_ids, input_mask]
__magic_name__ = model(a__ )
__magic_name__ = model(a__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
def snake_case__ ( self : Union[str, Any] , a__ : Optional[Any] , a__ : List[Any] , a__ : Tuple , a__ : int , a__ : List[Any] , a__ : List[str] , a__ : Optional[int] ):
__magic_name__ = TFConvBertForMaskedLM(config=a__ )
__magic_name__ = {
'input_ids': input_ids,
'attention_mask': input_mask,
'token_type_ids': token_type_ids,
}
__magic_name__ = model(a__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def snake_case__ ( self : Tuple , a__ : List[Any] , a__ : Any , a__ : Union[str, Any] , a__ : str , a__ : Optional[int] , a__ : List[str] , a__ : List[str] ):
__magic_name__ = self.num_labels
__magic_name__ = TFConvBertForSequenceClassification(config=a__ )
__magic_name__ = {
'input_ids': input_ids,
'attention_mask': input_mask,
'token_type_ids': token_type_ids,
}
__magic_name__ = model(a__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def snake_case__ ( self : Union[str, Any] , a__ : List[str] , a__ : Tuple , a__ : str , a__ : int , a__ : str , a__ : List[str] , a__ : List[Any] ):
__magic_name__ = self.num_choices
__magic_name__ = TFConvBertForMultipleChoice(config=a__ )
__magic_name__ = tf.tile(tf.expand_dims(a__ , 1 ) , (1, self.num_choices, 1) )
__magic_name__ = tf.tile(tf.expand_dims(a__ , 1 ) , (1, self.num_choices, 1) )
__magic_name__ = tf.tile(tf.expand_dims(a__ , 1 ) , (1, self.num_choices, 1) )
__magic_name__ = {
'input_ids': multiple_choice_inputs_ids,
'attention_mask': multiple_choice_input_mask,
'token_type_ids': multiple_choice_token_type_ids,
}
__magic_name__ = model(a__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def snake_case__ ( self : str , a__ : Optional[Any] , a__ : Tuple , a__ : int , a__ : str , a__ : int , a__ : Optional[Any] , a__ : Union[str, Any] ):
__magic_name__ = self.num_labels
__magic_name__ = TFConvBertForTokenClassification(config=a__ )
__magic_name__ = {
'input_ids': input_ids,
'attention_mask': input_mask,
'token_type_ids': token_type_ids,
}
__magic_name__ = model(a__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def snake_case__ ( self : Any , a__ : Any , a__ : Any , a__ : Tuple , a__ : List[Any] , a__ : List[Any] , a__ : Tuple , a__ : Optional[int] ):
__magic_name__ = TFConvBertForQuestionAnswering(config=a__ )
__magic_name__ = {
'input_ids': input_ids,
'attention_mask': input_mask,
'token_type_ids': token_type_ids,
}
__magic_name__ = model(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 snake_case__ ( self : Union[str, Any] ):
__magic_name__ = self.prepare_config_and_inputs()
(
__magic_name__
) = config_and_inputs
__magic_name__ = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
return config, inputs_dict
@require_tf
class _SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ,unittest.TestCase ):
__SCREAMING_SNAKE_CASE :Tuple = (
(
TFConvBertModel,
TFConvBertForMaskedLM,
TFConvBertForQuestionAnswering,
TFConvBertForSequenceClassification,
TFConvBertForTokenClassification,
TFConvBertForMultipleChoice,
)
if is_tf_available()
else ()
)
__SCREAMING_SNAKE_CASE :List[Any] = (
{
'feature-extraction': TFConvBertModel,
'fill-mask': TFConvBertForMaskedLM,
'question-answering': TFConvBertForQuestionAnswering,
'text-classification': TFConvBertForSequenceClassification,
'token-classification': TFConvBertForTokenClassification,
'zero-shot': TFConvBertForSequenceClassification,
}
if is_tf_available()
else {}
)
__SCREAMING_SNAKE_CASE :str = False
__SCREAMING_SNAKE_CASE :Dict = False
__SCREAMING_SNAKE_CASE :str = False
def snake_case__ ( self : Dict ):
__magic_name__ = TFConvBertModelTester(self )
__magic_name__ = ConfigTester(self , config_class=a__ , hidden_size=37 )
def snake_case__ ( self : List[str] ):
self.config_tester.run_common_tests()
def snake_case__ ( self : str ):
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*a__ )
def snake_case__ ( self : str ):
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*a__ )
def snake_case__ ( self : List[Any] ):
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*a__ )
def snake_case__ ( self : Tuple ):
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*a__ )
def snake_case__ ( self : Union[str, Any] ):
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*a__ )
def snake_case__ ( self : Tuple ):
__magic_name__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*a__ )
@slow
def snake_case__ ( self : Optional[Any] ):
__magic_name__ = self.model_tester.prepare_config_and_inputs_for_common()
__magic_name__ = True
__magic_name__ = True
if hasattr(a__ , '''use_cache''' ):
__magic_name__ = True
__magic_name__ = getattr(self.model_tester , '''encoder_seq_length''' , self.model_tester.seq_length )
__magic_name__ = getattr(self.model_tester , '''key_length''' , a__ )
for model_class in self.all_model_classes:
__magic_name__ = self._prepare_for_class(a__ , a__ )
__magic_name__ = model_class(a__ )
__magic_name__ = len(model(a__ ) )
with tempfile.TemporaryDirectory() as tmpdirname:
model.save_pretrained(a__ , saved_model=a__ )
__magic_name__ = os.path.join(a__ , '''saved_model''' , '''1''' )
__magic_name__ = tf.keras.models.load_model(a__ )
__magic_name__ = model(a__ )
if self.is_encoder_decoder:
__magic_name__ = outputs['encoder_hidden_states']
__magic_name__ = outputs['encoder_attentions']
else:
__magic_name__ = outputs['hidden_states']
__magic_name__ = outputs['attentions']
self.assertEqual(len(a__ ) , a__ )
__magic_name__ = getattr(
self.model_tester , '''expected_num_hidden_layers''' , self.model_tester.num_hidden_layers + 1 )
self.assertEqual(len(a__ ) , a__ )
self.assertListEqual(
list(output_hidden_states[0].shape[-2:] ) , [self.model_tester.seq_length, self.model_tester.hidden_size] , )
self.assertEqual(len(a__ ) , self.model_tester.num_hidden_layers )
self.assertListEqual(
list(output_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , )
@slow
def snake_case__ ( self : Tuple ):
__magic_name__ = TFConvBertModel.from_pretrained('''YituTech/conv-bert-base''' )
self.assertIsNotNone(a__ )
def snake_case__ ( self : Optional[Any] ):
__magic_name__ = self.model_tester.prepare_config_and_inputs_for_common()
__magic_name__ = True
__magic_name__ = getattr(self.model_tester , '''decoder_seq_length''' , self.model_tester.seq_length )
__magic_name__ = getattr(self.model_tester , '''encoder_seq_length''' , self.model_tester.seq_length )
__magic_name__ = getattr(self.model_tester , '''key_length''' , a__ )
__magic_name__ = getattr(self.model_tester , '''key_length''' , a__ )
def check_decoder_attentions_output(a__ : Dict ):
__magic_name__ = len(a__ )
self.assertEqual(out_len % 2 , 0 )
__magic_name__ = outputs.decoder_attentions
self.assertEqual(len(a__ ) , self.model_tester.num_hidden_layers )
self.assertListEqual(
list(decoder_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, decoder_seq_length, decoder_key_length] , )
def check_encoder_attentions_output(a__ : Any ):
__magic_name__ = [
t.numpy() for t in (outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions)
]
self.assertEqual(len(a__ ) , self.model_tester.num_hidden_layers )
self.assertListEqual(
list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads / 2, encoder_seq_length, encoder_key_length] , )
for model_class in self.all_model_classes:
__magic_name__ = True
__magic_name__ = False
__magic_name__ = model_class(a__ )
__magic_name__ = model(self._prepare_for_class(a__ , a__ ) )
__magic_name__ = len(a__ )
self.assertEqual(config.output_hidden_states , a__ )
check_encoder_attentions_output(a__ )
if self.is_encoder_decoder:
__magic_name__ = model_class(a__ )
__magic_name__ = model(self._prepare_for_class(a__ , a__ ) )
self.assertEqual(config.output_hidden_states , a__ )
check_decoder_attentions_output(a__ )
# Check that output attentions can also be changed via the config
del inputs_dict["output_attentions"]
__magic_name__ = True
__magic_name__ = model_class(a__ )
__magic_name__ = model(self._prepare_for_class(a__ , a__ ) )
self.assertEqual(config.output_hidden_states , a__ )
check_encoder_attentions_output(a__ )
# Check attention is always last and order is fine
__magic_name__ = True
__magic_name__ = True
__magic_name__ = model_class(a__ )
__magic_name__ = model(self._prepare_for_class(a__ , a__ ) )
self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1) , len(a__ ) )
self.assertEqual(model.config.output_hidden_states , a__ )
check_encoder_attentions_output(a__ )
@require_tf
class _SCREAMING_SNAKE_CASE ( unittest.TestCase ):
@slow
def snake_case__ ( self : List[str] ):
__magic_name__ = TFConvBertModel.from_pretrained('''YituTech/conv-bert-base''' )
__magic_name__ = tf.constant([[0, 1, 2, 3, 4, 5]] )
__magic_name__ = model(a__ )[0]
__magic_name__ = [1, 6, 768]
self.assertEqual(output.shape , a__ )
__magic_name__ = tf.constant(
[
[
[-0.03_475_493, -0.4_686_034, -0.30_638_832],
[0.22_637_248, -0.26_988_646, -0.7_423_424],
[0.10_324_868, -0.45_013_508, -0.58_280_784],
]
] )
tf.debugging.assert_near(output[:, :3, :3] , a__ , atol=1E-4 )
| 432 |
import requests
_lowerCamelCase : int = """https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey="""
def __a ( __lowerCAmelCase ) -> None:
# fetching a list of articles in json format
SCREAMING_SNAKE_CASE : List[str] = requests.get(_NEWS_API + bbc_news_api_key ).json()
# each article in the list is a dict
for i, article in enumerate(bbc_news_page['articles'] , 1 ):
print(F'''{i}.) {article['title']}''' )
if __name__ == "__main__":
fetch_bbc_news(bbc_news_api_key="""<Your BBC News API key goes here>""") | 352 | 0 |
"""simple docstring"""
def __lowercase ( _a , _a ):
snake_case_ : str = [0 for i in range(r + 1 )]
# nc0 = 1
snake_case_ : int = 1
for i in range(1 , n + 1 ):
# to compute current row from previous row.
snake_case_ : Any = min(_a , _a )
while j > 0:
c[j] += c[j - 1]
j -= 1
return c[r]
print(binomial_coefficient(n=10, r=5))
| 706 |
"""simple docstring"""
import argparse
import re
import numpy as np
import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import (
SamConfig,
SamImageProcessor,
SamModel,
SamProcessor,
SamVisionConfig,
)
lowercase__ : List[str] = {
'''iou_prediction_head.layers.0''': '''iou_prediction_head.proj_in''',
'''iou_prediction_head.layers.1''': '''iou_prediction_head.layers.0''',
'''iou_prediction_head.layers.2''': '''iou_prediction_head.proj_out''',
'''mask_decoder.output_upscaling.0''': '''mask_decoder.upscale_conv1''',
'''mask_decoder.output_upscaling.1''': '''mask_decoder.upscale_layer_norm''',
'''mask_decoder.output_upscaling.3''': '''mask_decoder.upscale_conv2''',
'''mask_downscaling.0''': '''mask_embed.conv1''',
'''mask_downscaling.1''': '''mask_embed.layer_norm1''',
'''mask_downscaling.3''': '''mask_embed.conv2''',
'''mask_downscaling.4''': '''mask_embed.layer_norm2''',
'''mask_downscaling.6''': '''mask_embed.conv3''',
'''point_embeddings''': '''point_embed''',
'''pe_layer.positional_encoding_gaussian_matrix''': '''shared_embedding.positional_embedding''',
'''image_encoder''': '''vision_encoder''',
'''neck.0''': '''neck.conv1''',
'''neck.1''': '''neck.layer_norm1''',
'''neck.2''': '''neck.conv2''',
'''neck.3''': '''neck.layer_norm2''',
'''patch_embed.proj''': '''patch_embed.projection''',
'''.norm''': '''.layer_norm''',
'''blocks''': '''layers''',
}
def __lowercase ( _a ):
snake_case_ : List[str] = {}
state_dict.pop('''pixel_mean''' , _a )
state_dict.pop('''pixel_std''' , _a )
snake_case_ : Union[str, Any] = r'''.*.output_hypernetworks_mlps.(\d+).layers.(\d+).*'''
for key, value in state_dict.items():
for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items():
if key_to_modify in key:
snake_case_ : Optional[int] = key.replace(_a , _a )
if re.match(_a , _a ):
snake_case_ : Union[str, Any] = int(re.match(_a , _a ).group(2 ) )
if layer_nb == 0:
snake_case_ : Optional[int] = key.replace('''layers.0''' , '''proj_in''' )
elif layer_nb == 1:
snake_case_ : Union[str, Any] = key.replace('''layers.1''' , '''layers.0''' )
elif layer_nb == 2:
snake_case_ : List[Any] = key.replace('''layers.2''' , '''proj_out''' )
snake_case_ : Optional[Any] = value
snake_case_ : Tuple = model_state_dict[
'''prompt_encoder.shared_embedding.positional_embedding'''
]
return model_state_dict
def __lowercase ( _a , _a , _a , _a="ybelkada/segment-anything" ):
snake_case_ : Optional[Any] = hf_hub_download(_a , f"checkpoints/{model_name}.pth" )
if "sam_vit_b" in model_name:
snake_case_ : Tuple = SamConfig()
elif "sam_vit_l" in model_name:
snake_case_ : Optional[Any] = SamVisionConfig(
hidden_size=1_024 , num_hidden_layers=24 , num_attention_heads=16 , global_attn_indexes=[5, 11, 17, 23] , )
snake_case_ : Union[str, Any] = SamConfig(
vision_config=_a , )
elif "sam_vit_h" in model_name:
snake_case_ : Tuple = SamVisionConfig(
hidden_size=1_280 , num_hidden_layers=32 , num_attention_heads=16 , global_attn_indexes=[7, 15, 23, 31] , )
snake_case_ : List[str] = SamConfig(
vision_config=_a , )
snake_case_ : Tuple = torch.load(_a , map_location='''cpu''' )
snake_case_ : Optional[Any] = replace_keys(_a )
snake_case_ : Any = SamImageProcessor()
snake_case_ : Optional[Any] = SamProcessor(image_processor=_a )
snake_case_ : Tuple = SamModel(_a )
hf_model.load_state_dict(_a )
snake_case_ : Tuple = hf_model.to('''cuda''' )
snake_case_ : Union[str, Any] = '''https://huggingface.co/ybelkada/segment-anything/resolve/main/assets/car.png'''
snake_case_ : Union[str, Any] = Image.open(requests.get(_a , stream=_a ).raw ).convert('''RGB''' )
snake_case_ : Tuple = [[[400, 650]]]
snake_case_ : List[str] = [[1]]
snake_case_ : Optional[int] = processor(images=np.array(_a ) , return_tensors='''pt''' ).to('''cuda''' )
with torch.no_grad():
snake_case_ : Optional[Any] = hf_model(**_a )
snake_case_ : Any = output.iou_scores.squeeze()
if model_name == "sam_vit_h_4b8939":
assert scores[-1].item() == 0.579_8902_5115_9668
snake_case_ : Optional[Any] = processor(
images=np.array(_a ) , input_points=_a , input_labels=_a , return_tensors='''pt''' ).to('''cuda''' )
with torch.no_grad():
snake_case_ : Optional[Any] = hf_model(**_a )
snake_case_ : Tuple = output.iou_scores.squeeze()
assert scores[-1].item() == 0.9712_6030_9219_3604
snake_case_ : Tuple = ((75, 275, 1_725, 850),)
snake_case_ : Optional[Any] = processor(images=np.array(_a ) , input_boxes=_a , return_tensors='''pt''' ).to('''cuda''' )
with torch.no_grad():
snake_case_ : Dict = hf_model(**_a )
snake_case_ : Any = output.iou_scores.squeeze()
assert scores[-1].item() == 0.8686_0156_0592_6514
# Test with 2 points and 1 image.
snake_case_ : Union[str, Any] = [[[400, 650], [800, 650]]]
snake_case_ : Optional[int] = [[1, 1]]
snake_case_ : Tuple = processor(
images=np.array(_a ) , input_points=_a , input_labels=_a , return_tensors='''pt''' ).to('''cuda''' )
with torch.no_grad():
snake_case_ : Dict = hf_model(**_a )
snake_case_ : Dict = output.iou_scores.squeeze()
assert scores[-1].item() == 0.9936_0477_9243_4692
if __name__ == "__main__":
lowercase__ : Optional[int] = argparse.ArgumentParser()
lowercase__ : Any = ['''sam_vit_b_01ec64''', '''sam_vit_h_4b8939''', '''sam_vit_l_0b3195''']
parser.add_argument(
'''--model_name''',
default='''sam_vit_h_4b8939''',
choices=choices,
type=str,
help='''Path to hf config.json of model to convert''',
)
parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
parser.add_argument(
'''--push_to_hub''',
action='''store_true''',
help='''Whether to push the model and processor to the hub after converting''',
)
parser.add_argument(
'''--model_hub_id''',
default='''ybelkada/segment-anything''',
choices=choices,
type=str,
help='''Path to hf config.json of model to convert''',
)
lowercase__ : Tuple = parser.parse_args()
convert_sam_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub, args.model_hub_id)
| 485 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.