code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
from dataclasses import dataclass from typing import Dict, Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, apply_forward_hook from .attention_processor import AttentionProcessor, AttnProcessor from .modeling_utils import ModelMixin from .vae import Decoder, DecoderOutput, DiagonalGaussianDistribution, Encoder @dataclass class snake_case__ ( _a ): _snake_case : Optional[int] = 42 class snake_case__ ( _a, _a ): _snake_case : Union[str, Any] = True @register_to_config def __init__( self , lowerCamelCase = 3 , lowerCamelCase = 3 , lowerCamelCase = ("DownEncoderBlock2D",) , lowerCamelCase = ("UpDecoderBlock2D",) , lowerCamelCase = (64,) , lowerCamelCase = 1 , lowerCamelCase = "silu" , lowerCamelCase = 4 , lowerCamelCase = 32 , lowerCamelCase = 32 , lowerCamelCase = 0.1_8215 , ): super().__init__() # pass init params to Encoder __a = Encoder( in_channels=_A , out_channels=_A , down_block_types=_A , block_out_channels=_A , layers_per_block=_A , act_fn=_A , norm_num_groups=_A , double_z=_A , ) # pass init params to Decoder __a = Decoder( in_channels=_A , out_channels=_A , up_block_types=_A , block_out_channels=_A , layers_per_block=_A , norm_num_groups=_A , act_fn=_A , ) __a = nn.Convad(2 * latent_channels , 2 * latent_channels , 1 ) __a = nn.Convad(_A , _A , 1 ) __a = False __a = False # only relevant if vae tiling is enabled __a = self.config.sample_size __a = ( self.config.sample_size[0] if isinstance(self.config.sample_size , (list, tuple) ) else self.config.sample_size ) __a = int(sample_size / (2 ** (len(self.config.block_out_channels ) - 1)) ) __a = 0.25 def a__ ( self , lowerCamelCase , lowerCamelCase=False ): if isinstance(_A , (Encoder, Decoder) ): __a = value def a__ ( self , lowerCamelCase = True ): __a = use_tiling def a__ ( self ): self.enable_tiling(_A ) def a__ ( self ): __a = True def a__ ( self ): __a = False @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def a__ ( self ): __a = {} def fn_recursive_add_processors(lowerCamelCase , lowerCamelCase , lowerCamelCase ): if hasattr(_A , "set_processor" ): __a = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(F"{name}.{sub_name}" , _A , _A ) return processors for name, module in self.named_children(): fn_recursive_add_processors(_A , _A , _A ) return processors def a__ ( self , lowerCamelCase ): __a = len(self.attn_processors.keys() ) if isinstance(_A , _A ) and len(_A ) != count: raise ValueError( F"A dict of processors was passed, but the number of processors {len(_A )} does not match the" F" number of attention layers: {count}. Please make sure to pass {count} processor classes." ) def fn_recursive_attn_processor(lowerCamelCase , lowerCamelCase , lowerCamelCase ): if hasattr(_A , "set_processor" ): if not isinstance(_A , _A ): module.set_processor(_A ) else: module.set_processor(processor.pop(F"{name}.processor" ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(F"{name}.{sub_name}" , _A , _A ) for name, module in self.named_children(): fn_recursive_attn_processor(_A , _A , _A ) def a__ ( self ): self.set_attn_processor(AttnProcessor() ) @apply_forward_hook def a__ ( self , lowerCamelCase , lowerCamelCase = True ): if self.use_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size): return self.tiled_encode(_A , return_dict=_A ) if self.use_slicing and x.shape[0] > 1: __a = [self.encoder(_A ) for x_slice in x.split(1 )] __a = torch.cat(_A ) else: __a = self.encoder(_A ) __a = self.quant_conv(_A ) __a = DiagonalGaussianDistribution(_A ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=_A ) def a__ ( self , lowerCamelCase , lowerCamelCase = True ): if self.use_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size): return self.tiled_decode(_A , return_dict=_A ) __a = self.post_quant_conv(_A ) __a = self.decoder(_A ) if not return_dict: return (dec,) return DecoderOutput(sample=_A ) @apply_forward_hook def a__ ( self , lowerCamelCase , lowerCamelCase = True ): if self.use_slicing and z.shape[0] > 1: __a = [self._decode(_A ).sample for z_slice in z.split(1 )] __a = torch.cat(_A ) else: __a = self._decode(_A ).sample if not return_dict: return (decoded,) return DecoderOutput(sample=_A ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = min(a.shape[2] , b.shape[2] , _A ) for y in range(_A ): __a = a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent) return b def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = min(a.shape[3] , b.shape[3] , _A ) for x in range(_A ): __a = a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent) return b def a__ ( self , lowerCamelCase , lowerCamelCase = True ): __a = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor) ) __a = int(self.tile_latent_min_size * self.tile_overlap_factor ) __a = self.tile_latent_min_size - blend_extent # Split the image into 512x512 tiles and encode them separately. __a = [] for i in range(0 , x.shape[2] , _A ): __a = [] for j in range(0 , x.shape[3] , _A ): __a = x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size] __a = self.encoder(_A ) __a = self.quant_conv(_A ) row.append(_A ) rows.append(_A ) __a = [] for i, row in enumerate(_A ): __a = [] for j, tile in enumerate(_A ): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: __a = self.blend_v(rows[i - 1][j] , _A , _A ) if j > 0: __a = self.blend_h(row[j - 1] , _A , _A ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(_A , dim=3 ) ) __a = torch.cat(_A , dim=2 ) __a = DiagonalGaussianDistribution(_A ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=_A ) def a__ ( self , lowerCamelCase , lowerCamelCase = True ): __a = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor) ) __a = int(self.tile_sample_min_size * self.tile_overlap_factor ) __a = self.tile_sample_min_size - blend_extent # Split z into overlapping 64x64 tiles and decode them separately. # The tiles have an overlap to avoid seams between tiles. __a = [] for i in range(0 , z.shape[2] , _A ): __a = [] for j in range(0 , z.shape[3] , _A ): __a = z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size] __a = self.post_quant_conv(_A ) __a = self.decoder(_A ) row.append(_A ) rows.append(_A ) __a = [] for i, row in enumerate(_A ): __a = [] for j, tile in enumerate(_A ): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: __a = self.blend_v(rows[i - 1][j] , _A , _A ) if j > 0: __a = self.blend_h(row[j - 1] , _A , _A ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(_A , dim=3 ) ) __a = torch.cat(_A , dim=2 ) if not return_dict: return (dec,) return DecoderOutput(sample=_A ) def a__ ( self , lowerCamelCase , lowerCamelCase = False , lowerCamelCase = True , lowerCamelCase = None , ): __a = sample __a = self.encode(_A ).latent_dist if sample_posterior: __a = posterior.sample(generator=_A ) else: __a = posterior.mode() __a = self.decode(_A ).sample if not return_dict: return (dec,) return DecoderOutput(sample=_A )
713
"""simple docstring""" from typing import Dict, Iterable, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging SCREAMING_SNAKE_CASE__:List[str] = logging.get_logger(__name__) class snake_case__ ( snake_case_ ): _snake_case : Dict = ["""pixel_values"""] def __init__( self , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = PILImageResampling.BICUBIC , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = True , lowerCamelCase = 1 / 255 , lowerCamelCase = True , lowerCamelCase = IMAGENET_DEFAULT_MEAN , lowerCamelCase = IMAGENET_DEFAULT_STD , **lowerCamelCase , ): super().__init__(**lowerCamelCase ) __a = size if size is not None else {"shortest_edge": 224} __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) __a = crop_size if crop_size is not None else {"height": 224, "width": 224} __a = get_size_dict(lowerCamelCase , param_name="crop_size" ) __a = do_resize __a = size __a = resample __a = do_center_crop __a = crop_size __a = do_rescale __a = rescale_factor __a = do_normalize __a = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN __a = image_std if image_std is not None else IMAGENET_DEFAULT_STD def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = PILImageResampling.BICUBIC , lowerCamelCase = None , **lowerCamelCase , ): __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) # size_dict is a dict with either keys "height" and "width" or "shortest_edge" if "shortest_edge" in size: __a = int((256 / 224) * size["shortest_edge"] ) __a = get_resize_output_image_size(lowerCamelCase , size=lowerCamelCase , default_to_square=lowerCamelCase ) __a = {"height": output_size[0], "width": output_size[1]} if "height" not in size_dict or "width" not in size_dict: raise ValueError( F"Size dict must have keys 'height' and 'width' or 'shortest_edge'. Got {size_dict.keys()}" ) return resize( lowerCamelCase , size=(size_dict["height"], size_dict["width"]) , resample=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): __a = get_size_dict(lowerCamelCase ) if "height" not in size or "width" not in size: raise ValueError(F"Size dict must have keys 'height' and 'width'. Got {size.keys()}" ) return center_crop(lowerCamelCase , size=(size["height"], size["width"]) , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): return rescale(lowerCamelCase , scale=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): return normalize(lowerCamelCase , mean=lowerCamelCase , std=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = ChannelDimension.FIRST , **lowerCamelCase , ): __a = do_resize if do_resize is not None else self.do_resize __a = resample if resample is not None else self.resample __a = do_center_crop if do_center_crop is not None else self.do_center_crop __a = do_rescale if do_rescale is not None else self.do_rescale __a = rescale_factor if rescale_factor is not None else self.rescale_factor __a = do_normalize if do_normalize is not None else self.do_normalize __a = image_mean if image_mean is not None else self.image_mean __a = image_std if image_std is not None else self.image_std __a = size if size is not None else self.size __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) __a = crop_size if crop_size is not None else self.crop_size __a = get_size_dict(lowerCamelCase , param_name="crop_size" ) __a = make_list_of_images(lowerCamelCase ) if not valid_images(lowerCamelCase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. __a = [to_numpy_array(lowerCamelCase ) for image in images] if do_resize: __a = [self.resize(lowerCamelCase , lowerCamelCase , lowerCamelCase ) for image in images] if do_center_crop: __a = [self.center_crop(lowerCamelCase , lowerCamelCase ) for image in images] if do_rescale: __a = [self.rescale(lowerCamelCase , lowerCamelCase ) for image in images] if do_normalize: __a = [self.normalize(lowerCamelCase , lowerCamelCase , lowerCamelCase ) for image in images] __a = [to_channel_dimension_format(lowerCamelCase , lowerCamelCase ) for image in images] __a = {"pixel_values": images} return BatchFeature(data=lowerCamelCase , tensor_type=lowerCamelCase )
67
0
"""simple docstring""" class snake_case__ : def __init__( self , lowerCamelCase ): __a = size __a = [0] * size __a = [0] * size @staticmethod def a__ ( lowerCamelCase ): return index | (index + 1) @staticmethod def a__ ( lowerCamelCase ): return (index & (index + 1)) - 1 def a__ ( self , lowerCamelCase , lowerCamelCase ): __a = value while index < self.size: __a = self.get_prev(__UpperCamelCase ) + 1 if current_left_border == index: __a = value else: __a = max(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase ) __a = self.get_next(__UpperCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase ): right -= 1 # Because of right is exclusive __a = 0 while left <= right: __a = self.get_prev(__UpperCamelCase ) if left <= current_left: __a = max(__UpperCamelCase , self.tree[right] ) __a = current_left else: __a = max(__UpperCamelCase , self.arr[right] ) right -= 1 return result if __name__ == "__main__": import doctest doctest.testmod()
714
"""simple docstring""" import inspect import unittest from transformers import ViTConfig 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 ViTForImageClassification, ViTForMaskedImageModeling, ViTModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class snake_case__ : 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=None , lowerCamelCase=2 , ): __a = parent __a = batch_size __a = image_size __a = patch_size __a = num_channels __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 = encoder_stride # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) __a = (image_size // patch_size) ** 2 __a = num_patches + 1 def a__ ( self ): __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = self.get_config() return config, pixel_values, labels def a__ ( self ): return ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=lowerCamelCase , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = ViTModel(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = ViTForMaskedImageModeling(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __a = 1 __a = ViTForMaskedImageModeling(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __a = model(lowerCamelCase ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = self.type_sequence_label_size __a = ViTForImageClassification(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __a = 1 __a = ViTForImageClassification(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __a = model(lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a__ ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class snake_case__ ( snake_case_, snake_case_, unittest.TestCase ): _snake_case : Any = ( ( ViTModel, ViTForImageClassification, ViTForMaskedImageModeling, ) if is_torch_available() else () ) _snake_case : List[Any] = ( {"""feature-extraction""": ViTModel, """image-classification""": ViTForImageClassification} if is_torch_available() else {} ) _snake_case : int = True _snake_case : int = False _snake_case : str = False _snake_case : Optional[Any] = False def a__ ( self ): __a = ViTModelTester(self ) __a = ConfigTester(self , config_class=lowerCamelCase , has_text_modality=lowerCamelCase , hidden_size=37 ) def a__ ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="ViT does not use inputs_embeds" ) def a__ ( self ): pass def a__ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __a = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCamelCase , nn.Linear ) ) def a__ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(lowerCamelCase ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase ) @slow def a__ ( self ): for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = ViTModel.from_pretrained(lowerCamelCase ) self.assertIsNotNone(lowerCamelCase ) def _lowerCamelCase( ): __a = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class snake_case__ ( unittest.TestCase ): @cached_property def a__ ( self ): return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224" ) if is_vision_available() else None @slow def a__ ( self ): __a = ViTForImageClassification.from_pretrained("google/vit-base-patch16-224" ).to(lowerCamelCase ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase ) # forward pass with torch.no_grad(): __a = model(**lowerCamelCase ) # verify the logits __a = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , lowerCamelCase ) __a = torch.tensor([-0.2744, 0.8215, -0.0836] ).to(lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCamelCase , atol=1E-4 ) ) @slow def a__ ( self ): # ViT models have an `interpolate_pos_encoding` argument in their forward method, # allowing to interpolate the pre-trained position embeddings in order to use # the model on higher resolutions. The DINO model by Facebook AI leverages this # to visualize self-attention on higher resolution images. __a = ViTModel.from_pretrained("facebook/dino-vits8" ).to(lowerCamelCase ) __a = ViTImageProcessor.from_pretrained("facebook/dino-vits8" , size=480 ) __a = prepare_img() __a = image_processor(images=lowerCamelCase , return_tensors="pt" ) __a = inputs.pixel_values.to(lowerCamelCase ) # forward pass with torch.no_grad(): __a = model(lowerCamelCase , interpolate_pos_encoding=lowerCamelCase ) # verify the logits __a = torch.Size((1, 3601, 384) ) self.assertEqual(outputs.last_hidden_state.shape , lowerCamelCase ) __a = torch.tensor( [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]] ).to(lowerCamelCase ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , lowerCamelCase , atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def a__ ( self ): __a = ViTModel.from_pretrained("facebook/dino-vits8" , torch_dtype=torch.floataa , device_map="auto" ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=lowerCamelCase , return_tensors="pt" ) __a = inputs.pixel_values.to(lowerCamelCase ) # forward pass to make sure inference works in fp16 with torch.no_grad(): __a = model(lowerCamelCase )
67
0
"""simple docstring""" from functools import lru_cache def _lowerCamelCase( a ): __a = 2 __a = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(_UpperCamelCase ) if n > 1: factors.add(_UpperCamelCase ) return factors @lru_cache def _lowerCamelCase( a ): return len(unique_prime_factors(_UpperCamelCase ) ) def _lowerCamelCase( a ): return len(set(_UpperCamelCase ) ) in (0, 1) def _lowerCamelCase( a ): __a = 2 while True: # Increment each value of a generated range __a = [base + i for i in range(_UpperCamelCase )] # Run elements through out unique_prime_factors function # Append our target number to the end. __a = [upf_len(_UpperCamelCase ) for x in group] checker.append(_UpperCamelCase ) # If all numbers in the list are equal, return the group variable. if equality(_UpperCamelCase ): return group # Increment our base variable by 1 base += 1 def _lowerCamelCase( a = 4 ): __a = run(_UpperCamelCase ) return results[0] if len(_UpperCamelCase ) else None if __name__ == "__main__": print(solution())
715
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetaImageProcessor class snake_case__ ( unittest.TestCase ): def __init__( self , lowerCamelCase , lowerCamelCase=7 , lowerCamelCase=3 , lowerCamelCase=30 , lowerCamelCase=400 , lowerCamelCase=True , lowerCamelCase=None , lowerCamelCase=True , lowerCamelCase=[0.5, 0.5, 0.5] , lowerCamelCase=[0.5, 0.5, 0.5] , lowerCamelCase=True , lowerCamelCase=1 / 255 , lowerCamelCase=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __a = size if size is not None else {"shortest_edge": 18, "longest_edge": 1333} __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 a__ ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def a__ ( self , lowerCamelCase , lowerCamelCase=False ): if not batched: __a = image_inputs[0] if isinstance(lowerCamelCase , Image.Image ): __a , __a = image.size else: __a , __a = image.shape[1], image.shape[2] if w < h: __a = int(self.size["shortest_edge"] * h / w ) __a = self.size["shortest_edge"] elif w > h: __a = self.size["shortest_edge"] __a = int(self.size["shortest_edge"] * w / h ) else: __a = self.size["shortest_edge"] __a = self.size["shortest_edge"] else: __a = [] for image in image_inputs: __a , __a = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __a = max(lowerCamelCase , key=lambda lowerCamelCase : item[0] )[0] __a = max(lowerCamelCase , key=lambda lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case__ ( snake_case_, unittest.TestCase ): _snake_case : List[Any] = DetaImageProcessor if is_vision_available() else None def a__ ( self ): __a = DetaImageProcessingTester(self ) @property def a__ ( self ): return self.image_processor_tester.prepare_image_processor_dict() def a__ ( self ): __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_rescale" ) ) self.assertTrue(hasattr(lowerCamelCase , "do_pad" ) ) self.assertTrue(hasattr(lowerCamelCase , "size" ) ) def a__ ( self ): __a = 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 , lowerCamelCase ) def a__ ( self ): pass def a__ ( self ): # 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 __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) __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, expected_height, expected_width, ) , ) def a__ ( self ): # 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 __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def a__ ( self ): # 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 __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def a__ ( self ): # prepare image and target __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": 39769, "annotations": target} # encode them __a = DetaImageProcessor() __a = image_processing(images=lowerCamelCase , annotations=lowerCamelCase , return_tensors="pt" ) # verify pixel values __a = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase ) __a = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase , atol=1E-4 ) ) # verify area __a = 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"] , lowerCamelCase ) ) # verify boxes __a = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase ) __a = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase , atol=1E-3 ) ) # verify image_id __a = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase ) ) # verify is_crowd __a = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase ) ) # verify class_labels __a = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase ) ) # verify orig_size __a = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase ) ) # verify size __a = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase ) ) @slow def a__ ( self ): # prepare image, target and masks_path __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": 39769, "segments_info": target} __a = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them __a = DetaImageProcessor(format="coco_panoptic" ) __a = image_processing(images=lowerCamelCase , annotations=lowerCamelCase , masks_path=lowerCamelCase , return_tensors="pt" ) # verify pixel values __a = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase ) __a = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase , atol=1E-4 ) ) # verify area __a = 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"] , lowerCamelCase ) ) # verify boxes __a = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase ) __a = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase , atol=1E-3 ) ) # verify image_id __a = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase ) ) # verify is_crowd __a = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase ) ) # verify class_labels __a = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase ) ) # verify masks __a = 822873 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , lowerCamelCase ) # verify orig_size __a = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase ) ) # verify size __a = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase ) )
67
0
"""simple docstring""" from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class UpperCamelCase ( __UpperCAmelCase ): _snake_case : Optional[int] = """""" _snake_case : str = """hf-legacy""" # "hf://"" is reserved for hffs def __init__( self , lowerCamelCase = None , lowerCamelCase = None , **lowerCamelCase , ): super().__init__(self , **lowerCamelCase ) __a = repo_info __a = token __a = None def a__ ( self ): if self.dir_cache is None: __a = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes __a = { "name": hf_file.rfilename, "size": None, "type": "file", } self.dir_cache.update( { str(lowerCamelCase ): {"name": str(lowerCamelCase ), "size": None, "type": "directory"} for d in list(PurePosixPath(hf_file.rfilename ).parents )[:-1] } ) def a__ ( self , lowerCamelCase , lowerCamelCase = "rb" , **lowerCamelCase , ): if not isinstance(self.repo_info , lowerCamelCase ): raise NotImplementedError(F"Open is only implemented for dataset repositories, but got {self.repo_info}" ) __a = hf_hub_url(self.repo_info.id , lowerCamelCase , revision=self.repo_info.sha ) return fsspec.open( lowerCamelCase , mode=lowerCamelCase , headers=get_authentication_headers_for_url(lowerCamelCase , use_auth_token=self.token ) , client_kwargs={"trust_env": True} , ).open() def a__ ( self , lowerCamelCase , **lowerCamelCase ): self._get_dirs() __a = self._strip_protocol(lowerCamelCase ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase=False , **lowerCamelCase ): self._get_dirs() __a = PurePosixPath(path.strip("/" ) ) __a = {} for p, f in self.dir_cache.items(): __a = PurePosixPath(p.strip("/" ) ) __a = p.parent if root == path: __a = f __a = list(paths.values() ) if detail: return out else: return sorted(f["name"] for f in out )
716
"""simple docstring""" import argparse import logging import sys from unittest.mock import patch import run_glue_deebert from transformers.testing_utils import TestCasePlus, get_gpu_count, require_torch_non_multi_gpu, slow logging.basicConfig(level=logging.DEBUG) SCREAMING_SNAKE_CASE__:Dict = logging.getLogger() def _lowerCamelCase( ): __a = argparse.ArgumentParser() parser.add_argument("-f" ) __a = parser.parse_args() return args.f class snake_case__ ( snake_case_ ): def a__ ( self ): __a = logging.StreamHandler(sys.stdout ) logger.addHandler(lowerCamelCase ) def a__ ( self , lowerCamelCase ): __a = get_gpu_count() if n_gpu > 1: pass # XXX: doesn't quite work with n_gpu > 1 https://github.com/huggingface/transformers/issues/10560 # script = f"{self.examples_dir_str}/research_projects/deebert/run_glue_deebert.py" # distributed_args = f"-m torch.distributed.launch --nproc_per_node={n_gpu} {script}".split() # cmd = [sys.executable] + distributed_args + args # execute_subprocess_async(cmd, env=self.get_env()) # XXX: test the results - need to save them first into .json file else: args.insert(0 , "run_glue_deebert.py" ) with patch.object(lowerCamelCase , "argv" , lowerCamelCase ): __a = run_glue_deebert.main() for value in result.values(): self.assertGreaterEqual(lowerCamelCase , 0.666 ) @slow @require_torch_non_multi_gpu def a__ ( self ): __a = "\n --model_type roberta\n --model_name_or_path roberta-base\n --task_name MRPC\n --do_train\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --max_seq_length 128\n --per_gpu_eval_batch_size=1\n --per_gpu_train_batch_size=8\n --learning_rate 2e-4\n --num_train_epochs 3\n --overwrite_output_dir\n --seed 42\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --save_steps 0\n --overwrite_cache\n --eval_after_first_stage\n ".split() self.run_and_check(lowerCamelCase ) __a = "\n --model_type roberta\n --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --task_name MRPC\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --max_seq_length 128\n --eval_each_highway\n --eval_highway\n --overwrite_cache\n --per_gpu_eval_batch_size=1\n ".split() self.run_and_check(lowerCamelCase ) __a = "\n --model_type roberta\n --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --task_name MRPC\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --max_seq_length 128\n --early_exit_entropy 0.1\n --eval_highway\n --overwrite_cache\n --per_gpu_eval_batch_size=1\n ".split() self.run_and_check(lowerCamelCase )
67
0
import inspect from typing import List, Optional, Tuple, Union import torch from ...models import UNetaDModel, VQModel from ...schedulers import DDIMScheduler from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class snake_case__ ( __lowerCAmelCase ): def __init__( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): super().__init__() self.register_modules(vqvae=lowerCamelCase__ , unet=lowerCamelCase__ , scheduler=lowerCamelCase__ ) @torch.no_grad() def __call__( self , lowerCamelCase = 1 , lowerCamelCase = None , lowerCamelCase = 0.0 , lowerCamelCase = 50 , lowerCamelCase = "pil" , lowerCamelCase = True , **lowerCamelCase , ): __a = randn_tensor( (batch_size, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , generator=lowerCamelCase__ , ) __a = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler __a = latents * self.scheduler.init_noise_sigma self.scheduler.set_timesteps(lowerCamelCase__ ) # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature __a = '''eta''' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __a = {} if accepts_eta: __a = eta for t in self.progress_bar(self.scheduler.timesteps ): __a = self.scheduler.scale_model_input(lowerCamelCase__ , lowerCamelCase__ ) # predict the noise residual __a = self.unet(lowerCamelCase__ , lowerCamelCase__ ).sample # compute the previous noisy sample x_t -> x_t-1 __a = self.scheduler.step(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , **lowerCamelCase__ ).prev_sample # decode the image latents with the VAE __a = self.vqvae.decode(lowerCamelCase__ ).sample __a = (image / 2 + 0.5).clamp(0 , 1 ) __a = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": __a = self.numpy_to_pil(lowerCamelCase__ ) if not return_dict: return (image,) return ImagePipelineOutput(images=lowerCamelCase__ )
717
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, 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 SCREAMING_SNAKE_CASE__:Union[str, Any] = logging.get_logger(__name__) if is_vision_available(): import PIL class snake_case__ ( snake_case_ ): _snake_case : Optional[Any] = ["""pixel_values"""] def __init__( self , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = PILImageResampling.BICUBIC , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = True , lowerCamelCase = 1 / 255 , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = True , **lowerCamelCase , ): super().__init__(**lowerCamelCase ) __a = size if size is not None else {"shortest_edge": 224} __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) __a = crop_size if crop_size is not None else {"height": 224, "width": 224} __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase , param_name="crop_size" ) __a = do_resize __a = size __a = resample __a = do_center_crop __a = crop_size __a = do_rescale __a = rescale_factor __a = do_normalize __a = image_mean if image_mean is not None else OPENAI_CLIP_MEAN __a = image_std if image_std is not None else OPENAI_CLIP_STD __a = do_convert_rgb def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = PILImageResampling.BICUBIC , lowerCamelCase = None , **lowerCamelCase , ): __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) if "shortest_edge" not in size: raise ValueError(F"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}" ) __a = get_resize_output_image_size(lowerCamelCase , size=size["shortest_edge"] , default_to_square=lowerCamelCase ) return resize(lowerCamelCase , size=lowerCamelCase , resample=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): __a = get_size_dict(lowerCamelCase ) 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(lowerCamelCase , size=(size["height"], size["width"]) , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): return rescale(lowerCamelCase , scale=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): return normalize(lowerCamelCase , mean=lowerCamelCase , std=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = ChannelDimension.FIRST , **lowerCamelCase , ): __a = do_resize if do_resize is not None else self.do_resize __a = size if size is not None else self.size __a = get_size_dict(lowerCamelCase , param_name="size" , default_to_square=lowerCamelCase ) __a = resample if resample is not None else self.resample __a = do_center_crop if do_center_crop is not None else self.do_center_crop __a = crop_size if crop_size is not None else self.crop_size __a = get_size_dict(lowerCamelCase , param_name="crop_size" , default_to_square=lowerCamelCase ) __a = do_rescale if do_rescale is not None else self.do_rescale __a = rescale_factor if rescale_factor is not None else self.rescale_factor __a = do_normalize if do_normalize is not None else self.do_normalize __a = image_mean if image_mean is not None else self.image_mean __a = image_std if image_std is not None else self.image_std __a = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __a = make_list_of_images(lowerCamelCase ) if not valid_images(lowerCamelCase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) 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: __a = [convert_to_rgb(lowerCamelCase ) for image in images] # All transformations expect numpy arrays. __a = [to_numpy_array(lowerCamelCase ) for image in images] if do_resize: __a = [self.resize(image=lowerCamelCase , size=lowerCamelCase , resample=lowerCamelCase ) for image in images] if do_center_crop: __a = [self.center_crop(image=lowerCamelCase , size=lowerCamelCase ) for image in images] if do_rescale: __a = [self.rescale(image=lowerCamelCase , scale=lowerCamelCase ) for image in images] if do_normalize: __a = [self.normalize(image=lowerCamelCase , mean=lowerCamelCase , std=lowerCamelCase ) for image in images] __a = [to_channel_dimension_format(lowerCamelCase , lowerCamelCase ) for image in images] __a = {"pixel_values": images} return BatchFeature(data=lowerCamelCase , tensor_type=lowerCamelCase )
67
0
from unittest.mock import patch import pyspark from datasets.packaged_modules.spark.spark import ( Spark, SparkExamplesIterable, _generate_iterable_examples, ) from ..utils import ( require_dill_gt_0_3_2, require_not_windows, ) def _lowerCamelCase( a , a ): __a = [] for part_id in partition_order: __a = df.where(F"SPARK_PARTITION_ID() = {part_id}" ).collect() for row_idx, row in enumerate(snake_case_ ): expected_row_ids_and_row_dicts.append((F"{part_id}_{row_idx}", row.asDict()) ) return expected_row_ids_and_row_dicts @require_not_windows @require_dill_gt_0_3_2 def _lowerCamelCase( ): __a = pyspark.sql.SparkSession.builder.master("local[*]" ).appName("pyspark" ).getOrCreate() __a = spark.range(1_0_0 ).repartition(1 ) __a = Spark(snake_case_ ) # The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means # that each partition can hold 2 rows. spark_builder._repartition_df_if_needed(max_shard_size=1_6 ) # Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions. assert spark_builder.df.rdd.getNumPartitions() == 5_0 @require_not_windows @require_dill_gt_0_3_2 def _lowerCamelCase( ): __a = pyspark.sql.SparkSession.builder.master("local[*]" ).appName("pyspark" ).getOrCreate() __a = spark.range(1_0 ).repartition(2 ) __a = [1, 0] __a = _generate_iterable_examples(snake_case_ , snake_case_ ) # Reverse the partitions. __a = _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case_ , snake_case_ ) for i, (row_id, row_dict) in enumerate(generate_fn() ): __a = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def _lowerCamelCase( ): __a = pyspark.sql.SparkSession.builder.master("local[*]" ).appName("pyspark" ).getOrCreate() __a = spark.range(1_0 ).repartition(1 ) __a = SparkExamplesIterable(snake_case_ ) assert it.n_shards == 1 for i, (row_id, row_dict) in enumerate(snake_case_ ): assert row_id == F"0_{i}" assert row_dict == {"id": i} @require_not_windows @require_dill_gt_0_3_2 def _lowerCamelCase( ): __a = pyspark.sql.SparkSession.builder.master("local[*]" ).appName("pyspark" ).getOrCreate() __a = spark.range(3_0 ).repartition(3 ) # Mock the generator so that shuffle reverses the partition indices. with patch("numpy.random.Generator" ) as generator_mock: __a = lambda a : x.reverse() __a = _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case_ , [2, 1, 0] ) __a = SparkExamplesIterable(snake_case_ ).shuffle_data_sources(snake_case_ ) assert shuffled_it.n_shards == 3 for i, (row_id, row_dict) in enumerate(snake_case_ ): __a = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def _lowerCamelCase( ): __a = pyspark.sql.SparkSession.builder.master("local[*]" ).appName("pyspark" ).getOrCreate() __a = spark.range(2_0 ).repartition(4 ) # Partitions 0 and 2 __a = SparkExamplesIterable(snake_case_ ).shard_data_sources(worker_id=0 , num_workers=2 ) assert shard_it_a.n_shards == 2 __a = _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case_ , [0, 2] ) for i, (row_id, row_dict) in enumerate(snake_case_ ): __a = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict # Partitions 1 and 3 __a = SparkExamplesIterable(snake_case_ ).shard_data_sources(worker_id=1 , num_workers=2 ) assert shard_it_a.n_shards == 2 __a = _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case_ , [1, 3] ) for i, (row_id, row_dict) in enumerate(snake_case_ ): __a = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def _lowerCamelCase( ): __a = pyspark.sql.SparkSession.builder.master("local[*]" ).appName("pyspark" ).getOrCreate() __a = spark.range(1_0_0 ).repartition(1 ) __a = Spark(snake_case_ ) # Choose a small max_shard_size for maximum partitioning. spark_builder._repartition_df_if_needed(max_shard_size=1 ) # The new number of partitions should not be greater than the number of rows. assert spark_builder.df.rdd.getNumPartitions() == 1_0_0
718
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation SCREAMING_SNAKE_CASE__:List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Any = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} SCREAMING_SNAKE_CASE__:Optional[Any] = { """vocab_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/vocab.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/vocab.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/vocab.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/vocab.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/vocab.json""", }, """merges_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/merges.txt""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/merges.txt""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/merges.txt""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/merges.txt""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/merges.txt""", }, """tokenizer_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/tokenizer.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/tokenizer.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/tokenizer.json""", }, } SCREAMING_SNAKE_CASE__:Union[str, Any] = { """gpt2""": 1024, """gpt2-medium""": 1024, """gpt2-large""": 1024, """gpt2-xl""": 1024, """distilgpt2""": 1024, } class snake_case__ ( snake_case_ ): _snake_case : Tuple = VOCAB_FILES_NAMES _snake_case : str = PRETRAINED_VOCAB_FILES_MAP _snake_case : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _snake_case : List[str] = ["""input_ids""", """attention_mask"""] _snake_case : Dict = GPTaTokenizer def __init__( self , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase="<|endoftext|>" , lowerCamelCase="<|endoftext|>" , lowerCamelCase="<|endoftext|>" , lowerCamelCase=False , **lowerCamelCase , ): super().__init__( lowerCamelCase , lowerCamelCase , tokenizer_file=lowerCamelCase , unk_token=lowerCamelCase , bos_token=lowerCamelCase , eos_token=lowerCamelCase , add_prefix_space=lowerCamelCase , **lowerCamelCase , ) __a = kwargs.pop("add_bos_token" , lowerCamelCase ) __a = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , lowerCamelCase ) != add_prefix_space: __a = getattr(lowerCamelCase , pre_tok_state.pop("type" ) ) __a = add_prefix_space __a = pre_tok_class(**lowerCamelCase ) __a = add_prefix_space def a__ ( self , *lowerCamelCase , **lowerCamelCase ): __a = kwargs.get("is_split_into_words" , lowerCamelCase ) assert self.add_prefix_space or not is_split_into_words, ( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*lowerCamelCase , **lowerCamelCase ) def a__ ( self , *lowerCamelCase , **lowerCamelCase ): __a = kwargs.get("is_split_into_words" , lowerCamelCase ) assert self.add_prefix_space or not is_split_into_words, ( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._encode_plus(*lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase = None ): __a = self._tokenizer.model.save(lowerCamelCase , name=lowerCamelCase ) return tuple(lowerCamelCase ) def a__ ( self , lowerCamelCase ): __a = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowerCamelCase , add_special_tokens=lowerCamelCase ) + [self.eos_token_id] ) if len(lowerCamelCase ) > self.model_max_length: __a = input_ids[-self.model_max_length :] return input_ids
67
0
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__ ( lowercase_, unittest.TestCase ): _snake_case : Optional[int] = MvpTokenizer _snake_case : Optional[int] = MvpTokenizerFast _snake_case : Optional[int] = True _snake_case : Tuple = filter_roberta_detectors def a__ ( self ): super().setUp() __a = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", ] __a = dict(zip(lowerCamelCase , range(len(lowerCamelCase ) ) ) ) __a = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] __a = {"unk_token": "<unk>"} __a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) __a = 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(lowerCamelCase ) + "\n" ) with open(self.merges_file , "w" , encoding="utf-8" ) as fp: fp.write("\n".join(lowerCamelCase ) ) def a__ ( self , **lowerCamelCase ): kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **lowerCamelCase ) def a__ ( self , **lowerCamelCase ): kwargs.update(self.special_tokens_map ) return self.rust_tokenizer_class.from_pretrained(self.tmpdirname , **lowerCamelCase ) def a__ ( self , lowerCamelCase ): return "lower newer", "lower newer" @cached_property def a__ ( self ): return MvpTokenizer.from_pretrained("RUCAIBox/mvp" ) @cached_property def a__ ( self ): return MvpTokenizerFast.from_pretrained("RUCAIBox/mvp" ) @require_torch def a__ ( self ): __a = ["A long paragraph for summarization.", "Another paragraph for summarization."] __a = [0, 250, 251, 17818, 13, 39186, 1938, 4, 2] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a = tokenizer(lowerCamelCase , max_length=len(lowerCamelCase ) , padding=lowerCamelCase , return_tensors="pt" ) self.assertIsInstance(lowerCamelCase , lowerCamelCase ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) __a = batch.input_ids.tolist()[0] self.assertListEqual(lowerCamelCase , lowerCamelCase ) # Test that special tokens are reset @require_torch def a__ ( self ): __a = ["A long paragraph for summarization.", "Another paragraph for summarization."] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a = tokenizer(lowerCamelCase , padding=lowerCamelCase , return_tensors="pt" ) # check if input_ids are returned and no labels self.assertIn("input_ids" , lowerCamelCase ) self.assertIn("attention_mask" , lowerCamelCase ) self.assertNotIn("labels" , lowerCamelCase ) self.assertNotIn("decoder_attention_mask" , lowerCamelCase ) @require_torch def a__ ( self ): __a = [ "Summary of the text.", "Another summary.", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a = tokenizer(text_target=lowerCamelCase , max_length=32 , padding="max_length" , return_tensors="pt" ) self.assertEqual(32 , targets["input_ids"].shape[1] ) @require_torch def a__ ( self ): for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a = tokenizer( ["I am a small frog" * 1024, "I am a small frog"] , padding=lowerCamelCase , truncation=lowerCamelCase , return_tensors="pt" ) self.assertIsInstance(lowerCamelCase , lowerCamelCase ) self.assertEqual(batch.input_ids.shape , (2, 1024) ) @require_torch def a__ ( self ): __a = ["A long paragraph for summarization."] __a = [ "Summary of the text.", ] for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]: __a = tokenizer(lowerCamelCase , text_target=lowerCamelCase , return_tensors="pt" ) __a = inputs["input_ids"] __a = 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 a__ ( self ): pass def a__ ( self ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})" ): __a = self.rust_tokenizer_class.from_pretrained(lowerCamelCase , **lowerCamelCase ) __a = self.tokenizer_class.from_pretrained(lowerCamelCase , **lowerCamelCase ) __a = "A, <mask> AllenNLP sentence." __a = tokenizer_r.encode_plus(lowerCamelCase , add_special_tokens=lowerCamelCase , return_token_type_ids=lowerCamelCase ) __a = tokenizer_p.encode_plus(lowerCamelCase , add_special_tokens=lowerCamelCase , return_token_type_ids=lowerCamelCase ) # 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 = tokenizer_r.convert_ids_to_tokens(tokens_r["input_ids"] ) __a = 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( lowerCamelCase , ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] ) self.assertSequenceEqual( lowerCamelCase , ["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"] )
719
"""simple docstring""" from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize("repo_id" , ["canonical_dataset_name", "org-name/dataset-name"] ) @pytest.mark.parametrize("path" , ["filename.csv", "filename with blanks.csv"] ) @pytest.mark.parametrize("revision" , [None, "v2"] ) def _lowerCamelCase( a , a , a ): __a = hf_hub_url(repo_id=a , path=a , revision=a ) assert url == F"https://huggingface.co/datasets/{repo_id}/resolve/{revision or 'main'}/{quote(a )}"
67
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 snake_case__ ( unittest.TestCase ): def __init__( self , lowerCamelCase , lowerCamelCase=7 , lowerCamelCase=3 , lowerCamelCase=30 , lowerCamelCase=400 , lowerCamelCase=True , lowerCamelCase=None , lowerCamelCase=True , lowerCamelCase=[0.5, 0.5, 0.5] , lowerCamelCase=[0.5, 0.5, 0.5] , lowerCamelCase=True , lowerCamelCase=1 / 255 , lowerCamelCase=True , ): __a = size if size is not None else {"shortest_edge": 18, "longest_edge": 1333} __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 a__ ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def a__ ( self , lowerCamelCase , lowerCamelCase=False ): if not batched: __a = image_inputs[0] if isinstance(lowerCamelCase , Image.Image ): __a , __a = image.size else: __a , __a = image.shape[1], image.shape[2] if w < h: __a = int(self.size["shortest_edge"] * h / w ) __a = self.size["shortest_edge"] elif w > h: __a = self.size["shortest_edge"] __a = int(self.size["shortest_edge"] * w / h ) else: __a = self.size["shortest_edge"] __a = self.size["shortest_edge"] else: __a = [] for image in image_inputs: __a , __a = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __a = max(lowerCamelCase , key=lambda lowerCamelCase : item[0] )[0] __a = max(lowerCamelCase , key=lambda lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case__ ( snake_case_, unittest.TestCase ): _snake_case : List[Any] = DeformableDetrImageProcessor if is_vision_available() else None def a__ ( self ): __a = DeformableDetrImageProcessingTester(self ) @property def a__ ( self ): return self.image_processor_tester.prepare_image_processor_dict() def a__ ( self ): __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_rescale" ) ) self.assertTrue(hasattr(lowerCamelCase , "do_pad" ) ) self.assertTrue(hasattr(lowerCamelCase , "size" ) ) def a__ ( self ): __a = 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 , lowerCamelCase ) __a = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=lowerCamelCase ) self.assertEqual(image_processor.size , {"shortest_edge": 42, "longest_edge": 84} ) self.assertEqual(image_processor.do_pad , lowerCamelCase ) def a__ ( self ): pass def a__ ( self ): __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 __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) __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, expected_height, expected_width, ) , ) def a__ ( self ): __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 __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def a__ ( self ): __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 __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def a__ ( self ): __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": 39769, "annotations": target} # encode them __a = DeformableDetrImageProcessor() __a = image_processing(images=lowerCamelCase , annotations=lowerCamelCase , return_tensors="pt" ) # verify pixel values __a = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase ) __a = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase , atol=1E-4 ) ) # verify area __a = 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"] , lowerCamelCase ) ) # verify boxes __a = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase ) __a = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase , atol=1E-3 ) ) # verify image_id __a = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase ) ) # verify is_crowd __a = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase ) ) # verify class_labels __a = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase ) ) # verify orig_size __a = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase ) ) # verify size __a = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase ) ) @slow def a__ ( self ): __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": 39769, "segments_info": target} __a = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them __a = DeformableDetrImageProcessor(format="coco_panoptic" ) __a = image_processing(images=lowerCamelCase , annotations=lowerCamelCase , masks_path=lowerCamelCase , return_tensors="pt" ) # verify pixel values __a = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase ) __a = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase , atol=1E-4 ) ) # verify area __a = 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"] , lowerCamelCase ) ) # verify boxes __a = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase ) __a = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase , atol=1E-3 ) ) # verify image_id __a = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase ) ) # verify is_crowd __a = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase ) ) # verify class_labels __a = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase ) ) # verify masks __a = 822873 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , lowerCamelCase ) # verify orig_size __a = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase ) ) # verify size __a = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase ) )
720
"""simple docstring""" from __future__ import annotations def _lowerCamelCase( a , a , a ): if len(a ) == 0: raise ValueError("find_max() arg is an empty sequence" ) if ( left >= len(a ) or left < -len(a ) or right >= len(a ) or right < -len(a ) ): raise IndexError("list index out of range" ) if left == right: return nums[left] __a = (left + right) >> 1 # the middle __a = find_max(a , a , a ) # find max in range[left, mid] __a = find_max(a , mid + 1 , a ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
67
0
"""simple docstring""" import argparse import os from pathlib import Path import torch from bark.generation import _load_model as _bark_load_model from huggingface_hub import hf_hub_download from transformers import EncodecConfig, EncodecModel, set_seed from transformers.models.bark.configuration_bark import ( BarkCoarseConfig, BarkConfig, BarkFineConfig, BarkSemanticConfig, ) from transformers.models.bark.generation_configuration_bark import ( BarkCoarseGenerationConfig, BarkFineGenerationConfig, BarkGenerationConfig, BarkSemanticGenerationConfig, ) from transformers.models.bark.modeling_bark import BarkCoarseModel, BarkFineModel, BarkModel, BarkSemanticModel from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__:Dict = logging.get_logger(__name__) set_seed(770) SCREAMING_SNAKE_CASE__:List[Any] = { """c_attn""": """att_proj""", """c_proj""": """out_proj""", """c_fc""": """in_proj""", """transformer.""": """""", """h.""": """layers.""", """ln_1""": """layernorm_1""", """ln_2""": """layernorm_2""", """ln_f""": """layernorm_final""", """wpe""": """position_embeds_layer""", """wte""": """input_embeds_layer""", } SCREAMING_SNAKE_CASE__:Optional[Any] = { """text_small""": { """repo_id""": """suno/bark""", """file_name""": """text.pt""", }, """coarse_small""": { """repo_id""": """suno/bark""", """file_name""": """coarse.pt""", }, """fine_small""": { """repo_id""": """suno/bark""", """file_name""": """fine.pt""", }, """text""": { """repo_id""": """suno/bark""", """file_name""": """text_2.pt""", }, """coarse""": { """repo_id""": """suno/bark""", """file_name""": """coarse_2.pt""", }, """fine""": { """repo_id""": """suno/bark""", """file_name""": """fine_2.pt""", }, } SCREAMING_SNAKE_CASE__:Union[str, Any] = os.path.dirname(os.path.abspath(__file__)) SCREAMING_SNAKE_CASE__:Union[str, Any] = os.path.join(os.path.expanduser("""~"""), """.cache""") SCREAMING_SNAKE_CASE__:Any = os.path.join(os.getenv("""XDG_CACHE_HOME""", default_cache_dir), """suno""", """bark_v0""") def _lowerCamelCase( a , a=False ): __a = model_type if use_small: key += "_small" return os.path.join(a , REMOTE_MODEL_PATHS[key]["file_name"] ) def _lowerCamelCase( a , a ): os.makedirs(a , exist_ok=a ) hf_hub_download(repo_id=a , filename=a , local_dir=a ) def _lowerCamelCase( a , a , a=False , a="text" ): if model_type == "text": __a = BarkSemanticModel __a = BarkSemanticConfig __a = BarkSemanticGenerationConfig elif model_type == "coarse": __a = BarkCoarseModel __a = BarkCoarseConfig __a = BarkCoarseGenerationConfig elif model_type == "fine": __a = BarkFineModel __a = BarkFineConfig __a = BarkFineGenerationConfig else: raise NotImplementedError() __a = F"{model_type}_small" if use_small else model_type __a = REMOTE_MODEL_PATHS[model_key] if not os.path.exists(a ): logger.info(F"{model_type} model not found, downloading into `{CACHE_DIR}`." ) _download(model_info["repo_id"] , model_info["file_name"] ) __a = torch.load(a , map_location=a ) # this is a hack __a = checkpoint["model_args"] if "input_vocab_size" not in model_args: __a = model_args["vocab_size"] __a = model_args["vocab_size"] del model_args["vocab_size"] # convert Bark model arguments to HF Bark model arguments __a = model_args.pop("n_head" ) __a = model_args.pop("n_embd" ) __a = model_args.pop("n_layer" ) __a = ConfigClass(**checkpoint["model_args"] ) __a = ModelClass(config=a ) __a = GenerationConfigClass() __a = model_generation_config __a = checkpoint["model"] # fixup checkpoint __a = "_orig_mod." for k, v in list(state_dict.items() ): if k.startswith(a ): # replace part of the key with corresponding layer name in HF implementation __a = k[len(a ) :] for old_layer_name in new_layer_name_dict: __a = new_k.replace(a , new_layer_name_dict[old_layer_name] ) __a = state_dict.pop(a ) __a = set(state_dict.keys() ) - set(model.state_dict().keys() ) __a = {k for k in extra_keys if not k.endswith(".attn.bias" )} __a = set(model.state_dict().keys() ) - set(state_dict.keys() ) __a = {k for k in missing_keys if not k.endswith(".attn.bias" )} if len(a ) != 0: raise ValueError(F"extra keys found: {extra_keys}" ) if len(a ) != 0: raise ValueError(F"missing keys: {missing_keys}" ) model.load_state_dict(a , strict=a ) __a = model.num_parameters(exclude_embeddings=a ) __a = checkpoint["best_val_loss"].item() logger.info(F"model loaded: {round(n_params/1E6 , 1 )}M params, {round(a , 3 )} loss" ) model.eval() model.to(a ) del checkpoint, state_dict return model def _lowerCamelCase( a , a=False , a="text" ): if model_type not in ("text", "coarse", "fine"): raise NotImplementedError() __a = "cpu" # do conversion on cpu __a = _get_ckpt_path(a , use_small=a ) __a = _load_model(a , a , model_type=a , use_small=a ) # load bark initial model __a = _bark_load_model(a , "cpu" , model_type=a , use_small=a ) if model_type == "text": __a = bark_model["model"] if model.num_parameters(exclude_embeddings=a ) != bark_model.get_num_params(): raise ValueError("initial and new models don\'t have the same number of parameters" ) # check if same output as the bark model __a = 5 __a = 1_0 if model_type in ["text", "coarse"]: __a = torch.randint(2_5_6 , (batch_size, sequence_length) , dtype=torch.int ) __a = bark_model(a )[0] __a = model(a ) # take last logits __a = output_new_model_total.logits[:, [-1], :] else: __a = 3 __a = 8 __a = torch.randint(2_5_6 , (batch_size, sequence_length, n_codes_total) , dtype=torch.int ) __a = model(a , a ) __a = bark_model(a , a ) __a = output_new_model_total.logits # output difference should come from the difference of self-attention implementation design if output_new_model.shape != output_old_model.shape: raise ValueError("initial and new outputs don\'t have the same shape" ) if (output_new_model - output_old_model).abs().max().item() > 1E-3: raise ValueError("initial and new outputs are not equal" ) Path(a ).mkdir(exist_ok=a ) model.save_pretrained(a ) def _lowerCamelCase( a , a , a , a , a , a , ): __a = os.path.join(a , a ) __a = BarkSemanticConfig.from_pretrained(os.path.join(a , "config.json" ) ) __a = BarkCoarseConfig.from_pretrained(os.path.join(a , "config.json" ) ) __a = BarkFineConfig.from_pretrained(os.path.join(a , "config.json" ) ) __a = EncodecConfig.from_pretrained("facebook/encodec_24khz" ) __a = BarkSemanticModel.from_pretrained(a ) __a = BarkCoarseModel.from_pretrained(a ) __a = BarkFineModel.from_pretrained(a ) __a = EncodecModel.from_pretrained("facebook/encodec_24khz" ) __a = BarkConfig.from_sub_model_configs( a , a , a , a ) __a = BarkGenerationConfig.from_sub_model_configs( semantic.generation_config , coarseAcoustic.generation_config , fineAcoustic.generation_config ) __a = BarkModel(a ) __a = semantic __a = coarseAcoustic __a = fineAcoustic __a = codec __a = bark_generation_config Path(a ).mkdir(exist_ok=a ) bark.save_pretrained(a , repo_id=a , push_to_hub=a ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__:Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument("""model_type""", type=str, help="""text, coarse or fine.""") parser.add_argument("""pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--is_small""", action="""store_true""", help="""convert the small version instead of the large.""") SCREAMING_SNAKE_CASE__:List[str] = parser.parse_args() load_model(args.pytorch_dump_folder_path, model_type=args.model_type, use_small=args.is_small)
721
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__:List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Tuple = { """google/bigbird-roberta-base""": """https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json""", """google/bigbird-roberta-large""": """https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json""", """google/bigbird-base-trivia-itc""": """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json""", # See all BigBird models at https://huggingface.co/models?filter=big_bird } class snake_case__ ( snake_case_ ): _snake_case : Any = """big_bird""" def __init__( self , lowerCamelCase=50358 , lowerCamelCase=768 , lowerCamelCase=12 , lowerCamelCase=12 , lowerCamelCase=3072 , lowerCamelCase="gelu_new" , lowerCamelCase=0.1 , lowerCamelCase=0.1 , lowerCamelCase=4096 , lowerCamelCase=2 , lowerCamelCase=0.02 , lowerCamelCase=1E-12 , lowerCamelCase=True , lowerCamelCase=0 , lowerCamelCase=1 , lowerCamelCase=2 , lowerCamelCase=66 , lowerCamelCase="block_sparse" , lowerCamelCase=True , lowerCamelCase=False , lowerCamelCase=64 , lowerCamelCase=3 , lowerCamelCase=None , **lowerCamelCase , ): super().__init__( pad_token_id=lowerCamelCase , bos_token_id=lowerCamelCase , eos_token_id=lowerCamelCase , sep_token_id=lowerCamelCase , **lowerCamelCase , ) __a = vocab_size __a = max_position_embeddings __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 = initializer_range __a = type_vocab_size __a = layer_norm_eps __a = use_cache __a = rescale_embeddings __a = attention_type __a = use_bias __a = block_size __a = num_random_blocks __a = classifier_dropout class snake_case__ ( snake_case_ ): @property def a__ ( self ): 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), ] )
67
0
"""simple docstring""" from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import ( BackboneOutput, BaseModelOutputWithNoAttention, BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) from ...modeling_utils import PreTrainedModel from ...utils import ( add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings, ) from ...utils.backbone_utils import BackboneMixin from .configuration_resnet import ResNetConfig SCREAMING_SNAKE_CASE__:int = logging.get_logger(__name__) # General docstring SCREAMING_SNAKE_CASE__:str = """ResNetConfig""" # Base docstring SCREAMING_SNAKE_CASE__:List[Any] = """microsoft/resnet-50""" SCREAMING_SNAKE_CASE__:Union[str, Any] = [1, 2048, 7, 7] # Image classification docstring SCREAMING_SNAKE_CASE__:Tuple = """microsoft/resnet-50""" SCREAMING_SNAKE_CASE__:Union[str, Any] = """tiger cat""" SCREAMING_SNAKE_CASE__:Optional[Any] = [ """microsoft/resnet-50""", # See all resnet models at https://huggingface.co/models?filter=resnet ] class snake_case__ ( nn.Module ): def __init__( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = 3 , lowerCamelCase = 1 , lowerCamelCase = "relu" ): super().__init__() __a = nn.Convad( lowerCamelCase , lowerCamelCase , kernel_size=lowerCamelCase , stride=lowerCamelCase , padding=kernel_size // 2 , bias=lowerCamelCase ) __a = nn.BatchNormad(lowerCamelCase ) __a = ACTaFN[activation] if activation is not None else nn.Identity() def a__ ( self , lowerCamelCase ): __a = self.convolution(lowerCamelCase ) __a = self.normalization(lowerCamelCase ) __a = self.activation(lowerCamelCase ) return hidden_state class snake_case__ ( nn.Module ): def __init__( self , lowerCamelCase ): super().__init__() __a = ResNetConvLayer( config.num_channels , config.embedding_size , kernel_size=7 , stride=2 , activation=config.hidden_act ) __a = nn.MaxPoolad(kernel_size=3 , stride=2 , padding=1 ) __a = config.num_channels def a__ ( self , lowerCamelCase ): __a = pixel_values.shape[1] if num_channels != self.num_channels: raise ValueError( "Make sure that the channel dimension of the pixel values match with the one set in the configuration." ) __a = self.embedder(lowerCamelCase ) __a = self.pooler(lowerCamelCase ) return embedding class snake_case__ ( nn.Module ): def __init__( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = 2 ): super().__init__() __a = nn.Convad(lowerCamelCase , lowerCamelCase , kernel_size=1 , stride=lowerCamelCase , bias=lowerCamelCase ) __a = nn.BatchNormad(lowerCamelCase ) def a__ ( self , lowerCamelCase ): __a = self.convolution(lowerCamelCase ) __a = self.normalization(lowerCamelCase ) return hidden_state class snake_case__ ( nn.Module ): def __init__( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = 1 , lowerCamelCase = "relu" ): super().__init__() __a = in_channels != out_channels or stride != 1 __a = ( ResNetShortCut(lowerCamelCase , lowerCamelCase , stride=lowerCamelCase ) if should_apply_shortcut else nn.Identity() ) __a = nn.Sequential( ResNetConvLayer(lowerCamelCase , lowerCamelCase , stride=lowerCamelCase ) , ResNetConvLayer(lowerCamelCase , lowerCamelCase , activation=lowerCamelCase ) , ) __a = ACTaFN[activation] def a__ ( self , lowerCamelCase ): __a = hidden_state __a = self.layer(lowerCamelCase ) __a = self.shortcut(lowerCamelCase ) hidden_state += residual __a = self.activation(lowerCamelCase ) return hidden_state class snake_case__ ( nn.Module ): def __init__( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = 1 , lowerCamelCase = "relu" , lowerCamelCase = 4 ): super().__init__() __a = in_channels != out_channels or stride != 1 __a = out_channels // reduction __a = ( ResNetShortCut(lowerCamelCase , lowerCamelCase , stride=lowerCamelCase ) if should_apply_shortcut else nn.Identity() ) __a = nn.Sequential( ResNetConvLayer(lowerCamelCase , lowerCamelCase , kernel_size=1 ) , ResNetConvLayer(lowerCamelCase , lowerCamelCase , stride=lowerCamelCase ) , ResNetConvLayer(lowerCamelCase , lowerCamelCase , kernel_size=1 , activation=lowerCamelCase ) , ) __a = ACTaFN[activation] def a__ ( self , lowerCamelCase ): __a = hidden_state __a = self.layer(lowerCamelCase ) __a = self.shortcut(lowerCamelCase ) hidden_state += residual __a = self.activation(lowerCamelCase ) return hidden_state class snake_case__ ( nn.Module ): def __init__( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase = 2 , lowerCamelCase = 2 , ): super().__init__() __a = ResNetBottleNeckLayer if config.layer_type == "bottleneck" else ResNetBasicLayer __a = nn.Sequential( # downsampling is done in the first layer with stride of 2 layer(lowerCamelCase , lowerCamelCase , stride=lowerCamelCase , activation=config.hidden_act ) , *[layer(lowerCamelCase , lowerCamelCase , activation=config.hidden_act ) for _ in range(depth - 1 )] , ) def a__ ( self , lowerCamelCase ): __a = input for layer in self.layers: __a = layer(lowerCamelCase ) return hidden_state class snake_case__ ( nn.Module ): def __init__( self , lowerCamelCase ): super().__init__() __a = nn.ModuleList([] ) # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input self.stages.append( ResNetStage( lowerCamelCase , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , ) ) __a = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for (in_channels, out_channels), depth in zip(lowerCamelCase , config.depths[1:] ): self.stages.append(ResNetStage(lowerCamelCase , lowerCamelCase , lowerCamelCase , depth=lowerCamelCase ) ) def a__ ( self , lowerCamelCase , lowerCamelCase = False , lowerCamelCase = True ): __a = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __a = hidden_states + (hidden_state,) __a = stage_module(lowerCamelCase ) if output_hidden_states: __a = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return BaseModelOutputWithNoAttention( last_hidden_state=lowerCamelCase , hidden_states=lowerCamelCase , ) class snake_case__ ( snake_case_ ): _snake_case : Union[str, Any] = ResNetConfig _snake_case : Tuple = """resnet""" _snake_case : Optional[Any] = """pixel_values""" _snake_case : Union[str, Any] = True def a__ ( self , lowerCamelCase ): if isinstance(lowerCamelCase , nn.Convad ): nn.init.kaiming_normal_(module.weight , mode="fan_out" , nonlinearity="relu" ) elif isinstance(lowerCamelCase , (nn.BatchNormad, nn.GroupNorm) ): nn.init.constant_(module.weight , 1 ) nn.init.constant_(module.bias , 0 ) def a__ ( self , lowerCamelCase , lowerCamelCase=False ): if isinstance(lowerCamelCase , lowerCamelCase ): __a = value SCREAMING_SNAKE_CASE__:List[str] = R""" This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`ResNetConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ SCREAMING_SNAKE_CASE__:Tuple = R""" Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ConvNextImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( """The bare ResNet model outputting raw features without any specific head on top.""", snake_case_, ) class snake_case__ ( snake_case_ ): def __init__( self , lowerCamelCase ): super().__init__(lowerCamelCase ) __a = config __a = ResNetEmbeddings(lowerCamelCase ) __a = ResNetEncoder(lowerCamelCase ) __a = nn.AdaptiveAvgPoolad((1, 1) ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=lowerCamelCase , config_class=_CONFIG_FOR_DOC , modality="vision" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def a__ ( self , lowerCamelCase , lowerCamelCase = None , lowerCamelCase = None ): __a = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __a = return_dict if return_dict is not None else self.config.use_return_dict __a = self.embedder(lowerCamelCase ) __a = self.encoder( lowerCamelCase , output_hidden_states=lowerCamelCase , return_dict=lowerCamelCase ) __a = encoder_outputs[0] __a = self.pooler(lowerCamelCase ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=lowerCamelCase , pooler_output=lowerCamelCase , hidden_states=encoder_outputs.hidden_states , ) @add_start_docstrings( """ ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. """, snake_case_, ) class snake_case__ ( snake_case_ ): def __init__( self , lowerCamelCase ): super().__init__(lowerCamelCase ) __a = config.num_labels __a = ResNetModel(lowerCamelCase ) # classification head __a = nn.Sequential( nn.Flatten() , nn.Linear(config.hidden_sizes[-1] , config.num_labels ) if config.num_labels > 0 else nn.Identity() , ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(lowerCamelCase ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=lowerCamelCase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def a__ ( self , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , ): __a = return_dict if return_dict is not None else self.config.use_return_dict __a = self.resnet(lowerCamelCase , output_hidden_states=lowerCamelCase , return_dict=lowerCamelCase ) __a = outputs.pooler_output if return_dict else outputs[1] __a = self.classifier(lowerCamelCase ) __a = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: __a = "regression" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): __a = "single_label_classification" else: __a = "multi_label_classification" if self.config.problem_type == "regression": __a = MSELoss() if self.num_labels == 1: __a = loss_fct(logits.squeeze() , labels.squeeze() ) else: __a = loss_fct(lowerCamelCase , lowerCamelCase ) elif self.config.problem_type == "single_label_classification": __a = CrossEntropyLoss() __a = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": __a = BCEWithLogitsLoss() __a = loss_fct(lowerCamelCase , lowerCamelCase ) if not return_dict: __a = (logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=lowerCamelCase , logits=lowerCamelCase , hidden_states=outputs.hidden_states ) @add_start_docstrings( """ ResNet backbone, to be used with frameworks like DETR and MaskFormer. """, snake_case_, ) class snake_case__ ( snake_case_, snake_case_ ): def __init__( self , lowerCamelCase ): super().__init__(lowerCamelCase ) super()._init_backbone(lowerCamelCase ) __a = [config.embedding_size] + config.hidden_sizes __a = ResNetEmbeddings(lowerCamelCase ) __a = ResNetEncoder(lowerCamelCase ) # initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(lowerCamelCase ) @replace_return_docstrings(output_type=lowerCamelCase , config_class=_CONFIG_FOR_DOC ) def a__ ( self , lowerCamelCase , lowerCamelCase = None , lowerCamelCase = None ): __a = return_dict if return_dict is not None else self.config.use_return_dict __a = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __a = self.embedder(lowerCamelCase ) __a = self.encoder(lowerCamelCase , output_hidden_states=lowerCamelCase , return_dict=lowerCamelCase ) __a = outputs.hidden_states __a = () for idx, stage in enumerate(self.stage_names ): if stage in self.out_features: feature_maps += (hidden_states[idx],) if not return_dict: __a = (feature_maps,) if output_hidden_states: output += (outputs.hidden_states,) return output return BackboneOutput( feature_maps=lowerCamelCase , hidden_states=outputs.hidden_states if output_hidden_states else None , attentions=lowerCamelCase , )
700
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation SCREAMING_SNAKE_CASE__:Optional[int] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Optional[int] = {"""tokenizer_file""": """tokenizer.json"""} SCREAMING_SNAKE_CASE__:Tuple = { """tokenizer_file""": { """bigscience/tokenizer""": """https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json""", """bigscience/bloom-560m""": """https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json""", """bigscience/bloom-1b1""": """https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json""", """bigscience/bloom-1b7""": """https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json""", """bigscience/bloom-3b""": """https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json""", """bigscience/bloom-7b1""": """https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json""", """bigscience/bloom""": """https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json""", }, } class snake_case__ ( snake_case_ ): _snake_case : Optional[Any] = VOCAB_FILES_NAMES _snake_case : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP _snake_case : Optional[int] = ["""input_ids""", """attention_mask"""] _snake_case : Optional[int] = None def __init__( self , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase="<unk>" , lowerCamelCase="<s>" , lowerCamelCase="</s>" , lowerCamelCase="<pad>" , lowerCamelCase=False , lowerCamelCase=False , **lowerCamelCase , ): super().__init__( lowerCamelCase , lowerCamelCase , tokenizer_file=lowerCamelCase , unk_token=lowerCamelCase , bos_token=lowerCamelCase , eos_token=lowerCamelCase , pad_token=lowerCamelCase , add_prefix_space=lowerCamelCase , clean_up_tokenization_spaces=lowerCamelCase , **lowerCamelCase , ) __a = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , lowerCamelCase ) != add_prefix_space: __a = getattr(lowerCamelCase , pre_tok_state.pop("type" ) ) __a = add_prefix_space __a = pre_tok_class(**lowerCamelCase ) __a = add_prefix_space def a__ ( self , *lowerCamelCase , **lowerCamelCase ): __a = kwargs.get("is_split_into_words" , lowerCamelCase ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with" " pretokenized inputs." ) return super()._batch_encode_plus(*lowerCamelCase , **lowerCamelCase ) def a__ ( self , *lowerCamelCase , **lowerCamelCase ): __a = kwargs.get("is_split_into_words" , lowerCamelCase ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with" " pretokenized inputs." ) return super()._encode_plus(*lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase = None ): __a = self._tokenizer.model.save(lowerCamelCase , name=lowerCamelCase ) return tuple(lowerCamelCase ) def a__ ( self , lowerCamelCase ): __a = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowerCamelCase , add_special_tokens=lowerCamelCase ) + [self.eos_token_id] ) if len(lowerCamelCase ) > self.model_max_length: __a = input_ids[-self.model_max_length :] return input_ids
67
0
"""simple docstring""" 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 ( MobileViTConfig, MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__:int = logging.get_logger(__name__) def _lowerCamelCase( a ): __a = MobileViTConfig() # size of the architecture if "mobilevit_s" in mobilevit_name: __a = [1_4_4, 1_9_2, 2_4_0] __a = [1_6, 3_2, 6_4, 9_6, 1_2_8, 1_6_0, 6_4_0] elif "mobilevit_xs" in mobilevit_name: __a = [9_6, 1_2_0, 1_4_4] __a = [1_6, 3_2, 4_8, 6_4, 8_0, 9_6, 3_8_4] elif "mobilevit_xxs" in mobilevit_name: __a = [6_4, 8_0, 9_6] __a = [1_6, 1_6, 2_4, 4_8, 6_4, 8_0, 3_2_0] __a = 0.05 __a = 2.0 if mobilevit_name.startswith("deeplabv3_" ): __a = 5_1_2 __a = 1_6 __a = 2_1 __a = "pascal-voc-id2label.json" else: __a = 1_0_0_0 __a = "imagenet-1k-id2label.json" __a = "huggingface/label-files" __a = json.load(open(hf_hub_download(a , a , repo_type="dataset" ) , "r" ) ) __a = {int(a ): v for k, v in idalabel.items()} __a = idalabel __a = {v: k for k, v in idalabel.items()} return config def _lowerCamelCase( a , a=False ): for i in range(1 , 6 ): if F"layer_{i}." in name: __a = name.replace(F"layer_{i}." , F"encoder.layer.{i - 1}." ) if "conv_1." in name: __a = name.replace("conv_1." , "conv_stem." ) if ".block." in name: __a = name.replace(".block." , "." ) if "exp_1x1" in name: __a = name.replace("exp_1x1" , "expand_1x1" ) if "red_1x1" in name: __a = name.replace("red_1x1" , "reduce_1x1" ) if ".local_rep.conv_3x3." in name: __a = name.replace(".local_rep.conv_3x3." , ".conv_kxk." ) if ".local_rep.conv_1x1." in name: __a = name.replace(".local_rep.conv_1x1." , ".conv_1x1." ) if ".norm." in name: __a = name.replace(".norm." , ".normalization." ) if ".conv." in name: __a = name.replace(".conv." , ".convolution." ) if ".conv_proj." in name: __a = name.replace(".conv_proj." , ".conv_projection." ) for i in range(0 , 2 ): for j in range(0 , 4 ): if F".{i}.{j}." in name: __a = name.replace(F".{i}.{j}." , F".{i}.layer.{j}." ) for i in range(2 , 6 ): for j in range(0 , 4 ): if F".{i}.{j}." in name: __a = name.replace(F".{i}.{j}." , F".{i}." ) if "expand_1x1" in name: __a = name.replace("expand_1x1" , "downsampling_layer.expand_1x1" ) if "conv_3x3" in name: __a = name.replace("conv_3x3" , "downsampling_layer.conv_3x3" ) if "reduce_1x1" in name: __a = name.replace("reduce_1x1" , "downsampling_layer.reduce_1x1" ) for i in range(2 , 5 ): if F".global_rep.{i}.weight" in name: __a = name.replace(F".global_rep.{i}.weight" , ".layernorm.weight" ) if F".global_rep.{i}.bias" in name: __a = name.replace(F".global_rep.{i}.bias" , ".layernorm.bias" ) if ".global_rep." in name: __a = name.replace(".global_rep." , ".transformer." ) if ".pre_norm_mha.0." in name: __a = name.replace(".pre_norm_mha.0." , ".layernorm_before." ) if ".pre_norm_mha.1.out_proj." in name: __a = name.replace(".pre_norm_mha.1.out_proj." , ".attention.output.dense." ) if ".pre_norm_ffn.0." in name: __a = name.replace(".pre_norm_ffn.0." , ".layernorm_after." ) if ".pre_norm_ffn.1." in name: __a = name.replace(".pre_norm_ffn.1." , ".intermediate.dense." ) if ".pre_norm_ffn.4." in name: __a = name.replace(".pre_norm_ffn.4." , ".output.dense." ) if ".transformer." in name: __a = name.replace(".transformer." , ".transformer.layer." ) if ".aspp_layer." in name: __a = name.replace(".aspp_layer." , "." ) if ".aspp_pool." in name: __a = name.replace(".aspp_pool." , "." ) if "seg_head." in name: __a = name.replace("seg_head." , "segmentation_head." ) if "segmentation_head.classifier.classifier." in name: __a = name.replace("segmentation_head.classifier.classifier." , "segmentation_head.classifier." ) if "classifier.fc." in name: __a = name.replace("classifier.fc." , "classifier." ) elif (not base_model) and ("segmentation_head." not in name): __a = "mobilevit." + name return name def _lowerCamelCase( a , a , a=False ): if base_model: __a = "" else: __a = "mobilevit." for key in orig_state_dict.copy().keys(): __a = orig_state_dict.pop(a ) if key[:8] == "encoder.": __a = key[8:] if "qkv" in key: __a = key.split("." ) __a = int(key_split[0][6:] ) - 1 __a = int(key_split[3] ) __a = model.get_submodule(F"{model_prefix}encoder.layer.{layer_num}" ) __a = layer.transformer.layer[transformer_num].attention.attention.all_head_size __a = ( F"{model_prefix}encoder.layer.{layer_num}.transformer.layer.{transformer_num}.attention.attention." ) 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:] else: __a = val return orig_state_dict def _lowerCamelCase( ): __a = "http://images.cocodataset.org/val2017/000000039769.jpg" __a = Image.open(requests.get(a , stream=a ).raw ) return im @torch.no_grad() def _lowerCamelCase( a , a , a , a=False ): __a = get_mobilevit_config(a ) # load original state_dict __a = torch.load(a , map_location="cpu" ) # load 🤗 model if mobilevit_name.startswith("deeplabv3_" ): __a = MobileViTForSemanticSegmentation(a ).eval() else: __a = MobileViTForImageClassification(a ).eval() __a = convert_state_dict(a , a ) model.load_state_dict(a ) # Check outputs on an image, prepared by MobileViTImageProcessor __a = MobileViTImageProcessor(crop_size=config.image_size , size=config.image_size + 3_2 ) __a = image_processor(images=prepare_img() , return_tensors="pt" ) __a = model(**a ) __a = outputs.logits if mobilevit_name.startswith("deeplabv3_" ): assert logits.shape == (1, 2_1, 3_2, 3_2) if mobilevit_name == "deeplabv3_mobilevit_s": __a = torch.tensor( [ [[6.20_65, 6.12_92, 6.20_70], [6.10_79, 6.12_54, 6.17_47], [6.00_42, 6.10_71, 6.10_34]], [[-6.92_53, -6.86_53, -7.03_98], [-7.32_18, -7.39_83, -7.36_70], [-7.19_61, -7.24_82, -7.15_69]], [[-4.47_23, -4.43_48, -4.37_69], [-5.36_29, -5.46_32, -5.45_98], [-5.15_87, -5.34_02, -5.50_59]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xs": __a = torch.tensor( [ [[5.44_49, 5.57_33, 5.63_14], [5.18_15, 5.39_30, 5.59_63], [5.16_56, 5.43_33, 5.48_53]], [[-9.44_23, -9.77_66, -9.67_14], [-9.15_81, -9.57_20, -9.55_19], [-9.10_06, -9.64_58, -9.57_03]], [[-7.77_21, -7.37_16, -7.15_83], [-8.45_99, -8.06_24, -7.79_44], [-8.41_72, -7.83_66, -7.50_25]], ] ) elif mobilevit_name == "deeplabv3_mobilevit_xxs": __a = torch.tensor( [ [[6.98_11, 6.97_43, 7.31_23], [7.17_77, 7.19_31, 7.39_38], [7.56_33, 7.80_50, 7.89_01]], [[-10.55_36, -10.23_32, -10.29_24], [-10.23_36, -9.86_24, -9.59_64], [-10.88_40, -10.81_58, -10.66_59]], [[-3.49_38, -3.06_31, -2.86_20], [-3.42_05, -2.81_35, -2.68_75], [-3.41_79, -2.79_45, -2.87_50]], ] ) else: raise ValueError(F"Unknown mobilevit_name: {mobilevit_name}" ) assert torch.allclose(logits[0, :3, :3, :3] , a , atol=1E-4 ) else: assert logits.shape == (1, 1_0_0_0) if mobilevit_name == "mobilevit_s": __a = torch.tensor([-0.98_66, 0.23_92, -1.12_41] ) elif mobilevit_name == "mobilevit_xs": __a = torch.tensor([-2.47_61, -0.93_99, -1.95_87] ) elif mobilevit_name == "mobilevit_xxs": __a = torch.tensor([-1.93_64, -1.23_27, -0.46_53] ) else: raise ValueError(F"Unknown mobilevit_name: {mobilevit_name}" ) assert torch.allclose(logits[0, :3] , a , atol=1E-4 ) Path(a ).mkdir(exist_ok=a ) print(F"Saving model {mobilevit_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(a ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(a ) if push_to_hub: __a = { "mobilevit_s": "mobilevit-small", "mobilevit_xs": "mobilevit-x-small", "mobilevit_xxs": "mobilevit-xx-small", "deeplabv3_mobilevit_s": "deeplabv3-mobilevit-small", "deeplabv3_mobilevit_xs": "deeplabv3-mobilevit-x-small", "deeplabv3_mobilevit_xxs": "deeplabv3-mobilevit-xx-small", } print("Pushing to the hub..." ) __a = model_mapping[mobilevit_name] image_processor.push_to_hub(a , organization="apple" ) model.push_to_hub(a , organization="apple" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__:Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--mobilevit_name""", default="""mobilevit_s""", type=str, help=( """Name of the MobileViT model you'd like to convert. Should be one of 'mobilevit_s', 'mobilevit_xs',""" """ 'mobilevit_xxs', 'deeplabv3_mobilevit_s', 'deeplabv3_mobilevit_xs', 'deeplabv3_mobilevit_xxs'.""" ), ) parser.add_argument( """--checkpoint_path""", required=True, type=str, help="""Path to the original state dict (.pt file).""" ) parser.add_argument( """--pytorch_dump_folder_path""", required=True, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) SCREAMING_SNAKE_CASE__:List[str] = parser.parse_args() convert_movilevit_checkpoint( args.mobilevit_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
701
"""simple docstring""" from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class snake_case__ : _snake_case : torch.Tensor # [batch_size x 3] _snake_case : torch.Tensor # [batch_size x 3] _snake_case : torch.Tensor # [batch_size x 3] _snake_case : torch.Tensor # [batch_size x 3] _snake_case : int _snake_case : int _snake_case : float _snake_case : float _snake_case : Tuple[int] def a__ ( self ): assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def a__ ( self ): return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def a__ ( self ): return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def a__ ( self ): __a = torch.arange(self.height * self.width ) __a = torch.stack( [ pixel_indices % self.width, torch.div(lowerCamelCase , self.width , rounding_mode="trunc" ), ] , axis=1 , ) return coords @property def a__ ( self ): __a , *__a = self.shape __a = int(np.prod(lowerCamelCase ) ) __a = self.get_image_coords() __a = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) __a = self.get_camera_rays(lowerCamelCase ) __a = rays.view(lowerCamelCase , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def a__ ( self , lowerCamelCase ): __a , *__a , __a = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] __a = coords.view(lowerCamelCase , -1 , 2 ) __a = self.resolution() __a = self.fov() __a = (flat.float() / (res - 1)) * 2 - 1 __a = fracs * torch.tan(fov / 2 ) __a = fracs.view(lowerCamelCase , -1 , 2 ) __a = ( self.z.view(lowerCamelCase , 1 , 3 ) + self.x.view(lowerCamelCase , 1 , 3 ) * fracs[:, :, :1] + self.y.view(lowerCamelCase , 1 , 3 ) * fracs[:, :, 1:] ) __a = directions / directions.norm(dim=-1 , keepdim=lowerCamelCase ) __a = torch.stack( [ torch.broadcast_to(self.origin.view(lowerCamelCase , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(lowerCamelCase , *lowerCamelCase , 2 , 3 ) def a__ ( self , lowerCamelCase , lowerCamelCase ): assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=lowerCamelCase , height=lowerCamelCase , x_fov=self.x_fov , y_fov=self.y_fov , ) def _lowerCamelCase( a ): __a = [] __a = [] __a = [] __a = [] for theta in np.linspace(0 , 2 * np.pi , num=2_0 ): __a = np.array([np.sin(a ), np.cos(a ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) __a = -z * 4 __a = np.array([np.cos(a ), -np.sin(a ), 0.0] ) __a = np.cross(a , a ) origins.append(a ) xs.append(a ) ys.append(a ) zs.append(a ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(a , axis=0 ) ).float() , x=torch.from_numpy(np.stack(a , axis=0 ) ).float() , y=torch.from_numpy(np.stack(a , axis=0 ) ).float() , z=torch.from_numpy(np.stack(a , axis=0 ) ).float() , width=a , height=a , x_fov=0.7 , y_fov=0.7 , shape=(1, len(a )) , )
67
0
"""simple docstring""" from __future__ import annotations def _lowerCamelCase( a , a , a ): if len(a ) == 0: raise ValueError("find_max() arg is an empty sequence" ) if ( left >= len(a ) or left < -len(a ) or right >= len(a ) or right < -len(a ) ): raise IndexError("list index out of range" ) if left == right: return nums[left] __a = (left + right) >> 1 # the middle __a = find_max(a , a , a ) # find max in range[left, mid] __a = find_max(a , mid + 1 , a ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
702
"""simple docstring""" def _lowerCamelCase( a ): return 1 if digit in (0, 1) else (digit * factorial(digit - 1 )) def _lowerCamelCase( a ): __a = 0 __a = number while duplicate > 0: __a , __a = divmod(a , 1_0 ) fact_sum += factorial(a ) return fact_sum == number if __name__ == "__main__": print("""Program to check whether a number is a Krisnamurthy Number or not.""") SCREAMING_SNAKE_CASE__:Optional[Any] = int(input("""Enter number: """).strip()) print( F'''{number} is {'' if krishnamurthy(number) else 'not '}a Krishnamurthy Number.''' )
67
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__:Union[str, Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Optional[int] = { """camembert-base""": """https://huggingface.co/camembert-base/resolve/main/config.json""", """umberto-commoncrawl-cased-v1""": ( """https://huggingface.co/Musixmatch/umberto-commoncrawl-cased-v1/resolve/main/config.json""" ), """umberto-wikipedia-uncased-v1""": ( """https://huggingface.co/Musixmatch/umberto-wikipedia-uncased-v1/resolve/main/config.json""" ), } class snake_case__ ( snake_case_ ): _snake_case : Optional[int] = """camembert""" def __init__( self , lowerCamelCase=30522 , lowerCamelCase=768 , lowerCamelCase=12 , lowerCamelCase=12 , lowerCamelCase=3072 , lowerCamelCase="gelu" , lowerCamelCase=0.1 , lowerCamelCase=0.1 , lowerCamelCase=512 , lowerCamelCase=2 , lowerCamelCase=0.02 , lowerCamelCase=1E-12 , lowerCamelCase=1 , lowerCamelCase=0 , lowerCamelCase=2 , lowerCamelCase="absolute" , lowerCamelCase=True , lowerCamelCase=None , **lowerCamelCase , ): super().__init__(pad_token_id=lowerCamelCase , bos_token_id=lowerCamelCase , eos_token_id=lowerCamelCase , **lowerCamelCase ) __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 snake_case__ ( snake_case_ ): @property def a__ ( self ): 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), ] )
703
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) SCREAMING_SNAKE_CASE__:Optional[Any] = { """configuration_gpt_bigcode""": ["""GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTBigCodeConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__:Union[str, Any] = [ """GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST""", """GPTBigCodeForSequenceClassification""", """GPTBigCodeForTokenClassification""", """GPTBigCodeForCausalLM""", """GPTBigCodeModel""", """GPTBigCodePreTrainedModel""", ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__:List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
67
0
"""simple docstring""" import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( HubertConfig, HubertForCTC, HubertModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() SCREAMING_SNAKE_CASE__:List[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:int = { """post_extract_proj""": """feature_projection.projection""", """encoder.pos_conv.0""": """encoder.pos_conv_embed.conv""", """self_attn.k_proj""": """encoder.layers.*.attention.k_proj""", """self_attn.v_proj""": """encoder.layers.*.attention.v_proj""", """self_attn.q_proj""": """encoder.layers.*.attention.q_proj""", """self_attn.out_proj""": """encoder.layers.*.attention.out_proj""", """self_attn_layer_norm""": """encoder.layers.*.layer_norm""", """fc1""": """encoder.layers.*.feed_forward.intermediate_dense""", """fc2""": """encoder.layers.*.feed_forward.output_dense""", """final_layer_norm""": """encoder.layers.*.final_layer_norm""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """feature_projection.layer_norm""", """w2v_encoder.proj""": """lm_head""", """mask_emb""": """masked_spec_embed""", } def _lowerCamelCase( a , a , a , a , a ): for attribute in key.split("." ): __a = getattr(a , a ) if weight_type is not None: __a = getattr(a , a ).shape else: __a = hf_pointer.shape assert hf_shape == value.shape, ( F"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be" F" {value.shape} for {full_name}" ) if weight_type == "weight": __a = value elif weight_type == "weight_g": __a = value elif weight_type == "weight_v": __a = value elif weight_type == "bias": __a = value else: __a = value logger.info(F"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def _lowerCamelCase( a , a , a ): __a = [] __a = fairseq_model.state_dict() __a = hf_model.hubert.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): __a = False if "conv_layers" in name: load_conv_layer( a , a , a , a , hf_model.config.feat_extract_norm == "group" , ) __a = True else: for key, mapped_key in MAPPING.items(): __a = "hubert." + mapped_key if (is_finetuned and mapped_key != "lm_head") else mapped_key if key in name or (key.split("w2v_model." )[-1] == name.split("." )[0] and not is_finetuned): __a = True if "*" in mapped_key: __a = name.split(a )[0].split("." )[-2] __a = mapped_key.replace("*" , a ) if "weight_g" in name: __a = "weight_g" elif "weight_v" in name: __a = "weight_v" elif "weight" in name: __a = "weight" elif "bias" in name: __a = "bias" else: __a = None set_recursively(a , a , a , a , a ) continue if not is_used: unused_weights.append(a ) logger.warning(F"Unused weights: {unused_weights}" ) def _lowerCamelCase( a , a , a , a , a ): __a = full_name.split("conv_layers." )[-1] __a = name.split("." ) __a = int(items[0] ) __a = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) __a = value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) __a = value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was" " found." ) __a = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F"{full_name} has size {value.shape}, but" F" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found." ) __a = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(a ) @torch.no_grad() def _lowerCamelCase( a , a , a=None , a=None , a=True ): if config_path is not None: __a = HubertConfig.from_pretrained(a ) else: __a = HubertConfig() if is_finetuned: if dict_path: __a = Dictionary.load(a ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __a = target_dict.pad_index __a = target_dict.bos_index __a = target_dict.eos_index __a = len(target_dict.symbols ) __a = os.path.join(a , "vocab.json" ) if not os.path.isdir(a ): logger.error("--pytorch_dump_folder_path ({}) should be a directory".format(a ) ) return os.makedirs(a , exist_ok=a ) with open(a , "w" , encoding="utf-8" ) as vocab_handle: json.dump(target_dict.indices , a ) __a = WavaVecaCTCTokenizer( a , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="|" , do_lower_case=a , ) __a = True if config.feat_extract_norm == "layer" else False __a = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_6_0_0_0 , padding_value=0 , do_normalize=a , return_attention_mask=a , ) __a = WavaVecaProcessor(feature_extractor=a , tokenizer=a ) processor.save_pretrained(a ) __a = HubertForCTC(a ) else: __a = HubertModel(a ) if is_finetuned: __a , __a , __a = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] )} ) else: __a , __a , __a = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) __a = model[0].eval() recursively_load_weights(a , a , a ) hf_wavavec.save_pretrained(a ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__:Any = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--not_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) SCREAMING_SNAKE_CASE__:List[str] = parser.parse_args() convert_hubert_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
704
"""simple docstring""" import argparse import OmegaConf import torch from diffusers import DDIMScheduler, LDMPipeline, UNetLDMModel, VQModel def _lowerCamelCase( a , a , a ): __a = OmegaConf.load(a ) __a = torch.load(a , map_location="cpu" )["model"] __a = list(state_dict.keys() ) # extract state_dict for VQVAE __a = {} __a = "first_stage_model." for key in keys: if key.startswith(a ): __a = state_dict[key] # extract state_dict for UNetLDM __a = {} __a = "model.diffusion_model." for key in keys: if key.startswith(a ): __a = state_dict[key] __a = config.model.params.first_stage_config.params __a = config.model.params.unet_config.params __a = VQModel(**a ).eval() vqvae.load_state_dict(a ) __a = UNetLDMModel(**a ).eval() unet.load_state_dict(a ) __a = 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=a , ) __a = LDMPipeline(a , a , a ) pipeline.save_pretrained(a ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__:List[Any] = 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) SCREAMING_SNAKE_CASE__:Union[str, Any] = parser.parse_args() convert_ldm_original(args.checkpoint_path, args.config_path, args.output_path)
67
0
"""simple docstring""" def _lowerCamelCase( a ): 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()
705
"""simple docstring""" from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...file_utils import TensorType, is_torch_available from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging SCREAMING_SNAKE_CASE__:List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Optional[Any] = { """facebook/blenderbot_small-90M""": """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/config.json""", # See all BlenderbotSmall models at https://huggingface.co/models?filter=blenderbot_small } class snake_case__ ( snake_case_ ): _snake_case : str = """blenderbot-small""" _snake_case : str = ["""past_key_values"""] _snake_case : List[Any] = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self , lowerCamelCase=50265 , lowerCamelCase=512 , lowerCamelCase=8 , lowerCamelCase=2048 , lowerCamelCase=16 , lowerCamelCase=8 , lowerCamelCase=2048 , lowerCamelCase=16 , lowerCamelCase=0.0 , lowerCamelCase=0.0 , lowerCamelCase=True , lowerCamelCase=True , lowerCamelCase="gelu" , lowerCamelCase=512 , lowerCamelCase=0.1 , lowerCamelCase=0.0 , lowerCamelCase=0.0 , lowerCamelCase=0.02 , lowerCamelCase=1 , lowerCamelCase=False , lowerCamelCase=0 , lowerCamelCase=1 , lowerCamelCase=2 , lowerCamelCase=2 , **lowerCamelCase , ): __a = vocab_size __a = max_position_embeddings __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 = encoder_layerdrop __a = decoder_layerdrop __a = use_cache __a = encoder_layers __a = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=lowerCamelCase , bos_token_id=lowerCamelCase , eos_token_id=lowerCamelCase , is_encoder_decoder=lowerCamelCase , decoder_start_token_id=lowerCamelCase , forced_eos_token_id=lowerCamelCase , **lowerCamelCase , ) class snake_case__ ( snake_case_ ): @property def a__ ( self ): if self.task in ["default", "seq2seq-lm"]: __a = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: __a = {0: "batch"} __a = {0: "batch", 1: "past_decoder_sequence + sequence"} else: __a = {0: "batch", 1: "decoder_sequence"} __a = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(lowerCamelCase , direction="inputs" ) elif self.task == "causal-lm": # TODO: figure this case out. __a = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: __a , __a = self.num_layers for i in range(lowerCamelCase ): __a = {0: "batch", 2: "past_sequence + sequence"} __a = {0: "batch", 2: "past_sequence + sequence"} else: __a = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}), ("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}), ] ) return common_inputs @property def a__ ( self ): if self.task in ["default", "seq2seq-lm"]: __a = super().outputs else: __a = super(lowerCamelCase , self ).outputs if self.use_past: __a , __a = self.num_layers for i in range(lowerCamelCase ): __a = {0: "batch", 2: "past_sequence + sequence"} __a = {0: "batch", 2: "past_sequence + sequence"} return common_outputs def a__ ( self , lowerCamelCase , lowerCamelCase = -1 , lowerCamelCase = -1 , lowerCamelCase = False , lowerCamelCase = None , ): __a = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) # Generate decoder inputs __a = seq_length if not self.use_past else 1 __a = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) __a = {F"decoder_{name}": tensor for name, tensor in decoder_inputs.items()} __a = dict(**lowerCamelCase , **lowerCamelCase ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch __a , __a = common_inputs["input_ids"].shape __a = common_inputs["decoder_input_ids"].shape[1] __a , __a = self.num_attention_heads __a = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) __a = decoder_seq_length + 3 __a = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) __a = torch.cat( [common_inputs["decoder_attention_mask"], torch.ones(lowerCamelCase , lowerCamelCase )] , dim=1 ) __a = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered __a , __a = self.num_layers __a = min(lowerCamelCase , lowerCamelCase ) __a = max(lowerCamelCase , lowerCamelCase ) - min_num_layers __a = "encoder" if num_encoder_layers > num_decoder_layers else "decoder" for _ in range(lowerCamelCase ): common_inputs["past_key_values"].append( ( torch.zeros(lowerCamelCase ), torch.zeros(lowerCamelCase ), torch.zeros(lowerCamelCase ), torch.zeros(lowerCamelCase ), ) ) # TODO: test this. __a = encoder_shape if remaining_side_name == "encoder" else decoder_shape for _ in range(lowerCamelCase , lowerCamelCase ): common_inputs["past_key_values"].append((torch.zeros(lowerCamelCase ), torch.zeros(lowerCamelCase )) ) return common_inputs def a__ ( self , lowerCamelCase , lowerCamelCase = -1 , lowerCamelCase = -1 , lowerCamelCase = False , lowerCamelCase = None , ): __a = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch __a , __a = common_inputs["input_ids"].shape # Not using the same length for past_key_values __a = seqlen + 2 __a , __a = self.num_layers __a , __a = self.num_attention_heads __a = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) __a = common_inputs["attention_mask"].dtype __a = torch.cat( [common_inputs["attention_mask"], torch.ones(lowerCamelCase , lowerCamelCase , dtype=lowerCamelCase )] , dim=1 ) __a = [ (torch.zeros(lowerCamelCase ), torch.zeros(lowerCamelCase )) for _ in range(lowerCamelCase ) ] return common_inputs def a__ ( self , lowerCamelCase , lowerCamelCase = -1 , lowerCamelCase = -1 , lowerCamelCase = False , lowerCamelCase = None , ): # Copied from OnnxConfig.generate_dummy_inputs # Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity. # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX __a = compute_effective_axis_dimension( lowerCamelCase , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX __a = tokenizer.num_special_tokens_to_add(lowerCamelCase ) __a = compute_effective_axis_dimension( lowerCamelCase , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=lowerCamelCase ) # Generate dummy inputs according to compute batch and sequence __a = [" ".join([tokenizer.unk_token] ) * seq_length] * batch_size __a = dict(tokenizer(lowerCamelCase , return_tensors=lowerCamelCase ) ) return common_inputs def a__ ( self , lowerCamelCase , lowerCamelCase = -1 , lowerCamelCase = -1 , lowerCamelCase = False , lowerCamelCase = None , ): if self.task in ["default", "seq2seq-lm"]: __a = self._generate_dummy_inputs_for_default_and_seqaseq_lm( lowerCamelCase , batch_size=lowerCamelCase , seq_length=lowerCamelCase , is_pair=lowerCamelCase , framework=lowerCamelCase ) elif self.task == "causal-lm": __a = self._generate_dummy_inputs_for_causal_lm( lowerCamelCase , batch_size=lowerCamelCase , seq_length=lowerCamelCase , is_pair=lowerCamelCase , framework=lowerCamelCase ) else: __a = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCamelCase , batch_size=lowerCamelCase , seq_length=lowerCamelCase , is_pair=lowerCamelCase , framework=lowerCamelCase ) return common_inputs def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): if self.task in ["default", "seq2seq-lm"]: __a = super()._flatten_past_key_values_(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) else: __a = super(lowerCamelCase , self )._flatten_past_key_values_( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase )
67
0
"""simple docstring""" import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv("""TEST_SAGEMAKER""", """False""" ) ) is not True, reason="""Skipping test because should only be run when releasing minor transformers version""", ) @pytest.mark.usefixtures("""sm_env""" ) @parameterized_class( [ { """framework""": """pytorch""", """script""": """run_glue_model_parallelism.py""", """model_name_or_path""": """roberta-large""", """instance_type""": """ml.p3dn.24xlarge""", """results""": {"""train_runtime""": 1_600, """eval_accuracy""": 0.3, """eval_loss""": 1.2}, }, { """framework""": """pytorch""", """script""": """run_glue.py""", """model_name_or_path""": """roberta-large""", """instance_type""": """ml.p3dn.24xlarge""", """results""": {"""train_runtime""": 1_600, """eval_accuracy""": 0.3, """eval_loss""": 1.2}, }, ] ) class snake_case__ ( unittest.TestCase ): def a__ ( self ): if self.framework == "pytorch": subprocess.run( F"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split() , encoding="utf-8" , check=lowerCamelCase , ) assert hasattr(self , "env" ) def a__ ( self , lowerCamelCase ): # configuration for running training on smdistributed Model Parallel __a = { "enabled": True, "processes_per_host": 8, } __a = { "enabled": True, "parameters": { "microbatches": 4, "placement_strategy": "spread", "pipeline": "interleaved", "optimize": "speed", "partitions": 4, "ddp": True, }, } __a = {"smdistributed": {"modelparallel": smp_options}, "mpi": mpi_options} __a = "trainer" if self.script == "run_glue.py" else "smtrainer" # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=F"{self.env.base_job_name}-{instance_count}-smp-{name_extension}" , instance_count=lowerCamelCase , instance_type=self.instance_type , debugger_hook_config=lowerCamelCase , hyperparameters={ **self.env.hyperparameters, "model_name_or_path": self.model_name_or_path, "max_steps": 500, } , metric_definitions=self.env.metric_definitions , distribution=lowerCamelCase , py_version="py36" , ) def a__ ( self , lowerCamelCase ): TrainingJobAnalytics(lowerCamelCase ).export_csv(F"{self.env.test_path}/{job_name}_metrics.csv" ) @parameterized.expand([(1,)] ) def a__ ( self , lowerCamelCase ): # create estimator __a = self.create_estimator(lowerCamelCase ) # run training estimator.fit() # result dataframe __a = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __a = list(result_metrics_df[result_metrics_df.metric_name == "eval_accuracy"]["value"] ) __a = list(result_metrics_df[result_metrics_df.metric_name == "eval_loss"]["value"] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __a = ( Session().describe_training_job(estimator.latest_training_job.name ).get("TrainingTimeInSeconds" , 999999 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results["eval_accuracy"] for t in eval_accuracy ) assert all(t <= self.results["eval_loss"] for t in eval_loss ) # dump tests result into json file to share in PR with open(F"{estimator.latest_training_job.name}.json" , "w" ) as outfile: json.dump({"train_time": train_runtime, "eval_accuracy": eval_accuracy, "eval_loss": eval_loss} , lowerCamelCase )
706
"""simple docstring""" import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class snake_case__ : def __init__( self , lowerCamelCase , lowerCamelCase=99 , lowerCamelCase=13 , lowerCamelCase=7 , lowerCamelCase=9 , lowerCamelCase=True , lowerCamelCase=True , lowerCamelCase=False , lowerCamelCase=32 , lowerCamelCase=5 , lowerCamelCase=4 , lowerCamelCase=37 , lowerCamelCase=8 , lowerCamelCase=0.1 , lowerCamelCase=0.002 , lowerCamelCase=1 , lowerCamelCase=0 , lowerCamelCase=0 , lowerCamelCase=None , lowerCamelCase=None , ): __a = parent __a = batch_size __a = encoder_seq_length __a = decoder_seq_length # For common tests __a = self.decoder_seq_length __a = is_training __a = use_attention_mask __a = use_labels __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = d_ff __a = relative_attention_num_buckets __a = dropout_rate __a = initializer_factor __a = eos_token_id __a = pad_token_id __a = decoder_start_token_id __a = None __a = decoder_layers def a__ ( self ): return TaConfig.from_pretrained("google/umt5-base" ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , ): if attention_mask is None: __a = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: __a = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: __a = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=lowerCamelCase ) if decoder_head_mask is None: __a = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=lowerCamelCase ) if cross_attn_head_mask is None: __a = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=lowerCamelCase ) 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, } def a__ ( self ): __a = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) __a = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input __a = input_ids.clamp(self.pad_token_id + 1 ) __a = decoder_input_ids.clamp(self.pad_token_id + 1 ) __a = self.get_config() __a = config.num_attention_heads __a = self.prepare_inputs_dict(lowerCamelCase , lowerCamelCase , lowerCamelCase ) return config, input_dict def a__ ( self ): __a , __a = self.prepare_config_and_inputs() return config, inputs_dict def a__ ( self ): return TaConfig( vocab_size=166 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def a__ ( self ): return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , ): __a = UMTaModel(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model( input_ids=lowerCamelCase , decoder_input_ids=lowerCamelCase , attention_mask=lowerCamelCase , decoder_attention_mask=lowerCamelCase , ) __a = model(input_ids=lowerCamelCase , decoder_input_ids=lowerCamelCase ) __a = result.last_hidden_state __a = result.past_key_values __a = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(lowerCamelCase ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , ): __a = UMTaModel(config=lowerCamelCase ).get_decoder().to(lowerCamelCase ).eval() # first forward pass __a = model(lowerCamelCase , use_cache=lowerCamelCase ) __a = model(lowerCamelCase ) __a = model(lowerCamelCase , use_cache=lowerCamelCase ) self.parent.assertTrue(len(lowerCamelCase ) == len(lowerCamelCase ) ) self.parent.assertTrue(len(lowerCamelCase ) == len(lowerCamelCase ) + 1 ) __a , __a = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __a = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and __a = torch.cat([input_ids, next_tokens] , dim=-1 ) __a = model(lowerCamelCase )["last_hidden_state"] __a = model(lowerCamelCase , past_key_values=lowerCamelCase )["last_hidden_state"] # select random slice __a = ids_tensor((1,) , output_from_past.shape[-1] ).item() __a = output_from_no_past[:, -1, random_slice_idx].detach() __a = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(lowerCamelCase , lowerCamelCase , atol=1E-3 ) ) def a__ ( self , lowerCamelCase , lowerCamelCase , ): __a = UMTaModel(config=lowerCamelCase ).to(lowerCamelCase ).half().eval() __a = model(**lowerCamelCase )["last_hidden_state"] self.parent.assertFalse(torch.isnan(lowerCamelCase ).any().item() ) @require_torch class snake_case__ ( snake_case_, snake_case_, snake_case_, unittest.TestCase ): _snake_case : Union[str, Any] = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) _snake_case : int = (UMTaForConditionalGeneration,) if is_torch_available() else () _snake_case : Optional[int] = ( { """conversational""": UMTaForConditionalGeneration, """feature-extraction""": UMTaModel, """summarization""": UMTaForConditionalGeneration, """text2text-generation""": UMTaForConditionalGeneration, """translation""": UMTaForConditionalGeneration, """question-answering""": UMTaForQuestionAnswering, } if is_torch_available() else {} ) _snake_case : List[Any] = True _snake_case : Union[str, Any] = False _snake_case : Union[str, Any] = False _snake_case : Tuple = True _snake_case : List[str] = True # The small UMT5 model needs higher percentages for CPU/MP tests _snake_case : Optional[Any] = [0.8, 0.9] def a__ ( self ): __a = UMTaModelTester(self ) @unittest.skip("Test has a segmentation fault on torch 1.8.0" ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() __a = UMTaModel(config_and_inputs[0] ).to(lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( lowerCamelCase , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , F"{tmpdirname}/t5_test.onnx" , export_params=lowerCamelCase , opset_version=9 , input_names=["input_ids", "decoder_input_ids"] , ) @unittest.skipIf(torch_device == "cpu" , "Cant do half precision" ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*lowerCamelCase ) def a__ ( self ): __a = ["encoder_attentions", "decoder_attentions", "cross_attentions"] __a = self.model_tester.prepare_config_and_inputs() __a = config_and_inputs[0] __a = UMTaForConditionalGeneration(lowerCamelCase ).eval() model.to(lowerCamelCase ) __a = { "head_mask": torch.zeros(config.num_layers , config.num_heads , device=lowerCamelCase ), "decoder_head_mask": torch.zeros(config.num_decoder_layers , config.num_heads , device=lowerCamelCase ), "cross_attn_head_mask": torch.zeros(config.num_decoder_layers , config.num_heads , device=lowerCamelCase ), } for attn_name, (name, mask) in zip(lowerCamelCase , head_masking.items() ): __a = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": __a = torch.ones( config.num_decoder_layers , config.num_heads , device=lowerCamelCase ) __a = model.generate( config_and_inputs[1]["input_ids"] , num_beams=1 , max_length=3 , output_attentions=lowerCamelCase , return_dict_in_generate=lowerCamelCase , **lowerCamelCase , ) # We check the state of decoder_attentions and cross_attentions just from the last step __a = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip("Does not work on the tiny model as we keep hitting edge cases." ) def a__ ( self ): pass @require_torch @require_sentencepiece @require_tokenizers class snake_case__ ( unittest.TestCase ): @slow @unittest.skip( "Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged" ) def a__ ( self ): __a = UMTaForConditionalGeneration.from_pretrained("google/umt5-small" , return_dict=lowerCamelCase ).to(lowerCamelCase ) __a = AutoTokenizer.from_pretrained("google/umt5-small" , use_fast=lowerCamelCase , legacy=lowerCamelCase ) __a = [ "Bonjour monsieur <extra_id_0> bien <extra_id_1>.", "No se como puedo <extra_id_0>.", "This is the reason why we <extra_id_0> them.", "The <extra_id_0> walks in <extra_id_1>, seats", "A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.", ] __a = tokenizer(lowerCamelCase , return_tensors="pt" , padding=lowerCamelCase ).input_ids # fmt: off __a = torch.tensor( [ [ 38530, 210703, 256299, 1410, 256298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 826, 321, 671, 25922, 256299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1460, 339, 312, 19014, 10620, 758, 256299, 2355,274, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 517, 256299, 14869, 281, 301, 256298, 275, 119983,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 320, 256299, 14869, 281, 2234, 289, 2275, 333,61391, 289, 256298, 543, 256297, 168714, 329, 256296,274, 1], ] ) # fmt: on torch.testing.assert_allclose(lowerCamelCase , lowerCamelCase ) __a = model.generate(input_ids.to(lowerCamelCase ) ) __a = [ "<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>", "<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", "<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", "<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", "<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", ] __a = tokenizer.batch_decode(lowerCamelCase ) self.assertEqual(lowerCamelCase , lowerCamelCase )
67
0
"""simple docstring""" import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def _lowerCamelCase( a = 8 ): __a = ascii_letters + digits + punctuation return "".join(secrets.choice(a ) for _ in range(a ) ) def _lowerCamelCase( a , a ): # Password Generator = full boot with random_number, random_letters, and # random_character FUNCTIONS # Put your code here... i -= len(a ) __a = i // 3 __a = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) __a = ( chars_incl + random(a , quotient + remainder ) + random(a , a ) + random(a , a ) ) __a = list(a ) shuffle(a ) return "".join(a ) # random is a generalised function for letters, characters and numbers def _lowerCamelCase( a , a ): return "".join(secrets.choice(a ) for _ in range(a ) ) def _lowerCamelCase( a , a ): pass # Put your code here... def _lowerCamelCase( a , a ): pass # Put your code here... def _lowerCamelCase( a , a ): pass # Put your code here... def _lowerCamelCase( a , a = 8 ): if len(a ) < min_length: # Your Password must be at least 8 characters long return False __a = any(char in ascii_uppercase for char in password ) __a = any(char in ascii_lowercase for char in password ) __a = any(char in digits for char in password ) __a = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def _lowerCamelCase( ): __a = int(input("Please indicate the max length of your password: " ).strip() ) __a = input( "Please indicate the characters that must be in your password: " ).strip() print("Password generated:" , password_generator(a ) ) print( "Alternative Password generated:" , alternative_password_generator(a , a ) , ) print("[If you are thinking of using this passsword, You better save it.]" ) if __name__ == "__main__": main()
707
"""simple docstring""" import argparse import torch from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert from transformers.utils import logging logging.set_verbosity_info() def _lowerCamelCase( a , a , a ): # Initialise PyTorch model __a = MobileBertConfig.from_json_file(a ) print(F"Building PyTorch model from configuration: {config}" ) __a = MobileBertForPreTraining(a ) # Load weights from tf checkpoint __a = load_tf_weights_in_mobilebert(a , a , a ) # Save pytorch-model print(F"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , a ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__:List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--mobilebert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained MobileBERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) SCREAMING_SNAKE_CASE__:List[Any] = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.mobilebert_config_file, args.pytorch_dump_path)
67
0
from __future__ import annotations import typing from collections.abc import Iterable import numpy as np SCREAMING_SNAKE_CASE__:Union[str, Any] = typing.Union[Iterable[float], Iterable[int], np.ndarray] # noqa: UP007 SCREAMING_SNAKE_CASE__:List[Any] = typing.Union[np.floataa, int, float] # noqa: UP007 def _lowerCamelCase( a , a ): return np.sqrt(np.sum((np.asarray(a ) - np.asarray(a )) ** 2 ) ) def _lowerCamelCase( a , a ): return sum((va - va) ** 2 for va, va in zip(a , a ) ) ** (1 / 2) if __name__ == "__main__": def _lowerCamelCase( ): from timeit import timeit print("Without Numpy" ) print( timeit( "euclidean_distance_no_np([1, 2, 3], [4, 5, 6])" , number=1_0_0_0_0 , globals=globals() , ) ) print("With Numpy" ) print( timeit( "euclidean_distance([1, 2, 3], [4, 5, 6])" , number=1_0_0_0_0 , globals=globals() , ) ) benchmark()
708
"""simple docstring""" import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class snake_case__ ( snake_case_ ): def a__ ( self , lowerCamelCase ): with open(lowerCamelCase , encoding="utf-8" ) as input_file: __a = re.compile(R"(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)" ) __a = input_file.read() __a = regexp.search(lowerCamelCase ) return match def a__ ( self , lowerCamelCase ): with open(lowerCamelCase , encoding="utf-8" ) as input_file: __a = re.compile(R"#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()" , re.DOTALL ) __a = input_file.read() # use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search` __a = regexp.finditer(lowerCamelCase ) __a = [match for match in matches if match is not None and match.group(1 ) is not None] return matches[0] if matches else None def a__ ( self ): __a = Path("./datasets" ) __a = list(dataset_paths.absolute().glob("**/*.py" ) ) for dataset in dataset_files: if self._no_encoding_on_file_open(str(lowerCamelCase ) ): raise AssertionError(F"open(...) must use utf-8 encoding in {dataset}" ) def a__ ( self ): __a = Path("./datasets" ) __a = list(dataset_paths.absolute().glob("**/*.py" ) ) for dataset in dataset_files: if self._no_print_statements(str(lowerCamelCase ) ): raise AssertionError(F"print statement found in {dataset}. Use datasets.logger/logging instead." )
67
0
"""simple docstring""" import inspect from typing import Callable, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import DiffusionPipeline from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import logging SCREAMING_SNAKE_CASE__:int = logging.get_logger(__name__) # pylint: disable=invalid-name class snake_case__ ( snake_case_ ): def __init__( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , ): super().__init__() self.register_modules( vae=lowerCamelCase , text_encoder=lowerCamelCase , tokenizer=lowerCamelCase , unet=lowerCamelCase , scheduler=lowerCamelCase , safety_checker=lowerCamelCase , feature_extractor=lowerCamelCase , ) def a__ ( self , lowerCamelCase = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __a = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(lowerCamelCase ) def a__ ( self ): self.enable_attention_slicing(lowerCamelCase ) @torch.no_grad() def __call__( self , lowerCamelCase , lowerCamelCase = 512 , lowerCamelCase = 512 , lowerCamelCase = 50 , lowerCamelCase = 7.5 , lowerCamelCase = None , lowerCamelCase = 1 , lowerCamelCase = 0.0 , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = "pil" , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = 1 , lowerCamelCase = None , **lowerCamelCase , ): if isinstance(lowerCamelCase , lowerCamelCase ): __a = 1 elif isinstance(lowerCamelCase , lowerCamelCase ): __a = len(lowerCamelCase ) else: raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(lowerCamelCase )}" ) 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(lowerCamelCase , lowerCamelCase ) or callback_steps <= 0) ): raise ValueError( F"`callback_steps` has to be a positive integer but is {callback_steps} of type" F" {type(lowerCamelCase )}." ) # get prompt text embeddings __a = self.tokenizer( lowerCamelCase , padding="max_length" , max_length=self.tokenizer.model_max_length , return_tensors="pt" , ) __a = text_inputs.input_ids if text_input_ids.shape[-1] > self.tokenizer.model_max_length: __a = 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 = text_input_ids[:, : self.tokenizer.model_max_length] if text_embeddings is None: __a = 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 = text_embeddings.shape __a = text_embeddings.repeat(1 , lowerCamelCase , 1 ) __a = text_embeddings.view(bs_embed * num_images_per_prompt , lowerCamelCase , -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 = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: __a = 42 if negative_prompt is None: __a = [""] elif type(lowerCamelCase ) is not type(lowerCamelCase ): raise TypeError( F"`negative_prompt` should be the same type to `prompt`, but got {type(lowerCamelCase )} !=" F" {type(lowerCamelCase )}." ) elif isinstance(lowerCamelCase , lowerCamelCase ): __a = [negative_prompt] elif batch_size != len(lowerCamelCase ): raise ValueError( F"`negative_prompt`: {negative_prompt} has batch size {len(lowerCamelCase )}, but `prompt`:" F" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" " the batch size of `prompt`." ) else: __a = negative_prompt __a = text_input_ids.shape[-1] __a = self.tokenizer( lowerCamelCase , padding="max_length" , max_length=lowerCamelCase , truncation=lowerCamelCase , return_tensors="pt" , ) __a = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt, using mps friendly method __a = uncond_embeddings.shape[1] __a = uncond_embeddings.repeat(lowerCamelCase , lowerCamelCase , 1 ) __a = uncond_embeddings.view(batch_size * num_images_per_prompt , lowerCamelCase , -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 = 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 = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8) __a = (batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64) __a = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not exist on mps __a = torch.randn( lowerCamelCase , generator=lowerCamelCase , device="cpu" , dtype=lowerCamelCase ).to(self.device ) __a = torch.randn(lowerCamelCase , generator=lowerCamelCase , device="cpu" , dtype=lowerCamelCase ).to( self.device ) else: __a = torch.randn( lowerCamelCase , generator=lowerCamelCase , device=self.device , dtype=lowerCamelCase ) __a = torch.randn(lowerCamelCase , generator=lowerCamelCase , device=self.device , dtype=lowerCamelCase ) else: if latents_reference.shape != latents_shape: raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {latents_shape}" ) __a = latents_reference.to(self.device ) __a = latents.to(self.device ) # This is the key part of the pipeline where we # try to ensure that the generated images w/ the same seed # but different sizes actually result in similar images __a = (latents_shape[3] - latents_shape_reference[3]) // 2 __a = (latents_shape[2] - latents_shape_reference[2]) // 2 __a = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx __a = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy __a = 0 if dx < 0 else dx __a = 0 if dy < 0 else dy __a = max(-dx , 0 ) __a = max(-dy , 0 ) # import pdb # pdb.set_trace() __a = latents_reference[:, :, dy : dy + h, dx : dx + w] # set timesteps self.scheduler.set_timesteps(lowerCamelCase ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand __a = self.scheduler.timesteps.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler __a = 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 = "eta" in set(inspect.signature(self.scheduler.step ).parameters.keys() ) __a = {} if accepts_eta: __a = eta for i, t in enumerate(self.progress_bar(lowerCamelCase ) ): # expand the latents if we are doing classifier free guidance __a = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents __a = self.scheduler.scale_model_input(lowerCamelCase , lowerCamelCase ) # predict the noise residual __a = self.unet(lowerCamelCase , lowerCamelCase , encoder_hidden_states=lowerCamelCase ).sample # perform guidance if do_classifier_free_guidance: __a , __a = noise_pred.chunk(2 ) __a = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # compute the previous noisy sample x_t -> x_t-1 __a = self.scheduler.step(lowerCamelCase , lowerCamelCase , lowerCamelCase , **lowerCamelCase ).prev_sample # call the callback, if provided if callback is not None and i % callback_steps == 0: callback(lowerCamelCase , lowerCamelCase , lowerCamelCase ) __a = 1 / 0.1_8215 * latents __a = self.vae.decode(lowerCamelCase ).sample __a = (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 = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if self.safety_checker is not None: __a = self.feature_extractor(self.numpy_to_pil(lowerCamelCase ) , return_tensors="pt" ).to( self.device ) __a , __a = self.safety_checker( images=lowerCamelCase , clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) ) else: __a = None if output_type == "pil": __a = self.numpy_to_pil(lowerCamelCase ) if not return_dict: return (image, has_nsfw_concept) return StableDiffusionPipelineOutput(images=lowerCamelCase , nsfw_content_detected=lowerCamelCase )
709
"""simple docstring""" from .imports import is_rich_available if is_rich_available(): from rich.traceback import install install(show_locals=False) else: raise ModuleNotFoundError("""To use the rich extension, install rich with `pip install rich`""")
67
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE__:Any = { """configuration_lxmert""": ["""LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LxmertConfig"""], """tokenization_lxmert""": ["""LxmertTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__:str = ["""LxmertTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__:Optional[Any] = [ """LxmertEncoder""", """LxmertForPreTraining""", """LxmertForQuestionAnswering""", """LxmertModel""", """LxmertPreTrainedModel""", """LxmertVisualFeatureEncoder""", """LxmertXLayer""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__:List[Any] = [ """TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFLxmertForPreTraining""", """TFLxmertMainLayer""", """TFLxmertModel""", """TFLxmertPreTrainedModel""", """TFLxmertVisualFeatureEncoder""", ] if TYPE_CHECKING: from .configuration_lxmert import LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, LxmertConfig from .tokenization_lxmert import LxmertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_lxmert_fast import LxmertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lxmert import ( LxmertEncoder, LxmertForPreTraining, LxmertForQuestionAnswering, LxmertModel, LxmertPreTrainedModel, LxmertVisualFeatureEncoder, LxmertXLayer, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_lxmert import ( TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFLxmertForPreTraining, TFLxmertMainLayer, TFLxmertModel, TFLxmertPreTrainedModel, TFLxmertVisualFeatureEncoder, ) else: import sys SCREAMING_SNAKE_CASE__:Optional[int] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
710
"""simple docstring""" import heapq import sys import numpy as np SCREAMING_SNAKE_CASE__:Optional[int] = tuple[int, int] class snake_case__ : def __init__( self ): __a = [] __a = set() def a__ ( self ): if not self.empty(): return self.elements[0][0] else: return float("inf" ) def a__ ( self ): return len(self.elements ) == 0 def a__ ( self , lowerCamelCase , lowerCamelCase ): if item not in self.set: heapq.heappush(self.elements , (priority, item) ) self.set.add(lowerCamelCase ) else: # update # print("update", item) __a = [] ((__a) , (__a)) = heapq.heappop(self.elements ) while x != item: temp.append((pri, x) ) ((__a) , (__a)) = heapq.heappop(self.elements ) temp.append((priority, item) ) for pro, xxx in temp: heapq.heappush(self.elements , (pro, xxx) ) def a__ ( self , lowerCamelCase ): if item in self.set: self.set.remove(lowerCamelCase ) __a = [] ((__a) , (__a)) = heapq.heappop(self.elements ) while x != item: temp.append((pro, x) ) ((__a) , (__a)) = heapq.heappop(self.elements ) for prito, yyy in temp: heapq.heappush(self.elements , (prito, yyy) ) def a__ ( self ): return self.elements[0][1] def a__ ( self ): ((__a) , (__a)) = heapq.heappop(self.elements ) self.set.remove(lowerCamelCase ) return (priority, item) def _lowerCamelCase( a , a ): # euclidean distance __a = np.array(a ) __a = np.array(a ) return np.linalg.norm(a - b ) def _lowerCamelCase( a , a ): # integer division by time variable return consistent_heuristic(a , a ) // t def _lowerCamelCase( a , a ): # manhattan distance return abs(p[0] - goal[0] ) + abs(p[1] - goal[1] ) def _lowerCamelCase( a , a , a , a ): __a = g_function[start] + Wa * heuristics[i](a , a ) return ans def _lowerCamelCase( a , a , a ): __a = np.chararray((n, n) ) for i in range(a ): for j in range(a ): __a = "*" for i in range(a ): for j in range(a ): if (j, (n - 1) - i) in blocks: __a = "#" __a = "-" __a = back_pointer[goal] while x != start: ((__a) , (__a)) = x # print(x) __a = "-" __a = back_pointer[x] __a = "-" for i in range(a ): for j in range(a ): if (i, j) == (0, n - 1): print(grid[i][j] , end=" " ) print("<-- End position" , end=" " ) else: print(grid[i][j] , end=" " ) print() print("^" ) print("Start position" ) print() print("# is an obstacle" ) print("- is the path taken by algorithm" ) print("PATH TAKEN BY THE ALGORITHM IS:-" ) __a = back_pointer[goal] while x != start: print(a , end=" " ) __a = back_pointer[x] print(a ) sys.exit() def _lowerCamelCase( a ): if p[0] < 0 or p[0] > n - 1: return False if p[1] < 0 or p[1] > n - 1: return False return True def _lowerCamelCase( a , a , a , a , a , a , a , a , ): for itera in range(a ): open_list[itera].remove_element(a ) # print("s", s) # print("j", j) ((__a) , (__a)) = s __a = (x - 1, y) __a = (x + 1, y) __a = (x, y + 1) __a = (x, y - 1) for neighbours in [left, right, up, down]: if neighbours not in blocks: if valid(a ) and neighbours not in visited: # print("neighbour", neighbours) visited.add(a ) __a = -1 __a = float("inf" ) if valid(a ) and g_function[neighbours] > g_function[s] + 1: __a = g_function[s] + 1 __a = s if neighbours not in close_list_anchor: open_list[0].put(a , key(a , 0 , a , a ) ) if neighbours not in close_list_inad: for var in range(1 , a ): if key(a , a , a , a ) <= Wa * key( a , 0 , a , a ): open_list[j].put( a , key(a , a , a , a ) ) def _lowerCamelCase( ): __a = [] for x in range(1 , 5 ): for y in range(1 , 6 ): some_list.append((x, y) ) for x in range(1_5 , 2_0 ): some_list.append((x, 1_7) ) for x in range(1_0 , 1_9 ): for y in range(1 , 1_5 ): some_list.append((x, y) ) # L block for x in range(1 , 4 ): for y in range(1_2 , 1_9 ): some_list.append((x, y) ) for x in range(3 , 1_3 ): for y in range(1_6 , 1_9 ): some_list.append((x, y) ) return some_list SCREAMING_SNAKE_CASE__:Any = {0: consistent_heuristic, 1: heuristic_a, 2: heuristic_a} SCREAMING_SNAKE_CASE__:str = [ (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1), ] SCREAMING_SNAKE_CASE__:int = make_common_ground() SCREAMING_SNAKE_CASE__:List[str] = blocks_blk # hyper parameters SCREAMING_SNAKE_CASE__:str = 1 SCREAMING_SNAKE_CASE__:Union[str, Any] = 1 SCREAMING_SNAKE_CASE__:Union[str, Any] = 20 SCREAMING_SNAKE_CASE__:Dict = 3 # one consistent and two other inconsistent # start and end destination SCREAMING_SNAKE_CASE__:Dict = (0, 0) SCREAMING_SNAKE_CASE__:Optional[Any] = (n - 1, n - 1) SCREAMING_SNAKE_CASE__:List[str] = 1 def _lowerCamelCase( a , a , a ): __a = {start: 0, goal: float("inf" )} __a = {start: -1, goal: -1} __a = [] __a = set() for i in range(a ): open_list.append(PriorityQueue() ) open_list[i].put(a , key(a , a , a , a ) ) __a = [] __a = [] while open_list[0].minkey() < float("inf" ): for i in range(1 , a ): # print(open_list[0].minkey(), open_list[i].minkey()) if open_list[i].minkey() <= Wa * open_list[0].minkey(): global t t += 1 if g_function[goal] <= open_list[i].minkey(): if g_function[goal] < float("inf" ): do_something(a , a , a ) else: __a , __a = open_list[i].top_show() visited.add(a ) expand_state( a , a , a , a , a , a , a , a , ) close_list_inad.append(a ) else: if g_function[goal] <= open_list[0].minkey(): if g_function[goal] < float("inf" ): do_something(a , a , a ) else: __a = open_list[0].top_show() visited.add(a ) expand_state( a , 0 , a , a , a , a , a , a , ) close_list_anchor.append(a ) print("No path found to goal" ) print() for i in range(n - 1 , -1 , -1 ): for j in range(a ): if (j, i) in blocks: print("#" , end=" " ) elif (j, i) in back_pointer: if (j, i) == (n - 1, n - 1): print("*" , end=" " ) else: print("-" , end=" " ) else: print("*" , end=" " ) if (j, i) == (n - 1, n - 1): print("<-- End position" , end=" " ) print() print("^" ) print("Start position" ) print() print("# is an obstacle" ) print("- is the path taken by algorithm" ) if __name__ == "__main__": multi_a_star(start, goal, n_heuristic)
67
0
"""simple docstring""" from typing import Any, Callable, Dict, List, Optional, Union import torch from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPipeline, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker SCREAMING_SNAKE_CASE__:int = """CompVis/stable-diffusion-v1-1""" SCREAMING_SNAKE_CASE__:Tuple = """CompVis/stable-diffusion-v1-2""" SCREAMING_SNAKE_CASE__:int = """CompVis/stable-diffusion-v1-3""" SCREAMING_SNAKE_CASE__:str = """CompVis/stable-diffusion-v1-4""" class snake_case__ ( snake_case_ ): def __init__( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase = True , ): super()._init_() __a = StableDiffusionPipeline.from_pretrained(lowerCamelCase ) __a = StableDiffusionPipeline.from_pretrained(lowerCamelCase ) __a = StableDiffusionPipeline.from_pretrained(lowerCamelCase ) __a = StableDiffusionPipeline( vae=lowerCamelCase , text_encoder=lowerCamelCase , tokenizer=lowerCamelCase , unet=lowerCamelCase , scheduler=lowerCamelCase , safety_checker=lowerCamelCase , feature_extractor=lowerCamelCase , requires_safety_checker=lowerCamelCase , ) self.register_modules(pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea , pipelinea=self.pipea ) @property def a__ ( self ): return {k: getattr(self , lowerCamelCase ) for k in self.config.keys() if not k.startswith("_" )} def a__ ( self , lowerCamelCase = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory __a = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(lowerCamelCase ) def a__ ( self ): self.enable_attention_slicing(lowerCamelCase ) @torch.no_grad() def a__ ( self , lowerCamelCase , lowerCamelCase = 512 , lowerCamelCase = 512 , lowerCamelCase = 50 , lowerCamelCase = 7.5 , lowerCamelCase = None , lowerCamelCase = 1 , lowerCamelCase = 0.0 , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = "pil" , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = 1 , **lowerCamelCase , ): return self.pipea( prompt=lowerCamelCase , height=lowerCamelCase , width=lowerCamelCase , num_inference_steps=lowerCamelCase , guidance_scale=lowerCamelCase , negative_prompt=lowerCamelCase , num_images_per_prompt=lowerCamelCase , eta=lowerCamelCase , generator=lowerCamelCase , latents=lowerCamelCase , output_type=lowerCamelCase , return_dict=lowerCamelCase , callback=lowerCamelCase , callback_steps=lowerCamelCase , **lowerCamelCase , ) @torch.no_grad() def a__ ( self , lowerCamelCase , lowerCamelCase = 512 , lowerCamelCase = 512 , lowerCamelCase = 50 , lowerCamelCase = 7.5 , lowerCamelCase = None , lowerCamelCase = 1 , lowerCamelCase = 0.0 , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = "pil" , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = 1 , **lowerCamelCase , ): return self.pipea( prompt=lowerCamelCase , height=lowerCamelCase , width=lowerCamelCase , num_inference_steps=lowerCamelCase , guidance_scale=lowerCamelCase , negative_prompt=lowerCamelCase , num_images_per_prompt=lowerCamelCase , eta=lowerCamelCase , generator=lowerCamelCase , latents=lowerCamelCase , output_type=lowerCamelCase , return_dict=lowerCamelCase , callback=lowerCamelCase , callback_steps=lowerCamelCase , **lowerCamelCase , ) @torch.no_grad() def a__ ( self , lowerCamelCase , lowerCamelCase = 512 , lowerCamelCase = 512 , lowerCamelCase = 50 , lowerCamelCase = 7.5 , lowerCamelCase = None , lowerCamelCase = 1 , lowerCamelCase = 0.0 , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = "pil" , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = 1 , **lowerCamelCase , ): return self.pipea( prompt=lowerCamelCase , height=lowerCamelCase , width=lowerCamelCase , num_inference_steps=lowerCamelCase , guidance_scale=lowerCamelCase , negative_prompt=lowerCamelCase , num_images_per_prompt=lowerCamelCase , eta=lowerCamelCase , generator=lowerCamelCase , latents=lowerCamelCase , output_type=lowerCamelCase , return_dict=lowerCamelCase , callback=lowerCamelCase , callback_steps=lowerCamelCase , **lowerCamelCase , ) @torch.no_grad() def a__ ( self , lowerCamelCase , lowerCamelCase = 512 , lowerCamelCase = 512 , lowerCamelCase = 50 , lowerCamelCase = 7.5 , lowerCamelCase = None , lowerCamelCase = 1 , lowerCamelCase = 0.0 , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = "pil" , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = 1 , **lowerCamelCase , ): return self.pipea( prompt=lowerCamelCase , height=lowerCamelCase , width=lowerCamelCase , num_inference_steps=lowerCamelCase , guidance_scale=lowerCamelCase , negative_prompt=lowerCamelCase , num_images_per_prompt=lowerCamelCase , eta=lowerCamelCase , generator=lowerCamelCase , latents=lowerCamelCase , output_type=lowerCamelCase , return_dict=lowerCamelCase , callback=lowerCamelCase , callback_steps=lowerCamelCase , **lowerCamelCase , ) @torch.no_grad() def a__ ( self , lowerCamelCase , lowerCamelCase = 512 , lowerCamelCase = 512 , lowerCamelCase = 50 , lowerCamelCase = 7.5 , lowerCamelCase = None , lowerCamelCase = 1 , lowerCamelCase = 0.0 , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = "pil" , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = 1 , **lowerCamelCase , ): __a = "cuda" if torch.cuda.is_available() else "cpu" self.to(lowerCamelCase ) # Checks if the height and width are divisible by 8 or not if height % 8 != 0 or width % 8 != 0: raise ValueError(F"`height` and `width` must be divisible by 8 but are {height} and {width}." ) # Get first result from Stable Diffusion Checkpoint v1.1 __a = self.textaimg_sda_a( prompt=lowerCamelCase , height=lowerCamelCase , width=lowerCamelCase , num_inference_steps=lowerCamelCase , guidance_scale=lowerCamelCase , negative_prompt=lowerCamelCase , num_images_per_prompt=lowerCamelCase , eta=lowerCamelCase , generator=lowerCamelCase , latents=lowerCamelCase , output_type=lowerCamelCase , return_dict=lowerCamelCase , callback=lowerCamelCase , callback_steps=lowerCamelCase , **lowerCamelCase , ) # Get first result from Stable Diffusion Checkpoint v1.2 __a = self.textaimg_sda_a( prompt=lowerCamelCase , height=lowerCamelCase , width=lowerCamelCase , num_inference_steps=lowerCamelCase , guidance_scale=lowerCamelCase , negative_prompt=lowerCamelCase , num_images_per_prompt=lowerCamelCase , eta=lowerCamelCase , generator=lowerCamelCase , latents=lowerCamelCase , output_type=lowerCamelCase , return_dict=lowerCamelCase , callback=lowerCamelCase , callback_steps=lowerCamelCase , **lowerCamelCase , ) # Get first result from Stable Diffusion Checkpoint v1.3 __a = self.textaimg_sda_a( prompt=lowerCamelCase , height=lowerCamelCase , width=lowerCamelCase , num_inference_steps=lowerCamelCase , guidance_scale=lowerCamelCase , negative_prompt=lowerCamelCase , num_images_per_prompt=lowerCamelCase , eta=lowerCamelCase , generator=lowerCamelCase , latents=lowerCamelCase , output_type=lowerCamelCase , return_dict=lowerCamelCase , callback=lowerCamelCase , callback_steps=lowerCamelCase , **lowerCamelCase , ) # Get first result from Stable Diffusion Checkpoint v1.4 __a = self.textaimg_sda_a( prompt=lowerCamelCase , height=lowerCamelCase , width=lowerCamelCase , num_inference_steps=lowerCamelCase , guidance_scale=lowerCamelCase , negative_prompt=lowerCamelCase , num_images_per_prompt=lowerCamelCase , eta=lowerCamelCase , generator=lowerCamelCase , latents=lowerCamelCase , output_type=lowerCamelCase , return_dict=lowerCamelCase , callback=lowerCamelCase , callback_steps=lowerCamelCase , **lowerCamelCase , ) # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]] )
711
"""simple docstring""" SCREAMING_SNAKE_CASE__:Any = """Alexander Joslin""" import operator as op from .stack import Stack def _lowerCamelCase( a ): __a = {"*": op.mul, "/": op.truediv, "+": op.add, "-": op.sub} __a = Stack() __a = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(a ) ) elif i in operators: # RULE 2 operator_stack.push(a ) elif i == ")": # RULE 4 __a = operator_stack.peek() operator_stack.pop() __a = operand_stack.peek() operand_stack.pop() __a = operand_stack.peek() operand_stack.pop() __a = operators[opr](a , a ) operand_stack.push(a ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": SCREAMING_SNAKE_CASE__:Tuple = """(5 + ((4 * 2) * (2 + 3)))""" # answer = 45 print(F'''{equation} = {dijkstras_two_stack_algorithm(equation)}''')
67
0
"""simple docstring""" from __future__ import annotations from collections import deque class snake_case__ : def __init__( self , lowerCamelCase ): __a = [] self.adlist.append( {"value": "", "next_states": [], "fail_state": 0, "output": []} ) for keyword in keywords: self.add_keyword(lowerCamelCase ) self.set_fail_transitions() def a__ ( self , lowerCamelCase , lowerCamelCase ): for state in self.adlist[current_state]["next_states"]: if char == self.adlist[state]["value"]: return state return None def a__ ( self , lowerCamelCase ): __a = 0 for character in keyword: __a = self.find_next_state(lowerCamelCase , lowerCamelCase ) if next_state is None: self.adlist.append( { "value": character, "next_states": [], "fail_state": 0, "output": [], } ) self.adlist[current_state]["next_states"].append(len(self.adlist ) - 1 ) __a = len(self.adlist ) - 1 else: __a = next_state self.adlist[current_state]["output"].append(lowerCamelCase ) def a__ ( self ): __a = deque() for node in self.adlist[0]["next_states"]: q.append(lowerCamelCase ) __a = 0 while q: __a = q.popleft() for child in self.adlist[r]["next_states"]: q.append(lowerCamelCase ) __a = self.adlist[r]["fail_state"] while ( self.find_next_state(lowerCamelCase , self.adlist[child]["value"] ) is None and state != 0 ): __a = self.adlist[state]["fail_state"] __a = self.find_next_state( lowerCamelCase , self.adlist[child]["value"] ) if self.adlist[child]["fail_state"] is None: __a = 0 __a = ( self.adlist[child]["output"] + self.adlist[self.adlist[child]["fail_state"]]["output"] ) def a__ ( self , lowerCamelCase ): __a = {} # returns a dict with keywords and list of its occurrences __a = 0 for i in range(len(lowerCamelCase ) ): while ( self.find_next_state(lowerCamelCase , string[i] ) is None and current_state != 0 ): __a = self.adlist[current_state]["fail_state"] __a = self.find_next_state(lowerCamelCase , string[i] ) if next_state is None: __a = 0 else: __a = next_state for key in self.adlist[current_state]["output"]: if key not in result: __a = [] result[key].append(i - len(lowerCamelCase ) + 1 ) return result if __name__ == "__main__": import doctest doctest.testmod()
712
"""simple docstring""" from math import pi def _lowerCamelCase( a , a ): return 2 * pi * radius * (angle / 3_6_0) if __name__ == "__main__": print(arc_length(90, 10))
67
0
def _lowerCamelCase( a = 4_0_0_0_0_0_0 ): __a = [] __a , __a = 0, 1 while b <= n: if b % 2 == 0: even_fibs.append(a ) __a , __a = b, a + b return sum(a ) if __name__ == "__main__": print(F'''{solution() = }''')
713
"""simple docstring""" from typing import Dict, Iterable, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging SCREAMING_SNAKE_CASE__:List[str] = logging.get_logger(__name__) class snake_case__ ( snake_case_ ): _snake_case : Dict = ["""pixel_values"""] def __init__( self , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = PILImageResampling.BICUBIC , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = True , lowerCamelCase = 1 / 255 , lowerCamelCase = True , lowerCamelCase = IMAGENET_DEFAULT_MEAN , lowerCamelCase = IMAGENET_DEFAULT_STD , **lowerCamelCase , ): super().__init__(**lowerCamelCase ) __a = size if size is not None else {"shortest_edge": 224} __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) __a = crop_size if crop_size is not None else {"height": 224, "width": 224} __a = get_size_dict(lowerCamelCase , param_name="crop_size" ) __a = do_resize __a = size __a = resample __a = do_center_crop __a = crop_size __a = do_rescale __a = rescale_factor __a = do_normalize __a = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN __a = image_std if image_std is not None else IMAGENET_DEFAULT_STD def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = PILImageResampling.BICUBIC , lowerCamelCase = None , **lowerCamelCase , ): __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) # size_dict is a dict with either keys "height" and "width" or "shortest_edge" if "shortest_edge" in size: __a = int((256 / 224) * size["shortest_edge"] ) __a = get_resize_output_image_size(lowerCamelCase , size=lowerCamelCase , default_to_square=lowerCamelCase ) __a = {"height": output_size[0], "width": output_size[1]} if "height" not in size_dict or "width" not in size_dict: raise ValueError( F"Size dict must have keys 'height' and 'width' or 'shortest_edge'. Got {size_dict.keys()}" ) return resize( lowerCamelCase , size=(size_dict["height"], size_dict["width"]) , resample=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): __a = get_size_dict(lowerCamelCase ) if "height" not in size or "width" not in size: raise ValueError(F"Size dict must have keys 'height' and 'width'. Got {size.keys()}" ) return center_crop(lowerCamelCase , size=(size["height"], size["width"]) , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): return rescale(lowerCamelCase , scale=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): return normalize(lowerCamelCase , mean=lowerCamelCase , std=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = ChannelDimension.FIRST , **lowerCamelCase , ): __a = do_resize if do_resize is not None else self.do_resize __a = resample if resample is not None else self.resample __a = do_center_crop if do_center_crop is not None else self.do_center_crop __a = do_rescale if do_rescale is not None else self.do_rescale __a = rescale_factor if rescale_factor is not None else self.rescale_factor __a = do_normalize if do_normalize is not None else self.do_normalize __a = image_mean if image_mean is not None else self.image_mean __a = image_std if image_std is not None else self.image_std __a = size if size is not None else self.size __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) __a = crop_size if crop_size is not None else self.crop_size __a = get_size_dict(lowerCamelCase , param_name="crop_size" ) __a = make_list_of_images(lowerCamelCase ) if not valid_images(lowerCamelCase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. __a = [to_numpy_array(lowerCamelCase ) for image in images] if do_resize: __a = [self.resize(lowerCamelCase , lowerCamelCase , lowerCamelCase ) for image in images] if do_center_crop: __a = [self.center_crop(lowerCamelCase , lowerCamelCase ) for image in images] if do_rescale: __a = [self.rescale(lowerCamelCase , lowerCamelCase ) for image in images] if do_normalize: __a = [self.normalize(lowerCamelCase , lowerCamelCase , lowerCamelCase ) for image in images] __a = [to_channel_dimension_format(lowerCamelCase , lowerCamelCase ) for image in images] __a = {"pixel_values": images} return BatchFeature(data=lowerCamelCase , tensor_type=lowerCamelCase )
67
0
"""simple docstring""" import os import tempfile import unittest import numpy as np from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp from flax.jax_utils import replicate from flax.training.common_utils import shard from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline @require_flax class snake_case__ ( unittest.TestCase ): def a__ ( self ): with tempfile.TemporaryDirectory() as tmpdirname: # pipeline has Flax weights __a = FlaxDiffusionPipeline.from_pretrained( "hf-internal-testing/tiny-stable-diffusion-pipe" , safety_checker=lowerCamelCase , cache_dir=lowerCamelCase ) __a = [t[-1] for t in os.walk(os.path.join(lowerCamelCase , os.listdir(lowerCamelCase )[0] , "snapshots" ) )] __a = [item for sublist in all_root_files for item in sublist] # None of the downloaded files should be a PyTorch file even if we have some here: # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin assert not any(f.endswith(".bin" ) for f in files ) @slow @require_flax class snake_case__ ( unittest.TestCase ): def a__ ( self ): __a , __a = FlaxStableDiffusionPipeline.from_pretrained( "hf-internal-testing/tiny-stable-diffusion-pipe" , safety_checker=lowerCamelCase ) __a = ( "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of" " field, close up, split lighting, cinematic" ) __a = jax.random.PRNGKey(0 ) __a = 4 __a = jax.device_count() __a = num_samples * [prompt] __a = pipeline.prepare_inputs(lowerCamelCase ) # shard inputs and rng __a = replicate(lowerCamelCase ) __a = jax.random.split(lowerCamelCase , lowerCamelCase ) __a = shard(lowerCamelCase ) __a = pipeline(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , jit=lowerCamelCase ).images assert images.shape == (num_samples, 1, 64, 64, 3) if jax.device_count() == 8: assert np.abs(np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 4.151_4745 ) < 1E-3 assert np.abs(np.abs(lowerCamelCase , dtype=np.floataa ).sum() - 49947.875 ) < 5E-1 __a = pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:] ) ) ) assert len(lowerCamelCase ) == num_samples def a__ ( self ): __a , __a = FlaxStableDiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4" , revision="flax" , safety_checker=lowerCamelCase ) __a = ( "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of" " field, close up, split lighting, cinematic" ) __a = jax.random.PRNGKey(0 ) __a = 50 __a = jax.device_count() __a = num_samples * [prompt] __a = pipeline.prepare_inputs(lowerCamelCase ) # shard inputs and rng __a = replicate(lowerCamelCase ) __a = jax.random.split(lowerCamelCase , lowerCamelCase ) __a = shard(lowerCamelCase ) __a = pipeline(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , jit=lowerCamelCase ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.0565_2401) ) < 1E-3 assert np.abs((np.abs(lowerCamelCase , dtype=np.floataa ).sum() - 2383808.2) ) < 5E-1 def a__ ( self ): __a , __a = FlaxStableDiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4" , revision="bf16" , dtype=jnp.bfloataa , safety_checker=lowerCamelCase ) __a = ( "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of" " field, close up, split lighting, cinematic" ) __a = jax.random.PRNGKey(0 ) __a = 50 __a = jax.device_count() __a = num_samples * [prompt] __a = pipeline.prepare_inputs(lowerCamelCase ) # shard inputs and rng __a = replicate(lowerCamelCase ) __a = jax.random.split(lowerCamelCase , lowerCamelCase ) __a = shard(lowerCamelCase ) __a = pipeline(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , jit=lowerCamelCase ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.0400_3906) ) < 1E-3 assert np.abs((np.abs(lowerCamelCase , dtype=np.floataa ).sum() - 2373516.75) ) < 5E-1 def a__ ( self ): __a , __a = FlaxStableDiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4" , revision="bf16" , dtype=jnp.bfloataa ) __a = ( "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of" " field, close up, split lighting, cinematic" ) __a = jax.random.PRNGKey(0 ) __a = 50 __a = jax.device_count() __a = num_samples * [prompt] __a = pipeline.prepare_inputs(lowerCamelCase ) # shard inputs and rng __a = replicate(lowerCamelCase ) __a = jax.random.split(lowerCamelCase , lowerCamelCase ) __a = shard(lowerCamelCase ) __a = pipeline(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , jit=lowerCamelCase ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.0400_3906) ) < 1E-3 assert np.abs((np.abs(lowerCamelCase , dtype=np.floataa ).sum() - 2373516.75) ) < 5E-1 def a__ ( self ): __a = FlaxDDIMScheduler( beta_start=0.0_0085 , beta_end=0.012 , beta_schedule="scaled_linear" , set_alpha_to_one=lowerCamelCase , steps_offset=1 , ) __a , __a = FlaxStableDiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4" , revision="bf16" , dtype=jnp.bfloataa , scheduler=lowerCamelCase , safety_checker=lowerCamelCase , ) __a = scheduler.create_state() __a = scheduler_state __a = ( "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of" " field, close up, split lighting, cinematic" ) __a = jax.random.PRNGKey(0 ) __a = 50 __a = jax.device_count() __a = num_samples * [prompt] __a = pipeline.prepare_inputs(lowerCamelCase ) # shard inputs and rng __a = replicate(lowerCamelCase ) __a = jax.random.split(lowerCamelCase , lowerCamelCase ) __a = shard(lowerCamelCase ) __a = pipeline(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , jit=lowerCamelCase ).images assert images.shape == (num_samples, 1, 512, 512, 3) if jax.device_count() == 8: assert np.abs((np.abs(images[0, 0, :2, :2, -2:] , dtype=np.floataa ).sum() - 0.0_4504_3945) ) < 1E-3 assert np.abs((np.abs(lowerCamelCase , dtype=np.floataa ).sum() - 2347693.5) ) < 5E-1 def a__ ( self ): __a = ( "A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of" " field, close up, split lighting, cinematic" ) __a = jax.device_count() __a = num_samples * [prompt] __a = jax.random.split(jax.random.PRNGKey(0 ) , lowerCamelCase ) __a , __a = FlaxStableDiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4" , revision="bf16" , dtype=jnp.bfloataa , safety_checker=lowerCamelCase , ) __a = replicate(lowerCamelCase ) __a = pipeline.prepare_inputs(lowerCamelCase ) __a = shard(lowerCamelCase ) __a = pipeline(lowerCamelCase , lowerCamelCase , lowerCamelCase , jit=lowerCamelCase ).images assert images.shape == (num_samples, 1, 512, 512, 3) __a = images[2, 0, 256, 10:17, 1] # With memory efficient attention __a , __a = FlaxStableDiffusionPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4" , revision="bf16" , dtype=jnp.bfloataa , safety_checker=lowerCamelCase , use_memory_efficient_attention=lowerCamelCase , ) __a = replicate(lowerCamelCase ) __a = pipeline.prepare_inputs(lowerCamelCase ) __a = shard(lowerCamelCase ) __a = pipeline(lowerCamelCase , lowerCamelCase , lowerCamelCase , jit=lowerCamelCase ).images assert images_eff.shape == (num_samples, 1, 512, 512, 3) __a = images[2, 0, 256, 10:17, 1] # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum` # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now. assert abs(slice_eff - slice ).max() < 1E-2
714
"""simple docstring""" import inspect import unittest from transformers import ViTConfig 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 ViTForImageClassification, ViTForMaskedImageModeling, ViTModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class snake_case__ : 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=None , lowerCamelCase=2 , ): __a = parent __a = batch_size __a = image_size __a = patch_size __a = num_channels __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 = encoder_stride # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) __a = (image_size // patch_size) ** 2 __a = num_patches + 1 def a__ ( self ): __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = self.get_config() return config, pixel_values, labels def a__ ( self ): return ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=lowerCamelCase , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = ViTModel(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = ViTForMaskedImageModeling(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __a = 1 __a = ViTForMaskedImageModeling(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __a = model(lowerCamelCase ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = self.type_sequence_label_size __a = ViTForImageClassification(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __a = 1 __a = ViTForImageClassification(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __a = model(lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a__ ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class snake_case__ ( snake_case_, snake_case_, unittest.TestCase ): _snake_case : Any = ( ( ViTModel, ViTForImageClassification, ViTForMaskedImageModeling, ) if is_torch_available() else () ) _snake_case : List[Any] = ( {"""feature-extraction""": ViTModel, """image-classification""": ViTForImageClassification} if is_torch_available() else {} ) _snake_case : int = True _snake_case : int = False _snake_case : str = False _snake_case : Optional[Any] = False def a__ ( self ): __a = ViTModelTester(self ) __a = ConfigTester(self , config_class=lowerCamelCase , has_text_modality=lowerCamelCase , hidden_size=37 ) def a__ ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="ViT does not use inputs_embeds" ) def a__ ( self ): pass def a__ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __a = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCamelCase , nn.Linear ) ) def a__ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(lowerCamelCase ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase ) @slow def a__ ( self ): for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = ViTModel.from_pretrained(lowerCamelCase ) self.assertIsNotNone(lowerCamelCase ) def _lowerCamelCase( ): __a = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class snake_case__ ( unittest.TestCase ): @cached_property def a__ ( self ): return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224" ) if is_vision_available() else None @slow def a__ ( self ): __a = ViTForImageClassification.from_pretrained("google/vit-base-patch16-224" ).to(lowerCamelCase ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase ) # forward pass with torch.no_grad(): __a = model(**lowerCamelCase ) # verify the logits __a = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , lowerCamelCase ) __a = torch.tensor([-0.2744, 0.8215, -0.0836] ).to(lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCamelCase , atol=1E-4 ) ) @slow def a__ ( self ): # ViT models have an `interpolate_pos_encoding` argument in their forward method, # allowing to interpolate the pre-trained position embeddings in order to use # the model on higher resolutions. The DINO model by Facebook AI leverages this # to visualize self-attention on higher resolution images. __a = ViTModel.from_pretrained("facebook/dino-vits8" ).to(lowerCamelCase ) __a = ViTImageProcessor.from_pretrained("facebook/dino-vits8" , size=480 ) __a = prepare_img() __a = image_processor(images=lowerCamelCase , return_tensors="pt" ) __a = inputs.pixel_values.to(lowerCamelCase ) # forward pass with torch.no_grad(): __a = model(lowerCamelCase , interpolate_pos_encoding=lowerCamelCase ) # verify the logits __a = torch.Size((1, 3601, 384) ) self.assertEqual(outputs.last_hidden_state.shape , lowerCamelCase ) __a = torch.tensor( [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]] ).to(lowerCamelCase ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , lowerCamelCase , atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def a__ ( self ): __a = ViTModel.from_pretrained("facebook/dino-vits8" , torch_dtype=torch.floataa , device_map="auto" ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=lowerCamelCase , return_tensors="pt" ) __a = inputs.pixel_values.to(lowerCamelCase ) # forward pass to make sure inference works in fp16 with torch.no_grad(): __a = model(lowerCamelCase )
67
0
"""simple docstring""" from collections import deque from .hash_table import HashTable class snake_case__ ( snake_case_ ): def __init__( self , *lowerCamelCase , **lowerCamelCase ): super().__init__(*lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase ): __a = deque([] ) if self.values[key] is None else self.values[key] self.values[key].appendleft(lowerCamelCase ) __a = self.values[key] def a__ ( self ): return ( sum(self.charge_factor - len(lowerCamelCase ) for slot in self.values ) / self.size_table * self.charge_factor ) def a__ ( self , lowerCamelCase , lowerCamelCase=None ): if not ( len(self.values[key] ) == self.charge_factor and self.values.count(lowerCamelCase ) == 0 ): return key return super()._collision_resolution(lowerCamelCase , lowerCamelCase )
715
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetaImageProcessor class snake_case__ ( unittest.TestCase ): def __init__( self , lowerCamelCase , lowerCamelCase=7 , lowerCamelCase=3 , lowerCamelCase=30 , lowerCamelCase=400 , lowerCamelCase=True , lowerCamelCase=None , lowerCamelCase=True , lowerCamelCase=[0.5, 0.5, 0.5] , lowerCamelCase=[0.5, 0.5, 0.5] , lowerCamelCase=True , lowerCamelCase=1 / 255 , lowerCamelCase=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __a = size if size is not None else {"shortest_edge": 18, "longest_edge": 1333} __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 a__ ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def a__ ( self , lowerCamelCase , lowerCamelCase=False ): if not batched: __a = image_inputs[0] if isinstance(lowerCamelCase , Image.Image ): __a , __a = image.size else: __a , __a = image.shape[1], image.shape[2] if w < h: __a = int(self.size["shortest_edge"] * h / w ) __a = self.size["shortest_edge"] elif w > h: __a = self.size["shortest_edge"] __a = int(self.size["shortest_edge"] * w / h ) else: __a = self.size["shortest_edge"] __a = self.size["shortest_edge"] else: __a = [] for image in image_inputs: __a , __a = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __a = max(lowerCamelCase , key=lambda lowerCamelCase : item[0] )[0] __a = max(lowerCamelCase , key=lambda lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case__ ( snake_case_, unittest.TestCase ): _snake_case : List[Any] = DetaImageProcessor if is_vision_available() else None def a__ ( self ): __a = DetaImageProcessingTester(self ) @property def a__ ( self ): return self.image_processor_tester.prepare_image_processor_dict() def a__ ( self ): __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_rescale" ) ) self.assertTrue(hasattr(lowerCamelCase , "do_pad" ) ) self.assertTrue(hasattr(lowerCamelCase , "size" ) ) def a__ ( self ): __a = 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 , lowerCamelCase ) def a__ ( self ): pass def a__ ( self ): # 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 __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) __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, expected_height, expected_width, ) , ) def a__ ( self ): # 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 __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def a__ ( self ): # 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 __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def a__ ( self ): # prepare image and target __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": 39769, "annotations": target} # encode them __a = DetaImageProcessor() __a = image_processing(images=lowerCamelCase , annotations=lowerCamelCase , return_tensors="pt" ) # verify pixel values __a = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase ) __a = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase , atol=1E-4 ) ) # verify area __a = 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"] , lowerCamelCase ) ) # verify boxes __a = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase ) __a = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase , atol=1E-3 ) ) # verify image_id __a = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase ) ) # verify is_crowd __a = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase ) ) # verify class_labels __a = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase ) ) # verify orig_size __a = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase ) ) # verify size __a = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase ) ) @slow def a__ ( self ): # prepare image, target and masks_path __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": 39769, "segments_info": target} __a = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them __a = DetaImageProcessor(format="coco_panoptic" ) __a = image_processing(images=lowerCamelCase , annotations=lowerCamelCase , masks_path=lowerCamelCase , return_tensors="pt" ) # verify pixel values __a = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase ) __a = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase , atol=1E-4 ) ) # verify area __a = 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"] , lowerCamelCase ) ) # verify boxes __a = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase ) __a = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase , atol=1E-3 ) ) # verify image_id __a = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase ) ) # verify is_crowd __a = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase ) ) # verify class_labels __a = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase ) ) # verify masks __a = 822873 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , lowerCamelCase ) # verify orig_size __a = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase ) ) # verify size __a = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase ) )
67
0
"""simple docstring""" def _lowerCamelCase( a , a ): if not isinstance(a , a ): raise ValueError("iterations must be defined as integers" ) if not isinstance(a , a ) or not number >= 1: raise ValueError( "starting number must be\n and integer and be more than 0" ) if not iterations >= 1: raise ValueError("Iterations must be done more than 0 times to play FizzBuzz" ) __a = "" 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(a ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
716
"""simple docstring""" import argparse import logging import sys from unittest.mock import patch import run_glue_deebert from transformers.testing_utils import TestCasePlus, get_gpu_count, require_torch_non_multi_gpu, slow logging.basicConfig(level=logging.DEBUG) SCREAMING_SNAKE_CASE__:Dict = logging.getLogger() def _lowerCamelCase( ): __a = argparse.ArgumentParser() parser.add_argument("-f" ) __a = parser.parse_args() return args.f class snake_case__ ( snake_case_ ): def a__ ( self ): __a = logging.StreamHandler(sys.stdout ) logger.addHandler(lowerCamelCase ) def a__ ( self , lowerCamelCase ): __a = get_gpu_count() if n_gpu > 1: pass # XXX: doesn't quite work with n_gpu > 1 https://github.com/huggingface/transformers/issues/10560 # script = f"{self.examples_dir_str}/research_projects/deebert/run_glue_deebert.py" # distributed_args = f"-m torch.distributed.launch --nproc_per_node={n_gpu} {script}".split() # cmd = [sys.executable] + distributed_args + args # execute_subprocess_async(cmd, env=self.get_env()) # XXX: test the results - need to save them first into .json file else: args.insert(0 , "run_glue_deebert.py" ) with patch.object(lowerCamelCase , "argv" , lowerCamelCase ): __a = run_glue_deebert.main() for value in result.values(): self.assertGreaterEqual(lowerCamelCase , 0.666 ) @slow @require_torch_non_multi_gpu def a__ ( self ): __a = "\n --model_type roberta\n --model_name_or_path roberta-base\n --task_name MRPC\n --do_train\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --max_seq_length 128\n --per_gpu_eval_batch_size=1\n --per_gpu_train_batch_size=8\n --learning_rate 2e-4\n --num_train_epochs 3\n --overwrite_output_dir\n --seed 42\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --save_steps 0\n --overwrite_cache\n --eval_after_first_stage\n ".split() self.run_and_check(lowerCamelCase ) __a = "\n --model_type roberta\n --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --task_name MRPC\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --max_seq_length 128\n --eval_each_highway\n --eval_highway\n --overwrite_cache\n --per_gpu_eval_batch_size=1\n ".split() self.run_and_check(lowerCamelCase ) __a = "\n --model_type roberta\n --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --task_name MRPC\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --max_seq_length 128\n --early_exit_entropy 0.1\n --eval_highway\n --overwrite_cache\n --per_gpu_eval_batch_size=1\n ".split() self.run_and_check(lowerCamelCase )
67
0
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 snake_case__ : def __init__( self , lowerCamelCase , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase="resnet50" , lowerCamelCase=3 , lowerCamelCase=32 , lowerCamelCase=3 , lowerCamelCase=True , lowerCamelCase=True , ): __a = parent __a = out_indices if out_indices is not None else [4] __a = stage_names __a = out_features __a = backbone __a = batch_size __a = image_size __a = num_channels __a = use_pretrained_backbone __a = is_training def a__ ( self ): __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = self.get_config() return config, pixel_values def a__ ( self ): 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 a__ ( self , lowerCamelCase , lowerCamelCase ): __a = TimmBackbone(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() with torch.no_grad(): __a = model(lowerCamelCase ) self.parent.assertEqual( result.feature_map[-1].shape , (self.batch_size, model.channels[-1], 14, 14) , ) def a__ ( self ): __a = self.prepare_config_and_inputs() __a , __a = config_and_inputs __a = {"pixel_values": pixel_values} return config, inputs_dict @require_torch @require_timm class snake_case__ ( snake_case_, snake_case_, snake_case_, unittest.TestCase ): _snake_case : str = (TimmBackbone,) if is_torch_available() else () _snake_case : int = {"""feature-extraction""": TimmBackbone} if is_torch_available() else {} _snake_case : Optional[Any] = False _snake_case : str = False _snake_case : int = False _snake_case : str = False def a__ ( self ): __a = TimmBackboneModelTester(self ) __a = ConfigTester(self , config_class=lowerCamelCase , has_text_modality=lowerCamelCase ) def a__ ( self ): 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 a__ ( self ): __a = "resnet18" __a = "microsoft/resnet-18" __a = AutoBackbone.from_pretrained(lowerCamelCase , use_timm_backbone=lowerCamelCase ) __a = AutoBackbone.from_pretrained(lowerCamelCase ) 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] ) __a = AutoBackbone.from_pretrained(lowerCamelCase , use_timm_backbone=lowerCamelCase , out_indices=[1, 2, 3] ) __a = AutoBackbone.from_pretrained(lowerCamelCase , 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 a__ ( self ): pass @unittest.skip("TimmBackbone doesn't have num_hidden_layers attribute" ) def a__ ( self ): pass @unittest.skip("TimmBackbone initialization is managed on the timm side" ) def a__ ( self ): pass @unittest.skip("TimmBackbone models doesn't have inputs_embeds" ) def a__ ( self ): pass @unittest.skip("TimmBackbone models doesn't have inputs_embeds" ) def a__ ( self ): pass @unittest.skip("TimmBackbone model cannot be created without specifying a backbone checkpoint" ) def a__ ( self ): pass @unittest.skip("Only checkpoints on timm can be loaded into TimmBackbone" ) def a__ ( self ): pass @unittest.skip("model weights aren't tied in TimmBackbone." ) def a__ ( self ): pass @unittest.skip("model weights aren't tied in TimmBackbone." ) def a__ ( self ): pass @unittest.skip("Only checkpoints on timm can be loaded into TimmBackbone" ) def a__ ( self ): pass @unittest.skip("Only checkpoints on timm can be loaded into TimmBackbone" ) def a__ ( self ): pass @unittest.skip("TimmBackbone doesn't have hidden size info in its configuration." ) def a__ ( self ): pass @unittest.skip("TimmBackbone doesn't support output_attentions." ) def a__ ( self ): pass @unittest.skip("Safetensors is not supported by timm." ) def a__ ( self ): pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def a__ ( self ): pass def a__ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(lowerCamelCase ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowerCamelCase ) def a__ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() __a = True __a = self.has_attentions # no need to test all models as different heads yield the same functionality __a = self.all_model_classes[0] __a = model_class(lowerCamelCase ) model.to(lowerCamelCase ) __a = self._prepare_for_class(lowerCamelCase , lowerCamelCase ) __a = model(**lowerCamelCase ) __a = outputs[0][-1] # Encoder-/Decoder-only models __a = outputs.hidden_states[0] hidden_states.retain_grad() if self.has_attentions: __a = outputs.attentions[0] attentions.retain_grad() output.flatten()[0].backward(retain_graph=lowerCamelCase ) self.assertIsNotNone(hidden_states.grad ) if self.has_attentions: self.assertIsNotNone(attentions.grad ) def a__ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(**lowerCamelCase ) 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 __a = copy.deepcopy(lowerCamelCase ) __a = None __a = model_class(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(**lowerCamelCase ) self.assertEqual(len(result.feature_maps ) , 1 ) self.assertEqual(len(model.channels ) , 1 ) # Check backbone can be initialized with fresh weights __a = copy.deepcopy(lowerCamelCase ) __a = False __a = model_class(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(**lowerCamelCase )
717
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, 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 SCREAMING_SNAKE_CASE__:Union[str, Any] = logging.get_logger(__name__) if is_vision_available(): import PIL class snake_case__ ( snake_case_ ): _snake_case : Optional[Any] = ["""pixel_values"""] def __init__( self , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = PILImageResampling.BICUBIC , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = True , lowerCamelCase = 1 / 255 , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = True , **lowerCamelCase , ): super().__init__(**lowerCamelCase ) __a = size if size is not None else {"shortest_edge": 224} __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) __a = crop_size if crop_size is not None else {"height": 224, "width": 224} __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase , param_name="crop_size" ) __a = do_resize __a = size __a = resample __a = do_center_crop __a = crop_size __a = do_rescale __a = rescale_factor __a = do_normalize __a = image_mean if image_mean is not None else OPENAI_CLIP_MEAN __a = image_std if image_std is not None else OPENAI_CLIP_STD __a = do_convert_rgb def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = PILImageResampling.BICUBIC , lowerCamelCase = None , **lowerCamelCase , ): __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) if "shortest_edge" not in size: raise ValueError(F"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}" ) __a = get_resize_output_image_size(lowerCamelCase , size=size["shortest_edge"] , default_to_square=lowerCamelCase ) return resize(lowerCamelCase , size=lowerCamelCase , resample=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): __a = get_size_dict(lowerCamelCase ) 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(lowerCamelCase , size=(size["height"], size["width"]) , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): return rescale(lowerCamelCase , scale=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): return normalize(lowerCamelCase , mean=lowerCamelCase , std=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = ChannelDimension.FIRST , **lowerCamelCase , ): __a = do_resize if do_resize is not None else self.do_resize __a = size if size is not None else self.size __a = get_size_dict(lowerCamelCase , param_name="size" , default_to_square=lowerCamelCase ) __a = resample if resample is not None else self.resample __a = do_center_crop if do_center_crop is not None else self.do_center_crop __a = crop_size if crop_size is not None else self.crop_size __a = get_size_dict(lowerCamelCase , param_name="crop_size" , default_to_square=lowerCamelCase ) __a = do_rescale if do_rescale is not None else self.do_rescale __a = rescale_factor if rescale_factor is not None else self.rescale_factor __a = do_normalize if do_normalize is not None else self.do_normalize __a = image_mean if image_mean is not None else self.image_mean __a = image_std if image_std is not None else self.image_std __a = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __a = make_list_of_images(lowerCamelCase ) if not valid_images(lowerCamelCase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) 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: __a = [convert_to_rgb(lowerCamelCase ) for image in images] # All transformations expect numpy arrays. __a = [to_numpy_array(lowerCamelCase ) for image in images] if do_resize: __a = [self.resize(image=lowerCamelCase , size=lowerCamelCase , resample=lowerCamelCase ) for image in images] if do_center_crop: __a = [self.center_crop(image=lowerCamelCase , size=lowerCamelCase ) for image in images] if do_rescale: __a = [self.rescale(image=lowerCamelCase , scale=lowerCamelCase ) for image in images] if do_normalize: __a = [self.normalize(image=lowerCamelCase , mean=lowerCamelCase , std=lowerCamelCase ) for image in images] __a = [to_channel_dimension_format(lowerCamelCase , lowerCamelCase ) for image in images] __a = {"pixel_values": images} return BatchFeature(data=lowerCamelCase , tensor_type=lowerCamelCase )
67
0
import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class snake_case__ ( snake_case_ ): def a__ ( self , lowerCamelCase ): with open(lowerCamelCase , encoding="utf-8" ) as input_file: __a = re.compile(R"(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)" ) __a = input_file.read() __a = regexp.search(lowerCamelCase ) return match def a__ ( self , lowerCamelCase ): with open(lowerCamelCase , encoding="utf-8" ) as input_file: __a = re.compile(R"#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()" , re.DOTALL ) __a = input_file.read() # use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search` __a = regexp.finditer(lowerCamelCase ) __a = [match for match in matches if match is not None and match.group(1 ) is not None] return matches[0] if matches else None def a__ ( self ): __a = Path("./datasets" ) __a = list(dataset_paths.absolute().glob("**/*.py" ) ) for dataset in dataset_files: if self._no_encoding_on_file_open(str(lowerCamelCase ) ): raise AssertionError(F"open(...) must use utf-8 encoding in {dataset}" ) def a__ ( self ): __a = Path("./datasets" ) __a = list(dataset_paths.absolute().glob("**/*.py" ) ) for dataset in dataset_files: if self._no_print_statements(str(lowerCamelCase ) ): raise AssertionError(F"print statement found in {dataset}. Use datasets.logger/logging instead." )
718
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation SCREAMING_SNAKE_CASE__:List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Any = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} SCREAMING_SNAKE_CASE__:Optional[Any] = { """vocab_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/vocab.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/vocab.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/vocab.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/vocab.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/vocab.json""", }, """merges_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/merges.txt""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/merges.txt""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/merges.txt""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/merges.txt""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/merges.txt""", }, """tokenizer_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/tokenizer.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/tokenizer.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/tokenizer.json""", }, } SCREAMING_SNAKE_CASE__:Union[str, Any] = { """gpt2""": 1024, """gpt2-medium""": 1024, """gpt2-large""": 1024, """gpt2-xl""": 1024, """distilgpt2""": 1024, } class snake_case__ ( snake_case_ ): _snake_case : Tuple = VOCAB_FILES_NAMES _snake_case : str = PRETRAINED_VOCAB_FILES_MAP _snake_case : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _snake_case : List[str] = ["""input_ids""", """attention_mask"""] _snake_case : Dict = GPTaTokenizer def __init__( self , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase="<|endoftext|>" , lowerCamelCase="<|endoftext|>" , lowerCamelCase="<|endoftext|>" , lowerCamelCase=False , **lowerCamelCase , ): super().__init__( lowerCamelCase , lowerCamelCase , tokenizer_file=lowerCamelCase , unk_token=lowerCamelCase , bos_token=lowerCamelCase , eos_token=lowerCamelCase , add_prefix_space=lowerCamelCase , **lowerCamelCase , ) __a = kwargs.pop("add_bos_token" , lowerCamelCase ) __a = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , lowerCamelCase ) != add_prefix_space: __a = getattr(lowerCamelCase , pre_tok_state.pop("type" ) ) __a = add_prefix_space __a = pre_tok_class(**lowerCamelCase ) __a = add_prefix_space def a__ ( self , *lowerCamelCase , **lowerCamelCase ): __a = kwargs.get("is_split_into_words" , lowerCamelCase ) assert self.add_prefix_space or not is_split_into_words, ( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*lowerCamelCase , **lowerCamelCase ) def a__ ( self , *lowerCamelCase , **lowerCamelCase ): __a = kwargs.get("is_split_into_words" , lowerCamelCase ) assert self.add_prefix_space or not is_split_into_words, ( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._encode_plus(*lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase = None ): __a = self._tokenizer.model.save(lowerCamelCase , name=lowerCamelCase ) return tuple(lowerCamelCase ) def a__ ( self , lowerCamelCase ): __a = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowerCamelCase , add_special_tokens=lowerCamelCase ) + [self.eos_token_id] ) if len(lowerCamelCase ) > self.model_max_length: __a = input_ids[-self.model_max_length :] return input_ids
67
0
from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class snake_case__ : _snake_case : torch.Tensor # [batch_size x 3] _snake_case : torch.Tensor # [batch_size x 3] _snake_case : torch.Tensor # [batch_size x 3] _snake_case : torch.Tensor # [batch_size x 3] _snake_case : int _snake_case : int _snake_case : float _snake_case : float _snake_case : Tuple[int] def a__ ( self ): assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def a__ ( self ): return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def a__ ( self ): return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def a__ ( self ): __a = torch.arange(self.height * self.width ) __a = torch.stack( [ pixel_indices % self.width, torch.div(lowerCamelCase , self.width , rounding_mode="trunc" ), ] , axis=1 , ) return coords @property def a__ ( self ): __a , *__a = self.shape __a = int(np.prod(lowerCamelCase ) ) __a = self.get_image_coords() __a = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) __a = self.get_camera_rays(lowerCamelCase ) __a = rays.view(lowerCamelCase , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def a__ ( self , lowerCamelCase ): __a , *__a , __a = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] __a = coords.view(lowerCamelCase , -1 , 2 ) __a = self.resolution() __a = self.fov() __a = (flat.float() / (res - 1)) * 2 - 1 __a = fracs * torch.tan(fov / 2 ) __a = fracs.view(lowerCamelCase , -1 , 2 ) __a = ( self.z.view(lowerCamelCase , 1 , 3 ) + self.x.view(lowerCamelCase , 1 , 3 ) * fracs[:, :, :1] + self.y.view(lowerCamelCase , 1 , 3 ) * fracs[:, :, 1:] ) __a = directions / directions.norm(dim=-1 , keepdim=lowerCamelCase ) __a = torch.stack( [ torch.broadcast_to(self.origin.view(lowerCamelCase , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(lowerCamelCase , *lowerCamelCase , 2 , 3 ) def a__ ( self , lowerCamelCase , lowerCamelCase ): assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=lowerCamelCase , height=lowerCamelCase , x_fov=self.x_fov , y_fov=self.y_fov , ) def _lowerCamelCase( a ): __a = [] __a = [] __a = [] __a = [] for theta in np.linspace(0 , 2 * np.pi , num=2_0 ): __a = np.array([np.sin(a ), np.cos(a ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) __a = -z * 4 __a = np.array([np.cos(a ), -np.sin(a ), 0.0] ) __a = np.cross(a , a ) origins.append(a ) xs.append(a ) ys.append(a ) zs.append(a ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(a , axis=0 ) ).float() , x=torch.from_numpy(np.stack(a , axis=0 ) ).float() , y=torch.from_numpy(np.stack(a , axis=0 ) ).float() , z=torch.from_numpy(np.stack(a , axis=0 ) ).float() , width=a , height=a , x_fov=0.7 , y_fov=0.7 , shape=(1, len(a )) , )
719
"""simple docstring""" from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize("repo_id" , ["canonical_dataset_name", "org-name/dataset-name"] ) @pytest.mark.parametrize("path" , ["filename.csv", "filename with blanks.csv"] ) @pytest.mark.parametrize("revision" , [None, "v2"] ) def _lowerCamelCase( a , a , a ): __a = hf_hub_url(repo_id=a , path=a , revision=a ) assert url == F"https://huggingface.co/datasets/{repo_id}/resolve/{revision or 'main'}/{quote(a )}"
67
0
"""simple docstring""" import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case__ : def __init__( self , lowerCamelCase , lowerCamelCase=13 , lowerCamelCase=7 , lowerCamelCase=True , lowerCamelCase=True , lowerCamelCase=False , lowerCamelCase=True , lowerCamelCase=99 , lowerCamelCase=32 , lowerCamelCase=5 , lowerCamelCase=4 , lowerCamelCase=37 , lowerCamelCase="gelu" , lowerCamelCase=0.1 , lowerCamelCase=0.1 , lowerCamelCase=512 , lowerCamelCase=16 , lowerCamelCase=2 , lowerCamelCase=0.02 , lowerCamelCase=3 , lowerCamelCase=4 , lowerCamelCase=None , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_input_mask __a = use_token_type_ids __a = use_labels __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = type_sequence_label_size __a = initializer_range __a = num_labels __a = num_choices __a = scope def a__ ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None if self.use_token_type_ids: __a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def a__ ( self ): return BioGptConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=lowerCamelCase , initializer_range=self.initializer_range , ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = BioGptModel(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase , attention_mask=lowerCamelCase ) __a = model(lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , ): __a = BioGptForCausalLM(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , *lowerCamelCase ): __a = BioGptModel(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() # create attention mask __a = torch.ones(input_ids.shape , dtype=torch.long , device=lowerCamelCase ) __a = self.seq_length // 2 __a = 0 # first forward pass __a , __a = model(lowerCamelCase , attention_mask=lowerCamelCase ).to_tuple() # create hypothetical next token and extent to next_input_ids __a = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids __a = ids_tensor((1,) , lowerCamelCase ).item() + 1 __a = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) __a = random_other_next_tokens # append to next input_ids and attn_mask __a = torch.cat([input_ids, next_tokens] , dim=-1 ) __a = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=lowerCamelCase )] , dim=1 , ) # get two different outputs __a = model(lowerCamelCase , attention_mask=lowerCamelCase )["last_hidden_state"] __a = model(lowerCamelCase , past_key_values=lowerCamelCase , attention_mask=lowerCamelCase )["last_hidden_state"] # select random slice __a = ids_tensor((1,) , output_from_past.shape[-1] ).item() __a = output_from_no_past[:, -1, random_slice_idx].detach() __a = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(lowerCamelCase , lowerCamelCase , atol=1E-3 ) ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , *lowerCamelCase ): __a = BioGptModel(config=lowerCamelCase ).to(lowerCamelCase ).eval() __a = torch.ones(input_ids.shape , dtype=torch.long , device=lowerCamelCase ) # first forward pass __a = model(lowerCamelCase , attention_mask=lowerCamelCase , use_cache=lowerCamelCase ) __a , __a = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids __a = ids_tensor((self.batch_size, 3) , config.vocab_size ) __a = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and __a = torch.cat([input_ids, next_tokens] , dim=-1 ) __a = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) __a = model(lowerCamelCase , attention_mask=lowerCamelCase )["last_hidden_state"] __a = model(lowerCamelCase , attention_mask=lowerCamelCase , past_key_values=lowerCamelCase )[ "last_hidden_state" ] # select random slice __a = ids_tensor((1,) , output_from_past.shape[-1] ).item() __a = output_from_no_past[:, -3:, random_slice_idx].detach() __a = 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(lowerCamelCase , lowerCamelCase , atol=1E-3 ) ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , *lowerCamelCase , lowerCamelCase=False ): __a = BioGptForCausalLM(lowerCamelCase ) model.to(lowerCamelCase ) if gradient_checkpointing: model.gradient_checkpointing_enable() __a = model(lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def a__ ( self , lowerCamelCase , *lowerCamelCase ): __a = BioGptModel(lowerCamelCase ) __a = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , *lowerCamelCase ): __a = self.num_labels __a = BioGptForTokenClassification(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def a__ ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class snake_case__ ( snake_case_, snake_case_, snake_case_, unittest.TestCase ): _snake_case : List[str] = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) _snake_case : Union[str, Any] = (BioGptForCausalLM,) if is_torch_available() else () _snake_case : Optional[int] = ( { """feature-extraction""": BioGptModel, """text-classification""": BioGptForSequenceClassification, """text-generation""": BioGptForCausalLM, """token-classification""": BioGptForTokenClassification, """zero-shot""": BioGptForSequenceClassification, } if is_torch_available() else {} ) _snake_case : List[str] = False def a__ ( self ): __a = BioGptModelTester(self ) __a = ConfigTester(self , config_class=lowerCamelCase , hidden_size=37 ) def a__ ( self ): self.config_tester.run_common_tests() def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __a = type self.model_tester.create_and_check_model(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*lowerCamelCase , gradient_checkpointing=lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*lowerCamelCase ) @slow def a__ ( self ): __a = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(lowerCamelCase ) __a = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) __a = "left" # Define PAD Token = EOS Token = 50256 __a = tokenizer.eos_token __a = model.config.eos_token_id # use different length sentences to test batching __a = [ "Hello, my dog is a little", "Today, I", ] __a = tokenizer(lowerCamelCase , return_tensors="pt" , padding=lowerCamelCase ) __a = inputs["input_ids"].to(lowerCamelCase ) __a = model.generate( input_ids=lowerCamelCase , attention_mask=inputs["attention_mask"].to(lowerCamelCase ) , ) __a = tokenizer(sentences[0] , return_tensors="pt" ).input_ids.to(lowerCamelCase ) __a = model.generate(input_ids=lowerCamelCase ) __a = inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].long().sum().cpu().item() __a = tokenizer(sentences[1] , return_tensors="pt" ).input_ids.to(lowerCamelCase ) __a = model.generate(input_ids=lowerCamelCase , max_length=model.config.max_length - num_paddings ) __a = tokenizer.batch_decode(lowerCamelCase , skip_special_tokens=lowerCamelCase ) __a = tokenizer.decode(output_non_padded[0] , skip_special_tokens=lowerCamelCase ) __a = tokenizer.decode(output_padded[0] , skip_special_tokens=lowerCamelCase ) __a = [ "Hello, my dog is a little bit bigger than a little bit.", "Today, I have a good idea of how to use the information", ] self.assertListEqual(lowerCamelCase , lowerCamelCase ) self.assertListEqual(lowerCamelCase , [non_padded_sentence, padded_sentence] ) @slow def a__ ( self ): for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = BioGptModel.from_pretrained(lowerCamelCase ) self.assertIsNotNone(lowerCamelCase ) def a__ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() __a = 3 __a = input_dict["input_ids"] __a = input_ids.ne(1 ).to(lowerCamelCase ) __a = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __a = BioGptForSequenceClassification(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase , attention_mask=lowerCamelCase , labels=lowerCamelCase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def a__ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() __a = 3 __a = "multi_label_classification" __a = input_dict["input_ids"] __a = input_ids.ne(1 ).to(lowerCamelCase ) __a = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __a = BioGptForSequenceClassification(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase , attention_mask=lowerCamelCase , labels=lowerCamelCase ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class snake_case__ ( unittest.TestCase ): @slow def a__ ( self ): __a = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) __a = torch.tensor([[2, 4805, 9, 656, 21]] ) __a = model(lowerCamelCase )[0] __a = 42384 __a = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , lowerCamelCase ) __a = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , lowerCamelCase , atol=1E-4 ) ) @slow def a__ ( self ): __a = BioGptTokenizer.from_pretrained("microsoft/biogpt" ) __a = BioGptForCausalLM.from_pretrained("microsoft/biogpt" ) model.to(lowerCamelCase ) torch.manual_seed(0 ) __a = tokenizer("COVID-19 is" , return_tensors="pt" ).to(lowerCamelCase ) __a = model.generate( **lowerCamelCase , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=lowerCamelCase , ) __a = tokenizer.decode(output_ids[0] , skip_special_tokens=lowerCamelCase ) __a = ( "COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the" " causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and" " territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK)," " and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and" " more than 800,000 deaths." ) self.assertEqual(lowerCamelCase , lowerCamelCase )
720
"""simple docstring""" from __future__ import annotations def _lowerCamelCase( a , a , a ): if len(a ) == 0: raise ValueError("find_max() arg is an empty sequence" ) if ( left >= len(a ) or left < -len(a ) or right >= len(a ) or right < -len(a ) ): raise IndexError("list index out of range" ) if left == right: return nums[left] __a = (left + right) >> 1 # the middle __a = find_max(a , a , a ) # find max in range[left, mid] __a = find_max(a , mid + 1 , a ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
67
0
"""simple docstring""" def _lowerCamelCase( a ): if not isinstance(a , a ): raise ValueError("Input series is not valid, valid series - [2, 4, 6]" ) if len(a ) == 0: raise ValueError("Input list must be a non empty list" ) if len(a ) == 1: return True __a = series[1] - series[0] for index in range(len(a ) - 1 ): if series[index + 1] - series[index] != common_diff: return False return True def _lowerCamelCase( a ): if not isinstance(a , a ): raise ValueError("Input series is not valid, valid series - [2, 4, 6]" ) if len(a ) == 0: raise ValueError("Input list must be a non empty list" ) __a = 0 for val in series: answer += val return answer / len(a ) if __name__ == "__main__": import doctest doctest.testmod()
721
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__:List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Tuple = { """google/bigbird-roberta-base""": """https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json""", """google/bigbird-roberta-large""": """https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json""", """google/bigbird-base-trivia-itc""": """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json""", # See all BigBird models at https://huggingface.co/models?filter=big_bird } class snake_case__ ( snake_case_ ): _snake_case : Any = """big_bird""" def __init__( self , lowerCamelCase=50358 , lowerCamelCase=768 , lowerCamelCase=12 , lowerCamelCase=12 , lowerCamelCase=3072 , lowerCamelCase="gelu_new" , lowerCamelCase=0.1 , lowerCamelCase=0.1 , lowerCamelCase=4096 , lowerCamelCase=2 , lowerCamelCase=0.02 , lowerCamelCase=1E-12 , lowerCamelCase=True , lowerCamelCase=0 , lowerCamelCase=1 , lowerCamelCase=2 , lowerCamelCase=66 , lowerCamelCase="block_sparse" , lowerCamelCase=True , lowerCamelCase=False , lowerCamelCase=64 , lowerCamelCase=3 , lowerCamelCase=None , **lowerCamelCase , ): super().__init__( pad_token_id=lowerCamelCase , bos_token_id=lowerCamelCase , eos_token_id=lowerCamelCase , sep_token_id=lowerCamelCase , **lowerCamelCase , ) __a = vocab_size __a = max_position_embeddings __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 = initializer_range __a = type_vocab_size __a = layer_norm_eps __a = use_cache __a = rescale_embeddings __a = attention_type __a = use_bias __a = block_size __a = num_random_blocks __a = classifier_dropout class snake_case__ ( snake_case_ ): @property def a__ ( self ): 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), ] )
67
0
"""simple docstring""" def _lowerCamelCase( a ): if upper_limit < 0: raise ValueError("Limit for the Catalan sequence must be ≥ 0" ) __a = [0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 __a = 1 if upper_limit > 0: __a = 1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2 , upper_limit + 1 ): for j in range(a ): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print("""\n********* Catalan Numbers Using Dynamic Programming ************\n""") print("""\n*** Enter -1 at any time to quit ***""") print("""\nEnter the upper limit (≥ 0) for the Catalan number sequence: """, end="""""") try: while True: SCREAMING_SNAKE_CASE__:str = int(input().strip()) if N < 0: print("""\n********* Goodbye!! ************""") break else: print(F'''The Catalan numbers from 0 through {N} are:''') print(catalan_numbers(N)) print("""Try another upper limit for the sequence: """, end="""""") except (NameError, ValueError): print("""\n********* Invalid input, goodbye! ************\n""") import doctest doctest.testmod()
700
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation SCREAMING_SNAKE_CASE__:Optional[int] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Optional[int] = {"""tokenizer_file""": """tokenizer.json"""} SCREAMING_SNAKE_CASE__:Tuple = { """tokenizer_file""": { """bigscience/tokenizer""": """https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json""", """bigscience/bloom-560m""": """https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json""", """bigscience/bloom-1b1""": """https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json""", """bigscience/bloom-1b7""": """https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json""", """bigscience/bloom-3b""": """https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json""", """bigscience/bloom-7b1""": """https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json""", """bigscience/bloom""": """https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json""", }, } class snake_case__ ( snake_case_ ): _snake_case : Optional[Any] = VOCAB_FILES_NAMES _snake_case : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP _snake_case : Optional[int] = ["""input_ids""", """attention_mask"""] _snake_case : Optional[int] = None def __init__( self , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase="<unk>" , lowerCamelCase="<s>" , lowerCamelCase="</s>" , lowerCamelCase="<pad>" , lowerCamelCase=False , lowerCamelCase=False , **lowerCamelCase , ): super().__init__( lowerCamelCase , lowerCamelCase , tokenizer_file=lowerCamelCase , unk_token=lowerCamelCase , bos_token=lowerCamelCase , eos_token=lowerCamelCase , pad_token=lowerCamelCase , add_prefix_space=lowerCamelCase , clean_up_tokenization_spaces=lowerCamelCase , **lowerCamelCase , ) __a = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , lowerCamelCase ) != add_prefix_space: __a = getattr(lowerCamelCase , pre_tok_state.pop("type" ) ) __a = add_prefix_space __a = pre_tok_class(**lowerCamelCase ) __a = add_prefix_space def a__ ( self , *lowerCamelCase , **lowerCamelCase ): __a = kwargs.get("is_split_into_words" , lowerCamelCase ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with" " pretokenized inputs." ) return super()._batch_encode_plus(*lowerCamelCase , **lowerCamelCase ) def a__ ( self , *lowerCamelCase , **lowerCamelCase ): __a = kwargs.get("is_split_into_words" , lowerCamelCase ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with" " pretokenized inputs." ) return super()._encode_plus(*lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase = None ): __a = self._tokenizer.model.save(lowerCamelCase , name=lowerCamelCase ) return tuple(lowerCamelCase ) def a__ ( self , lowerCamelCase ): __a = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowerCamelCase , add_special_tokens=lowerCamelCase ) + [self.eos_token_id] ) if len(lowerCamelCase ) > self.model_max_length: __a = input_ids[-self.model_max_length :] return input_ids
67
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE__:Optional[Any] = {"""configuration_xlnet""": ["""XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLNetConfig"""]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__:int = ["""XLNetTokenizer"""] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__:Dict = ["""XLNetTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__:Union[str, Any] = [ """XLNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """XLNetForMultipleChoice""", """XLNetForQuestionAnswering""", """XLNetForQuestionAnsweringSimple""", """XLNetForSequenceClassification""", """XLNetForTokenClassification""", """XLNetLMHeadModel""", """XLNetModel""", """XLNetPreTrainedModel""", """load_tf_weights_in_xlnet""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__:List[str] = [ """TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFXLNetForMultipleChoice""", """TFXLNetForQuestionAnsweringSimple""", """TFXLNetForSequenceClassification""", """TFXLNetForTokenClassification""", """TFXLNetLMHeadModel""", """TFXLNetMainLayer""", """TFXLNetModel""", """TFXLNetPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__:Optional[int] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
701
"""simple docstring""" from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class snake_case__ : _snake_case : torch.Tensor # [batch_size x 3] _snake_case : torch.Tensor # [batch_size x 3] _snake_case : torch.Tensor # [batch_size x 3] _snake_case : torch.Tensor # [batch_size x 3] _snake_case : int _snake_case : int _snake_case : float _snake_case : float _snake_case : Tuple[int] def a__ ( self ): assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def a__ ( self ): return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def a__ ( self ): return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def a__ ( self ): __a = torch.arange(self.height * self.width ) __a = torch.stack( [ pixel_indices % self.width, torch.div(lowerCamelCase , self.width , rounding_mode="trunc" ), ] , axis=1 , ) return coords @property def a__ ( self ): __a , *__a = self.shape __a = int(np.prod(lowerCamelCase ) ) __a = self.get_image_coords() __a = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) __a = self.get_camera_rays(lowerCamelCase ) __a = rays.view(lowerCamelCase , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def a__ ( self , lowerCamelCase ): __a , *__a , __a = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] __a = coords.view(lowerCamelCase , -1 , 2 ) __a = self.resolution() __a = self.fov() __a = (flat.float() / (res - 1)) * 2 - 1 __a = fracs * torch.tan(fov / 2 ) __a = fracs.view(lowerCamelCase , -1 , 2 ) __a = ( self.z.view(lowerCamelCase , 1 , 3 ) + self.x.view(lowerCamelCase , 1 , 3 ) * fracs[:, :, :1] + self.y.view(lowerCamelCase , 1 , 3 ) * fracs[:, :, 1:] ) __a = directions / directions.norm(dim=-1 , keepdim=lowerCamelCase ) __a = torch.stack( [ torch.broadcast_to(self.origin.view(lowerCamelCase , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(lowerCamelCase , *lowerCamelCase , 2 , 3 ) def a__ ( self , lowerCamelCase , lowerCamelCase ): assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=lowerCamelCase , height=lowerCamelCase , x_fov=self.x_fov , y_fov=self.y_fov , ) def _lowerCamelCase( a ): __a = [] __a = [] __a = [] __a = [] for theta in np.linspace(0 , 2 * np.pi , num=2_0 ): __a = np.array([np.sin(a ), np.cos(a ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) __a = -z * 4 __a = np.array([np.cos(a ), -np.sin(a ), 0.0] ) __a = np.cross(a , a ) origins.append(a ) xs.append(a ) ys.append(a ) zs.append(a ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(a , axis=0 ) ).float() , x=torch.from_numpy(np.stack(a , axis=0 ) ).float() , y=torch.from_numpy(np.stack(a , axis=0 ) ).float() , z=torch.from_numpy(np.stack(a , axis=0 ) ).float() , width=a , height=a , x_fov=0.7 , y_fov=0.7 , shape=(1, len(a )) , )
67
0
"""simple docstring""" import multiprocessing import time from arguments import PretokenizationArguments from datasets import load_dataset from transformers import AutoTokenizer, HfArgumentParser def _lowerCamelCase( a ): __a = {} __a = tokenizer(example["content"] , truncation=a )["input_ids"] __a = len(example["content"] ) / len(output["input_ids"] ) return output SCREAMING_SNAKE_CASE__:Optional[Any] = HfArgumentParser(PretokenizationArguments) SCREAMING_SNAKE_CASE__:List[str] = parser.parse_args() if args.num_workers is None: SCREAMING_SNAKE_CASE__:int = multiprocessing.cpu_count() SCREAMING_SNAKE_CASE__:List[str] = AutoTokenizer.from_pretrained(args.tokenizer_dir) SCREAMING_SNAKE_CASE__:List[Any] = time.time() SCREAMING_SNAKE_CASE__:Optional[int] = load_dataset(args.dataset_name, split="""train""") print(F'''Dataset loaded in {time.time()-t_start:.2f}s''') SCREAMING_SNAKE_CASE__:List[str] = time.time() SCREAMING_SNAKE_CASE__:Tuple = ds.map( tokenize, num_proc=args.num_workers, remove_columns=[ """repo_name""", """path""", """copies""", """size""", """content""", """license""", """hash""", """line_mean""", """line_max""", """alpha_frac""", """autogenerated""", ], ) print(F'''Dataset tokenized in {time.time()-t_start:.2f}s''') SCREAMING_SNAKE_CASE__:Tuple = time.time() ds.push_to_hub(args.tokenized_data_repo) print(F'''Data pushed to the hub in {time.time()-t_start:.2f}s''')
702
"""simple docstring""" def _lowerCamelCase( a ): return 1 if digit in (0, 1) else (digit * factorial(digit - 1 )) def _lowerCamelCase( a ): __a = 0 __a = number while duplicate > 0: __a , __a = divmod(a , 1_0 ) fact_sum += factorial(a ) return fact_sum == number if __name__ == "__main__": print("""Program to check whether a number is a Krisnamurthy Number or not.""") SCREAMING_SNAKE_CASE__:Optional[Any] = int(input("""Enter number: """).strip()) print( F'''{number} is {'' if krishnamurthy(number) else 'not '}a Krishnamurthy Number.''' )
67
0
"""simple docstring""" from collections.abc import Sequence def _lowerCamelCase( a = None ): if nums is None or not nums: raise ValueError("Input sequence should not be empty" ) __a = nums[0] for i in range(1 , len(a ) ): __a = nums[i] __a = max(a , ans + num , a ) return ans if __name__ == "__main__": import doctest doctest.testmod() # Try on a sample input from the user SCREAMING_SNAKE_CASE__:Optional[Any] = int(input("""Enter number of elements : """).strip()) SCREAMING_SNAKE_CASE__:Union[str, Any] = list(map(int, input("""\nEnter the numbers : """).strip().split()))[:n] print(max_subsequence_sum(array))
703
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) SCREAMING_SNAKE_CASE__:Optional[Any] = { """configuration_gpt_bigcode""": ["""GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTBigCodeConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__:Union[str, Any] = [ """GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST""", """GPTBigCodeForSequenceClassification""", """GPTBigCodeForTokenClassification""", """GPTBigCodeForCausalLM""", """GPTBigCodeModel""", """GPTBigCodePreTrainedModel""", ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__:List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
67
0
"""simple docstring""" def _lowerCamelCase( a , a ): _validate_point(a ) _validate_point(a ) if len(a ) != len(a ): raise ValueError("Both points must be in the same n-dimensional space" ) return float(sum(abs(a - b ) for a, b in zip(a , a ) ) ) def _lowerCamelCase( a ): if point: if isinstance(a , a ): for item in point: if not isinstance(a , (int, float) ): __a = ( "Expected a list of numbers as input, found " F"{type(a ).__name__}" ) raise TypeError(a ) else: __a = F"Expected a list of numbers as input, found {type(a ).__name__}" raise TypeError(a ) else: raise ValueError("Missing an input" ) def _lowerCamelCase( a , a ): _validate_point(a ) _validate_point(a ) if len(a ) != len(a ): raise ValueError("Both points must be in the same n-dimensional space" ) return float(sum(abs(x - y ) for x, y in zip(a , a ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
704
"""simple docstring""" import argparse import OmegaConf import torch from diffusers import DDIMScheduler, LDMPipeline, UNetLDMModel, VQModel def _lowerCamelCase( a , a , a ): __a = OmegaConf.load(a ) __a = torch.load(a , map_location="cpu" )["model"] __a = list(state_dict.keys() ) # extract state_dict for VQVAE __a = {} __a = "first_stage_model." for key in keys: if key.startswith(a ): __a = state_dict[key] # extract state_dict for UNetLDM __a = {} __a = "model.diffusion_model." for key in keys: if key.startswith(a ): __a = state_dict[key] __a = config.model.params.first_stage_config.params __a = config.model.params.unet_config.params __a = VQModel(**a ).eval() vqvae.load_state_dict(a ) __a = UNetLDMModel(**a ).eval() unet.load_state_dict(a ) __a = 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=a , ) __a = LDMPipeline(a , a , a ) pipeline.save_pretrained(a ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__:List[Any] = 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) SCREAMING_SNAKE_CASE__:Union[str, Any] = parser.parse_args() convert_ldm_original(args.checkpoint_path, args.config_path, args.output_path)
67
0
"""simple docstring""" from ....configuration_utils import PretrainedConfig from ....utils import logging SCREAMING_SNAKE_CASE__:List[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Optional[Any] = { """CarlCochet/trajectory-transformer-halfcheetah-medium-v2""": ( """https://huggingface.co/CarlCochet/trajectory-transformer-halfcheetah-medium-v2/resolve/main/config.json""" ), # See all TrajectoryTransformer models at https://huggingface.co/models?filter=trajectory_transformer } class snake_case__ ( snake_case_ ): _snake_case : Tuple = """trajectory_transformer""" _snake_case : Any = ["""past_key_values"""] _snake_case : Dict = { """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self , lowerCamelCase=100 , lowerCamelCase=5 , lowerCamelCase=1 , lowerCamelCase=1 , lowerCamelCase=249 , lowerCamelCase=6 , lowerCamelCase=17 , lowerCamelCase=25 , lowerCamelCase=4 , lowerCamelCase=4 , lowerCamelCase=128 , lowerCamelCase=0.1 , lowerCamelCase=0.1 , lowerCamelCase=0.1 , lowerCamelCase=0.0006 , lowerCamelCase=512 , lowerCamelCase=0.02 , lowerCamelCase=1E-12 , lowerCamelCase=1 , lowerCamelCase=True , lowerCamelCase=1 , lowerCamelCase=50256 , lowerCamelCase=50256 , **lowerCamelCase , ): __a = vocab_size __a = action_weight __a = reward_weight __a = value_weight __a = max_position_embeddings __a = block_size __a = action_dim __a = observation_dim __a = transition_dim __a = learning_rate __a = n_layer __a = n_head __a = n_embd __a = embd_pdrop __a = attn_pdrop __a = resid_pdrop __a = initializer_range __a = layer_norm_eps __a = kaiming_initializer_range __a = use_cache super().__init__(pad_token_id=lowerCamelCase , bos_token_id=lowerCamelCase , eos_token_id=lowerCamelCase , **lowerCamelCase )
705
"""simple docstring""" from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...file_utils import TensorType, is_torch_available from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging SCREAMING_SNAKE_CASE__:List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Optional[Any] = { """facebook/blenderbot_small-90M""": """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/config.json""", # See all BlenderbotSmall models at https://huggingface.co/models?filter=blenderbot_small } class snake_case__ ( snake_case_ ): _snake_case : str = """blenderbot-small""" _snake_case : str = ["""past_key_values"""] _snake_case : List[Any] = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self , lowerCamelCase=50265 , lowerCamelCase=512 , lowerCamelCase=8 , lowerCamelCase=2048 , lowerCamelCase=16 , lowerCamelCase=8 , lowerCamelCase=2048 , lowerCamelCase=16 , lowerCamelCase=0.0 , lowerCamelCase=0.0 , lowerCamelCase=True , lowerCamelCase=True , lowerCamelCase="gelu" , lowerCamelCase=512 , lowerCamelCase=0.1 , lowerCamelCase=0.0 , lowerCamelCase=0.0 , lowerCamelCase=0.02 , lowerCamelCase=1 , lowerCamelCase=False , lowerCamelCase=0 , lowerCamelCase=1 , lowerCamelCase=2 , lowerCamelCase=2 , **lowerCamelCase , ): __a = vocab_size __a = max_position_embeddings __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 = encoder_layerdrop __a = decoder_layerdrop __a = use_cache __a = encoder_layers __a = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=lowerCamelCase , bos_token_id=lowerCamelCase , eos_token_id=lowerCamelCase , is_encoder_decoder=lowerCamelCase , decoder_start_token_id=lowerCamelCase , forced_eos_token_id=lowerCamelCase , **lowerCamelCase , ) class snake_case__ ( snake_case_ ): @property def a__ ( self ): if self.task in ["default", "seq2seq-lm"]: __a = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: __a = {0: "batch"} __a = {0: "batch", 1: "past_decoder_sequence + sequence"} else: __a = {0: "batch", 1: "decoder_sequence"} __a = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(lowerCamelCase , direction="inputs" ) elif self.task == "causal-lm": # TODO: figure this case out. __a = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: __a , __a = self.num_layers for i in range(lowerCamelCase ): __a = {0: "batch", 2: "past_sequence + sequence"} __a = {0: "batch", 2: "past_sequence + sequence"} else: __a = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}), ("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}), ] ) return common_inputs @property def a__ ( self ): if self.task in ["default", "seq2seq-lm"]: __a = super().outputs else: __a = super(lowerCamelCase , self ).outputs if self.use_past: __a , __a = self.num_layers for i in range(lowerCamelCase ): __a = {0: "batch", 2: "past_sequence + sequence"} __a = {0: "batch", 2: "past_sequence + sequence"} return common_outputs def a__ ( self , lowerCamelCase , lowerCamelCase = -1 , lowerCamelCase = -1 , lowerCamelCase = False , lowerCamelCase = None , ): __a = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) # Generate decoder inputs __a = seq_length if not self.use_past else 1 __a = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) __a = {F"decoder_{name}": tensor for name, tensor in decoder_inputs.items()} __a = dict(**lowerCamelCase , **lowerCamelCase ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch __a , __a = common_inputs["input_ids"].shape __a = common_inputs["decoder_input_ids"].shape[1] __a , __a = self.num_attention_heads __a = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) __a = decoder_seq_length + 3 __a = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) __a = torch.cat( [common_inputs["decoder_attention_mask"], torch.ones(lowerCamelCase , lowerCamelCase )] , dim=1 ) __a = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered __a , __a = self.num_layers __a = min(lowerCamelCase , lowerCamelCase ) __a = max(lowerCamelCase , lowerCamelCase ) - min_num_layers __a = "encoder" if num_encoder_layers > num_decoder_layers else "decoder" for _ in range(lowerCamelCase ): common_inputs["past_key_values"].append( ( torch.zeros(lowerCamelCase ), torch.zeros(lowerCamelCase ), torch.zeros(lowerCamelCase ), torch.zeros(lowerCamelCase ), ) ) # TODO: test this. __a = encoder_shape if remaining_side_name == "encoder" else decoder_shape for _ in range(lowerCamelCase , lowerCamelCase ): common_inputs["past_key_values"].append((torch.zeros(lowerCamelCase ), torch.zeros(lowerCamelCase )) ) return common_inputs def a__ ( self , lowerCamelCase , lowerCamelCase = -1 , lowerCamelCase = -1 , lowerCamelCase = False , lowerCamelCase = None , ): __a = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch __a , __a = common_inputs["input_ids"].shape # Not using the same length for past_key_values __a = seqlen + 2 __a , __a = self.num_layers __a , __a = self.num_attention_heads __a = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) __a = common_inputs["attention_mask"].dtype __a = torch.cat( [common_inputs["attention_mask"], torch.ones(lowerCamelCase , lowerCamelCase , dtype=lowerCamelCase )] , dim=1 ) __a = [ (torch.zeros(lowerCamelCase ), torch.zeros(lowerCamelCase )) for _ in range(lowerCamelCase ) ] return common_inputs def a__ ( self , lowerCamelCase , lowerCamelCase = -1 , lowerCamelCase = -1 , lowerCamelCase = False , lowerCamelCase = None , ): # Copied from OnnxConfig.generate_dummy_inputs # Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity. # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX __a = compute_effective_axis_dimension( lowerCamelCase , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX __a = tokenizer.num_special_tokens_to_add(lowerCamelCase ) __a = compute_effective_axis_dimension( lowerCamelCase , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=lowerCamelCase ) # Generate dummy inputs according to compute batch and sequence __a = [" ".join([tokenizer.unk_token] ) * seq_length] * batch_size __a = dict(tokenizer(lowerCamelCase , return_tensors=lowerCamelCase ) ) return common_inputs def a__ ( self , lowerCamelCase , lowerCamelCase = -1 , lowerCamelCase = -1 , lowerCamelCase = False , lowerCamelCase = None , ): if self.task in ["default", "seq2seq-lm"]: __a = self._generate_dummy_inputs_for_default_and_seqaseq_lm( lowerCamelCase , batch_size=lowerCamelCase , seq_length=lowerCamelCase , is_pair=lowerCamelCase , framework=lowerCamelCase ) elif self.task == "causal-lm": __a = self._generate_dummy_inputs_for_causal_lm( lowerCamelCase , batch_size=lowerCamelCase , seq_length=lowerCamelCase , is_pair=lowerCamelCase , framework=lowerCamelCase ) else: __a = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCamelCase , batch_size=lowerCamelCase , seq_length=lowerCamelCase , is_pair=lowerCamelCase , framework=lowerCamelCase ) return common_inputs def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): if self.task in ["default", "seq2seq-lm"]: __a = super()._flatten_past_key_values_(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) else: __a = super(lowerCamelCase , self )._flatten_past_key_values_( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase )
67
0
"""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() SCREAMING_SNAKE_CASE__:Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Optional[int] = """Hello world! cécé herlolip""" def _lowerCamelCase( a , a , a ): __a = FairseqRobertaModel.from_pretrained(a ) roberta.eval() # disable dropout __a = roberta.model.encoder.sentence_encoder __a = 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=5_1_4 , type_vocab_size=1 , layer_norm_eps=1E-5 , ) if classification_head: __a = roberta.model.classification_heads["mnli"].out_proj.weight.shape[0] print("Our RoBERTa config:" , a ) __a = XLMRobertaXLForSequenceClassification(a ) if classification_head else XLMRobertaXLForMaskedLM(a ) model.eval() # Now let's copy all the weights. # Embeddings __a = roberta_sent_encoder.embed_tokens.weight __a = roberta_sent_encoder.embed_positions.weight __a = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c RoBERTa doesn't use them. __a = roberta_sent_encoder.layer_norm.weight __a = roberta_sent_encoder.layer_norm.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer __a = model.roberta.encoder.layer[i] __a = roberta_sent_encoder.layers[i] __a = layer.attention __a = roberta_layer.self_attn_layer_norm.weight __a = roberta_layer.self_attn_layer_norm.bias # self attention __a = 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 = roberta_layer.self_attn.q_proj.weight __a = roberta_layer.self_attn.q_proj.bias __a = roberta_layer.self_attn.k_proj.weight __a = roberta_layer.self_attn.k_proj.bias __a = roberta_layer.self_attn.v_proj.weight __a = roberta_layer.self_attn.v_proj.bias # self-attention output __a = layer.attention.output assert self_output.dense.weight.shape == roberta_layer.self_attn.out_proj.weight.shape __a = roberta_layer.self_attn.out_proj.weight __a = roberta_layer.self_attn.out_proj.bias # this one is final layer norm __a = roberta_layer.final_layer_norm.weight __a = roberta_layer.final_layer_norm.bias # intermediate __a = layer.intermediate assert intermediate.dense.weight.shape == roberta_layer.fca.weight.shape __a = roberta_layer.fca.weight __a = roberta_layer.fca.bias # output __a = layer.output assert bert_output.dense.weight.shape == roberta_layer.fca.weight.shape __a = roberta_layer.fca.weight __a = roberta_layer.fca.bias # end of layer if classification_head: __a = roberta.model.classification_heads["mnli"].dense.weight __a = roberta.model.classification_heads["mnli"].dense.bias __a = roberta.model.classification_heads["mnli"].out_proj.weight __a = roberta.model.classification_heads["mnli"].out_proj.bias else: # LM Head __a = roberta.model.encoder.lm_head.dense.weight __a = roberta.model.encoder.lm_head.dense.bias __a = roberta.model.encoder.lm_head.layer_norm.weight __a = roberta.model.encoder.lm_head.layer_norm.bias __a = roberta.model.encoder.lm_head.weight __a = roberta.model.encoder.lm_head.bias # Let's check that we get the same results. __a = roberta.encode(a ).unsqueeze(0 ) # batch of size 1 __a = model(a )[0] if classification_head: __a = roberta.model.classification_heads["mnli"](roberta.extract_features(a ) ) else: __a = roberta.model(a )[0] print(our_output.shape , their_output.shape ) __a = torch.max(torch.abs(our_output - their_output ) ).item() print(F"max_absolute_diff = {max_absolute_diff}" ) # ~ 1e-7 __a = 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" ) pathlib.Path(a ).mkdir(parents=a , exist_ok=a ) print(F"Saving model to {pytorch_dump_folder_path}" ) model.save_pretrained(a ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__:List[str] = 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.""" ) SCREAMING_SNAKE_CASE__:int = parser.parse_args() convert_xlm_roberta_xl_checkpoint_to_pytorch( args.roberta_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
706
"""simple docstring""" import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class snake_case__ : def __init__( self , lowerCamelCase , lowerCamelCase=99 , lowerCamelCase=13 , lowerCamelCase=7 , lowerCamelCase=9 , lowerCamelCase=True , lowerCamelCase=True , lowerCamelCase=False , lowerCamelCase=32 , lowerCamelCase=5 , lowerCamelCase=4 , lowerCamelCase=37 , lowerCamelCase=8 , lowerCamelCase=0.1 , lowerCamelCase=0.002 , lowerCamelCase=1 , lowerCamelCase=0 , lowerCamelCase=0 , lowerCamelCase=None , lowerCamelCase=None , ): __a = parent __a = batch_size __a = encoder_seq_length __a = decoder_seq_length # For common tests __a = self.decoder_seq_length __a = is_training __a = use_attention_mask __a = use_labels __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = d_ff __a = relative_attention_num_buckets __a = dropout_rate __a = initializer_factor __a = eos_token_id __a = pad_token_id __a = decoder_start_token_id __a = None __a = decoder_layers def a__ ( self ): return TaConfig.from_pretrained("google/umt5-base" ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , ): if attention_mask is None: __a = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: __a = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: __a = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=lowerCamelCase ) if decoder_head_mask is None: __a = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=lowerCamelCase ) if cross_attn_head_mask is None: __a = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=lowerCamelCase ) 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, } def a__ ( self ): __a = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) __a = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input __a = input_ids.clamp(self.pad_token_id + 1 ) __a = decoder_input_ids.clamp(self.pad_token_id + 1 ) __a = self.get_config() __a = config.num_attention_heads __a = self.prepare_inputs_dict(lowerCamelCase , lowerCamelCase , lowerCamelCase ) return config, input_dict def a__ ( self ): __a , __a = self.prepare_config_and_inputs() return config, inputs_dict def a__ ( self ): return TaConfig( vocab_size=166 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def a__ ( self ): return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , ): __a = UMTaModel(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model( input_ids=lowerCamelCase , decoder_input_ids=lowerCamelCase , attention_mask=lowerCamelCase , decoder_attention_mask=lowerCamelCase , ) __a = model(input_ids=lowerCamelCase , decoder_input_ids=lowerCamelCase ) __a = result.last_hidden_state __a = result.past_key_values __a = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(lowerCamelCase ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , ): __a = UMTaModel(config=lowerCamelCase ).get_decoder().to(lowerCamelCase ).eval() # first forward pass __a = model(lowerCamelCase , use_cache=lowerCamelCase ) __a = model(lowerCamelCase ) __a = model(lowerCamelCase , use_cache=lowerCamelCase ) self.parent.assertTrue(len(lowerCamelCase ) == len(lowerCamelCase ) ) self.parent.assertTrue(len(lowerCamelCase ) == len(lowerCamelCase ) + 1 ) __a , __a = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __a = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and __a = torch.cat([input_ids, next_tokens] , dim=-1 ) __a = model(lowerCamelCase )["last_hidden_state"] __a = model(lowerCamelCase , past_key_values=lowerCamelCase )["last_hidden_state"] # select random slice __a = ids_tensor((1,) , output_from_past.shape[-1] ).item() __a = output_from_no_past[:, -1, random_slice_idx].detach() __a = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(lowerCamelCase , lowerCamelCase , atol=1E-3 ) ) def a__ ( self , lowerCamelCase , lowerCamelCase , ): __a = UMTaModel(config=lowerCamelCase ).to(lowerCamelCase ).half().eval() __a = model(**lowerCamelCase )["last_hidden_state"] self.parent.assertFalse(torch.isnan(lowerCamelCase ).any().item() ) @require_torch class snake_case__ ( snake_case_, snake_case_, snake_case_, unittest.TestCase ): _snake_case : Union[str, Any] = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) _snake_case : int = (UMTaForConditionalGeneration,) if is_torch_available() else () _snake_case : Optional[int] = ( { """conversational""": UMTaForConditionalGeneration, """feature-extraction""": UMTaModel, """summarization""": UMTaForConditionalGeneration, """text2text-generation""": UMTaForConditionalGeneration, """translation""": UMTaForConditionalGeneration, """question-answering""": UMTaForQuestionAnswering, } if is_torch_available() else {} ) _snake_case : List[Any] = True _snake_case : Union[str, Any] = False _snake_case : Union[str, Any] = False _snake_case : Tuple = True _snake_case : List[str] = True # The small UMT5 model needs higher percentages for CPU/MP tests _snake_case : Optional[Any] = [0.8, 0.9] def a__ ( self ): __a = UMTaModelTester(self ) @unittest.skip("Test has a segmentation fault on torch 1.8.0" ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() __a = UMTaModel(config_and_inputs[0] ).to(lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( lowerCamelCase , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , F"{tmpdirname}/t5_test.onnx" , export_params=lowerCamelCase , opset_version=9 , input_names=["input_ids", "decoder_input_ids"] , ) @unittest.skipIf(torch_device == "cpu" , "Cant do half precision" ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*lowerCamelCase ) def a__ ( self ): __a = ["encoder_attentions", "decoder_attentions", "cross_attentions"] __a = self.model_tester.prepare_config_and_inputs() __a = config_and_inputs[0] __a = UMTaForConditionalGeneration(lowerCamelCase ).eval() model.to(lowerCamelCase ) __a = { "head_mask": torch.zeros(config.num_layers , config.num_heads , device=lowerCamelCase ), "decoder_head_mask": torch.zeros(config.num_decoder_layers , config.num_heads , device=lowerCamelCase ), "cross_attn_head_mask": torch.zeros(config.num_decoder_layers , config.num_heads , device=lowerCamelCase ), } for attn_name, (name, mask) in zip(lowerCamelCase , head_masking.items() ): __a = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": __a = torch.ones( config.num_decoder_layers , config.num_heads , device=lowerCamelCase ) __a = model.generate( config_and_inputs[1]["input_ids"] , num_beams=1 , max_length=3 , output_attentions=lowerCamelCase , return_dict_in_generate=lowerCamelCase , **lowerCamelCase , ) # We check the state of decoder_attentions and cross_attentions just from the last step __a = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip("Does not work on the tiny model as we keep hitting edge cases." ) def a__ ( self ): pass @require_torch @require_sentencepiece @require_tokenizers class snake_case__ ( unittest.TestCase ): @slow @unittest.skip( "Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged" ) def a__ ( self ): __a = UMTaForConditionalGeneration.from_pretrained("google/umt5-small" , return_dict=lowerCamelCase ).to(lowerCamelCase ) __a = AutoTokenizer.from_pretrained("google/umt5-small" , use_fast=lowerCamelCase , legacy=lowerCamelCase ) __a = [ "Bonjour monsieur <extra_id_0> bien <extra_id_1>.", "No se como puedo <extra_id_0>.", "This is the reason why we <extra_id_0> them.", "The <extra_id_0> walks in <extra_id_1>, seats", "A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.", ] __a = tokenizer(lowerCamelCase , return_tensors="pt" , padding=lowerCamelCase ).input_ids # fmt: off __a = torch.tensor( [ [ 38530, 210703, 256299, 1410, 256298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 826, 321, 671, 25922, 256299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1460, 339, 312, 19014, 10620, 758, 256299, 2355,274, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 517, 256299, 14869, 281, 301, 256298, 275, 119983,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 320, 256299, 14869, 281, 2234, 289, 2275, 333,61391, 289, 256298, 543, 256297, 168714, 329, 256296,274, 1], ] ) # fmt: on torch.testing.assert_allclose(lowerCamelCase , lowerCamelCase ) __a = model.generate(input_ids.to(lowerCamelCase ) ) __a = [ "<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>", "<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", "<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", "<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", "<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", ] __a = tokenizer.batch_decode(lowerCamelCase ) self.assertEqual(lowerCamelCase , lowerCamelCase )
67
0
"""simple docstring""" import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class snake_case__ ( snake_case_ ): _snake_case : Tuple = """Speech2TextFeatureExtractor""" _snake_case : Dict = """Speech2TextTokenizer""" def __init__( self , lowerCamelCase , lowerCamelCase ): super().__init__(lowerCamelCase , lowerCamelCase ) __a = self.feature_extractor __a = False def __call__( self , *lowerCamelCase , **lowerCamelCase ): # For backward compatibility if self._in_target_context_manager: return self.current_processor(*lowerCamelCase , **lowerCamelCase ) if "raw_speech" in kwargs: warnings.warn("Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead." ) __a = kwargs.pop("raw_speech" ) else: __a = kwargs.pop("audio" , lowerCamelCase ) __a = kwargs.pop("sampling_rate" , lowerCamelCase ) __a = kwargs.pop("text" , lowerCamelCase ) if len(lowerCamelCase ) > 0: __a = args[0] __a = args[1:] if audio is None and text is None: raise ValueError("You need to specify either an `audio` or `text` input to process." ) if audio is not None: __a = self.feature_extractor(lowerCamelCase , *lowerCamelCase , sampling_rate=lowerCamelCase , **lowerCamelCase ) if text is not None: __a = self.tokenizer(lowerCamelCase , **lowerCamelCase ) if text is None: return inputs elif audio is None: return encodings else: __a = encodings["input_ids"] return inputs def a__ ( self , *lowerCamelCase , **lowerCamelCase ): return self.tokenizer.batch_decode(*lowerCamelCase , **lowerCamelCase ) def a__ ( self , *lowerCamelCase , **lowerCamelCase ): return self.tokenizer.decode(*lowerCamelCase , **lowerCamelCase ) @contextmanager def a__ ( self ): warnings.warn( "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your " "labels by using the argument `text` of the regular `__call__` method (either in the same call as " "your audio inputs, or in a separate call." ) __a = True __a = self.tokenizer yield __a = self.feature_extractor __a = False
707
"""simple docstring""" import argparse import torch from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert from transformers.utils import logging logging.set_verbosity_info() def _lowerCamelCase( a , a , a ): # Initialise PyTorch model __a = MobileBertConfig.from_json_file(a ) print(F"Building PyTorch model from configuration: {config}" ) __a = MobileBertForPreTraining(a ) # Load weights from tf checkpoint __a = load_tf_weights_in_mobilebert(a , a , a ) # Save pytorch-model print(F"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , a ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__:List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--mobilebert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained MobileBERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) SCREAMING_SNAKE_CASE__:List[Any] = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.mobilebert_config_file, args.pytorch_dump_path)
67
0
import argparse import os import jax as jnp import numpy as onp import torch import torch.nn as nn from music_spectrogram_diffusion import inference from tax import checkpoints from diffusers import DDPMScheduler, OnnxRuntimeModel, SpectrogramDiffusionPipeline from diffusers.pipelines.spectrogram_diffusion import SpectrogramContEncoder, SpectrogramNotesEncoder, TaFilmDecoder SCREAMING_SNAKE_CASE__:Tuple = """base_with_context""" def _lowerCamelCase( a , a ): __a = nn.Parameter(torch.FloatTensor(weights["token_embedder"]["embedding"] ) ) __a = nn.Parameter( torch.FloatTensor(weights["Embed_0"]["embedding"] ) , requires_grad=a ) for lyr_num, lyr in enumerate(model.encoders ): __a = weights[F"layers_{lyr_num}"] __a = nn.Parameter( torch.FloatTensor(ly_weight["pre_attention_layer_norm"]["scale"] ) ) __a = ly_weight["attention"] __a = nn.Parameter(torch.FloatTensor(attention_weights["query"]["kernel"].T ) ) __a = nn.Parameter(torch.FloatTensor(attention_weights["key"]["kernel"].T ) ) __a = nn.Parameter(torch.FloatTensor(attention_weights["value"]["kernel"].T ) ) __a = nn.Parameter(torch.FloatTensor(attention_weights["out"]["kernel"].T ) ) __a = nn.Parameter(torch.FloatTensor(ly_weight["pre_mlp_layer_norm"]["scale"] ) ) __a = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_0"]["kernel"].T ) ) __a = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_1"]["kernel"].T ) ) __a = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wo"]["kernel"].T ) ) __a = nn.Parameter(torch.FloatTensor(weights["encoder_norm"]["scale"] ) ) return model def _lowerCamelCase( a , a ): __a = nn.Parameter(torch.FloatTensor(weights["input_proj"]["kernel"].T ) ) __a = nn.Parameter( torch.FloatTensor(weights["Embed_0"]["embedding"] ) , requires_grad=a ) for lyr_num, lyr in enumerate(model.encoders ): __a = weights[F"layers_{lyr_num}"] __a = ly_weight["attention"] __a = nn.Parameter(torch.FloatTensor(attention_weights["query"]["kernel"].T ) ) __a = nn.Parameter(torch.FloatTensor(attention_weights["key"]["kernel"].T ) ) __a = nn.Parameter(torch.FloatTensor(attention_weights["value"]["kernel"].T ) ) __a = nn.Parameter(torch.FloatTensor(attention_weights["out"]["kernel"].T ) ) __a = nn.Parameter( torch.FloatTensor(ly_weight["pre_attention_layer_norm"]["scale"] ) ) __a = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_0"]["kernel"].T ) ) __a = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_1"]["kernel"].T ) ) __a = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wo"]["kernel"].T ) ) __a = nn.Parameter(torch.FloatTensor(ly_weight["pre_mlp_layer_norm"]["scale"] ) ) __a = nn.Parameter(torch.FloatTensor(weights["encoder_norm"]["scale"] ) ) return model def _lowerCamelCase( a , a ): __a = nn.Parameter(torch.FloatTensor(weights["time_emb_dense0"]["kernel"].T ) ) __a = nn.Parameter(torch.FloatTensor(weights["time_emb_dense1"]["kernel"].T ) ) __a = nn.Parameter( torch.FloatTensor(weights["Embed_0"]["embedding"] ) , requires_grad=a ) __a = nn.Parameter( torch.FloatTensor(weights["continuous_inputs_projection"]["kernel"].T ) ) for lyr_num, lyr in enumerate(model.decoders ): __a = weights[F"layers_{lyr_num}"] __a = nn.Parameter( torch.FloatTensor(ly_weight["pre_self_attention_layer_norm"]["scale"] ) ) __a = nn.Parameter( torch.FloatTensor(ly_weight["FiLMLayer_0"]["DenseGeneral_0"]["kernel"].T ) ) __a = ly_weight["self_attention"] __a = nn.Parameter(torch.FloatTensor(attention_weights["query"]["kernel"].T ) ) __a = nn.Parameter(torch.FloatTensor(attention_weights["key"]["kernel"].T ) ) __a = nn.Parameter(torch.FloatTensor(attention_weights["value"]["kernel"].T ) ) __a = nn.Parameter(torch.FloatTensor(attention_weights["out"]["kernel"].T ) ) __a = ly_weight["MultiHeadDotProductAttention_0"] __a = nn.Parameter(torch.FloatTensor(attention_weights["query"]["kernel"].T ) ) __a = nn.Parameter(torch.FloatTensor(attention_weights["key"]["kernel"].T ) ) __a = nn.Parameter(torch.FloatTensor(attention_weights["value"]["kernel"].T ) ) __a = nn.Parameter(torch.FloatTensor(attention_weights["out"]["kernel"].T ) ) __a = nn.Parameter( torch.FloatTensor(ly_weight["pre_cross_attention_layer_norm"]["scale"] ) ) __a = nn.Parameter(torch.FloatTensor(ly_weight["pre_mlp_layer_norm"]["scale"] ) ) __a = nn.Parameter( torch.FloatTensor(ly_weight["FiLMLayer_1"]["DenseGeneral_0"]["kernel"].T ) ) __a = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_0"]["kernel"].T ) ) __a = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wi_1"]["kernel"].T ) ) __a = nn.Parameter(torch.FloatTensor(ly_weight["mlp"]["wo"]["kernel"].T ) ) __a = nn.Parameter(torch.FloatTensor(weights["decoder_norm"]["scale"] ) ) __a = nn.Parameter(torch.FloatTensor(weights["spec_out_dense"]["kernel"].T ) ) return model def _lowerCamelCase( a ): __a = checkpoints.load_tax_checkpoint(args.checkpoint_path ) __a = jnp.tree_util.tree_map(onp.array , a ) __a = [ "from __gin__ import dynamic_registration", "from music_spectrogram_diffusion.models.diffusion import diffusion_utils", "diffusion_utils.ClassifierFreeGuidanceConfig.eval_condition_weight = 2.0", "diffusion_utils.DiffusionConfig.classifier_free_guidance = @diffusion_utils.ClassifierFreeGuidanceConfig()", ] __a = os.path.join(args.checkpoint_path , ".." , "config.gin" ) __a = inference.parse_training_gin_file(a , a ) __a = inference.InferenceModel(args.checkpoint_path , a ) __a = DDPMScheduler(beta_schedule="squaredcos_cap_v2" , variance_type="fixed_large" ) __a = SpectrogramNotesEncoder( max_length=synth_model.sequence_length["inputs"] , vocab_size=synth_model.model.module.config.vocab_size , d_model=synth_model.model.module.config.emb_dim , dropout_rate=synth_model.model.module.config.dropout_rate , num_layers=synth_model.model.module.config.num_encoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , feed_forward_proj="gated-gelu" , ) __a = SpectrogramContEncoder( input_dims=synth_model.audio_codec.n_dims , targets_context_length=synth_model.sequence_length["targets_context"] , d_model=synth_model.model.module.config.emb_dim , dropout_rate=synth_model.model.module.config.dropout_rate , num_layers=synth_model.model.module.config.num_encoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , feed_forward_proj="gated-gelu" , ) __a = TaFilmDecoder( input_dims=synth_model.audio_codec.n_dims , targets_length=synth_model.sequence_length["targets_context"] , max_decoder_noise_time=synth_model.model.module.config.max_decoder_noise_time , d_model=synth_model.model.module.config.emb_dim , num_layers=synth_model.model.module.config.num_decoder_layers , num_heads=synth_model.model.module.config.num_heads , d_kv=synth_model.model.module.config.head_dim , d_ff=synth_model.model.module.config.mlp_dim , dropout_rate=synth_model.model.module.config.dropout_rate , ) __a = load_notes_encoder(ta_checkpoint["target"]["token_encoder"] , a ) __a = load_continuous_encoder(ta_checkpoint["target"]["continuous_encoder"] , a ) __a = load_decoder(ta_checkpoint["target"]["decoder"] , a ) __a = OnnxRuntimeModel.from_pretrained("kashif/soundstream_mel_decoder" ) __a = SpectrogramDiffusionPipeline( notes_encoder=a , continuous_encoder=a , decoder=a , scheduler=a , melgan=a , ) if args.save: pipe.save_pretrained(args.output_path ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__:Optional[int] = argparse.ArgumentParser() parser.add_argument("""--output_path""", default=None, type=str, required=True, help="""Path to the converted model.""") parser.add_argument( """--save""", default=True, type=bool, required=False, help="""Whether to save the converted model or not.""" ) parser.add_argument( """--checkpoint_path""", default=F'''{MODEL}/checkpoint_500000''', type=str, required=False, help="""Path to the original jax model checkpoint.""", ) SCREAMING_SNAKE_CASE__:Dict = parser.parse_args() main(args)
708
"""simple docstring""" import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class snake_case__ ( snake_case_ ): def a__ ( self , lowerCamelCase ): with open(lowerCamelCase , encoding="utf-8" ) as input_file: __a = re.compile(R"(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)" ) __a = input_file.read() __a = regexp.search(lowerCamelCase ) return match def a__ ( self , lowerCamelCase ): with open(lowerCamelCase , encoding="utf-8" ) as input_file: __a = re.compile(R"#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()" , re.DOTALL ) __a = input_file.read() # use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search` __a = regexp.finditer(lowerCamelCase ) __a = [match for match in matches if match is not None and match.group(1 ) is not None] return matches[0] if matches else None def a__ ( self ): __a = Path("./datasets" ) __a = list(dataset_paths.absolute().glob("**/*.py" ) ) for dataset in dataset_files: if self._no_encoding_on_file_open(str(lowerCamelCase ) ): raise AssertionError(F"open(...) must use utf-8 encoding in {dataset}" ) def a__ ( self ): __a = Path("./datasets" ) __a = list(dataset_paths.absolute().glob("**/*.py" ) ) for dataset in dataset_files: if self._no_print_statements(str(lowerCamelCase ) ): raise AssertionError(F"print statement found in {dataset}. Use datasets.logger/logging instead." )
67
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) SCREAMING_SNAKE_CASE__:Optional[int] = {"""configuration_vit_mae""": ["""VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """ViTMAEConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__:Union[str, Any] = [ """VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST""", """ViTMAEForPreTraining""", """ViTMAELayer""", """ViTMAEModel""", """ViTMAEPreTrainedModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__:str = [ """TFViTMAEForPreTraining""", """TFViTMAEModel""", """TFViTMAEPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_vit_mae import VIT_MAE_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMAEConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_mae import ( VIT_MAE_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMAEForPreTraining, ViTMAELayer, ViTMAEModel, ViTMAEPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vit_mae import TFViTMAEForPreTraining, TFViTMAEModel, TFViTMAEPreTrainedModel else: import sys SCREAMING_SNAKE_CASE__:int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
709
"""simple docstring""" from .imports import is_rich_available if is_rich_available(): from rich.traceback import install install(show_locals=False) else: raise ModuleNotFoundError("""To use the rich extension, install rich with `pip install rich`""")
67
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__:List[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:List[Any] = { """facebook/data2vec-vision-base-ft""": ( """https://huggingface.co/facebook/data2vec-vision-base-ft/resolve/main/config.json""" ), } class snake_case__ ( snake_case_ ): _snake_case : Any = """data2vec-vision""" def __init__( self , lowerCamelCase=768 , lowerCamelCase=12 , lowerCamelCase=12 , lowerCamelCase=3072 , lowerCamelCase="gelu" , lowerCamelCase=0.0 , lowerCamelCase=0.0 , lowerCamelCase=0.02 , lowerCamelCase=1E-12 , lowerCamelCase=224 , lowerCamelCase=16 , lowerCamelCase=3 , lowerCamelCase=False , lowerCamelCase=False , lowerCamelCase=False , lowerCamelCase=False , lowerCamelCase=0.1 , lowerCamelCase=0.1 , lowerCamelCase=True , lowerCamelCase=[3, 5, 7, 11] , lowerCamelCase=[1, 2, 3, 6] , lowerCamelCase=True , lowerCamelCase=0.4 , lowerCamelCase=256 , lowerCamelCase=1 , lowerCamelCase=False , lowerCamelCase=255 , **lowerCamelCase , ): super().__init__(**lowerCamelCase ) __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 = initializer_range __a = layer_norm_eps __a = image_size __a = patch_size __a = num_channels __a = use_mask_token __a = use_absolute_position_embeddings __a = use_relative_position_bias __a = use_shared_relative_position_bias __a = layer_scale_init_value __a = drop_path_rate __a = use_mean_pooling # decode head attributes (semantic segmentation) __a = out_indices __a = pool_scales # auxiliary head attributes (semantic segmentation) __a = use_auxiliary_head __a = auxiliary_loss_weight __a = auxiliary_channels __a = auxiliary_num_convs __a = auxiliary_concat_input __a = semantic_loss_ignore_index class snake_case__ ( snake_case_ ): _snake_case : Optional[Any] = version.parse("""1.11""" ) @property def a__ ( self ): return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def a__ ( self ): return 1E-4
710
"""simple docstring""" import heapq import sys import numpy as np SCREAMING_SNAKE_CASE__:Optional[int] = tuple[int, int] class snake_case__ : def __init__( self ): __a = [] __a = set() def a__ ( self ): if not self.empty(): return self.elements[0][0] else: return float("inf" ) def a__ ( self ): return len(self.elements ) == 0 def a__ ( self , lowerCamelCase , lowerCamelCase ): if item not in self.set: heapq.heappush(self.elements , (priority, item) ) self.set.add(lowerCamelCase ) else: # update # print("update", item) __a = [] ((__a) , (__a)) = heapq.heappop(self.elements ) while x != item: temp.append((pri, x) ) ((__a) , (__a)) = heapq.heappop(self.elements ) temp.append((priority, item) ) for pro, xxx in temp: heapq.heappush(self.elements , (pro, xxx) ) def a__ ( self , lowerCamelCase ): if item in self.set: self.set.remove(lowerCamelCase ) __a = [] ((__a) , (__a)) = heapq.heappop(self.elements ) while x != item: temp.append((pro, x) ) ((__a) , (__a)) = heapq.heappop(self.elements ) for prito, yyy in temp: heapq.heappush(self.elements , (prito, yyy) ) def a__ ( self ): return self.elements[0][1] def a__ ( self ): ((__a) , (__a)) = heapq.heappop(self.elements ) self.set.remove(lowerCamelCase ) return (priority, item) def _lowerCamelCase( a , a ): # euclidean distance __a = np.array(a ) __a = np.array(a ) return np.linalg.norm(a - b ) def _lowerCamelCase( a , a ): # integer division by time variable return consistent_heuristic(a , a ) // t def _lowerCamelCase( a , a ): # manhattan distance return abs(p[0] - goal[0] ) + abs(p[1] - goal[1] ) def _lowerCamelCase( a , a , a , a ): __a = g_function[start] + Wa * heuristics[i](a , a ) return ans def _lowerCamelCase( a , a , a ): __a = np.chararray((n, n) ) for i in range(a ): for j in range(a ): __a = "*" for i in range(a ): for j in range(a ): if (j, (n - 1) - i) in blocks: __a = "#" __a = "-" __a = back_pointer[goal] while x != start: ((__a) , (__a)) = x # print(x) __a = "-" __a = back_pointer[x] __a = "-" for i in range(a ): for j in range(a ): if (i, j) == (0, n - 1): print(grid[i][j] , end=" " ) print("<-- End position" , end=" " ) else: print(grid[i][j] , end=" " ) print() print("^" ) print("Start position" ) print() print("# is an obstacle" ) print("- is the path taken by algorithm" ) print("PATH TAKEN BY THE ALGORITHM IS:-" ) __a = back_pointer[goal] while x != start: print(a , end=" " ) __a = back_pointer[x] print(a ) sys.exit() def _lowerCamelCase( a ): if p[0] < 0 or p[0] > n - 1: return False if p[1] < 0 or p[1] > n - 1: return False return True def _lowerCamelCase( a , a , a , a , a , a , a , a , ): for itera in range(a ): open_list[itera].remove_element(a ) # print("s", s) # print("j", j) ((__a) , (__a)) = s __a = (x - 1, y) __a = (x + 1, y) __a = (x, y + 1) __a = (x, y - 1) for neighbours in [left, right, up, down]: if neighbours not in blocks: if valid(a ) and neighbours not in visited: # print("neighbour", neighbours) visited.add(a ) __a = -1 __a = float("inf" ) if valid(a ) and g_function[neighbours] > g_function[s] + 1: __a = g_function[s] + 1 __a = s if neighbours not in close_list_anchor: open_list[0].put(a , key(a , 0 , a , a ) ) if neighbours not in close_list_inad: for var in range(1 , a ): if key(a , a , a , a ) <= Wa * key( a , 0 , a , a ): open_list[j].put( a , key(a , a , a , a ) ) def _lowerCamelCase( ): __a = [] for x in range(1 , 5 ): for y in range(1 , 6 ): some_list.append((x, y) ) for x in range(1_5 , 2_0 ): some_list.append((x, 1_7) ) for x in range(1_0 , 1_9 ): for y in range(1 , 1_5 ): some_list.append((x, y) ) # L block for x in range(1 , 4 ): for y in range(1_2 , 1_9 ): some_list.append((x, y) ) for x in range(3 , 1_3 ): for y in range(1_6 , 1_9 ): some_list.append((x, y) ) return some_list SCREAMING_SNAKE_CASE__:Any = {0: consistent_heuristic, 1: heuristic_a, 2: heuristic_a} SCREAMING_SNAKE_CASE__:str = [ (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1), ] SCREAMING_SNAKE_CASE__:int = make_common_ground() SCREAMING_SNAKE_CASE__:List[str] = blocks_blk # hyper parameters SCREAMING_SNAKE_CASE__:str = 1 SCREAMING_SNAKE_CASE__:Union[str, Any] = 1 SCREAMING_SNAKE_CASE__:Union[str, Any] = 20 SCREAMING_SNAKE_CASE__:Dict = 3 # one consistent and two other inconsistent # start and end destination SCREAMING_SNAKE_CASE__:Dict = (0, 0) SCREAMING_SNAKE_CASE__:Optional[Any] = (n - 1, n - 1) SCREAMING_SNAKE_CASE__:List[str] = 1 def _lowerCamelCase( a , a , a ): __a = {start: 0, goal: float("inf" )} __a = {start: -1, goal: -1} __a = [] __a = set() for i in range(a ): open_list.append(PriorityQueue() ) open_list[i].put(a , key(a , a , a , a ) ) __a = [] __a = [] while open_list[0].minkey() < float("inf" ): for i in range(1 , a ): # print(open_list[0].minkey(), open_list[i].minkey()) if open_list[i].minkey() <= Wa * open_list[0].minkey(): global t t += 1 if g_function[goal] <= open_list[i].minkey(): if g_function[goal] < float("inf" ): do_something(a , a , a ) else: __a , __a = open_list[i].top_show() visited.add(a ) expand_state( a , a , a , a , a , a , a , a , ) close_list_inad.append(a ) else: if g_function[goal] <= open_list[0].minkey(): if g_function[goal] < float("inf" ): do_something(a , a , a ) else: __a = open_list[0].top_show() visited.add(a ) expand_state( a , 0 , a , a , a , a , a , a , ) close_list_anchor.append(a ) print("No path found to goal" ) print() for i in range(n - 1 , -1 , -1 ): for j in range(a ): if (j, i) in blocks: print("#" , end=" " ) elif (j, i) in back_pointer: if (j, i) == (n - 1, n - 1): print("*" , end=" " ) else: print("-" , end=" " ) else: print("*" , end=" " ) if (j, i) == (n - 1, n - 1): print("<-- End position" , end=" " ) print() print("^" ) print("Start position" ) print() print("# is an obstacle" ) print("- is the path taken by algorithm" ) if __name__ == "__main__": multi_a_star(start, goal, n_heuristic)
67
0
"""simple docstring""" import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def _lowerCamelCase( a , a , a=1_0_2_4 , a=1_0_2_4 , a=False , **a ): __a = AutoTokenizer.from_pretrained(a ) __a = SeqaSeqDataset(a , a , a , a , type_path="train" , **a ) __a = tok.pad_token_id def get_lens(a ): __a = tqdm( DataLoader(a , batch_size=5_1_2 , num_workers=8 , shuffle=a , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) __a = [] for batch in dl: __a = batch["input_ids"].ne(a ).sum(1 ).tolist() __a = batch["labels"].ne(a ).sum(1 ).tolist() if consider_target: for src, tgt in zip(a , a ): max_lens.append(max(a , a ) ) else: max_lens.extend(a ) return max_lens __a = get_lens(a ) __a = SeqaSeqDataset(a , a , a , a , type_path="val" , **a ) __a = get_lens(a ) pickle_save(a , train_ds.len_file ) pickle_save(a , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
711
"""simple docstring""" SCREAMING_SNAKE_CASE__:Any = """Alexander Joslin""" import operator as op from .stack import Stack def _lowerCamelCase( a ): __a = {"*": op.mul, "/": op.truediv, "+": op.add, "-": op.sub} __a = Stack() __a = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(a ) ) elif i in operators: # RULE 2 operator_stack.push(a ) elif i == ")": # RULE 4 __a = operator_stack.peek() operator_stack.pop() __a = operand_stack.peek() operand_stack.pop() __a = operand_stack.peek() operand_stack.pop() __a = operators[opr](a , a ) operand_stack.push(a ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": SCREAMING_SNAKE_CASE__:Tuple = """(5 + ((4 * 2) * (2 + 3)))""" # answer = 45 print(F'''{equation} = {dijkstras_two_stack_algorithm(equation)}''')
67
0
"""simple docstring""" import argparse import os import numpy as np import tensorflow as tf import torch from transformers import BertModel def _lowerCamelCase( a , a , a ): __a = ("dense.weight", "attention.self.query", "attention.self.key", "attention.self.value") __a = ( ("layer.", "layer_"), ("word_embeddings.weight", "word_embeddings"), ("position_embeddings.weight", "position_embeddings"), ("token_type_embeddings.weight", "token_type_embeddings"), (".", "/"), ("LayerNorm/weight", "LayerNorm/gamma"), ("LayerNorm/bias", "LayerNorm/beta"), ("weight", "kernel"), ) if not os.path.isdir(a ): os.makedirs(a ) __a = model.state_dict() def to_tf_var_name(a ): for patt, repl in iter(a ): __a = name.replace(a , a ) return F"bert/{name}" def create_tf_var(a , a , a ): __a = tf.dtypes.as_dtype(tensor.dtype ) __a = tf.get_variable(dtype=a , shape=tensor.shape , name=a , initializer=tf.zeros_initializer() ) session.run(tf.variables_initializer([tf_var] ) ) session.run(a ) return tf_var tf.reset_default_graph() with tf.Session() as session: for var_name in state_dict: __a = to_tf_var_name(a ) __a = state_dict[var_name].numpy() if any(x in var_name for x in tensors_to_transpose ): __a = torch_tensor.T __a = create_tf_var(tensor=a , name=a , session=a ) tf.keras.backend.set_value(a , a ) __a = session.run(a ) print(F"Successfully created {tf_name}: {np.allclose(a , a )}" ) __a = tf.train.Saver(tf.trainable_variables() ) saver.save(a , os.path.join(a , model_name.replace("-" , "_" ) + ".ckpt" ) ) def _lowerCamelCase( a=None ): __a = argparse.ArgumentParser() parser.add_argument("--model_name" , type=a , required=a , help="model name e.g. bert-base-uncased" ) parser.add_argument( "--cache_dir" , type=a , default=a , required=a , help="Directory containing pytorch model" ) parser.add_argument("--pytorch_model_path" , type=a , required=a , help="/path/to/<pytorch-model-name>.bin" ) parser.add_argument("--tf_cache_dir" , type=a , required=a , help="Directory in which to save tensorflow model" ) __a = parser.parse_args(a ) __a = BertModel.from_pretrained( pretrained_model_name_or_path=args.model_name , state_dict=torch.load(args.pytorch_model_path ) , cache_dir=args.cache_dir , ) convert_pytorch_checkpoint_to_tf(model=a , ckpt_dir=args.tf_cache_dir , model_name=args.model_name ) if __name__ == "__main__": main()
712
"""simple docstring""" from math import pi def _lowerCamelCase( a , a ): return 2 * pi * radius * (angle / 3_6_0) if __name__ == "__main__": print(arc_length(90, 10))
67
0
import numpy as np class snake_case__ : def __init__( self ): __a = (0, 0) __a = None __a = 0 __a = 0 __a = 0 def __eq__( self , lowerCamelCase ): return self.position == cell.position def a__ ( self ): print(self.position ) class snake_case__ : def __init__( self , lowerCamelCase=(5, 5) ): __a = np.zeros(lowerCamelCase ) __a = world_size[0] __a = world_size[1] def a__ ( self ): print(self.w ) def a__ ( self , lowerCamelCase ): __a = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] __a = cell.position[0] __a = cell.position[1] __a = [] for n in neughbour_cord: __a = current_x + n[0] __a = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: __a = Cell() __a = (x, y) __a = cell neighbours.append(lowerCamelCase ) return neighbours def _lowerCamelCase( a , a , a ): __a = [] __a = [] _open.append(a ) while _open: __a = np.argmin([n.f for n in _open] ) __a = _open[min_f] _closed.append(_open.pop(a ) ) if current == goal: break for n in world.get_neigbours(a ): for c in _closed: if c == n: continue __a = current.g + 1 __a , __a = n.position __a , __a = goal.position __a = (ya - ya) ** 2 + (xa - xa) ** 2 __a = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(a ) __a = [] while current.parent is not None: path.append(current.position ) __a = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": SCREAMING_SNAKE_CASE__:Any = Gridworld() # Start position and goal SCREAMING_SNAKE_CASE__:Tuple = Cell() SCREAMING_SNAKE_CASE__:Dict = (0, 0) SCREAMING_SNAKE_CASE__:Optional[int] = Cell() SCREAMING_SNAKE_CASE__:List[str] = (4, 4) print(F'''path from {start.position} to {goal.position}''') SCREAMING_SNAKE_CASE__:Union[str, Any] = astar(world, start, goal) # Just for visual reasons. for i in s: SCREAMING_SNAKE_CASE__:List[Any] = 1 print(world.w)
713
"""simple docstring""" from typing import Dict, Iterable, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging SCREAMING_SNAKE_CASE__:List[str] = logging.get_logger(__name__) class snake_case__ ( snake_case_ ): _snake_case : Dict = ["""pixel_values"""] def __init__( self , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = PILImageResampling.BICUBIC , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = True , lowerCamelCase = 1 / 255 , lowerCamelCase = True , lowerCamelCase = IMAGENET_DEFAULT_MEAN , lowerCamelCase = IMAGENET_DEFAULT_STD , **lowerCamelCase , ): super().__init__(**lowerCamelCase ) __a = size if size is not None else {"shortest_edge": 224} __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) __a = crop_size if crop_size is not None else {"height": 224, "width": 224} __a = get_size_dict(lowerCamelCase , param_name="crop_size" ) __a = do_resize __a = size __a = resample __a = do_center_crop __a = crop_size __a = do_rescale __a = rescale_factor __a = do_normalize __a = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN __a = image_std if image_std is not None else IMAGENET_DEFAULT_STD def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = PILImageResampling.BICUBIC , lowerCamelCase = None , **lowerCamelCase , ): __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) # size_dict is a dict with either keys "height" and "width" or "shortest_edge" if "shortest_edge" in size: __a = int((256 / 224) * size["shortest_edge"] ) __a = get_resize_output_image_size(lowerCamelCase , size=lowerCamelCase , default_to_square=lowerCamelCase ) __a = {"height": output_size[0], "width": output_size[1]} if "height" not in size_dict or "width" not in size_dict: raise ValueError( F"Size dict must have keys 'height' and 'width' or 'shortest_edge'. Got {size_dict.keys()}" ) return resize( lowerCamelCase , size=(size_dict["height"], size_dict["width"]) , resample=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): __a = get_size_dict(lowerCamelCase ) if "height" not in size or "width" not in size: raise ValueError(F"Size dict must have keys 'height' and 'width'. Got {size.keys()}" ) return center_crop(lowerCamelCase , size=(size["height"], size["width"]) , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): return rescale(lowerCamelCase , scale=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): return normalize(lowerCamelCase , mean=lowerCamelCase , std=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = ChannelDimension.FIRST , **lowerCamelCase , ): __a = do_resize if do_resize is not None else self.do_resize __a = resample if resample is not None else self.resample __a = do_center_crop if do_center_crop is not None else self.do_center_crop __a = do_rescale if do_rescale is not None else self.do_rescale __a = rescale_factor if rescale_factor is not None else self.rescale_factor __a = do_normalize if do_normalize is not None else self.do_normalize __a = image_mean if image_mean is not None else self.image_mean __a = image_std if image_std is not None else self.image_std __a = size if size is not None else self.size __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) __a = crop_size if crop_size is not None else self.crop_size __a = get_size_dict(lowerCamelCase , param_name="crop_size" ) __a = make_list_of_images(lowerCamelCase ) if not valid_images(lowerCamelCase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. __a = [to_numpy_array(lowerCamelCase ) for image in images] if do_resize: __a = [self.resize(lowerCamelCase , lowerCamelCase , lowerCamelCase ) for image in images] if do_center_crop: __a = [self.center_crop(lowerCamelCase , lowerCamelCase ) for image in images] if do_rescale: __a = [self.rescale(lowerCamelCase , lowerCamelCase ) for image in images] if do_normalize: __a = [self.normalize(lowerCamelCase , lowerCamelCase , lowerCamelCase ) for image in images] __a = [to_channel_dimension_format(lowerCamelCase , lowerCamelCase ) for image in images] __a = {"pixel_values": images} return BatchFeature(data=lowerCamelCase , tensor_type=lowerCamelCase )
67
0
"""simple docstring""" def _lowerCamelCase( a ): __a = [0] * len(a ) for i in range(1 , len(a ) ): # use last results for better performance - dynamic programming __a = prefix_result[i - 1] while j > 0 and input_string[i] != input_string[j]: __a = prefix_result[j - 1] if input_string[i] == input_string[j]: j += 1 __a = j return prefix_result def _lowerCamelCase( a ): return max(prefix_function(a ) ) if __name__ == "__main__": import doctest doctest.testmod()
714
"""simple docstring""" import inspect import unittest from transformers import ViTConfig 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 ViTForImageClassification, ViTForMaskedImageModeling, ViTModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class snake_case__ : 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=None , lowerCamelCase=2 , ): __a = parent __a = batch_size __a = image_size __a = patch_size __a = num_channels __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 = encoder_stride # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) __a = (image_size // patch_size) ** 2 __a = num_patches + 1 def a__ ( self ): __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = self.get_config() return config, pixel_values, labels def a__ ( self ): return ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=lowerCamelCase , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = ViTModel(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = ViTForMaskedImageModeling(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __a = 1 __a = ViTForMaskedImageModeling(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __a = model(lowerCamelCase ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = self.type_sequence_label_size __a = ViTForImageClassification(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __a = 1 __a = ViTForImageClassification(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __a = model(lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a__ ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class snake_case__ ( snake_case_, snake_case_, unittest.TestCase ): _snake_case : Any = ( ( ViTModel, ViTForImageClassification, ViTForMaskedImageModeling, ) if is_torch_available() else () ) _snake_case : List[Any] = ( {"""feature-extraction""": ViTModel, """image-classification""": ViTForImageClassification} if is_torch_available() else {} ) _snake_case : int = True _snake_case : int = False _snake_case : str = False _snake_case : Optional[Any] = False def a__ ( self ): __a = ViTModelTester(self ) __a = ConfigTester(self , config_class=lowerCamelCase , has_text_modality=lowerCamelCase , hidden_size=37 ) def a__ ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="ViT does not use inputs_embeds" ) def a__ ( self ): pass def a__ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __a = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCamelCase , nn.Linear ) ) def a__ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(lowerCamelCase ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase ) @slow def a__ ( self ): for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = ViTModel.from_pretrained(lowerCamelCase ) self.assertIsNotNone(lowerCamelCase ) def _lowerCamelCase( ): __a = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class snake_case__ ( unittest.TestCase ): @cached_property def a__ ( self ): return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224" ) if is_vision_available() else None @slow def a__ ( self ): __a = ViTForImageClassification.from_pretrained("google/vit-base-patch16-224" ).to(lowerCamelCase ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase ) # forward pass with torch.no_grad(): __a = model(**lowerCamelCase ) # verify the logits __a = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , lowerCamelCase ) __a = torch.tensor([-0.2744, 0.8215, -0.0836] ).to(lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCamelCase , atol=1E-4 ) ) @slow def a__ ( self ): # ViT models have an `interpolate_pos_encoding` argument in their forward method, # allowing to interpolate the pre-trained position embeddings in order to use # the model on higher resolutions. The DINO model by Facebook AI leverages this # to visualize self-attention on higher resolution images. __a = ViTModel.from_pretrained("facebook/dino-vits8" ).to(lowerCamelCase ) __a = ViTImageProcessor.from_pretrained("facebook/dino-vits8" , size=480 ) __a = prepare_img() __a = image_processor(images=lowerCamelCase , return_tensors="pt" ) __a = inputs.pixel_values.to(lowerCamelCase ) # forward pass with torch.no_grad(): __a = model(lowerCamelCase , interpolate_pos_encoding=lowerCamelCase ) # verify the logits __a = torch.Size((1, 3601, 384) ) self.assertEqual(outputs.last_hidden_state.shape , lowerCamelCase ) __a = torch.tensor( [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]] ).to(lowerCamelCase ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , lowerCamelCase , atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def a__ ( self ): __a = ViTModel.from_pretrained("facebook/dino-vits8" , torch_dtype=torch.floataa , device_map="auto" ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=lowerCamelCase , return_tensors="pt" ) __a = inputs.pixel_values.to(lowerCamelCase ) # forward pass to make sure inference works in fp16 with torch.no_grad(): __a = model(lowerCamelCase )
67
0
"""simple docstring""" import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class snake_case__ ( unittest.TestCase ): @parameterized.expand([(None,), ("foo.json",)] ) def a__ ( self , lowerCamelCase ): __a = GenerationConfig( do_sample=lowerCamelCase , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowerCamelCase , config_name=lowerCamelCase ) __a = GenerationConfig.from_pretrained(lowerCamelCase , config_name=lowerCamelCase ) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , lowerCamelCase ) self.assertEqual(loaded_config.temperature , 0.7 ) self.assertEqual(loaded_config.length_penalty , 1.0 ) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]] ) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50 ) self.assertEqual(loaded_config.max_length , 20 ) self.assertEqual(loaded_config.max_time , lowerCamelCase ) def a__ ( self ): __a = AutoConfig.from_pretrained("gpt2" ) __a = GenerationConfig.from_model_config(lowerCamelCase ) __a = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(lowerCamelCase , lowerCamelCase ) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id ) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id ) def a__ ( self ): __a = GenerationConfig() __a = { "max_new_tokens": 1024, "foo": "bar", } __a = copy.deepcopy(lowerCamelCase ) __a = generation_config.update(**lowerCamelCase ) # update_kwargs was not modified (no side effects) self.assertEqual(lowerCamelCase , lowerCamelCase ) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1024 ) # `.update()` returns a dictionary of unused kwargs self.assertEqual(lowerCamelCase , {"foo": "bar"} ) def a__ ( self ): __a = GenerationConfig() __a = "bar" with tempfile.TemporaryDirectory("test-generation-config" ) as tmp_dir: generation_config.save_pretrained(lowerCamelCase ) __a = GenerationConfig.from_pretrained(lowerCamelCase ) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , "bar" ) __a = GenerationConfig.from_model_config(lowerCamelCase ) assert not hasattr(lowerCamelCase , "foo" ) # no new kwargs should be initialized if from config def a__ ( self ): __a = GenerationConfig() self.assertEqual(default_config.temperature , 1.0 ) self.assertEqual(default_config.do_sample , lowerCamelCase ) self.assertEqual(default_config.num_beams , 1 ) __a = GenerationConfig( do_sample=lowerCamelCase , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7 ) self.assertEqual(config.do_sample , lowerCamelCase ) self.assertEqual(config.num_beams , 1 ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowerCamelCase ) __a = GenerationConfig.from_pretrained(lowerCamelCase , temperature=1.0 ) self.assertEqual(loaded_config.temperature , 1.0 ) self.assertEqual(loaded_config.do_sample , lowerCamelCase ) self.assertEqual(loaded_config.num_beams , 1 ) # default value @is_staging_test class snake_case__ ( unittest.TestCase ): @classmethod def a__ ( cls ): __a = TOKEN HfFolder.save_token(lowerCamelCase ) @classmethod def a__ ( cls ): try: delete_repo(token=cls._token , repo_id="test-generation-config" ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id="valid_org/test-generation-config-org" ) except HTTPError: pass def a__ ( self ): __a = GenerationConfig( do_sample=lowerCamelCase , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub("test-generation-config" , use_auth_token=self._token ) __a = GenerationConfig.from_pretrained(F"{USER}/test-generation-config" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowerCamelCase , getattr(lowerCamelCase , lowerCamelCase ) ) # Reset repo delete_repo(token=self._token , repo_id="test-generation-config" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowerCamelCase , repo_id="test-generation-config" , push_to_hub=lowerCamelCase , use_auth_token=self._token ) __a = GenerationConfig.from_pretrained(F"{USER}/test-generation-config" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowerCamelCase , getattr(lowerCamelCase , lowerCamelCase ) ) def a__ ( self ): __a = GenerationConfig( do_sample=lowerCamelCase , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub("valid_org/test-generation-config-org" , use_auth_token=self._token ) __a = GenerationConfig.from_pretrained("valid_org/test-generation-config-org" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowerCamelCase , getattr(lowerCamelCase , lowerCamelCase ) ) # Reset repo delete_repo(token=self._token , repo_id="valid_org/test-generation-config-org" ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowerCamelCase , repo_id="valid_org/test-generation-config-org" , push_to_hub=lowerCamelCase , use_auth_token=self._token ) __a = GenerationConfig.from_pretrained("valid_org/test-generation-config-org" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowerCamelCase , getattr(lowerCamelCase , lowerCamelCase ) )
715
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetaImageProcessor class snake_case__ ( unittest.TestCase ): def __init__( self , lowerCamelCase , lowerCamelCase=7 , lowerCamelCase=3 , lowerCamelCase=30 , lowerCamelCase=400 , lowerCamelCase=True , lowerCamelCase=None , lowerCamelCase=True , lowerCamelCase=[0.5, 0.5, 0.5] , lowerCamelCase=[0.5, 0.5, 0.5] , lowerCamelCase=True , lowerCamelCase=1 / 255 , lowerCamelCase=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __a = size if size is not None else {"shortest_edge": 18, "longest_edge": 1333} __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 a__ ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def a__ ( self , lowerCamelCase , lowerCamelCase=False ): if not batched: __a = image_inputs[0] if isinstance(lowerCamelCase , Image.Image ): __a , __a = image.size else: __a , __a = image.shape[1], image.shape[2] if w < h: __a = int(self.size["shortest_edge"] * h / w ) __a = self.size["shortest_edge"] elif w > h: __a = self.size["shortest_edge"] __a = int(self.size["shortest_edge"] * w / h ) else: __a = self.size["shortest_edge"] __a = self.size["shortest_edge"] else: __a = [] for image in image_inputs: __a , __a = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __a = max(lowerCamelCase , key=lambda lowerCamelCase : item[0] )[0] __a = max(lowerCamelCase , key=lambda lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case__ ( snake_case_, unittest.TestCase ): _snake_case : List[Any] = DetaImageProcessor if is_vision_available() else None def a__ ( self ): __a = DetaImageProcessingTester(self ) @property def a__ ( self ): return self.image_processor_tester.prepare_image_processor_dict() def a__ ( self ): __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_rescale" ) ) self.assertTrue(hasattr(lowerCamelCase , "do_pad" ) ) self.assertTrue(hasattr(lowerCamelCase , "size" ) ) def a__ ( self ): __a = 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 , lowerCamelCase ) def a__ ( self ): pass def a__ ( self ): # 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 __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) __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, expected_height, expected_width, ) , ) def a__ ( self ): # 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 __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def a__ ( self ): # 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 __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def a__ ( self ): # prepare image and target __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": 39769, "annotations": target} # encode them __a = DetaImageProcessor() __a = image_processing(images=lowerCamelCase , annotations=lowerCamelCase , return_tensors="pt" ) # verify pixel values __a = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase ) __a = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase , atol=1E-4 ) ) # verify area __a = 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"] , lowerCamelCase ) ) # verify boxes __a = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase ) __a = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase , atol=1E-3 ) ) # verify image_id __a = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase ) ) # verify is_crowd __a = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase ) ) # verify class_labels __a = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase ) ) # verify orig_size __a = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase ) ) # verify size __a = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase ) ) @slow def a__ ( self ): # prepare image, target and masks_path __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": 39769, "segments_info": target} __a = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them __a = DetaImageProcessor(format="coco_panoptic" ) __a = image_processing(images=lowerCamelCase , annotations=lowerCamelCase , masks_path=lowerCamelCase , return_tensors="pt" ) # verify pixel values __a = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase ) __a = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase , atol=1E-4 ) ) # verify area __a = 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"] , lowerCamelCase ) ) # verify boxes __a = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase ) __a = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase , atol=1E-3 ) ) # verify image_id __a = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase ) ) # verify is_crowd __a = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase ) ) # verify class_labels __a = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase ) ) # verify masks __a = 822873 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , lowerCamelCase ) # verify orig_size __a = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase ) ) # verify size __a = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase ) )
67
0
"""simple docstring""" import string def _lowerCamelCase( a ): for key in range(len(string.ascii_uppercase ) ): __a = "" for symbol in message: if symbol in string.ascii_uppercase: __a = string.ascii_uppercase.find(a ) __a = num - key if num < 0: __a = num + len(string.ascii_uppercase ) __a = translated + string.ascii_uppercase[num] else: __a = translated + symbol print(F"Decryption using Key #{key}: {translated}" ) def _lowerCamelCase( ): __a = input("Encrypted message: " ) __a = message.upper() decrypt(a ) if __name__ == "__main__": import doctest doctest.testmod() main()
716
"""simple docstring""" import argparse import logging import sys from unittest.mock import patch import run_glue_deebert from transformers.testing_utils import TestCasePlus, get_gpu_count, require_torch_non_multi_gpu, slow logging.basicConfig(level=logging.DEBUG) SCREAMING_SNAKE_CASE__:Dict = logging.getLogger() def _lowerCamelCase( ): __a = argparse.ArgumentParser() parser.add_argument("-f" ) __a = parser.parse_args() return args.f class snake_case__ ( snake_case_ ): def a__ ( self ): __a = logging.StreamHandler(sys.stdout ) logger.addHandler(lowerCamelCase ) def a__ ( self , lowerCamelCase ): __a = get_gpu_count() if n_gpu > 1: pass # XXX: doesn't quite work with n_gpu > 1 https://github.com/huggingface/transformers/issues/10560 # script = f"{self.examples_dir_str}/research_projects/deebert/run_glue_deebert.py" # distributed_args = f"-m torch.distributed.launch --nproc_per_node={n_gpu} {script}".split() # cmd = [sys.executable] + distributed_args + args # execute_subprocess_async(cmd, env=self.get_env()) # XXX: test the results - need to save them first into .json file else: args.insert(0 , "run_glue_deebert.py" ) with patch.object(lowerCamelCase , "argv" , lowerCamelCase ): __a = run_glue_deebert.main() for value in result.values(): self.assertGreaterEqual(lowerCamelCase , 0.666 ) @slow @require_torch_non_multi_gpu def a__ ( self ): __a = "\n --model_type roberta\n --model_name_or_path roberta-base\n --task_name MRPC\n --do_train\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --max_seq_length 128\n --per_gpu_eval_batch_size=1\n --per_gpu_train_batch_size=8\n --learning_rate 2e-4\n --num_train_epochs 3\n --overwrite_output_dir\n --seed 42\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --save_steps 0\n --overwrite_cache\n --eval_after_first_stage\n ".split() self.run_and_check(lowerCamelCase ) __a = "\n --model_type roberta\n --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --task_name MRPC\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --max_seq_length 128\n --eval_each_highway\n --eval_highway\n --overwrite_cache\n --per_gpu_eval_batch_size=1\n ".split() self.run_and_check(lowerCamelCase ) __a = "\n --model_type roberta\n --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --task_name MRPC\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --max_seq_length 128\n --early_exit_entropy 0.1\n --eval_highway\n --overwrite_cache\n --per_gpu_eval_batch_size=1\n ".split() self.run_and_check(lowerCamelCase )
67
0
import argparse import json from collections import OrderedDict import torch from huggingface_hub import cached_download, hf_hub_url from transformers import AutoImageProcessor, CvtConfig, CvtForImageClassification def _lowerCamelCase( a ): __a = [] embed.append( ( F"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.weight", F"stage{idx}.patch_embed.proj.weight", ) ) embed.append( ( F"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.projection.bias", F"stage{idx}.patch_embed.proj.bias", ) ) embed.append( ( F"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.weight", F"stage{idx}.patch_embed.norm.weight", ) ) embed.append( ( F"cvt.encoder.stages.{idx}.embedding.convolution_embeddings.normalization.bias", F"stage{idx}.patch_embed.norm.bias", ) ) return embed def _lowerCamelCase( a , a ): __a = [] attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.convolution.weight", F"stage{idx}.blocks.{cnt}.attn.conv_proj_q.conv.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.weight", F"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.bias", F"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.bias", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_mean", F"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_mean", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.running_var", F"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.running_var", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_query.convolution_projection.normalization.num_batches_tracked", F"stage{idx}.blocks.{cnt}.attn.conv_proj_q.bn.num_batches_tracked", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.convolution.weight", F"stage{idx}.blocks.{cnt}.attn.conv_proj_k.conv.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.weight", F"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.bias", F"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.bias", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_mean", F"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_mean", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.running_var", F"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.running_var", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_key.convolution_projection.normalization.num_batches_tracked", F"stage{idx}.blocks.{cnt}.attn.conv_proj_k.bn.num_batches_tracked", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.convolution.weight", F"stage{idx}.blocks.{cnt}.attn.conv_proj_v.conv.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.weight", F"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.bias", F"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.bias", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_mean", F"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_mean", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.running_var", F"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.running_var", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.convolution_projection_value.convolution_projection.normalization.num_batches_tracked", F"stage{idx}.blocks.{cnt}.attn.conv_proj_v.bn.num_batches_tracked", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.weight", F"stage{idx}.blocks.{cnt}.attn.proj_q.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_query.bias", F"stage{idx}.blocks.{cnt}.attn.proj_q.bias", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.weight", F"stage{idx}.blocks.{cnt}.attn.proj_k.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_key.bias", F"stage{idx}.blocks.{cnt}.attn.proj_k.bias", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.weight", F"stage{idx}.blocks.{cnt}.attn.proj_v.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.attention.projection_value.bias", F"stage{idx}.blocks.{cnt}.attn.proj_v.bias", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.weight", F"stage{idx}.blocks.{cnt}.attn.proj.weight", ) ) attention_weights.append( ( F"cvt.encoder.stages.{idx}.layers.{cnt}.attention.output.dense.bias", F"stage{idx}.blocks.{cnt}.attn.proj.bias", ) ) attention_weights.append( (F"cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.weight", F"stage{idx}.blocks.{cnt}.mlp.fc1.weight") ) attention_weights.append( (F"cvt.encoder.stages.{idx}.layers.{cnt}.intermediate.dense.bias", F"stage{idx}.blocks.{cnt}.mlp.fc1.bias") ) attention_weights.append( (F"cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.weight", F"stage{idx}.blocks.{cnt}.mlp.fc2.weight") ) attention_weights.append( (F"cvt.encoder.stages.{idx}.layers.{cnt}.output.dense.bias", F"stage{idx}.blocks.{cnt}.mlp.fc2.bias") ) attention_weights.append( (F"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.weight", F"stage{idx}.blocks.{cnt}.norm1.weight") ) attention_weights.append( (F"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_before.bias", F"stage{idx}.blocks.{cnt}.norm1.bias") ) attention_weights.append( (F"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.weight", F"stage{idx}.blocks.{cnt}.norm2.weight") ) attention_weights.append( (F"cvt.encoder.stages.{idx}.layers.{cnt}.layernorm_after.bias", F"stage{idx}.blocks.{cnt}.norm2.bias") ) return attention_weights def _lowerCamelCase( a ): __a = [] token.append((F"cvt.encoder.stages.{idx}.cls_token", "stage2.cls_token") ) return token def _lowerCamelCase( ): __a = [] head.append(("layernorm.weight", "norm.weight") ) head.append(("layernorm.bias", "norm.bias") ) head.append(("classifier.weight", "head.weight") ) head.append(("classifier.bias", "head.bias") ) return head def _lowerCamelCase( a , a , a , a ): __a = "imagenet-1k-id2label.json" __a = 1_0_0_0 __a = "huggingface/label-files" __a = num_labels __a = json.load(open(cached_download(hf_hub_url(a , a , repo_type="dataset" ) ) , "r" ) ) __a = {int(a ): v for k, v in idalabel.items()} __a = idalabel __a = {v: k for k, v in idalabel.items()} __a = __a = CvtConfig(num_labels=a , idalabel=a , labelaid=a ) # For depth size 13 (13 = 1+2+10) if cvt_model.rsplit("/" , 1 )[-1][4:6] == "13": __a = [1, 2, 1_0] # For depth size 21 (21 = 1+4+16) elif cvt_model.rsplit("/" , 1 )[-1][4:6] == "21": __a = [1, 4, 1_6] # For wide cvt (similar to wide-resnet) depth size 24 (w24 = 2 + 2 20) else: __a = [2, 2, 2_0] __a = [3, 1_2, 1_6] __a = [1_9_2, 7_6_8, 1_0_2_4] __a = CvtForImageClassification(a ) __a = AutoImageProcessor.from_pretrained("facebook/convnext-base-224-22k-1k" ) __a = image_size __a = torch.load(a , map_location=torch.device("cpu" ) ) __a = OrderedDict() __a = [] for idx in range(len(config.depth ) ): if config.cls_token[idx]: __a = list_of_state_dict + cls_token(a ) __a = list_of_state_dict + embeddings(a ) for cnt in range(config.depth[idx] ): __a = list_of_state_dict + attention(a , a ) __a = list_of_state_dict + final() for gg in list_of_state_dict: print(a ) for i in range(len(a ) ): __a = original_weights[list_of_state_dict[i][1]] model.load_state_dict(a ) model.save_pretrained(a ) image_processor.save_pretrained(a ) # Download the weights from zoo: https://1drv.ms/u/s!AhIXJn_J-blW9RzF3rMW7SsLHa8h?e=blQ0Al if __name__ == "__main__": SCREAMING_SNAKE_CASE__:Tuple = argparse.ArgumentParser() parser.add_argument( """--cvt_model""", default="""cvt-w24""", type=str, help="""Name of the cvt model you'd like to convert.""", ) parser.add_argument( """--image_size""", default=384, type=int, help="""Input Image Size""", ) parser.add_argument( """--cvt_file_name""", default=R"""cvtmodels\CvT-w24-384x384-IN-22k.pth""", type=str, help="""Input Image Size""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) SCREAMING_SNAKE_CASE__:List[Any] = parser.parse_args() convert_cvt_checkpoint(args.cvt_model, args.image_size, args.cvt_file_name, args.pytorch_dump_folder_path)
717
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, 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 SCREAMING_SNAKE_CASE__:Union[str, Any] = logging.get_logger(__name__) if is_vision_available(): import PIL class snake_case__ ( snake_case_ ): _snake_case : Optional[Any] = ["""pixel_values"""] def __init__( self , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = PILImageResampling.BICUBIC , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = True , lowerCamelCase = 1 / 255 , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = True , **lowerCamelCase , ): super().__init__(**lowerCamelCase ) __a = size if size is not None else {"shortest_edge": 224} __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) __a = crop_size if crop_size is not None else {"height": 224, "width": 224} __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase , param_name="crop_size" ) __a = do_resize __a = size __a = resample __a = do_center_crop __a = crop_size __a = do_rescale __a = rescale_factor __a = do_normalize __a = image_mean if image_mean is not None else OPENAI_CLIP_MEAN __a = image_std if image_std is not None else OPENAI_CLIP_STD __a = do_convert_rgb def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = PILImageResampling.BICUBIC , lowerCamelCase = None , **lowerCamelCase , ): __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) if "shortest_edge" not in size: raise ValueError(F"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}" ) __a = get_resize_output_image_size(lowerCamelCase , size=size["shortest_edge"] , default_to_square=lowerCamelCase ) return resize(lowerCamelCase , size=lowerCamelCase , resample=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): __a = get_size_dict(lowerCamelCase ) 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(lowerCamelCase , size=(size["height"], size["width"]) , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): return rescale(lowerCamelCase , scale=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): return normalize(lowerCamelCase , mean=lowerCamelCase , std=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = ChannelDimension.FIRST , **lowerCamelCase , ): __a = do_resize if do_resize is not None else self.do_resize __a = size if size is not None else self.size __a = get_size_dict(lowerCamelCase , param_name="size" , default_to_square=lowerCamelCase ) __a = resample if resample is not None else self.resample __a = do_center_crop if do_center_crop is not None else self.do_center_crop __a = crop_size if crop_size is not None else self.crop_size __a = get_size_dict(lowerCamelCase , param_name="crop_size" , default_to_square=lowerCamelCase ) __a = do_rescale if do_rescale is not None else self.do_rescale __a = rescale_factor if rescale_factor is not None else self.rescale_factor __a = do_normalize if do_normalize is not None else self.do_normalize __a = image_mean if image_mean is not None else self.image_mean __a = image_std if image_std is not None else self.image_std __a = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __a = make_list_of_images(lowerCamelCase ) if not valid_images(lowerCamelCase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) 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: __a = [convert_to_rgb(lowerCamelCase ) for image in images] # All transformations expect numpy arrays. __a = [to_numpy_array(lowerCamelCase ) for image in images] if do_resize: __a = [self.resize(image=lowerCamelCase , size=lowerCamelCase , resample=lowerCamelCase ) for image in images] if do_center_crop: __a = [self.center_crop(image=lowerCamelCase , size=lowerCamelCase ) for image in images] if do_rescale: __a = [self.rescale(image=lowerCamelCase , scale=lowerCamelCase ) for image in images] if do_normalize: __a = [self.normalize(image=lowerCamelCase , mean=lowerCamelCase , std=lowerCamelCase ) for image in images] __a = [to_channel_dimension_format(lowerCamelCase , lowerCamelCase ) for image in images] __a = {"pixel_values": images} return BatchFeature(data=lowerCamelCase , tensor_type=lowerCamelCase )
67
0
SCREAMING_SNAKE_CASE__:Any = """Alexander Joslin""" import operator as op from .stack import Stack def _lowerCamelCase( a ): __a = {"*": op.mul, "/": op.truediv, "+": op.add, "-": op.sub} __a = Stack() __a = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(a ) ) elif i in operators: # RULE 2 operator_stack.push(a ) elif i == ")": # RULE 4 __a = operator_stack.peek() operator_stack.pop() __a = operand_stack.peek() operand_stack.pop() __a = operand_stack.peek() operand_stack.pop() __a = operators[opr](a , a ) operand_stack.push(a ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": SCREAMING_SNAKE_CASE__:Tuple = """(5 + ((4 * 2) * (2 + 3)))""" # answer = 45 print(F'''{equation} = {dijkstras_two_stack_algorithm(equation)}''')
718
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation SCREAMING_SNAKE_CASE__:List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Any = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} SCREAMING_SNAKE_CASE__:Optional[Any] = { """vocab_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/vocab.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/vocab.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/vocab.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/vocab.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/vocab.json""", }, """merges_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/merges.txt""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/merges.txt""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/merges.txt""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/merges.txt""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/merges.txt""", }, """tokenizer_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/tokenizer.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/tokenizer.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/tokenizer.json""", }, } SCREAMING_SNAKE_CASE__:Union[str, Any] = { """gpt2""": 1024, """gpt2-medium""": 1024, """gpt2-large""": 1024, """gpt2-xl""": 1024, """distilgpt2""": 1024, } class snake_case__ ( snake_case_ ): _snake_case : Tuple = VOCAB_FILES_NAMES _snake_case : str = PRETRAINED_VOCAB_FILES_MAP _snake_case : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _snake_case : List[str] = ["""input_ids""", """attention_mask"""] _snake_case : Dict = GPTaTokenizer def __init__( self , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase="<|endoftext|>" , lowerCamelCase="<|endoftext|>" , lowerCamelCase="<|endoftext|>" , lowerCamelCase=False , **lowerCamelCase , ): super().__init__( lowerCamelCase , lowerCamelCase , tokenizer_file=lowerCamelCase , unk_token=lowerCamelCase , bos_token=lowerCamelCase , eos_token=lowerCamelCase , add_prefix_space=lowerCamelCase , **lowerCamelCase , ) __a = kwargs.pop("add_bos_token" , lowerCamelCase ) __a = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , lowerCamelCase ) != add_prefix_space: __a = getattr(lowerCamelCase , pre_tok_state.pop("type" ) ) __a = add_prefix_space __a = pre_tok_class(**lowerCamelCase ) __a = add_prefix_space def a__ ( self , *lowerCamelCase , **lowerCamelCase ): __a = kwargs.get("is_split_into_words" , lowerCamelCase ) assert self.add_prefix_space or not is_split_into_words, ( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*lowerCamelCase , **lowerCamelCase ) def a__ ( self , *lowerCamelCase , **lowerCamelCase ): __a = kwargs.get("is_split_into_words" , lowerCamelCase ) assert self.add_prefix_space or not is_split_into_words, ( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._encode_plus(*lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase = None ): __a = self._tokenizer.model.save(lowerCamelCase , name=lowerCamelCase ) return tuple(lowerCamelCase ) def a__ ( self , lowerCamelCase ): __a = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowerCamelCase , add_special_tokens=lowerCamelCase ) + [self.eos_token_id] ) if len(lowerCamelCase ) > self.model_max_length: __a = input_ids[-self.model_max_length :] return input_ids
67
0
import inspect import unittest from transformers import ViTConfig 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 ViTForImageClassification, ViTForMaskedImageModeling, ViTModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class snake_case__ : 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=None , lowerCamelCase=2 , ): __a = parent __a = batch_size __a = image_size __a = patch_size __a = num_channels __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 = encoder_stride # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) __a = (image_size // patch_size) ** 2 __a = num_patches + 1 def a__ ( self ): __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = self.get_config() return config, pixel_values, labels def a__ ( self ): return ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=lowerCamelCase , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = ViTModel(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = ViTForMaskedImageModeling(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __a = 1 __a = ViTForMaskedImageModeling(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __a = model(lowerCamelCase ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = self.type_sequence_label_size __a = ViTForImageClassification(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __a = 1 __a = ViTForImageClassification(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __a = model(lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a__ ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class snake_case__ ( snake_case_, snake_case_, unittest.TestCase ): _snake_case : Any = ( ( ViTModel, ViTForImageClassification, ViTForMaskedImageModeling, ) if is_torch_available() else () ) _snake_case : List[Any] = ( {"""feature-extraction""": ViTModel, """image-classification""": ViTForImageClassification} if is_torch_available() else {} ) _snake_case : int = True _snake_case : int = False _snake_case : str = False _snake_case : Optional[Any] = False def a__ ( self ): __a = ViTModelTester(self ) __a = ConfigTester(self , config_class=lowerCamelCase , has_text_modality=lowerCamelCase , hidden_size=37 ) def a__ ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="ViT does not use inputs_embeds" ) def a__ ( self ): pass def a__ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __a = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCamelCase , nn.Linear ) ) def a__ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(lowerCamelCase ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase ) @slow def a__ ( self ): for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = ViTModel.from_pretrained(lowerCamelCase ) self.assertIsNotNone(lowerCamelCase ) def _lowerCamelCase( ): __a = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class snake_case__ ( unittest.TestCase ): @cached_property def a__ ( self ): return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224" ) if is_vision_available() else None @slow def a__ ( self ): __a = ViTForImageClassification.from_pretrained("google/vit-base-patch16-224" ).to(lowerCamelCase ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase ) # forward pass with torch.no_grad(): __a = model(**lowerCamelCase ) # verify the logits __a = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , lowerCamelCase ) __a = torch.tensor([-0.2744, 0.8215, -0.0836] ).to(lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCamelCase , atol=1E-4 ) ) @slow def a__ ( self ): # ViT models have an `interpolate_pos_encoding` argument in their forward method, # allowing to interpolate the pre-trained position embeddings in order to use # the model on higher resolutions. The DINO model by Facebook AI leverages this # to visualize self-attention on higher resolution images. __a = ViTModel.from_pretrained("facebook/dino-vits8" ).to(lowerCamelCase ) __a = ViTImageProcessor.from_pretrained("facebook/dino-vits8" , size=480 ) __a = prepare_img() __a = image_processor(images=lowerCamelCase , return_tensors="pt" ) __a = inputs.pixel_values.to(lowerCamelCase ) # forward pass with torch.no_grad(): __a = model(lowerCamelCase , interpolate_pos_encoding=lowerCamelCase ) # verify the logits __a = torch.Size((1, 3601, 384) ) self.assertEqual(outputs.last_hidden_state.shape , lowerCamelCase ) __a = torch.tensor( [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]] ).to(lowerCamelCase ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , lowerCamelCase , atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def a__ ( self ): __a = ViTModel.from_pretrained("facebook/dino-vits8" , torch_dtype=torch.floataa , device_map="auto" ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=lowerCamelCase , return_tensors="pt" ) __a = inputs.pixel_values.to(lowerCamelCase ) # forward pass to make sure inference works in fp16 with torch.no_grad(): __a = model(lowerCamelCase )
719
"""simple docstring""" from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize("repo_id" , ["canonical_dataset_name", "org-name/dataset-name"] ) @pytest.mark.parametrize("path" , ["filename.csv", "filename with blanks.csv"] ) @pytest.mark.parametrize("revision" , [None, "v2"] ) def _lowerCamelCase( a , a , a ): __a = hf_hub_url(repo_id=a , path=a , revision=a ) assert url == F"https://huggingface.co/datasets/{repo_id}/resolve/{revision or 'main'}/{quote(a )}"
67
0
"""simple docstring""" from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast from ...utils import logging if TYPE_CHECKING: from ...feature_extraction_utils import FeatureExtractionMixin from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType SCREAMING_SNAKE_CASE__:Optional[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Tuple = { """openai/whisper-base""": """https://huggingface.co/openai/whisper-base/resolve/main/config.json""", } # fmt: off SCREAMING_SNAKE_CASE__:Optional[Any] = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 357, 366, 438, 532, 685, 705, 796, 930, 1058, 1220, 1267, 1279, 1303, 1343, 1377, 1391, 1635, 1782, 1875, 2162, 2361, 2488, 3467, 4008, 4211, 4600, 4808, 5299, 5855, 6329, 7203, 9609, 9959, 10563, 10786, 11420, 11709, 11907, 13163, 13697, 13700, 14808, 15306, 16410, 16791, 17992, 19203, 19510, 20724, 22305, 22935, 27007, 30109, 30420, 33409, 34949, 40283, 40493, 40549, 47282, 49146, 50257, 50359, 50360, 50361 ] SCREAMING_SNAKE_CASE__:int = [ 1, 2, 7, 8, 9, 10, 14, 25, 26, 27, 28, 29, 31, 58, 59, 60, 61, 62, 63, 90, 91, 92, 93, 359, 503, 522, 542, 873, 893, 902, 918, 922, 931, 1350, 1853, 1982, 2460, 2627, 3246, 3253, 3268, 3536, 3846, 3961, 4183, 4667, 6585, 6647, 7273, 9061, 9383, 10428, 10929, 11938, 12033, 12331, 12562, 13793, 14157, 14635, 15265, 15618, 16553, 16604, 18362, 18956, 20075, 21675, 22520, 26130, 26161, 26435, 28279, 29464, 31650, 32302, 32470, 36865, 42863, 47425, 49870, 50254, 50258, 50360, 50361, 50362 ] class snake_case__ ( snake_case_ ): _snake_case : Union[str, Any] = """whisper""" _snake_case : int = ["""past_key_values"""] _snake_case : Optional[Any] = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self , lowerCamelCase=51865 , lowerCamelCase=80 , lowerCamelCase=6 , lowerCamelCase=4 , lowerCamelCase=6 , lowerCamelCase=4 , lowerCamelCase=1536 , lowerCamelCase=1536 , lowerCamelCase=0.0 , lowerCamelCase=0.0 , lowerCamelCase=50257 , lowerCamelCase=True , lowerCamelCase=True , lowerCamelCase="gelu" , lowerCamelCase=256 , lowerCamelCase=0.0 , lowerCamelCase=0.0 , lowerCamelCase=0.0 , lowerCamelCase=0.02 , lowerCamelCase=False , lowerCamelCase=1500 , lowerCamelCase=448 , lowerCamelCase=50256 , lowerCamelCase=50256 , lowerCamelCase=50256 , lowerCamelCase=None , lowerCamelCase=[220, 50256] , lowerCamelCase=False , lowerCamelCase=256 , lowerCamelCase=False , lowerCamelCase=0.05 , lowerCamelCase=10 , lowerCamelCase=2 , lowerCamelCase=0.0 , lowerCamelCase=10 , lowerCamelCase=0 , lowerCamelCase=7 , **lowerCamelCase , ): __a = vocab_size __a = num_mel_bins __a = d_model __a = encoder_layers __a = encoder_attention_heads __a = decoder_layers __a = decoder_attention_heads __a = decoder_ffn_dim __a = encoder_ffn_dim __a = dropout __a = attention_dropout __a = activation_dropout __a = activation_function __a = init_std __a = encoder_layerdrop __a = decoder_layerdrop __a = use_cache __a = encoder_layers __a = scale_embedding # scale factor will be sqrt(d_model) if True __a = max_source_positions __a = max_target_positions # Audio Classification-specific parameters. Feel free to ignore for other classes. __a = classifier_proj_size __a = use_weighted_layer_sum # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 __a = apply_spec_augment __a = mask_time_prob __a = mask_time_length __a = mask_time_min_masks __a = mask_feature_prob __a = mask_feature_length __a = mask_feature_min_masks __a = median_filter_width super().__init__( pad_token_id=lowerCamelCase , bos_token_id=lowerCamelCase , eos_token_id=lowerCamelCase , is_encoder_decoder=lowerCamelCase , decoder_start_token_id=lowerCamelCase , suppress_tokens=lowerCamelCase , begin_suppress_tokens=lowerCamelCase , **lowerCamelCase , ) class snake_case__ ( snake_case_ ): @property def a__ ( self ): __a = OrderedDict( [ ("input_features", {0: "batch", 1: "feature_size", 2: "encoder_sequence"}), ] ) if self.use_past: __a = {0: "batch"} else: __a = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(lowerCamelCase , direction="inputs" ) return common_inputs def a__ ( self , lowerCamelCase , lowerCamelCase = -1 , lowerCamelCase = -1 , lowerCamelCase = False , lowerCamelCase = None , lowerCamelCase = 22050 , lowerCamelCase = 5.0 , lowerCamelCase = 220 , ): __a = OrderedDict() __a = OnnxConfig.generate_dummy_inputs( self , preprocessor=preprocessor.feature_extractor , batch_size=lowerCamelCase , framework=lowerCamelCase , sampling_rate=lowerCamelCase , time_duration=lowerCamelCase , frequency=lowerCamelCase , ) __a = encoder_inputs["input_features"].shape[2] __a = encoder_sequence_length // 2 if self.use_past else seq_length __a = super().generate_dummy_inputs( preprocessor.tokenizer , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) __a = encoder_inputs.pop("input_features" ) __a = decoder_inputs.pop("decoder_input_ids" ) if "past_key_values" in decoder_inputs: __a = decoder_inputs.pop("past_key_values" ) return dummy_inputs @property def a__ ( self ): return 1E-3
720
"""simple docstring""" from __future__ import annotations def _lowerCamelCase( a , a , a ): if len(a ) == 0: raise ValueError("find_max() arg is an empty sequence" ) if ( left >= len(a ) or left < -len(a ) or right >= len(a ) or right < -len(a ) ): raise IndexError("list index out of range" ) if left == right: return nums[left] __a = (left + right) >> 1 # the middle __a = find_max(a , a , a ) # find max in range[left, mid] __a = find_max(a , mid + 1 , a ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
67
0
"""simple docstring""" from itertools import permutations def _lowerCamelCase( a ): if num[3] % 2 != 0: return False if (num[2] + num[3] + num[4]) % 3 != 0: return False if num[5] % 5 != 0: return False __a = [7, 1_1, 1_3, 1_7] for i, test in enumerate(a ): if (num[i + 4] * 1_0_0 + num[i + 5] * 1_0 + num[i + 6]) % test != 0: return False return True def _lowerCamelCase( a = 1_0 ): return sum( int("".join(map(a , a ) ) ) for num in permutations(range(a ) ) if is_substring_divisible(a ) ) if __name__ == "__main__": print(F'''{solution() = }''')
721
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__:List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Tuple = { """google/bigbird-roberta-base""": """https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json""", """google/bigbird-roberta-large""": """https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json""", """google/bigbird-base-trivia-itc""": """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json""", # See all BigBird models at https://huggingface.co/models?filter=big_bird } class snake_case__ ( snake_case_ ): _snake_case : Any = """big_bird""" def __init__( self , lowerCamelCase=50358 , lowerCamelCase=768 , lowerCamelCase=12 , lowerCamelCase=12 , lowerCamelCase=3072 , lowerCamelCase="gelu_new" , lowerCamelCase=0.1 , lowerCamelCase=0.1 , lowerCamelCase=4096 , lowerCamelCase=2 , lowerCamelCase=0.02 , lowerCamelCase=1E-12 , lowerCamelCase=True , lowerCamelCase=0 , lowerCamelCase=1 , lowerCamelCase=2 , lowerCamelCase=66 , lowerCamelCase="block_sparse" , lowerCamelCase=True , lowerCamelCase=False , lowerCamelCase=64 , lowerCamelCase=3 , lowerCamelCase=None , **lowerCamelCase , ): super().__init__( pad_token_id=lowerCamelCase , bos_token_id=lowerCamelCase , eos_token_id=lowerCamelCase , sep_token_id=lowerCamelCase , **lowerCamelCase , ) __a = vocab_size __a = max_position_embeddings __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 = initializer_range __a = type_vocab_size __a = layer_norm_eps __a = use_cache __a = rescale_embeddings __a = attention_type __a = use_bias __a = block_size __a = num_random_blocks __a = classifier_dropout class snake_case__ ( snake_case_ ): @property def a__ ( self ): 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), ] )
67
0
"""simple docstring""" def _lowerCamelCase( a ): # if the collection is empty, returns empty if collection == []: return [] # get some information about the collection __a = len(a ) __a = max(a ) __a = min(a ) # create the counting array __a = coll_max + 1 - coll_min __a = [0] * counting_arr_length # count how much a number appears in the collection for number in collection: counting_arr[number - coll_min] += 1 # sum each position with it's predecessors. now, counting_arr[i] tells # us how many elements <= i has in the collection for i in range(1 , a ): __a = counting_arr[i] + counting_arr[i - 1] # create the output collection __a = [0] * coll_len # place the elements in the output, respecting the original order (stable # sort) from end to begin, updating counting_arr for i in reversed(range(0 , a ) ): __a = collection[i] counting_arr[collection[i] - coll_min] -= 1 return ordered def _lowerCamelCase( a ): return "".join([chr(a ) for i in counting_sort([ord(a ) for c in string] )] ) if __name__ == "__main__": # Test string sort assert counting_sort_string("""thisisthestring""") == "eghhiiinrsssttt" SCREAMING_SNAKE_CASE__:Optional[int] = input("""Enter numbers separated by a comma:\n""").strip() SCREAMING_SNAKE_CASE__:Dict = [int(item) for item in user_input.split(""",""")] print(counting_sort(unsorted))
700
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation SCREAMING_SNAKE_CASE__:Optional[int] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Optional[int] = {"""tokenizer_file""": """tokenizer.json"""} SCREAMING_SNAKE_CASE__:Tuple = { """tokenizer_file""": { """bigscience/tokenizer""": """https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json""", """bigscience/bloom-560m""": """https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json""", """bigscience/bloom-1b1""": """https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json""", """bigscience/bloom-1b7""": """https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json""", """bigscience/bloom-3b""": """https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json""", """bigscience/bloom-7b1""": """https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json""", """bigscience/bloom""": """https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json""", }, } class snake_case__ ( snake_case_ ): _snake_case : Optional[Any] = VOCAB_FILES_NAMES _snake_case : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP _snake_case : Optional[int] = ["""input_ids""", """attention_mask"""] _snake_case : Optional[int] = None def __init__( self , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase="<unk>" , lowerCamelCase="<s>" , lowerCamelCase="</s>" , lowerCamelCase="<pad>" , lowerCamelCase=False , lowerCamelCase=False , **lowerCamelCase , ): super().__init__( lowerCamelCase , lowerCamelCase , tokenizer_file=lowerCamelCase , unk_token=lowerCamelCase , bos_token=lowerCamelCase , eos_token=lowerCamelCase , pad_token=lowerCamelCase , add_prefix_space=lowerCamelCase , clean_up_tokenization_spaces=lowerCamelCase , **lowerCamelCase , ) __a = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , lowerCamelCase ) != add_prefix_space: __a = getattr(lowerCamelCase , pre_tok_state.pop("type" ) ) __a = add_prefix_space __a = pre_tok_class(**lowerCamelCase ) __a = add_prefix_space def a__ ( self , *lowerCamelCase , **lowerCamelCase ): __a = kwargs.get("is_split_into_words" , lowerCamelCase ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with" " pretokenized inputs." ) return super()._batch_encode_plus(*lowerCamelCase , **lowerCamelCase ) def a__ ( self , *lowerCamelCase , **lowerCamelCase ): __a = kwargs.get("is_split_into_words" , lowerCamelCase ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with" " pretokenized inputs." ) return super()._encode_plus(*lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase = None ): __a = self._tokenizer.model.save(lowerCamelCase , name=lowerCamelCase ) return tuple(lowerCamelCase ) def a__ ( self , lowerCamelCase ): __a = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowerCamelCase , add_special_tokens=lowerCamelCase ) + [self.eos_token_id] ) if len(lowerCamelCase ) > self.model_max_length: __a = input_ids[-self.model_max_length :] return input_ids
67
0
"""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 snake_case__ ( unittest.TestCase ): @slow def a__ ( self ): __a = AutoImageProcessor.from_pretrained("microsoft/dit-base-finetuned-rvlcdip" ) __a = AutoModelForImageClassification.from_pretrained("microsoft/dit-base-finetuned-rvlcdip" ) model.to(lowerCamelCase ) from datasets import load_dataset __a = load_dataset("nielsr/rvlcdip-demo" ) __a = dataset["train"][0]["image"].convert("RGB" ) __a = image_processor(lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase ) # forward pass with torch.no_grad(): __a = model(**lowerCamelCase ) __a = outputs.logits __a = torch.Size((1, 16) ) self.assertEqual(logits.shape , lowerCamelCase ) __a = torch.tensor( [-0.4158, -0.4092, -0.4347] , device=lowerCamelCase , dtype=torch.float , ) self.assertTrue(torch.allclose(logits[0, :3] , lowerCamelCase , atol=1E-4 ) )
701
"""simple docstring""" from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class snake_case__ : _snake_case : torch.Tensor # [batch_size x 3] _snake_case : torch.Tensor # [batch_size x 3] _snake_case : torch.Tensor # [batch_size x 3] _snake_case : torch.Tensor # [batch_size x 3] _snake_case : int _snake_case : int _snake_case : float _snake_case : float _snake_case : Tuple[int] def a__ ( self ): assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def a__ ( self ): return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def a__ ( self ): return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def a__ ( self ): __a = torch.arange(self.height * self.width ) __a = torch.stack( [ pixel_indices % self.width, torch.div(lowerCamelCase , self.width , rounding_mode="trunc" ), ] , axis=1 , ) return coords @property def a__ ( self ): __a , *__a = self.shape __a = int(np.prod(lowerCamelCase ) ) __a = self.get_image_coords() __a = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) __a = self.get_camera_rays(lowerCamelCase ) __a = rays.view(lowerCamelCase , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def a__ ( self , lowerCamelCase ): __a , *__a , __a = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] __a = coords.view(lowerCamelCase , -1 , 2 ) __a = self.resolution() __a = self.fov() __a = (flat.float() / (res - 1)) * 2 - 1 __a = fracs * torch.tan(fov / 2 ) __a = fracs.view(lowerCamelCase , -1 , 2 ) __a = ( self.z.view(lowerCamelCase , 1 , 3 ) + self.x.view(lowerCamelCase , 1 , 3 ) * fracs[:, :, :1] + self.y.view(lowerCamelCase , 1 , 3 ) * fracs[:, :, 1:] ) __a = directions / directions.norm(dim=-1 , keepdim=lowerCamelCase ) __a = torch.stack( [ torch.broadcast_to(self.origin.view(lowerCamelCase , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(lowerCamelCase , *lowerCamelCase , 2 , 3 ) def a__ ( self , lowerCamelCase , lowerCamelCase ): assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=lowerCamelCase , height=lowerCamelCase , x_fov=self.x_fov , y_fov=self.y_fov , ) def _lowerCamelCase( a ): __a = [] __a = [] __a = [] __a = [] for theta in np.linspace(0 , 2 * np.pi , num=2_0 ): __a = np.array([np.sin(a ), np.cos(a ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) __a = -z * 4 __a = np.array([np.cos(a ), -np.sin(a ), 0.0] ) __a = np.cross(a , a ) origins.append(a ) xs.append(a ) ys.append(a ) zs.append(a ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(a , axis=0 ) ).float() , x=torch.from_numpy(np.stack(a , axis=0 ) ).float() , y=torch.from_numpy(np.stack(a , axis=0 ) ).float() , z=torch.from_numpy(np.stack(a , axis=0 ) ).float() , width=a , height=a , x_fov=0.7 , y_fov=0.7 , shape=(1, len(a )) , )
67
0
"""simple docstring""" from __future__ import annotations def _lowerCamelCase( a , a , a ): __a = list(range(len(a ) ) ) __a = [v / w for v, w in zip(a , a )] index.sort(key=lambda a : ratio[i] , reverse=a ) __a = 0 __a = [0] * len(a ) for i in index: if weight[i] <= capacity: __a = 1 max_value += value[i] capacity -= weight[i] else: __a = capacity / weight[i] max_value += value[i] * capacity / weight[i] break return max_value, fractions if __name__ == "__main__": import doctest doctest.testmod()
702
"""simple docstring""" def _lowerCamelCase( a ): return 1 if digit in (0, 1) else (digit * factorial(digit - 1 )) def _lowerCamelCase( a ): __a = 0 __a = number while duplicate > 0: __a , __a = divmod(a , 1_0 ) fact_sum += factorial(a ) return fact_sum == number if __name__ == "__main__": print("""Program to check whether a number is a Krisnamurthy Number or not.""") SCREAMING_SNAKE_CASE__:Optional[Any] = int(input("""Enter number: """).strip()) print( F'''{number} is {'' if krishnamurthy(number) else 'not '}a Krishnamurthy Number.''' )
67
0
"""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 snake_case__ ( snake_case_, snake_case_ ): @register_to_config def __init__( self , lowerCamelCase = 128 , lowerCamelCase = 256 , lowerCamelCase = 2000.0 , lowerCamelCase = 768 , lowerCamelCase = 12 , lowerCamelCase = 12 , lowerCamelCase = 64 , lowerCamelCase = 2048 , lowerCamelCase = 0.1 , ): super().__init__() __a = nn.Sequential( nn.Linear(lowerCamelCase , d_model * 4 , bias=lowerCamelCase ) , nn.SiLU() , nn.Linear(d_model * 4 , d_model * 4 , bias=lowerCamelCase ) , nn.SiLU() , ) __a = nn.Embedding(lowerCamelCase , lowerCamelCase ) __a = False __a = nn.Linear(lowerCamelCase , lowerCamelCase , bias=lowerCamelCase ) __a = nn.Dropout(p=lowerCamelCase ) __a = nn.ModuleList() for lyr_num in range(lowerCamelCase ): # FiLM conditional T5 decoder __a = DecoderLayer(d_model=lowerCamelCase , d_kv=lowerCamelCase , num_heads=lowerCamelCase , d_ff=lowerCamelCase , dropout_rate=lowerCamelCase ) self.decoders.append(lowerCamelCase ) __a = TaLayerNorm(lowerCamelCase ) __a = nn.Dropout(p=lowerCamelCase ) __a = nn.Linear(lowerCamelCase , lowerCamelCase , bias=lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase ): __a = torch.mul(query_input.unsqueeze(-1 ) , key_input.unsqueeze(-2 ) ) return mask.unsqueeze(-3 ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a , __a , __a = decoder_input_tokens.shape assert decoder_noise_time.shape == (batch,) # decoder_noise_time is in [0, 1), so rescale to expected timing range. __a = 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 ) __a = self.conditioning_emb(lowerCamelCase ).unsqueeze(1 ) assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4) __a = 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. __a = torch.broadcast_to( torch.arange(lowerCamelCase , device=decoder_input_tokens.device ) , (batch, seq_length) , ) __a = self.position_encoding(lowerCamelCase ) __a = self.continuous_inputs_projection(lowerCamelCase ) inputs += position_encodings __a = self.dropout(lowerCamelCase ) # decoder: No padding present. __a = torch.ones( decoder_input_tokens.shape[:2] , device=decoder_input_tokens.device , dtype=inputs.dtype ) # Translate encoding masks to encoder-decoder masks. __a = [(x, self.encoder_decoder_mask(lowerCamelCase , lowerCamelCase )) for x, y in encodings_and_masks] # cross attend style: concat encodings __a = torch.cat([x[0] for x in encodings_and_encdec_masks] , dim=1 ) __a = torch.cat([x[1] for x in encodings_and_encdec_masks] , dim=-1 ) for lyr in self.decoders: __a = lyr( lowerCamelCase , conditioning_emb=lowerCamelCase , encoder_hidden_states=lowerCamelCase , encoder_attention_mask=lowerCamelCase , )[0] __a = self.decoder_norm(lowerCamelCase ) __a = self.post_dropout(lowerCamelCase ) __a = self.spec_out(lowerCamelCase ) return spec_out class snake_case__ ( nn.Module ): def __init__( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase=1E-6 ): super().__init__() __a = 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 a__ ( self , lowerCamelCase , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , ): __a = self.layer[0]( lowerCamelCase , conditioning_emb=lowerCamelCase , attention_mask=lowerCamelCase , ) if encoder_hidden_states is not None: __a = torch.where(encoder_attention_mask > 0 , 0 , -1E10 ).to( encoder_hidden_states.dtype ) __a = self.layer[1]( lowerCamelCase , key_value_states=lowerCamelCase , attention_mask=lowerCamelCase , ) # Apply Film Conditional Feed Forward layer __a = self.layer[-1](lowerCamelCase , lowerCamelCase ) return (hidden_states,) class snake_case__ ( nn.Module ): def __init__( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): super().__init__() __a = TaLayerNorm(lowerCamelCase ) __a = TaFiLMLayer(in_features=d_model * 4 , out_features=lowerCamelCase ) __a = Attention(query_dim=lowerCamelCase , heads=lowerCamelCase , dim_head=lowerCamelCase , out_bias=lowerCamelCase , scale_qk=lowerCamelCase ) __a = nn.Dropout(lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase=None , lowerCamelCase=None , ): # pre_self_attention_layer_norm __a = self.layer_norm(lowerCamelCase ) if conditioning_emb is not None: __a = self.FiLMLayer(lowerCamelCase , lowerCamelCase ) # Self-attention block __a = self.attention(lowerCamelCase ) __a = hidden_states + self.dropout(lowerCamelCase ) return hidden_states class snake_case__ ( nn.Module ): def __init__( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): super().__init__() __a = Attention(query_dim=lowerCamelCase , heads=lowerCamelCase , dim_head=lowerCamelCase , out_bias=lowerCamelCase , scale_qk=lowerCamelCase ) __a = TaLayerNorm(lowerCamelCase , eps=lowerCamelCase ) __a = nn.Dropout(lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase=None , lowerCamelCase=None , ): __a = self.layer_norm(lowerCamelCase ) __a = self.attention( lowerCamelCase , encoder_hidden_states=lowerCamelCase , attention_mask=attention_mask.squeeze(1 ) , ) __a = hidden_states + self.dropout(lowerCamelCase ) return layer_output class snake_case__ ( nn.Module ): def __init__( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): super().__init__() __a = TaDenseGatedActDense(d_model=lowerCamelCase , d_ff=lowerCamelCase , dropout_rate=lowerCamelCase ) __a = TaFiLMLayer(in_features=d_model * 4 , out_features=lowerCamelCase ) __a = TaLayerNorm(lowerCamelCase , eps=lowerCamelCase ) __a = nn.Dropout(lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase=None ): __a = self.layer_norm(lowerCamelCase ) if conditioning_emb is not None: __a = self.film(lowerCamelCase , lowerCamelCase ) __a = self.DenseReluDense(lowerCamelCase ) __a = hidden_states + self.dropout(lowerCamelCase ) return hidden_states class snake_case__ ( nn.Module ): def __init__( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): super().__init__() __a = nn.Linear(lowerCamelCase , lowerCamelCase , bias=lowerCamelCase ) __a = nn.Linear(lowerCamelCase , lowerCamelCase , bias=lowerCamelCase ) __a = nn.Linear(lowerCamelCase , lowerCamelCase , bias=lowerCamelCase ) __a = nn.Dropout(lowerCamelCase ) __a = NewGELUActivation() def a__ ( self , lowerCamelCase ): __a = self.act(self.wi_a(lowerCamelCase ) ) __a = self.wi_a(lowerCamelCase ) __a = hidden_gelu * hidden_linear __a = self.dropout(lowerCamelCase ) __a = self.wo(lowerCamelCase ) return hidden_states class snake_case__ ( nn.Module ): def __init__( self , lowerCamelCase , lowerCamelCase=1E-6 ): super().__init__() __a = nn.Parameter(torch.ones(lowerCamelCase ) ) __a = eps def a__ ( self , lowerCamelCase ): # T5 uses a layer_norm which only scales and doesn't shift, which is also known as Root Mean # Square Layer Normalization https://arxiv.org/abs/1910.07467 thus variance is calculated # w/o mean and there is no bias. Additionally we want to make sure that the accumulation for # half-precision inputs is done in fp32 __a = hidden_states.to(torch.floataa ).pow(2 ).mean(-1 , keepdim=lowerCamelCase ) __a = hidden_states * torch.rsqrt(variance + self.variance_epsilon ) # convert into half-precision if necessary if self.weight.dtype in [torch.floataa, torch.bfloataa]: __a = hidden_states.to(self.weight.dtype ) return self.weight * hidden_states class snake_case__ ( nn.Module ): def a__ ( self , lowerCamelCase ): return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi ) * (input + 0.04_4715 * torch.pow(lowerCamelCase , 3.0 )) )) class snake_case__ ( nn.Module ): def __init__( self , lowerCamelCase , lowerCamelCase ): super().__init__() __a = nn.Linear(lowerCamelCase , out_features * 2 , bias=lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase ): __a = self.scale_bias(lowerCamelCase ) __a , __a = torch.chunk(lowerCamelCase , 2 , -1 ) __a = x * (1 + scale) + shift return x
703
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) SCREAMING_SNAKE_CASE__:Optional[Any] = { """configuration_gpt_bigcode""": ["""GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTBigCodeConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__:Union[str, Any] = [ """GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST""", """GPTBigCodeForSequenceClassification""", """GPTBigCodeForTokenClassification""", """GPTBigCodeForCausalLM""", """GPTBigCodeModel""", """GPTBigCodePreTrainedModel""", ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__:List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
67
0
"""simple docstring""" import argparse import os import re import packaging.version SCREAMING_SNAKE_CASE__:List[Any] = """examples/""" SCREAMING_SNAKE_CASE__:Dict = { """examples""": (re.compile(R"""^check_min_version\(\"[^\"]+\"\)\s*$""", re.MULTILINE), """check_min_version(\"VERSION\")\n"""), """init""": (re.compile(R"""^__version__\s+=\s+\"([^\"]+)\"\s*$""", re.MULTILINE), """__version__ = \"VERSION\"\n"""), """setup""": (re.compile(R"""^(\s*)version\s*=\s*\"[^\"]+\",""", re.MULTILINE), R"""\1version=\"VERSION\","""), """doc""": (re.compile(R"""^(\s*)release\s*=\s*\"[^\"]+\"$""", re.MULTILINE), """release = \"VERSION\"\n"""), } SCREAMING_SNAKE_CASE__:int = { """init""": """src/diffusers/__init__.py""", """setup""": """setup.py""", } SCREAMING_SNAKE_CASE__:List[str] = """README.md""" def _lowerCamelCase( a , a , a ): with open(a , "r" , encoding="utf-8" , newline="\n" ) as f: __a = f.read() __a , __a = REPLACE_PATTERNS[pattern] __a = replace.replace("VERSION" , a ) __a = re_pattern.sub(a , a ) with open(a , "w" , encoding="utf-8" , newline="\n" ) as f: f.write(a ) def _lowerCamelCase( a ): for folder, directories, fnames in os.walk(a ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove("research_projects" ) if "legacy" in directories: directories.remove("legacy" ) for fname in fnames: if fname.endswith(".py" ): update_version_in_file(os.path.join(a , a ) , a , pattern="examples" ) def _lowerCamelCase( a , a=False ): for pattern, fname in REPLACE_FILES.items(): update_version_in_file(a , a , a ) if not patch: update_version_in_examples(a ) def _lowerCamelCase( ): __a = "🤗 Transformers currently provides the following architectures" __a = "1. Want to contribute a new model?" with open(a , "r" , encoding="utf-8" , newline="\n" ) as f: __a = f.readlines() # Find the start of the list. __a = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 __a = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith("1." ): __a = lines[index].replace( "https://huggingface.co/docs/diffusers/main/model_doc" , "https://huggingface.co/docs/diffusers/model_doc" , ) index += 1 with open(a , "w" , encoding="utf-8" , newline="\n" ) as f: f.writelines(a ) def _lowerCamelCase( ): with open(REPLACE_FILES["init"] , "r" ) as f: __a = f.read() __a = REPLACE_PATTERNS["init"][0].search(a ).groups()[0] return packaging.version.parse(a ) def _lowerCamelCase( a=False ): __a = get_version() if patch and default_version.is_devrelease: raise ValueError("Can't create a patch version from the dev branch, checkout a released version!" ) if default_version.is_devrelease: __a = default_version.base_version elif patch: __a = F"{default_version.major}.{default_version.minor}.{default_version.micro + 1}" else: __a = F"{default_version.major}.{default_version.minor + 1}.0" # Now let's ask nicely if that's the right one. __a = input(F"Which version are you releasing? [{default_version}]" ) if len(a ) == 0: __a = default_version print(F"Updating version to {version}." ) global_version_update(a , patch=a ) def _lowerCamelCase( ): __a = get_version() __a = F"{current_version.major}.{current_version.minor + 1}.0.dev0" __a = current_version.base_version # Check with the user we got that right. __a = input(F"Which version are we developing now? [{dev_version}]" ) if len(a ) == 0: __a = dev_version print(F"Updating version to {version}." ) global_version_update(a ) # print("Cleaning main README, don't forget to run `make fix-copies`.") # clean_main_ref_in_model_list() if __name__ == "__main__": SCREAMING_SNAKE_CASE__:Optional[Any] = argparse.ArgumentParser() parser.add_argument("""--post_release""", action="""store_true""", help="""Whether this is pre or post release.""") parser.add_argument("""--patch""", action="""store_true""", help="""Whether or not this is a patch release.""") SCREAMING_SNAKE_CASE__:Dict = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("""Nothing to do after a patch :-)""") else: post_release_work()
704
"""simple docstring""" import argparse import OmegaConf import torch from diffusers import DDIMScheduler, LDMPipeline, UNetLDMModel, VQModel def _lowerCamelCase( a , a , a ): __a = OmegaConf.load(a ) __a = torch.load(a , map_location="cpu" )["model"] __a = list(state_dict.keys() ) # extract state_dict for VQVAE __a = {} __a = "first_stage_model." for key in keys: if key.startswith(a ): __a = state_dict[key] # extract state_dict for UNetLDM __a = {} __a = "model.diffusion_model." for key in keys: if key.startswith(a ): __a = state_dict[key] __a = config.model.params.first_stage_config.params __a = config.model.params.unet_config.params __a = VQModel(**a ).eval() vqvae.load_state_dict(a ) __a = UNetLDMModel(**a ).eval() unet.load_state_dict(a ) __a = 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=a , ) __a = LDMPipeline(a , a , a ) pipeline.save_pretrained(a ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__:List[Any] = 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) SCREAMING_SNAKE_CASE__:Union[str, Any] = parser.parse_args() convert_ldm_original(args.checkpoint_path, args.config_path, args.output_path)
67
0
"""simple docstring""" def _lowerCamelCase( a ): __a = 0 while num > 0: digit_sum += num % 1_0 num //= 1_0 return digit_sum def _lowerCamelCase( a = 1_0_0 ): __a = 1 __a = 2 for i in range(2 , max_n + 1 ): __a = pre_numerator __a = 2 * i // 3 if i % 3 == 0 else 1 __a = cur_numerator __a = e_cont * pre_numerator + temp return sum_digits(a ) if __name__ == "__main__": print(F'''{solution() = }''')
705
"""simple docstring""" from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...file_utils import TensorType, is_torch_available from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging SCREAMING_SNAKE_CASE__:List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Optional[Any] = { """facebook/blenderbot_small-90M""": """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/config.json""", # See all BlenderbotSmall models at https://huggingface.co/models?filter=blenderbot_small } class snake_case__ ( snake_case_ ): _snake_case : str = """blenderbot-small""" _snake_case : str = ["""past_key_values"""] _snake_case : List[Any] = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self , lowerCamelCase=50265 , lowerCamelCase=512 , lowerCamelCase=8 , lowerCamelCase=2048 , lowerCamelCase=16 , lowerCamelCase=8 , lowerCamelCase=2048 , lowerCamelCase=16 , lowerCamelCase=0.0 , lowerCamelCase=0.0 , lowerCamelCase=True , lowerCamelCase=True , lowerCamelCase="gelu" , lowerCamelCase=512 , lowerCamelCase=0.1 , lowerCamelCase=0.0 , lowerCamelCase=0.0 , lowerCamelCase=0.02 , lowerCamelCase=1 , lowerCamelCase=False , lowerCamelCase=0 , lowerCamelCase=1 , lowerCamelCase=2 , lowerCamelCase=2 , **lowerCamelCase , ): __a = vocab_size __a = max_position_embeddings __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 = encoder_layerdrop __a = decoder_layerdrop __a = use_cache __a = encoder_layers __a = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=lowerCamelCase , bos_token_id=lowerCamelCase , eos_token_id=lowerCamelCase , is_encoder_decoder=lowerCamelCase , decoder_start_token_id=lowerCamelCase , forced_eos_token_id=lowerCamelCase , **lowerCamelCase , ) class snake_case__ ( snake_case_ ): @property def a__ ( self ): if self.task in ["default", "seq2seq-lm"]: __a = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: __a = {0: "batch"} __a = {0: "batch", 1: "past_decoder_sequence + sequence"} else: __a = {0: "batch", 1: "decoder_sequence"} __a = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(lowerCamelCase , direction="inputs" ) elif self.task == "causal-lm": # TODO: figure this case out. __a = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: __a , __a = self.num_layers for i in range(lowerCamelCase ): __a = {0: "batch", 2: "past_sequence + sequence"} __a = {0: "batch", 2: "past_sequence + sequence"} else: __a = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}), ("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}), ] ) return common_inputs @property def a__ ( self ): if self.task in ["default", "seq2seq-lm"]: __a = super().outputs else: __a = super(lowerCamelCase , self ).outputs if self.use_past: __a , __a = self.num_layers for i in range(lowerCamelCase ): __a = {0: "batch", 2: "past_sequence + sequence"} __a = {0: "batch", 2: "past_sequence + sequence"} return common_outputs def a__ ( self , lowerCamelCase , lowerCamelCase = -1 , lowerCamelCase = -1 , lowerCamelCase = False , lowerCamelCase = None , ): __a = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) # Generate decoder inputs __a = seq_length if not self.use_past else 1 __a = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) __a = {F"decoder_{name}": tensor for name, tensor in decoder_inputs.items()} __a = dict(**lowerCamelCase , **lowerCamelCase ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch __a , __a = common_inputs["input_ids"].shape __a = common_inputs["decoder_input_ids"].shape[1] __a , __a = self.num_attention_heads __a = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) __a = decoder_seq_length + 3 __a = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) __a = torch.cat( [common_inputs["decoder_attention_mask"], torch.ones(lowerCamelCase , lowerCamelCase )] , dim=1 ) __a = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered __a , __a = self.num_layers __a = min(lowerCamelCase , lowerCamelCase ) __a = max(lowerCamelCase , lowerCamelCase ) - min_num_layers __a = "encoder" if num_encoder_layers > num_decoder_layers else "decoder" for _ in range(lowerCamelCase ): common_inputs["past_key_values"].append( ( torch.zeros(lowerCamelCase ), torch.zeros(lowerCamelCase ), torch.zeros(lowerCamelCase ), torch.zeros(lowerCamelCase ), ) ) # TODO: test this. __a = encoder_shape if remaining_side_name == "encoder" else decoder_shape for _ in range(lowerCamelCase , lowerCamelCase ): common_inputs["past_key_values"].append((torch.zeros(lowerCamelCase ), torch.zeros(lowerCamelCase )) ) return common_inputs def a__ ( self , lowerCamelCase , lowerCamelCase = -1 , lowerCamelCase = -1 , lowerCamelCase = False , lowerCamelCase = None , ): __a = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch __a , __a = common_inputs["input_ids"].shape # Not using the same length for past_key_values __a = seqlen + 2 __a , __a = self.num_layers __a , __a = self.num_attention_heads __a = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) __a = common_inputs["attention_mask"].dtype __a = torch.cat( [common_inputs["attention_mask"], torch.ones(lowerCamelCase , lowerCamelCase , dtype=lowerCamelCase )] , dim=1 ) __a = [ (torch.zeros(lowerCamelCase ), torch.zeros(lowerCamelCase )) for _ in range(lowerCamelCase ) ] return common_inputs def a__ ( self , lowerCamelCase , lowerCamelCase = -1 , lowerCamelCase = -1 , lowerCamelCase = False , lowerCamelCase = None , ): # Copied from OnnxConfig.generate_dummy_inputs # Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity. # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX __a = compute_effective_axis_dimension( lowerCamelCase , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX __a = tokenizer.num_special_tokens_to_add(lowerCamelCase ) __a = compute_effective_axis_dimension( lowerCamelCase , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=lowerCamelCase ) # Generate dummy inputs according to compute batch and sequence __a = [" ".join([tokenizer.unk_token] ) * seq_length] * batch_size __a = dict(tokenizer(lowerCamelCase , return_tensors=lowerCamelCase ) ) return common_inputs def a__ ( self , lowerCamelCase , lowerCamelCase = -1 , lowerCamelCase = -1 , lowerCamelCase = False , lowerCamelCase = None , ): if self.task in ["default", "seq2seq-lm"]: __a = self._generate_dummy_inputs_for_default_and_seqaseq_lm( lowerCamelCase , batch_size=lowerCamelCase , seq_length=lowerCamelCase , is_pair=lowerCamelCase , framework=lowerCamelCase ) elif self.task == "causal-lm": __a = self._generate_dummy_inputs_for_causal_lm( lowerCamelCase , batch_size=lowerCamelCase , seq_length=lowerCamelCase , is_pair=lowerCamelCase , framework=lowerCamelCase ) else: __a = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCamelCase , batch_size=lowerCamelCase , seq_length=lowerCamelCase , is_pair=lowerCamelCase , framework=lowerCamelCase ) return common_inputs def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): if self.task in ["default", "seq2seq-lm"]: __a = super()._flatten_past_key_values_(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) else: __a = super(lowerCamelCase , self )._flatten_past_key_values_( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase )
67
0
"""simple docstring""" from copy import deepcopy import torch import torch.nn.functional as F from torch.optim import AdamW from torch.optim.lr_scheduler import LambdaLR from torch.utils.data import DataLoader from accelerate.accelerator import Accelerator from accelerate.state import GradientState from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import DistributedType, is_torch_version, set_seed def _lowerCamelCase( a , a , a , a ): for param, grad_param in zip(model_a.parameters() , model_b.parameters() ): if not param.requires_grad: continue if not did_step: # Grads should not be in sync assert ( torch.allclose(param.grad , grad_param.grad ) is False ), F"Gradients in sync when they should not be at iteration {iteration}:\nmodel_a grad ({param.grad}) == model_b grad ({grad_param.grad})" else: # Grads should be in sync assert ( torch.allclose(param.grad , grad_param.grad ) is True ), F"Gradients not in sync when they should be at iteration {iteration}:\nmodel_a grad ({param.grad}) != model_b grad ({grad_param.grad})" def _lowerCamelCase( a , a , a , a , a=True ): model.train() __a = model(a ) __a = F.mse_loss(a , target.to(output.device ) ) if not do_backward: loss /= accelerator.gradient_accumulation_steps loss.backward() else: accelerator.backward(a ) def _lowerCamelCase( a , a=False ): set_seed(4_2 ) __a = RegressionModel() __a = deepcopy(a ) __a = RegressionDataset(length=8_0 ) __a = DataLoader(a , batch_size=1_6 ) model.to(accelerator.device ) if sched: __a = AdamW(params=model.parameters() , lr=1E-3 ) __a = AdamW(params=ddp_model.parameters() , lr=1E-3 ) __a = LambdaLR(a , lr_lambda=lambda a : epoch**0.65 ) __a = LambdaLR(a , lr_lambda=lambda a : epoch**0.65 ) # Make a copy of `model` if sched: __a , __a , __a , __a = accelerator.prepare(a , a , a , a ) else: __a , __a = accelerator.prepare(a , a ) if sched: return (model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched) return model, ddp_model, dataloader def _lowerCamelCase( a ): # Test when on a single CPU or GPU that the context manager does nothing __a , __a , __a = get_training_setup(a ) # Use a single batch __a , __a = next(iter(a ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model __a , __a = accelerator.gather((ddp_input, ddp_target) ) __a , __a = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(a , a , a , a ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(a ): step_model(a , a , a , a ) else: # Sync grads step_model(a , a , a , a ) # Since `no_sync` is a noop, `ddp_model` and `model` grads should always be in sync check_model_parameters(a , a , a , a ) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue assert torch.allclose( param.grad , ddp_param.grad ), F"Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})" # Shuffle ddp_input on each iteration torch.manual_seed(1_3_3_7 + iteration ) __a = ddp_input[torch.randperm(len(a ) )] def _lowerCamelCase( a ): # Test on distributed setup that context manager behaves properly __a , __a , __a = get_training_setup(a ) # Use a single batch __a , __a = next(iter(a ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model __a , __a = accelerator.gather((ddp_input, ddp_target) ) __a , __a = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(a , a , a , a ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(a ): step_model(a , a , a , a ) else: # Sync grads step_model(a , a , a , a ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue if iteration % 2 == 0: # Grads should not be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is False ), F"Gradients in sync when they should not be:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})" else: # Grads should be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is True ), F"Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})" # Shuffle ddp_input on each iteration torch.manual_seed(1_3_3_7 + iteration ) __a = ddp_input[torch.randperm(len(a ) )] def _lowerCamelCase( a=False , a=False ): __a = Accelerator( split_batches=a , dispatch_batches=a , gradient_accumulation_steps=2 ) # Test that context manager behaves properly __a , __a , __a = get_training_setup(a ) for iteration, batch in enumerate(a ): __a , __a = batch.values() # Gather the distributed inputs and targs for the base model __a , __a = accelerator.gather((ddp_input, ddp_target) ) __a , __a = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(a , a , a , a , a ) # Do "gradient accumulation" (noop) with accelerator.accumulate(a ): step_model(a , a , a , a ) # DDP model and model should only be in sync when not (iteration % 2 == 0) for param, ddp_param in zip(model.parameters() , ddp_model.parameters() ): if not param.requires_grad: continue if ((iteration + 1) % 2 == 0) or (iteration == len(a ) - 1): # Grads should be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is True ), F"Gradients not in sync when they should be at iteration {iteration}:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})" else: # Grads should not be in sync assert ( torch.allclose(param.grad , ddp_param.grad ) is False ), F"Gradients in sync when they should not be at iteration {iteration}:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})" # Shuffle ddp_input on each iteration torch.manual_seed(1_3_3_7 + iteration ) __a = ddp_input[torch.randperm(len(a ) )] GradientState._reset_state() def _lowerCamelCase( a=False , a=False ): __a = Accelerator( split_batches=a , dispatch_batches=a , gradient_accumulation_steps=2 ) # Test that context manager behaves properly __a , __a , __a , __a , __a , __a , __a = get_training_setup(a , a ) for iteration, batch in enumerate(a ): __a , __a = batch.values() # Gather the distributed inputs and targs for the base model __a , __a = accelerator.gather((ddp_input, ddp_target) ) __a , __a = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" model.train() ddp_model.train() step_model(a , a , a , a , a ) opt.step() if ((iteration + 1) % 2 == 0) or ((iteration + 1) == len(a )): if split_batches: sched.step() else: for _ in range(accelerator.num_processes ): sched.step() opt.zero_grad() # Perform gradient accumulation under wrapper with accelerator.accumulate(a ): step_model(a , a , a , a ) ddp_opt.step() ddp_sched.step() ddp_opt.zero_grad() # Learning rates should be the same assert ( opt.param_groups[0]["lr"] == ddp_opt.param_groups[0]["lr"] ), F"Learning rates found in each optimizer did not align\nopt: {opt.param_groups[0]['lr']}\nDDP opt: {ddp_opt.param_groups[0]['lr']}\n" __a = (((iteration + 1) % 2) == 0) or ((iteration + 1) == len(a )) if accelerator.num_processes > 1: check_model_parameters(a , a , a , a ) # Shuffle ddp_input on each iteration torch.manual_seed(1_3_3_7 + iteration ) GradientState._reset_state() def _lowerCamelCase( ): __a = Accelerator() __a = RegressionDataset(length=8_0 ) __a = DataLoader(a , batch_size=1_6 ) __a = RegressionDataset(length=9_6 ) __a = DataLoader(a , batch_size=1_6 ) __a , __a = accelerator.prepare(a , a ) assert accelerator.gradient_state.active_dataloader is None for iteration, _ in enumerate(a ): assert id(accelerator.gradient_state.active_dataloader ) == id(a ) if iteration < len(a ) - 1: assert not accelerator.gradient_state.end_of_dataloader if iteration == 1: for batch_num, _ in enumerate(a ): assert id(accelerator.gradient_state.active_dataloader ) == id(a ) if batch_num < len(a ) - 1: assert not accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader else: assert accelerator.gradient_state.end_of_dataloader assert accelerator.gradient_state.active_dataloader is None def _lowerCamelCase( ): __a = Accelerator() __a = accelerator.state if state.local_process_index == 0: print("**Test `accumulate` gradient accumulation with dataloader break**" ) test_dataloader_break() if state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print("**Test NOOP `no_sync` context manager**" ) test_noop_sync(a ) if state.distributed_type in (DistributedType.MULTI_GPU, DistributedType.MULTI_CPU): if state.local_process_index == 0: print("**Test Distributed `no_sync` context manager**" ) test_distributed_sync(a ) if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if state.local_process_index == 0: print( "**Test `accumulate` gradient accumulation, " , F"`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**" , ) test_gradient_accumulation(a , a ) # Currently will break on torch 2.0 +, need to investigate why if is_torch_version("<" , "2.0" ) or state.distributed_type == DistributedType.NO: if state.local_process_index == 0: print( "**Test `accumulate` gradient accumulation with optimizer and scheduler, " , "`split_batches=False`, `dispatch_batches=False`**" , ) test_gradient_accumulation_with_opt_and_scheduler() if state.distributed_type == DistributedType.MULTI_GPU: for split_batch in [True, False]: for dispatch_batches in [True, False]: if not split_batch and not dispatch_batches: continue if state.local_process_index == 0: print( "**Test `accumulate` gradient accumulation with optimizer and scheduler, " , F"`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}`**" , ) test_gradient_accumulation_with_opt_and_scheduler(a , a ) def _lowerCamelCase( a ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
706
"""simple docstring""" import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class snake_case__ : def __init__( self , lowerCamelCase , lowerCamelCase=99 , lowerCamelCase=13 , lowerCamelCase=7 , lowerCamelCase=9 , lowerCamelCase=True , lowerCamelCase=True , lowerCamelCase=False , lowerCamelCase=32 , lowerCamelCase=5 , lowerCamelCase=4 , lowerCamelCase=37 , lowerCamelCase=8 , lowerCamelCase=0.1 , lowerCamelCase=0.002 , lowerCamelCase=1 , lowerCamelCase=0 , lowerCamelCase=0 , lowerCamelCase=None , lowerCamelCase=None , ): __a = parent __a = batch_size __a = encoder_seq_length __a = decoder_seq_length # For common tests __a = self.decoder_seq_length __a = is_training __a = use_attention_mask __a = use_labels __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = d_ff __a = relative_attention_num_buckets __a = dropout_rate __a = initializer_factor __a = eos_token_id __a = pad_token_id __a = decoder_start_token_id __a = None __a = decoder_layers def a__ ( self ): return TaConfig.from_pretrained("google/umt5-base" ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , ): if attention_mask is None: __a = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: __a = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: __a = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=lowerCamelCase ) if decoder_head_mask is None: __a = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=lowerCamelCase ) if cross_attn_head_mask is None: __a = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=lowerCamelCase ) 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, } def a__ ( self ): __a = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) __a = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input __a = input_ids.clamp(self.pad_token_id + 1 ) __a = decoder_input_ids.clamp(self.pad_token_id + 1 ) __a = self.get_config() __a = config.num_attention_heads __a = self.prepare_inputs_dict(lowerCamelCase , lowerCamelCase , lowerCamelCase ) return config, input_dict def a__ ( self ): __a , __a = self.prepare_config_and_inputs() return config, inputs_dict def a__ ( self ): return TaConfig( vocab_size=166 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def a__ ( self ): return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , ): __a = UMTaModel(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model( input_ids=lowerCamelCase , decoder_input_ids=lowerCamelCase , attention_mask=lowerCamelCase , decoder_attention_mask=lowerCamelCase , ) __a = model(input_ids=lowerCamelCase , decoder_input_ids=lowerCamelCase ) __a = result.last_hidden_state __a = result.past_key_values __a = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(lowerCamelCase ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , ): __a = UMTaModel(config=lowerCamelCase ).get_decoder().to(lowerCamelCase ).eval() # first forward pass __a = model(lowerCamelCase , use_cache=lowerCamelCase ) __a = model(lowerCamelCase ) __a = model(lowerCamelCase , use_cache=lowerCamelCase ) self.parent.assertTrue(len(lowerCamelCase ) == len(lowerCamelCase ) ) self.parent.assertTrue(len(lowerCamelCase ) == len(lowerCamelCase ) + 1 ) __a , __a = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __a = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and __a = torch.cat([input_ids, next_tokens] , dim=-1 ) __a = model(lowerCamelCase )["last_hidden_state"] __a = model(lowerCamelCase , past_key_values=lowerCamelCase )["last_hidden_state"] # select random slice __a = ids_tensor((1,) , output_from_past.shape[-1] ).item() __a = output_from_no_past[:, -1, random_slice_idx].detach() __a = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(lowerCamelCase , lowerCamelCase , atol=1E-3 ) ) def a__ ( self , lowerCamelCase , lowerCamelCase , ): __a = UMTaModel(config=lowerCamelCase ).to(lowerCamelCase ).half().eval() __a = model(**lowerCamelCase )["last_hidden_state"] self.parent.assertFalse(torch.isnan(lowerCamelCase ).any().item() ) @require_torch class snake_case__ ( snake_case_, snake_case_, snake_case_, unittest.TestCase ): _snake_case : Union[str, Any] = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) _snake_case : int = (UMTaForConditionalGeneration,) if is_torch_available() else () _snake_case : Optional[int] = ( { """conversational""": UMTaForConditionalGeneration, """feature-extraction""": UMTaModel, """summarization""": UMTaForConditionalGeneration, """text2text-generation""": UMTaForConditionalGeneration, """translation""": UMTaForConditionalGeneration, """question-answering""": UMTaForQuestionAnswering, } if is_torch_available() else {} ) _snake_case : List[Any] = True _snake_case : Union[str, Any] = False _snake_case : Union[str, Any] = False _snake_case : Tuple = True _snake_case : List[str] = True # The small UMT5 model needs higher percentages for CPU/MP tests _snake_case : Optional[Any] = [0.8, 0.9] def a__ ( self ): __a = UMTaModelTester(self ) @unittest.skip("Test has a segmentation fault on torch 1.8.0" ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() __a = UMTaModel(config_and_inputs[0] ).to(lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( lowerCamelCase , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , F"{tmpdirname}/t5_test.onnx" , export_params=lowerCamelCase , opset_version=9 , input_names=["input_ids", "decoder_input_ids"] , ) @unittest.skipIf(torch_device == "cpu" , "Cant do half precision" ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*lowerCamelCase ) def a__ ( self ): __a = ["encoder_attentions", "decoder_attentions", "cross_attentions"] __a = self.model_tester.prepare_config_and_inputs() __a = config_and_inputs[0] __a = UMTaForConditionalGeneration(lowerCamelCase ).eval() model.to(lowerCamelCase ) __a = { "head_mask": torch.zeros(config.num_layers , config.num_heads , device=lowerCamelCase ), "decoder_head_mask": torch.zeros(config.num_decoder_layers , config.num_heads , device=lowerCamelCase ), "cross_attn_head_mask": torch.zeros(config.num_decoder_layers , config.num_heads , device=lowerCamelCase ), } for attn_name, (name, mask) in zip(lowerCamelCase , head_masking.items() ): __a = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": __a = torch.ones( config.num_decoder_layers , config.num_heads , device=lowerCamelCase ) __a = model.generate( config_and_inputs[1]["input_ids"] , num_beams=1 , max_length=3 , output_attentions=lowerCamelCase , return_dict_in_generate=lowerCamelCase , **lowerCamelCase , ) # We check the state of decoder_attentions and cross_attentions just from the last step __a = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip("Does not work on the tiny model as we keep hitting edge cases." ) def a__ ( self ): pass @require_torch @require_sentencepiece @require_tokenizers class snake_case__ ( unittest.TestCase ): @slow @unittest.skip( "Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged" ) def a__ ( self ): __a = UMTaForConditionalGeneration.from_pretrained("google/umt5-small" , return_dict=lowerCamelCase ).to(lowerCamelCase ) __a = AutoTokenizer.from_pretrained("google/umt5-small" , use_fast=lowerCamelCase , legacy=lowerCamelCase ) __a = [ "Bonjour monsieur <extra_id_0> bien <extra_id_1>.", "No se como puedo <extra_id_0>.", "This is the reason why we <extra_id_0> them.", "The <extra_id_0> walks in <extra_id_1>, seats", "A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.", ] __a = tokenizer(lowerCamelCase , return_tensors="pt" , padding=lowerCamelCase ).input_ids # fmt: off __a = torch.tensor( [ [ 38530, 210703, 256299, 1410, 256298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 826, 321, 671, 25922, 256299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1460, 339, 312, 19014, 10620, 758, 256299, 2355,274, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 517, 256299, 14869, 281, 301, 256298, 275, 119983,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 320, 256299, 14869, 281, 2234, 289, 2275, 333,61391, 289, 256298, 543, 256297, 168714, 329, 256296,274, 1], ] ) # fmt: on torch.testing.assert_allclose(lowerCamelCase , lowerCamelCase ) __a = model.generate(input_ids.to(lowerCamelCase ) ) __a = [ "<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>", "<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", "<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", "<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", "<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", ] __a = tokenizer.batch_decode(lowerCamelCase ) self.assertEqual(lowerCamelCase , lowerCamelCase )
67
0
"""simple docstring""" import unittest import numpy as np from transformers import RoFormerConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.roformer.modeling_flax_roformer import ( FlaxRoFormerForMaskedLM, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerModel, ) class snake_case__ ( unittest.TestCase ): def __init__( self , lowerCamelCase , lowerCamelCase=13 , lowerCamelCase=7 , lowerCamelCase=True , lowerCamelCase=True , lowerCamelCase=True , lowerCamelCase=True , lowerCamelCase=99 , lowerCamelCase=32 , lowerCamelCase=5 , lowerCamelCase=4 , lowerCamelCase=37 , lowerCamelCase="gelu" , lowerCamelCase=0.1 , lowerCamelCase=0.1 , lowerCamelCase=512 , lowerCamelCase=16 , lowerCamelCase=2 , lowerCamelCase=0.02 , lowerCamelCase=4 , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_attention_mask __a = use_token_type_ids __a = use_labels __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = type_sequence_label_size __a = initializer_range __a = num_choices def a__ ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_attention_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None if self.use_token_type_ids: __a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a = RoFormerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=lowerCamelCase , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def a__ ( self ): __a = self.prepare_config_and_inputs() __a , __a , __a , __a = config_and_inputs __a = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask} return config, inputs_dict @require_flax class snake_case__ ( snake_case_, unittest.TestCase ): _snake_case : Optional[int] = True _snake_case : Tuple = ( ( FlaxRoFormerModel, FlaxRoFormerForMaskedLM, FlaxRoFormerForSequenceClassification, FlaxRoFormerForTokenClassification, FlaxRoFormerForMultipleChoice, FlaxRoFormerForQuestionAnswering, ) if is_flax_available() else () ) def a__ ( self ): __a = FlaxRoFormerModelTester(self ) @slow def a__ ( self ): for model_class_name in self.all_model_classes: __a = model_class_name.from_pretrained("junnyu/roformer_chinese_small" , from_pt=lowerCamelCase ) __a = model(np.ones((1, 1) ) ) self.assertIsNotNone(lowerCamelCase ) @require_flax class snake_case__ ( unittest.TestCase ): @slow def a__ ( self ): __a = FlaxRoFormerForMaskedLM.from_pretrained("junnyu/roformer_chinese_base" ) __a = jnp.array([[0, 1, 2, 3, 4, 5]] ) __a = model(lowerCamelCase )[0] __a = 50000 __a = (1, 6, vocab_size) self.assertEqual(output.shape , lowerCamelCase ) __a = jnp.array( [[[-0.1205, -1.0265, 0.2922], [-1.5134, 0.1974, 0.1519], [-5.0135, -3.9003, -0.8404]]] ) self.assertTrue(jnp.allclose(output[:, :3, :3] , lowerCamelCase , atol=1E-4 ) )
707
"""simple docstring""" import argparse import torch from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert from transformers.utils import logging logging.set_verbosity_info() def _lowerCamelCase( a , a , a ): # Initialise PyTorch model __a = MobileBertConfig.from_json_file(a ) print(F"Building PyTorch model from configuration: {config}" ) __a = MobileBertForPreTraining(a ) # Load weights from tf checkpoint __a = load_tf_weights_in_mobilebert(a , a , a ) # Save pytorch-model print(F"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , a ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__:List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--mobilebert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained MobileBERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) SCREAMING_SNAKE_CASE__:List[Any] = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.mobilebert_config_file, args.pytorch_dump_path)
67
0
import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor SCREAMING_SNAKE_CASE__:List[str] = logging.get_logger(__name__) class snake_case__ ( snake_case_ ): def __init__( self , *lowerCamelCase , **lowerCamelCase ): warnings.warn( "The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please" " use GLPNImageProcessor instead." , lowerCamelCase , ) super().__init__(*lowerCamelCase , **lowerCamelCase )
708
"""simple docstring""" import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class snake_case__ ( snake_case_ ): def a__ ( self , lowerCamelCase ): with open(lowerCamelCase , encoding="utf-8" ) as input_file: __a = re.compile(R"(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)" ) __a = input_file.read() __a = regexp.search(lowerCamelCase ) return match def a__ ( self , lowerCamelCase ): with open(lowerCamelCase , encoding="utf-8" ) as input_file: __a = re.compile(R"#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()" , re.DOTALL ) __a = input_file.read() # use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search` __a = regexp.finditer(lowerCamelCase ) __a = [match for match in matches if match is not None and match.group(1 ) is not None] return matches[0] if matches else None def a__ ( self ): __a = Path("./datasets" ) __a = list(dataset_paths.absolute().glob("**/*.py" ) ) for dataset in dataset_files: if self._no_encoding_on_file_open(str(lowerCamelCase ) ): raise AssertionError(F"open(...) must use utf-8 encoding in {dataset}" ) def a__ ( self ): __a = Path("./datasets" ) __a = list(dataset_paths.absolute().glob("**/*.py" ) ) for dataset in dataset_files: if self._no_print_statements(str(lowerCamelCase ) ): raise AssertionError(F"print statement found in {dataset}. Use datasets.logger/logging instead." )
67
0
"""simple docstring""" import sys SCREAMING_SNAKE_CASE__:List[Any] = ( """73167176531330624919225119674426574742355349194934""" """96983520312774506326239578318016984801869478851843""" """85861560789112949495459501737958331952853208805511""" """12540698747158523863050715693290963295227443043557""" """66896648950445244523161731856403098711121722383113""" """62229893423380308135336276614282806444486645238749""" """30358907296290491560440772390713810515859307960866""" """70172427121883998797908792274921901699720888093776""" """65727333001053367881220235421809751254540594752243""" """52584907711670556013604839586446706324415722155397""" """53697817977846174064955149290862569321978468622482""" """83972241375657056057490261407972968652414535100474""" """82166370484403199890008895243450658541227588666881""" """16427171479924442928230863465674813919123162824586""" """17866458359124566529476545682848912883142607690042""" """24219022671055626321111109370544217506941658960408""" """07198403850962455444362981230987879927244284909188""" """84580156166097919133875499200524063689912560717606""" """05886116467109405077541002256983155200055935729725""" """71636269561882670428252483600823257530420752963450""" ) def _lowerCamelCase( a = N ): __a = -sys.maxsize - 1 for i in range(len(a ) - 1_2 ): __a = 1 for j in range(1_3 ): product *= int(n[i + j] ) if product > largest_product: __a = product return largest_product if __name__ == "__main__": print(F'''{solution() = }''')
709
"""simple docstring""" from .imports import is_rich_available if is_rich_available(): from rich.traceback import install install(show_locals=False) else: raise ModuleNotFoundError("""To use the rich extension, install rich with `pip install rich`""")
67
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) SCREAMING_SNAKE_CASE__:Optional[Any] = { """configuration_gpt_bigcode""": ["""GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTBigCodeConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__:Union[str, Any] = [ """GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST""", """GPTBigCodeForSequenceClassification""", """GPTBigCodeForTokenClassification""", """GPTBigCodeForCausalLM""", """GPTBigCodeModel""", """GPTBigCodePreTrainedModel""", ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__:List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
710
"""simple docstring""" import heapq import sys import numpy as np SCREAMING_SNAKE_CASE__:Optional[int] = tuple[int, int] class snake_case__ : def __init__( self ): __a = [] __a = set() def a__ ( self ): if not self.empty(): return self.elements[0][0] else: return float("inf" ) def a__ ( self ): return len(self.elements ) == 0 def a__ ( self , lowerCamelCase , lowerCamelCase ): if item not in self.set: heapq.heappush(self.elements , (priority, item) ) self.set.add(lowerCamelCase ) else: # update # print("update", item) __a = [] ((__a) , (__a)) = heapq.heappop(self.elements ) while x != item: temp.append((pri, x) ) ((__a) , (__a)) = heapq.heappop(self.elements ) temp.append((priority, item) ) for pro, xxx in temp: heapq.heappush(self.elements , (pro, xxx) ) def a__ ( self , lowerCamelCase ): if item in self.set: self.set.remove(lowerCamelCase ) __a = [] ((__a) , (__a)) = heapq.heappop(self.elements ) while x != item: temp.append((pro, x) ) ((__a) , (__a)) = heapq.heappop(self.elements ) for prito, yyy in temp: heapq.heappush(self.elements , (prito, yyy) ) def a__ ( self ): return self.elements[0][1] def a__ ( self ): ((__a) , (__a)) = heapq.heappop(self.elements ) self.set.remove(lowerCamelCase ) return (priority, item) def _lowerCamelCase( a , a ): # euclidean distance __a = np.array(a ) __a = np.array(a ) return np.linalg.norm(a - b ) def _lowerCamelCase( a , a ): # integer division by time variable return consistent_heuristic(a , a ) // t def _lowerCamelCase( a , a ): # manhattan distance return abs(p[0] - goal[0] ) + abs(p[1] - goal[1] ) def _lowerCamelCase( a , a , a , a ): __a = g_function[start] + Wa * heuristics[i](a , a ) return ans def _lowerCamelCase( a , a , a ): __a = np.chararray((n, n) ) for i in range(a ): for j in range(a ): __a = "*" for i in range(a ): for j in range(a ): if (j, (n - 1) - i) in blocks: __a = "#" __a = "-" __a = back_pointer[goal] while x != start: ((__a) , (__a)) = x # print(x) __a = "-" __a = back_pointer[x] __a = "-" for i in range(a ): for j in range(a ): if (i, j) == (0, n - 1): print(grid[i][j] , end=" " ) print("<-- End position" , end=" " ) else: print(grid[i][j] , end=" " ) print() print("^" ) print("Start position" ) print() print("# is an obstacle" ) print("- is the path taken by algorithm" ) print("PATH TAKEN BY THE ALGORITHM IS:-" ) __a = back_pointer[goal] while x != start: print(a , end=" " ) __a = back_pointer[x] print(a ) sys.exit() def _lowerCamelCase( a ): if p[0] < 0 or p[0] > n - 1: return False if p[1] < 0 or p[1] > n - 1: return False return True def _lowerCamelCase( a , a , a , a , a , a , a , a , ): for itera in range(a ): open_list[itera].remove_element(a ) # print("s", s) # print("j", j) ((__a) , (__a)) = s __a = (x - 1, y) __a = (x + 1, y) __a = (x, y + 1) __a = (x, y - 1) for neighbours in [left, right, up, down]: if neighbours not in blocks: if valid(a ) and neighbours not in visited: # print("neighbour", neighbours) visited.add(a ) __a = -1 __a = float("inf" ) if valid(a ) and g_function[neighbours] > g_function[s] + 1: __a = g_function[s] + 1 __a = s if neighbours not in close_list_anchor: open_list[0].put(a , key(a , 0 , a , a ) ) if neighbours not in close_list_inad: for var in range(1 , a ): if key(a , a , a , a ) <= Wa * key( a , 0 , a , a ): open_list[j].put( a , key(a , a , a , a ) ) def _lowerCamelCase( ): __a = [] for x in range(1 , 5 ): for y in range(1 , 6 ): some_list.append((x, y) ) for x in range(1_5 , 2_0 ): some_list.append((x, 1_7) ) for x in range(1_0 , 1_9 ): for y in range(1 , 1_5 ): some_list.append((x, y) ) # L block for x in range(1 , 4 ): for y in range(1_2 , 1_9 ): some_list.append((x, y) ) for x in range(3 , 1_3 ): for y in range(1_6 , 1_9 ): some_list.append((x, y) ) return some_list SCREAMING_SNAKE_CASE__:Any = {0: consistent_heuristic, 1: heuristic_a, 2: heuristic_a} SCREAMING_SNAKE_CASE__:str = [ (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1), ] SCREAMING_SNAKE_CASE__:int = make_common_ground() SCREAMING_SNAKE_CASE__:List[str] = blocks_blk # hyper parameters SCREAMING_SNAKE_CASE__:str = 1 SCREAMING_SNAKE_CASE__:Union[str, Any] = 1 SCREAMING_SNAKE_CASE__:Union[str, Any] = 20 SCREAMING_SNAKE_CASE__:Dict = 3 # one consistent and two other inconsistent # start and end destination SCREAMING_SNAKE_CASE__:Dict = (0, 0) SCREAMING_SNAKE_CASE__:Optional[Any] = (n - 1, n - 1) SCREAMING_SNAKE_CASE__:List[str] = 1 def _lowerCamelCase( a , a , a ): __a = {start: 0, goal: float("inf" )} __a = {start: -1, goal: -1} __a = [] __a = set() for i in range(a ): open_list.append(PriorityQueue() ) open_list[i].put(a , key(a , a , a , a ) ) __a = [] __a = [] while open_list[0].minkey() < float("inf" ): for i in range(1 , a ): # print(open_list[0].minkey(), open_list[i].minkey()) if open_list[i].minkey() <= Wa * open_list[0].minkey(): global t t += 1 if g_function[goal] <= open_list[i].minkey(): if g_function[goal] < float("inf" ): do_something(a , a , a ) else: __a , __a = open_list[i].top_show() visited.add(a ) expand_state( a , a , a , a , a , a , a , a , ) close_list_inad.append(a ) else: if g_function[goal] <= open_list[0].minkey(): if g_function[goal] < float("inf" ): do_something(a , a , a ) else: __a = open_list[0].top_show() visited.add(a ) expand_state( a , 0 , a , a , a , a , a , a , ) close_list_anchor.append(a ) print("No path found to goal" ) print() for i in range(n - 1 , -1 , -1 ): for j in range(a ): if (j, i) in blocks: print("#" , end=" " ) elif (j, i) in back_pointer: if (j, i) == (n - 1, n - 1): print("*" , end=" " ) else: print("-" , end=" " ) else: print("*" , end=" " ) if (j, i) == (n - 1, n - 1): print("<-- End position" , end=" " ) print() print("^" ) print("Start position" ) print() print("# is an obstacle" ) print("- is the path taken by algorithm" ) if __name__ == "__main__": multi_a_star(start, goal, n_heuristic)
67
0
"""simple docstring""" import math import os import unittest from transformers import MegatronBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MegatronBertForCausalLM, MegatronBertForMaskedLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, MegatronBertModel, ) class snake_case__ : def __init__( self , lowerCamelCase , lowerCamelCase=13 , lowerCamelCase=7 , lowerCamelCase=True , lowerCamelCase=True , lowerCamelCase=True , lowerCamelCase=True , lowerCamelCase=99 , lowerCamelCase=64 , lowerCamelCase=32 , lowerCamelCase=5 , lowerCamelCase=4 , lowerCamelCase=37 , lowerCamelCase="gelu" , lowerCamelCase=0.1 , lowerCamelCase=0.1 , lowerCamelCase=512 , lowerCamelCase=16 , lowerCamelCase=2 , lowerCamelCase=0.02 , lowerCamelCase=3 , lowerCamelCase=4 , lowerCamelCase=None , ): __a = parent __a = batch_size __a = seq_length __a = is_training __a = use_input_mask __a = use_token_type_ids __a = use_labels __a = vocab_size __a = hidden_size __a = embedding_size __a = num_hidden_layers __a = num_attention_heads __a = intermediate_size __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = type_sequence_label_size __a = initializer_range __a = num_labels __a = num_choices __a = scope def a__ ( self ): __a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __a = None if self.use_input_mask: __a = random_attention_mask([self.batch_size, self.seq_length] ) __a = None if self.use_token_type_ids: __a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __a = None __a = None __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __a = ids_tensor([self.batch_size] , self.num_choices ) __a = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def a__ ( self ): return MegatronBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , embedding_size=self.embedding_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=lowerCamelCase , initializer_range=self.initializer_range , ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = MegatronBertModel(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase ) __a = model(lowerCamelCase , token_type_ids=lowerCamelCase ) __a = model(lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = MegatronBertForMaskedLM(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = MegatronBertForCausalLM(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = MegatronBertForNextSentencePrediction(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model( lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase , labels=lowerCamelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = MegatronBertForPreTraining(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model( lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase , labels=lowerCamelCase , next_sentence_label=lowerCamelCase , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = MegatronBertForQuestionAnswering(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model( 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 a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = self.num_labels __a = MegatronBertForSequenceClassification(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = self.num_labels __a = MegatronBertForTokenClassification(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = self.num_choices __a = MegatronBertForMultipleChoice(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __a = model( lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase , labels=lowerCamelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a__ ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class snake_case__ ( snake_case_, snake_case_, unittest.TestCase ): _snake_case : int = ( ( MegatronBertModel, MegatronBertForMaskedLM, MegatronBertForCausalLM, MegatronBertForMultipleChoice, MegatronBertForNextSentencePrediction, MegatronBertForPreTraining, MegatronBertForQuestionAnswering, MegatronBertForSequenceClassification, MegatronBertForTokenClassification, ) if is_torch_available() else () ) _snake_case : Any = ( { """feature-extraction""": MegatronBertModel, """fill-mask""": MegatronBertForMaskedLM, """question-answering""": MegatronBertForQuestionAnswering, """text-classification""": MegatronBertForSequenceClassification, """text-generation""": MegatronBertForCausalLM, """token-classification""": MegatronBertForTokenClassification, """zero-shot""": MegatronBertForSequenceClassification, } if is_torch_available() else {} ) _snake_case : Dict = True # test_resize_embeddings = False _snake_case : str = False def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase=False ): __a = super()._prepare_for_class(lowerCamelCase , lowerCamelCase , return_labels=lowerCamelCase ) if return_labels: if model_class in get_values(lowerCamelCase ): __a = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=lowerCamelCase ) __a = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=lowerCamelCase ) return inputs_dict def a__ ( self ): __a = MegatronBertModelTester(self ) __a = ConfigTester(self , config_class=lowerCamelCase , hidden_size=37 ) def a__ ( self ): self.config_tester.run_common_tests() def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_model(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_masked_lm(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_multiple_choice(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_next_sequence_prediction(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_pretraining(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_question_answering(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_sequence_classification(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_megatron_bert_for_token_classification(*lowerCamelCase ) def _lowerCamelCase( a ): return torch.tensor( a , dtype=torch.long , device=a , ) SCREAMING_SNAKE_CASE__:Optional[int] = 1e-4 @require_torch @require_sentencepiece @require_tokenizers class snake_case__ ( unittest.TestCase ): @slow @unittest.skip("Model is not available." ) def a__ ( self ): __a = "nvidia/megatron-bert-uncased-345m" if "MYDIR" in os.environ: __a = os.path.join(os.environ["MYDIR"] , lowerCamelCase ) __a = MegatronBertModel.from_pretrained(lowerCamelCase ) model.to(lowerCamelCase ) model.half() __a = _long_tensor([[101, 7110, 1005, 1056, 2023, 11333, 17413, 1029, 102]] ) with torch.no_grad(): __a = model(lowerCamelCase )[0] __a = torch.Size((1, 9, 1024) ) self.assertEqual(output.shape , lowerCamelCase ) __a = [-0.6040, -0.2517, -0.1025, 0.3420, -0.6758, -0.0017, -0.1089, -0.1990, 0.5728] for ii in range(3 ): for jj in range(3 ): __a = output[0, ii, jj] __a = expected[3 * ii + jj] __a = "ii={} jj={} a={} b={}".format(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) self.assertTrue(math.isclose(lowerCamelCase , lowerCamelCase , rel_tol=lowerCamelCase , abs_tol=lowerCamelCase ) , msg=lowerCamelCase )
711
"""simple docstring""" SCREAMING_SNAKE_CASE__:Any = """Alexander Joslin""" import operator as op from .stack import Stack def _lowerCamelCase( a ): __a = {"*": op.mul, "/": op.truediv, "+": op.add, "-": op.sub} __a = Stack() __a = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(a ) ) elif i in operators: # RULE 2 operator_stack.push(a ) elif i == ")": # RULE 4 __a = operator_stack.peek() operator_stack.pop() __a = operand_stack.peek() operand_stack.pop() __a = operand_stack.peek() operand_stack.pop() __a = operators[opr](a , a ) operand_stack.push(a ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": SCREAMING_SNAKE_CASE__:Tuple = """(5 + ((4 * 2) * (2 + 3)))""" # answer = 45 print(F'''{equation} = {dijkstras_two_stack_algorithm(equation)}''')
67
0
"""simple docstring""" from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxCrossAttnUpBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, FlaxUpBlockaD, ) @flax.struct.dataclass class snake_case__ ( snake_case_ ): _snake_case : jnp.ndarray @flax_register_to_config class snake_case__ ( nn.Module, snake_case_, snake_case_ ): _snake_case : int = 32 _snake_case : int = 4 _snake_case : int = 4 _snake_case : Tuple[str] = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) _snake_case : Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D") _snake_case : Union[bool, Tuple[bool]] = False _snake_case : Tuple[int] = (320, 640, 1_280, 1_280) _snake_case : int = 2 _snake_case : Union[int, Tuple[int]] = 8 _snake_case : Optional[Union[int, Tuple[int]]] = None _snake_case : int = 1_280 _snake_case : float = 0.0 _snake_case : bool = False _snake_case : jnp.dtype = jnp.floataa _snake_case : bool = True _snake_case : int = 0 _snake_case : bool = False def a__ ( self , lowerCamelCase ): # init input tensors __a = (1, self.in_channels, self.sample_size, self.sample_size) __a = jnp.zeros(lowerCamelCase , dtype=jnp.floataa ) __a = jnp.ones((1,) , dtype=jnp.intaa ) __a = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) __a , __a = jax.random.split(lowerCamelCase ) __a = {"params": params_rng, "dropout": dropout_rng} return self.init(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase )["params"] def a__ ( self ): __a = self.block_out_channels __a = block_out_channels[0] * 4 if self.num_attention_heads is not None: raise ValueError( "At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19." ) # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. __a = self.num_attention_heads or self.attention_head_dim # input __a = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time __a = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) __a = FlaxTimestepEmbedding(lowerCamelCase , dtype=self.dtype ) __a = self.only_cross_attention if isinstance(lowerCamelCase , lowerCamelCase ): __a = (only_cross_attention,) * len(self.down_block_types ) if isinstance(lowerCamelCase , lowerCamelCase ): __a = (num_attention_heads,) * len(self.down_block_types ) # down __a = [] __a = block_out_channels[0] for i, down_block_type in enumerate(self.down_block_types ): __a = output_channel __a = block_out_channels[i] __a = i == len(lowerCamelCase ) - 1 if down_block_type == "CrossAttnDownBlock2D": __a = FlaxCrossAttnDownBlockaD( in_channels=lowerCamelCase , out_channels=lowerCamelCase , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: __a = FlaxDownBlockaD( in_channels=lowerCamelCase , out_channels=lowerCamelCase , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(lowerCamelCase ) __a = down_blocks # mid __a = FlaxUNetMidBlockaDCrossAttn( in_channels=block_out_channels[-1] , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) # up __a = [] __a = list(reversed(lowerCamelCase ) ) __a = list(reversed(lowerCamelCase ) ) __a = list(reversed(lowerCamelCase ) ) __a = reversed_block_out_channels[0] for i, up_block_type in enumerate(self.up_block_types ): __a = output_channel __a = reversed_block_out_channels[i] __a = reversed_block_out_channels[min(i + 1 , len(lowerCamelCase ) - 1 )] __a = i == len(lowerCamelCase ) - 1 if up_block_type == "CrossAttnUpBlock2D": __a = FlaxCrossAttnUpBlockaD( in_channels=lowerCamelCase , out_channels=lowerCamelCase , prev_output_channel=lowerCamelCase , num_layers=self.layers_per_block + 1 , num_attention_heads=reversed_num_attention_heads[i] , add_upsample=not is_final_block , dropout=self.dropout , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: __a = FlaxUpBlockaD( in_channels=lowerCamelCase , out_channels=lowerCamelCase , prev_output_channel=lowerCamelCase , num_layers=self.layers_per_block + 1 , add_upsample=not is_final_block , dropout=self.dropout , dtype=self.dtype , ) up_blocks.append(lowerCamelCase ) __a = output_channel __a = up_blocks # out __a = nn.GroupNorm(num_groups=32 , epsilon=1E-5 ) __a = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase = True , lowerCamelCase = False , ): # 1. time if not isinstance(lowerCamelCase , jnp.ndarray ): __a = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(lowerCamelCase , jnp.ndarray ) and len(timesteps.shape ) == 0: __a = timesteps.astype(dtype=jnp.floataa ) __a = jnp.expand_dims(lowerCamelCase , 0 ) __a = self.time_proj(lowerCamelCase ) __a = self.time_embedding(lowerCamelCase ) # 2. pre-process __a = jnp.transpose(lowerCamelCase , (0, 2, 3, 1) ) __a = self.conv_in(lowerCamelCase ) # 3. down __a = (sample,) for down_block in self.down_blocks: if isinstance(lowerCamelCase , lowerCamelCase ): __a , __a = down_block(lowerCamelCase , lowerCamelCase , lowerCamelCase , deterministic=not train ) else: __a , __a = down_block(lowerCamelCase , lowerCamelCase , deterministic=not train ) down_block_res_samples += res_samples if down_block_additional_residuals is not None: __a = () for down_block_res_sample, down_block_additional_residual in zip( lowerCamelCase , lowerCamelCase ): down_block_res_sample += down_block_additional_residual new_down_block_res_samples += (down_block_res_sample,) __a = new_down_block_res_samples # 4. mid __a = self.mid_block(lowerCamelCase , lowerCamelCase , lowerCamelCase , deterministic=not train ) if mid_block_additional_residual is not None: sample += mid_block_additional_residual # 5. up for up_block in self.up_blocks: __a = down_block_res_samples[-(self.layers_per_block + 1) :] __a = down_block_res_samples[: -(self.layers_per_block + 1)] if isinstance(lowerCamelCase , lowerCamelCase ): __a = up_block( lowerCamelCase , temb=lowerCamelCase , encoder_hidden_states=lowerCamelCase , res_hidden_states_tuple=lowerCamelCase , deterministic=not train , ) else: __a = up_block(lowerCamelCase , temb=lowerCamelCase , res_hidden_states_tuple=lowerCamelCase , deterministic=not train ) # 6. post-process __a = self.conv_norm_out(lowerCamelCase ) __a = nn.silu(lowerCamelCase ) __a = self.conv_out(lowerCamelCase ) __a = jnp.transpose(lowerCamelCase , (0, 3, 1, 2) ) if not return_dict: return (sample,) return FlaxUNetaDConditionOutput(sample=lowerCamelCase )
712
"""simple docstring""" from math import pi def _lowerCamelCase( a , a ): return 2 * pi * radius * (angle / 3_6_0) if __name__ == "__main__": print(arc_length(90, 10))
67
0
from __future__ import annotations from math import pow, sqrt def _lowerCamelCase( a , a , a ): if (resistance, reactance, impedance).count(0 ) != 1: raise ValueError("One and only one argument must be 0" ) if resistance == 0: return {"resistance": sqrt(pow(a , 2 ) - pow(a , 2 ) )} elif reactance == 0: return {"reactance": sqrt(pow(a , 2 ) - pow(a , 2 ) )} elif impedance == 0: return {"impedance": sqrt(pow(a , 2 ) + pow(a , 2 ) )} else: raise ValueError("Exactly one argument must be 0" ) if __name__ == "__main__": import doctest doctest.testmod()
713
"""simple docstring""" from typing import Dict, Iterable, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging SCREAMING_SNAKE_CASE__:List[str] = logging.get_logger(__name__) class snake_case__ ( snake_case_ ): _snake_case : Dict = ["""pixel_values"""] def __init__( self , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = PILImageResampling.BICUBIC , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = True , lowerCamelCase = 1 / 255 , lowerCamelCase = True , lowerCamelCase = IMAGENET_DEFAULT_MEAN , lowerCamelCase = IMAGENET_DEFAULT_STD , **lowerCamelCase , ): super().__init__(**lowerCamelCase ) __a = size if size is not None else {"shortest_edge": 224} __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) __a = crop_size if crop_size is not None else {"height": 224, "width": 224} __a = get_size_dict(lowerCamelCase , param_name="crop_size" ) __a = do_resize __a = size __a = resample __a = do_center_crop __a = crop_size __a = do_rescale __a = rescale_factor __a = do_normalize __a = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN __a = image_std if image_std is not None else IMAGENET_DEFAULT_STD def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = PILImageResampling.BICUBIC , lowerCamelCase = None , **lowerCamelCase , ): __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) # size_dict is a dict with either keys "height" and "width" or "shortest_edge" if "shortest_edge" in size: __a = int((256 / 224) * size["shortest_edge"] ) __a = get_resize_output_image_size(lowerCamelCase , size=lowerCamelCase , default_to_square=lowerCamelCase ) __a = {"height": output_size[0], "width": output_size[1]} if "height" not in size_dict or "width" not in size_dict: raise ValueError( F"Size dict must have keys 'height' and 'width' or 'shortest_edge'. Got {size_dict.keys()}" ) return resize( lowerCamelCase , size=(size_dict["height"], size_dict["width"]) , resample=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): __a = get_size_dict(lowerCamelCase ) if "height" not in size or "width" not in size: raise ValueError(F"Size dict must have keys 'height' and 'width'. Got {size.keys()}" ) return center_crop(lowerCamelCase , size=(size["height"], size["width"]) , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): return rescale(lowerCamelCase , scale=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): return normalize(lowerCamelCase , mean=lowerCamelCase , std=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = ChannelDimension.FIRST , **lowerCamelCase , ): __a = do_resize if do_resize is not None else self.do_resize __a = resample if resample is not None else self.resample __a = do_center_crop if do_center_crop is not None else self.do_center_crop __a = do_rescale if do_rescale is not None else self.do_rescale __a = rescale_factor if rescale_factor is not None else self.rescale_factor __a = do_normalize if do_normalize is not None else self.do_normalize __a = image_mean if image_mean is not None else self.image_mean __a = image_std if image_std is not None else self.image_std __a = size if size is not None else self.size __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) __a = crop_size if crop_size is not None else self.crop_size __a = get_size_dict(lowerCamelCase , param_name="crop_size" ) __a = make_list_of_images(lowerCamelCase ) if not valid_images(lowerCamelCase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. __a = [to_numpy_array(lowerCamelCase ) for image in images] if do_resize: __a = [self.resize(lowerCamelCase , lowerCamelCase , lowerCamelCase ) for image in images] if do_center_crop: __a = [self.center_crop(lowerCamelCase , lowerCamelCase ) for image in images] if do_rescale: __a = [self.rescale(lowerCamelCase , lowerCamelCase ) for image in images] if do_normalize: __a = [self.normalize(lowerCamelCase , lowerCamelCase , lowerCamelCase ) for image in images] __a = [to_channel_dimension_format(lowerCamelCase , lowerCamelCase ) for image in images] __a = {"pixel_values": images} return BatchFeature(data=lowerCamelCase , tensor_type=lowerCamelCase )
67
0
"""simple docstring""" def _lowerCamelCase( ): __a = [3_1, 2_8, 3_1, 3_0, 3_1, 3_0, 3_1, 3_1, 3_0, 3_1, 3_0, 3_1] __a = 6 __a = 1 __a = 1_9_0_1 __a = 0 while year < 2_0_0_1: day += 7 if (year % 4 == 0 and year % 1_0_0 != 0) or (year % 4_0_0 == 0): if day > days_per_month[month - 1] and month != 2: month += 1 __a = day - days_per_month[month - 2] elif day > 2_9 and month == 2: month += 1 __a = day - 2_9 else: if day > days_per_month[month - 1]: month += 1 __a = day - days_per_month[month - 2] if month > 1_2: year += 1 __a = 1 if year < 2_0_0_1 and day == 1: sundays += 1 return sundays if __name__ == "__main__": print(solution())
714
"""simple docstring""" import inspect import unittest from transformers import ViTConfig 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 ViTForImageClassification, ViTForMaskedImageModeling, ViTModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class snake_case__ : 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=None , lowerCamelCase=2 , ): __a = parent __a = batch_size __a = image_size __a = patch_size __a = num_channels __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 = encoder_stride # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) __a = (image_size // patch_size) ** 2 __a = num_patches + 1 def a__ ( self ): __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = self.get_config() return config, pixel_values, labels def a__ ( self ): return ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=lowerCamelCase , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = ViTModel(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = ViTForMaskedImageModeling(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __a = 1 __a = ViTForMaskedImageModeling(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __a = model(lowerCamelCase ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = self.type_sequence_label_size __a = ViTForImageClassification(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __a = 1 __a = ViTForImageClassification(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __a = model(lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a__ ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class snake_case__ ( snake_case_, snake_case_, unittest.TestCase ): _snake_case : Any = ( ( ViTModel, ViTForImageClassification, ViTForMaskedImageModeling, ) if is_torch_available() else () ) _snake_case : List[Any] = ( {"""feature-extraction""": ViTModel, """image-classification""": ViTForImageClassification} if is_torch_available() else {} ) _snake_case : int = True _snake_case : int = False _snake_case : str = False _snake_case : Optional[Any] = False def a__ ( self ): __a = ViTModelTester(self ) __a = ConfigTester(self , config_class=lowerCamelCase , has_text_modality=lowerCamelCase , hidden_size=37 ) def a__ ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="ViT does not use inputs_embeds" ) def a__ ( self ): pass def a__ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __a = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCamelCase , nn.Linear ) ) def a__ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(lowerCamelCase ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase ) @slow def a__ ( self ): for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = ViTModel.from_pretrained(lowerCamelCase ) self.assertIsNotNone(lowerCamelCase ) def _lowerCamelCase( ): __a = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class snake_case__ ( unittest.TestCase ): @cached_property def a__ ( self ): return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224" ) if is_vision_available() else None @slow def a__ ( self ): __a = ViTForImageClassification.from_pretrained("google/vit-base-patch16-224" ).to(lowerCamelCase ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase ) # forward pass with torch.no_grad(): __a = model(**lowerCamelCase ) # verify the logits __a = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , lowerCamelCase ) __a = torch.tensor([-0.2744, 0.8215, -0.0836] ).to(lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCamelCase , atol=1E-4 ) ) @slow def a__ ( self ): # ViT models have an `interpolate_pos_encoding` argument in their forward method, # allowing to interpolate the pre-trained position embeddings in order to use # the model on higher resolutions. The DINO model by Facebook AI leverages this # to visualize self-attention on higher resolution images. __a = ViTModel.from_pretrained("facebook/dino-vits8" ).to(lowerCamelCase ) __a = ViTImageProcessor.from_pretrained("facebook/dino-vits8" , size=480 ) __a = prepare_img() __a = image_processor(images=lowerCamelCase , return_tensors="pt" ) __a = inputs.pixel_values.to(lowerCamelCase ) # forward pass with torch.no_grad(): __a = model(lowerCamelCase , interpolate_pos_encoding=lowerCamelCase ) # verify the logits __a = torch.Size((1, 3601, 384) ) self.assertEqual(outputs.last_hidden_state.shape , lowerCamelCase ) __a = torch.tensor( [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]] ).to(lowerCamelCase ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , lowerCamelCase , atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def a__ ( self ): __a = ViTModel.from_pretrained("facebook/dino-vits8" , torch_dtype=torch.floataa , device_map="auto" ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=lowerCamelCase , return_tensors="pt" ) __a = inputs.pixel_values.to(lowerCamelCase ) # forward pass to make sure inference works in fp16 with torch.no_grad(): __a = model(lowerCamelCase )
67
0
"""simple docstring""" 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 snake_case__ : # setable values _snake_case : Optional[int] = None _snake_case : Optional[jnp.ndarray] = None _snake_case : Optional[jnp.ndarray] = None # sigma(t_i) @classmethod def a__ ( cls ): return cls() @dataclass class snake_case__ ( snake_case_ ): _snake_case : jnp.ndarray _snake_case : jnp.ndarray _snake_case : KarrasVeSchedulerState class snake_case__ ( snake_case_, snake_case_ ): @property def a__ ( self ): return True @register_to_config def __init__( self , lowerCamelCase = 0.02 , lowerCamelCase = 100 , lowerCamelCase = 1.007 , lowerCamelCase = 80 , lowerCamelCase = 0.05 , lowerCamelCase = 50 , ): pass def a__ ( self ): return KarrasVeSchedulerState.create() def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = () ): __a = jnp.arange(0 , lowerCamelCase )[::-1].copy() __a = [ ( 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=lowerCamelCase , schedule=jnp.array(lowerCamelCase , dtype=jnp.floataa ) , timesteps=lowerCamelCase , ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , ): if self.config.s_min <= sigma <= self.config.s_max: __a = min(self.config.s_churn / state.num_inference_steps , 2**0.5 - 1 ) else: __a = 0 # sample eps ~ N(0, S_noise^2 * I) __a = random.split(lowerCamelCase , num=1 ) __a = self.config.s_noise * random.normal(key=lowerCamelCase , shape=sample.shape ) __a = sigma + gamma * sigma __a = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase = True , ): __a = sample_hat + sigma_hat * model_output __a = (sample_hat - pred_original_sample) / sigma_hat __a = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative, state) return FlaxKarrasVeOutput(prev_sample=lowerCamelCase , derivative=lowerCamelCase , state=lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase = True , ): __a = sample_prev + sigma_prev * model_output __a = (sample_prev - pred_original_sample) / sigma_prev __a = 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=lowerCamelCase , derivative=lowerCamelCase , state=lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): raise NotImplementedError()
715
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetaImageProcessor class snake_case__ ( unittest.TestCase ): def __init__( self , lowerCamelCase , lowerCamelCase=7 , lowerCamelCase=3 , lowerCamelCase=30 , lowerCamelCase=400 , lowerCamelCase=True , lowerCamelCase=None , lowerCamelCase=True , lowerCamelCase=[0.5, 0.5, 0.5] , lowerCamelCase=[0.5, 0.5, 0.5] , lowerCamelCase=True , lowerCamelCase=1 / 255 , lowerCamelCase=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __a = size if size is not None else {"shortest_edge": 18, "longest_edge": 1333} __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 a__ ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def a__ ( self , lowerCamelCase , lowerCamelCase=False ): if not batched: __a = image_inputs[0] if isinstance(lowerCamelCase , Image.Image ): __a , __a = image.size else: __a , __a = image.shape[1], image.shape[2] if w < h: __a = int(self.size["shortest_edge"] * h / w ) __a = self.size["shortest_edge"] elif w > h: __a = self.size["shortest_edge"] __a = int(self.size["shortest_edge"] * w / h ) else: __a = self.size["shortest_edge"] __a = self.size["shortest_edge"] else: __a = [] for image in image_inputs: __a , __a = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __a = max(lowerCamelCase , key=lambda lowerCamelCase : item[0] )[0] __a = max(lowerCamelCase , key=lambda lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case__ ( snake_case_, unittest.TestCase ): _snake_case : List[Any] = DetaImageProcessor if is_vision_available() else None def a__ ( self ): __a = DetaImageProcessingTester(self ) @property def a__ ( self ): return self.image_processor_tester.prepare_image_processor_dict() def a__ ( self ): __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_rescale" ) ) self.assertTrue(hasattr(lowerCamelCase , "do_pad" ) ) self.assertTrue(hasattr(lowerCamelCase , "size" ) ) def a__ ( self ): __a = 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 , lowerCamelCase ) def a__ ( self ): pass def a__ ( self ): # 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 __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) __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, expected_height, expected_width, ) , ) def a__ ( self ): # 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 __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def a__ ( self ): # 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 __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def a__ ( self ): # prepare image and target __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": 39769, "annotations": target} # encode them __a = DetaImageProcessor() __a = image_processing(images=lowerCamelCase , annotations=lowerCamelCase , return_tensors="pt" ) # verify pixel values __a = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase ) __a = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase , atol=1E-4 ) ) # verify area __a = 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"] , lowerCamelCase ) ) # verify boxes __a = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase ) __a = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase , atol=1E-3 ) ) # verify image_id __a = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase ) ) # verify is_crowd __a = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase ) ) # verify class_labels __a = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase ) ) # verify orig_size __a = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase ) ) # verify size __a = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase ) ) @slow def a__ ( self ): # prepare image, target and masks_path __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": 39769, "segments_info": target} __a = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them __a = DetaImageProcessor(format="coco_panoptic" ) __a = image_processing(images=lowerCamelCase , annotations=lowerCamelCase , masks_path=lowerCamelCase , return_tensors="pt" ) # verify pixel values __a = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase ) __a = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase , atol=1E-4 ) ) # verify area __a = 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"] , lowerCamelCase ) ) # verify boxes __a = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase ) __a = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase , atol=1E-3 ) ) # verify image_id __a = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase ) ) # verify is_crowd __a = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase ) ) # verify class_labels __a = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase ) ) # verify masks __a = 822873 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , lowerCamelCase ) # verify orig_size __a = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase ) ) # verify size __a = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase ) )
67
0
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device SCREAMING_SNAKE_CASE__:Any = False class UpperCamelCase ( unittest.TestCase ): pass @nightly @require_torch_gpu class UpperCamelCase ( unittest.TestCase ): def a__ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def a__ ( self ): __a = VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion" , torch_dtype=torch.floataa ) pipe.to(lowerCamelCase ) pipe.set_progress_bar_config(disable=lowerCamelCase ) __a = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) __a = torch.manual_seed(0 ) __a = pipe.dual_guided( prompt="first prompt" , image=lowerCamelCase , text_to_image_strength=0.75 , generator=lowerCamelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type="numpy" , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(lowerCamelCase ) __a = VersatileDiffusionPipeline.from_pretrained(lowerCamelCase , torch_dtype=torch.floataa ) pipe.to(lowerCamelCase ) pipe.set_progress_bar_config(disable=lowerCamelCase ) __a = generator.manual_seed(0 ) __a = pipe.dual_guided( prompt="first prompt" , image=lowerCamelCase , text_to_image_strength=0.75 , generator=lowerCamelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type="numpy" , ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def a__ ( self ): __a = VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion" , torch_dtype=torch.floataa ) pipe.to(lowerCamelCase ) pipe.set_progress_bar_config(disable=lowerCamelCase ) __a = "cyberpunk 2077" __a = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg" ) __a = torch.manual_seed(0 ) __a = pipe.dual_guided( prompt=lowerCamelCase , image=lowerCamelCase , text_to_image_strength=0.75 , generator=lowerCamelCase , guidance_scale=7.5 , num_inference_steps=50 , output_type="numpy" , ).images __a = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) __a = np.array([0.1448, 0.1619, 0.1741, 0.1086, 0.1147, 0.1128, 0.1199, 0.1165, 0.1001] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 __a = "A painting of a squirrel eating a burger " __a = torch.manual_seed(0 ) __a = pipe.text_to_image( prompt=lowerCamelCase , generator=lowerCamelCase , guidance_scale=7.5 , num_inference_steps=50 , output_type="numpy" ).images __a = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) __a = np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 __a = pipe.image_variation(lowerCamelCase , generator=lowerCamelCase , output_type="numpy" ).images __a = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) __a = np.array([0.3076, 0.3123, 0.3284, 0.3782, 0.3770, 0.3894, 0.4297, 0.4331, 0.4456] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
716
"""simple docstring""" import argparse import logging import sys from unittest.mock import patch import run_glue_deebert from transformers.testing_utils import TestCasePlus, get_gpu_count, require_torch_non_multi_gpu, slow logging.basicConfig(level=logging.DEBUG) SCREAMING_SNAKE_CASE__:Dict = logging.getLogger() def _lowerCamelCase( ): __a = argparse.ArgumentParser() parser.add_argument("-f" ) __a = parser.parse_args() return args.f class snake_case__ ( snake_case_ ): def a__ ( self ): __a = logging.StreamHandler(sys.stdout ) logger.addHandler(lowerCamelCase ) def a__ ( self , lowerCamelCase ): __a = get_gpu_count() if n_gpu > 1: pass # XXX: doesn't quite work with n_gpu > 1 https://github.com/huggingface/transformers/issues/10560 # script = f"{self.examples_dir_str}/research_projects/deebert/run_glue_deebert.py" # distributed_args = f"-m torch.distributed.launch --nproc_per_node={n_gpu} {script}".split() # cmd = [sys.executable] + distributed_args + args # execute_subprocess_async(cmd, env=self.get_env()) # XXX: test the results - need to save them first into .json file else: args.insert(0 , "run_glue_deebert.py" ) with patch.object(lowerCamelCase , "argv" , lowerCamelCase ): __a = run_glue_deebert.main() for value in result.values(): self.assertGreaterEqual(lowerCamelCase , 0.666 ) @slow @require_torch_non_multi_gpu def a__ ( self ): __a = "\n --model_type roberta\n --model_name_or_path roberta-base\n --task_name MRPC\n --do_train\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --max_seq_length 128\n --per_gpu_eval_batch_size=1\n --per_gpu_train_batch_size=8\n --learning_rate 2e-4\n --num_train_epochs 3\n --overwrite_output_dir\n --seed 42\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --save_steps 0\n --overwrite_cache\n --eval_after_first_stage\n ".split() self.run_and_check(lowerCamelCase ) __a = "\n --model_type roberta\n --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --task_name MRPC\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --max_seq_length 128\n --eval_each_highway\n --eval_highway\n --overwrite_cache\n --per_gpu_eval_batch_size=1\n ".split() self.run_and_check(lowerCamelCase ) __a = "\n --model_type roberta\n --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --task_name MRPC\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --max_seq_length 128\n --early_exit_entropy 0.1\n --eval_highway\n --overwrite_cache\n --per_gpu_eval_batch_size=1\n ".split() self.run_and_check(lowerCamelCase )
67
0
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import SegformerImageProcessor, SwinConfig, UperNetConfig, UperNetForSemanticSegmentation def _lowerCamelCase( a ): __a = 3_8_4 __a = 7 if "tiny" in model_name: __a = 9_6 __a = (2, 2, 6, 2) __a = (3, 6, 1_2, 2_4) elif "small" in model_name: __a = 9_6 __a = (2, 2, 1_8, 2) __a = (3, 6, 1_2, 2_4) elif "base" in model_name: __a = 1_2_8 __a = (2, 2, 1_8, 2) __a = (4, 8, 1_6, 3_2) __a = 1_2 __a = 5_1_2 elif "large" in model_name: __a = 1_9_2 __a = (2, 2, 1_8, 2) __a = (6, 1_2, 2_4, 4_8) __a = 1_2 __a = 7_6_8 # set label information __a = 1_5_0 __a = "huggingface/label-files" __a = "ade20k-id2label.json" __a = json.load(open(hf_hub_download(a , a , repo_type="dataset" ) , "r" ) ) __a = {int(a ): v for k, v in idalabel.items()} __a = {v: k for k, v in idalabel.items()} __a = SwinConfig( embed_dim=a , depths=a , num_heads=a , window_size=a , out_features=["stage1", "stage2", "stage3", "stage4"] , ) __a = UperNetConfig( backbone_config=a , auxiliary_in_channels=a , num_labels=a , idalabel=a , labelaid=a , ) return config def _lowerCamelCase( a ): __a = [] # fmt: off # stem rename_keys.append(("backbone.patch_embed.projection.weight", "backbone.embeddings.patch_embeddings.projection.weight") ) rename_keys.append(("backbone.patch_embed.projection.bias", "backbone.embeddings.patch_embeddings.projection.bias") ) rename_keys.append(("backbone.patch_embed.norm.weight", "backbone.embeddings.norm.weight") ) rename_keys.append(("backbone.patch_embed.norm.bias", "backbone.embeddings.norm.bias") ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((F"backbone.stages.{i}.blocks.{j}.norm1.weight", F"backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.weight") ) rename_keys.append((F"backbone.stages.{i}.blocks.{j}.norm1.bias", F"backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.bias") ) rename_keys.append((F"backbone.stages.{i}.blocks.{j}.attn.w_msa.relative_position_bias_table", F"backbone.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table") ) rename_keys.append((F"backbone.stages.{i}.blocks.{j}.attn.w_msa.relative_position_index", F"backbone.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index") ) rename_keys.append((F"backbone.stages.{i}.blocks.{j}.attn.w_msa.proj.weight", F"backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight") ) rename_keys.append((F"backbone.stages.{i}.blocks.{j}.attn.w_msa.proj.bias", F"backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias") ) rename_keys.append((F"backbone.stages.{i}.blocks.{j}.norm2.weight", F"backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.weight") ) rename_keys.append((F"backbone.stages.{i}.blocks.{j}.norm2.bias", F"backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.bias") ) rename_keys.append((F"backbone.stages.{i}.blocks.{j}.ffn.layers.0.0.weight", F"backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight") ) rename_keys.append((F"backbone.stages.{i}.blocks.{j}.ffn.layers.0.0.bias", F"backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias") ) rename_keys.append((F"backbone.stages.{i}.blocks.{j}.ffn.layers.1.weight", F"backbone.encoder.layers.{i}.blocks.{j}.output.dense.weight") ) rename_keys.append((F"backbone.stages.{i}.blocks.{j}.ffn.layers.1.bias", F"backbone.encoder.layers.{i}.blocks.{j}.output.dense.bias") ) if i < 3: rename_keys.append((F"backbone.stages.{i}.downsample.reduction.weight", F"backbone.encoder.layers.{i}.downsample.reduction.weight") ) rename_keys.append((F"backbone.stages.{i}.downsample.norm.weight", F"backbone.encoder.layers.{i}.downsample.norm.weight") ) rename_keys.append((F"backbone.stages.{i}.downsample.norm.bias", F"backbone.encoder.layers.{i}.downsample.norm.bias") ) rename_keys.append((F"backbone.norm{i}.weight", F"backbone.hidden_states_norms.stage{i+1}.weight") ) rename_keys.append((F"backbone.norm{i}.bias", F"backbone.hidden_states_norms.stage{i+1}.bias") ) # decode head rename_keys.extend( [ ("decode_head.conv_seg.weight", "decode_head.classifier.weight"), ("decode_head.conv_seg.bias", "decode_head.classifier.bias"), ("auxiliary_head.conv_seg.weight", "auxiliary_head.classifier.weight"), ("auxiliary_head.conv_seg.bias", "auxiliary_head.classifier.bias"), ] ) # fmt: on return rename_keys def _lowerCamelCase( a , a , a ): __a = dct.pop(a ) __a = val def _lowerCamelCase( a , a ): __a = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): __a = 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) __a = state_dict.pop(F"backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.weight" ) __a = state_dict.pop(F"backbone.stages.{i}.blocks.{j}.attn.w_msa.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict __a = in_proj_weight[:dim, :] __a = in_proj_bias[: dim] __a = in_proj_weight[ dim : dim * 2, : ] __a = in_proj_bias[ dim : dim * 2 ] __a = in_proj_weight[ -dim :, : ] __a = in_proj_bias[-dim :] # fmt: on def _lowerCamelCase( a ): __a , __a = x.shape __a = x.reshape(a , 4 , in_channel // 4 ) __a = x[:, [0, 2, 1, 3], :].transpose(1 , 2 ).reshape(a , a ) return x def _lowerCamelCase( a ): __a , __a = x.shape __a = x.reshape(a , in_channel // 4 , 4 ) __a = x[:, :, [0, 2, 1, 3]].transpose(1 , 2 ).reshape(a , a ) return x def _lowerCamelCase( a ): __a = x.shape[0] __a = x.reshape(4 , in_channel // 4 ) __a = x[[0, 2, 1, 3], :].transpose(0 , 1 ).reshape(a ) return x def _lowerCamelCase( a ): __a = x.shape[0] __a = x.reshape(in_channel // 4 , 4 ) __a = x[:, [0, 2, 1, 3]].transpose(0 , 1 ).reshape(a ) return x def _lowerCamelCase( a , a , a ): __a = { "upernet-swin-tiny": "https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K/upernet_swin_tiny_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K_20210531_112542-e380ad3e.pth", "upernet-swin-small": "https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_small_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K/upernet_swin_small_patch4_window7_512x512_160k_ade20k_pretrain_224x224_1K_20210526_192015-ee2fff1c.pth", "upernet-swin-base": "https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_base_patch4_window12_512x512_160k_ade20k_pretrain_384x384_22K/upernet_swin_base_patch4_window12_512x512_160k_ade20k_pretrain_384x384_22K_20210531_125459-429057bf.pth", "upernet-swin-large": "https://download.openmmlab.com/mmsegmentation/v0.5/swin/upernet_swin_large_patch4_window12_512x512_pretrain_384x384_22K_160k_ade20k/upernet_swin_large_patch4_window12_512x512_pretrain_384x384_22K_160k_ade20k_20220318_091743-9ba68901.pth", } __a = model_name_to_url[model_name] __a = torch.hub.load_state_dict_from_url(a , map_location="cpu" , file_name=a )[ "state_dict" ] for name, param in state_dict.items(): print(a , param.shape ) __a = get_upernet_config(a ) __a = UperNetForSemanticSegmentation(a ) model.eval() # replace "bn" => "batch_norm" for key in state_dict.copy().keys(): __a = state_dict.pop(a ) if "bn" in key: __a = key.replace("bn" , "batch_norm" ) __a = val # rename keys __a = create_rename_keys(a ) for src, dest in rename_keys: rename_key(a , a , a ) read_in_q_k_v(a , config.backbone_config ) # fix downsample parameters for key, value in state_dict.items(): if "downsample" in key: if "reduction" in key: __a = reverse_correct_unfold_reduction_order(a ) if "norm" in key: __a = reverse_correct_unfold_norm_order(a ) model.load_state_dict(a ) # verify on image __a = "https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg" __a = Image.open(requests.get(a , stream=a ).raw ).convert("RGB" ) __a = SegformerImageProcessor() __a = processor(a , return_tensors="pt" ).pixel_values with torch.no_grad(): __a = model(a ) __a = outputs.logits print(logits.shape ) print("First values of logits:" , logits[0, 0, :3, :3] ) # assert values if model_name == "upernet-swin-tiny": __a = torch.tensor( [[-7.59_58, -7.59_58, -7.43_02], [-7.59_58, -7.59_58, -7.43_02], [-7.47_97, -7.47_97, -7.30_68]] ) elif model_name == "upernet-swin-small": __a = torch.tensor( [[-7.19_21, -7.19_21, -6.95_32], [-7.19_21, -7.19_21, -6.95_32], [-7.09_08, -7.09_08, -6.85_34]] ) elif model_name == "upernet-swin-base": __a = torch.tensor( [[-6.58_51, -6.58_51, -6.43_30], [-6.58_51, -6.58_51, -6.43_30], [-6.47_63, -6.47_63, -6.32_54]] ) elif model_name == "upernet-swin-large": __a = torch.tensor( [[-7.52_97, -7.52_97, -7.38_02], [-7.52_97, -7.52_97, -7.38_02], [-7.40_44, -7.40_44, -7.25_86]] ) print("Logits:" , outputs.logits[0, 0, :3, :3] ) assert torch.allclose(outputs.logits[0, 0, :3, :3] , a , atol=1E-4 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: print(F"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(a ) print(F"Saving processor to {pytorch_dump_folder_path}" ) processor.save_pretrained(a ) if push_to_hub: print(F"Pushing model and processor for {model_name} to hub" ) model.push_to_hub(F"openmmlab/{model_name}" ) processor.push_to_hub(F"openmmlab/{model_name}" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__:Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--model_name""", default="""upernet-swin-tiny""", type=str, choices=[F'''upernet-swin-{size}''' for size in ["""tiny""", """small""", """base""", """large"""]], help="""Name of the Swin + UperNet model you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory.""" ) parser.add_argument( """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub.""" ) SCREAMING_SNAKE_CASE__:List[Any] = parser.parse_args() convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
717
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, 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 SCREAMING_SNAKE_CASE__:Union[str, Any] = logging.get_logger(__name__) if is_vision_available(): import PIL class snake_case__ ( snake_case_ ): _snake_case : Optional[Any] = ["""pixel_values"""] def __init__( self , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = PILImageResampling.BICUBIC , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = True , lowerCamelCase = 1 / 255 , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = True , **lowerCamelCase , ): super().__init__(**lowerCamelCase ) __a = size if size is not None else {"shortest_edge": 224} __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) __a = crop_size if crop_size is not None else {"height": 224, "width": 224} __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase , param_name="crop_size" ) __a = do_resize __a = size __a = resample __a = do_center_crop __a = crop_size __a = do_rescale __a = rescale_factor __a = do_normalize __a = image_mean if image_mean is not None else OPENAI_CLIP_MEAN __a = image_std if image_std is not None else OPENAI_CLIP_STD __a = do_convert_rgb def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = PILImageResampling.BICUBIC , lowerCamelCase = None , **lowerCamelCase , ): __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) if "shortest_edge" not in size: raise ValueError(F"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}" ) __a = get_resize_output_image_size(lowerCamelCase , size=size["shortest_edge"] , default_to_square=lowerCamelCase ) return resize(lowerCamelCase , size=lowerCamelCase , resample=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): __a = get_size_dict(lowerCamelCase ) 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(lowerCamelCase , size=(size["height"], size["width"]) , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): return rescale(lowerCamelCase , scale=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): return normalize(lowerCamelCase , mean=lowerCamelCase , std=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = ChannelDimension.FIRST , **lowerCamelCase , ): __a = do_resize if do_resize is not None else self.do_resize __a = size if size is not None else self.size __a = get_size_dict(lowerCamelCase , param_name="size" , default_to_square=lowerCamelCase ) __a = resample if resample is not None else self.resample __a = do_center_crop if do_center_crop is not None else self.do_center_crop __a = crop_size if crop_size is not None else self.crop_size __a = get_size_dict(lowerCamelCase , param_name="crop_size" , default_to_square=lowerCamelCase ) __a = do_rescale if do_rescale is not None else self.do_rescale __a = rescale_factor if rescale_factor is not None else self.rescale_factor __a = do_normalize if do_normalize is not None else self.do_normalize __a = image_mean if image_mean is not None else self.image_mean __a = image_std if image_std is not None else self.image_std __a = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __a = make_list_of_images(lowerCamelCase ) if not valid_images(lowerCamelCase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) 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: __a = [convert_to_rgb(lowerCamelCase ) for image in images] # All transformations expect numpy arrays. __a = [to_numpy_array(lowerCamelCase ) for image in images] if do_resize: __a = [self.resize(image=lowerCamelCase , size=lowerCamelCase , resample=lowerCamelCase ) for image in images] if do_center_crop: __a = [self.center_crop(image=lowerCamelCase , size=lowerCamelCase ) for image in images] if do_rescale: __a = [self.rescale(image=lowerCamelCase , scale=lowerCamelCase ) for image in images] if do_normalize: __a = [self.normalize(image=lowerCamelCase , mean=lowerCamelCase , std=lowerCamelCase ) for image in images] __a = [to_channel_dimension_format(lowerCamelCase , lowerCamelCase ) for image in images] __a = {"pixel_values": images} return BatchFeature(data=lowerCamelCase , tensor_type=lowerCamelCase )
67
0
from __future__ import annotations import math def _lowerCamelCase( a ): if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(a ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def _lowerCamelCase( a ): __a = str(a ) __a = [n] for i in range(1 , len(a ) ): list_nums.append(int(str_num[i:] ) ) list_nums.append(int(str_num[:-i] ) ) return list_nums def _lowerCamelCase( a ): if len(str(a ) ) > 3: if not is_prime(int(str(a )[-3:] ) ) or not is_prime(int(str(a )[:3] ) ): return False return True def _lowerCamelCase( a = 1_1 ): __a = [] __a = 1_3 while len(a ) != count: if validate(a ): __a = list_truncated_nums(a ) if all(is_prime(a ) for i in list_nums ): list_truncated_primes.append(a ) num += 2 return list_truncated_primes def _lowerCamelCase( ): return sum(compute_truncated_primes(1_1 ) ) if __name__ == "__main__": print(F'''{sum(compute_truncated_primes(11)) = }''')
718
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation SCREAMING_SNAKE_CASE__:List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Any = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} SCREAMING_SNAKE_CASE__:Optional[Any] = { """vocab_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/vocab.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/vocab.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/vocab.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/vocab.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/vocab.json""", }, """merges_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/merges.txt""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/merges.txt""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/merges.txt""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/merges.txt""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/merges.txt""", }, """tokenizer_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/tokenizer.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/tokenizer.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/tokenizer.json""", }, } SCREAMING_SNAKE_CASE__:Union[str, Any] = { """gpt2""": 1024, """gpt2-medium""": 1024, """gpt2-large""": 1024, """gpt2-xl""": 1024, """distilgpt2""": 1024, } class snake_case__ ( snake_case_ ): _snake_case : Tuple = VOCAB_FILES_NAMES _snake_case : str = PRETRAINED_VOCAB_FILES_MAP _snake_case : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _snake_case : List[str] = ["""input_ids""", """attention_mask"""] _snake_case : Dict = GPTaTokenizer def __init__( self , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase="<|endoftext|>" , lowerCamelCase="<|endoftext|>" , lowerCamelCase="<|endoftext|>" , lowerCamelCase=False , **lowerCamelCase , ): super().__init__( lowerCamelCase , lowerCamelCase , tokenizer_file=lowerCamelCase , unk_token=lowerCamelCase , bos_token=lowerCamelCase , eos_token=lowerCamelCase , add_prefix_space=lowerCamelCase , **lowerCamelCase , ) __a = kwargs.pop("add_bos_token" , lowerCamelCase ) __a = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , lowerCamelCase ) != add_prefix_space: __a = getattr(lowerCamelCase , pre_tok_state.pop("type" ) ) __a = add_prefix_space __a = pre_tok_class(**lowerCamelCase ) __a = add_prefix_space def a__ ( self , *lowerCamelCase , **lowerCamelCase ): __a = kwargs.get("is_split_into_words" , lowerCamelCase ) assert self.add_prefix_space or not is_split_into_words, ( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*lowerCamelCase , **lowerCamelCase ) def a__ ( self , *lowerCamelCase , **lowerCamelCase ): __a = kwargs.get("is_split_into_words" , lowerCamelCase ) assert self.add_prefix_space or not is_split_into_words, ( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._encode_plus(*lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase = None ): __a = self._tokenizer.model.save(lowerCamelCase , name=lowerCamelCase ) return tuple(lowerCamelCase ) def a__ ( self , lowerCamelCase ): __a = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowerCamelCase , add_special_tokens=lowerCamelCase ) + [self.eos_token_id] ) if len(lowerCamelCase ) > self.model_max_length: __a = input_ids[-self.model_max_length :] return input_ids
67
0
class snake_case__ : def __init__( self ): __a = 0 __a = 0 __a = {} def a__ ( self , lowerCamelCase ): if vertex not in self.adjacency: __a = {} self.num_vertices += 1 def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): self.add_vertex(lowerCamelCase ) self.add_vertex(lowerCamelCase ) if head == tail: return __a = weight __a = weight def a__ ( self ): __a = self.get_edges() for edge in edges: __a , __a , __a = edge edges.remove((tail, head, weight) ) for i in range(len(lowerCamelCase ) ): __a = list(edges[i] ) edges.sort(key=lambda lowerCamelCase : e[2] ) for i in range(len(lowerCamelCase ) - 1 ): if edges[i][2] >= edges[i + 1][2]: __a = edges[i][2] + 1 for edge in edges: __a , __a , __a = edge __a = weight __a = weight def __str__( self ): __a = "" for tail in self.adjacency: for head in self.adjacency[tail]: __a = self.adjacency[head][tail] string += F"{head} -> {tail} == {weight}\n" return string.rstrip("\n" ) def a__ ( self ): __a = [] for tail in self.adjacency: for head in self.adjacency[tail]: output.append((tail, head, self.adjacency[head][tail]) ) return output def a__ ( self ): return self.adjacency.keys() @staticmethod def a__ ( lowerCamelCase=None , lowerCamelCase=None ): __a = Graph() if vertices is None: __a = [] if edges is None: __a = [] for vertex in vertices: g.add_vertex(lowerCamelCase ) for edge in edges: g.add_edge(*lowerCamelCase ) return g class snake_case__ : def __init__( self ): __a = {} __a = {} def __len__( self ): return len(self.parent ) def a__ ( self , lowerCamelCase ): if item in self.parent: return self.find(lowerCamelCase ) __a = item __a = 0 return item def a__ ( self , lowerCamelCase ): if item not in self.parent: return self.make_set(lowerCamelCase ) if item != self.parent[item]: __a = self.find(self.parent[item] ) return self.parent[item] def a__ ( self , lowerCamelCase , lowerCamelCase ): __a = self.find(lowerCamelCase ) __a = self.find(lowerCamelCase ) if roota == roota: return roota if self.rank[roota] > self.rank[roota]: __a = roota return roota if self.rank[roota] < self.rank[roota]: __a = roota return roota if self.rank[roota] == self.rank[roota]: self.rank[roota] += 1 __a = roota return roota return None @staticmethod def a__ ( lowerCamelCase ): __a = graph.num_vertices __a = Graph.UnionFind() __a = [] while num_components > 1: __a = {} for vertex in graph.get_vertices(): __a = -1 __a = graph.get_edges() for edge in edges: __a , __a , __a = edge edges.remove((tail, head, weight) ) for edge in edges: __a , __a , __a = edge __a = union_find.find(lowerCamelCase ) __a = union_find.find(lowerCamelCase ) if seta != seta: if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: __a = [head, tail, weight] if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight: __a = [head, tail, weight] for vertex in cheap_edge: if cheap_edge[vertex] != -1: __a , __a , __a = cheap_edge[vertex] if union_find.find(lowerCamelCase ) != union_find.find(lowerCamelCase ): union_find.union(lowerCamelCase , lowerCamelCase ) mst_edges.append(cheap_edge[vertex] ) __a = num_components - 1 __a = Graph.build(edges=lowerCamelCase ) return mst
719
"""simple docstring""" from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize("repo_id" , ["canonical_dataset_name", "org-name/dataset-name"] ) @pytest.mark.parametrize("path" , ["filename.csv", "filename with blanks.csv"] ) @pytest.mark.parametrize("revision" , [None, "v2"] ) def _lowerCamelCase( a , a , a ): __a = hf_hub_url(repo_id=a , path=a , revision=a ) assert url == F"https://huggingface.co/datasets/{repo_id}/resolve/{revision or 'main'}/{quote(a )}"
67
0
"""simple docstring""" def _lowerCamelCase( a ): if divisor % 5 == 0 or divisor % 2 == 0: return 0 __a = 1 __a = 1 while repunit: __a = (1_0 * repunit + 1) % divisor repunit_index += 1 return repunit_index def _lowerCamelCase( a = 1_0_0_0_0_0_0 ): __a = limit - 1 if divisor % 2 == 0: divisor += 1 while least_divisible_repunit(a ) <= limit: divisor += 2 return divisor if __name__ == "__main__": print(F'''{solution() = }''')
720
"""simple docstring""" from __future__ import annotations def _lowerCamelCase( a , a , a ): if len(a ) == 0: raise ValueError("find_max() arg is an empty sequence" ) if ( left >= len(a ) or left < -len(a ) or right >= len(a ) or right < -len(a ) ): raise IndexError("list index out of range" ) if left == right: return nums[left] __a = (left + right) >> 1 # the middle __a = find_max(a , a , a ) # find max in range[left, mid] __a = find_max(a , mid + 1 , a ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
67
0
"""simple docstring""" SCREAMING_SNAKE_CASE__:List[Any] = {str(digit): digit**5 for digit in range(10)} def _lowerCamelCase( a ): return sum(DIGITS_FIFTH_POWER[digit] for digit in str(a ) ) def _lowerCamelCase( ): return sum( number for number in range(1_0_0_0 , 1_0_0_0_0_0_0 ) if number == digits_fifth_powers_sum(a ) ) if __name__ == "__main__": print(solution())
721
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__:List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Tuple = { """google/bigbird-roberta-base""": """https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json""", """google/bigbird-roberta-large""": """https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json""", """google/bigbird-base-trivia-itc""": """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json""", # See all BigBird models at https://huggingface.co/models?filter=big_bird } class snake_case__ ( snake_case_ ): _snake_case : Any = """big_bird""" def __init__( self , lowerCamelCase=50358 , lowerCamelCase=768 , lowerCamelCase=12 , lowerCamelCase=12 , lowerCamelCase=3072 , lowerCamelCase="gelu_new" , lowerCamelCase=0.1 , lowerCamelCase=0.1 , lowerCamelCase=4096 , lowerCamelCase=2 , lowerCamelCase=0.02 , lowerCamelCase=1E-12 , lowerCamelCase=True , lowerCamelCase=0 , lowerCamelCase=1 , lowerCamelCase=2 , lowerCamelCase=66 , lowerCamelCase="block_sparse" , lowerCamelCase=True , lowerCamelCase=False , lowerCamelCase=64 , lowerCamelCase=3 , lowerCamelCase=None , **lowerCamelCase , ): super().__init__( pad_token_id=lowerCamelCase , bos_token_id=lowerCamelCase , eos_token_id=lowerCamelCase , sep_token_id=lowerCamelCase , **lowerCamelCase , ) __a = vocab_size __a = max_position_embeddings __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 = initializer_range __a = type_vocab_size __a = layer_norm_eps __a = use_cache __a = rescale_embeddings __a = attention_type __a = use_bias __a = block_size __a = num_random_blocks __a = classifier_dropout class snake_case__ ( snake_case_ ): @property def a__ ( self ): 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), ] )
67
0
"""simple docstring""" def _lowerCamelCase( a , a ): __a = len(a ) __a = [] for i in range(len(a ) - pat_len + 1 ): __a = True for j in range(a ): if s[i + j] != pattern[j]: __a = False break if match_found: position.append(a ) return position if __name__ == "__main__": assert naive_pattern_search("""ABCDEFG""", """DE""") == [3] print(naive_pattern_search("""ABAAABCDBBABCDDEBCABC""", """ABC"""))
700
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation SCREAMING_SNAKE_CASE__:Optional[int] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Optional[int] = {"""tokenizer_file""": """tokenizer.json"""} SCREAMING_SNAKE_CASE__:Tuple = { """tokenizer_file""": { """bigscience/tokenizer""": """https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json""", """bigscience/bloom-560m""": """https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json""", """bigscience/bloom-1b1""": """https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json""", """bigscience/bloom-1b7""": """https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json""", """bigscience/bloom-3b""": """https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json""", """bigscience/bloom-7b1""": """https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json""", """bigscience/bloom""": """https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json""", }, } class snake_case__ ( snake_case_ ): _snake_case : Optional[Any] = VOCAB_FILES_NAMES _snake_case : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP _snake_case : Optional[int] = ["""input_ids""", """attention_mask"""] _snake_case : Optional[int] = None def __init__( self , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase="<unk>" , lowerCamelCase="<s>" , lowerCamelCase="</s>" , lowerCamelCase="<pad>" , lowerCamelCase=False , lowerCamelCase=False , **lowerCamelCase , ): super().__init__( lowerCamelCase , lowerCamelCase , tokenizer_file=lowerCamelCase , unk_token=lowerCamelCase , bos_token=lowerCamelCase , eos_token=lowerCamelCase , pad_token=lowerCamelCase , add_prefix_space=lowerCamelCase , clean_up_tokenization_spaces=lowerCamelCase , **lowerCamelCase , ) __a = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , lowerCamelCase ) != add_prefix_space: __a = getattr(lowerCamelCase , pre_tok_state.pop("type" ) ) __a = add_prefix_space __a = pre_tok_class(**lowerCamelCase ) __a = add_prefix_space def a__ ( self , *lowerCamelCase , **lowerCamelCase ): __a = kwargs.get("is_split_into_words" , lowerCamelCase ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with" " pretokenized inputs." ) return super()._batch_encode_plus(*lowerCamelCase , **lowerCamelCase ) def a__ ( self , *lowerCamelCase , **lowerCamelCase ): __a = kwargs.get("is_split_into_words" , lowerCamelCase ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with" " pretokenized inputs." ) return super()._encode_plus(*lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase = None ): __a = self._tokenizer.model.save(lowerCamelCase , name=lowerCamelCase ) return tuple(lowerCamelCase ) def a__ ( self , lowerCamelCase ): __a = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowerCamelCase , add_special_tokens=lowerCamelCase ) + [self.eos_token_id] ) if len(lowerCamelCase ) > self.model_max_length: __a = input_ids[-self.model_max_length :] return input_ids
67
0
"""simple docstring""" import contextlib import copy import random from typing import Any, Dict, Iterable, Optional, Union import numpy as np import torch from .utils import deprecate, is_transformers_available if is_transformers_available(): import transformers def _lowerCamelCase( a ): random.seed(a ) np.random.seed(a ) torch.manual_seed(a ) torch.cuda.manual_seed_all(a ) # ^^ safe to call this function even if cuda is not available class snake_case__ : def __init__( self , lowerCamelCase , lowerCamelCase = 0.9999 , lowerCamelCase = 0.0 , lowerCamelCase = 0 , lowerCamelCase = False , lowerCamelCase = 1.0 , lowerCamelCase = 2 / 3 , lowerCamelCase = None , lowerCamelCase = None , **lowerCamelCase , ): if isinstance(lowerCamelCase , torch.nn.Module ): __a = ( "Passing a `torch.nn.Module` to `ExponentialMovingAverage` is deprecated. " "Please pass the parameters of the module instead." ) deprecate( "passing a `torch.nn.Module` to `ExponentialMovingAverage`" , "1.0.0" , lowerCamelCase , standard_warn=lowerCamelCase , ) __a = parameters.parameters() # set use_ema_warmup to True if a torch.nn.Module is passed for backwards compatibility __a = True if kwargs.get("max_value" , lowerCamelCase ) is not None: __a = "The `max_value` argument is deprecated. Please use `decay` instead." deprecate("max_value" , "1.0.0" , lowerCamelCase , standard_warn=lowerCamelCase ) __a = kwargs["max_value"] if kwargs.get("min_value" , lowerCamelCase ) is not None: __a = "The `min_value` argument is deprecated. Please use `min_decay` instead." deprecate("min_value" , "1.0.0" , lowerCamelCase , standard_warn=lowerCamelCase ) __a = kwargs["min_value"] __a = list(lowerCamelCase ) __a = [p.clone().detach() for p in parameters] if kwargs.get("device" , lowerCamelCase ) is not None: __a = "The `device` argument is deprecated. Please use `to` instead." deprecate("device" , "1.0.0" , lowerCamelCase , standard_warn=lowerCamelCase ) self.to(device=kwargs["device"] ) __a = None __a = decay __a = min_decay __a = update_after_step __a = use_ema_warmup __a = inv_gamma __a = power __a = 0 __a = None # set in `step()` __a = model_cls __a = model_config @classmethod def a__ ( cls , lowerCamelCase , lowerCamelCase ): __a , __a = model_cls.load_config(lowerCamelCase , return_unused_kwargs=lowerCamelCase ) __a = model_cls.from_pretrained(lowerCamelCase ) __a = cls(model.parameters() , model_cls=lowerCamelCase , model_config=model.config ) ema_model.load_state_dict(lowerCamelCase ) return ema_model def a__ ( self , lowerCamelCase ): if self.model_cls is None: raise ValueError("`save_pretrained` can only be used if `model_cls` was defined at __init__." ) if self.model_config is None: raise ValueError("`save_pretrained` can only be used if `model_config` was defined at __init__." ) __a = self.model_cls.from_config(self.model_config ) __a = self.state_dict() state_dict.pop("shadow_params" , lowerCamelCase ) model.register_to_config(**lowerCamelCase ) self.copy_to(model.parameters() ) model.save_pretrained(lowerCamelCase ) def a__ ( self , lowerCamelCase ): __a = max(0 , optimization_step - self.update_after_step - 1 ) if step <= 0: return 0.0 if self.use_ema_warmup: __a = 1 - (1 + step / self.inv_gamma) ** -self.power else: __a = (1 + step) / (10 + step) __a = min(lowerCamelCase , self.decay ) # make sure decay is not smaller than min_decay __a = max(lowerCamelCase , self.min_decay ) return cur_decay_value @torch.no_grad() def a__ ( self , lowerCamelCase ): if isinstance(lowerCamelCase , torch.nn.Module ): __a = ( "Passing a `torch.nn.Module` to `ExponentialMovingAverage.step` is deprecated. " "Please pass the parameters of the module instead." ) deprecate( "passing a `torch.nn.Module` to `ExponentialMovingAverage.step`" , "1.0.0" , lowerCamelCase , standard_warn=lowerCamelCase , ) __a = parameters.parameters() __a = list(lowerCamelCase ) self.optimization_step += 1 # Compute the decay factor for the exponential moving average. __a = self.get_decay(self.optimization_step ) __a = decay __a = 1 - decay __a = contextlib.nullcontext if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled(): import deepspeed for s_param, param in zip(self.shadow_params , lowerCamelCase ): if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled(): __a = deepspeed.zero.GatheredParameters(lowerCamelCase , modifier_rank=lowerCamelCase ) with context_manager(): if param.requires_grad: s_param.sub_(one_minus_decay * (s_param - param) ) else: s_param.copy_(lowerCamelCase ) def a__ ( self , lowerCamelCase ): __a = list(lowerCamelCase ) for s_param, param in zip(self.shadow_params , lowerCamelCase ): param.data.copy_(s_param.to(param.device ).data ) def a__ ( self , lowerCamelCase=None , lowerCamelCase=None ): __a = [ p.to(device=lowerCamelCase , dtype=lowerCamelCase ) if p.is_floating_point() else p.to(device=lowerCamelCase ) for p in self.shadow_params ] def a__ ( self ): return { "decay": self.decay, "min_decay": self.min_decay, "optimization_step": self.optimization_step, "update_after_step": self.update_after_step, "use_ema_warmup": self.use_ema_warmup, "inv_gamma": self.inv_gamma, "power": self.power, "shadow_params": self.shadow_params, } def a__ ( self , lowerCamelCase ): __a = [param.detach().cpu().clone() for param in parameters] def a__ ( self , lowerCamelCase ): if self.temp_stored_params is None: raise RuntimeError("This ExponentialMovingAverage has no `store()`ed weights " "to `restore()`" ) for c_param, param in zip(self.temp_stored_params , lowerCamelCase ): param.data.copy_(c_param.data ) # Better memory-wise. __a = None def a__ ( self , lowerCamelCase ): __a = copy.deepcopy(lowerCamelCase ) __a = state_dict.get("decay" , self.decay ) if self.decay < 0.0 or self.decay > 1.0: raise ValueError("Decay must be between 0 and 1" ) __a = state_dict.get("min_decay" , self.min_decay ) if not isinstance(self.min_decay , lowerCamelCase ): raise ValueError("Invalid min_decay" ) __a = state_dict.get("optimization_step" , self.optimization_step ) if not isinstance(self.optimization_step , lowerCamelCase ): raise ValueError("Invalid optimization_step" ) __a = state_dict.get("update_after_step" , self.update_after_step ) if not isinstance(self.update_after_step , lowerCamelCase ): raise ValueError("Invalid update_after_step" ) __a = state_dict.get("use_ema_warmup" , self.use_ema_warmup ) if not isinstance(self.use_ema_warmup , lowerCamelCase ): raise ValueError("Invalid use_ema_warmup" ) __a = state_dict.get("inv_gamma" , self.inv_gamma ) if not isinstance(self.inv_gamma , (float, int) ): raise ValueError("Invalid inv_gamma" ) __a = state_dict.get("power" , self.power ) if not isinstance(self.power , (float, int) ): raise ValueError("Invalid power" ) __a = state_dict.get("shadow_params" , lowerCamelCase ) if shadow_params is not None: __a = shadow_params if not isinstance(self.shadow_params , lowerCamelCase ): raise ValueError("shadow_params must be a list" ) if not all(isinstance(lowerCamelCase , torch.Tensor ) for p in self.shadow_params ): raise ValueError("shadow_params must all be Tensors" )
701
"""simple docstring""" from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class snake_case__ : _snake_case : torch.Tensor # [batch_size x 3] _snake_case : torch.Tensor # [batch_size x 3] _snake_case : torch.Tensor # [batch_size x 3] _snake_case : torch.Tensor # [batch_size x 3] _snake_case : int _snake_case : int _snake_case : float _snake_case : float _snake_case : Tuple[int] def a__ ( self ): assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def a__ ( self ): return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def a__ ( self ): return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def a__ ( self ): __a = torch.arange(self.height * self.width ) __a = torch.stack( [ pixel_indices % self.width, torch.div(lowerCamelCase , self.width , rounding_mode="trunc" ), ] , axis=1 , ) return coords @property def a__ ( self ): __a , *__a = self.shape __a = int(np.prod(lowerCamelCase ) ) __a = self.get_image_coords() __a = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) __a = self.get_camera_rays(lowerCamelCase ) __a = rays.view(lowerCamelCase , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def a__ ( self , lowerCamelCase ): __a , *__a , __a = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] __a = coords.view(lowerCamelCase , -1 , 2 ) __a = self.resolution() __a = self.fov() __a = (flat.float() / (res - 1)) * 2 - 1 __a = fracs * torch.tan(fov / 2 ) __a = fracs.view(lowerCamelCase , -1 , 2 ) __a = ( self.z.view(lowerCamelCase , 1 , 3 ) + self.x.view(lowerCamelCase , 1 , 3 ) * fracs[:, :, :1] + self.y.view(lowerCamelCase , 1 , 3 ) * fracs[:, :, 1:] ) __a = directions / directions.norm(dim=-1 , keepdim=lowerCamelCase ) __a = torch.stack( [ torch.broadcast_to(self.origin.view(lowerCamelCase , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(lowerCamelCase , *lowerCamelCase , 2 , 3 ) def a__ ( self , lowerCamelCase , lowerCamelCase ): assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=lowerCamelCase , height=lowerCamelCase , x_fov=self.x_fov , y_fov=self.y_fov , ) def _lowerCamelCase( a ): __a = [] __a = [] __a = [] __a = [] for theta in np.linspace(0 , 2 * np.pi , num=2_0 ): __a = np.array([np.sin(a ), np.cos(a ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) __a = -z * 4 __a = np.array([np.cos(a ), -np.sin(a ), 0.0] ) __a = np.cross(a , a ) origins.append(a ) xs.append(a ) ys.append(a ) zs.append(a ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(a , axis=0 ) ).float() , x=torch.from_numpy(np.stack(a , axis=0 ) ).float() , y=torch.from_numpy(np.stack(a , axis=0 ) ).float() , z=torch.from_numpy(np.stack(a , axis=0 ) ).float() , width=a , height=a , x_fov=0.7 , y_fov=0.7 , shape=(1, len(a )) , )
67
0
"""simple docstring""" def _lowerCamelCase( a = 1_0_0 ): __a = n * (n + 1) * (2 * n + 1) / 6 __a = (n * (n + 1) / 2) ** 2 return int(square_of_sum - sum_of_squares ) if __name__ == "__main__": print(F'''{solution() = }''')
702
"""simple docstring""" def _lowerCamelCase( a ): return 1 if digit in (0, 1) else (digit * factorial(digit - 1 )) def _lowerCamelCase( a ): __a = 0 __a = number while duplicate > 0: __a , __a = divmod(a , 1_0 ) fact_sum += factorial(a ) return fact_sum == number if __name__ == "__main__": print("""Program to check whether a number is a Krisnamurthy Number or not.""") SCREAMING_SNAKE_CASE__:Optional[Any] = int(input("""Enter number: """).strip()) print( F'''{number} is {'' if krishnamurthy(number) else 'not '}a Krishnamurthy Number.''' )
67
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig SCREAMING_SNAKE_CASE__:List[Any] = { """albert-base-v1""": """https://huggingface.co/albert-base-v1/resolve/main/config.json""", """albert-large-v1""": """https://huggingface.co/albert-large-v1/resolve/main/config.json""", """albert-xlarge-v1""": """https://huggingface.co/albert-xlarge-v1/resolve/main/config.json""", """albert-xxlarge-v1""": """https://huggingface.co/albert-xxlarge-v1/resolve/main/config.json""", """albert-base-v2""": """https://huggingface.co/albert-base-v2/resolve/main/config.json""", """albert-large-v2""": """https://huggingface.co/albert-large-v2/resolve/main/config.json""", """albert-xlarge-v2""": """https://huggingface.co/albert-xlarge-v2/resolve/main/config.json""", """albert-xxlarge-v2""": """https://huggingface.co/albert-xxlarge-v2/resolve/main/config.json""", } class snake_case__ ( snake_case_ ): _snake_case : Dict = """albert""" def __init__( self , lowerCamelCase=30000 , lowerCamelCase=128 , lowerCamelCase=4096 , lowerCamelCase=12 , lowerCamelCase=1 , lowerCamelCase=64 , lowerCamelCase=16384 , lowerCamelCase=1 , lowerCamelCase="gelu_new" , lowerCamelCase=0 , lowerCamelCase=0 , lowerCamelCase=512 , lowerCamelCase=2 , lowerCamelCase=0.02 , lowerCamelCase=1E-12 , lowerCamelCase=0.1 , lowerCamelCase="absolute" , lowerCamelCase=0 , lowerCamelCase=2 , lowerCamelCase=3 , **lowerCamelCase , ): super().__init__(pad_token_id=lowerCamelCase , bos_token_id=lowerCamelCase , eos_token_id=lowerCamelCase , **lowerCamelCase ) __a = vocab_size __a = embedding_size __a = hidden_size __a = num_hidden_layers __a = num_hidden_groups __a = num_attention_heads __a = inner_group_num __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 = classifier_dropout_prob __a = position_embedding_type class snake_case__ ( snake_case_ ): @property def a__ ( self ): if self.task == "multiple-choice": __a = {0: "batch", 1: "choice", 2: "sequence"} else: __a = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ("token_type_ids", dynamic_axis), ] )
703
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_torch_available, ) SCREAMING_SNAKE_CASE__:Optional[Any] = { """configuration_gpt_bigcode""": ["""GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTBigCodeConfig"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__:Union[str, Any] = [ """GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST""", """GPTBigCodeForSequenceClassification""", """GPTBigCodeForTokenClassification""", """GPTBigCodeForCausalLM""", """GPTBigCodeModel""", """GPTBigCodePreTrainedModel""", ] if TYPE_CHECKING: from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_bigcode import ( GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTBigCodeForCausalLM, GPTBigCodeForSequenceClassification, GPTBigCodeForTokenClassification, GPTBigCodeModel, GPTBigCodePreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__:List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
67
0
"""simple docstring""" import heapq import sys import numpy as np SCREAMING_SNAKE_CASE__:Optional[int] = tuple[int, int] class snake_case__ : def __init__( self ): __a = [] __a = set() def a__ ( self ): if not self.empty(): return self.elements[0][0] else: return float("inf" ) def a__ ( self ): return len(self.elements ) == 0 def a__ ( self , lowerCamelCase , lowerCamelCase ): if item not in self.set: heapq.heappush(self.elements , (priority, item) ) self.set.add(lowerCamelCase ) else: # update # print("update", item) __a = [] ((__a) , (__a)) = heapq.heappop(self.elements ) while x != item: temp.append((pri, x) ) ((__a) , (__a)) = heapq.heappop(self.elements ) temp.append((priority, item) ) for pro, xxx in temp: heapq.heappush(self.elements , (pro, xxx) ) def a__ ( self , lowerCamelCase ): if item in self.set: self.set.remove(lowerCamelCase ) __a = [] ((__a) , (__a)) = heapq.heappop(self.elements ) while x != item: temp.append((pro, x) ) ((__a) , (__a)) = heapq.heappop(self.elements ) for prito, yyy in temp: heapq.heappush(self.elements , (prito, yyy) ) def a__ ( self ): return self.elements[0][1] def a__ ( self ): ((__a) , (__a)) = heapq.heappop(self.elements ) self.set.remove(lowerCamelCase ) return (priority, item) def _lowerCamelCase( a , a ): # euclidean distance __a = np.array(a ) __a = np.array(a ) return np.linalg.norm(a - b ) def _lowerCamelCase( a , a ): # integer division by time variable return consistent_heuristic(a , a ) // t def _lowerCamelCase( a , a ): # manhattan distance return abs(p[0] - goal[0] ) + abs(p[1] - goal[1] ) def _lowerCamelCase( a , a , a , a ): __a = g_function[start] + Wa * heuristics[i](a , a ) return ans def _lowerCamelCase( a , a , a ): __a = np.chararray((n, n) ) for i in range(a ): for j in range(a ): __a = "*" for i in range(a ): for j in range(a ): if (j, (n - 1) - i) in blocks: __a = "#" __a = "-" __a = back_pointer[goal] while x != start: ((__a) , (__a)) = x # print(x) __a = "-" __a = back_pointer[x] __a = "-" for i in range(a ): for j in range(a ): if (i, j) == (0, n - 1): print(grid[i][j] , end=" " ) print("<-- End position" , end=" " ) else: print(grid[i][j] , end=" " ) print() print("^" ) print("Start position" ) print() print("# is an obstacle" ) print("- is the path taken by algorithm" ) print("PATH TAKEN BY THE ALGORITHM IS:-" ) __a = back_pointer[goal] while x != start: print(a , end=" " ) __a = back_pointer[x] print(a ) sys.exit() def _lowerCamelCase( a ): if p[0] < 0 or p[0] > n - 1: return False if p[1] < 0 or p[1] > n - 1: return False return True def _lowerCamelCase( a , a , a , a , a , a , a , a , ): for itera in range(a ): open_list[itera].remove_element(a ) # print("s", s) # print("j", j) ((__a) , (__a)) = s __a = (x - 1, y) __a = (x + 1, y) __a = (x, y + 1) __a = (x, y - 1) for neighbours in [left, right, up, down]: if neighbours not in blocks: if valid(a ) and neighbours not in visited: # print("neighbour", neighbours) visited.add(a ) __a = -1 __a = float("inf" ) if valid(a ) and g_function[neighbours] > g_function[s] + 1: __a = g_function[s] + 1 __a = s if neighbours not in close_list_anchor: open_list[0].put(a , key(a , 0 , a , a ) ) if neighbours not in close_list_inad: for var in range(1 , a ): if key(a , a , a , a ) <= Wa * key( a , 0 , a , a ): open_list[j].put( a , key(a , a , a , a ) ) def _lowerCamelCase( ): __a = [] for x in range(1 , 5 ): for y in range(1 , 6 ): some_list.append((x, y) ) for x in range(1_5 , 2_0 ): some_list.append((x, 1_7) ) for x in range(1_0 , 1_9 ): for y in range(1 , 1_5 ): some_list.append((x, y) ) # L block for x in range(1 , 4 ): for y in range(1_2 , 1_9 ): some_list.append((x, y) ) for x in range(3 , 1_3 ): for y in range(1_6 , 1_9 ): some_list.append((x, y) ) return some_list SCREAMING_SNAKE_CASE__:Any = {0: consistent_heuristic, 1: heuristic_a, 2: heuristic_a} SCREAMING_SNAKE_CASE__:str = [ (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1), ] SCREAMING_SNAKE_CASE__:int = make_common_ground() SCREAMING_SNAKE_CASE__:List[str] = blocks_blk # hyper parameters SCREAMING_SNAKE_CASE__:str = 1 SCREAMING_SNAKE_CASE__:Union[str, Any] = 1 SCREAMING_SNAKE_CASE__:Union[str, Any] = 20 SCREAMING_SNAKE_CASE__:Dict = 3 # one consistent and two other inconsistent # start and end destination SCREAMING_SNAKE_CASE__:Dict = (0, 0) SCREAMING_SNAKE_CASE__:Optional[Any] = (n - 1, n - 1) SCREAMING_SNAKE_CASE__:List[str] = 1 def _lowerCamelCase( a , a , a ): __a = {start: 0, goal: float("inf" )} __a = {start: -1, goal: -1} __a = [] __a = set() for i in range(a ): open_list.append(PriorityQueue() ) open_list[i].put(a , key(a , a , a , a ) ) __a = [] __a = [] while open_list[0].minkey() < float("inf" ): for i in range(1 , a ): # print(open_list[0].minkey(), open_list[i].minkey()) if open_list[i].minkey() <= Wa * open_list[0].minkey(): global t t += 1 if g_function[goal] <= open_list[i].minkey(): if g_function[goal] < float("inf" ): do_something(a , a , a ) else: __a , __a = open_list[i].top_show() visited.add(a ) expand_state( a , a , a , a , a , a , a , a , ) close_list_inad.append(a ) else: if g_function[goal] <= open_list[0].minkey(): if g_function[goal] < float("inf" ): do_something(a , a , a ) else: __a = open_list[0].top_show() visited.add(a ) expand_state( a , 0 , a , a , a , a , a , a , ) close_list_anchor.append(a ) print("No path found to goal" ) print() for i in range(n - 1 , -1 , -1 ): for j in range(a ): if (j, i) in blocks: print("#" , end=" " ) elif (j, i) in back_pointer: if (j, i) == (n - 1, n - 1): print("*" , end=" " ) else: print("-" , end=" " ) else: print("*" , end=" " ) if (j, i) == (n - 1, n - 1): print("<-- End position" , end=" " ) print() print("^" ) print("Start position" ) print() print("# is an obstacle" ) print("- is the path taken by algorithm" ) if __name__ == "__main__": multi_a_star(start, goal, n_heuristic)
704
"""simple docstring""" import argparse import OmegaConf import torch from diffusers import DDIMScheduler, LDMPipeline, UNetLDMModel, VQModel def _lowerCamelCase( a , a , a ): __a = OmegaConf.load(a ) __a = torch.load(a , map_location="cpu" )["model"] __a = list(state_dict.keys() ) # extract state_dict for VQVAE __a = {} __a = "first_stage_model." for key in keys: if key.startswith(a ): __a = state_dict[key] # extract state_dict for UNetLDM __a = {} __a = "model.diffusion_model." for key in keys: if key.startswith(a ): __a = state_dict[key] __a = config.model.params.first_stage_config.params __a = config.model.params.unet_config.params __a = VQModel(**a ).eval() vqvae.load_state_dict(a ) __a = UNetLDMModel(**a ).eval() unet.load_state_dict(a ) __a = 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=a , ) __a = LDMPipeline(a , a , a ) pipeline.save_pretrained(a ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__:List[Any] = 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) SCREAMING_SNAKE_CASE__:Union[str, Any] = parser.parse_args() convert_ldm_original(args.checkpoint_path, args.config_path, args.output_path)
67
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__:Optional[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Union[str, Any] = { """transfo-xl-wt103""": """https://huggingface.co/transfo-xl-wt103/resolve/main/config.json""", } class snake_case__ ( snake_case_ ): _snake_case : Optional[Any] = """transfo-xl""" _snake_case : List[str] = ["""mems"""] _snake_case : Optional[Any] = { """n_token""": """vocab_size""", """hidden_size""": """d_model""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self , lowerCamelCase=267735 , lowerCamelCase=[20000, 40000, 200000] , lowerCamelCase=1024 , lowerCamelCase=1024 , lowerCamelCase=16 , lowerCamelCase=64 , lowerCamelCase=4096 , lowerCamelCase=4 , lowerCamelCase=False , lowerCamelCase=18 , lowerCamelCase=1600 , lowerCamelCase=1000 , lowerCamelCase=True , lowerCamelCase=True , lowerCamelCase=0 , lowerCamelCase=-1 , lowerCamelCase=True , lowerCamelCase=0.1 , lowerCamelCase=0.0 , lowerCamelCase=True , lowerCamelCase="normal" , lowerCamelCase=0.01 , lowerCamelCase=0.01 , lowerCamelCase=0.02 , lowerCamelCase=1E-5 , lowerCamelCase=0 , **lowerCamelCase , ): __a = vocab_size __a = [] self.cutoffs.extend(lowerCamelCase ) if proj_share_all_but_first: __a = [False] + [True] * len(self.cutoffs ) else: __a = [False] + [False] * len(self.cutoffs ) __a = d_model __a = d_embed __a = d_head __a = d_inner __a = div_val __a = pre_lnorm __a = n_layer __a = n_head __a = mem_len __a = same_length __a = attn_type __a = clamp_len __a = sample_softmax __a = adaptive __a = dropout __a = dropatt __a = untie_r __a = init __a = init_range __a = proj_init_std __a = init_std __a = layer_norm_epsilon super().__init__(eos_token_id=lowerCamelCase , **lowerCamelCase ) @property def a__ ( self ): # Message copied from Transformer-XL documentation 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 a__ ( self , lowerCamelCase ): # Message copied from Transformer-XL documentation raise NotImplementedError( F"The model {self.model_type} is one of the few models that has no sequence length limit." )
705
"""simple docstring""" from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...file_utils import TensorType, is_torch_available from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging SCREAMING_SNAKE_CASE__:List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Optional[Any] = { """facebook/blenderbot_small-90M""": """https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/config.json""", # See all BlenderbotSmall models at https://huggingface.co/models?filter=blenderbot_small } class snake_case__ ( snake_case_ ): _snake_case : str = """blenderbot-small""" _snake_case : str = ["""past_key_values"""] _snake_case : List[Any] = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self , lowerCamelCase=50265 , lowerCamelCase=512 , lowerCamelCase=8 , lowerCamelCase=2048 , lowerCamelCase=16 , lowerCamelCase=8 , lowerCamelCase=2048 , lowerCamelCase=16 , lowerCamelCase=0.0 , lowerCamelCase=0.0 , lowerCamelCase=True , lowerCamelCase=True , lowerCamelCase="gelu" , lowerCamelCase=512 , lowerCamelCase=0.1 , lowerCamelCase=0.0 , lowerCamelCase=0.0 , lowerCamelCase=0.02 , lowerCamelCase=1 , lowerCamelCase=False , lowerCamelCase=0 , lowerCamelCase=1 , lowerCamelCase=2 , lowerCamelCase=2 , **lowerCamelCase , ): __a = vocab_size __a = max_position_embeddings __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 = encoder_layerdrop __a = decoder_layerdrop __a = use_cache __a = encoder_layers __a = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=lowerCamelCase , bos_token_id=lowerCamelCase , eos_token_id=lowerCamelCase , is_encoder_decoder=lowerCamelCase , decoder_start_token_id=lowerCamelCase , forced_eos_token_id=lowerCamelCase , **lowerCamelCase , ) class snake_case__ ( snake_case_ ): @property def a__ ( self ): if self.task in ["default", "seq2seq-lm"]: __a = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: __a = {0: "batch"} __a = {0: "batch", 1: "past_decoder_sequence + sequence"} else: __a = {0: "batch", 1: "decoder_sequence"} __a = {0: "batch", 1: "decoder_sequence"} if self.use_past: self.fill_with_past_key_values_(lowerCamelCase , direction="inputs" ) elif self.task == "causal-lm": # TODO: figure this case out. __a = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ] ) if self.use_past: __a , __a = self.num_layers for i in range(lowerCamelCase ): __a = {0: "batch", 2: "past_sequence + sequence"} __a = {0: "batch", 2: "past_sequence + sequence"} else: __a = OrderedDict( [ ("input_ids", {0: "batch", 1: "encoder_sequence"}), ("attention_mask", {0: "batch", 1: "encoder_sequence"}), ("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}), ("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}), ] ) return common_inputs @property def a__ ( self ): if self.task in ["default", "seq2seq-lm"]: __a = super().outputs else: __a = super(lowerCamelCase , self ).outputs if self.use_past: __a , __a = self.num_layers for i in range(lowerCamelCase ): __a = {0: "batch", 2: "past_sequence + sequence"} __a = {0: "batch", 2: "past_sequence + sequence"} return common_outputs def a__ ( self , lowerCamelCase , lowerCamelCase = -1 , lowerCamelCase = -1 , lowerCamelCase = False , lowerCamelCase = None , ): __a = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) # Generate decoder inputs __a = seq_length if not self.use_past else 1 __a = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) __a = {F"decoder_{name}": tensor for name, tensor in decoder_inputs.items()} __a = dict(**lowerCamelCase , **lowerCamelCase ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch __a , __a = common_inputs["input_ids"].shape __a = common_inputs["decoder_input_ids"].shape[1] __a , __a = self.num_attention_heads __a = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) __a = decoder_seq_length + 3 __a = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) __a = torch.cat( [common_inputs["decoder_attention_mask"], torch.ones(lowerCamelCase , lowerCamelCase )] , dim=1 ) __a = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered __a , __a = self.num_layers __a = min(lowerCamelCase , lowerCamelCase ) __a = max(lowerCamelCase , lowerCamelCase ) - min_num_layers __a = "encoder" if num_encoder_layers > num_decoder_layers else "decoder" for _ in range(lowerCamelCase ): common_inputs["past_key_values"].append( ( torch.zeros(lowerCamelCase ), torch.zeros(lowerCamelCase ), torch.zeros(lowerCamelCase ), torch.zeros(lowerCamelCase ), ) ) # TODO: test this. __a = encoder_shape if remaining_side_name == "encoder" else decoder_shape for _ in range(lowerCamelCase , lowerCamelCase ): common_inputs["past_key_values"].append((torch.zeros(lowerCamelCase ), torch.zeros(lowerCamelCase )) ) return common_inputs def a__ ( self , lowerCamelCase , lowerCamelCase = -1 , lowerCamelCase = -1 , lowerCamelCase = False , lowerCamelCase = None , ): __a = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch __a , __a = common_inputs["input_ids"].shape # Not using the same length for past_key_values __a = seqlen + 2 __a , __a = self.num_layers __a , __a = self.num_attention_heads __a = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) __a = common_inputs["attention_mask"].dtype __a = torch.cat( [common_inputs["attention_mask"], torch.ones(lowerCamelCase , lowerCamelCase , dtype=lowerCamelCase )] , dim=1 ) __a = [ (torch.zeros(lowerCamelCase ), torch.zeros(lowerCamelCase )) for _ in range(lowerCamelCase ) ] return common_inputs def a__ ( self , lowerCamelCase , lowerCamelCase = -1 , lowerCamelCase = -1 , lowerCamelCase = False , lowerCamelCase = None , ): # Copied from OnnxConfig.generate_dummy_inputs # Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity. # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX __a = compute_effective_axis_dimension( lowerCamelCase , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX __a = tokenizer.num_special_tokens_to_add(lowerCamelCase ) __a = compute_effective_axis_dimension( lowerCamelCase , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=lowerCamelCase ) # Generate dummy inputs according to compute batch and sequence __a = [" ".join([tokenizer.unk_token] ) * seq_length] * batch_size __a = dict(tokenizer(lowerCamelCase , return_tensors=lowerCamelCase ) ) return common_inputs def a__ ( self , lowerCamelCase , lowerCamelCase = -1 , lowerCamelCase = -1 , lowerCamelCase = False , lowerCamelCase = None , ): if self.task in ["default", "seq2seq-lm"]: __a = self._generate_dummy_inputs_for_default_and_seqaseq_lm( lowerCamelCase , batch_size=lowerCamelCase , seq_length=lowerCamelCase , is_pair=lowerCamelCase , framework=lowerCamelCase ) elif self.task == "causal-lm": __a = self._generate_dummy_inputs_for_causal_lm( lowerCamelCase , batch_size=lowerCamelCase , seq_length=lowerCamelCase , is_pair=lowerCamelCase , framework=lowerCamelCase ) else: __a = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( lowerCamelCase , batch_size=lowerCamelCase , seq_length=lowerCamelCase , is_pair=lowerCamelCase , framework=lowerCamelCase ) return common_inputs def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): if self.task in ["default", "seq2seq-lm"]: __a = super()._flatten_past_key_values_(lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ) else: __a = super(lowerCamelCase , self )._flatten_past_key_values_( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase )
67
0
"""simple docstring""" import numpy as np import torch import torch.nn as nn from transformers import CLIPConfig, CLIPVisionModelWithProjection, PreTrainedModel from ...utils import logging SCREAMING_SNAKE_CASE__:List[Any] = logging.get_logger(__name__) class snake_case__ ( snake_case_ ): _snake_case : int = CLIPConfig _snake_case : Dict = ["""CLIPEncoderLayer"""] def __init__( self , lowerCamelCase ): super().__init__(lowerCamelCase ) __a = CLIPVisionModelWithProjection(config.vision_config ) __a = nn.Linear(config.vision_config.projection_dim , 1 ) __a = nn.Linear(config.vision_config.projection_dim , 1 ) @torch.no_grad() def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase=0.5 , lowerCamelCase=0.5 ): __a = self.vision_model(lowerCamelCase )[0] __a = self.p_head(lowerCamelCase ) __a = nsfw_detected.flatten() __a = nsfw_detected > p_threshold __a = nsfw_detected.tolist() if any(lowerCamelCase ): logger.warning( "Potential NSFW content was detected in one or more images. A black image will be returned instead." " Try again with a different prompt and/or seed." ) for idx, nsfw_detected_ in enumerate(lowerCamelCase ): if nsfw_detected_: __a = np.zeros(images[idx].shape ) __a = self.w_head(lowerCamelCase ) __a = watermark_detected.flatten() __a = watermark_detected > w_threshold __a = watermark_detected.tolist() if any(lowerCamelCase ): logger.warning( "Potential watermarked content was detected in one or more images. A black image will be returned instead." " Try again with a different prompt and/or seed." ) for idx, watermark_detected_ in enumerate(lowerCamelCase ): if watermark_detected_: __a = np.zeros(images[idx].shape ) return images, nsfw_detected, watermark_detected
706
"""simple docstring""" import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class snake_case__ : def __init__( self , lowerCamelCase , lowerCamelCase=99 , lowerCamelCase=13 , lowerCamelCase=7 , lowerCamelCase=9 , lowerCamelCase=True , lowerCamelCase=True , lowerCamelCase=False , lowerCamelCase=32 , lowerCamelCase=5 , lowerCamelCase=4 , lowerCamelCase=37 , lowerCamelCase=8 , lowerCamelCase=0.1 , lowerCamelCase=0.002 , lowerCamelCase=1 , lowerCamelCase=0 , lowerCamelCase=0 , lowerCamelCase=None , lowerCamelCase=None , ): __a = parent __a = batch_size __a = encoder_seq_length __a = decoder_seq_length # For common tests __a = self.decoder_seq_length __a = is_training __a = use_attention_mask __a = use_labels __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = d_ff __a = relative_attention_num_buckets __a = dropout_rate __a = initializer_factor __a = eos_token_id __a = pad_token_id __a = decoder_start_token_id __a = None __a = decoder_layers def a__ ( self ): return TaConfig.from_pretrained("google/umt5-base" ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , ): if attention_mask is None: __a = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: __a = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: __a = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=lowerCamelCase ) if decoder_head_mask is None: __a = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=lowerCamelCase ) if cross_attn_head_mask is None: __a = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=lowerCamelCase ) 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, } def a__ ( self ): __a = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) __a = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input __a = input_ids.clamp(self.pad_token_id + 1 ) __a = decoder_input_ids.clamp(self.pad_token_id + 1 ) __a = self.get_config() __a = config.num_attention_heads __a = self.prepare_inputs_dict(lowerCamelCase , lowerCamelCase , lowerCamelCase ) return config, input_dict def a__ ( self ): __a , __a = self.prepare_config_and_inputs() return config, inputs_dict def a__ ( self ): return TaConfig( vocab_size=166 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def a__ ( self ): return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , ): __a = UMTaModel(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model( input_ids=lowerCamelCase , decoder_input_ids=lowerCamelCase , attention_mask=lowerCamelCase , decoder_attention_mask=lowerCamelCase , ) __a = model(input_ids=lowerCamelCase , decoder_input_ids=lowerCamelCase ) __a = result.last_hidden_state __a = result.past_key_values __a = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(lowerCamelCase ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , ): __a = UMTaModel(config=lowerCamelCase ).get_decoder().to(lowerCamelCase ).eval() # first forward pass __a = model(lowerCamelCase , use_cache=lowerCamelCase ) __a = model(lowerCamelCase ) __a = model(lowerCamelCase , use_cache=lowerCamelCase ) self.parent.assertTrue(len(lowerCamelCase ) == len(lowerCamelCase ) ) self.parent.assertTrue(len(lowerCamelCase ) == len(lowerCamelCase ) + 1 ) __a , __a = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __a = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and __a = torch.cat([input_ids, next_tokens] , dim=-1 ) __a = model(lowerCamelCase )["last_hidden_state"] __a = model(lowerCamelCase , past_key_values=lowerCamelCase )["last_hidden_state"] # select random slice __a = ids_tensor((1,) , output_from_past.shape[-1] ).item() __a = output_from_no_past[:, -1, random_slice_idx].detach() __a = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(lowerCamelCase , lowerCamelCase , atol=1E-3 ) ) def a__ ( self , lowerCamelCase , lowerCamelCase , ): __a = UMTaModel(config=lowerCamelCase ).to(lowerCamelCase ).half().eval() __a = model(**lowerCamelCase )["last_hidden_state"] self.parent.assertFalse(torch.isnan(lowerCamelCase ).any().item() ) @require_torch class snake_case__ ( snake_case_, snake_case_, snake_case_, unittest.TestCase ): _snake_case : Union[str, Any] = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) _snake_case : int = (UMTaForConditionalGeneration,) if is_torch_available() else () _snake_case : Optional[int] = ( { """conversational""": UMTaForConditionalGeneration, """feature-extraction""": UMTaModel, """summarization""": UMTaForConditionalGeneration, """text2text-generation""": UMTaForConditionalGeneration, """translation""": UMTaForConditionalGeneration, """question-answering""": UMTaForQuestionAnswering, } if is_torch_available() else {} ) _snake_case : List[Any] = True _snake_case : Union[str, Any] = False _snake_case : Union[str, Any] = False _snake_case : Tuple = True _snake_case : List[str] = True # The small UMT5 model needs higher percentages for CPU/MP tests _snake_case : Optional[Any] = [0.8, 0.9] def a__ ( self ): __a = UMTaModelTester(self ) @unittest.skip("Test has a segmentation fault on torch 1.8.0" ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() __a = UMTaModel(config_and_inputs[0] ).to(lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( lowerCamelCase , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , F"{tmpdirname}/t5_test.onnx" , export_params=lowerCamelCase , opset_version=9 , input_names=["input_ids", "decoder_input_ids"] , ) @unittest.skipIf(torch_device == "cpu" , "Cant do half precision" ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*lowerCamelCase ) def a__ ( self ): __a = ["encoder_attentions", "decoder_attentions", "cross_attentions"] __a = self.model_tester.prepare_config_and_inputs() __a = config_and_inputs[0] __a = UMTaForConditionalGeneration(lowerCamelCase ).eval() model.to(lowerCamelCase ) __a = { "head_mask": torch.zeros(config.num_layers , config.num_heads , device=lowerCamelCase ), "decoder_head_mask": torch.zeros(config.num_decoder_layers , config.num_heads , device=lowerCamelCase ), "cross_attn_head_mask": torch.zeros(config.num_decoder_layers , config.num_heads , device=lowerCamelCase ), } for attn_name, (name, mask) in zip(lowerCamelCase , head_masking.items() ): __a = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": __a = torch.ones( config.num_decoder_layers , config.num_heads , device=lowerCamelCase ) __a = model.generate( config_and_inputs[1]["input_ids"] , num_beams=1 , max_length=3 , output_attentions=lowerCamelCase , return_dict_in_generate=lowerCamelCase , **lowerCamelCase , ) # We check the state of decoder_attentions and cross_attentions just from the last step __a = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip("Does not work on the tiny model as we keep hitting edge cases." ) def a__ ( self ): pass @require_torch @require_sentencepiece @require_tokenizers class snake_case__ ( unittest.TestCase ): @slow @unittest.skip( "Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged" ) def a__ ( self ): __a = UMTaForConditionalGeneration.from_pretrained("google/umt5-small" , return_dict=lowerCamelCase ).to(lowerCamelCase ) __a = AutoTokenizer.from_pretrained("google/umt5-small" , use_fast=lowerCamelCase , legacy=lowerCamelCase ) __a = [ "Bonjour monsieur <extra_id_0> bien <extra_id_1>.", "No se como puedo <extra_id_0>.", "This is the reason why we <extra_id_0> them.", "The <extra_id_0> walks in <extra_id_1>, seats", "A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.", ] __a = tokenizer(lowerCamelCase , return_tensors="pt" , padding=lowerCamelCase ).input_ids # fmt: off __a = torch.tensor( [ [ 38530, 210703, 256299, 1410, 256298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 826, 321, 671, 25922, 256299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1460, 339, 312, 19014, 10620, 758, 256299, 2355,274, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 517, 256299, 14869, 281, 301, 256298, 275, 119983,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 320, 256299, 14869, 281, 2234, 289, 2275, 333,61391, 289, 256298, 543, 256297, 168714, 329, 256296,274, 1], ] ) # fmt: on torch.testing.assert_allclose(lowerCamelCase , lowerCamelCase ) __a = model.generate(input_ids.to(lowerCamelCase ) ) __a = [ "<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>", "<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", "<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", "<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", "<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", ] __a = tokenizer.batch_decode(lowerCamelCase ) self.assertEqual(lowerCamelCase , lowerCamelCase )
67
0
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case__ : def __init__( self , lowerCamelCase = 6 ): __a = None __a = None self.create_linked_list(lowerCamelCase ) def a__ ( self , lowerCamelCase ): __a = Node() __a = current_node __a = current_node __a = current_node for _ in range(1 , lowerCamelCase ): __a = Node() __a = current_node __a = previous_node __a = current_node __a = self.front __a = previous_node def a__ ( self ): return ( self.front == self.rear and self.front is not None and self.front.data is None ) def a__ ( self ): self.check_can_perform_operation() return self.front.data if self.front else None def a__ ( self , lowerCamelCase ): if self.rear is None: return self.check_is_full() if not self.is_empty(): __a = self.rear.next if self.rear: __a = data def a__ ( self ): self.check_can_perform_operation() if self.rear is None or self.front is None: return None if self.front == self.rear: __a = self.front.data __a = None return data __a = self.front __a = old_front.next __a = old_front.data __a = None return data def a__ ( self ): if self.is_empty(): raise Exception("Empty Queue" ) def a__ ( self ): if self.rear and self.rear.next == self.front: raise Exception("Full Queue" ) class snake_case__ : def __init__( self ): __a = None __a = None __a = None if __name__ == "__main__": import doctest doctest.testmod()
707
"""simple docstring""" import argparse import torch from transformers import MobileBertConfig, MobileBertForPreTraining, load_tf_weights_in_mobilebert from transformers.utils import logging logging.set_verbosity_info() def _lowerCamelCase( a , a , a ): # Initialise PyTorch model __a = MobileBertConfig.from_json_file(a ) print(F"Building PyTorch model from configuration: {config}" ) __a = MobileBertForPreTraining(a ) # Load weights from tf checkpoint __a = load_tf_weights_in_mobilebert(a , a , a ) # Save pytorch-model print(F"Save PyTorch model to {pytorch_dump_path}" ) torch.save(model.state_dict() , a ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__:List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path.""" ) parser.add_argument( """--mobilebert_config_file""", default=None, type=str, required=True, help=( """The config json file corresponding to the pre-trained MobileBERT model. \n""" """This specifies the model architecture.""" ), ) parser.add_argument( """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model.""" ) SCREAMING_SNAKE_CASE__:List[Any] = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.mobilebert_config_file, args.pytorch_dump_path)
67
0
import tempfile import unittest from transformers import TaConfig, is_torch_available from transformers.testing_utils import ( require_sentencepiece, require_tokenizers, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import AutoTokenizer, UMTaForConditionalGeneration, UMTaForQuestionAnswering, UMTaModel class snake_case__ : def __init__( self , lowerCamelCase , lowerCamelCase=99 , lowerCamelCase=13 , lowerCamelCase=7 , lowerCamelCase=9 , lowerCamelCase=True , lowerCamelCase=True , lowerCamelCase=False , lowerCamelCase=32 , lowerCamelCase=5 , lowerCamelCase=4 , lowerCamelCase=37 , lowerCamelCase=8 , lowerCamelCase=0.1 , lowerCamelCase=0.002 , lowerCamelCase=1 , lowerCamelCase=0 , lowerCamelCase=0 , lowerCamelCase=None , lowerCamelCase=None , ): __a = parent __a = batch_size __a = encoder_seq_length __a = decoder_seq_length # For common tests __a = self.decoder_seq_length __a = is_training __a = use_attention_mask __a = use_labels __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = d_ff __a = relative_attention_num_buckets __a = dropout_rate __a = initializer_factor __a = eos_token_id __a = pad_token_id __a = decoder_start_token_id __a = None __a = decoder_layers def a__ ( self ): return TaConfig.from_pretrained("google/umt5-base" ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , ): if attention_mask is None: __a = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: __a = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: __a = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=lowerCamelCase ) if decoder_head_mask is None: __a = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=lowerCamelCase ) if cross_attn_head_mask is None: __a = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=lowerCamelCase ) 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, } def a__ ( self ): __a = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) __a = ids_tensor([self.batch_size, self.decoder_seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for NllbMoe the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input __a = input_ids.clamp(self.pad_token_id + 1 ) __a = decoder_input_ids.clamp(self.pad_token_id + 1 ) __a = self.get_config() __a = config.num_attention_heads __a = self.prepare_inputs_dict(lowerCamelCase , lowerCamelCase , lowerCamelCase ) return config, input_dict def a__ ( self ): __a , __a = self.prepare_config_and_inputs() return config, inputs_dict def a__ ( self ): return TaConfig( vocab_size=166 , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def a__ ( self ): return TaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , d_ff=self.d_ff , d_kv=self.hidden_size // self.num_attention_heads , num_layers=self.num_hidden_layers , num_decoder_layers=self.decoder_layers , num_heads=self.num_attention_heads , relative_attention_num_buckets=self.relative_attention_num_buckets , dropout_rate=self.dropout_rate , initializer_factor=self.initializer_factor , eos_token_id=self.eos_token_id , bos_token_id=self.pad_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.decoder_start_token_id , ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , ): __a = UMTaModel(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model( input_ids=lowerCamelCase , decoder_input_ids=lowerCamelCase , attention_mask=lowerCamelCase , decoder_attention_mask=lowerCamelCase , ) __a = model(input_ids=lowerCamelCase , decoder_input_ids=lowerCamelCase ) __a = result.last_hidden_state __a = result.past_key_values __a = result.encoder_last_hidden_state self.parent.assertEqual(encoder_output.size() , (self.batch_size, self.encoder_seq_length, self.hidden_size) ) self.parent.assertEqual(decoder_output.size() , (self.batch_size, self.decoder_seq_length, self.hidden_size) ) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(lowerCamelCase ) , config.num_layers ) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0] ) , 4 ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase , ): __a = UMTaModel(config=lowerCamelCase ).get_decoder().to(lowerCamelCase ).eval() # first forward pass __a = model(lowerCamelCase , use_cache=lowerCamelCase ) __a = model(lowerCamelCase ) __a = model(lowerCamelCase , use_cache=lowerCamelCase ) self.parent.assertTrue(len(lowerCamelCase ) == len(lowerCamelCase ) ) self.parent.assertTrue(len(lowerCamelCase ) == len(lowerCamelCase ) + 1 ) __a , __a = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids __a = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and __a = torch.cat([input_ids, next_tokens] , dim=-1 ) __a = model(lowerCamelCase )["last_hidden_state"] __a = model(lowerCamelCase , past_key_values=lowerCamelCase )["last_hidden_state"] # select random slice __a = ids_tensor((1,) , output_from_past.shape[-1] ).item() __a = output_from_no_past[:, -1, random_slice_idx].detach() __a = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(lowerCamelCase , lowerCamelCase , atol=1E-3 ) ) def a__ ( self , lowerCamelCase , lowerCamelCase , ): __a = UMTaModel(config=lowerCamelCase ).to(lowerCamelCase ).half().eval() __a = model(**lowerCamelCase )["last_hidden_state"] self.parent.assertFalse(torch.isnan(lowerCamelCase ).any().item() ) @require_torch class snake_case__ ( snake_case_, snake_case_, snake_case_, unittest.TestCase ): _snake_case : Union[str, Any] = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) _snake_case : int = (UMTaForConditionalGeneration,) if is_torch_available() else () _snake_case : Optional[int] = ( { """conversational""": UMTaForConditionalGeneration, """feature-extraction""": UMTaModel, """summarization""": UMTaForConditionalGeneration, """text2text-generation""": UMTaForConditionalGeneration, """translation""": UMTaForConditionalGeneration, """question-answering""": UMTaForQuestionAnswering, } if is_torch_available() else {} ) _snake_case : List[Any] = True _snake_case : Union[str, Any] = False _snake_case : Union[str, Any] = False _snake_case : Tuple = True _snake_case : List[str] = True # The small UMT5 model needs higher percentages for CPU/MP tests _snake_case : Optional[Any] = [0.8, 0.9] def a__ ( self ): __a = UMTaModelTester(self ) @unittest.skip("Test has a segmentation fault on torch 1.8.0" ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() __a = UMTaModel(config_and_inputs[0] ).to(lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( lowerCamelCase , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , F"{tmpdirname}/t5_test.onnx" , export_params=lowerCamelCase , opset_version=9 , input_names=["input_ids", "decoder_input_ids"] , ) @unittest.skipIf(torch_device == "cpu" , "Cant do half precision" ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*lowerCamelCase ) def a__ ( self ): __a = ["encoder_attentions", "decoder_attentions", "cross_attentions"] __a = self.model_tester.prepare_config_and_inputs() __a = config_and_inputs[0] __a = UMTaForConditionalGeneration(lowerCamelCase ).eval() model.to(lowerCamelCase ) __a = { "head_mask": torch.zeros(config.num_layers , config.num_heads , device=lowerCamelCase ), "decoder_head_mask": torch.zeros(config.num_decoder_layers , config.num_heads , device=lowerCamelCase ), "cross_attn_head_mask": torch.zeros(config.num_decoder_layers , config.num_heads , device=lowerCamelCase ), } for attn_name, (name, mask) in zip(lowerCamelCase , head_masking.items() ): __a = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": __a = torch.ones( config.num_decoder_layers , config.num_heads , device=lowerCamelCase ) __a = model.generate( config_and_inputs[1]["input_ids"] , num_beams=1 , max_length=3 , output_attentions=lowerCamelCase , return_dict_in_generate=lowerCamelCase , **lowerCamelCase , ) # We check the state of decoder_attentions and cross_attentions just from the last step __a = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1] self.assertEqual(sum([w.sum().item() for w in attn_weights] ) , 0.0 ) @unittest.skip("Does not work on the tiny model as we keep hitting edge cases." ) def a__ ( self ): pass @require_torch @require_sentencepiece @require_tokenizers class snake_case__ ( unittest.TestCase ): @slow @unittest.skip( "Unless we stop stripping left and right by default for all special tokens, the expected ids obtained here will not match the original ones. Wait for https://github.com/huggingface/transformers/pull/23909 to be merged" ) def a__ ( self ): __a = UMTaForConditionalGeneration.from_pretrained("google/umt5-small" , return_dict=lowerCamelCase ).to(lowerCamelCase ) __a = AutoTokenizer.from_pretrained("google/umt5-small" , use_fast=lowerCamelCase , legacy=lowerCamelCase ) __a = [ "Bonjour monsieur <extra_id_0> bien <extra_id_1>.", "No se como puedo <extra_id_0>.", "This is the reason why we <extra_id_0> them.", "The <extra_id_0> walks in <extra_id_1>, seats", "A <extra_id_0> walks into a bar and orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>.", ] __a = tokenizer(lowerCamelCase , return_tensors="pt" , padding=lowerCamelCase ).input_ids # fmt: off __a = torch.tensor( [ [ 38530, 210703, 256299, 1410, 256298, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 826, 321, 671, 25922, 256299, 274, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 1460, 339, 312, 19014, 10620, 758, 256299, 2355,274, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 517, 256299, 14869, 281, 301, 256298, 275, 119983,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 320, 256299, 14869, 281, 2234, 289, 2275, 333,61391, 289, 256298, 543, 256297, 168714, 329, 256296,274, 1], ] ) # fmt: on torch.testing.assert_allclose(lowerCamelCase , lowerCamelCase ) __a = model.generate(input_ids.to(lowerCamelCase ) ) __a = [ "<pad><extra_id_0> et<extra_id_1> [eod] <extra_id_2><extra_id_55>.. [eod] 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 💐 <extra_id_56>ajšietosto<extra_id_56>lleux<extra_id_19><extra_id_6>ajšie</s>", "<pad><extra_id_0>.<extra_id_1>.,<0x0A>...spech <0x0A><extra_id_20> <extra_id_21></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", "<pad><extra_id_0> are not going to be a part of the world. We are not going to be a part of<extra_id_1> and<extra_id_2><0x0A><extra_id_48>.<extra_id_48></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", "<pad><extra_id_0> door<extra_id_1>, the door<extra_id_2> 피해[/</s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", "<pad><extra_id_0>nyone who<extra_id_1> drink<extra_id_2> a<extra_id_3> alcohol<extra_id_4> A<extra_id_5> A. This<extra_id_6> I<extra_id_7><extra_id_52><extra_id_53></s><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad><pad>", ] __a = tokenizer.batch_decode(lowerCamelCase ) self.assertEqual(lowerCamelCase , lowerCamelCase )
708
"""simple docstring""" import re from pathlib import Path from unittest import TestCase import pytest @pytest.mark.integration class snake_case__ ( snake_case_ ): def a__ ( self , lowerCamelCase ): with open(lowerCamelCase , encoding="utf-8" ) as input_file: __a = re.compile(R"(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)" ) __a = input_file.read() __a = regexp.search(lowerCamelCase ) return match def a__ ( self , lowerCamelCase ): with open(lowerCamelCase , encoding="utf-8" ) as input_file: __a = re.compile(R"#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()" , re.DOTALL ) __a = input_file.read() # use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search` __a = regexp.finditer(lowerCamelCase ) __a = [match for match in matches if match is not None and match.group(1 ) is not None] return matches[0] if matches else None def a__ ( self ): __a = Path("./datasets" ) __a = list(dataset_paths.absolute().glob("**/*.py" ) ) for dataset in dataset_files: if self._no_encoding_on_file_open(str(lowerCamelCase ) ): raise AssertionError(F"open(...) must use utf-8 encoding in {dataset}" ) def a__ ( self ): __a = Path("./datasets" ) __a = list(dataset_paths.absolute().glob("**/*.py" ) ) for dataset in dataset_files: if self._no_print_statements(str(lowerCamelCase ) ): raise AssertionError(F"print statement found in {dataset}. Use datasets.logger/logging instead." )
67
0
"""simple docstring""" from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class snake_case__ ( snake_case_ ): _snake_case : Optional[Any] = """ClapFeatureExtractor""" _snake_case : Any = ("""RobertaTokenizer""", """RobertaTokenizerFast""") def __init__( self , lowerCamelCase , lowerCamelCase ): super().__init__(lowerCamelCase , lowerCamelCase ) def __call__( self , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , **lowerCamelCase ): __a = 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: __a = self.tokenizer(lowerCamelCase , return_tensors=lowerCamelCase , **lowerCamelCase ) if audios is not None: __a = self.feature_extractor( lowerCamelCase , sampling_rate=lowerCamelCase , return_tensors=lowerCamelCase , **lowerCamelCase ) if text is not None and audios is not None: __a = audio_features.input_features return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**lowerCamelCase ) , tensor_type=lowerCamelCase ) def a__ ( self , *lowerCamelCase , **lowerCamelCase ): return self.tokenizer.batch_decode(*lowerCamelCase , **lowerCamelCase ) def a__ ( self , *lowerCamelCase , **lowerCamelCase ): return self.tokenizer.decode(*lowerCamelCase , **lowerCamelCase ) @property def a__ ( self ): __a = self.tokenizer.model_input_names __a = self.feature_extractor.model_input_names return list(dict.fromkeys(tokenizer_input_names + feature_extractor_input_names ) )
709
"""simple docstring""" from .imports import is_rich_available if is_rich_available(): from rich.traceback import install install(show_locals=False) else: raise ModuleNotFoundError("""To use the rich extension, install rich with `pip install rich`""")
67
0
"""simple docstring""" import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class snake_case__ ( unittest.TestCase ): @property def a__ ( self ): torch.manual_seed(0 ) __a = 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 a__ ( self ): __a = self.dummy_uncond_unet __a = KarrasVeScheduler() __a = KarrasVePipeline(unet=lowerCamelCase , scheduler=lowerCamelCase ) pipe.to(lowerCamelCase ) pipe.set_progress_bar_config(disable=lowerCamelCase ) __a = torch.manual_seed(0 ) __a = pipe(num_inference_steps=2 , generator=lowerCamelCase , output_type="numpy" ).images __a = torch.manual_seed(0 ) __a = pipe(num_inference_steps=2 , generator=lowerCamelCase , output_type="numpy" , return_dict=lowerCamelCase )[0] __a = image[0, -3:, -3:, -1] __a = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __a = np.array([0.0, 1.0, 0.0, 0.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 snake_case__ ( unittest.TestCase ): def a__ ( self ): __a = "google/ncsnpp-celebahq-256" __a = UNetaDModel.from_pretrained(lowerCamelCase ) __a = KarrasVeScheduler() __a = KarrasVePipeline(unet=lowerCamelCase , scheduler=lowerCamelCase ) pipe.to(lowerCamelCase ) pipe.set_progress_bar_config(disable=lowerCamelCase ) __a = torch.manual_seed(0 ) __a = pipe(num_inference_steps=20 , generator=lowerCamelCase , output_type="numpy" ).images __a = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) __a = np.array([0.578, 0.5811, 0.5924, 0.5809, 0.587, 0.5886, 0.5861, 0.5802, 0.586] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
710
"""simple docstring""" import heapq import sys import numpy as np SCREAMING_SNAKE_CASE__:Optional[int] = tuple[int, int] class snake_case__ : def __init__( self ): __a = [] __a = set() def a__ ( self ): if not self.empty(): return self.elements[0][0] else: return float("inf" ) def a__ ( self ): return len(self.elements ) == 0 def a__ ( self , lowerCamelCase , lowerCamelCase ): if item not in self.set: heapq.heappush(self.elements , (priority, item) ) self.set.add(lowerCamelCase ) else: # update # print("update", item) __a = [] ((__a) , (__a)) = heapq.heappop(self.elements ) while x != item: temp.append((pri, x) ) ((__a) , (__a)) = heapq.heappop(self.elements ) temp.append((priority, item) ) for pro, xxx in temp: heapq.heappush(self.elements , (pro, xxx) ) def a__ ( self , lowerCamelCase ): if item in self.set: self.set.remove(lowerCamelCase ) __a = [] ((__a) , (__a)) = heapq.heappop(self.elements ) while x != item: temp.append((pro, x) ) ((__a) , (__a)) = heapq.heappop(self.elements ) for prito, yyy in temp: heapq.heappush(self.elements , (prito, yyy) ) def a__ ( self ): return self.elements[0][1] def a__ ( self ): ((__a) , (__a)) = heapq.heappop(self.elements ) self.set.remove(lowerCamelCase ) return (priority, item) def _lowerCamelCase( a , a ): # euclidean distance __a = np.array(a ) __a = np.array(a ) return np.linalg.norm(a - b ) def _lowerCamelCase( a , a ): # integer division by time variable return consistent_heuristic(a , a ) // t def _lowerCamelCase( a , a ): # manhattan distance return abs(p[0] - goal[0] ) + abs(p[1] - goal[1] ) def _lowerCamelCase( a , a , a , a ): __a = g_function[start] + Wa * heuristics[i](a , a ) return ans def _lowerCamelCase( a , a , a ): __a = np.chararray((n, n) ) for i in range(a ): for j in range(a ): __a = "*" for i in range(a ): for j in range(a ): if (j, (n - 1) - i) in blocks: __a = "#" __a = "-" __a = back_pointer[goal] while x != start: ((__a) , (__a)) = x # print(x) __a = "-" __a = back_pointer[x] __a = "-" for i in range(a ): for j in range(a ): if (i, j) == (0, n - 1): print(grid[i][j] , end=" " ) print("<-- End position" , end=" " ) else: print(grid[i][j] , end=" " ) print() print("^" ) print("Start position" ) print() print("# is an obstacle" ) print("- is the path taken by algorithm" ) print("PATH TAKEN BY THE ALGORITHM IS:-" ) __a = back_pointer[goal] while x != start: print(a , end=" " ) __a = back_pointer[x] print(a ) sys.exit() def _lowerCamelCase( a ): if p[0] < 0 or p[0] > n - 1: return False if p[1] < 0 or p[1] > n - 1: return False return True def _lowerCamelCase( a , a , a , a , a , a , a , a , ): for itera in range(a ): open_list[itera].remove_element(a ) # print("s", s) # print("j", j) ((__a) , (__a)) = s __a = (x - 1, y) __a = (x + 1, y) __a = (x, y + 1) __a = (x, y - 1) for neighbours in [left, right, up, down]: if neighbours not in blocks: if valid(a ) and neighbours not in visited: # print("neighbour", neighbours) visited.add(a ) __a = -1 __a = float("inf" ) if valid(a ) and g_function[neighbours] > g_function[s] + 1: __a = g_function[s] + 1 __a = s if neighbours not in close_list_anchor: open_list[0].put(a , key(a , 0 , a , a ) ) if neighbours not in close_list_inad: for var in range(1 , a ): if key(a , a , a , a ) <= Wa * key( a , 0 , a , a ): open_list[j].put( a , key(a , a , a , a ) ) def _lowerCamelCase( ): __a = [] for x in range(1 , 5 ): for y in range(1 , 6 ): some_list.append((x, y) ) for x in range(1_5 , 2_0 ): some_list.append((x, 1_7) ) for x in range(1_0 , 1_9 ): for y in range(1 , 1_5 ): some_list.append((x, y) ) # L block for x in range(1 , 4 ): for y in range(1_2 , 1_9 ): some_list.append((x, y) ) for x in range(3 , 1_3 ): for y in range(1_6 , 1_9 ): some_list.append((x, y) ) return some_list SCREAMING_SNAKE_CASE__:Any = {0: consistent_heuristic, 1: heuristic_a, 2: heuristic_a} SCREAMING_SNAKE_CASE__:str = [ (0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (16, 1), (17, 1), (18, 1), (19, 1), ] SCREAMING_SNAKE_CASE__:int = make_common_ground() SCREAMING_SNAKE_CASE__:List[str] = blocks_blk # hyper parameters SCREAMING_SNAKE_CASE__:str = 1 SCREAMING_SNAKE_CASE__:Union[str, Any] = 1 SCREAMING_SNAKE_CASE__:Union[str, Any] = 20 SCREAMING_SNAKE_CASE__:Dict = 3 # one consistent and two other inconsistent # start and end destination SCREAMING_SNAKE_CASE__:Dict = (0, 0) SCREAMING_SNAKE_CASE__:Optional[Any] = (n - 1, n - 1) SCREAMING_SNAKE_CASE__:List[str] = 1 def _lowerCamelCase( a , a , a ): __a = {start: 0, goal: float("inf" )} __a = {start: -1, goal: -1} __a = [] __a = set() for i in range(a ): open_list.append(PriorityQueue() ) open_list[i].put(a , key(a , a , a , a ) ) __a = [] __a = [] while open_list[0].minkey() < float("inf" ): for i in range(1 , a ): # print(open_list[0].minkey(), open_list[i].minkey()) if open_list[i].minkey() <= Wa * open_list[0].minkey(): global t t += 1 if g_function[goal] <= open_list[i].minkey(): if g_function[goal] < float("inf" ): do_something(a , a , a ) else: __a , __a = open_list[i].top_show() visited.add(a ) expand_state( a , a , a , a , a , a , a , a , ) close_list_inad.append(a ) else: if g_function[goal] <= open_list[0].minkey(): if g_function[goal] < float("inf" ): do_something(a , a , a ) else: __a = open_list[0].top_show() visited.add(a ) expand_state( a , 0 , a , a , a , a , a , a , ) close_list_anchor.append(a ) print("No path found to goal" ) print() for i in range(n - 1 , -1 , -1 ): for j in range(a ): if (j, i) in blocks: print("#" , end=" " ) elif (j, i) in back_pointer: if (j, i) == (n - 1, n - 1): print("*" , end=" " ) else: print("-" , end=" " ) else: print("*" , end=" " ) if (j, i) == (n - 1, n - 1): print("<-- End position" , end=" " ) print() print("^" ) print("Start position" ) print() print("# is an obstacle" ) print("- is the path taken by algorithm" ) if __name__ == "__main__": multi_a_star(start, goal, n_heuristic)
67
0
"""simple docstring""" def _lowerCamelCase( a , a ): __a = len(a ) print("The following activities are selected:" ) # The first activity is always selected __a = 0 print(a , end="," ) # Consider rest of the activities for j in range(a ): # If this activity has start time greater than # or equal to the finish time of previously # selected activity, then select it if start[j] >= finish[i]: print(a , end="," ) __a = j if __name__ == "__main__": import doctest doctest.testmod() SCREAMING_SNAKE_CASE__:str = [1, 3, 0, 5, 8, 5] SCREAMING_SNAKE_CASE__:Union[str, Any] = [2, 4, 6, 7, 9, 9] print_max_activities(start, finish)
711
"""simple docstring""" SCREAMING_SNAKE_CASE__:Any = """Alexander Joslin""" import operator as op from .stack import Stack def _lowerCamelCase( a ): __a = {"*": op.mul, "/": op.truediv, "+": op.add, "-": op.sub} __a = Stack() __a = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(a ) ) elif i in operators: # RULE 2 operator_stack.push(a ) elif i == ")": # RULE 4 __a = operator_stack.peek() operator_stack.pop() __a = operand_stack.peek() operand_stack.pop() __a = operand_stack.peek() operand_stack.pop() __a = operators[opr](a , a ) operand_stack.push(a ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": SCREAMING_SNAKE_CASE__:Tuple = """(5 + ((4 * 2) * (2 + 3)))""" # answer = 45 print(F'''{equation} = {dijkstras_two_stack_algorithm(equation)}''')
67
0
"""simple docstring""" import inspect import unittest from transformers import SegformerConfig, is_torch_available, is_vision_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_MAPPING, SegformerForImageClassification, SegformerForSemanticSegmentation, SegformerModel, ) from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import SegformerImageProcessor class snake_case__ ( snake_case_ ): def a__ ( self ): __a = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(lowerCamelCase , "hidden_sizes" ) ) self.parent.assertTrue(hasattr(lowerCamelCase , "num_attention_heads" ) ) self.parent.assertTrue(hasattr(lowerCamelCase , "num_encoder_blocks" ) ) class snake_case__ : def __init__( self , lowerCamelCase , lowerCamelCase=13 , lowerCamelCase=64 , lowerCamelCase=3 , lowerCamelCase=4 , lowerCamelCase=[2, 2, 2, 2] , lowerCamelCase=[8, 4, 2, 1] , lowerCamelCase=[16, 32, 64, 128] , lowerCamelCase=[1, 4, 8, 16] , lowerCamelCase=[1, 2, 4, 8] , lowerCamelCase=True , lowerCamelCase=True , lowerCamelCase="gelu" , lowerCamelCase=0.1 , lowerCamelCase=0.1 , lowerCamelCase=0.02 , lowerCamelCase=3 , lowerCamelCase=None , ): __a = parent __a = batch_size __a = image_size __a = num_channels __a = num_encoder_blocks __a = sr_ratios __a = depths __a = hidden_sizes __a = downsampling_rates __a = num_attention_heads __a = is_training __a = use_labels __a = hidden_act __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = initializer_range __a = num_labels __a = scope def a__ ( self ): __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None if self.use_labels: __a = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) __a = self.get_config() return config, pixel_values, labels def a__ ( self ): return SegformerConfig( image_size=self.image_size , num_channels=self.num_channels , num_encoder_blocks=self.num_encoder_blocks , depths=self.depths , hidden_sizes=self.hidden_sizes , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , initializer_range=self.initializer_range , ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = SegformerModel(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase ) __a = __a = self.image_size // (self.downsampling_rates[-1] * 2) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], expected_height, expected_width) ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = self.num_labels __a = SegformerForSemanticSegmentation(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) ) __a = model(lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4) ) self.parent.assertGreater(result.loss , 0.0 ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = 1 __a = SegformerForSemanticSegmentation(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = torch.randint(0 , 1 , (self.batch_size, self.image_size, self.image_size) ).to(lowerCamelCase ) __a = model(lowerCamelCase , labels=lowerCamelCase ) self.parent.assertGreater(result.loss , 0.0 ) def a__ ( self ): __a = self.prepare_config_and_inputs() __a , __a , __a = config_and_inputs __a = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class snake_case__ ( snake_case_, snake_case_, unittest.TestCase ): _snake_case : List[str] = ( ( SegformerModel, SegformerForSemanticSegmentation, SegformerForImageClassification, ) if is_torch_available() else () ) _snake_case : Union[str, Any] = ( { """feature-extraction""": SegformerModel, """image-classification""": SegformerForImageClassification, """image-segmentation""": SegformerForSemanticSegmentation, } if is_torch_available() else {} ) _snake_case : int = True _snake_case : int = False _snake_case : Any = False _snake_case : int = False def a__ ( self ): __a = SegformerModelTester(self ) __a = SegformerConfigTester(self , config_class=lowerCamelCase ) def a__ ( self ): self.config_tester.run_common_tests() def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_binary_image_segmentation(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_segmentation(*lowerCamelCase ) @unittest.skip("SegFormer does not use inputs_embeds" ) def a__ ( self ): pass @unittest.skip("SegFormer does not have get_input_embeddings method and get_output_embeddings methods" ) def a__ ( self ): pass def a__ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(lowerCamelCase ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowerCamelCase ) def a__ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() __a = True for model_class in self.all_model_classes: __a = True __a = False __a = True __a = model_class(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(lowerCamelCase , lowerCamelCase ) ) __a = outputs.attentions __a = sum(self.model_tester.depths ) self.assertEqual(len(lowerCamelCase ) , lowerCamelCase ) # check that output_attentions also work using config del inputs_dict["output_attentions"] __a = True __a = model_class(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(lowerCamelCase , lowerCamelCase ) ) __a = outputs.attentions self.assertEqual(len(lowerCamelCase ) , lowerCamelCase ) # verify the first attentions (first block, first layer) __a = (self.model_tester.image_size // 4) ** 2 __a = (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2 self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len] , ) # verify the last attentions (last block, last layer) __a = (self.model_tester.image_size // 32) ** 2 __a = (self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2 self.assertListEqual( list(attentions[-1].shape[-3:] ) , [self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len] , ) __a = len(lowerCamelCase ) # Check attention is always last and order is fine __a = True __a = True __a = model_class(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(lowerCamelCase , lowerCamelCase ) ) self.assertEqual(out_len + 1 , len(lowerCamelCase ) ) __a = outputs.attentions self.assertEqual(len(lowerCamelCase ) , lowerCamelCase ) # verify the first attentions (first block, first layer) __a = (self.model_tester.image_size // 4) ** 2 __a = (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2 self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len] , ) def a__ ( self ): def check_hidden_states_output(lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = model_class(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() with torch.no_grad(): __a = model(**self._prepare_for_class(lowerCamelCase , lowerCamelCase ) ) __a = outputs.hidden_states __a = self.model_tester.num_encoder_blocks self.assertEqual(len(lowerCamelCase ) , lowerCamelCase ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.hidden_sizes[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = True check_hidden_states_output(lowerCamelCase , lowerCamelCase , lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __a = True check_hidden_states_output(lowerCamelCase , lowerCamelCase , lowerCamelCase ) def a__ ( self ): if not self.model_tester.is_training: return __a , __a = self.model_tester.prepare_config_and_inputs_for_common() __a = True for model_class in self.all_model_classes: if model_class in get_values(lowerCamelCase ): continue __a = model_class(lowerCamelCase ) model.to(lowerCamelCase ) model.train() __a = self._prepare_for_class(lowerCamelCase , lowerCamelCase , return_labels=lowerCamelCase ) __a = model(**lowerCamelCase ).loss loss.backward() @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def a__ ( self ): pass @slow def a__ ( self ): for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = SegformerModel.from_pretrained(lowerCamelCase ) self.assertIsNotNone(lowerCamelCase ) def _lowerCamelCase( ): __a = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch class snake_case__ ( unittest.TestCase ): @slow def a__ ( self ): # only resize + normalize __a = SegformerImageProcessor( image_scale=(512, 512) , keep_ratio=lowerCamelCase , align=lowerCamelCase , do_random_crop=lowerCamelCase ) __a = SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512" ).to( lowerCamelCase ) __a = prepare_img() __a = image_processor(images=lowerCamelCase , return_tensors="pt" ) __a = encoded_inputs.pixel_values.to(lowerCamelCase ) with torch.no_grad(): __a = model(lowerCamelCase ) __a = torch.Size((1, model.config.num_labels, 128, 128) ) self.assertEqual(outputs.logits.shape , lowerCamelCase ) __a = torch.tensor( [ [[-4.6310, -5.5232, -6.2356], [-5.1921, -6.1444, -6.5996], [-5.4424, -6.2790, -6.7574]], [[-12.1391, -13.3122, -13.9554], [-12.8732, -13.9352, -14.3563], [-12.9438, -13.8226, -14.2513]], [[-12.5134, -13.4686, -14.4915], [-12.8669, -14.4343, -14.7758], [-13.2523, -14.5819, -15.0694]], ] ).to(lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3] , lowerCamelCase , atol=1E-4 ) ) @slow def a__ ( self ): # only resize + normalize __a = SegformerImageProcessor( image_scale=(512, 512) , keep_ratio=lowerCamelCase , align=lowerCamelCase , do_random_crop=lowerCamelCase ) __a = SegformerForSemanticSegmentation.from_pretrained( "nvidia/segformer-b1-finetuned-cityscapes-1024-1024" ).to(lowerCamelCase ) __a = prepare_img() __a = image_processor(images=lowerCamelCase , return_tensors="pt" ) __a = encoded_inputs.pixel_values.to(lowerCamelCase ) with torch.no_grad(): __a = model(lowerCamelCase ) __a = torch.Size((1, model.config.num_labels, 128, 128) ) self.assertEqual(outputs.logits.shape , lowerCamelCase ) __a = torch.tensor( [ [[-13.5748, -13.9111, -12.6500], [-14.3500, -15.3683, -14.2328], [-14.7532, -16.0424, -15.6087]], [[-17.1651, -15.8725, -12.9653], [-17.2580, -17.3718, -14.8223], [-16.6058, -16.8783, -16.7452]], [[-3.6456, -3.0209, -1.4203], [-3.0797, -3.1959, -2.0000], [-1.8757, -1.9217, -1.6997]], ] ).to(lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3] , lowerCamelCase , atol=1E-1 ) ) @slow def a__ ( self ): # only resize + normalize __a = SegformerImageProcessor( image_scale=(512, 512) , keep_ratio=lowerCamelCase , align=lowerCamelCase , do_random_crop=lowerCamelCase ) __a = SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512" ).to( lowerCamelCase ) __a = prepare_img() __a = image_processor(images=lowerCamelCase , return_tensors="pt" ) __a = encoded_inputs.pixel_values.to(lowerCamelCase ) with torch.no_grad(): __a = model(lowerCamelCase ) __a = outputs.logits.detach().cpu() __a = image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase , target_sizes=[(500, 300)] ) __a = torch.Size((500, 300) ) self.assertEqual(segmentation[0].shape , lowerCamelCase ) __a = image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase ) __a = torch.Size((128, 128) ) self.assertEqual(segmentation[0].shape , lowerCamelCase )
712
"""simple docstring""" from math import pi def _lowerCamelCase( a , a ): return 2 * pi * radius * (angle / 3_6_0) if __name__ == "__main__": print(arc_length(90, 10))
67
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available SCREAMING_SNAKE_CASE__:Dict = { """configuration_xlm""": ["""XLM_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLMConfig""", """XLMOnnxConfig"""], """tokenization_xlm""": ["""XLMTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__:Tuple = [ """XLM_PRETRAINED_MODEL_ARCHIVE_LIST""", """XLMForMultipleChoice""", """XLMForQuestionAnswering""", """XLMForQuestionAnsweringSimple""", """XLMForSequenceClassification""", """XLMForTokenClassification""", """XLMModel""", """XLMPreTrainedModel""", """XLMWithLMHeadModel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__:Dict = [ """TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFXLMForMultipleChoice""", """TFXLMForQuestionAnsweringSimple""", """TFXLMForSequenceClassification""", """TFXLMForTokenClassification""", """TFXLMMainLayer""", """TFXLMModel""", """TFXLMPreTrainedModel""", """TFXLMWithLMHeadModel""", ] if TYPE_CHECKING: from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig from .tokenization_xlm import XLMTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlm import ( XLM_PRETRAINED_MODEL_ARCHIVE_LIST, XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMPreTrainedModel, XLMWithLMHeadModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlm import ( TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLMForMultipleChoice, TFXLMForQuestionAnsweringSimple, TFXLMForSequenceClassification, TFXLMForTokenClassification, TFXLMMainLayer, TFXLMModel, TFXLMPreTrainedModel, TFXLMWithLMHeadModel, ) else: import sys SCREAMING_SNAKE_CASE__:Optional[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
713
"""simple docstring""" from typing import Dict, Iterable, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging SCREAMING_SNAKE_CASE__:List[str] = logging.get_logger(__name__) class snake_case__ ( snake_case_ ): _snake_case : Dict = ["""pixel_values"""] def __init__( self , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = PILImageResampling.BICUBIC , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = True , lowerCamelCase = 1 / 255 , lowerCamelCase = True , lowerCamelCase = IMAGENET_DEFAULT_MEAN , lowerCamelCase = IMAGENET_DEFAULT_STD , **lowerCamelCase , ): super().__init__(**lowerCamelCase ) __a = size if size is not None else {"shortest_edge": 224} __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) __a = crop_size if crop_size is not None else {"height": 224, "width": 224} __a = get_size_dict(lowerCamelCase , param_name="crop_size" ) __a = do_resize __a = size __a = resample __a = do_center_crop __a = crop_size __a = do_rescale __a = rescale_factor __a = do_normalize __a = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN __a = image_std if image_std is not None else IMAGENET_DEFAULT_STD def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = PILImageResampling.BICUBIC , lowerCamelCase = None , **lowerCamelCase , ): __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) # size_dict is a dict with either keys "height" and "width" or "shortest_edge" if "shortest_edge" in size: __a = int((256 / 224) * size["shortest_edge"] ) __a = get_resize_output_image_size(lowerCamelCase , size=lowerCamelCase , default_to_square=lowerCamelCase ) __a = {"height": output_size[0], "width": output_size[1]} if "height" not in size_dict or "width" not in size_dict: raise ValueError( F"Size dict must have keys 'height' and 'width' or 'shortest_edge'. Got {size_dict.keys()}" ) return resize( lowerCamelCase , size=(size_dict["height"], size_dict["width"]) , resample=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): __a = get_size_dict(lowerCamelCase ) if "height" not in size or "width" not in size: raise ValueError(F"Size dict must have keys 'height' and 'width'. Got {size.keys()}" ) return center_crop(lowerCamelCase , size=(size["height"], size["width"]) , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): return rescale(lowerCamelCase , scale=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): return normalize(lowerCamelCase , mean=lowerCamelCase , std=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = ChannelDimension.FIRST , **lowerCamelCase , ): __a = do_resize if do_resize is not None else self.do_resize __a = resample if resample is not None else self.resample __a = do_center_crop if do_center_crop is not None else self.do_center_crop __a = do_rescale if do_rescale is not None else self.do_rescale __a = rescale_factor if rescale_factor is not None else self.rescale_factor __a = do_normalize if do_normalize is not None else self.do_normalize __a = image_mean if image_mean is not None else self.image_mean __a = image_std if image_std is not None else self.image_std __a = size if size is not None else self.size __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) __a = crop_size if crop_size is not None else self.crop_size __a = get_size_dict(lowerCamelCase , param_name="crop_size" ) __a = make_list_of_images(lowerCamelCase ) if not valid_images(lowerCamelCase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) if do_resize and size is None: raise ValueError("Size must be specified if do_resize is True." ) if do_center_crop and crop_size is None: raise ValueError("Crop size must be specified if do_center_crop is True." ) if do_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("Image mean and std must be specified if do_normalize is True." ) # All transformations expect numpy arrays. __a = [to_numpy_array(lowerCamelCase ) for image in images] if do_resize: __a = [self.resize(lowerCamelCase , lowerCamelCase , lowerCamelCase ) for image in images] if do_center_crop: __a = [self.center_crop(lowerCamelCase , lowerCamelCase ) for image in images] if do_rescale: __a = [self.rescale(lowerCamelCase , lowerCamelCase ) for image in images] if do_normalize: __a = [self.normalize(lowerCamelCase , lowerCamelCase , lowerCamelCase ) for image in images] __a = [to_channel_dimension_format(lowerCamelCase , lowerCamelCase ) for image in images] __a = {"pixel_values": images} return BatchFeature(data=lowerCamelCase , tensor_type=lowerCamelCase )
67
0
"""simple docstring""" import os def _lowerCamelCase( ): __a = os.path.dirname(os.path.realpath(a ) ) __a = os.path.join(a , "triangle.txt" ) with open(a ) as f: __a = f.readlines() __a = [] for line in triangle: __a = [] for number in line.strip().split(" " ): numbers_from_line.append(int(a ) ) a.append(a ) for i in range(1 , len(a ) ): for j in range(len(a[i] ) ): __a = a[i - 1][j] if j != len(a[i - 1] ) else 0 __a = a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(a , a ) return max(a[-1] ) if __name__ == "__main__": print(solution())
714
"""simple docstring""" import inspect import unittest from transformers import ViTConfig 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 ViTForImageClassification, ViTForMaskedImageModeling, ViTModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class snake_case__ : 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=None , lowerCamelCase=2 , ): __a = parent __a = batch_size __a = image_size __a = patch_size __a = num_channels __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 = encoder_stride # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) __a = (image_size // patch_size) ** 2 __a = num_patches + 1 def a__ ( self ): __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = self.get_config() return config, pixel_values, labels def a__ ( self ): return ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=lowerCamelCase , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = ViTModel(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = ViTForMaskedImageModeling(config=lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images __a = 1 __a = ViTForMaskedImageModeling(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __a = model(lowerCamelCase ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = self.type_sequence_label_size __a = ViTForImageClassification(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = model(lowerCamelCase , labels=lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __a = 1 __a = ViTForImageClassification(lowerCamelCase ) model.to(lowerCamelCase ) model.eval() __a = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __a = model(lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a__ ( self ): __a = self.prepare_config_and_inputs() ( ( __a ) , ( __a ) , ( __a ) , ) = config_and_inputs __a = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class snake_case__ ( snake_case_, snake_case_, unittest.TestCase ): _snake_case : Any = ( ( ViTModel, ViTForImageClassification, ViTForMaskedImageModeling, ) if is_torch_available() else () ) _snake_case : List[Any] = ( {"""feature-extraction""": ViTModel, """image-classification""": ViTForImageClassification} if is_torch_available() else {} ) _snake_case : int = True _snake_case : int = False _snake_case : str = False _snake_case : Optional[Any] = False def a__ ( self ): __a = ViTModelTester(self ) __a = ConfigTester(self , config_class=lowerCamelCase , has_text_modality=lowerCamelCase , hidden_size=37 ) def a__ ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="ViT does not use inputs_embeds" ) def a__ ( self ): pass def a__ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) __a = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCamelCase , nn.Linear ) ) def a__ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(lowerCamelCase ) __a = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase ) @slow def a__ ( self ): for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __a = ViTModel.from_pretrained(lowerCamelCase ) self.assertIsNotNone(lowerCamelCase ) def _lowerCamelCase( ): __a = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class snake_case__ ( unittest.TestCase ): @cached_property def a__ ( self ): return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224" ) if is_vision_available() else None @slow def a__ ( self ): __a = ViTForImageClassification.from_pretrained("google/vit-base-patch16-224" ).to(lowerCamelCase ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase ) # forward pass with torch.no_grad(): __a = model(**lowerCamelCase ) # verify the logits __a = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , lowerCamelCase ) __a = torch.tensor([-0.2744, 0.8215, -0.0836] ).to(lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCamelCase , atol=1E-4 ) ) @slow def a__ ( self ): # ViT models have an `interpolate_pos_encoding` argument in their forward method, # allowing to interpolate the pre-trained position embeddings in order to use # the model on higher resolutions. The DINO model by Facebook AI leverages this # to visualize self-attention on higher resolution images. __a = ViTModel.from_pretrained("facebook/dino-vits8" ).to(lowerCamelCase ) __a = ViTImageProcessor.from_pretrained("facebook/dino-vits8" , size=480 ) __a = prepare_img() __a = image_processor(images=lowerCamelCase , return_tensors="pt" ) __a = inputs.pixel_values.to(lowerCamelCase ) # forward pass with torch.no_grad(): __a = model(lowerCamelCase , interpolate_pos_encoding=lowerCamelCase ) # verify the logits __a = torch.Size((1, 3601, 384) ) self.assertEqual(outputs.last_hidden_state.shape , lowerCamelCase ) __a = torch.tensor( [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]] ).to(lowerCamelCase ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , lowerCamelCase , atol=1E-4 ) ) @slow @require_accelerate @require_torch_gpu def a__ ( self ): __a = ViTModel.from_pretrained("facebook/dino-vits8" , torch_dtype=torch.floataa , device_map="auto" ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=lowerCamelCase , return_tensors="pt" ) __a = inputs.pixel_values.to(lowerCamelCase ) # forward pass to make sure inference works in fp16 with torch.no_grad(): __a = model(lowerCamelCase )
67
0
"""simple docstring""" from __future__ import annotations def _lowerCamelCase( a , a ): # Checks if the entire collection has been sorted if len(a ) <= 1 or n <= 1: return insert_next(a , n - 1 ) rec_insertion_sort(a , n - 1 ) def _lowerCamelCase( a , a ): # Checks order between adjacent elements if index >= len(a ) or collection[index - 1] <= collection[index]: return # Swaps adjacent elements since they are not in ascending order __a , __a = ( collection[index], collection[index - 1], ) insert_next(a , index + 1 ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__:int = input("""Enter integers separated by spaces: """) SCREAMING_SNAKE_CASE__:list[int] = [int(num) for num in numbers.split()] rec_insertion_sort(number_list, len(number_list)) print(number_list)
715
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetaImageProcessor class snake_case__ ( unittest.TestCase ): def __init__( self , lowerCamelCase , lowerCamelCase=7 , lowerCamelCase=3 , lowerCamelCase=30 , lowerCamelCase=400 , lowerCamelCase=True , lowerCamelCase=None , lowerCamelCase=True , lowerCamelCase=[0.5, 0.5, 0.5] , lowerCamelCase=[0.5, 0.5, 0.5] , lowerCamelCase=True , lowerCamelCase=1 / 255 , lowerCamelCase=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __a = size if size is not None else {"shortest_edge": 18, "longest_edge": 1333} __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 a__ ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def a__ ( self , lowerCamelCase , lowerCamelCase=False ): if not batched: __a = image_inputs[0] if isinstance(lowerCamelCase , Image.Image ): __a , __a = image.size else: __a , __a = image.shape[1], image.shape[2] if w < h: __a = int(self.size["shortest_edge"] * h / w ) __a = self.size["shortest_edge"] elif w > h: __a = self.size["shortest_edge"] __a = int(self.size["shortest_edge"] * w / h ) else: __a = self.size["shortest_edge"] __a = self.size["shortest_edge"] else: __a = [] for image in image_inputs: __a , __a = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __a = max(lowerCamelCase , key=lambda lowerCamelCase : item[0] )[0] __a = max(lowerCamelCase , key=lambda lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case__ ( snake_case_, unittest.TestCase ): _snake_case : List[Any] = DetaImageProcessor if is_vision_available() else None def a__ ( self ): __a = DetaImageProcessingTester(self ) @property def a__ ( self ): return self.image_processor_tester.prepare_image_processor_dict() def a__ ( self ): __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_rescale" ) ) self.assertTrue(hasattr(lowerCamelCase , "do_pad" ) ) self.assertTrue(hasattr(lowerCamelCase , "size" ) ) def a__ ( self ): __a = 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 , lowerCamelCase ) def a__ ( self ): pass def a__ ( self ): # 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 __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) __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, expected_height, expected_width, ) , ) def a__ ( self ): # 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 __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def a__ ( self ): # 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 __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __a = image_processing(lowerCamelCase , return_tensors="pt" ).pixel_values __a , __a = self.image_processor_tester.get_expected_values(lowerCamelCase , batched=lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def a__ ( self ): # prepare image and target __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": 39769, "annotations": target} # encode them __a = DetaImageProcessor() __a = image_processing(images=lowerCamelCase , annotations=lowerCamelCase , return_tensors="pt" ) # verify pixel values __a = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase ) __a = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase , atol=1E-4 ) ) # verify area __a = 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"] , lowerCamelCase ) ) # verify boxes __a = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase ) __a = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase , atol=1E-3 ) ) # verify image_id __a = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase ) ) # verify is_crowd __a = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase ) ) # verify class_labels __a = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase ) ) # verify orig_size __a = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase ) ) # verify size __a = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase ) ) @slow def a__ ( self ): # prepare image, target and masks_path __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": 39769, "segments_info": target} __a = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them __a = DetaImageProcessor(format="coco_panoptic" ) __a = image_processing(images=lowerCamelCase , annotations=lowerCamelCase , masks_path=lowerCamelCase , return_tensors="pt" ) # verify pixel values __a = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["pixel_values"].shape , lowerCamelCase ) __a = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , lowerCamelCase , atol=1E-4 ) ) # verify area __a = 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"] , lowerCamelCase ) ) # verify boxes __a = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , lowerCamelCase ) __a = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , lowerCamelCase , atol=1E-3 ) ) # verify image_id __a = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , lowerCamelCase ) ) # verify is_crowd __a = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , lowerCamelCase ) ) # verify class_labels __a = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , lowerCamelCase ) ) # verify masks __a = 822873 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , lowerCamelCase ) # verify orig_size __a = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , lowerCamelCase ) ) # verify size __a = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , lowerCamelCase ) )
67
0
"""simple docstring""" from __future__ import annotations import inspect import unittest from transformers import ViTConfig 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 TFViTForImageClassification, TFViTModel if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class UpperCamelCase : def __init__( self , lowerCamelCase , lowerCamelCase=13 , lowerCamelCase=30 , lowerCamelCase=2 , lowerCamelCase=3 , lowerCamelCase=True , lowerCamelCase=True , lowerCamelCase=32 , lowerCamelCase=2 , lowerCamelCase=4 , lowerCamelCase=37 , lowerCamelCase="gelu" , lowerCamelCase=0.1 , lowerCamelCase=0.1 , lowerCamelCase=10 , lowerCamelCase=0.02 , lowerCamelCase=3 , lowerCamelCase=None , ): __a = parent __a = batch_size __a = image_size __a = patch_size __a = num_channels __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 # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) __a = (image_size // patch_size) ** 2 __a = num_patches + 1 def a__ ( self ): __a = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __a = None if self.use_labels: __a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __a = self.get_config() return config, pixel_values, labels def a__ ( self ): return ViTConfig( 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 , ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = TFViTModel(config=lowerCamelCase ) __a = model(lowerCamelCase , training=lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) # Test with an image with different size than the one specified in config. __a = self.image_size // 2 __a = pixel_values[:, :, :image_size, :image_size] __a = model(lowerCamelCase , interpolate_pos_encoding=lowerCamelCase , training=lowerCamelCase ) __a = (image_size // self.patch_size) ** 2 + 1 self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, seq_length, self.hidden_size) ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase ): __a = self.type_sequence_label_size __a = TFViTForImageClassification(lowerCamelCase ) __a = model(lowerCamelCase , labels=lowerCamelCase , training=lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # Test with an image with different size than the one specified in config. __a = self.image_size // 2 __a = pixel_values[:, :, :image_size, :image_size] __a = model(lowerCamelCase , interpolate_pos_encoding=lowerCamelCase , training=lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images __a = 1 __a = TFViTForImageClassification(lowerCamelCase ) __a = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __a = model(lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def a__ ( self ): __a = self.prepare_config_and_inputs() __a , __a , __a = config_and_inputs __a = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class UpperCamelCase ( snake_case_, snake_case_, unittest.TestCase ): _snake_case : str = (TFViTModel, TFViTForImageClassification) if is_tf_available() else () _snake_case : Any = ( {"""feature-extraction""": TFViTModel, """image-classification""": TFViTForImageClassification} if is_tf_available() else {} ) _snake_case : str = False _snake_case : Optional[Any] = False _snake_case : List[Any] = False def a__ ( self ): __a = TFViTModelTester(self ) __a = ConfigTester(self , config_class=lowerCamelCase , has_text_modality=lowerCamelCase , hidden_size=37 ) def a__ ( self ): self.config_tester.run_common_tests() @unittest.skip(reason="ViT does not use inputs_embeds" ) def a__ ( self ): pass @unittest.skip(reason="ViT does not use inputs_embeds" ) def a__ ( self ): pass def a__ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (tf.keras.layers.Layer) ) __a = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowerCamelCase , tf.keras.layers.Layer ) ) def a__ ( self ): __a , __a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __a = model_class(lowerCamelCase ) __a = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __a = [*signature.parameters.keys()] __a = ["pixel_values"] self.assertListEqual(arg_names[:1] , lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowerCamelCase ) def a__ ( self ): __a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*lowerCamelCase ) @slow def a__ ( self ): __a = TFViTModel.from_pretrained("google/vit-base-patch16-224" ) self.assertIsNotNone(lowerCamelCase ) def _lowerCamelCase( ): __a = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class UpperCamelCase ( unittest.TestCase ): @cached_property def a__ ( self ): return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224" ) if is_vision_available() else None @slow def a__ ( self ): __a = TFViTForImageClassification.from_pretrained("google/vit-base-patch16-224" ) __a = self.default_image_processor __a = prepare_img() __a = image_processor(images=lowerCamelCase , return_tensors="tf" ) # forward pass __a = model(**lowerCamelCase ) # verify the logits __a = tf.TensorShape((1, 1000) ) self.assertEqual(outputs.logits.shape , lowerCamelCase ) __a = tf.constant([-0.2744, 0.8215, -0.0836] ) tf.debugging.assert_near(outputs.logits[0, :3] , lowerCamelCase , atol=1E-4 )
716
"""simple docstring""" import argparse import logging import sys from unittest.mock import patch import run_glue_deebert from transformers.testing_utils import TestCasePlus, get_gpu_count, require_torch_non_multi_gpu, slow logging.basicConfig(level=logging.DEBUG) SCREAMING_SNAKE_CASE__:Dict = logging.getLogger() def _lowerCamelCase( ): __a = argparse.ArgumentParser() parser.add_argument("-f" ) __a = parser.parse_args() return args.f class snake_case__ ( snake_case_ ): def a__ ( self ): __a = logging.StreamHandler(sys.stdout ) logger.addHandler(lowerCamelCase ) def a__ ( self , lowerCamelCase ): __a = get_gpu_count() if n_gpu > 1: pass # XXX: doesn't quite work with n_gpu > 1 https://github.com/huggingface/transformers/issues/10560 # script = f"{self.examples_dir_str}/research_projects/deebert/run_glue_deebert.py" # distributed_args = f"-m torch.distributed.launch --nproc_per_node={n_gpu} {script}".split() # cmd = [sys.executable] + distributed_args + args # execute_subprocess_async(cmd, env=self.get_env()) # XXX: test the results - need to save them first into .json file else: args.insert(0 , "run_glue_deebert.py" ) with patch.object(lowerCamelCase , "argv" , lowerCamelCase ): __a = run_glue_deebert.main() for value in result.values(): self.assertGreaterEqual(lowerCamelCase , 0.666 ) @slow @require_torch_non_multi_gpu def a__ ( self ): __a = "\n --model_type roberta\n --model_name_or_path roberta-base\n --task_name MRPC\n --do_train\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --max_seq_length 128\n --per_gpu_eval_batch_size=1\n --per_gpu_train_batch_size=8\n --learning_rate 2e-4\n --num_train_epochs 3\n --overwrite_output_dir\n --seed 42\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --save_steps 0\n --overwrite_cache\n --eval_after_first_stage\n ".split() self.run_and_check(lowerCamelCase ) __a = "\n --model_type roberta\n --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --task_name MRPC\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --max_seq_length 128\n --eval_each_highway\n --eval_highway\n --overwrite_cache\n --per_gpu_eval_batch_size=1\n ".split() self.run_and_check(lowerCamelCase ) __a = "\n --model_type roberta\n --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --task_name MRPC\n --do_eval\n --do_lower_case\n --data_dir ./tests/fixtures/tests_samples/MRPC/\n --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n --plot_data_dir ./examples/deebert/results/\n --max_seq_length 128\n --early_exit_entropy 0.1\n --eval_highway\n --overwrite_cache\n --per_gpu_eval_batch_size=1\n ".split() self.run_and_check(lowerCamelCase )
67
0
import json from typing import Iterator, List, Union from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers from tokenizers.implementations.base_tokenizer import BaseTokenizer from tokenizers.models import Unigram from tokenizers.processors import TemplateProcessing class snake_case__ ( snake_case_ ): def __init__( self , lowerCamelCase = "▁" , lowerCamelCase = True , lowerCamelCase = "<unk>" , lowerCamelCase = "</s>" , lowerCamelCase = "<pad>" , ): __a = { "pad": {"id": 0, "token": pad_token}, "eos": {"id": 1, "token": eos_token}, "unk": {"id": 2, "token": unk_token}, } __a = [None] * len(self.special_tokens ) for token_dict in self.special_tokens.values(): __a = token_dict["token"] __a = Tokenizer(Unigram() ) __a = normalizers.Sequence( [ normalizers.Nmt(), normalizers.NFKC(), normalizers.Replace(Regex(" {2,}" ) , " " ), normalizers.Lowercase(), ] ) __a = pre_tokenizers.Sequence( [ pre_tokenizers.Metaspace(replacement=lowerCamelCase , add_prefix_space=lowerCamelCase ), pre_tokenizers.Digits(individual_digits=lowerCamelCase ), pre_tokenizers.Punctuation(), ] ) __a = decoders.Metaspace(replacement=lowerCamelCase , add_prefix_space=lowerCamelCase ) __a = TemplateProcessing( single=F"$A {self.special_tokens['eos']['token']}" , special_tokens=[(self.special_tokens["eos"]["token"], self.special_tokens["eos"]["id"])] , ) __a = { "model": "SentencePieceUnigram", "replacement": replacement, "add_prefix_space": add_prefix_space, } super().__init__(lowerCamelCase , lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase = 8000 , lowerCamelCase = True , ): __a = trainers.UnigramTrainer( vocab_size=lowerCamelCase , special_tokens=self.special_tokens_list , show_progress=lowerCamelCase , ) if isinstance(lowerCamelCase , lowerCamelCase ): __a = [files] self._tokenizer.train(lowerCamelCase , trainer=lowerCamelCase ) self.add_unk_id() def a__ ( self , lowerCamelCase , lowerCamelCase = 8000 , lowerCamelCase = True , ): __a = trainers.UnigramTrainer( vocab_size=lowerCamelCase , special_tokens=self.special_tokens_list , show_progress=lowerCamelCase , ) self._tokenizer.train_from_iterator(lowerCamelCase , trainer=lowerCamelCase ) self.add_unk_id() def a__ ( self ): __a = json.loads(self._tokenizer.to_str() ) __a = self.special_tokens["unk"]["id"] __a = Tokenizer.from_str(json.dumps(lowerCamelCase ) )
717
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, 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 SCREAMING_SNAKE_CASE__:Union[str, Any] = logging.get_logger(__name__) if is_vision_available(): import PIL class snake_case__ ( snake_case_ ): _snake_case : Optional[Any] = ["""pixel_values"""] def __init__( self , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = PILImageResampling.BICUBIC , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = True , lowerCamelCase = 1 / 255 , lowerCamelCase = True , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = True , **lowerCamelCase , ): super().__init__(**lowerCamelCase ) __a = size if size is not None else {"shortest_edge": 224} __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) __a = crop_size if crop_size is not None else {"height": 224, "width": 224} __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase , param_name="crop_size" ) __a = do_resize __a = size __a = resample __a = do_center_crop __a = crop_size __a = do_rescale __a = rescale_factor __a = do_normalize __a = image_mean if image_mean is not None else OPENAI_CLIP_MEAN __a = image_std if image_std is not None else OPENAI_CLIP_STD __a = do_convert_rgb def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = PILImageResampling.BICUBIC , lowerCamelCase = None , **lowerCamelCase , ): __a = get_size_dict(lowerCamelCase , default_to_square=lowerCamelCase ) if "shortest_edge" not in size: raise ValueError(F"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}" ) __a = get_resize_output_image_size(lowerCamelCase , size=size["shortest_edge"] , default_to_square=lowerCamelCase ) return resize(lowerCamelCase , size=lowerCamelCase , resample=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): __a = get_size_dict(lowerCamelCase ) 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(lowerCamelCase , size=(size["height"], size["width"]) , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): return rescale(lowerCamelCase , scale=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase = None , **lowerCamelCase , ): return normalize(lowerCamelCase , mean=lowerCamelCase , std=lowerCamelCase , data_format=lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = None , lowerCamelCase = ChannelDimension.FIRST , **lowerCamelCase , ): __a = do_resize if do_resize is not None else self.do_resize __a = size if size is not None else self.size __a = get_size_dict(lowerCamelCase , param_name="size" , default_to_square=lowerCamelCase ) __a = resample if resample is not None else self.resample __a = do_center_crop if do_center_crop is not None else self.do_center_crop __a = crop_size if crop_size is not None else self.crop_size __a = get_size_dict(lowerCamelCase , param_name="crop_size" , default_to_square=lowerCamelCase ) __a = do_rescale if do_rescale is not None else self.do_rescale __a = rescale_factor if rescale_factor is not None else self.rescale_factor __a = do_normalize if do_normalize is not None else self.do_normalize __a = image_mean if image_mean is not None else self.image_mean __a = image_std if image_std is not None else self.image_std __a = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __a = make_list_of_images(lowerCamelCase ) if not valid_images(lowerCamelCase ): raise ValueError( "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, " "torch.Tensor, tf.Tensor or jax.ndarray." ) 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: __a = [convert_to_rgb(lowerCamelCase ) for image in images] # All transformations expect numpy arrays. __a = [to_numpy_array(lowerCamelCase ) for image in images] if do_resize: __a = [self.resize(image=lowerCamelCase , size=lowerCamelCase , resample=lowerCamelCase ) for image in images] if do_center_crop: __a = [self.center_crop(image=lowerCamelCase , size=lowerCamelCase ) for image in images] if do_rescale: __a = [self.rescale(image=lowerCamelCase , scale=lowerCamelCase ) for image in images] if do_normalize: __a = [self.normalize(image=lowerCamelCase , mean=lowerCamelCase , std=lowerCamelCase ) for image in images] __a = [to_channel_dimension_format(lowerCamelCase , lowerCamelCase ) for image in images] __a = {"pixel_values": images} return BatchFeature(data=lowerCamelCase , tensor_type=lowerCamelCase )
67
0
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__:Dict = logging.get_logger(__name__) def _lowerCamelCase( a ): __a = DPTConfig(embedding_type="hybrid" ) if "large" in checkpoint_url: __a = 1_0_2_4 __a = 4_0_9_6 __a = 2_4 __a = 1_6 __a = [5, 1_1, 1_7, 2_3] __a = [2_5_6, 5_1_2, 1_0_2_4, 1_0_2_4] __a = (1, 3_8_4, 3_8_4) if "nyu" or "midas" in checkpoint_url: __a = 7_6_8 __a = [1, 1, 1, 0.5] __a = [2_5_6, 5_1_2, 7_6_8, 7_6_8] __a = 1_5_0 __a = 1_6 __a = (1, 3_8_4, 3_8_4) __a = False __a = "project" if "ade" in checkpoint_url: __a = True __a = 7_6_8 __a = [1, 1, 1, 0.5] __a = 1_5_0 __a = 1_6 __a = "huggingface/label-files" __a = "ade20k-id2label.json" __a = json.load(open(cached_download(hf_hub_url(a , a , repo_type="dataset" ) ) , "r" ) ) __a = {int(a ): v for k, v in idalabel.items()} __a = idalabel __a = {v: k for k, v in idalabel.items()} __a = [1, 1_5_0, 4_8_0, 4_8_0] return config, expected_shape def _lowerCamelCase( a ): __a = ["pretrained.model.head.weight", "pretrained.model.head.bias"] for k in ignore_keys: state_dict.pop(a , a ) def _lowerCamelCase( a ): if ( "pretrained.model" in name and "cls_token" not in name and "pos_embed" not in name and "patch_embed" not in name ): __a = name.replace("pretrained.model" , "dpt.encoder" ) if "pretrained.model" in name: __a = name.replace("pretrained.model" , "dpt.embeddings" ) if "patch_embed" in name: __a = name.replace("patch_embed" , "" ) if "pos_embed" in name: __a = name.replace("pos_embed" , "position_embeddings" ) if "attn.proj" in name: __a = name.replace("attn.proj" , "attention.output.dense" ) if "proj" in name and "project" not in name: __a = name.replace("proj" , "projection" ) if "blocks" in name: __a = name.replace("blocks" , "layer" ) 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 "norm1" in name and "backbone" not in name: __a = name.replace("norm1" , "layernorm_before" ) if "norm2" in name and "backbone" not in name: __a = name.replace("norm2" , "layernorm_after" ) if "scratch.output_conv" in name: __a = name.replace("scratch.output_conv" , "head" ) if "scratch" in name: __a = name.replace("scratch" , "neck" ) if "layer1_rn" in name: __a = name.replace("layer1_rn" , "convs.0" ) if "layer2_rn" in name: __a = name.replace("layer2_rn" , "convs.1" ) if "layer3_rn" in name: __a = name.replace("layer3_rn" , "convs.2" ) if "layer4_rn" in name: __a = name.replace("layer4_rn" , "convs.3" ) if "refinenet" in name: __a = int(name[len("neck.refinenet" ) : len("neck.refinenet" ) + 1] ) # tricky here: we need to map 4 to 0, 3 to 1, 2 to 2 and 1 to 3 __a = name.replace(F"refinenet{layer_idx}" , F"fusion_stage.layers.{abs(layer_idx-4 )}" ) if "out_conv" in name: __a = name.replace("out_conv" , "projection" ) if "resConfUnit1" in name: __a = name.replace("resConfUnit1" , "residual_layer1" ) if "resConfUnit2" in name: __a = name.replace("resConfUnit2" , "residual_layer2" ) if "conv1" in name: __a = name.replace("conv1" , "convolution1" ) if "conv2" in name: __a = name.replace("conv2" , "convolution2" ) # readout blocks if "pretrained.act_postprocess1.0.project.0" in name: __a = name.replace("pretrained.act_postprocess1.0.project.0" , "neck.reassemble_stage.readout_projects.0.0" ) if "pretrained.act_postprocess2.0.project.0" in name: __a = name.replace("pretrained.act_postprocess2.0.project.0" , "neck.reassemble_stage.readout_projects.1.0" ) if "pretrained.act_postprocess3.0.project.0" in name: __a = name.replace("pretrained.act_postprocess3.0.project.0" , "neck.reassemble_stage.readout_projects.2.0" ) if "pretrained.act_postprocess4.0.project.0" in name: __a = name.replace("pretrained.act_postprocess4.0.project.0" , "neck.reassemble_stage.readout_projects.3.0" ) # resize blocks if "pretrained.act_postprocess1.3" in name: __a = name.replace("pretrained.act_postprocess1.3" , "neck.reassemble_stage.layers.0.projection" ) if "pretrained.act_postprocess1.4" in name: __a = name.replace("pretrained.act_postprocess1.4" , "neck.reassemble_stage.layers.0.resize" ) if "pretrained.act_postprocess2.3" in name: __a = name.replace("pretrained.act_postprocess2.3" , "neck.reassemble_stage.layers.1.projection" ) if "pretrained.act_postprocess2.4" in name: __a = name.replace("pretrained.act_postprocess2.4" , "neck.reassemble_stage.layers.1.resize" ) if "pretrained.act_postprocess3.3" in name: __a = name.replace("pretrained.act_postprocess3.3" , "neck.reassemble_stage.layers.2.projection" ) if "pretrained.act_postprocess4.3" in name: __a = name.replace("pretrained.act_postprocess4.3" , "neck.reassemble_stage.layers.3.projection" ) if "pretrained.act_postprocess4.4" in name: __a = name.replace("pretrained.act_postprocess4.4" , "neck.reassemble_stage.layers.3.resize" ) if "pretrained" in name: __a = name.replace("pretrained" , "dpt" ) if "bn" in name: __a = name.replace("bn" , "batch_norm" ) if "head" in name: __a = name.replace("head" , "head.head" ) if "encoder.norm" in name: __a = name.replace("encoder.norm" , "layernorm" ) if "auxlayer" in name: __a = name.replace("auxlayer" , "auxiliary_head.head" ) if "backbone" in name: __a = name.replace("backbone" , "backbone.bit.encoder" ) if ".." in name: __a = name.replace(".." , "." ) if "stem.conv" in name: __a = name.replace("stem.conv" , "bit.embedder.convolution" ) if "blocks" in name: __a = name.replace("blocks" , "layers" ) if "convolution" in name and "backbone" in name: __a = name.replace("convolution" , "conv" ) if "layer" in name and "backbone" in name: __a = name.replace("layer" , "layers" ) if "backbone.bit.encoder.bit" in name: __a = name.replace("backbone.bit.encoder.bit" , "backbone.bit" ) if "embedder.conv" in name: __a = name.replace("embedder.conv" , "embedder.convolution" ) if "backbone.bit.encoder.stem.norm" in name: __a = name.replace("backbone.bit.encoder.stem.norm" , "backbone.bit.embedder.norm" ) return name def _lowerCamelCase( a , a ): for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) __a = state_dict.pop(F"dpt.encoder.layer.{i}.attn.qkv.weight" ) __a = state_dict.pop(F"dpt.encoder.layer.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict __a = in_proj_weight[: config.hidden_size, :] __a = in_proj_bias[: config.hidden_size] __a = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] __a = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] __a = in_proj_weight[ -config.hidden_size :, : ] __a = in_proj_bias[-config.hidden_size :] def _lowerCamelCase( ): __a = "http://images.cocodataset.org/val2017/000000039769.jpg" __a = Image.open(requests.get(a , stream=a ).raw ) return im @torch.no_grad() def _lowerCamelCase( a , a , a , a , a ): __a , __a = get_dpt_config(a ) # load original state_dict from URL # state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu") __a = torch.load(a , map_location="cpu" ) # remove certain keys remove_ignore_keys_(a ) # rename keys for key in state_dict.copy().keys(): __a = state_dict.pop(a ) __a = val # read in qkv matrices read_in_q_k_v(a , a ) # load HuggingFace model __a = DPTForSemanticSegmentation(a ) if "ade" in checkpoint_url else DPTForDepthEstimation(a ) model.load_state_dict(a ) model.eval() # Check outputs on an image __a = 4_8_0 if "ade" in checkpoint_url else 3_8_4 __a = DPTImageProcessor(size=a ) __a = prepare_img() __a = image_processor(a , return_tensors="pt" ) # forward pass __a = model(**a ).logits if "ade" in checkpoint_url else model(**a ).predicted_depth if show_prediction: __a = ( torch.nn.functional.interpolate( outputs.unsqueeze(1 ) , size=(image.size[1], image.size[0]) , mode="bicubic" , align_corners=a , ) .squeeze() .cpu() .numpy() ) Image.fromarray((prediction / prediction.max()) * 2_5_5 ).show() if pytorch_dump_folder_path is not None: Path(a ).mkdir(exist_ok=a ) print(F"Saving model to {pytorch_dump_folder_path}" ) model.save_pretrained(a ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(a ) if push_to_hub: model.push_to_hub("ybelkada/dpt-hybrid-midas" ) image_processor.push_to_hub("ybelkada/dpt-hybrid-midas" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__:Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( """--checkpoint_url""", default="""https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt""", type=str, help="""URL of the original DPT checkpoint you'd like to convert.""", ) parser.add_argument( """--pytorch_dump_folder_path""", default=None, type=str, required=False, help="""Path to the output PyTorch model directory.""", ) parser.add_argument( """--push_to_hub""", action="""store_true""", ) parser.add_argument( """--model_name""", default="""dpt-large""", type=str, help="""Name of the model, in case you're pushing to the hub.""", ) parser.add_argument( """--show_prediction""", action="""store_true""", ) SCREAMING_SNAKE_CASE__:List[str] = parser.parse_args() convert_dpt_checkpoint( args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name, args.show_prediction )
718
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation SCREAMING_SNAKE_CASE__:List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Any = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} SCREAMING_SNAKE_CASE__:Optional[Any] = { """vocab_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/vocab.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/vocab.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/vocab.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/vocab.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/vocab.json""", }, """merges_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/merges.txt""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/merges.txt""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/merges.txt""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/merges.txt""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/merges.txt""", }, """tokenizer_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/tokenizer.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/tokenizer.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/tokenizer.json""", }, } SCREAMING_SNAKE_CASE__:Union[str, Any] = { """gpt2""": 1024, """gpt2-medium""": 1024, """gpt2-large""": 1024, """gpt2-xl""": 1024, """distilgpt2""": 1024, } class snake_case__ ( snake_case_ ): _snake_case : Tuple = VOCAB_FILES_NAMES _snake_case : str = PRETRAINED_VOCAB_FILES_MAP _snake_case : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _snake_case : List[str] = ["""input_ids""", """attention_mask"""] _snake_case : Dict = GPTaTokenizer def __init__( self , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase="<|endoftext|>" , lowerCamelCase="<|endoftext|>" , lowerCamelCase="<|endoftext|>" , lowerCamelCase=False , **lowerCamelCase , ): super().__init__( lowerCamelCase , lowerCamelCase , tokenizer_file=lowerCamelCase , unk_token=lowerCamelCase , bos_token=lowerCamelCase , eos_token=lowerCamelCase , add_prefix_space=lowerCamelCase , **lowerCamelCase , ) __a = kwargs.pop("add_bos_token" , lowerCamelCase ) __a = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , lowerCamelCase ) != add_prefix_space: __a = getattr(lowerCamelCase , pre_tok_state.pop("type" ) ) __a = add_prefix_space __a = pre_tok_class(**lowerCamelCase ) __a = add_prefix_space def a__ ( self , *lowerCamelCase , **lowerCamelCase ): __a = kwargs.get("is_split_into_words" , lowerCamelCase ) assert self.add_prefix_space or not is_split_into_words, ( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*lowerCamelCase , **lowerCamelCase ) def a__ ( self , *lowerCamelCase , **lowerCamelCase ): __a = kwargs.get("is_split_into_words" , lowerCamelCase ) assert self.add_prefix_space or not is_split_into_words, ( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._encode_plus(*lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase = None ): __a = self._tokenizer.model.save(lowerCamelCase , name=lowerCamelCase ) return tuple(lowerCamelCase ) def a__ ( self , lowerCamelCase ): __a = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowerCamelCase , add_special_tokens=lowerCamelCase ) + [self.eos_token_id] ) if len(lowerCamelCase ) > self.model_max_length: __a = input_ids[-self.model_max_length :] return input_ids
67
0
from __future__ import annotations from typing import Any def _lowerCamelCase( a ): create_state_space_tree(a , [] , 0 ) def _lowerCamelCase( a , a , a ): if index == len(a ): print(a ) return create_state_space_tree(a , a , index + 1 ) current_subsequence.append(sequence[index] ) create_state_space_tree(a , a , index + 1 ) current_subsequence.pop() if __name__ == "__main__": SCREAMING_SNAKE_CASE__:list[Any] = [3, 1, 2, 4] generate_all_subsequences(seq) seq.clear() seq.extend(["""A""", """B""", """C"""]) generate_all_subsequences(seq)
719
"""simple docstring""" from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize("repo_id" , ["canonical_dataset_name", "org-name/dataset-name"] ) @pytest.mark.parametrize("path" , ["filename.csv", "filename with blanks.csv"] ) @pytest.mark.parametrize("revision" , [None, "v2"] ) def _lowerCamelCase( a , a , a ): __a = hf_hub_url(repo_id=a , path=a , revision=a ) assert url == F"https://huggingface.co/datasets/{repo_id}/resolve/{revision or 'main'}/{quote(a )}"
67
0
"""simple docstring""" import torch from torch import nn from transformers import CLIPPreTrainedModel, CLIPVisionModel from ...models.attention import BasicTransformerBlock from ...utils import logging SCREAMING_SNAKE_CASE__:str = logging.get_logger(__name__) # pylint: disable=invalid-name class snake_case__ ( snake_case_ ): def __init__( self , lowerCamelCase , lowerCamelCase=768 ): super().__init__(lowerCamelCase ) __a = proj_size __a = CLIPVisionModel(lowerCamelCase ) __a = PaintByExampleMapper(lowerCamelCase ) __a = nn.LayerNorm(config.hidden_size ) __a = nn.Linear(config.hidden_size , self.proj_size ) # uncondition for scaling __a = nn.Parameter(torch.randn((1, 1, self.proj_size) ) ) def a__ ( self , lowerCamelCase , lowerCamelCase=False ): __a = self.model(pixel_values=lowerCamelCase ) __a = clip_output.pooler_output __a = self.mapper(latent_states[:, None] ) __a = self.final_layer_norm(lowerCamelCase ) __a = self.proj_out(lowerCamelCase ) if return_uncond_vector: return latent_states, self.uncond_vector return latent_states class snake_case__ ( nn.Module ): def __init__( self , lowerCamelCase ): super().__init__() __a = (config.num_hidden_layers + 1) // 5 __a = config.hidden_size __a = 1 __a = nn.ModuleList( [ BasicTransformerBlock(lowerCamelCase , lowerCamelCase , lowerCamelCase , activation_fn="gelu" , attention_bias=lowerCamelCase ) for _ in range(lowerCamelCase ) ] ) def a__ ( self , lowerCamelCase ): for block in self.blocks: __a = block(lowerCamelCase ) return hidden_states
720
"""simple docstring""" from __future__ import annotations def _lowerCamelCase( a , a , a ): if len(a ) == 0: raise ValueError("find_max() arg is an empty sequence" ) if ( left >= len(a ) or left < -len(a ) or right >= len(a ) or right < -len(a ) ): raise IndexError("list index out of range" ) if left == right: return nums[left] __a = (left + right) >> 1 # the middle __a = find_max(a , a , a ) # find max in range[left, mid] __a = find_max(a , mid + 1 , a ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
67
0
"""simple docstring""" 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() SCREAMING_SNAKE_CASE__:Any = logging.get_logger(__name__) def _lowerCamelCase( a , a=False ): __a = [] 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" __a = [(pair[0], pair[1][4:]) if pair[1].startswith("vit" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("norm.weight", "vit.layernorm.weight"), ("norm.bias", "vit.layernorm.bias"), ("head.weight", "classifier.weight"), ("head.bias", "classifier.bias"), ] ) return rename_keys def _lowerCamelCase( a , a , a=False ): for i in range(config.num_hidden_layers ): if base_model: __a = "" else: __a = "vit." # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) __a = state_dict.pop(F"blocks.{i}.attn.qkv.weight" ) __a = state_dict.pop(F"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict __a = in_proj_weight[ : config.hidden_size, : ] __a = in_proj_bias[: config.hidden_size] __a = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] __a = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] __a = in_proj_weight[ -config.hidden_size :, : ] __a = in_proj_bias[-config.hidden_size :] def _lowerCamelCase( a ): __a = ["head.weight", "head.bias"] for k in ignore_keys: state_dict.pop(a , a ) def _lowerCamelCase( a , a , a ): __a = dct.pop(a ) __a = val def _lowerCamelCase( ): __a = "http://images.cocodataset.org/val2017/000000039769.jpg" __a = Image.open(requests.get(a , stream=a ).raw ) return im @torch.no_grad() def _lowerCamelCase( a , a , a=True ): __a = ViTConfig() # patch_size if model_name[-1] == "8": __a = 8 # set labels if required if not base_model: __a = 1_0_0_0 __a = "huggingface/label-files" __a = "imagenet-1k-id2label.json" __a = json.load(open(hf_hub_download(a , a , repo_type="dataset" ) , "r" ) ) __a = {int(a ): v for k, v in idalabel.items()} __a = idalabel __a = {v: k for k, v in idalabel.items()} # size of the architecture if model_name in ["dino_vits8", "dino_vits16"]: __a = 3_8_4 __a = 1_5_3_6 __a = 1_2 __a = 6 # load original model from torch hub __a = torch.hub.load("facebookresearch/dino:main" , a ) original_model.eval() # load state_dict of original model, remove and rename some keys __a = original_model.state_dict() if base_model: remove_classification_head_(a ) __a = create_rename_keys(a , base_model=a ) for src, dest in rename_keys: rename_key(a , a , a ) read_in_q_k_v(a , a , a ) # load HuggingFace model if base_model: __a = ViTModel(a , add_pooling_layer=a ).eval() else: __a = ViTForImageClassification(a ).eval() model.load_state_dict(a ) # Check outputs on an image, prepared by ViTImageProcessor __a = ViTImageProcessor() __a = image_processor(images=prepare_img() , return_tensors="pt" ) __a = encoding["pixel_values"] __a = model(a ) if base_model: __a = original_model(a ) assert torch.allclose(a , outputs.last_hidden_state[:, 0, :] , atol=1E-1 ) else: __a = original_model(a ) assert logits.shape == outputs.logits.shape assert torch.allclose(a , outputs.logits , atol=1E-3 ) Path(a ).mkdir(exist_ok=a ) print(F"Saving model {model_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(a ) print(F"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(a ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__:Dict = 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) SCREAMING_SNAKE_CASE__:Optional[Any] = parser.parse_args() convert_vit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.base_model)
721
"""simple docstring""" from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__:List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Tuple = { """google/bigbird-roberta-base""": """https://huggingface.co/google/bigbird-roberta-base/resolve/main/config.json""", """google/bigbird-roberta-large""": """https://huggingface.co/google/bigbird-roberta-large/resolve/main/config.json""", """google/bigbird-base-trivia-itc""": """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/config.json""", # See all BigBird models at https://huggingface.co/models?filter=big_bird } class snake_case__ ( snake_case_ ): _snake_case : Any = """big_bird""" def __init__( self , lowerCamelCase=50358 , lowerCamelCase=768 , lowerCamelCase=12 , lowerCamelCase=12 , lowerCamelCase=3072 , lowerCamelCase="gelu_new" , lowerCamelCase=0.1 , lowerCamelCase=0.1 , lowerCamelCase=4096 , lowerCamelCase=2 , lowerCamelCase=0.02 , lowerCamelCase=1E-12 , lowerCamelCase=True , lowerCamelCase=0 , lowerCamelCase=1 , lowerCamelCase=2 , lowerCamelCase=66 , lowerCamelCase="block_sparse" , lowerCamelCase=True , lowerCamelCase=False , lowerCamelCase=64 , lowerCamelCase=3 , lowerCamelCase=None , **lowerCamelCase , ): super().__init__( pad_token_id=lowerCamelCase , bos_token_id=lowerCamelCase , eos_token_id=lowerCamelCase , sep_token_id=lowerCamelCase , **lowerCamelCase , ) __a = vocab_size __a = max_position_embeddings __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 = initializer_range __a = type_vocab_size __a = layer_norm_eps __a = use_cache __a = rescale_embeddings __a = attention_type __a = use_bias __a = block_size __a = num_random_blocks __a = classifier_dropout class snake_case__ ( snake_case_ ): @property def a__ ( self ): 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), ] )
67
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__:Dict = {"""configuration_timm_backbone""": ["""TimmBackboneConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__:Optional[Any] = ["""TimmBackbone"""] if TYPE_CHECKING: from .configuration_timm_backbone import TimmBackboneConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timm_backbone import TimmBackbone else: import sys SCREAMING_SNAKE_CASE__:List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
700
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation SCREAMING_SNAKE_CASE__:Optional[int] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Optional[int] = {"""tokenizer_file""": """tokenizer.json"""} SCREAMING_SNAKE_CASE__:Tuple = { """tokenizer_file""": { """bigscience/tokenizer""": """https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json""", """bigscience/bloom-560m""": """https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json""", """bigscience/bloom-1b1""": """https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json""", """bigscience/bloom-1b7""": """https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json""", """bigscience/bloom-3b""": """https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json""", """bigscience/bloom-7b1""": """https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json""", """bigscience/bloom""": """https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json""", }, } class snake_case__ ( snake_case_ ): _snake_case : Optional[Any] = VOCAB_FILES_NAMES _snake_case : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP _snake_case : Optional[int] = ["""input_ids""", """attention_mask"""] _snake_case : Optional[int] = None def __init__( self , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase="<unk>" , lowerCamelCase="<s>" , lowerCamelCase="</s>" , lowerCamelCase="<pad>" , lowerCamelCase=False , lowerCamelCase=False , **lowerCamelCase , ): super().__init__( lowerCamelCase , lowerCamelCase , tokenizer_file=lowerCamelCase , unk_token=lowerCamelCase , bos_token=lowerCamelCase , eos_token=lowerCamelCase , pad_token=lowerCamelCase , add_prefix_space=lowerCamelCase , clean_up_tokenization_spaces=lowerCamelCase , **lowerCamelCase , ) __a = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , lowerCamelCase ) != add_prefix_space: __a = getattr(lowerCamelCase , pre_tok_state.pop("type" ) ) __a = add_prefix_space __a = pre_tok_class(**lowerCamelCase ) __a = add_prefix_space def a__ ( self , *lowerCamelCase , **lowerCamelCase ): __a = kwargs.get("is_split_into_words" , lowerCamelCase ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with" " pretokenized inputs." ) return super()._batch_encode_plus(*lowerCamelCase , **lowerCamelCase ) def a__ ( self , *lowerCamelCase , **lowerCamelCase ): __a = kwargs.get("is_split_into_words" , lowerCamelCase ) if not (self.add_prefix_space or not is_split_into_words): raise Exception( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with" " pretokenized inputs." ) return super()._encode_plus(*lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase = None ): __a = self._tokenizer.model.save(lowerCamelCase , name=lowerCamelCase ) return tuple(lowerCamelCase ) def a__ ( self , lowerCamelCase ): __a = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowerCamelCase , add_special_tokens=lowerCamelCase ) + [self.eos_token_id] ) if len(lowerCamelCase ) > self.model_max_length: __a = input_ids[-self.model_max_length :] return input_ids
67
0
"""simple docstring""" import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def _lowerCamelCase( a ): __a = args.pruning_method __a = args.threshold __a = args.model_name_or_path.rstrip("/" ) __a = args.target_model_path print(F"Load fine-pruned model from {model_name_or_path}" ) __a = torch.load(os.path.join(a , "pytorch_model.bin" ) ) __a = {} for name, tensor in model.items(): if "embeddings" in name or "LayerNorm" in name or "pooler" in name: __a = tensor print(F"Copied layer {name}" ) elif "classifier" in name or "qa_output" in name: __a = tensor print(F"Copied layer {name}" ) elif "bias" in name: __a = tensor print(F"Copied layer {name}" ) else: if pruning_method == "magnitude": __a = MagnitudeBinarizer.apply(inputs=a , threshold=a ) __a = tensor * mask print(F"Pruned layer {name}" ) elif pruning_method == "topK": if "mask_scores" in name: continue __a = name[:-6] __a = model[F"{prefix_}mask_scores"] __a = TopKBinarizer.apply(a , a ) __a = tensor * mask print(F"Pruned layer {name}" ) elif pruning_method == "sigmoied_threshold": if "mask_scores" in name: continue __a = name[:-6] __a = model[F"{prefix_}mask_scores"] __a = ThresholdBinarizer.apply(a , a , a ) __a = tensor * mask print(F"Pruned layer {name}" ) elif pruning_method == "l0": if "mask_scores" in name: continue __a = name[:-6] __a = model[F"{prefix_}mask_scores"] __a , __a = -0.1, 1.1 __a = torch.sigmoid(a ) __a = s * (r - l) + l __a = s_bar.clamp(min=0.0 , max=1.0 ) __a = tensor * mask print(F"Pruned layer {name}" ) else: raise ValueError("Unknown pruning method" ) if target_model_path is None: __a = os.path.join( os.path.dirname(a ) , F"bertarized_{os.path.basename(a )}" ) if not os.path.isdir(a ): shutil.copytree(a , a ) print(F"\nCreated folder {target_model_path}" ) torch.save(a , os.path.join(a , "pytorch_model.bin" ) ) print("\nPruned model saved! See you later!" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__:Union[str, Any] = argparse.ArgumentParser() parser.add_argument( """--pruning_method""", choices=["""l0""", """magnitude""", """topK""", """sigmoied_threshold"""], type=str, required=True, help=( """Pruning Method (l0 = L0 regularization, magnitude = Magnitude pruning, topK = Movement pruning,""" """ sigmoied_threshold = Soft movement pruning)""" ), ) parser.add_argument( """--threshold""", type=float, required=False, help=( """For `magnitude` and `topK`, it is the level of remaining weights (in %) in the fine-pruned model.""" """For `sigmoied_threshold`, it is the threshold \tau against which the (sigmoied) scores are compared.""" """Not needed for `l0`""" ), ) parser.add_argument( """--model_name_or_path""", type=str, required=True, help="""Folder containing the model that was previously fine-pruned""", ) parser.add_argument( """--target_model_path""", default=None, type=str, required=False, help="""Folder containing the model that was previously fine-pruned""", ) SCREAMING_SNAKE_CASE__:List[Any] = parser.parse_args() main(args)
701
"""simple docstring""" from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class snake_case__ : _snake_case : torch.Tensor # [batch_size x 3] _snake_case : torch.Tensor # [batch_size x 3] _snake_case : torch.Tensor # [batch_size x 3] _snake_case : torch.Tensor # [batch_size x 3] _snake_case : int _snake_case : int _snake_case : float _snake_case : float _snake_case : Tuple[int] def a__ ( self ): assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def a__ ( self ): return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def a__ ( self ): return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def a__ ( self ): __a = torch.arange(self.height * self.width ) __a = torch.stack( [ pixel_indices % self.width, torch.div(lowerCamelCase , self.width , rounding_mode="trunc" ), ] , axis=1 , ) return coords @property def a__ ( self ): __a , *__a = self.shape __a = int(np.prod(lowerCamelCase ) ) __a = self.get_image_coords() __a = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) __a = self.get_camera_rays(lowerCamelCase ) __a = rays.view(lowerCamelCase , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def a__ ( self , lowerCamelCase ): __a , *__a , __a = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] __a = coords.view(lowerCamelCase , -1 , 2 ) __a = self.resolution() __a = self.fov() __a = (flat.float() / (res - 1)) * 2 - 1 __a = fracs * torch.tan(fov / 2 ) __a = fracs.view(lowerCamelCase , -1 , 2 ) __a = ( self.z.view(lowerCamelCase , 1 , 3 ) + self.x.view(lowerCamelCase , 1 , 3 ) * fracs[:, :, :1] + self.y.view(lowerCamelCase , 1 , 3 ) * fracs[:, :, 1:] ) __a = directions / directions.norm(dim=-1 , keepdim=lowerCamelCase ) __a = torch.stack( [ torch.broadcast_to(self.origin.view(lowerCamelCase , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(lowerCamelCase , *lowerCamelCase , 2 , 3 ) def a__ ( self , lowerCamelCase , lowerCamelCase ): assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=lowerCamelCase , height=lowerCamelCase , x_fov=self.x_fov , y_fov=self.y_fov , ) def _lowerCamelCase( a ): __a = [] __a = [] __a = [] __a = [] for theta in np.linspace(0 , 2 * np.pi , num=2_0 ): __a = np.array([np.sin(a ), np.cos(a ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) __a = -z * 4 __a = np.array([np.cos(a ), -np.sin(a ), 0.0] ) __a = np.cross(a , a ) origins.append(a ) xs.append(a ) ys.append(a ) zs.append(a ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(a , axis=0 ) ).float() , x=torch.from_numpy(np.stack(a , axis=0 ) ).float() , y=torch.from_numpy(np.stack(a , axis=0 ) ).float() , z=torch.from_numpy(np.stack(a , axis=0 ) ).float() , width=a , height=a , x_fov=0.7 , y_fov=0.7 , shape=(1, len(a )) , )
67
0
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation SCREAMING_SNAKE_CASE__:List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__:Any = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} SCREAMING_SNAKE_CASE__:Optional[Any] = { """vocab_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/vocab.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/vocab.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/vocab.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/vocab.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/vocab.json""", }, """merges_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/merges.txt""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/merges.txt""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/merges.txt""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/merges.txt""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/merges.txt""", }, """tokenizer_file""": { """gpt2""": """https://huggingface.co/gpt2/resolve/main/tokenizer.json""", """gpt2-medium""": """https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json""", """gpt2-large""": """https://huggingface.co/gpt2-large/resolve/main/tokenizer.json""", """gpt2-xl""": """https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json""", """distilgpt2""": """https://huggingface.co/distilgpt2/resolve/main/tokenizer.json""", }, } SCREAMING_SNAKE_CASE__:Union[str, Any] = { """gpt2""": 1024, """gpt2-medium""": 1024, """gpt2-large""": 1024, """gpt2-xl""": 1024, """distilgpt2""": 1024, } class snake_case__ ( snake_case_ ): _snake_case : Tuple = VOCAB_FILES_NAMES _snake_case : str = PRETRAINED_VOCAB_FILES_MAP _snake_case : List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _snake_case : List[str] = ["""input_ids""", """attention_mask"""] _snake_case : Dict = GPTaTokenizer def __init__( self , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase="<|endoftext|>" , lowerCamelCase="<|endoftext|>" , lowerCamelCase="<|endoftext|>" , lowerCamelCase=False , **lowerCamelCase , ): super().__init__( lowerCamelCase , lowerCamelCase , tokenizer_file=lowerCamelCase , unk_token=lowerCamelCase , bos_token=lowerCamelCase , eos_token=lowerCamelCase , add_prefix_space=lowerCamelCase , **lowerCamelCase , ) __a = kwargs.pop("add_bos_token" , lowerCamelCase ) __a = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , lowerCamelCase ) != add_prefix_space: __a = getattr(lowerCamelCase , pre_tok_state.pop("type" ) ) __a = add_prefix_space __a = pre_tok_class(**lowerCamelCase ) __a = add_prefix_space def a__ ( self , *lowerCamelCase , **lowerCamelCase ): __a = kwargs.get("is_split_into_words" , lowerCamelCase ) assert self.add_prefix_space or not is_split_into_words, ( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*lowerCamelCase , **lowerCamelCase ) def a__ ( self , *lowerCamelCase , **lowerCamelCase ): __a = kwargs.get("is_split_into_words" , lowerCamelCase ) assert self.add_prefix_space or not is_split_into_words, ( F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True " "to use it with pretokenized inputs." ) return super()._encode_plus(*lowerCamelCase , **lowerCamelCase ) def a__ ( self , lowerCamelCase , lowerCamelCase = None ): __a = self._tokenizer.model.save(lowerCamelCase , name=lowerCamelCase ) return tuple(lowerCamelCase ) def a__ ( self , lowerCamelCase ): __a = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(lowerCamelCase , add_special_tokens=lowerCamelCase ) + [self.eos_token_id] ) if len(lowerCamelCase ) > self.model_max_length: __a = input_ids[-self.model_max_length :] return input_ids
702
"""simple docstring""" def _lowerCamelCase( a ): return 1 if digit in (0, 1) else (digit * factorial(digit - 1 )) def _lowerCamelCase( a ): __a = 0 __a = number while duplicate > 0: __a , __a = divmod(a , 1_0 ) fact_sum += factorial(a ) return fact_sum == number if __name__ == "__main__": print("""Program to check whether a number is a Krisnamurthy Number or not.""") SCREAMING_SNAKE_CASE__:Optional[Any] = int(input("""Enter number: """).strip()) print( F'''{number} is {'' if krishnamurthy(number) else 'not '}a Krishnamurthy Number.''' )
67
0