code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
import argparse import json import os from tensorflow.core.protobuf.saved_model_pba import SavedModel # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_copies.py __a : Optional[Any] = """.""" # Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model) __a : str = [ """Assert""", """AssignVariableOp""", """EmptyTensorList""", """MergeV2Checkpoints""", """ReadVariableOp""", """ResourceGather""", """RestoreV2""", """SaveV2""", """ShardedFilename""", """StatefulPartitionedCall""", """StaticRegexFullMatch""", """VarHandleOp""", ] def UpperCAmelCase ( lowercase , lowercase , lowercase ): """simple docstring""" __lowercase = SavedModel() __lowercase = [] with open(os.path.join(lowercase , '''utils''' , '''tf_ops''' , '''onnx.json''' ) ) as f: __lowercase = json.load(lowercase )['''opsets'''] for i in range(1 , opset + 1 ): onnx_ops.extend(onnx_opsets[str(lowercase )] ) with open(lowercase , '''rb''' ) as f: saved_model.ParseFromString(f.read() ) __lowercase = set() # Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs) for meta_graph in saved_model.meta_graphs: # Add operations in the graph definition model_op_names.update(node.op for node in meta_graph.graph_def.node ) # Go through the functions in the graph definition for func in meta_graph.graph_def.library.function: # Add operations in each function model_op_names.update(node.op for node in func.node_def ) # Convert to list, sorted if you want __lowercase = sorted(lowercase ) __lowercase = [] for op in model_op_names: if op not in onnx_ops and op not in INTERNAL_OPS: incompatible_ops.append(lowercase ) if strict and len(lowercase ) > 0: raise Exception(F"Found the following incompatible ops for the opset {opset}:\n" + incompatible_ops ) elif len(lowercase ) > 0: print(F"Found the following incompatible ops for the opset {opset}:" ) print(*lowercase , sep='''\n''' ) else: print(F"The saved model {saved_model_path} can properly be converted with ONNX." ) if __name__ == "__main__": __a : List[Any] = argparse.ArgumentParser() parser.add_argument("""--saved_model_path""", help="""Path of the saved model to check (the .pb file).""") parser.add_argument( """--opset""", default=1_2, type=int, help="""The ONNX opset against which the model has to be tested.""" ) parser.add_argument( """--framework""", choices=["""onnx"""], default="""onnx""", help="""Frameworks against which to test the saved model.""" ) parser.add_argument( """--strict""", action="""store_true""", help="""Whether make the checking strict (raise errors) or not (raise warnings)""" ) __a : int = parser.parse_args() if args.framework == "onnx": onnx_compliancy(args.saved_model_path, args.strict, args.opset)
210
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __a : Any = { """configuration_bloom""": ["""BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP""", """BloomConfig""", """BloomOnnxConfig"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a : Optional[int] = ["""BloomTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a : str = [ """BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST""", """BloomForCausalLM""", """BloomModel""", """BloomPreTrainedModel""", """BloomForSequenceClassification""", """BloomForTokenClassification""", """BloomForQuestionAnswering""", ] if TYPE_CHECKING: from .configuration_bloom import BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP, BloomConfig, BloomOnnxConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bloom_fast import BloomTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bloom import ( BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST, BloomForCausalLM, BloomForQuestionAnswering, BloomForSequenceClassification, BloomForTokenClassification, BloomModel, BloomPreTrainedModel, ) else: import sys __a : Dict = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
210
1
"""simple docstring""" 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 __a ( lowerCAmelCase__ ): SCREAMING_SNAKE_CASE__ : "DiagonalGaussianDistribution" class __a ( lowerCAmelCase__ , lowerCAmelCase__ ): SCREAMING_SNAKE_CASE__ : Any = True @register_to_config def __init__( self , a__ = 3 , a__ = 3 , a__ = ("DownEncoderBlock2D",) , a__ = ("UpDecoderBlock2D",) , a__ = (64,) , a__ = 1 , a__ = "silu" , a__ = 4 , a__ = 32 , a__ = 32 , a__ = 0.18215 , ): super().__init__() # pass init params to Encoder _lowerCamelCase = 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 _lowerCamelCase = 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__ , ) _lowerCamelCase = nn.Convad(2 * latent_channels , 2 * latent_channels , 1 ) _lowerCamelCase = nn.Convad(a__ , a__ , 1 ) _lowerCamelCase = False _lowerCamelCase = False # only relevant if vae tiling is enabled _lowerCamelCase = self.config.sample_size _lowerCamelCase = ( self.config.sample_size[0] if isinstance(self.config.sample_size , (list, tuple) ) else self.config.sample_size ) _lowerCamelCase = int(sample_size / (2 ** (len(self.config.block_out_channels ) - 1)) ) _lowerCamelCase = 0.25 def snake_case_ ( self , a__ , a__=False ): if isinstance(a__ , (Encoder, Decoder) ): _lowerCamelCase = value def snake_case_ ( self , a__ = True ): _lowerCamelCase = use_tiling def snake_case_ ( self ): self.enable_tiling(a__ ) def snake_case_ ( self ): _lowerCamelCase = True def snake_case_ ( self ): _lowerCamelCase = False @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def snake_case_ ( self ): _lowerCamelCase = {} def fn_recursive_add_processors(a__ , a__ , a__ ): if hasattr(a__ , 'set_processor' ): _lowerCamelCase = 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 snake_case_ ( self , a__ ): _lowerCamelCase = len(self.attn_processors.keys() ) if isinstance(a__ , a__ ) and len(a__ ) != count: raise ValueError( F'A dict of processors was passed, but the number of processors {len(a__ )} does not match the' F' number of attention layers: {count}. Please make sure to pass {count} processor classes.' ) def fn_recursive_attn_processor(a__ , a__ , a__ ): if hasattr(a__ , 'set_processor' ): if not isinstance(a__ , a__ ): module.set_processor(a__ ) else: module.set_processor(processor.pop(F'{name}.processor' ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(F'{name}.{sub_name}' , a__ , a__ ) for name, module in self.named_children(): fn_recursive_attn_processor(a__ , a__ , a__ ) def snake_case_ ( self ): self.set_attn_processor(AttnProcessor() ) @apply_forward_hook def snake_case_ ( self , a__ , a__ = 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: _lowerCamelCase = [self.encoder(a__ ) for x_slice in x.split(1 )] _lowerCamelCase = torch.cat(a__ ) else: _lowerCamelCase = self.encoder(a__ ) _lowerCamelCase = self.quant_conv(a__ ) _lowerCamelCase = DiagonalGaussianDistribution(a__ ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=a__ ) def snake_case_ ( self , a__ , a__ = 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__ ) _lowerCamelCase = self.post_quant_conv(a__ ) _lowerCamelCase = self.decoder(a__ ) if not return_dict: return (dec,) return DecoderOutput(sample=a__ ) @apply_forward_hook def snake_case_ ( self , a__ , a__ = True ): if self.use_slicing and z.shape[0] > 1: _lowerCamelCase = [self._decode(a__ ).sample for z_slice in z.split(1 )] _lowerCamelCase = torch.cat(a__ ) else: _lowerCamelCase = self._decode(a__ ).sample if not return_dict: return (decoded,) return DecoderOutput(sample=a__ ) def snake_case_ ( self , a__ , a__ , a__ ): _lowerCamelCase = min(a.shape[2] , b.shape[2] , a__ ) for y in range(a__ ): _lowerCamelCase = a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent) return b def snake_case_ ( self , a__ , a__ , a__ ): _lowerCamelCase = min(a.shape[3] , b.shape[3] , a__ ) for x in range(a__ ): _lowerCamelCase = a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent) return b def snake_case_ ( self , a__ , a__ = True ): _lowerCamelCase = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor) ) _lowerCamelCase = int(self.tile_latent_min_size * self.tile_overlap_factor ) _lowerCamelCase = self.tile_latent_min_size - blend_extent # Split the image into 512x512 tiles and encode them separately. _lowerCamelCase = [] for i in range(0 , x.shape[2] , a__ ): _lowerCamelCase = [] for j in range(0 , x.shape[3] , a__ ): _lowerCamelCase = x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size] _lowerCamelCase = self.encoder(a__ ) _lowerCamelCase = self.quant_conv(a__ ) row.append(a__ ) rows.append(a__ ) _lowerCamelCase = [] for i, row in enumerate(a__ ): _lowerCamelCase = [] 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: _lowerCamelCase = self.blend_v(rows[i - 1][j] , a__ , a__ ) if j > 0: _lowerCamelCase = self.blend_h(row[j - 1] , a__ , a__ ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(a__ , dim=3 ) ) _lowerCamelCase = torch.cat(a__ , dim=2 ) _lowerCamelCase = DiagonalGaussianDistribution(a__ ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=a__ ) def snake_case_ ( self , a__ , a__ = True ): _lowerCamelCase = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor) ) _lowerCamelCase = int(self.tile_sample_min_size * self.tile_overlap_factor ) _lowerCamelCase = 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. _lowerCamelCase = [] for i in range(0 , z.shape[2] , a__ ): _lowerCamelCase = [] for j in range(0 , z.shape[3] , a__ ): _lowerCamelCase = z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size] _lowerCamelCase = self.post_quant_conv(a__ ) _lowerCamelCase = self.decoder(a__ ) row.append(a__ ) rows.append(a__ ) _lowerCamelCase = [] for i, row in enumerate(a__ ): _lowerCamelCase = [] 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: _lowerCamelCase = self.blend_v(rows[i - 1][j] , a__ , a__ ) if j > 0: _lowerCamelCase = self.blend_h(row[j - 1] , a__ , a__ ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(a__ , dim=3 ) ) _lowerCamelCase = torch.cat(a__ , dim=2 ) if not return_dict: return (dec,) return DecoderOutput(sample=a__ ) def snake_case_ ( self , a__ , a__ = False , a__ = True , a__ = None , ): _lowerCamelCase = sample _lowerCamelCase = self.encode(a__ ).latent_dist if sample_posterior: _lowerCamelCase = posterior.sample(generator=a__ ) else: _lowerCamelCase = posterior.mode() _lowerCamelCase = self.decode(a__ ).sample if not return_dict: return (dec,) return DecoderOutput(sample=a__ )
80
"""simple docstring""" 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 __a ( lowerCAmelCase__ ): SCREAMING_SNAKE_CASE__ : "DiagonalGaussianDistribution" class __a ( lowerCAmelCase__ , lowerCAmelCase__ ): SCREAMING_SNAKE_CASE__ : Any = True @register_to_config def __init__( self , a__ = 3 , a__ = 3 , a__ = ("DownEncoderBlock2D",) , a__ = ("UpDecoderBlock2D",) , a__ = (64,) , a__ = 1 , a__ = "silu" , a__ = 4 , a__ = 32 , a__ = 32 , a__ = 0.18215 , ): super().__init__() # pass init params to Encoder _lowerCamelCase = 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 _lowerCamelCase = 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__ , ) _lowerCamelCase = nn.Convad(2 * latent_channels , 2 * latent_channels , 1 ) _lowerCamelCase = nn.Convad(a__ , a__ , 1 ) _lowerCamelCase = False _lowerCamelCase = False # only relevant if vae tiling is enabled _lowerCamelCase = self.config.sample_size _lowerCamelCase = ( self.config.sample_size[0] if isinstance(self.config.sample_size , (list, tuple) ) else self.config.sample_size ) _lowerCamelCase = int(sample_size / (2 ** (len(self.config.block_out_channels ) - 1)) ) _lowerCamelCase = 0.25 def snake_case_ ( self , a__ , a__=False ): if isinstance(a__ , (Encoder, Decoder) ): _lowerCamelCase = value def snake_case_ ( self , a__ = True ): _lowerCamelCase = use_tiling def snake_case_ ( self ): self.enable_tiling(a__ ) def snake_case_ ( self ): _lowerCamelCase = True def snake_case_ ( self ): _lowerCamelCase = False @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def snake_case_ ( self ): _lowerCamelCase = {} def fn_recursive_add_processors(a__ , a__ , a__ ): if hasattr(a__ , 'set_processor' ): _lowerCamelCase = 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 snake_case_ ( self , a__ ): _lowerCamelCase = len(self.attn_processors.keys() ) if isinstance(a__ , a__ ) and len(a__ ) != count: raise ValueError( F'A dict of processors was passed, but the number of processors {len(a__ )} does not match the' F' number of attention layers: {count}. Please make sure to pass {count} processor classes.' ) def fn_recursive_attn_processor(a__ , a__ , a__ ): if hasattr(a__ , 'set_processor' ): if not isinstance(a__ , a__ ): module.set_processor(a__ ) else: module.set_processor(processor.pop(F'{name}.processor' ) ) for sub_name, child in module.named_children(): fn_recursive_attn_processor(F'{name}.{sub_name}' , a__ , a__ ) for name, module in self.named_children(): fn_recursive_attn_processor(a__ , a__ , a__ ) def snake_case_ ( self ): self.set_attn_processor(AttnProcessor() ) @apply_forward_hook def snake_case_ ( self , a__ , a__ = 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: _lowerCamelCase = [self.encoder(a__ ) for x_slice in x.split(1 )] _lowerCamelCase = torch.cat(a__ ) else: _lowerCamelCase = self.encoder(a__ ) _lowerCamelCase = self.quant_conv(a__ ) _lowerCamelCase = DiagonalGaussianDistribution(a__ ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=a__ ) def snake_case_ ( self , a__ , a__ = 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__ ) _lowerCamelCase = self.post_quant_conv(a__ ) _lowerCamelCase = self.decoder(a__ ) if not return_dict: return (dec,) return DecoderOutput(sample=a__ ) @apply_forward_hook def snake_case_ ( self , a__ , a__ = True ): if self.use_slicing and z.shape[0] > 1: _lowerCamelCase = [self._decode(a__ ).sample for z_slice in z.split(1 )] _lowerCamelCase = torch.cat(a__ ) else: _lowerCamelCase = self._decode(a__ ).sample if not return_dict: return (decoded,) return DecoderOutput(sample=a__ ) def snake_case_ ( self , a__ , a__ , a__ ): _lowerCamelCase = min(a.shape[2] , b.shape[2] , a__ ) for y in range(a__ ): _lowerCamelCase = a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent) return b def snake_case_ ( self , a__ , a__ , a__ ): _lowerCamelCase = min(a.shape[3] , b.shape[3] , a__ ) for x in range(a__ ): _lowerCamelCase = a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent) return b def snake_case_ ( self , a__ , a__ = True ): _lowerCamelCase = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor) ) _lowerCamelCase = int(self.tile_latent_min_size * self.tile_overlap_factor ) _lowerCamelCase = self.tile_latent_min_size - blend_extent # Split the image into 512x512 tiles and encode them separately. _lowerCamelCase = [] for i in range(0 , x.shape[2] , a__ ): _lowerCamelCase = [] for j in range(0 , x.shape[3] , a__ ): _lowerCamelCase = x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size] _lowerCamelCase = self.encoder(a__ ) _lowerCamelCase = self.quant_conv(a__ ) row.append(a__ ) rows.append(a__ ) _lowerCamelCase = [] for i, row in enumerate(a__ ): _lowerCamelCase = [] 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: _lowerCamelCase = self.blend_v(rows[i - 1][j] , a__ , a__ ) if j > 0: _lowerCamelCase = self.blend_h(row[j - 1] , a__ , a__ ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(a__ , dim=3 ) ) _lowerCamelCase = torch.cat(a__ , dim=2 ) _lowerCamelCase = DiagonalGaussianDistribution(a__ ) if not return_dict: return (posterior,) return AutoencoderKLOutput(latent_dist=a__ ) def snake_case_ ( self , a__ , a__ = True ): _lowerCamelCase = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor) ) _lowerCamelCase = int(self.tile_sample_min_size * self.tile_overlap_factor ) _lowerCamelCase = 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. _lowerCamelCase = [] for i in range(0 , z.shape[2] , a__ ): _lowerCamelCase = [] for j in range(0 , z.shape[3] , a__ ): _lowerCamelCase = z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size] _lowerCamelCase = self.post_quant_conv(a__ ) _lowerCamelCase = self.decoder(a__ ) row.append(a__ ) rows.append(a__ ) _lowerCamelCase = [] for i, row in enumerate(a__ ): _lowerCamelCase = [] 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: _lowerCamelCase = self.blend_v(rows[i - 1][j] , a__ , a__ ) if j > 0: _lowerCamelCase = self.blend_h(row[j - 1] , a__ , a__ ) result_row.append(tile[:, :, :row_limit, :row_limit] ) result_rows.append(torch.cat(a__ , dim=3 ) ) _lowerCamelCase = torch.cat(a__ , dim=2 ) if not return_dict: return (dec,) return DecoderOutput(sample=a__ ) def snake_case_ ( self , a__ , a__ = False , a__ = True , a__ = None , ): _lowerCamelCase = sample _lowerCamelCase = self.encode(a__ ).latent_dist if sample_posterior: _lowerCamelCase = posterior.sample(generator=a__ ) else: _lowerCamelCase = posterior.mode() _lowerCamelCase = self.decode(a__ ).sample if not return_dict: return (dec,) return DecoderOutput(sample=a__ )
80
1
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import MaskaFormerConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel if is_vision_available(): from transformers import MaskaFormerImageProcessor if is_vision_available(): from PIL import Image class UpperCamelCase__: def __init__( self ,__UpperCAmelCase ,__UpperCAmelCase=2 ,__UpperCAmelCase=True ,__UpperCAmelCase=False ,__UpperCAmelCase=10 ,__UpperCAmelCase=3 ,__UpperCAmelCase=32 * 8 ,__UpperCAmelCase=32 * 8 ,__UpperCAmelCase=4 ,__UpperCAmelCase=64 ,) -> Dict: A__ = parent A__ = batch_size A__ = is_training A__ = use_auxiliary_loss A__ = num_queries A__ = num_channels A__ = min_size A__ = max_size A__ = num_labels A__ = hidden_dim A__ = hidden_dim def snake_case__ ( self ) -> List[Any]: A__ = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( __UpperCAmelCase ) A__ = torch.ones([self.batch_size, self.min_size, self.max_size] ,device=__UpperCAmelCase ) A__ = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] ,device=__UpperCAmelCase ) > 0.5 ).float() A__ = (torch.rand((self.batch_size, self.num_labels) ,device=__UpperCAmelCase ) > 0.5).long() A__ = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def snake_case__ ( self ) -> List[str]: A__ = MaskaFormerConfig( hidden_size=self.hidden_dim ,) A__ = self.num_queries A__ = self.num_labels A__ = [1, 1, 1, 1] A__ = self.num_channels A__ = 64 A__ = 1_28 A__ = self.hidden_dim A__ = self.hidden_dim A__ = self.hidden_dim return config def snake_case__ ( self ) -> List[str]: A__ , A__ , A__ , A__ , A__ = self.prepare_config_and_inputs() A__ = {'pixel_values': pixel_values, 'pixel_mask': pixel_mask} return config, inputs_dict def snake_case__ ( self ,__UpperCAmelCase ,__UpperCAmelCase ) -> List[str]: A__ = output.encoder_hidden_states A__ = output.pixel_decoder_hidden_states A__ = output.transformer_decoder_hidden_states self.parent.assertTrue(len(__UpperCAmelCase ) ,len(config.backbone_config.depths ) ) self.parent.assertTrue(len(__UpperCAmelCase ) ,len(config.backbone_config.depths ) ) self.parent.assertTrue(len(__UpperCAmelCase ) ,config.decoder_layers ) def snake_case__ ( self ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase=False ) -> List[str]: with torch.no_grad(): A__ = MaskaFormerModel(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() A__ = model(pixel_values=__UpperCAmelCase ,pixel_mask=__UpperCAmelCase ) A__ = model(__UpperCAmelCase ,output_hidden_states=__UpperCAmelCase ) self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape ,(self.batch_size, self.num_queries, self.hidden_dim) ,) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(__UpperCAmelCase ,__UpperCAmelCase ) def snake_case__ ( self ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ) -> Union[str, Any]: A__ = MaskaFormerForUniversalSegmentation(config=__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.eval() def comm_check_on_output(__UpperCAmelCase ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape ,(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) ,) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape ,(self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): A__ = model(pixel_values=__UpperCAmelCase ,pixel_mask=__UpperCAmelCase ) A__ = model(__UpperCAmelCase ) comm_check_on_output(__UpperCAmelCase ) A__ = model( pixel_values=__UpperCAmelCase ,pixel_mask=__UpperCAmelCase ,mask_labels=__UpperCAmelCase ,class_labels=__UpperCAmelCase ) comm_check_on_output(__UpperCAmelCase ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape ,torch.Size([1] ) ) @require_torch class UpperCamelCase__( __A , __A , unittest.TestCase ): lowerCAmelCase__ : Optional[int] = (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else () lowerCAmelCase__ : Tuple = {'feature-extraction': MaskaFormerModel} if is_torch_available() else {} lowerCAmelCase__ : List[Any] = False lowerCAmelCase__ : List[Any] = False lowerCAmelCase__ : int = False lowerCAmelCase__ : Dict = False def snake_case__ ( self ) -> Optional[int]: A__ = MaskaFormerModelTester(self ) A__ = ConfigTester(self ,config_class=__UpperCAmelCase ,has_text_modality=__UpperCAmelCase ) def snake_case__ ( self ) -> Optional[Any]: self.config_tester.run_common_tests() def snake_case__ ( self ) -> Optional[int]: A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(__UpperCAmelCase ,**__UpperCAmelCase ,output_hidden_states=__UpperCAmelCase ) def snake_case__ ( self ) -> Optional[int]: A__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*__UpperCAmelCase ) @unittest.skip(reason='Mask2Former does not use inputs_embeds' ) def snake_case__ ( self ) -> Optional[int]: pass @unittest.skip(reason='Mask2Former does not have a get_input_embeddings method' ) def snake_case__ ( self ) -> List[Any]: pass @unittest.skip(reason='Mask2Former is not a generative model' ) def snake_case__ ( self ) -> int: pass @unittest.skip(reason='Mask2Former does not use token embeddings' ) def snake_case__ ( self ) -> int: pass @require_torch_multi_gpu @unittest.skip( reason='Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`' ) def snake_case__ ( self ) -> List[str]: pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def snake_case__ ( self ) -> Union[str, Any]: pass def snake_case__ ( self ) -> Union[str, Any]: A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A__ = model_class(__UpperCAmelCase ) 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] ,__UpperCAmelCase ) @slow def snake_case__ ( self ) -> Optional[int]: for model_name in ["facebook/mask2former-swin-small-coco-instance"]: A__ = MaskaFormerModel.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) def snake_case__ ( self ) -> Any: A__ = (self.model_tester.min_size,) * 2 A__ = { 'pixel_values': torch.randn((2, 3, *size) ,device=__UpperCAmelCase ), 'mask_labels': torch.randn((2, 10, *size) ,device=__UpperCAmelCase ), 'class_labels': torch.zeros(2 ,10 ,device=__UpperCAmelCase ).long(), } A__ = self.model_tester.get_config() A__ = MaskaFormerForUniversalSegmentation(__UpperCAmelCase ).to(__UpperCAmelCase ) A__ = model(**__UpperCAmelCase ) self.assertTrue(outputs.loss is not None ) def snake_case__ ( self ) -> str: A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskaformer_model(__UpperCAmelCase ,**__UpperCAmelCase ,output_hidden_states=__UpperCAmelCase ) def snake_case__ ( self ) -> List[Any]: A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: A__ = model_class(__UpperCAmelCase ).to(__UpperCAmelCase ) A__ = model(**__UpperCAmelCase ,output_attentions=__UpperCAmelCase ) self.assertTrue(outputs.attentions is not None ) def snake_case__ ( self ) -> str: if not self.model_tester.is_training: return A__ = self.all_model_classes[1] A__ , A__ , A__ , A__ , A__ = self.model_tester.prepare_config_and_inputs() A__ = model_class(__UpperCAmelCase ) model.to(__UpperCAmelCase ) model.train() A__ = model(__UpperCAmelCase ,mask_labels=__UpperCAmelCase ,class_labels=__UpperCAmelCase ).loss loss.backward() def snake_case__ ( self ) -> Any: A__ = self.all_model_classes[1] A__ , A__ , A__ , A__ , A__ = self.model_tester.prepare_config_and_inputs() A__ = True A__ = True A__ = model_class(__UpperCAmelCase ).to(__UpperCAmelCase ) model.train() A__ = model(__UpperCAmelCase ,mask_labels=__UpperCAmelCase ,class_labels=__UpperCAmelCase ) A__ = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() A__ = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() A__ = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() A__ = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=__UpperCAmelCase ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) __lowerCamelCase = 1E-4 def UpperCAmelCase ( ): """simple docstring""" A__ = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_vision @slow class UpperCamelCase__( unittest.TestCase ): @cached_property def snake_case__ ( self ) -> int: return "facebook/mask2former-swin-small-coco-instance" @cached_property def snake_case__ ( self ) -> Tuple: return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints ) if is_vision_available() else None def snake_case__ ( self ) -> str: A__ = MaskaFormerModel.from_pretrained(self.model_checkpoints ).to(__UpperCAmelCase ) A__ = self.default_image_processor A__ = prepare_img() A__ = image_processor(__UpperCAmelCase ,return_tensors='pt' ).to(__UpperCAmelCase ) A__ = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(__UpperCAmelCase ,(1, 3, 3_84, 3_84) ) with torch.no_grad(): A__ = model(**__UpperCAmelCase ) A__ = torch.tensor( [[-0.2_7_9_0, -1.0_7_1_7, -1.1_6_6_8], [-0.5_1_2_8, -0.3_1_2_8, -0.4_9_8_7], [-0.5_8_3_2, 0.1_9_7_1, -0.0_1_9_7]] ).to(__UpperCAmelCase ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] ,__UpperCAmelCase ,atol=__UpperCAmelCase ) ) A__ = torch.tensor( [[0.8_9_7_3, 1.1_8_4_7, 1.1_7_7_6], [1.1_9_3_4, 1.5_0_4_0, 1.5_1_2_8], [1.1_1_5_3, 1.4_4_8_6, 1.4_9_5_1]] ).to(__UpperCAmelCase ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] ,__UpperCAmelCase ,atol=__UpperCAmelCase ) ) A__ = torch.tensor( [[2.1_1_5_2, 1.7_0_0_0, -0.8_6_0_3], [1.5_8_0_8, 1.8_0_0_4, -0.9_3_5_3], [1.6_0_4_3, 1.7_4_9_5, -0.5_9_9_9]] ).to(__UpperCAmelCase ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] ,__UpperCAmelCase ,atol=__UpperCAmelCase ) ) def snake_case__ ( self ) -> Tuple: A__ = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(__UpperCAmelCase ).eval() A__ = self.default_image_processor A__ = prepare_img() A__ = image_processor(__UpperCAmelCase ,return_tensors='pt' ).to(__UpperCAmelCase ) A__ = inputs['pixel_values'].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(__UpperCAmelCase ,(1, 3, 3_84, 3_84) ) with torch.no_grad(): A__ = model(**__UpperCAmelCase ) # masks_queries_logits A__ = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape ,(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) ) A__ = [ [-8.7_8_3_9, -9.0_0_5_6, -8.8_1_2_1], [-7.4_1_0_4, -7.0_3_1_3, -6.5_4_0_1], [-6.6_1_0_5, -6.3_4_2_7, -6.4_6_7_5], ] A__ = torch.tensor(__UpperCAmelCase ).to(__UpperCAmelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] ,__UpperCAmelCase ,atol=__UpperCAmelCase ) ) # class_queries_logits A__ = outputs.class_queries_logits self.assertEqual(class_queries_logits.shape ,(1, model.config.num_queries, model.config.num_labels + 1) ) A__ = torch.tensor( [ [1.8_3_2_4, -8.0_8_3_5, -4.1_9_2_2], [0.8_4_5_0, -9.0_0_5_0, -3.6_0_5_3], [0.3_0_4_5, -7.7_2_9_3, -3.0_2_7_5], ] ).to(__UpperCAmelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] ,__UpperCAmelCase ,atol=__UpperCAmelCase ) ) def snake_case__ ( self ) -> Any: A__ = MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints ).to(__UpperCAmelCase ).eval() A__ = self.default_image_processor A__ = image_processor( [np.zeros((3, 8_00, 13_33) ), np.zeros((3, 8_00, 13_33) )] ,segmentation_maps=[np.zeros((3_84, 3_84) ).astype(np.floataa ), np.zeros((3_84, 3_84) ).astype(np.floataa )] ,return_tensors='pt' ,) A__ = inputs['pixel_values'].to(__UpperCAmelCase ) A__ = [el.to(__UpperCAmelCase ) for el in inputs['mask_labels']] A__ = [el.to(__UpperCAmelCase ) for el in inputs['class_labels']] with torch.no_grad(): A__ = model(**__UpperCAmelCase ) self.assertTrue(outputs.loss is not None )
221
"""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 UpperCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ): """simple docstring""" 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 UpperCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__=True ): """simple docstring""" model.train() A__ = model(UpperCamelCase__ ) A__ = F.mse_loss(UpperCamelCase__ , target.to(output.device ) ) if not do_backward: loss /= accelerator.gradient_accumulation_steps loss.backward() else: accelerator.backward(UpperCamelCase__ ) def UpperCAmelCase ( UpperCamelCase__ , UpperCamelCase__=False ): """simple docstring""" set_seed(42 ) A__ = RegressionModel() A__ = deepcopy(UpperCamelCase__ ) A__ = RegressionDataset(length=80 ) A__ = DataLoader(UpperCamelCase__ , batch_size=16 ) 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(UpperCamelCase__ , lr_lambda=lambda UpperCamelCase__ : epoch**0.6_5 ) A__ = LambdaLR(UpperCamelCase__ , lr_lambda=lambda UpperCamelCase__ : epoch**0.6_5 ) # Make a copy of `model` if sched: A__ , A__ , A__ , A__ = accelerator.prepare(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: A__ , A__ = accelerator.prepare(UpperCamelCase__ , UpperCamelCase__ ) if sched: return (model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched) return model, ddp_model, dataloader def UpperCAmelCase ( UpperCamelCase__ ): """simple docstring""" A__ , A__ , A__ = get_training_setup(UpperCamelCase__ ) # Use a single batch A__ , A__ = next(iter(UpperCamelCase__ ) ).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(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(UpperCamelCase__ ): step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: # Sync grads step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Since `no_sync` is a noop, `ddp_model` and `model` grads should always be in sync check_model_parameters(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) 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_337 + iteration ) A__ = ddp_input[torch.randperm(len(UpperCamelCase__ ) )] def UpperCAmelCase ( UpperCamelCase__ ): """simple docstring""" A__ , A__ , A__ = get_training_setup(UpperCamelCase__ ) # Use a single batch A__ , A__ = next(iter(UpperCamelCase__ ) ).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(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(UpperCamelCase__ ): step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: # Sync grads step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # 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_337 + iteration ) A__ = ddp_input[torch.randperm(len(UpperCamelCase__ ) )] def UpperCAmelCase ( UpperCamelCase__=False , UpperCamelCase__=False ): """simple docstring""" A__ = Accelerator( split_batches=UpperCamelCase__ , dispatch_batches=UpperCamelCase__ , gradient_accumulation_steps=2 ) # Test that context manager behaves properly A__ , A__ , A__ = get_training_setup(UpperCamelCase__ ) for iteration, batch in enumerate(UpperCamelCase__ ): 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(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Do "gradient accumulation" (noop) with accelerator.accumulate(UpperCamelCase__ ): step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # 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(UpperCamelCase__ ) - 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_337 + iteration ) A__ = ddp_input[torch.randperm(len(UpperCamelCase__ ) )] GradientState._reset_state() def UpperCAmelCase ( UpperCamelCase__=False , UpperCamelCase__=False ): """simple docstring""" A__ = Accelerator( split_batches=UpperCamelCase__ , dispatch_batches=UpperCamelCase__ , gradient_accumulation_steps=2 ) # Test that context manager behaves properly A__ , A__ , A__ , A__ , A__ , A__ , A__ = get_training_setup(UpperCamelCase__ , UpperCamelCase__ ) for iteration, batch in enumerate(UpperCamelCase__ ): 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(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) opt.step() if ((iteration + 1) % 2 == 0) or ((iteration + 1) == len(UpperCamelCase__ )): 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(UpperCamelCase__ ): step_model(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) 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(UpperCamelCase__ )) if accelerator.num_processes > 1: check_model_parameters(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Shuffle ddp_input on each iteration torch.manual_seed(1_337 + iteration ) GradientState._reset_state() def UpperCAmelCase ( ): """simple docstring""" A__ = Accelerator() A__ = RegressionDataset(length=80 ) A__ = DataLoader(UpperCamelCase__ , batch_size=16 ) A__ = RegressionDataset(length=96 ) A__ = DataLoader(UpperCamelCase__ , batch_size=16 ) A__ , A__ = accelerator.prepare(UpperCamelCase__ , UpperCamelCase__ ) assert accelerator.gradient_state.active_dataloader is None for iteration, _ in enumerate(UpperCamelCase__ ): assert id(accelerator.gradient_state.active_dataloader ) == id(UpperCamelCase__ ) if iteration < len(UpperCamelCase__ ) - 1: assert not accelerator.gradient_state.end_of_dataloader if iteration == 1: for batch_num, _ in enumerate(UpperCamelCase__ ): assert id(accelerator.gradient_state.active_dataloader ) == id(UpperCamelCase__ ) if batch_num < len(UpperCamelCase__ ) - 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 UpperCAmelCase ( ): """simple docstring""" 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(UpperCamelCase__ ) 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(UpperCamelCase__ ) 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(UpperCamelCase__ , UpperCamelCase__ ) # 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(UpperCamelCase__ , UpperCamelCase__ ) def UpperCAmelCase ( UpperCamelCase__ ): """simple docstring""" main() if __name__ == "__main__": main()
221
1
'''simple docstring''' from collections import OrderedDict from ...utils import logging from .auto_factory import _BaseAutoModelClass, _LazyAutoMapping, auto_class_update from .configuration_auto import CONFIG_MAPPING_NAMES SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ = OrderedDict( [ # Base model mapping ('albert', 'FlaxAlbertModel'), ('bart', 'FlaxBartModel'), ('beit', 'FlaxBeitModel'), ('bert', 'FlaxBertModel'), ('big_bird', 'FlaxBigBirdModel'), ('blenderbot', 'FlaxBlenderbotModel'), ('blenderbot-small', 'FlaxBlenderbotSmallModel'), ('clip', 'FlaxCLIPModel'), ('distilbert', 'FlaxDistilBertModel'), ('electra', 'FlaxElectraModel'), ('gpt-sw3', 'FlaxGPT2Model'), ('gpt2', 'FlaxGPT2Model'), ('gpt_neo', 'FlaxGPTNeoModel'), ('gptj', 'FlaxGPTJModel'), ('longt5', 'FlaxLongT5Model'), ('marian', 'FlaxMarianModel'), ('mbart', 'FlaxMBartModel'), ('mt5', 'FlaxMT5Model'), ('opt', 'FlaxOPTModel'), ('pegasus', 'FlaxPegasusModel'), ('regnet', 'FlaxRegNetModel'), ('resnet', 'FlaxResNetModel'), ('roberta', 'FlaxRobertaModel'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormModel'), ('roformer', 'FlaxRoFormerModel'), ('t5', 'FlaxT5Model'), ('vision-text-dual-encoder', 'FlaxVisionTextDualEncoderModel'), ('vit', 'FlaxViTModel'), ('wav2vec2', 'FlaxWav2Vec2Model'), ('whisper', 'FlaxWhisperModel'), ('xglm', 'FlaxXGLMModel'), ('xlm-roberta', 'FlaxXLMRobertaModel'), ] ) SCREAMING_SNAKE_CASE__ = OrderedDict( [ # Model for pre-training mapping ('albert', 'FlaxAlbertForPreTraining'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForPreTraining'), ('big_bird', 'FlaxBigBirdForPreTraining'), ('electra', 'FlaxElectraForPreTraining'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('t5', 'FlaxT5ForConditionalGeneration'), ('wav2vec2', 'FlaxWav2Vec2ForPreTraining'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) SCREAMING_SNAKE_CASE__ = OrderedDict( [ # Model for Masked LM mapping ('albert', 'FlaxAlbertForMaskedLM'), ('bart', 'FlaxBartForConditionalGeneration'), ('bert', 'FlaxBertForMaskedLM'), ('big_bird', 'FlaxBigBirdForMaskedLM'), ('distilbert', 'FlaxDistilBertForMaskedLM'), ('electra', 'FlaxElectraForMaskedLM'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('roberta', 'FlaxRobertaForMaskedLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMaskedLM'), ('roformer', 'FlaxRoFormerForMaskedLM'), ('xlm-roberta', 'FlaxXLMRobertaForMaskedLM'), ] ) SCREAMING_SNAKE_CASE__ = OrderedDict( [ # Model for Seq2Seq Causal LM mapping ('bart', 'FlaxBartForConditionalGeneration'), ('blenderbot', 'FlaxBlenderbotForConditionalGeneration'), ('blenderbot-small', 'FlaxBlenderbotSmallForConditionalGeneration'), ('encoder-decoder', 'FlaxEncoderDecoderModel'), ('longt5', 'FlaxLongT5ForConditionalGeneration'), ('marian', 'FlaxMarianMTModel'), ('mbart', 'FlaxMBartForConditionalGeneration'), ('mt5', 'FlaxMT5ForConditionalGeneration'), ('pegasus', 'FlaxPegasusForConditionalGeneration'), ('t5', 'FlaxT5ForConditionalGeneration'), ] ) SCREAMING_SNAKE_CASE__ = OrderedDict( [ # Model for Image-classsification ('beit', 'FlaxBeitForImageClassification'), ('regnet', 'FlaxRegNetForImageClassification'), ('resnet', 'FlaxResNetForImageClassification'), ('vit', 'FlaxViTForImageClassification'), ] ) SCREAMING_SNAKE_CASE__ = OrderedDict( [ ('vision-encoder-decoder', 'FlaxVisionEncoderDecoderModel'), ] ) SCREAMING_SNAKE_CASE__ = OrderedDict( [ # Model for Causal LM mapping ('bart', 'FlaxBartForCausalLM'), ('bert', 'FlaxBertForCausalLM'), ('big_bird', 'FlaxBigBirdForCausalLM'), ('electra', 'FlaxElectraForCausalLM'), ('gpt-sw3', 'FlaxGPT2LMHeadModel'), ('gpt2', 'FlaxGPT2LMHeadModel'), ('gpt_neo', 'FlaxGPTNeoForCausalLM'), ('gptj', 'FlaxGPTJForCausalLM'), ('opt', 'FlaxOPTForCausalLM'), ('roberta', 'FlaxRobertaForCausalLM'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForCausalLM'), ('xglm', 'FlaxXGLMForCausalLM'), ('xlm-roberta', 'FlaxXLMRobertaForCausalLM'), ] ) SCREAMING_SNAKE_CASE__ = OrderedDict( [ # Model for Sequence Classification mapping ('albert', 'FlaxAlbertForSequenceClassification'), ('bart', 'FlaxBartForSequenceClassification'), ('bert', 'FlaxBertForSequenceClassification'), ('big_bird', 'FlaxBigBirdForSequenceClassification'), ('distilbert', 'FlaxDistilBertForSequenceClassification'), ('electra', 'FlaxElectraForSequenceClassification'), ('mbart', 'FlaxMBartForSequenceClassification'), ('roberta', 'FlaxRobertaForSequenceClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForSequenceClassification'), ('roformer', 'FlaxRoFormerForSequenceClassification'), ('xlm-roberta', 'FlaxXLMRobertaForSequenceClassification'), ] ) SCREAMING_SNAKE_CASE__ = OrderedDict( [ # Model for Question Answering mapping ('albert', 'FlaxAlbertForQuestionAnswering'), ('bart', 'FlaxBartForQuestionAnswering'), ('bert', 'FlaxBertForQuestionAnswering'), ('big_bird', 'FlaxBigBirdForQuestionAnswering'), ('distilbert', 'FlaxDistilBertForQuestionAnswering'), ('electra', 'FlaxElectraForQuestionAnswering'), ('mbart', 'FlaxMBartForQuestionAnswering'), ('roberta', 'FlaxRobertaForQuestionAnswering'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForQuestionAnswering'), ('roformer', 'FlaxRoFormerForQuestionAnswering'), ('xlm-roberta', 'FlaxXLMRobertaForQuestionAnswering'), ] ) SCREAMING_SNAKE_CASE__ = OrderedDict( [ # Model for Token Classification mapping ('albert', 'FlaxAlbertForTokenClassification'), ('bert', 'FlaxBertForTokenClassification'), ('big_bird', 'FlaxBigBirdForTokenClassification'), ('distilbert', 'FlaxDistilBertForTokenClassification'), ('electra', 'FlaxElectraForTokenClassification'), ('roberta', 'FlaxRobertaForTokenClassification'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForTokenClassification'), ('roformer', 'FlaxRoFormerForTokenClassification'), ('xlm-roberta', 'FlaxXLMRobertaForTokenClassification'), ] ) SCREAMING_SNAKE_CASE__ = OrderedDict( [ # Model for Multiple Choice mapping ('albert', 'FlaxAlbertForMultipleChoice'), ('bert', 'FlaxBertForMultipleChoice'), ('big_bird', 'FlaxBigBirdForMultipleChoice'), ('distilbert', 'FlaxDistilBertForMultipleChoice'), ('electra', 'FlaxElectraForMultipleChoice'), ('roberta', 'FlaxRobertaForMultipleChoice'), ('roberta-prelayernorm', 'FlaxRobertaPreLayerNormForMultipleChoice'), ('roformer', 'FlaxRoFormerForMultipleChoice'), ('xlm-roberta', 'FlaxXLMRobertaForMultipleChoice'), ] ) SCREAMING_SNAKE_CASE__ = OrderedDict( [ ('bert', 'FlaxBertForNextSentencePrediction'), ] ) SCREAMING_SNAKE_CASE__ = OrderedDict( [ ('speech-encoder-decoder', 'FlaxSpeechEncoderDecoderModel'), ('whisper', 'FlaxWhisperForConditionalGeneration'), ] ) SCREAMING_SNAKE_CASE__ = OrderedDict( [ ('whisper', 'FlaxWhisperForAudioClassification'), ] ) SCREAMING_SNAKE_CASE__ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) SCREAMING_SNAKE_CASE__ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) SCREAMING_SNAKE_CASE__ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) SCREAMING_SNAKE_CASE__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) SCREAMING_SNAKE_CASE__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) SCREAMING_SNAKE_CASE__ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) SCREAMING_SNAKE_CASE__ = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) SCREAMING_SNAKE_CASE__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) SCREAMING_SNAKE_CASE__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) SCREAMING_SNAKE_CASE__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) SCREAMING_SNAKE_CASE__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) SCREAMING_SNAKE_CASE__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) SCREAMING_SNAKE_CASE__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) SCREAMING_SNAKE_CASE__ = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class a_ ( _BaseAutoModelClass ): lowercase = FLAX_MODEL_MAPPING SCREAMING_SNAKE_CASE__ = auto_class_update(FlaxAutoModel) class a_ ( _BaseAutoModelClass ): lowercase = FLAX_MODEL_FOR_PRETRAINING_MAPPING SCREAMING_SNAKE_CASE__ = auto_class_update(FlaxAutoModelForPreTraining, head_doc='pretraining') class a_ ( _BaseAutoModelClass ): lowercase = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING SCREAMING_SNAKE_CASE__ = auto_class_update(FlaxAutoModelForCausalLM, head_doc='causal language modeling') class a_ ( _BaseAutoModelClass ): lowercase = FLAX_MODEL_FOR_MASKED_LM_MAPPING SCREAMING_SNAKE_CASE__ = auto_class_update(FlaxAutoModelForMaskedLM, head_doc='masked language modeling') class a_ ( _BaseAutoModelClass ): lowercase = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING SCREAMING_SNAKE_CASE__ = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc='sequence-to-sequence language modeling', checkpoint_for_example='t5-base' ) class a_ ( _BaseAutoModelClass ): lowercase = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING SCREAMING_SNAKE_CASE__ = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc='sequence classification' ) class a_ ( _BaseAutoModelClass ): lowercase = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING SCREAMING_SNAKE_CASE__ = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc='question answering') class a_ ( _BaseAutoModelClass ): lowercase = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING SCREAMING_SNAKE_CASE__ = auto_class_update( FlaxAutoModelForTokenClassification, head_doc='token classification' ) class a_ ( _BaseAutoModelClass ): lowercase = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING SCREAMING_SNAKE_CASE__ = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc='multiple choice') class a_ ( _BaseAutoModelClass ): lowercase = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING SCREAMING_SNAKE_CASE__ = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc='next sentence prediction' ) class a_ ( _BaseAutoModelClass ): lowercase = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING SCREAMING_SNAKE_CASE__ = auto_class_update( FlaxAutoModelForImageClassification, head_doc='image classification' ) class a_ ( _BaseAutoModelClass ): lowercase = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING SCREAMING_SNAKE_CASE__ = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc='vision-to-text modeling') class a_ ( _BaseAutoModelClass ): lowercase = FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING SCREAMING_SNAKE_CASE__ = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc='sequence-to-sequence speech-to-text modeling' )
183
'''simple docstring''' import re import string import numpy as np import datasets SCREAMING_SNAKE_CASE__ = '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n' SCREAMING_SNAKE_CASE__ = '\nArgs:\n predictions: List of predicted texts.\n references: List of reference texts.\n regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n ignore when calculating the exact matches. Note: these regexes are removed\n from the input data before the changes based on the options below (e.g. ignore_case,\n ignore_punctuation, ignore_numbers) are applied.\n ignore_case: Boolean, defaults to False. If true, turns everything\n to lowercase so that capitalization differences are ignored.\n ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\n ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n comparing predictions and references.\nReturns:\n exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 25.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 50.0\n\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n >>> print(round(results["exact_match"], 1))\n 75.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n >>> preds = ["cat?", "theater", "yelling", "agent"]\n >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n >>> print(round(results["exact_match"], 1))\n 100.0\n\n >>> exact_match = datasets.load_metric("exact_match")\n >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n >>> results = exact_match.compute(references=refs, predictions=preds)\n >>> print(round(results["exact_match"], 1))\n 33.3\n\n' SCREAMING_SNAKE_CASE__ = '\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a_ ( datasets.Metric ): def A__ ( self ) -> Optional[Any]: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , reference_urls=[] , ) def A__ ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=False , ) -> List[Any]: """simple docstring""" if regexes_to_ignore is not None: for s in regexes_to_ignore: UpperCamelCase = np.array([re.sub(_SCREAMING_SNAKE_CASE , """""" , _SCREAMING_SNAKE_CASE ) for x in predictions] ) UpperCamelCase = np.array([re.sub(_SCREAMING_SNAKE_CASE , """""" , _SCREAMING_SNAKE_CASE ) for x in references] ) else: UpperCamelCase = np.asarray(_SCREAMING_SNAKE_CASE ) UpperCamelCase = np.asarray(_SCREAMING_SNAKE_CASE ) if ignore_case: UpperCamelCase = np.char.lower(_SCREAMING_SNAKE_CASE ) UpperCamelCase = np.char.lower(_SCREAMING_SNAKE_CASE ) if ignore_punctuation: UpperCamelCase = string.punctuation.maketrans("""""" , """""" , string.punctuation ) UpperCamelCase = np.char.translate(_SCREAMING_SNAKE_CASE , table=_SCREAMING_SNAKE_CASE ) UpperCamelCase = np.char.translate(_SCREAMING_SNAKE_CASE , table=_SCREAMING_SNAKE_CASE ) if ignore_numbers: UpperCamelCase = string.digits.maketrans("""""" , """""" , string.digits ) UpperCamelCase = np.char.translate(_SCREAMING_SNAKE_CASE , table=_SCREAMING_SNAKE_CASE ) UpperCamelCase = np.char.translate(_SCREAMING_SNAKE_CASE , table=_SCREAMING_SNAKE_CASE ) UpperCamelCase = predictions == references return {"exact_match": np.mean(_SCREAMING_SNAKE_CASE ) * 100}
183
1
import os import posixpath import uuid from dataclasses import dataclass from typing import TYPE_CHECKING, Iterable, List, Optional, Tuple, Union import numpy as np import pyarrow as pa import datasets from datasets.arrow_writer import ArrowWriter, ParquetWriter from datasets.config import MAX_SHARD_SIZE from datasets.filesystems import ( is_remote_filesystem, rename, ) from datasets.iterable_dataset import _BaseExamplesIterable from datasets.utils.py_utils import convert_file_size_to_int __lowerCamelCase : Union[str, Any] = datasets.utils.logging.get_logger(__name__) if TYPE_CHECKING: import pyspark @dataclass class __snake_case ( datasets.BuilderConfig ): lowerCAmelCase_ = None def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : "pyspark.sql.DataFrame" , __UpperCamelCase : List[int] , ) -> str: """simple docstring""" import pyspark def generate_fn(): SCREAMING_SNAKE_CASE__ = df.select("""*""" , pyspark.sql.functions.spark_partition_id().alias("""part_id""" ) ) for partition_id in partition_order: SCREAMING_SNAKE_CASE__ = df_with_partition_id.select("""*""" ).where(f"""part_id = {partition_id}""" ).drop("""part_id""" ) SCREAMING_SNAKE_CASE__ = partition_df.collect() SCREAMING_SNAKE_CASE__ = 0 for row in rows: yield f"""{partition_id}_{row_id}""", row.asDict() row_id += 1 return generate_fn class __snake_case ( _BaseExamplesIterable ): def __init__( self : int , _lowercase : "pyspark.sql.DataFrame" , _lowercase : Tuple=None , ): """simple docstring""" SCREAMING_SNAKE_CASE__ = df SCREAMING_SNAKE_CASE__ = partition_order or range(self.df.rdd.getNumPartitions() ) SCREAMING_SNAKE_CASE__ = _generate_iterable_examples(self.df , self.partition_order ) def __iter__( self : List[str] ): """simple docstring""" yield from self.generate_examples_fn() def __a ( self : Optional[Any] , _lowercase : np.random.Generator ): """simple docstring""" SCREAMING_SNAKE_CASE__ = list(range(self.df.rdd.getNumPartitions() ) ) generator.shuffle(_A ) return SparkExamplesIterable(self.df , partition_order=_A ) def __a ( self : List[Any] , _lowercase : int , _lowercase : int ): """simple docstring""" SCREAMING_SNAKE_CASE__ = self.split_shard_indices_by_worker(_A , _A ) return SparkExamplesIterable(self.df , partition_order=_A ) @property def __a ( self : List[str] ): """simple docstring""" return len(self.partition_order ) class __snake_case ( datasets.DatasetBuilder ): lowerCAmelCase_ = SparkConfig def __init__( self : Tuple , _lowercase : "pyspark.sql.DataFrame" , _lowercase : str = None , _lowercase : str = None , **_lowercase : Union[str, Any] , ): """simple docstring""" import pyspark SCREAMING_SNAKE_CASE__ = pyspark.sql.SparkSession.builder.getOrCreate() SCREAMING_SNAKE_CASE__ = df SCREAMING_SNAKE_CASE__ = working_dir super().__init__( cache_dir=_A , config_name=str(self.df.semanticHash() ) , **_A , ) def __a ( self : int ): """simple docstring""" def create_cache_and_write_probe(_lowercase : str ): # makedirs with exist_ok will recursively create the directory. It will not throw an error if directories # already exist. os.makedirs(self._cache_dir , exist_ok=_A ) SCREAMING_SNAKE_CASE__ = os.path.join(self._cache_dir , """fs_test""" + uuid.uuida().hex ) # Opening the file in append mode will create a new file unless it already exists, in which case it will not # change the file contents. open(_A , """a""" ) return [probe_file] if self._spark.conf.get("""spark.master""" , """""" ).startswith("""local""" ): return # If the cluster is multi-node, make sure that the user provided a cache_dir and that it is on an NFS # accessible to the driver. # TODO: Stream batches to the driver using ArrowCollectSerializer instead of throwing an error. if self._cache_dir: SCREAMING_SNAKE_CASE__ = ( self._spark.sparkContext.parallelize(range(1 ) , 1 ).mapPartitions(_A ).collect() ) if os.path.isfile(probe[0] ): return raise ValueError( """When using Dataset.from_spark on a multi-node cluster, the driver and all workers should be able to access cache_dir""" ) def __a ( self : str ): """simple docstring""" return datasets.DatasetInfo(features=self.config.features ) def __a ( self : Optional[Any] , _lowercase : datasets.download.download_manager.DownloadManager ): """simple docstring""" return [datasets.SplitGenerator(name=datasets.Split.TRAIN )] def __a ( self : Any , _lowercase : Dict ): """simple docstring""" import pyspark def get_arrow_batch_size(_lowercase : Tuple ): for batch in it: yield pa.RecordBatch.from_pydict({"""batch_bytes""": [batch.nbytes]} ) SCREAMING_SNAKE_CASE__ = self.df.count() SCREAMING_SNAKE_CASE__ = df_num_rows if df_num_rows <= 1_00 else 1_00 # Approximate the size of each row (in Arrow format) by averaging over a max-100-row sample. SCREAMING_SNAKE_CASE__ = ( self.df.limit(_A ) .repartition(1 ) .mapInArrow(_A , """batch_bytes: long""" ) .agg(pyspark.sql.functions.sum("""batch_bytes""" ).alias("""sample_bytes""" ) ) .collect()[0] .sample_bytes / sample_num_rows ) SCREAMING_SNAKE_CASE__ = approx_bytes_per_row * df_num_rows if approx_total_size > max_shard_size: # Make sure there is at least one row per partition. SCREAMING_SNAKE_CASE__ = min(_A , int(approx_total_size / max_shard_size ) ) SCREAMING_SNAKE_CASE__ = self.df.repartition(_A ) def __a ( self : str , _lowercase : str , _lowercase : str , _lowercase : int , ): """simple docstring""" import pyspark SCREAMING_SNAKE_CASE__ = ParquetWriter if file_format == '''parquet''' else ArrowWriter SCREAMING_SNAKE_CASE__ = os.path.join(self._working_dir , os.path.basename(_A ) ) if self._working_dir else fpath SCREAMING_SNAKE_CASE__ = file_format == '''parquet''' # Define these so that we don't reference self in write_arrow, which will result in a pickling error due to # pickling the SparkContext. SCREAMING_SNAKE_CASE__ = self.config.features SCREAMING_SNAKE_CASE__ = self._writer_batch_size SCREAMING_SNAKE_CASE__ = self._fs.storage_options def write_arrow(_lowercase : Dict ): # Within the same SparkContext, no two task attempts will share the same attempt ID. SCREAMING_SNAKE_CASE__ = pyspark.TaskContext().taskAttemptId() SCREAMING_SNAKE_CASE__ = next(_A , _A ) if first_batch is None: # Some partitions might not receive any data. return pa.RecordBatch.from_arrays( [[task_id], [0], [0]] , names=["""task_id""", """num_examples""", """num_bytes"""] , ) SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = writer_class( features=_A , path=working_fpath.replace("""SSSSS""" , f"""{shard_id:05d}""" ).replace("""TTTTT""" , f"""{task_id:05d}""" ) , writer_batch_size=_A , storage_options=_A , embed_local_files=_A , ) SCREAMING_SNAKE_CASE__ = pa.Table.from_batches([first_batch] ) writer.write_table(_A ) for batch in it: if max_shard_size is not None and writer._num_bytes >= max_shard_size: SCREAMING_SNAKE_CASE__ = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=["""task_id""", """num_examples""", """num_bytes"""] , ) shard_id += 1 SCREAMING_SNAKE_CASE__ = writer_class( features=writer._features , path=working_fpath.replace("""SSSSS""" , f"""{shard_id:05d}""" ).replace("""TTTTT""" , f"""{task_id:05d}""" ) , writer_batch_size=_A , storage_options=_A , embed_local_files=_A , ) SCREAMING_SNAKE_CASE__ = pa.Table.from_batches([batch] ) writer.write_table(_A ) if writer._num_bytes > 0: SCREAMING_SNAKE_CASE__ = writer.finalize() writer.close() yield pa.RecordBatch.from_arrays( [[task_id], [num_examples], [num_bytes]] , names=["""task_id""", """num_examples""", """num_bytes"""] , ) if working_fpath != fpath: for file in os.listdir(os.path.dirname(_A ) ): SCREAMING_SNAKE_CASE__ = os.path.join(os.path.dirname(_A ) , os.path.basename(_A ) ) shutil.move(_A , _A ) SCREAMING_SNAKE_CASE__ = ( self.df.mapInArrow(_A , """task_id: long, num_examples: long, num_bytes: long""" ) .groupBy("""task_id""" ) .agg( pyspark.sql.functions.sum("""num_examples""" ).alias("""total_num_examples""" ) , pyspark.sql.functions.sum("""num_bytes""" ).alias("""total_num_bytes""" ) , pyspark.sql.functions.count("""num_bytes""" ).alias("""num_shards""" ) , pyspark.sql.functions.collect_list("""num_examples""" ).alias("""shard_lengths""" ) , ) .collect() ) for row in stats: yield row.task_id, (row.total_num_examples, row.total_num_bytes, row.num_shards, row.shard_lengths) def __a ( self : Optional[int] , _lowercase : "datasets.SplitGenerator" , _lowercase : str = "arrow" , _lowercase : Optional[Union[str, int]] = None , _lowercase : Optional[int] = None , **_lowercase : int , ): """simple docstring""" self._validate_cache_dir() SCREAMING_SNAKE_CASE__ = convert_file_size_to_int(max_shard_size or MAX_SHARD_SIZE ) self._repartition_df_if_needed(_A ) SCREAMING_SNAKE_CASE__ = not is_remote_filesystem(self._fs ) SCREAMING_SNAKE_CASE__ = os.path.join if is_local else posixpath.join SCREAMING_SNAKE_CASE__ = '''-TTTTT-SSSSS-of-NNNNN''' SCREAMING_SNAKE_CASE__ = f"""{self.name}-{split_generator.name}{SUFFIX}.{file_format}""" SCREAMING_SNAKE_CASE__ = path_join(self._output_dir , _A ) SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = [] for task_id, content in self._prepare_split_single(_A , _A , _A ): ( SCREAMING_SNAKE_CASE__ ) = content if num_bytes > 0: total_num_examples += num_examples total_num_bytes += num_bytes total_shards += num_shards task_id_and_num_shards.append((task_id, num_shards) ) all_shard_lengths.extend(_A ) SCREAMING_SNAKE_CASE__ = total_num_examples SCREAMING_SNAKE_CASE__ = total_num_bytes # should rename everything at the end logger.debug(f"""Renaming {total_shards} shards.""" ) if total_shards > 1: SCREAMING_SNAKE_CASE__ = all_shard_lengths # Define fs outside of _rename_shard so that we don't reference self in the function, which will result in a # pickling error due to pickling the SparkContext. SCREAMING_SNAKE_CASE__ = self._fs # use the -SSSSS-of-NNNNN pattern def _rename_shard( _lowercase : int , _lowercase : int , _lowercase : int , ): rename( _A , fpath.replace("""SSSSS""" , f"""{shard_id:05d}""" ).replace("""TTTTT""" , f"""{task_id:05d}""" ) , fpath.replace("""TTTTT-SSSSS""" , f"""{global_shard_id:05d}""" ).replace("""NNNNN""" , f"""{total_shards:05d}""" ) , ) SCREAMING_SNAKE_CASE__ = [] SCREAMING_SNAKE_CASE__ = 0 for i in range(len(_A ) ): SCREAMING_SNAKE_CASE__ = task_id_and_num_shards[i] for shard_id in range(_A ): args.append([task_id, shard_id, global_shard_id] ) global_shard_id += 1 self._spark.sparkContext.parallelize(_A , len(_A ) ).map(lambda _lowercase : _rename_shard(*_A ) ).collect() else: # don't use any pattern SCREAMING_SNAKE_CASE__ = 0 SCREAMING_SNAKE_CASE__ = task_id_and_num_shards[0][0] self._rename( fpath.replace("""SSSSS""" , f"""{shard_id:05d}""" ).replace("""TTTTT""" , f"""{task_id:05d}""" ) , fpath.replace(_A , """""" ) , ) def __a ( self : List[Any] , _lowercase : "datasets.SplitGenerator" , ): """simple docstring""" return SparkExamplesIterable(self.df )
219
'''simple docstring''' from __future__ import annotations def __UpperCAmelCase ( A : list , A : int , A : int , A : int ) -> list: UpperCAmelCase_ : Any = [] UpperCAmelCase_ , UpperCAmelCase_ : Tuple = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) UpperCAmelCase_ : List[Any] = result + left + right return input_list def __UpperCAmelCase ( A : list ) -> list: if len(A ) <= 1: return input_list UpperCAmelCase_ : List[str] = list(A ) # iteration for two-way merging UpperCAmelCase_ : Tuple = 2 while p <= len(A ): # getting low, high and middle value for merge-sort of single list for i in range(0 , len(A ) , A ): UpperCAmelCase_ : Union[str, Any] = i UpperCAmelCase_ : int = i + p - 1 UpperCAmelCase_ : Any = (low + high + 1) // 2 UpperCAmelCase_ : Union[str, Any] = merge(A , A , A , A ) # final merge of last two parts if p * 2 >= len(A ): UpperCAmelCase_ : str = i UpperCAmelCase_ : Tuple = merge(A , 0 , A , len(A ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": _UpperCamelCase : str = input('Enter numbers separated by a comma:\n').strip() if user_input == "": _UpperCamelCase : List[str] = [] else: _UpperCamelCase : Optional[int] = [int(item.strip()) for item in user_input.split(',')] print(iter_merge_sort(unsorted))
304
0
import copy import random from transformers import CLIPTokenizer class _snake_case ( snake_case ): def __init__( self , *_a , **_a ): super().__init__(*_a , **_a ) __magic_name__ : Union[str, Any] = {} def SCREAMING_SNAKE_CASE ( self , _a , *_a , **_a ): __magic_name__ : Optional[Any] = super().add_tokens(_a , *_a , **_a ) if num_added_tokens == 0: raise ValueError( f'''The tokenizer already contains the token {placeholder_token}. Please pass a different''' " `placeholder_token` that is not already in the tokenizer." ) def SCREAMING_SNAKE_CASE ( self , _a , *_a , _a=1 , **_a ): __magic_name__ : Optional[Any] = [] if num_vec_per_token == 1: self.try_adding_tokens(_a , *_a , **_a ) output.append(_a ) else: __magic_name__ : Optional[Any] = [] for i in range(_a ): __magic_name__ : Any = placeholder_token + f'''_{i}''' self.try_adding_tokens(_a , *_a , **_a ) output.append(_a ) # handle cases where there is a new placeholder token that contains the current placeholder token but is larger for token in self.token_map: if token in placeholder_token: raise ValueError( f'''The tokenizer already has placeholder token {token} that can get confused with''' f''' {placeholder_token}keep placeholder tokens independent''' ) __magic_name__ : Union[str, Any] = output def SCREAMING_SNAKE_CASE ( self , _a , _a=False , _a=1.0 ): if isinstance(_a , _a ): __magic_name__ : Tuple = [] for i in range(len(_a ) ): output.append(self.replace_placeholder_tokens_in_text(text[i] , vector_shuffle=_a ) ) return output for placeholder_token in self.token_map: if placeholder_token in text: __magic_name__ : Optional[Any] = self.token_map[placeholder_token] __magic_name__ : List[Any] = tokens[: 1 + int(len(_a ) * prop_tokens_to_load )] if vector_shuffle: __magic_name__ : Dict = copy.copy(_a ) random.shuffle(_a ) __magic_name__ : Optional[int] = text.replace(_a , " ".join(_a ) ) return text def __call__( self , _a , *_a , _a=False , _a=1.0 , **_a ): return super().__call__( self.replace_placeholder_tokens_in_text( _a , vector_shuffle=_a , prop_tokens_to_load=_a ) , *_a , **_a , ) def SCREAMING_SNAKE_CASE ( self , _a , *_a , _a=False , _a=1.0 , **_a ): return super().encode( self.replace_placeholder_tokens_in_text( _a , vector_shuffle=_a , prop_tokens_to_load=_a ) , *_a , **_a , )
41
from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class _snake_case ( snake_case ): UpperCamelCase__ = ['image_processor', 'tokenizer'] UpperCamelCase__ = 'BridgeTowerImageProcessor' UpperCamelCase__ = ('RobertaTokenizer', 'RobertaTokenizerFast') def __init__( self , _a , _a ): super().__init__(_a , _a ) def __call__( self , _a , _a = None , _a = True , _a = False , _a = None , _a = None , _a = 0 , _a = None , _a = None , _a = None , _a = False , _a = False , _a = False , _a = False , _a = True , _a = None , **_a , ): __magic_name__ : Dict = self.tokenizer( text=_a , add_special_tokens=_a , padding=_a , truncation=_a , max_length=_a , stride=_a , pad_to_multiple_of=_a , return_token_type_ids=_a , return_attention_mask=_a , return_overflowing_tokens=_a , return_special_tokens_mask=_a , return_offsets_mapping=_a , return_length=_a , verbose=_a , return_tensors=_a , **_a , ) # add pixel_values + pixel_mask __magic_name__ : List[str] = self.image_processor( _a , return_tensors=_a , do_normalize=_a , do_center_crop=_a , **_a ) encoding.update(_a ) return encoding def SCREAMING_SNAKE_CASE ( self , *_a , **_a ): return self.tokenizer.batch_decode(*_a , **_a ) def SCREAMING_SNAKE_CASE ( self , *_a , **_a ): return self.tokenizer.decode(*_a , **_a ) @property def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Dict = self.tokenizer.model_input_names __magic_name__ : Any = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
41
1
"""simple docstring""" import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class __A ( _SCREAMING_SNAKE_CASE, unittest.TestCase ): """simple docstring""" __lowerCAmelCase = TransfoXLTokenizer __lowerCAmelCase = False __lowerCAmelCase = False def SCREAMING_SNAKE_CASE ( self ) -> int: super().setUp() a =[ '''<unk>''', '''[CLS]''', '''[SEP]''', '''want''', '''unwanted''', '''wa''', '''un''', '''running''', ''',''', '''low''', '''l''', ] a =os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def SCREAMING_SNAKE_CASE ( self , **__A ) -> List[Any]: a =True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **__A ) def SCREAMING_SNAKE_CASE ( self , __A ) -> Any: a ='''<unk> UNwanted , running''' a ='''<unk> unwanted, running''' return input_text, output_text def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=__A ) a =tokenizer.tokenize('''<unk> UNwanted , running''' ) self.assertListEqual(__A , ['''<unk>''', '''unwanted''', ''',''', '''running'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__A ) , [0, 4, 8, 7] ) def SCREAMING_SNAKE_CASE ( self ) -> int: a =TransfoXLTokenizer(lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo ! how \n Are yoU ? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> Any: a =TransfoXLTokenizer(lower_case=__A ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo ! how \n Are yoU ? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def SCREAMING_SNAKE_CASE ( self ) -> int: a =TransfoXLTokenizer(lower_case=__A ) a ='''Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?''' a =[ '''Hello''', '''(''', '''bracket''', ''')''', '''and''', '''side''', '''@-@''', '''scrolled''', '''[''', '''and''', ''']''', '''Henry''', '''\'s''', '''$''', '''5''', '''@,@''', '''000''', '''with''', '''3''', '''@.@''', '''34''', '''m''', '''.''', '''What''', '''\'s''', '''up''', '''!''', '''?''', ] self.assertListEqual(tokenizer.tokenize(__A ) , __A ) self.assertEqual(tokenizer.convert_tokens_to_string(__A ) , __A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: a =self.get_tokenizer() a =len(__A ) tokenizer.add_tokens(['''new1''', '''new2'''] ) tokenizer.move_added_token('''new1''' , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(__A ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode('''new1''' ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , '''new1''' )
81
"""simple docstring""" def _lowercase ( __snake_case ,__snake_case ) -> float: if digit_amount > 0: return round(number - int(__snake_case ) ,__snake_case ) return number - int(__snake_case ) if __name__ == "__main__": print(decimal_isolate(1.53, 0)) print(decimal_isolate(35.345, 1)) print(decimal_isolate(35.345, 2)) print(decimal_isolate(35.345, 3)) print(decimal_isolate(-14.789, 3)) print(decimal_isolate(0, 2)) print(decimal_isolate(-14.123, 1)) print(decimal_isolate(-14.123, 2)) print(decimal_isolate(-14.123, 3))
269
0
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer lowerCamelCase__ : Union[str, Any] = logging.getLogger(__name__) def UpperCAmelCase_ ( ) -> str: SCREAMING_SNAKE_CASE_ = argparse.ArgumentParser( description='Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.' ) parser.add_argument( '--dataset_name' , type=__UpperCAmelCase , default='wikitext' , help='Name of the training. Explore datasets at: hf.co/datasets.' , ) parser.add_argument( '--dataset_config' , type=__UpperCAmelCase , default='wikitext-103-raw-v1' , help='Configuration name of the dataset.' ) parser.add_argument( '--tokenizer_name_or_path' , type=__UpperCAmelCase , default='sayakpaul/unigram-tokenizer-wikitext' , help='Tokenizer identifier. Can be a local filepath or a Hub identifier.' , ) parser.add_argument( '--shard_size' , type=__UpperCAmelCase , default=10_00 , help='Number of entries to go in a single shard.' , ) parser.add_argument('--split' , type=__UpperCAmelCase , default='train' , choices=['train', 'test', 'validation'] ) parser.add_argument( '--limit' , default=__UpperCAmelCase , type=__UpperCAmelCase , help='Limit the number of shards (used for debugging).' , ) parser.add_argument( '--max_length' , type=__UpperCAmelCase , default=5_12 , help='Maximum sequence length. For training on TPUs, it helps to have a maximum' ' sequence length that is a multiple of 8.' , ) parser.add_argument( '--output_dir' , default='tf-tpu' , type=__UpperCAmelCase , help='Output directory where the TFRecord shards will be saved. If the' ' path is appended with `gs://` (\'gs://tf-tpu\', for example) then the TFRecord' ' shards will be directly saved to a Google Cloud Storage bucket.' , ) SCREAMING_SNAKE_CASE_ = parser.parse_args() return args def UpperCAmelCase_ ( __UpperCAmelCase : Tuple ) -> Tuple: def fn(__UpperCAmelCase : Optional[Any] ): return tokenizer(examples['text'] ) return fn def UpperCAmelCase_ ( __UpperCAmelCase : Optional[int] ) -> Optional[int]: SCREAMING_SNAKE_CASE_ = [] for i in range(len(tokenized_data['input_ids'] ) ): SCREAMING_SNAKE_CASE_ = { 'input_ids': tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data['input_ids'][i] ) ), 'attention_mask': tf.train.Feature( intaa_list=tf.train.IntaaList(value=tokenized_data['attention_mask'][i] ) ), } SCREAMING_SNAKE_CASE_ = tf.train.Features(feature=__UpperCAmelCase ) SCREAMING_SNAKE_CASE_ = tf.train.Example(features=__UpperCAmelCase ) SCREAMING_SNAKE_CASE_ = example.SerializeToString() records.append(__UpperCAmelCase ) return records def UpperCAmelCase_ ( __UpperCAmelCase : Tuple ) -> List[str]: SCREAMING_SNAKE_CASE_ = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: SCREAMING_SNAKE_CASE_ = min(len(__UpperCAmelCase ) , args.limit ) SCREAMING_SNAKE_CASE_ = dataset.select(range(__UpperCAmelCase ) ) print(f"Limiting the dataset to {args.limit} entries." ) SCREAMING_SNAKE_CASE_ = AutoTokenizer.from_pretrained(args.tokenizer_name_or_path ) # Handle output directory creation. # For serializing into a Google Cloud Storage Bucket, one needs to first # create a bucket. if "gs" not in args.output_dir: if not os.path.exists(args.output_dir ): os.makedirs(args.output_dir ) SCREAMING_SNAKE_CASE_ = os.path.join(args.output_dir , args.split ) if not os.path.exists(__UpperCAmelCase ): os.makedirs(__UpperCAmelCase ) else: SCREAMING_SNAKE_CASE_ = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. SCREAMING_SNAKE_CASE_ = tokenize_function(__UpperCAmelCase ) SCREAMING_SNAKE_CASE_ = dataset.map(__UpperCAmelCase , batched=__UpperCAmelCase , num_proc=4 , remove_columns=['text'] ) # We need to concatenate all our texts together, and then split the result # into chunks of a fixed size, which we will call block_size. To do this, we # will use the map method again, with the option batched=True. When we use batched=True, # the function we pass to map() will be passed multiple inputs at once, allowing us # to group them into more or fewer examples than we had in the input. # This allows us to create our new fixed-length samples. The advantage of this # method is that we don't lose a whole lot of content from the dataset compared to the # case where we simply tokenize with a pre-defined max_length. def group_texts(__UpperCAmelCase : List[Any] ): # Concatenate all texts. SCREAMING_SNAKE_CASE_ = {k: sum(examples[k] , [] ) for k in examples.keys()} SCREAMING_SNAKE_CASE_ = len(concatenated_examples[list(examples.keys() )[0]] ) # We drop the small remainder, though you could add padding instead if the model supports it # In this, as in all things, we advise you to follow your heart 🫀 SCREAMING_SNAKE_CASE_ = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. SCREAMING_SNAKE_CASE_ = { k: [t[i : i + args.max_length] for i in range(0 , __UpperCAmelCase , args.max_length )] for k, t in concatenated_examples.items() } return result SCREAMING_SNAKE_CASE_ = dataset_tokenized.map(__UpperCAmelCase , batched=__UpperCAmelCase , batch_size=10_00 , num_proc=4 ) SCREAMING_SNAKE_CASE_ = 0 SCREAMING_SNAKE_CASE_ = 0 for shard in range(0 , len(__UpperCAmelCase ) , args.shard_size ): SCREAMING_SNAKE_CASE_ = grouped_dataset[shard : shard + args.shard_size] SCREAMING_SNAKE_CASE_ = len(dataset_snapshot['input_ids'] ) SCREAMING_SNAKE_CASE_ = os.path.join(__UpperCAmelCase , f"dataset-{shard_count}-{records_containing}.tfrecord" ) SCREAMING_SNAKE_CASE_ = get_serialized_examples(__UpperCAmelCase ) with tf.io.TFRecordWriter(__UpperCAmelCase ) as out_file: for i in range(len(__UpperCAmelCase ) ): SCREAMING_SNAKE_CASE_ = serialized_examples[i] out_file.write(__UpperCAmelCase ) print('Wrote file {} containing {} records'.format(__UpperCAmelCase , __UpperCAmelCase ) ) shard_count += 1 total_records += records_containing with open(f"split-{args.split}-records-count.txt" , 'w' ) as f: print(f"Total {args.split} records: {total_records}" , file=__UpperCAmelCase ) if __name__ == "__main__": lowerCamelCase__ : Union[str, Any] = parse_args() main(args)
210
from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def UpperCAmelCase_ ( __UpperCAmelCase : Optional[int] ) -> int: if not is_accelerate_available(): return method SCREAMING_SNAKE_CASE_ = version.parse(accelerate.__version__ ).base_version if version.parse(__UpperCAmelCase ) < version.parse('0.17.0' ): return method def wrapper(self : Optional[int] , *__UpperCAmelCase : Optional[Any] , **__UpperCAmelCase : Optional[Any] ): if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ): self._hf_hook.pre_forward(self ) return method(self , *__UpperCAmelCase , **__UpperCAmelCase ) return wrapper
210
1
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor from .base import PipelineTool class _lowercase ( snake_case_ ): lowercase = "openai/whisper-base" lowercase = ( "This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the " "transcribed text." ) lowercase = "transcriber" lowercase = WhisperProcessor lowercase = WhisperForConditionalGeneration lowercase = ["audio"] lowercase = ["text"] def SCREAMING_SNAKE_CASE__ ( self : Tuple , snake_case : Optional[int] ) -> Union[str, Any]: """simple docstring""" return self.pre_processor(snake_case , return_tensors='pt' ).input_features def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] , snake_case : Any ) -> Tuple: """simple docstring""" return self.model.generate(inputs=snake_case ) def SCREAMING_SNAKE_CASE__ ( self : Tuple , snake_case : Dict ) -> int: """simple docstring""" return self.pre_processor.batch_decode(snake_case , skip_special_tokens=snake_case )[0]
175
import json import os from dataclasses import dataclass from functools import partial from typing import Callable import flax.linen as nn import jax import jax.numpy as jnp import joblib import optax import wandb from flax import jax_utils, struct, traverse_util from flax.serialization import from_bytes, to_bytes from flax.training import train_state from flax.training.common_utils import shard from tqdm.auto import tqdm from transformers import BigBirdConfig, FlaxBigBirdForQuestionAnswering from transformers.models.big_bird.modeling_flax_big_bird import FlaxBigBirdForQuestionAnsweringModule class __snake_case ( lowerCAmelCase ): _a : BigBirdConfig _a : jnp.dtype= jnp.floataa _a : bool= True def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' super().setup() lowercase : List[str] = nn.Dense(5 ,dtype=self.dtype ) def __call__( self ,*snake_case ,**snake_case ): '''simple docstring''' lowercase : int = super().__call__(*snake_case ,**snake_case ) lowercase : Any = self.cls(outputs[2] ) return outputs[:2] + (cls_out,) class __snake_case ( lowerCAmelCase ): _a : List[Any]= FlaxBigBirdForNaturalQuestionsModule def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> List[str]: def cross_entropy(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ): lowercase : int = logits.shape[-1] lowercase : Dict = (labels[..., None] == jnp.arange(SCREAMING_SNAKE_CASE__ )[None]).astype("""f4""" ) lowercase : Any = jax.nn.log_softmax(SCREAMING_SNAKE_CASE__ , axis=-1 ) lowercase : Optional[Any] = -jnp.sum(labels * logits , axis=-1 ) if reduction is not None: lowercase : Any = reduction(SCREAMING_SNAKE_CASE__ ) return loss lowercase : Optional[Any] = partial(SCREAMING_SNAKE_CASE__ , reduction=jnp.mean ) lowercase : Optional[int] = cross_entropy(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowercase : Dict = cross_entropy(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowercase : int = cross_entropy(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return (start_loss + end_loss + pooled_loss) / 3 @dataclass class __snake_case : _a : str= "google/bigbird-roberta-base" _a : int= 3000 _a : int= 1_0500 _a : int= 128 _a : int= 3 _a : int= 1 _a : int= 5 # tx_args _a : float= 3E-5 _a : float= 0.0 _a : int= 2_0000 _a : float= 0.00_95 _a : str= "bigbird-roberta-natural-questions" _a : str= "training-expt" _a : str= "data/nq-training.jsonl" _a : str= "data/nq-validation.jsonl" def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' os.makedirs(self.base_dir ,exist_ok=snake_case ) lowercase : Optional[int] = os.path.join(self.base_dir ,self.save_dir ) lowercase : Optional[int] = self.batch_size_per_device * jax.device_count() @dataclass class __snake_case : _a : int _a : int= 4096 # no dynamic padding on TPUs def __call__( self ,snake_case ): '''simple docstring''' lowercase : int = self.collate_fn(snake_case ) lowercase : Union[str, Any] = jax.tree_util.tree_map(snake_case ,snake_case ) return batch def _SCREAMING_SNAKE_CASE ( self ,snake_case ): '''simple docstring''' lowercase , lowercase : Union[str, Any] = self.fetch_inputs(features["""input_ids"""] ) lowercase : Tuple = { """input_ids""": jnp.array(snake_case ,dtype=jnp.intaa ), """attention_mask""": jnp.array(snake_case ,dtype=jnp.intaa ), """start_labels""": jnp.array(features["""start_token"""] ,dtype=jnp.intaa ), """end_labels""": jnp.array(features["""end_token"""] ,dtype=jnp.intaa ), """pooled_labels""": jnp.array(features["""category"""] ,dtype=jnp.intaa ), } return batch def _SCREAMING_SNAKE_CASE ( self ,snake_case ): '''simple docstring''' lowercase : Tuple = [self._fetch_inputs(snake_case ) for ids in input_ids] return zip(*snake_case ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ): '''simple docstring''' lowercase : Union[str, Any] = [1 for _ in range(len(snake_case ) )] while len(snake_case ) < self.max_length: input_ids.append(self.pad_id ) attention_mask.append(0 ) return input_ids, attention_mask def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ) -> Any: if seed is not None: lowercase : Optional[int] = dataset.shuffle(seed=SCREAMING_SNAKE_CASE__ ) for i in range(len(SCREAMING_SNAKE_CASE__ ) // batch_size ): lowercase : Optional[Any] = dataset[i * batch_size : (i + 1) * batch_size] yield dict(SCREAMING_SNAKE_CASE__ ) @partial(jax.pmap , axis_name="""batch""" ) def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) -> List[Any]: def loss_fn(SCREAMING_SNAKE_CASE__ ): lowercase : List[str] = model_inputs.pop("""start_labels""" ) lowercase : Optional[int] = model_inputs.pop("""end_labels""" ) lowercase : str = model_inputs.pop("""pooled_labels""" ) lowercase : Union[str, Any] = state.apply_fn(**SCREAMING_SNAKE_CASE__ , params=SCREAMING_SNAKE_CASE__ , dropout_rng=SCREAMING_SNAKE_CASE__ , train=SCREAMING_SNAKE_CASE__ ) lowercase , lowercase , lowercase : List[str] = outputs return state.loss_fn( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , ) lowercase , lowercase : int = jax.random.split(SCREAMING_SNAKE_CASE__ ) lowercase : Dict = jax.value_and_grad(SCREAMING_SNAKE_CASE__ ) lowercase , lowercase : Union[str, Any] = grad_fn(state.params ) lowercase : List[Any] = jax.lax.pmean({"""loss""": loss} , axis_name="""batch""" ) lowercase : List[Any] = jax.lax.pmean(SCREAMING_SNAKE_CASE__ , """batch""" ) lowercase : str = state.apply_gradients(grads=SCREAMING_SNAKE_CASE__ ) return state, metrics, new_drp_rng @partial(jax.pmap , axis_name="""batch""" ) def _snake_case( SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) -> List[str]: lowercase : int = model_inputs.pop("""start_labels""" ) lowercase : Dict = model_inputs.pop("""end_labels""" ) lowercase : Optional[Any] = model_inputs.pop("""pooled_labels""" ) lowercase : Optional[int] = state.apply_fn(**SCREAMING_SNAKE_CASE__ , params=state.params , train=SCREAMING_SNAKE_CASE__ ) lowercase , lowercase , lowercase : List[Any] = outputs lowercase : Dict = state.loss_fn(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowercase : str = jax.lax.pmean({"""loss""": loss} , axis_name="""batch""" ) return metrics class __snake_case ( train_state.TrainState ): _a : Callable= struct.field(pytree_node=lowerCAmelCase ) @dataclass class __snake_case : _a : Args _a : Callable _a : Callable _a : Callable _a : Callable _a : wandb _a : Callable= None def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ,snake_case=None ): '''simple docstring''' lowercase : Tuple = model.params lowercase : Any = TrainState.create( apply_fn=model.__call__ ,params=snake_case ,tx=snake_case ,loss_fn=snake_case ,) if ckpt_dir is not None: lowercase , lowercase , lowercase , lowercase , lowercase : Tuple = restore_checkpoint(snake_case ,snake_case ) lowercase : List[str] = { """lr""": args.lr, """init_lr""": args.init_lr, """warmup_steps""": args.warmup_steps, """num_train_steps""": num_train_steps, """weight_decay""": args.weight_decay, } lowercase , lowercase : Tuple = build_tx(**snake_case ) lowercase : str = train_state.TrainState( step=snake_case ,apply_fn=model.__call__ ,params=snake_case ,tx=snake_case ,opt_state=snake_case ,) lowercase : Any = args lowercase : Optional[Any] = data_collator lowercase : List[str] = lr lowercase : str = params lowercase : Tuple = jax_utils.replicate(snake_case ) return state def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ,snake_case ): '''simple docstring''' lowercase : Dict = self.args lowercase : Optional[Any] = len(snake_case ) // args.batch_size lowercase : int = jax.random.PRNGKey(0 ) lowercase : List[str] = jax.random.split(snake_case ,jax.device_count() ) for epoch in range(args.max_epochs ): lowercase : List[Any] = jnp.array(0 ,dtype=jnp.floataa ) lowercase : List[str] = get_batched_dataset(snake_case ,args.batch_size ,seed=snake_case ) lowercase : int = 0 for batch in tqdm(snake_case ,total=snake_case ,desc=f"Running EPOCH-{epoch}" ): lowercase : Dict = self.data_collator(snake_case ) lowercase , lowercase , lowercase : Optional[int] = self.train_step_fn(snake_case ,snake_case ,**snake_case ) running_loss += jax_utils.unreplicate(metrics["""loss"""] ) i += 1 if i % args.logging_steps == 0: lowercase : Optional[Any] = jax_utils.unreplicate(state.step ) lowercase : List[str] = running_loss.item() / i lowercase : List[str] = self.scheduler_fn(state_step - 1 ) lowercase : int = self.evaluate(snake_case ,snake_case ) lowercase : Tuple = { """step""": state_step.item(), """eval_loss""": eval_loss.item(), """tr_loss""": tr_loss, """lr""": lr.item(), } tqdm.write(str(snake_case ) ) self.logger.log(snake_case ,commit=snake_case ) if i % args.save_steps == 0: self.save_checkpoint(args.save_dir + f"-e{epoch}-s{i}" ,state=snake_case ) def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ): '''simple docstring''' lowercase : List[str] = get_batched_dataset(snake_case ,self.args.batch_size ) lowercase : Any = len(snake_case ) // self.args.batch_size lowercase : List[Any] = jnp.array(0 ,dtype=jnp.floataa ) lowercase : Optional[int] = 0 for batch in tqdm(snake_case ,total=snake_case ,desc="""Evaluating ... """ ): lowercase : Tuple = self.data_collator(snake_case ) lowercase : Optional[int] = self.val_step_fn(snake_case ,**snake_case ) running_loss += jax_utils.unreplicate(metrics["""loss"""] ) i += 1 return running_loss / i def _SCREAMING_SNAKE_CASE ( self ,snake_case ,snake_case ): '''simple docstring''' lowercase : str = jax_utils.unreplicate(snake_case ) print(f"SAVING CHECKPOINT IN {save_dir}" ,end=""" ... """ ) self.model_save_fn(snake_case ,params=state.params ) with open(os.path.join(snake_case ,"""opt_state.msgpack""" ) ,"""wb""" ) as f: f.write(to_bytes(state.opt_state ) ) joblib.dump(self.args ,os.path.join(snake_case ,"""args.joblib""" ) ) joblib.dump(self.data_collator ,os.path.join(snake_case ,"""data_collator.joblib""" ) ) with open(os.path.join(snake_case ,"""training_state.json""" ) ,"""w""" ) as f: json.dump({"""step""": state.step.item()} ,snake_case ) print("""DONE""" ) def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Union[str, Any]: print(f"RESTORING CHECKPOINT FROM {save_dir}" , end=""" ... """ ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , """flax_model.msgpack""" ) , """rb""" ) as f: lowercase : str = from_bytes(state.params , f.read() ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , """opt_state.msgpack""" ) , """rb""" ) as f: lowercase : Optional[int] = from_bytes(state.opt_state , f.read() ) lowercase : Optional[Any] = joblib.load(os.path.join(SCREAMING_SNAKE_CASE__ , """args.joblib""" ) ) lowercase : int = joblib.load(os.path.join(SCREAMING_SNAKE_CASE__ , """data_collator.joblib""" ) ) with open(os.path.join(SCREAMING_SNAKE_CASE__ , """training_state.json""" ) , """r""" ) as f: lowercase : Tuple = json.load(SCREAMING_SNAKE_CASE__ ) lowercase : Tuple = training_state["""step"""] print("""DONE""" ) return params, opt_state, step, args, data_collator def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> List[Any]: lowercase : List[str] = num_train_steps - warmup_steps lowercase : Dict = optax.linear_schedule(init_value=SCREAMING_SNAKE_CASE__ , end_value=SCREAMING_SNAKE_CASE__ , transition_steps=SCREAMING_SNAKE_CASE__ ) lowercase : List[str] = optax.linear_schedule(init_value=SCREAMING_SNAKE_CASE__ , end_value=1e-7 , transition_steps=SCREAMING_SNAKE_CASE__ ) lowercase : Tuple = optax.join_schedules(schedules=[warmup_fn, decay_fn] , boundaries=[warmup_steps] ) return lr def _snake_case( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Optional[Any]: def weight_decay_mask(SCREAMING_SNAKE_CASE__ ): lowercase : List[Any] = traverse_util.flatten_dict(SCREAMING_SNAKE_CASE__ ) lowercase : List[Any] = {k: (v[-1] != """bias""" and v[-2:] != ("""LayerNorm""", """scale""")) for k, v in params.items()} return traverse_util.unflatten_dict(SCREAMING_SNAKE_CASE__ ) lowercase : List[str] = scheduler_fn(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowercase : List[str] = optax.adamw(learning_rate=SCREAMING_SNAKE_CASE__ , weight_decay=SCREAMING_SNAKE_CASE__ , mask=SCREAMING_SNAKE_CASE__ ) return tx, lr
20
0
from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class UpperCamelCase_ : '''simple docstring''' UpperCAmelCase__ = 42 UpperCAmelCase__ = None UpperCAmelCase__ = None _lowerCamelCase : Optional[Any] = namedtuple("""CoinsDistribResult""", """moves excess""") def SCREAMING_SNAKE_CASE ( lowercase_ ) -> int: """simple docstring""" if root is None: return 0 # Validation def count_nodes(lowercase_ ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(lowercase_ ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(a_ ) != count_coins(a_ ): raise ValueError('''The nodes number should be same as the number of coins''' ) # Main calculation def get_distrib(lowercase_ ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) A__ , A__ = get_distrib(node.left ) A__ , A__ = get_distrib(node.right ) A__ = 1 - left_distrib_excess A__ = 1 - right_distrib_excess A__ = ( left_distrib_moves + right_distrib_moves + abs(a_ ) + abs(a_ ) ) A__ = node.data - coins_to_left - coins_to_right return CoinsDistribResult(a_ , a_ ) return get_distrib(a_ )[0] if __name__ == "__main__": import doctest doctest.testmod()
364
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) _lowerCamelCase : Optional[Any] = { """configuration_trocr""": ["""TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TrOCRConfig"""], """processing_trocr""": ["""TrOCRProcessor"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Any = [ """TROCR_PRETRAINED_MODEL_ARCHIVE_LIST""", """TrOCRForCausalLM""", """TrOCRPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys _lowerCamelCase : List[str] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
231
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 YolosConfig, YolosForObjectDetection, YolosImageProcessor from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase : List[Any] = logging.get_logger(__name__) def _lowerCAmelCase ( _UpperCamelCase : str ) -> YolosConfig: """simple docstring""" _SCREAMING_SNAKE_CASE =YolosConfig() # size of the architecture if "yolos_ti" in yolos_name: _SCREAMING_SNAKE_CASE =1_92 _SCREAMING_SNAKE_CASE =7_68 _SCREAMING_SNAKE_CASE =12 _SCREAMING_SNAKE_CASE =3 _SCREAMING_SNAKE_CASE =[8_00, 13_33] _SCREAMING_SNAKE_CASE =False elif yolos_name == "yolos_s_dWr": _SCREAMING_SNAKE_CASE =3_30 _SCREAMING_SNAKE_CASE =14 _SCREAMING_SNAKE_CASE =6 _SCREAMING_SNAKE_CASE =13_20 elif "yolos_s" in yolos_name: _SCREAMING_SNAKE_CASE =3_84 _SCREAMING_SNAKE_CASE =15_36 _SCREAMING_SNAKE_CASE =12 _SCREAMING_SNAKE_CASE =6 elif "yolos_b" in yolos_name: _SCREAMING_SNAKE_CASE =[8_00, 13_44] _SCREAMING_SNAKE_CASE =91 _SCREAMING_SNAKE_CASE ='huggingface/label-files' _SCREAMING_SNAKE_CASE ='coco-detection-id2label.json' _SCREAMING_SNAKE_CASE =json.load(open(hf_hub_download(_UpperCamelCase , _UpperCamelCase , repo_type='dataset' ) , 'r' ) ) _SCREAMING_SNAKE_CASE ={int(_UpperCamelCase ): v for k, v in idalabel.items()} _SCREAMING_SNAKE_CASE =idalabel _SCREAMING_SNAKE_CASE ={v: k for k, v in idalabel.items()} return config def _lowerCAmelCase ( _UpperCamelCase : dict , _UpperCamelCase : YolosConfig , _UpperCamelCase : bool = False ) -> Union[str, Any]: """simple docstring""" for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _SCREAMING_SNAKE_CASE =state_dict.pop(f"blocks.{i}.attn.qkv.weight" ) _SCREAMING_SNAKE_CASE =state_dict.pop(f"blocks.{i}.attn.qkv.bias" ) # next, add query, keys and values (in that order) to the state dict _SCREAMING_SNAKE_CASE =in_proj_weight[: config.hidden_size, :] _SCREAMING_SNAKE_CASE =in_proj_bias[: config.hidden_size] _SCREAMING_SNAKE_CASE =in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _SCREAMING_SNAKE_CASE =in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _SCREAMING_SNAKE_CASE =in_proj_weight[-config.hidden_size :, :] _SCREAMING_SNAKE_CASE =in_proj_bias[-config.hidden_size :] def _lowerCAmelCase ( _UpperCamelCase : str ) -> str: """simple docstring""" if "backbone" in name: _SCREAMING_SNAKE_CASE =name.replace('backbone' , 'vit' ) if "cls_token" in name: _SCREAMING_SNAKE_CASE =name.replace('cls_token' , 'embeddings.cls_token' ) if "det_token" in name: _SCREAMING_SNAKE_CASE =name.replace('det_token' , 'embeddings.detection_tokens' ) if "mid_pos_embed" in name: _SCREAMING_SNAKE_CASE =name.replace('mid_pos_embed' , 'encoder.mid_position_embeddings' ) if "pos_embed" in name: _SCREAMING_SNAKE_CASE =name.replace('pos_embed' , 'embeddings.position_embeddings' ) if "patch_embed.proj" in name: _SCREAMING_SNAKE_CASE =name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "blocks" in name: _SCREAMING_SNAKE_CASE =name.replace('blocks' , 'encoder.layer' ) if "attn.proj" in name: _SCREAMING_SNAKE_CASE =name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: _SCREAMING_SNAKE_CASE =name.replace('attn' , 'attention.self' ) if "norm1" in name: _SCREAMING_SNAKE_CASE =name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: _SCREAMING_SNAKE_CASE =name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: _SCREAMING_SNAKE_CASE =name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: _SCREAMING_SNAKE_CASE =name.replace('mlp.fc2' , 'output.dense' ) if "class_embed" in name: _SCREAMING_SNAKE_CASE =name.replace('class_embed' , 'class_labels_classifier' ) if "bbox_embed" in name: _SCREAMING_SNAKE_CASE =name.replace('bbox_embed' , 'bbox_predictor' ) if "vit.norm" in name: _SCREAMING_SNAKE_CASE =name.replace('vit.norm' , 'vit.layernorm' ) return name def _lowerCAmelCase ( _UpperCamelCase : dict , _UpperCamelCase : YolosForObjectDetection ) -> dict: """simple docstring""" for key in orig_state_dict.copy().keys(): _SCREAMING_SNAKE_CASE =orig_state_dict.pop(_UpperCamelCase ) if "qkv" in key: _SCREAMING_SNAKE_CASE =key.split('.' ) _SCREAMING_SNAKE_CASE =int(key_split[2] ) _SCREAMING_SNAKE_CASE =model.vit.encoder.layer[layer_num].attention.attention.all_head_size if "weight" in key: _SCREAMING_SNAKE_CASE =val[:dim, :] _SCREAMING_SNAKE_CASE =val[ dim : dim * 2, : ] _SCREAMING_SNAKE_CASE =val[-dim:, :] else: _SCREAMING_SNAKE_CASE =val[:dim] _SCREAMING_SNAKE_CASE =val[dim : dim * 2] _SCREAMING_SNAKE_CASE =val[-dim:] else: _SCREAMING_SNAKE_CASE =val return orig_state_dict def _lowerCAmelCase ( ) -> torch.Tensor: """simple docstring""" _SCREAMING_SNAKE_CASE ='http://images.cocodataset.org/val2017/000000039769.jpg' _SCREAMING_SNAKE_CASE =Image.open(requests.get(_UpperCamelCase , stream=_UpperCamelCase ).raw ) return im @torch.no_grad() def _lowerCAmelCase ( _UpperCamelCase : str , _UpperCamelCase : str , _UpperCamelCase : str , _UpperCamelCase : bool = False ) -> Optional[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE =get_yolos_config(_UpperCamelCase ) # load original state_dict _SCREAMING_SNAKE_CASE =torch.load(_UpperCamelCase , map_location='cpu' )['model'] # load 🤗 model _SCREAMING_SNAKE_CASE =YolosForObjectDetection(_UpperCamelCase ) model.eval() _SCREAMING_SNAKE_CASE =convert_state_dict(_UpperCamelCase , _UpperCamelCase ) model.load_state_dict(_UpperCamelCase ) # Check outputs on an image, prepared by YolosImageProcessor _SCREAMING_SNAKE_CASE =8_00 if yolos_name != 'yolos_ti' else 5_12 _SCREAMING_SNAKE_CASE =YolosImageProcessor(format='coco_detection' , size=_UpperCamelCase ) _SCREAMING_SNAKE_CASE =image_processor(images=prepare_img() , return_tensors='pt' ) _SCREAMING_SNAKE_CASE =model(**_UpperCamelCase ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =outputs.logits, outputs.pred_boxes _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE =None, None if yolos_name == "yolos_ti": _SCREAMING_SNAKE_CASE =torch.tensor( [[-39.50_22, -11.98_20, -17.68_88], [-29.95_74, -9.97_69, -17.76_91], [-42.32_81, -20.72_00, -30.62_94]] ) _SCREAMING_SNAKE_CASE =torch.tensor( [[0.40_21, 0.08_36, 0.79_79], [0.01_84, 0.26_09, 0.03_64], [0.17_81, 0.20_04, 0.20_95]] ) elif yolos_name == "yolos_s_200_pre": _SCREAMING_SNAKE_CASE =torch.tensor( [[-24.02_48, -10.30_24, -14.82_90], [-42.03_92, -16.82_00, -27.43_34], [-27.27_43, -11.81_54, -18.71_48]] ) _SCREAMING_SNAKE_CASE =torch.tensor( [[0.25_59, 0.54_55, 0.47_06], [0.29_89, 0.72_79, 0.18_75], [0.77_32, 0.40_17, 0.44_62]] ) elif yolos_name == "yolos_s_300_pre": _SCREAMING_SNAKE_CASE =torch.tensor( [[-36.22_20, -14.43_85, -23.54_57], [-35.69_70, -14.75_83, -21.39_35], [-31.59_39, -13.60_42, -16.80_49]] ) _SCREAMING_SNAKE_CASE =torch.tensor( [[0.76_14, 0.23_16, 0.47_28], [0.71_68, 0.44_95, 0.38_55], [0.49_96, 0.14_66, 0.99_96]] ) elif yolos_name == "yolos_s_dWr": _SCREAMING_SNAKE_CASE =torch.tensor( [[-42.86_68, -24.10_49, -41.16_90], [-34.74_56, -14.12_74, -24.91_94], [-33.78_98, -12.19_46, -25.64_95]] ) _SCREAMING_SNAKE_CASE =torch.tensor( [[0.55_87, 0.27_73, 0.06_05], [0.50_04, 0.30_14, 0.99_94], [0.49_99, 0.15_48, 0.99_94]] ) elif yolos_name == "yolos_base": _SCREAMING_SNAKE_CASE =torch.tensor( [[-40.60_64, -24.30_84, -32.64_47], [-55.19_90, -30.77_19, -35.58_77], [-51.43_11, -33.35_07, -35.64_62]] ) _SCREAMING_SNAKE_CASE =torch.tensor( [[0.55_55, 0.27_94, 0.06_55], [0.90_49, 0.26_64, 0.18_94], [0.91_83, 0.19_84, 0.16_35]] ) else: raise ValueError(f"Unknown yolos_name: {yolos_name}" ) assert torch.allclose(logits[0, :3, :3] , _UpperCamelCase , atol=1E-4 ) assert torch.allclose(pred_boxes[0, :3, :3] , _UpperCamelCase , atol=1E-4 ) Path(_UpperCamelCase ).mkdir(exist_ok=_UpperCamelCase ) print(f"Saving model {yolos_name} to {pytorch_dump_folder_path}" ) model.save_pretrained(_UpperCamelCase ) print(f"Saving image processor to {pytorch_dump_folder_path}" ) image_processor.save_pretrained(_UpperCamelCase ) if push_to_hub: _SCREAMING_SNAKE_CASE ={ 'yolos_ti': 'yolos-tiny', 'yolos_s_200_pre': 'yolos-small', 'yolos_s_300_pre': 'yolos-small-300', 'yolos_s_dWr': 'yolos-small-dwr', 'yolos_base': 'yolos-base', } print('Pushing to the hub...' ) _SCREAMING_SNAKE_CASE =model_mapping[yolos_name] image_processor.push_to_hub(_UpperCamelCase , organization='hustvl' ) model.push_to_hub(_UpperCamelCase , organization='hustvl' ) if __name__ == "__main__": lowerCamelCase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--yolos_name", default="yolos_s_200_pre", type=str, help=( "Name of the YOLOS model you'd like to convert. Should be one of 'yolos_ti', 'yolos_s_200_pre'," " 'yolos_s_300_pre', 'yolos_s_dWr', 'yolos_base'." ), ) parser.add_argument( "--checkpoint_path", default=None, type=str, help="Path to the original state dict (.pth file)." ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model to the 🤗 hub." ) lowerCamelCase : int = parser.parse_args() convert_yolos_checkpoint(args.yolos_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub)
47
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy as np import tensorflow as tf from transformers import ( TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST, FlaubertConfig, TFFlaubertForMultipleChoice, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForSequenceClassification, TFFlaubertForTokenClassification, TFFlaubertModel, TFFlaubertWithLMHeadModel, ) class __lowerCAmelCase : def __init__( self , __UpperCAmelCase , ): '''simple docstring''' __UpperCamelCase = parent __UpperCamelCase = 13 __UpperCamelCase = 7 __UpperCamelCase = True __UpperCamelCase = True __UpperCamelCase = True __UpperCamelCase = True __UpperCamelCase = True __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = 2 __UpperCamelCase = 99 __UpperCamelCase = 0 __UpperCamelCase = 32 __UpperCamelCase = 2 __UpperCamelCase = 4 __UpperCamelCase = 0.1 __UpperCamelCase = 0.1 __UpperCamelCase = 512 __UpperCamelCase = 16 __UpperCamelCase = 2 __UpperCamelCase = 0.0_2 __UpperCamelCase = 3 __UpperCamelCase = 4 __UpperCamelCase = 'last' __UpperCamelCase = True __UpperCamelCase = None __UpperCamelCase = 0 def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase = random_attention_mask([self.batch_size, self.seq_length] , dtype=tf.floataa ) __UpperCamelCase = None if self.use_input_lengths: __UpperCamelCase = ( ids_tensor([self.batch_size] , vocab_size=2 ) + self.seq_length - 2 ) # small variation of seq_length __UpperCamelCase = None if self.use_token_type_ids: __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.n_langs ) __UpperCamelCase = None __UpperCamelCase = None __UpperCamelCase = None if self.use_labels: __UpperCamelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCamelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __UpperCamelCase = ids_tensor([self.batch_size] , 2 , dtype=tf.floataa ) __UpperCamelCase = ids_tensor([self.batch_size] , self.num_choices ) __UpperCamelCase = FlaubertConfig( vocab_size=self.vocab_size , n_special=self.n_special , emb_dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , gelu_activation=self.gelu_activation , sinusoidal_embeddings=self.sinusoidal_embeddings , asm=self.asm , causal=self.causal , n_langs=self.n_langs , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , summary_type=self.summary_type , use_proj=self.use_proj , bos_token_id=self.bos_token_id , ) return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ): '''simple docstring''' __UpperCamelCase = TFFlaubertModel(config=__UpperCAmelCase ) __UpperCamelCase = {'input_ids': input_ids, 'lengths': input_lengths, 'langs': token_type_ids} __UpperCamelCase = model(__UpperCAmelCase ) __UpperCamelCase = [input_ids, input_mask] __UpperCamelCase = model(__UpperCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ): '''simple docstring''' __UpperCamelCase = TFFlaubertWithLMHeadModel(__UpperCAmelCase ) __UpperCamelCase = {'input_ids': input_ids, 'lengths': input_lengths, 'langs': token_type_ids} __UpperCamelCase = model(__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ): '''simple docstring''' __UpperCamelCase = TFFlaubertForQuestionAnsweringSimple(__UpperCAmelCase ) __UpperCamelCase = {'input_ids': input_ids, 'lengths': input_lengths} __UpperCamelCase = model(__UpperCAmelCase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ): '''simple docstring''' __UpperCamelCase = TFFlaubertForSequenceClassification(__UpperCAmelCase ) __UpperCamelCase = {'input_ids': input_ids, 'lengths': input_lengths} __UpperCamelCase = model(__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ): '''simple docstring''' __UpperCamelCase = self.num_labels __UpperCamelCase = TFFlaubertForTokenClassification(config=__UpperCAmelCase ) __UpperCamelCase = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} __UpperCamelCase = model(__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , ): '''simple docstring''' __UpperCamelCase = self.num_choices __UpperCamelCase = TFFlaubertForMultipleChoice(config=__UpperCAmelCase ) __UpperCamelCase = tf.tile(tf.expand_dims(__UpperCAmelCase , 1 ) , (1, self.num_choices, 1) ) __UpperCamelCase = tf.tile(tf.expand_dims(__UpperCAmelCase , 1 ) , (1, self.num_choices, 1) ) __UpperCamelCase = tf.tile(tf.expand_dims(__UpperCAmelCase , 1 ) , (1, self.num_choices, 1) ) __UpperCamelCase = { 'input_ids': multiple_choice_inputs_ids, 'attention_mask': multiple_choice_input_mask, 'token_type_ids': multiple_choice_token_type_ids, } __UpperCamelCase = model(__UpperCAmelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = self.prepare_config_and_inputs() ( ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ) = config_and_inputs __UpperCamelCase = { 'input_ids': input_ids, 'token_type_ids': token_type_ids, 'langs': token_type_ids, 'lengths': input_lengths, } return config, inputs_dict @require_tf class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): lowercase = ( ( TFFlaubertModel, TFFlaubertWithLMHeadModel, TFFlaubertForSequenceClassification, TFFlaubertForQuestionAnsweringSimple, TFFlaubertForTokenClassification, TFFlaubertForMultipleChoice, ) if is_tf_available() else () ) lowercase = ( (TFFlaubertWithLMHeadModel,) if is_tf_available() else () ) # TODO (PVP): Check other models whether language generation is also applicable lowercase = ( { "feature-extraction": TFFlaubertModel, "fill-mask": TFFlaubertWithLMHeadModel, "question-answering": TFFlaubertForQuestionAnsweringSimple, "text-classification": TFFlaubertForSequenceClassification, "token-classification": TFFlaubertForTokenClassification, "zero-shot": TFFlaubertForSequenceClassification, } if is_tf_available() else {} ) lowercase = False lowercase = False def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ): '''simple docstring''' if ( pipeline_test_casse_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith('Fast' ) ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = TFFlaubertModelTester(self ) __UpperCamelCase = ConfigTester(self , config_class=__UpperCAmelCase , emb_dim=37 ) def UpperCAmelCase ( self ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_model(*__UpperCAmelCase ) def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_lm_head(*__UpperCAmelCase ) def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_qa(*__UpperCAmelCase ) def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_sequence_classif(*__UpperCAmelCase ) def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_token_classification(*__UpperCAmelCase ) def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_flaubert_for_multiple_choice(*__UpperCAmelCase ) @slow def UpperCAmelCase ( self ): '''simple docstring''' for model_name in TF_FLAUBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase = TFFlaubertModel.from_pretrained(__UpperCAmelCase ) self.assertIsNotNone(__UpperCAmelCase ) @require_tf @require_sentencepiece @require_tokenizers class __lowerCAmelCase ( unittest.TestCase ): @slow def UpperCAmelCase ( self ): '''simple docstring''' __UpperCamelCase = TFFlaubertModel.from_pretrained('jplu/tf-flaubert-small-cased' ) __UpperCamelCase = tf.convert_to_tensor( [[0, 158, 735, 2592, 1424, 6727, 82, 1]] , dtype=tf.intaa , ) # "J'aime flaubert !" __UpperCamelCase = model(__UpperCAmelCase )[0] __UpperCamelCase = tf.TensorShape((1, 8, 512) ) self.assertEqual(output.shape , __UpperCAmelCase ) # compare the actual values for a slice. __UpperCamelCase = tf.convert_to_tensor( [ [ [-1.8_7_6_8_7_7_3, -1.5_6_6_5_5_5, 0.2_7_0_7_2_4_1_8], [-1.6_9_2_0_0_3_8, -0.5_8_7_3_5_0_5, 1.9_3_2_9_5_9_9], [-2.9_5_6_3_9_8_5, -1.6_9_9_3_8_3_5, 1.7_9_7_2_0_5_2], ] ] , dtype=tf.floataa , ) self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
316
0
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_flax, require_tf, require_torch from transformers.utils import ( expand_dims, flatten_dict, is_flax_available, is_tf_available, is_torch_available, reshape, squeeze, transpose, ) if is_flax_available(): import jax.numpy as jnp if is_tf_available(): import tensorflow as tf if is_torch_available(): import torch class lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __A ( self ) -> Dict: SCREAMING_SNAKE_CASE = { 'task_specific_params': { 'summarization': {'length_penalty': 1.0, 'max_length': 128, 'min_length': 12, 'num_beams': 4}, 'summarization_cnn': {'length_penalty': 2.0, 'max_length': 142, 'min_length': 56, 'num_beams': 4}, 'summarization_xsum': {'length_penalty': 1.0, 'max_length': 62, 'min_length': 11, 'num_beams': 6}, } } SCREAMING_SNAKE_CASE = { 'task_specific_params.summarization.length_penalty': 1.0, 'task_specific_params.summarization.max_length': 128, 'task_specific_params.summarization.min_length': 12, 'task_specific_params.summarization.num_beams': 4, 'task_specific_params.summarization_cnn.length_penalty': 2.0, 'task_specific_params.summarization_cnn.max_length': 142, 'task_specific_params.summarization_cnn.min_length': 56, 'task_specific_params.summarization_cnn.num_beams': 4, 'task_specific_params.summarization_xsum.length_penalty': 1.0, 'task_specific_params.summarization_xsum.max_length': 62, 'task_specific_params.summarization_xsum.min_length': 11, 'task_specific_params.summarization_xsum.num_beams': 6, } self.assertEqual(flatten_dict(lowerCAmelCase__ ) , lowerCAmelCase__ ) def __A ( self ) -> Optional[Any]: SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(transpose(lowerCAmelCase__ ) , x.transpose() ) ) SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(transpose(lowerCAmelCase__ , axes=(1, 2, 0) ) , x.transpose((1, 2, 0) ) ) ) @require_torch def __A ( self ) -> Dict: SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 ) SCREAMING_SNAKE_CASE = torch.tensor(lowerCAmelCase__ ) self.assertTrue(np.allclose(transpose(lowerCAmelCase__ ) , transpose(lowerCAmelCase__ ).numpy() ) ) SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 , 5 ) SCREAMING_SNAKE_CASE = torch.tensor(lowerCAmelCase__ ) self.assertTrue(np.allclose(transpose(lowerCAmelCase__ , axes=(1, 2, 0) ) , transpose(lowerCAmelCase__ , axes=(1, 2, 0) ).numpy() ) ) @require_tf def __A ( self ) -> Optional[int]: SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 ) SCREAMING_SNAKE_CASE = tf.constant(lowerCAmelCase__ ) self.assertTrue(np.allclose(transpose(lowerCAmelCase__ ) , transpose(lowerCAmelCase__ ).numpy() ) ) SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 , 5 ) SCREAMING_SNAKE_CASE = tf.constant(lowerCAmelCase__ ) self.assertTrue(np.allclose(transpose(lowerCAmelCase__ , axes=(1, 2, 0) ) , transpose(lowerCAmelCase__ , axes=(1, 2, 0) ).numpy() ) ) @require_flax def __A ( self ) -> List[str]: SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 ) SCREAMING_SNAKE_CASE = jnp.array(lowerCAmelCase__ ) self.assertTrue(np.allclose(transpose(lowerCAmelCase__ ) , np.asarray(transpose(lowerCAmelCase__ ) ) ) ) SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 , 5 ) SCREAMING_SNAKE_CASE = jnp.array(lowerCAmelCase__ ) self.assertTrue(np.allclose(transpose(lowerCAmelCase__ , axes=(1, 2, 0) ) , np.asarray(transpose(lowerCAmelCase__ , axes=(1, 2, 0) ) ) ) ) def __A ( self ) -> Optional[Any]: SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(reshape(lowerCAmelCase__ , (4, 3) ) , np.reshape(lowerCAmelCase__ , (4, 3) ) ) ) SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 , 5 ) self.assertTrue(np.allclose(reshape(lowerCAmelCase__ , (12, 5) ) , np.reshape(lowerCAmelCase__ , (12, 5) ) ) ) @require_torch def __A ( self ) -> str: SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 ) SCREAMING_SNAKE_CASE = torch.tensor(lowerCAmelCase__ ) self.assertTrue(np.allclose(reshape(lowerCAmelCase__ , (4, 3) ) , reshape(lowerCAmelCase__ , (4, 3) ).numpy() ) ) SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 , 5 ) SCREAMING_SNAKE_CASE = torch.tensor(lowerCAmelCase__ ) self.assertTrue(np.allclose(reshape(lowerCAmelCase__ , (12, 5) ) , reshape(lowerCAmelCase__ , (12, 5) ).numpy() ) ) @require_tf def __A ( self ) -> int: SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 ) SCREAMING_SNAKE_CASE = tf.constant(lowerCAmelCase__ ) self.assertTrue(np.allclose(reshape(lowerCAmelCase__ , (4, 3) ) , reshape(lowerCAmelCase__ , (4, 3) ).numpy() ) ) SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 , 5 ) SCREAMING_SNAKE_CASE = tf.constant(lowerCAmelCase__ ) self.assertTrue(np.allclose(reshape(lowerCAmelCase__ , (12, 5) ) , reshape(lowerCAmelCase__ , (12, 5) ).numpy() ) ) @require_flax def __A ( self ) -> int: SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 ) SCREAMING_SNAKE_CASE = jnp.array(lowerCAmelCase__ ) self.assertTrue(np.allclose(reshape(lowerCAmelCase__ , (4, 3) ) , np.asarray(reshape(lowerCAmelCase__ , (4, 3) ) ) ) ) SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 , 5 ) SCREAMING_SNAKE_CASE = jnp.array(lowerCAmelCase__ ) self.assertTrue(np.allclose(reshape(lowerCAmelCase__ , (12, 5) ) , np.asarray(reshape(lowerCAmelCase__ , (12, 5) ) ) ) ) def __A ( self ) -> List[str]: SCREAMING_SNAKE_CASE = np.random.randn(1 , 3 , 4 ) self.assertTrue(np.allclose(squeeze(lowerCAmelCase__ ) , np.squeeze(lowerCAmelCase__ ) ) ) SCREAMING_SNAKE_CASE = np.random.randn(1 , 4 , 1 , 5 ) self.assertTrue(np.allclose(squeeze(lowerCAmelCase__ , axis=2 ) , np.squeeze(lowerCAmelCase__ , axis=2 ) ) ) @require_torch def __A ( self ) -> List[str]: SCREAMING_SNAKE_CASE = np.random.randn(1 , 3 , 4 ) SCREAMING_SNAKE_CASE = torch.tensor(lowerCAmelCase__ ) self.assertTrue(np.allclose(squeeze(lowerCAmelCase__ ) , squeeze(lowerCAmelCase__ ).numpy() ) ) SCREAMING_SNAKE_CASE = np.random.randn(1 , 4 , 1 , 5 ) SCREAMING_SNAKE_CASE = torch.tensor(lowerCAmelCase__ ) self.assertTrue(np.allclose(squeeze(lowerCAmelCase__ , axis=2 ) , squeeze(lowerCAmelCase__ , axis=2 ).numpy() ) ) @require_tf def __A ( self ) -> str: SCREAMING_SNAKE_CASE = np.random.randn(1 , 3 , 4 ) SCREAMING_SNAKE_CASE = tf.constant(lowerCAmelCase__ ) self.assertTrue(np.allclose(squeeze(lowerCAmelCase__ ) , squeeze(lowerCAmelCase__ ).numpy() ) ) SCREAMING_SNAKE_CASE = np.random.randn(1 , 4 , 1 , 5 ) SCREAMING_SNAKE_CASE = tf.constant(lowerCAmelCase__ ) self.assertTrue(np.allclose(squeeze(lowerCAmelCase__ , axis=2 ) , squeeze(lowerCAmelCase__ , axis=2 ).numpy() ) ) @require_flax def __A ( self ) -> Tuple: SCREAMING_SNAKE_CASE = np.random.randn(1 , 3 , 4 ) SCREAMING_SNAKE_CASE = jnp.array(lowerCAmelCase__ ) self.assertTrue(np.allclose(squeeze(lowerCAmelCase__ ) , np.asarray(squeeze(lowerCAmelCase__ ) ) ) ) SCREAMING_SNAKE_CASE = np.random.randn(1 , 4 , 1 , 5 ) SCREAMING_SNAKE_CASE = jnp.array(lowerCAmelCase__ ) self.assertTrue(np.allclose(squeeze(lowerCAmelCase__ , axis=2 ) , np.asarray(squeeze(lowerCAmelCase__ , axis=2 ) ) ) ) def __A ( self ) -> List[Any]: SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 ) self.assertTrue(np.allclose(expand_dims(lowerCAmelCase__ , axis=1 ) , np.expand_dims(lowerCAmelCase__ , axis=1 ) ) ) @require_torch def __A ( self ) -> Any: SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 ) SCREAMING_SNAKE_CASE = torch.tensor(lowerCAmelCase__ ) self.assertTrue(np.allclose(expand_dims(lowerCAmelCase__ , axis=1 ) , expand_dims(lowerCAmelCase__ , axis=1 ).numpy() ) ) @require_tf def __A ( self ) -> str: SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 ) SCREAMING_SNAKE_CASE = tf.constant(lowerCAmelCase__ ) self.assertTrue(np.allclose(expand_dims(lowerCAmelCase__ , axis=1 ) , expand_dims(lowerCAmelCase__ , axis=1 ).numpy() ) ) @require_flax def __A ( self ) -> int: SCREAMING_SNAKE_CASE = np.random.randn(3 , 4 ) SCREAMING_SNAKE_CASE = jnp.array(lowerCAmelCase__ ) self.assertTrue(np.allclose(expand_dims(lowerCAmelCase__ , axis=1 ) , np.asarray(expand_dims(lowerCAmelCase__ , axis=1 ) ) ) )
38
"""simple docstring""" import json import os from typing import Optional, Tuple from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging __UpperCamelCase = logging.get_logger(__name__) __UpperCamelCase = {'''vocab_file''': '''vocab.json'''} __UpperCamelCase = { '''vocab_file''': { '''mgp-str''': '''https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json''', } } __UpperCamelCase = {'''mgp-str''': 27} class lowerCAmelCase ( lowerCamelCase_ ): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = VOCAB_FILES_NAMES SCREAMING_SNAKE_CASE_ : List[Any] = PRETRAINED_VOCAB_FILES_MAP SCREAMING_SNAKE_CASE_ : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , lowerCAmelCase__ , lowerCAmelCase__="[GO]" , lowerCAmelCase__="[GO]" , lowerCAmelCase__="[s]" , lowerCAmelCase__="[GO]" , **lowerCAmelCase__ ) -> int: super().__init__( unk_token=lowerCAmelCase__ , bos_token=lowerCAmelCase__ , eos_token=lowerCAmelCase__ , pad_token=lowerCAmelCase__ , **lowerCAmelCase__ , ) with open(lowerCAmelCase__ , encoding='utf-8' ) as vocab_handle: SCREAMING_SNAKE_CASE = json.load(lowerCAmelCase__ ) SCREAMING_SNAKE_CASE = {v: k for k, v in self.vocab.items()} @property def __A ( self ) -> List[str]: return len(self.vocab ) def __A ( self ) -> str: return dict(self.vocab , **self.added_tokens_encoder ) def __A ( self , lowerCAmelCase__ ) -> Tuple: SCREAMING_SNAKE_CASE = [] for s in text: char_tokens.extend(lowerCAmelCase__ ) return char_tokens def __A ( self , lowerCAmelCase__ ) -> int: return self.vocab.get(lowerCAmelCase__ , self.vocab.get(self.unk_token ) ) def __A ( self , lowerCAmelCase__ ) -> int: return self.decoder.get(lowerCAmelCase__ ) def __A ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> Tuple[str]: if not os.path.isdir(lowerCAmelCase__ ): logger.error('Vocabulary path ({}) should be a directory'.format(lowerCAmelCase__ ) ) return SCREAMING_SNAKE_CASE = os.path.join( lowerCAmelCase__ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) with open(lowerCAmelCase__ , 'w' , encoding='utf-8' ) as f: f.write(json.dumps(self.vocab , indent=2 , sort_keys=lowerCAmelCase__ , ensure_ascii=lowerCAmelCase__ ) + '\n' ) return (vocab_file,)
38
1
from __future__ import annotations class __a : def __init__( self : Tuple , SCREAMING_SNAKE_CASE : int ): '''simple docstring''' UpperCamelCase__ : List[Any] = data UpperCamelCase__ : Node | None = None UpperCamelCase__ : Node | None = None def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> Optional[int]: # In Order traversal of the tree if tree: display(tree.left ) print(tree.data ) display(tree.right ) def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> Optional[Any]: return 1 + max(depth_of_tree(tree.left ) , depth_of_tree(tree.right ) ) if tree else 0 def SCREAMING_SNAKE_CASE ( __lowerCAmelCase ) -> str: if not tree: return True if tree.left and tree.right: return is_full_binary_tree(tree.left ) and is_full_binary_tree(tree.right ) else: return not tree.left and not tree.right def SCREAMING_SNAKE_CASE ( ) -> List[str]: # Main function for testing. UpperCamelCase__ : Optional[int] = Node(1 ) UpperCamelCase__ : str = Node(2 ) UpperCamelCase__ : Optional[Any] = Node(3 ) UpperCamelCase__ : List[Any] = Node(4 ) UpperCamelCase__ : Dict = Node(5 ) UpperCamelCase__ : Union[str, Any] = Node(6 ) UpperCamelCase__ : Tuple = Node(7 ) UpperCamelCase__ : List[Any] = Node(8 ) UpperCamelCase__ : Optional[Any] = Node(9 ) print(is_full_binary_tree(UpperCAmelCase_ ) ) print(depth_of_tree(UpperCAmelCase_ ) ) print("Tree is: " ) display(UpperCAmelCase_ ) if __name__ == "__main__": main()
189
'''simple docstring''' import numpy as np def UpperCamelCase( UpperCAmelCase_ ): return (2 / (1 + np.exp(-2 * vector ))) - 1 if __name__ == "__main__": import doctest doctest.testmod()
151
0
import flax.linen as nn import jax import jax.numpy as jnp class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' __snake_case = 4_2 __snake_case = jnp.floataa def UpperCamelCase__ ( self ): snake_case_ = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self , _UpperCAmelCase ): snake_case_ , snake_case_ , snake_case_ , snake_case_ = hidden_states.shape snake_case_ = jax.image.resize( _UpperCAmelCase , shape=(batch, height * 2, width * 2, channels) , method='''nearest''' , ) snake_case_ = self.conv(_UpperCAmelCase ) return hidden_states class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' __snake_case = 4_2 __snake_case = jnp.floataa def UpperCamelCase__ ( self ): snake_case_ = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self , _UpperCAmelCase ): # pad = ((0, 0), (0, 1), (0, 1), (0, 0)) # pad height and width dim # hidden_states = jnp.pad(hidden_states, pad_width=pad) snake_case_ = self.conv(_UpperCAmelCase ) return hidden_states class lowerCAmelCase_ ( nn.Module ): '''simple docstring''' __snake_case = 4_2 __snake_case = None __snake_case = 0.0 __snake_case = None __snake_case = jnp.floataa def UpperCamelCase__ ( self ): snake_case_ = self.in_channels if self.out_channels is None else self.out_channels snake_case_ = nn.GroupNorm(num_groups=32 , epsilon=1E-5 ) snake_case_ = nn.Conv( _UpperCAmelCase , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) snake_case_ = nn.Dense(_UpperCAmelCase , dtype=self.dtype ) snake_case_ = nn.GroupNorm(num_groups=32 , epsilon=1E-5 ) snake_case_ = nn.Dropout(self.dropout_prob ) snake_case_ = nn.Conv( _UpperCAmelCase , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) snake_case_ = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut snake_case_ = None if use_nin_shortcut: snake_case_ = nn.Conv( _UpperCAmelCase , kernel_size=(1, 1) , strides=(1, 1) , padding='''VALID''' , dtype=self.dtype , ) def __call__( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=True ): snake_case_ = hidden_states snake_case_ = self.norma(_UpperCAmelCase ) snake_case_ = nn.swish(_UpperCAmelCase ) snake_case_ = self.conva(_UpperCAmelCase ) snake_case_ = self.time_emb_proj(nn.swish(_UpperCAmelCase ) ) snake_case_ = jnp.expand_dims(jnp.expand_dims(_UpperCAmelCase , 1 ) , 1 ) snake_case_ = hidden_states + temb snake_case_ = self.norma(_UpperCAmelCase ) snake_case_ = nn.swish(_UpperCAmelCase ) snake_case_ = self.dropout(_UpperCAmelCase , _UpperCAmelCase ) snake_case_ = self.conva(_UpperCAmelCase ) if self.conv_shortcut is not None: snake_case_ = self.conv_shortcut(_UpperCAmelCase ) return hidden_states + residual
364
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 lowerCAmelCase_ : '''simple docstring''' def __init__( self , _UpperCAmelCase , _UpperCAmelCase=99 , _UpperCAmelCase=13 , _UpperCAmelCase=7 , _UpperCAmelCase=9 , _UpperCAmelCase=True , _UpperCAmelCase=True , _UpperCAmelCase=False , _UpperCAmelCase=32 , _UpperCAmelCase=5 , _UpperCAmelCase=4 , _UpperCAmelCase=37 , _UpperCAmelCase=8 , _UpperCAmelCase=0.1 , _UpperCAmelCase=0.002 , _UpperCAmelCase=1 , _UpperCAmelCase=0 , _UpperCAmelCase=0 , _UpperCAmelCase=None , _UpperCAmelCase=None , ): snake_case_ = parent snake_case_ = batch_size snake_case_ = encoder_seq_length snake_case_ = decoder_seq_length # For common tests snake_case_ = self.decoder_seq_length snake_case_ = is_training snake_case_ = use_attention_mask snake_case_ = use_labels snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = d_ff snake_case_ = relative_attention_num_buckets snake_case_ = dropout_rate snake_case_ = initializer_factor snake_case_ = eos_token_id snake_case_ = pad_token_id snake_case_ = decoder_start_token_id snake_case_ = None snake_case_ = decoder_layers def UpperCamelCase__ ( self ): return TaConfig.from_pretrained('''google/umt5-base''' ) def UpperCamelCase__ ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=None , _UpperCAmelCase=None , ): if attention_mask is None: snake_case_ = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: snake_case_ = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: snake_case_ = torch.ones(config.num_hidden_layers , config.num_attention_heads , device=_UpperCAmelCase ) if decoder_head_mask is None: snake_case_ = torch.ones(config.num_decoder_layers , config.num_attention_heads , device=_UpperCAmelCase ) if cross_attn_head_mask is None: snake_case_ = torch.ones( config.num_decoder_layers , config.num_attention_heads , device=_UpperCAmelCase ) 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 UpperCamelCase__ ( self ): snake_case_ = ids_tensor([self.batch_size, self.encoder_seq_length] , self.vocab_size ) snake_case_ = 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 snake_case_ = input_ids.clamp(self.pad_token_id + 1 ) snake_case_ = decoder_input_ids.clamp(self.pad_token_id + 1 ) snake_case_ = self.get_config() snake_case_ = config.num_attention_heads snake_case_ = self.prepare_inputs_dict(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) return config, input_dict def UpperCamelCase__ ( self ): snake_case_ , snake_case_ = self.prepare_config_and_inputs() return config, inputs_dict def UpperCamelCase__ ( self ): return TaConfig( vocab_size=1_66 , 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 UpperCamelCase__ ( 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 UpperCamelCase__ ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ): snake_case_ = UMTaModel(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() snake_case_ = model( input_ids=_UpperCAmelCase , decoder_input_ids=_UpperCAmelCase , attention_mask=_UpperCAmelCase , decoder_attention_mask=_UpperCAmelCase , ) snake_case_ = model(input_ids=_UpperCAmelCase , decoder_input_ids=_UpperCAmelCase ) snake_case_ = result.last_hidden_state snake_case_ = result.past_key_values snake_case_ = 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(_UpperCAmelCase ) , 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 UpperCamelCase__ ( self , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ): snake_case_ = UMTaModel(config=_UpperCAmelCase ).get_decoder().to(_UpperCAmelCase ).eval() # first forward pass snake_case_ = model(_UpperCAmelCase , use_cache=_UpperCAmelCase ) snake_case_ = model(_UpperCAmelCase ) snake_case_ = model(_UpperCAmelCase , use_cache=_UpperCAmelCase ) self.parent.assertTrue(len(_UpperCAmelCase ) == len(_UpperCAmelCase ) ) self.parent.assertTrue(len(_UpperCAmelCase ) == len(_UpperCAmelCase ) + 1 ) snake_case_ , snake_case_ = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids snake_case_ = ids_tensor((self.batch_size, 1) , config.vocab_size ) # append to next input_ids and snake_case_ = torch.cat([input_ids, next_tokens] , dim=-1 ) snake_case_ = model(_UpperCAmelCase )['''last_hidden_state'''] snake_case_ = model(_UpperCAmelCase , past_key_values=_UpperCAmelCase )['''last_hidden_state'''] # select random slice snake_case_ = ids_tensor((1,) , output_from_past.shape[-1] ).item() snake_case_ = output_from_no_past[:, -1, random_slice_idx].detach() snake_case_ = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(_UpperCAmelCase , _UpperCAmelCase , atol=1E-3 ) ) def UpperCamelCase__ ( self , _UpperCAmelCase , _UpperCAmelCase , ): snake_case_ = UMTaModel(config=_UpperCAmelCase ).to(_UpperCAmelCase ).half().eval() snake_case_ = model(**_UpperCAmelCase )['''last_hidden_state'''] self.parent.assertFalse(torch.isnan(_UpperCAmelCase ).any().item() ) @require_torch class lowerCAmelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): '''simple docstring''' __snake_case = ( (UMTaModel, UMTaForConditionalGeneration, UMTaForQuestionAnswering) if is_torch_available() else () ) __snake_case = (UMTaForConditionalGeneration,) if is_torch_available() else () __snake_case = ( { "conversational": UMTaForConditionalGeneration, "feature-extraction": UMTaModel, "summarization": UMTaForConditionalGeneration, "text2text-generation": UMTaForConditionalGeneration, "translation": UMTaForConditionalGeneration, "question-answering": UMTaForQuestionAnswering, } if is_torch_available() else {} ) __snake_case = True __snake_case = False __snake_case = False __snake_case = True __snake_case = True # The small UMT5 model needs higher percentages for CPU/MP tests __snake_case = [0.8, 0.9] def UpperCamelCase__ ( self ): snake_case_ = UMTaModelTester(self ) @unittest.skip('''Test has a segmentation fault on torch 1.8.0''' ) def UpperCamelCase__ ( self ): snake_case_ = self.model_tester.prepare_config_and_inputs() snake_case_ = UMTaModel(config_and_inputs[0] ).to(_UpperCAmelCase ) with tempfile.TemporaryDirectory() as tmpdirname: torch.onnx.export( _UpperCAmelCase , (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]) , F'''{tmpdirname}/t5_test.onnx''' , export_params=_UpperCAmelCase , opset_version=9 , input_names=['''input_ids''', '''decoder_input_ids'''] , ) @unittest.skipIf(torch_device == '''cpu''' , '''Cant do half precision''' ) def UpperCamelCase__ ( self ): snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model_fpaa_forward(*_UpperCAmelCase ) def UpperCamelCase__ ( self ): snake_case_ = ['''encoder_attentions''', '''decoder_attentions''', '''cross_attentions'''] snake_case_ = self.model_tester.prepare_config_and_inputs() snake_case_ = config_and_inputs[0] snake_case_ = UMTaForConditionalGeneration(_UpperCAmelCase ).eval() model.to(_UpperCAmelCase ) snake_case_ = { '''head_mask''': torch.zeros(config.num_layers , config.num_heads , device=_UpperCAmelCase ), '''decoder_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=_UpperCAmelCase ), '''cross_attn_head_mask''': torch.zeros(config.num_decoder_layers , config.num_heads , device=_UpperCAmelCase ), } for attn_name, (name, mask) in zip(_UpperCAmelCase , head_masking.items() ): snake_case_ = {name: mask} # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified if name == "head_mask": snake_case_ = torch.ones( config.num_decoder_layers , config.num_heads , device=_UpperCAmelCase ) snake_case_ = model.generate( config_and_inputs[1]['''input_ids'''] , num_beams=1 , max_length=3 , output_attentions=_UpperCAmelCase , return_dict_in_generate=_UpperCAmelCase , **_UpperCAmelCase , ) # We check the state of decoder_attentions and cross_attentions just from the last step snake_case_ = 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 UpperCamelCase__ ( self ): pass @require_torch @require_sentencepiece @require_tokenizers class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @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 UpperCamelCase__ ( self ): snake_case_ = UMTaForConditionalGeneration.from_pretrained('''google/umt5-small''' , return_dict=_UpperCAmelCase ).to(_UpperCAmelCase ) snake_case_ = AutoTokenizer.from_pretrained('''google/umt5-small''' , use_fast=_UpperCAmelCase , legacy=_UpperCAmelCase ) snake_case_ = [ '''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>.''', ] snake_case_ = tokenizer(_UpperCAmelCase , return_tensors='''pt''' , padding=_UpperCAmelCase ).input_ids # fmt: off snake_case_ = torch.tensor( [ [ 3_85_30, 21_07_03, 25_62_99, 14_10, 25_62_98, 2_74, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 8_26, 3_21, 6_71, 2_59_22, 25_62_99, 2_74, 1, 0,0, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 14_60, 3_39, 3_12, 1_90_14, 1_06_20, 7_58, 25_62_99, 23_55,2_74, 1, 0, 0, 0, 0, 0, 0,0, 0], [ 5_17, 25_62_99, 1_48_69, 2_81, 3_01, 25_62_98, 2_75, 11_99_83,1, 0, 0, 0, 0, 0, 0, 0,0, 0], [ 3_20, 25_62_99, 1_48_69, 2_81, 22_34, 2_89, 22_75, 3_33,6_13_91, 2_89, 25_62_98, 5_43, 25_62_97, 16_87_14, 3_29, 25_62_96,2_74, 1], ] ) # fmt: on torch.testing.assert_allclose(_UpperCAmelCase , _UpperCAmelCase ) snake_case_ = model.generate(input_ids.to(_UpperCAmelCase ) ) snake_case_ = [ '''<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>''', ] snake_case_ = tokenizer.batch_decode(_UpperCAmelCase ) self.assertEqual(_UpperCAmelCase , _UpperCAmelCase )
267
0
'''simple docstring''' from jiwer import compute_measures import datasets __lowerCAmelCase = '\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n' __lowerCAmelCase = '\\nWord error rate (WER) is a common metric of the performance of an automatic speech recognition system.\n\nThe general difficulty of measuring performance lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the Levenshtein distance, working at the word level instead of the phoneme level. The WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort.\n\nThis problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between perplexity and word error rate.\n\nWord error rate can then be computed as:\n\nWER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct words,\nN is the number of words in the reference (N=S+D+C).\n\nThis value indicates the average number of errors per reference word. The lower the value, the better the\nperformance of the ASR system with a WER of 0 being a perfect score.\n' __lowerCAmelCase = '\nCompute WER score of transcribed segments against references.\n\nArgs:\n references: List of references for each speech input.\n predictions: List of transcriptions to score.\n concatenate_texts (bool, default=False): Whether to concatenate all input texts or compute WER iteratively.\n\nReturns:\n (float): the word error rate\n\nExamples:\n\n >>> predictions = ["this is the prediction", "there is an other sample"]\n >>> references = ["this is the reference", "there is another one"]\n >>> wer = datasets.load_metric("wer")\n >>> wer_score = wer.compute(predictions=predictions, references=references)\n >>> print(wer_score)\n 0.5\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _lowerCAmelCase ( datasets.Metric ): '''simple docstring''' def lowercase (self ) -> List[str]: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { """predictions""": datasets.Value("""string""" , id="""sequence""" ), """references""": datasets.Value("""string""" , id="""sequence""" ), } ) , codebase_urls=["""https://github.com/jitsi/jiwer/"""] , reference_urls=[ """https://en.wikipedia.org/wiki/Word_error_rate""", ] , ) def lowercase (self , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=False ) -> Dict: if concatenate_texts: return compute_measures(UpperCAmelCase , UpperCAmelCase )["wer"] else: _snake_case = 0 _snake_case = 0 for prediction, reference in zip(UpperCAmelCase , UpperCAmelCase ): _snake_case = compute_measures(UpperCAmelCase , UpperCAmelCase ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
341
'''simple docstring''' from __future__ import annotations def __SCREAMING_SNAKE_CASE ( _SCREAMING_SNAKE_CASE ): if len(_SCREAMING_SNAKE_CASE ) == 0: return [] _snake_case, _snake_case = min(_SCREAMING_SNAKE_CASE ), max(_SCREAMING_SNAKE_CASE ) _snake_case = int(max_value - min_value ) + 1 _snake_case = [[] for _ in range(_SCREAMING_SNAKE_CASE )] for i in my_list: buckets[int(i - min_value )].append(_SCREAMING_SNAKE_CASE ) return [v for bucket in buckets for v in sorted(_SCREAMING_SNAKE_CASE )] if __name__ == "__main__": from doctest import testmod testmod() assert bucket_sort([4, 5, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bucket_sort([0, 1, -10, 15, 2, -2]) == [-10, -2, 0, 1, 2, 15]
341
1
def SCREAMING_SNAKE_CASE ( snake_case_ : int , snake_case_ : int ): return int((input_a, input_a).count(1 ) != 0 ) def SCREAMING_SNAKE_CASE ( ): assert or_gate(0 , 0 ) == 0 assert or_gate(0 , 1 ) == 1 assert or_gate(1 , 0 ) == 1 assert or_gate(1 , 1 ) == 1 if __name__ == "__main__": print(or_gate(0, 1)) print(or_gate(1, 0)) print(or_gate(0, 0)) print(or_gate(1, 1))
286
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 SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): """simple docstring""" def __init__( self : List[str] , __A : int , __A : str=7 , __A : Union[str, Any]=3 , __A : Union[str, Any]=3_0 , __A : Optional[int]=4_0_0 , __A : Optional[Any]=True , __A : Optional[int]=None , __A : Union[str, Any]=True , __A : Optional[int]=[0.5, 0.5, 0.5] , __A : Any=[0.5, 0.5, 0.5] , __A : Optional[int]=True , __A : Optional[Any]=1 / 2_5_5 , __A : Union[str, Any]=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p snake_case__ : Optional[Any] = size if size is not None else {"shortest_edge": 1_8, "longest_edge": 1_3_3_3} snake_case__ : List[Any] = parent snake_case__ : Union[str, Any] = batch_size snake_case__ : Tuple = num_channels snake_case__ : List[Any] = min_resolution snake_case__ : Optional[Any] = max_resolution snake_case__ : str = do_resize snake_case__ : List[str] = size snake_case__ : List[Any] = do_normalize snake_case__ : Dict = image_mean snake_case__ : List[Any] = image_std snake_case__ : int = do_rescale snake_case__ : Tuple = rescale_factor snake_case__ : str = do_pad def _lowercase ( self : List[str] ): 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 _lowercase ( self : Optional[Any] , __A : Dict , __A : Union[str, Any]=False ): if not batched: snake_case__ : List[str] = image_inputs[0] if isinstance(__A , Image.Image ): snake_case__, snake_case__ : Any = image.size else: snake_case__, snake_case__ : List[str] = image.shape[1], image.shape[2] if w < h: snake_case__ : List[str] = int(self.size["shortest_edge"] * h / w ) snake_case__ : Tuple = self.size["shortest_edge"] elif w > h: snake_case__ : Optional[int] = self.size["shortest_edge"] snake_case__ : Union[str, Any] = int(self.size["shortest_edge"] * w / h ) else: snake_case__ : Optional[Any] = self.size["shortest_edge"] snake_case__ : List[Any] = self.size["shortest_edge"] else: snake_case__ : Union[str, Any] = [] for image in image_inputs: snake_case__, snake_case__ : int = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) snake_case__ : Any = max(__A , key=lambda __A : item[0] )[0] snake_case__ : Optional[int] = max(__A , key=lambda __A : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class SCREAMING_SNAKE_CASE__ ( UpperCamelCase_ , unittest.TestCase ): """simple docstring""" a_ = DeformableDetrImageProcessor if is_vision_available() else None def _lowercase ( self : Optional[int] ): snake_case__ : str = DeformableDetrImageProcessingTester(self ) @property def _lowercase ( self : List[Any] ): return self.image_processor_tester.prepare_image_processor_dict() def _lowercase ( self : Union[str, Any] ): snake_case__ : int = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__A , "image_mean" ) ) self.assertTrue(hasattr(__A , "image_std" ) ) self.assertTrue(hasattr(__A , "do_normalize" ) ) self.assertTrue(hasattr(__A , "do_resize" ) ) self.assertTrue(hasattr(__A , "do_rescale" ) ) self.assertTrue(hasattr(__A , "do_pad" ) ) self.assertTrue(hasattr(__A , "size" ) ) def _lowercase ( self : Tuple ): snake_case__ : int = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 1_8, "longest_edge": 1_3_3_3} ) self.assertEqual(image_processor.do_pad , __A ) snake_case__ : List[Any] = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=__A ) self.assertEqual(image_processor.size , {"shortest_edge": 4_2, "longest_edge": 8_4} ) self.assertEqual(image_processor.do_pad , __A ) def _lowercase ( self : Any ): pass def _lowercase ( self : Optional[int] ): # Initialize image_processing snake_case__ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images snake_case__ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A ) for image in image_inputs: self.assertIsInstance(__A , Image.Image ) # Test not batched input snake_case__ : Tuple = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values snake_case__, snake_case__ : Dict = self.image_processor_tester.get_expected_values(__A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched snake_case__, snake_case__ : Optional[Any] = self.image_processor_tester.get_expected_values(__A , batched=__A ) snake_case__ : Union[str, Any] = image_processing(__A , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _lowercase ( self : Any ): # Initialize image_processing snake_case__ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors snake_case__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A , numpify=__A ) for image in image_inputs: self.assertIsInstance(__A , np.ndarray ) # Test not batched input snake_case__ : Union[str, Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values snake_case__, snake_case__ : Union[str, Any] = self.image_processor_tester.get_expected_values(__A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched snake_case__ : Union[str, Any] = image_processing(__A , return_tensors="pt" ).pixel_values snake_case__, snake_case__ : Any = self.image_processor_tester.get_expected_values(__A , batched=__A ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _lowercase ( self : Union[str, Any] ): # Initialize image_processing snake_case__ : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors snake_case__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__A , torchify=__A ) for image in image_inputs: self.assertIsInstance(__A , torch.Tensor ) # Test not batched input snake_case__ : Tuple = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values snake_case__, snake_case__ : List[Any] = self.image_processor_tester.get_expected_values(__A ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched snake_case__ : Optional[Any] = image_processing(__A , return_tensors="pt" ).pixel_values snake_case__, snake_case__ : int = self.image_processor_tester.get_expected_values(__A , batched=__A ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def _lowercase ( self : Optional[int] ): # prepare image and target snake_case__ : List[Any] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: snake_case__ : Any = json.loads(f.read() ) snake_case__ : List[str] = {"image_id": 3_9_7_6_9, "annotations": target} # encode them snake_case__ : Optional[Any] = DeformableDetrImageProcessor() snake_case__ : Tuple = image_processing(images=__A , annotations=__A , return_tensors="pt" ) # verify pixel values snake_case__ : str = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding["pixel_values"].shape , __A ) snake_case__ : int = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , __A , atol=1e-4 ) ) # verify area snake_case__ : int = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , __A ) ) # verify boxes snake_case__ : str = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , __A ) snake_case__ : List[Any] = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , __A , atol=1e-3 ) ) # verify image_id snake_case__ : int = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , __A ) ) # verify is_crowd snake_case__ : Dict = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , __A ) ) # verify class_labels snake_case__ : Optional[int] = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , __A ) ) # verify orig_size snake_case__ : Union[str, Any] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , __A ) ) # verify size snake_case__ : List[str] = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , __A ) ) @slow def _lowercase ( self : Union[str, Any] ): # prepare image, target and masks_path snake_case__ : str = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f: snake_case__ : Optional[int] = json.loads(f.read() ) snake_case__ : Any = {"file_name": "000000039769.png", "image_id": 3_9_7_6_9, "segments_info": target} snake_case__ : List[Any] = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them snake_case__ : Dict = DeformableDetrImageProcessor(format="coco_panoptic" ) snake_case__ : List[Any] = image_processing(images=__A , annotations=__A , masks_path=__A , return_tensors="pt" ) # verify pixel values snake_case__ : Optional[int] = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding["pixel_values"].shape , __A ) snake_case__ : Tuple = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , __A , atol=1e-4 ) ) # verify area snake_case__ : Any = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding["labels"][0]["area"] , __A ) ) # verify boxes snake_case__ : Union[str, Any] = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , __A ) snake_case__ : Tuple = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , __A , atol=1e-3 ) ) # verify image_id snake_case__ : Union[str, Any] = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , __A ) ) # verify is_crowd snake_case__ : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , __A ) ) # verify class_labels snake_case__ : List[str] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , __A ) ) # verify masks snake_case__ : Optional[Any] = 8_2_2_8_7_3 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , __A ) # verify orig_size snake_case__ : Dict = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , __A ) ) # verify size snake_case__ : Dict = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , __A ) )
286
1
'''simple docstring''' from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Sequence, Value from .base import TaskTemplate @dataclass(frozen=_a ) class SCREAMING_SNAKE_CASE ( _a ): """simple docstring""" _SCREAMING_SNAKE_CASE = field(default="""question-answering-extractive""" , metadata={"""include_in_asdict_even_if_is_default""": True} ) _SCREAMING_SNAKE_CASE = Features({"""question""": Value("""string""" ), """context""": Value("""string""" )} ) _SCREAMING_SNAKE_CASE = Features( { """answers""": Sequence( { """text""": Value("""string""" ), """answer_start""": Value("""int32""" ), } ) } ) _SCREAMING_SNAKE_CASE = "question" _SCREAMING_SNAKE_CASE = "context" _SCREAMING_SNAKE_CASE = "answers" @property def A ( self : Dict ): """simple docstring""" return {self.question_column: "question", self.context_column: "context", self.answers_column: "answers"}
28
import os def a_ ( ) -> Optional[Any]: """simple docstring""" snake_case__ = os.path.join(os.path.dirname(_A ) , 'num.txt' ) with open(_A ) as file_hand: return str(sum(int(_A ) for line in file_hand ) )[:10] if __name__ == "__main__": print(solution())
307
0
"""simple docstring""" import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging A_ = logging.get_logger(__name__) A_ = { '''microsoft/git-base''': '''https://huggingface.co/microsoft/git-base/resolve/main/config.json''', } class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = 'git_vision_model' def __init__( self : Union[str, Any] , snake_case : Any=768 , snake_case : Optional[int]=3072 , snake_case : Tuple=12 , snake_case : Any=12 , snake_case : Dict=3 , snake_case : Dict=224 , snake_case : List[str]=16 , snake_case : Optional[int]="quick_gelu" , snake_case : Optional[int]=1e-5 , snake_case : Tuple=0.0 , snake_case : Optional[int]=0.02 , **snake_case : Optional[Any] , ): '''simple docstring''' super().__init__(**snake_case ) A__ : Dict = hidden_size A__ : Optional[Any] = intermediate_size A__ : List[str] = num_hidden_layers A__ : Optional[Any] = num_attention_heads A__ : Any = num_channels A__ : Tuple = patch_size A__ : Any = image_size A__ : str = initializer_range A__ : Any = attention_dropout A__ : List[str] = layer_norm_eps A__ : Tuple = hidden_act @classmethod def _UpperCamelCase ( cls : str , snake_case : Union[str, os.PathLike] , **snake_case : Any ): '''simple docstring''' cls._set_token_in_kwargs(snake_case ) A__ , A__ : Any = cls.get_config_dict(snake_case , **snake_case ) # get the vision config dict if we are loading from GITConfig if config_dict.get("""model_type""" ) == "git": A__ : Tuple = config_dict["""vision_config"""] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(snake_case , **snake_case ) class __SCREAMING_SNAKE_CASE ( UpperCamelCase ): snake_case_ = 'git' def __init__( self : Any , snake_case : Tuple=None , snake_case : int=3_0522 , snake_case : Optional[int]=768 , snake_case : int=6 , snake_case : int=12 , snake_case : Optional[Any]=3072 , snake_case : Dict="gelu" , snake_case : str=0.1 , snake_case : int=0.1 , snake_case : Dict=1024 , snake_case : Optional[Any]=0.02 , snake_case : Optional[int]=1e-12 , snake_case : int=0 , snake_case : int="absolute" , snake_case : List[str]=True , snake_case : List[str]=False , snake_case : List[str]=101 , snake_case : int=102 , snake_case : Tuple=None , **snake_case : Optional[Any] , ): '''simple docstring''' super().__init__(bos_token_id=snake_case , eos_token_id=snake_case , pad_token_id=snake_case , **snake_case ) if vision_config is None: A__ : Any = {} logger.info("""vision_config is None. initializing the GitVisionConfig with default values.""" ) A__ : Union[str, Any] = GitVisionConfig(**snake_case ) A__ : Any = vocab_size A__ : Optional[int] = hidden_size A__ : List[str] = num_hidden_layers A__ : Dict = num_attention_heads A__ : List[Any] = hidden_act A__ : Tuple = intermediate_size A__ : str = hidden_dropout_prob A__ : List[Any] = attention_probs_dropout_prob A__ : Any = max_position_embeddings A__ : Union[str, Any] = initializer_range A__ : Union[str, Any] = layer_norm_eps A__ : Dict = position_embedding_type A__ : List[str] = use_cache A__ : List[Any] = tie_word_embeddings A__ : List[str] = num_image_with_embedding A__ : str = bos_token_id A__ : int = eos_token_id def _UpperCamelCase ( self : Optional[int] ): '''simple docstring''' A__ : Union[str, Any] = copy.deepcopy(self.__dict__ ) A__ : Union[str, Any] = self.vision_config.to_dict() A__ : str = self.__class__.model_type return output
296
"""simple docstring""" import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTConfig, DeiTForImageClassificationWithTeacher, DeiTImageProcessor from transformers.utils import logging logging.set_verbosity_info() A_ = logging.get_logger(__name__) def _lowerCAmelCase ( UpperCAmelCase__ : Union[str, Any], UpperCAmelCase__ : Tuple=False ) ->str: A__ : Optional[int] = [] 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'deit.encoder.layer.{i}.layernorm_before.weight') ) rename_keys.append((f'blocks.{i}.norm1.bias', f'deit.encoder.layer.{i}.layernorm_before.bias') ) rename_keys.append((f'blocks.{i}.attn.proj.weight', f'deit.encoder.layer.{i}.attention.output.dense.weight') ) rename_keys.append((f'blocks.{i}.attn.proj.bias', f'deit.encoder.layer.{i}.attention.output.dense.bias') ) rename_keys.append((f'blocks.{i}.norm2.weight', f'deit.encoder.layer.{i}.layernorm_after.weight') ) rename_keys.append((f'blocks.{i}.norm2.bias', f'deit.encoder.layer.{i}.layernorm_after.bias') ) rename_keys.append((f'blocks.{i}.mlp.fc1.weight', f'deit.encoder.layer.{i}.intermediate.dense.weight') ) rename_keys.append((f'blocks.{i}.mlp.fc1.bias', f'deit.encoder.layer.{i}.intermediate.dense.bias') ) rename_keys.append((f'blocks.{i}.mlp.fc2.weight', f'deit.encoder.layer.{i}.output.dense.weight') ) rename_keys.append((f'blocks.{i}.mlp.fc2.bias', f'deit.encoder.layer.{i}.output.dense.bias') ) # projection layer + position embeddings rename_keys.extend( [ ("""cls_token""", """deit.embeddings.cls_token"""), ("""dist_token""", """deit.embeddings.distillation_token"""), ("""patch_embed.proj.weight""", """deit.embeddings.patch_embeddings.projection.weight"""), ("""patch_embed.proj.bias""", """deit.embeddings.patch_embeddings.projection.bias"""), ("""pos_embed""", """deit.embeddings.position_embeddings"""), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("""norm.weight""", """layernorm.weight"""), ("""norm.bias""", """layernorm.bias"""), ("""pre_logits.fc.weight""", """pooler.dense.weight"""), ("""pre_logits.fc.bias""", """pooler.dense.bias"""), ] ) # if just the base model, we should remove "deit" from all keys that start with "deit" A__ : Optional[int] = [(pair[0], pair[1][4:]) if pair[1].startswith("""deit""" ) else pair for pair in rename_keys] else: # layernorm + classification heads rename_keys.extend( [ ("""norm.weight""", """deit.layernorm.weight"""), ("""norm.bias""", """deit.layernorm.bias"""), ("""head.weight""", """cls_classifier.weight"""), ("""head.bias""", """cls_classifier.bias"""), ("""head_dist.weight""", """distillation_classifier.weight"""), ("""head_dist.bias""", """distillation_classifier.bias"""), ] ) return rename_keys def _lowerCAmelCase ( UpperCAmelCase__ : Optional[int], UpperCAmelCase__ : Tuple, UpperCAmelCase__ : List[Any]=False ) ->str: for i in range(config.num_hidden_layers ): if base_model: A__ : Any = """""" else: A__ : Tuple = """deit.""" # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) A__ : Any = state_dict.pop(f'blocks.{i}.attn.qkv.weight' ) A__ : Tuple = state_dict.pop(f'blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict A__ : List[Any] = in_proj_weight[ : config.hidden_size, : ] A__ : str = in_proj_bias[: config.hidden_size] A__ : Any = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] A__ : Dict = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] A__ : Optional[Any] = in_proj_weight[ -config.hidden_size :, : ] A__ : Any = in_proj_bias[-config.hidden_size :] def _lowerCAmelCase ( UpperCAmelCase__ : List[Any], UpperCAmelCase__ : List[Any], UpperCAmelCase__ : Union[str, Any] ) ->Any: A__ : int = dct.pop(UpperCAmelCase__ ) A__ : Tuple = val def _lowerCAmelCase ( ) ->List[Any]: A__ : Optional[int] = """http://images.cocodataset.org/val2017/000000039769.jpg""" A__ : int = Image.open(requests.get(UpperCAmelCase__, stream=UpperCAmelCase__ ).raw ) return im @torch.no_grad() def _lowerCAmelCase ( UpperCAmelCase__ : Dict, UpperCAmelCase__ : Any ) ->Tuple: A__ : List[Any] = DeiTConfig() # all deit models have fine-tuned heads A__ : Tuple = False # dataset (fine-tuned on ImageNet 2012), patch_size and image_size A__ : str = 1_0_0_0 A__ : List[str] = """huggingface/label-files""" A__ : Dict = """imagenet-1k-id2label.json""" A__ : List[str] = json.load(open(hf_hub_download(UpperCAmelCase__, UpperCAmelCase__, repo_type="""dataset""" ), """r""" ) ) A__ : Dict = {int(UpperCAmelCase__ ): v for k, v in idalabel.items()} A__ : Optional[int] = idalabel A__ : Dict = {v: k for k, v in idalabel.items()} A__ : List[str] = int(deit_name[-6:-4] ) A__ : str = int(deit_name[-3:] ) # size of the architecture if deit_name[9:].startswith("""tiny""" ): A__ : List[str] = 1_9_2 A__ : int = 7_6_8 A__ : List[Any] = 1_2 A__ : Dict = 3 elif deit_name[9:].startswith("""small""" ): A__ : List[Any] = 3_8_4 A__ : List[str] = 1_5_3_6 A__ : Any = 1_2 A__ : Union[str, Any] = 6 if deit_name[9:].startswith("""base""" ): pass elif deit_name[4:].startswith("""large""" ): A__ : int = 1_0_2_4 A__ : str = 4_0_9_6 A__ : Any = 2_4 A__ : int = 1_6 # load original model from timm A__ : Dict = timm.create_model(UpperCAmelCase__, pretrained=UpperCAmelCase__ ) timm_model.eval() # load state_dict of original model, remove and rename some keys A__ : Tuple = timm_model.state_dict() A__ : str = create_rename_keys(UpperCAmelCase__, UpperCAmelCase__ ) for src, dest in rename_keys: rename_key(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) read_in_q_k_v(UpperCAmelCase__, UpperCAmelCase__, UpperCAmelCase__ ) # load HuggingFace model A__ : str = DeiTForImageClassificationWithTeacher(UpperCAmelCase__ ).eval() model.load_state_dict(UpperCAmelCase__ ) # Check outputs on an image, prepared by DeiTImageProcessor A__ : int = int( (2_5_6 / 2_2_4) * config.image_size ) # to maintain same ratio w.r.t. 224 images, see https://github.com/facebookresearch/deit/blob/ab5715372db8c6cad5740714b2216d55aeae052e/datasets.py#L103 A__ : Any = DeiTImageProcessor(size=UpperCAmelCase__, crop_size=config.image_size ) A__ : Union[str, Any] = image_processor(images=prepare_img(), return_tensors="""pt""" ) A__ : Optional[Any] = encoding["""pixel_values"""] A__ : Union[str, Any] = model(UpperCAmelCase__ ) A__ : Union[str, Any] = timm_model(UpperCAmelCase__ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(UpperCAmelCase__, outputs.logits, atol=1e-3 ) Path(UpperCAmelCase__ ).mkdir(exist_ok=UpperCAmelCase__ ) print(f'Saving model {deit_name} to {pytorch_dump_folder_path}' ) model.save_pretrained(UpperCAmelCase__ ) print(f'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(UpperCAmelCase__ ) if __name__ == "__main__": A_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--deit_name''', default='''vit_deit_base_distilled_patch16_224''', type=str, help='''Name of the DeiT timm model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) A_ = parser.parse_args() convert_deit_checkpoint(args.deit_name, args.pytorch_dump_folder_path)
296
1
"""simple docstring""" import doctest import logging import os import unittest from pathlib import Path from typing import List, Union import transformers from transformers.testing_utils import require_tf, require_torch, slow _UpperCamelCase: Tuple = logging.getLogger() @unittest.skip('Temporarily disable the doc tests.' ) @require_torch @require_tf @slow class a__ ( unittest.TestCase ): def lowercase ( self : Optional[int], lowerCAmelCase : Path, lowerCAmelCase : Union[str, None] = None, lowerCAmelCase : Union[List[str], None] = None, lowerCAmelCase : Union[str, List[str], None] = None, lowerCAmelCase : bool = True, ) -> Optional[Any]: lowercase : Optional[int] = [file for file in os.listdir(UpperCAmelCase_ ) if os.path.isfile(os.path.join(UpperCAmelCase_, UpperCAmelCase_ ) )] if identifier is not None: lowercase : Tuple = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(UpperCAmelCase_, UpperCAmelCase_ ): for n_ in n_identifier: lowercase : Any = [file for file in files if n_ not in file] else: lowercase : str = [file for file in files if n_identifier not in file] lowercase : Optional[Any] = ignore_files or [] ignore_files.append('__init__.py' ) lowercase : Optional[int] = [file for file in files if file not in ignore_files] for file in files: # Open all files print('Testing', UpperCAmelCase_ ) if only_modules: lowercase : Tuple = file.split('.' )[0] try: lowercase : List[Any] = getattr(UpperCAmelCase_, UpperCAmelCase_ ) lowercase : str = doctest.DocTestSuite(UpperCAmelCase_ ) lowercase : List[str] = unittest.TextTestRunner().run(UpperCAmelCase_ ) self.assertIs(len(result.failures ), 0 ) except AttributeError: logger.info(f'''{module_identifier} is not a module.''' ) else: lowercase : Tuple = doctest.testfile(str('..' / directory / file ), optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed, 0 ) def lowercase ( self : str ) -> List[str]: lowercase : List[str] = Path('src/transformers' ) lowercase : List[Any] = 'modeling' lowercase : Dict = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(UpperCAmelCase_, identifier=UpperCAmelCase_, ignore_files=UpperCAmelCase_ ) def lowercase ( self : Dict ) -> Dict: lowercase : Union[str, Any] = Path('src/transformers' ) lowercase : int = 'tokenization' self.analyze_directory(UpperCAmelCase_, identifier=UpperCAmelCase_ ) def lowercase ( self : int ) -> Union[str, Any]: lowercase : Dict = Path('src/transformers' ) lowercase : List[str] = 'configuration' self.analyze_directory(UpperCAmelCase_, identifier=UpperCAmelCase_ ) def lowercase ( self : Union[str, Any] ) -> int: lowercase : int = Path('src/transformers' ) lowercase : List[str] = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(UpperCAmelCase_, n_identifier=UpperCAmelCase_ ) def lowercase ( self : str ) -> int: lowercase : str = Path('docs/source' ) lowercase : Any = ['favicon.ico'] self.analyze_directory(UpperCAmelCase_, ignore_files=UpperCAmelCase_, only_modules=UpperCAmelCase_ )
255
def _lowercase ( UpperCamelCase_ , UpperCamelCase_ ) -> str: '''simple docstring''' if not isinstance(UpperCamelCase_ , UpperCamelCase_ ): raise ValueError('iterations must be defined as integers' ) if not isinstance(UpperCamelCase_ , UpperCamelCase_ ) or not number >= 1: raise ValueError( 'starting number must be\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' ) SCREAMING_SNAKE_CASE__ = '' while number <= iterations: if number % 3 == 0: out += "Fizz" if number % 5 == 0: out += "Buzz" if 0 not in (number % 3, number % 5): out += str(UpperCamelCase_ ) # print(out) number += 1 out += " " return out if __name__ == "__main__": import doctest doctest.testmod()
176
0
from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, convert_to_rgb, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging _lowerCAmelCase = logging.get_logger(__name__) if is_vision_available(): import PIL class _SCREAMING_SNAKE_CASE ( __a ): __SCREAMING_SNAKE_CASE :str = ["""pixel_values"""] def __init__( self : Any , a__ : List[Any] = True , a__ : Optional[int] = None , a__ : List[str] = PILImageResampling.BICUBIC , a__ : Union[str, Any] = True , a__ : Tuple = None , a__ : Dict = True , a__ : str = 1 / 255 , a__ : Any = True , a__ : Any = None , a__ : Any = None , a__ : Optional[int] = True , **a__ : str , ): super().__init__(**lowerCamelCase_ ) __magic_name__ = size if size is not None else {'''shortest_edge''': 224} __magic_name__ = get_size_dict(lowerCamelCase_ , default_to_square=lowerCamelCase_ ) __magic_name__ = crop_size if crop_size is not None else {'''height''': 224, '''width''': 224} __magic_name__ = get_size_dict(lowerCamelCase_ , default_to_square=lowerCamelCase_ , param_name='''crop_size''' ) __magic_name__ = do_resize __magic_name__ = size __magic_name__ = resample __magic_name__ = do_center_crop __magic_name__ = crop_size __magic_name__ = do_rescale __magic_name__ = rescale_factor __magic_name__ = do_normalize __magic_name__ = image_mean if image_mean is not None else OPENAI_CLIP_MEAN __magic_name__ = image_std if image_std is not None else OPENAI_CLIP_STD __magic_name__ = do_convert_rgb def snake_case__ ( self : int , a__ : str , a__ : Tuple , a__ : Dict = PILImageResampling.BICUBIC , a__ : str = None , **a__ : Optional[int] , ): __magic_name__ = 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()}''' ) __magic_name__ = 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 snake_case__ ( self : Dict , a__ : str , a__ : Union[str, Any] , a__ : Dict = None , **a__ : Tuple , ): __magic_name__ = 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 snake_case__ ( self : str , a__ : List[str] , a__ : Dict , a__ : List[str] = None , **a__ : List[str] , ): return rescale(lowerCamelCase_ , scale=lowerCamelCase_ , data_format=lowerCamelCase_ , **lowerCamelCase_ ) def snake_case__ ( self : str , a__ : int , a__ : List[Any] , a__ : Union[str, Any] , a__ : Optional[Any] = None , **a__ : Union[str, Any] , ): return normalize(lowerCamelCase_ , mean=lowerCamelCase_ , std=lowerCamelCase_ , data_format=lowerCamelCase_ , **lowerCamelCase_ ) def snake_case__ ( self : Any , a__ : int , a__ : Dict = None , a__ : List[Any] = None , a__ : List[str] = None , a__ : Union[str, Any] = None , a__ : Any = None , a__ : Tuple = None , a__ : int = None , a__ : int = None , a__ : Optional[Any] = None , a__ : Tuple = None , a__ : Tuple = None , a__ : Dict = None , a__ : Tuple = ChannelDimension.FIRST , **a__ : int , ): __magic_name__ = do_resize if do_resize is not None else self.do_resize __magic_name__ = size if size is not None else self.size __magic_name__ = get_size_dict(lowerCamelCase_ , param_name='''size''' , default_to_square=lowerCamelCase_ ) __magic_name__ = resample if resample is not None else self.resample __magic_name__ = do_center_crop if do_center_crop is not None else self.do_center_crop __magic_name__ = crop_size if crop_size is not None else self.crop_size __magic_name__ = get_size_dict(lowerCamelCase_ , param_name='''crop_size''' , default_to_square=lowerCamelCase_ ) __magic_name__ = do_rescale if do_rescale is not None else self.do_rescale __magic_name__ = rescale_factor if rescale_factor is not None else self.rescale_factor __magic_name__ = do_normalize if do_normalize is not None else self.do_normalize __magic_name__ = image_mean if image_mean is not None else self.image_mean __magic_name__ = image_std if image_std is not None else self.image_std __magic_name__ = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb __magic_name__ = make_list_of_images(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: __magic_name__ = [convert_to_rgb(lowerCamelCase_ ) for image in images] # All transformations expect numpy arrays. __magic_name__ = [to_numpy_array(lowerCamelCase_ ) for image in images] if do_resize: __magic_name__ = [self.resize(image=lowerCamelCase_ , size=lowerCamelCase_ , resample=lowerCamelCase_ ) for image in images] if do_center_crop: __magic_name__ = [self.center_crop(image=lowerCamelCase_ , size=lowerCamelCase_ ) for image in images] if do_rescale: __magic_name__ = [self.rescale(image=lowerCamelCase_ , scale=lowerCamelCase_ ) for image in images] if do_normalize: __magic_name__ = [self.normalize(image=lowerCamelCase_ , mean=lowerCamelCase_ , std=lowerCamelCase_ ) for image in images] __magic_name__ = [to_channel_dimension_format(lowerCamelCase_ , lowerCamelCase_ ) for image in images] __magic_name__ = {'''pixel_values''': images} return BatchFeature(data=lowerCamelCase_ , tensor_type=lowerCamelCase_ )
355
'''simple docstring''' import re from flax.core.frozen_dict import freeze from flax.traverse_util import flatten_dict, unflatten_dict from jax.experimental import PartitionSpec as P # Sentinels _lowerCAmelCase = object() # For specifying empty leaf dict `{}` _lowerCAmelCase = object() def UpperCamelCase ( a , a ) -> Union[str, Any]: '''simple docstring''' __magic_name__ = tuple((re.compile(x + '''$''' ) for x in qs) ) for i in range(len(a ) - len(a ) + 1 ): __magic_name__ = [x.match(a ) for x, y in zip(a , ks[i:] )] if matches and all(a ): return True return False def UpperCamelCase ( a ) -> Tuple: '''simple docstring''' def replace(a , a ): for rule, replacement in rules: if _match(a , a ): return replacement return val return replace def UpperCamelCase ( ) -> Union[str, Any]: '''simple docstring''' return [ # embeddings (("transformer", "wpe", "embedding"), P('''mp''' , a )), (("transformer", "wte", "embedding"), P('''mp''' , a )), # atention (("attention", "(q_proj|k_proj|v_proj)", "kernel"), P(a , '''mp''' )), (("attention", "out_proj", "kernel"), P('''mp''' , a )), (("attention", "out_proj", "bias"), None), # mlp (("mlp", "c_fc", "kernel"), P(a , '''mp''' )), (("mlp", "c_fc", "bias"), P('''mp''' )), (("mlp", "c_proj", "kernel"), P('''mp''' , a )), (("mlp", "c_proj", "bias"), None), # layer norms ((r"ln_\d+", "bias"), None), ((r"\d+", r"ln_\d+", "scale"), None), (("ln_f", "bias"), None), (("ln_f", "scale"), None), ] def UpperCamelCase ( a ) -> str: '''simple docstring''' __magic_name__ = _get_partition_rules() __magic_name__ = _replacement_rules(a ) __magic_name__ = {k: _unmatched for k in flatten_dict(a )} __magic_name__ = {k: replace(a , a ) for k, v in initd.items()} assert _unmatched not in result.values(), "Incomplete partition spec." return freeze(unflatten_dict(a ) )
98
0
'''simple docstring''' A_ : Any = """0.21.0""" from .accelerator import Accelerator from .big_modeling import ( cpu_offload, cpu_offload_with_hook, disk_offload, dispatch_model, init_empty_weights, init_on_device, load_checkpoint_and_dispatch, ) from .data_loader import skip_first_batches from .launchers import debug_launcher, notebook_launcher from .state import PartialState from .utils import ( DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, FullyShardedDataParallelPlugin, GradScalerKwargs, InitProcessGroupKwargs, find_executable_batch_size, infer_auto_device_map, is_rich_available, load_checkpoint_in_model, synchronize_rng_states, ) if is_rich_available(): from .utils import rich
215
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available A_ : Optional[int] = {"""configuration_ibert""": ["""IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """IBertConfig""", """IBertOnnxConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A_ : str = [ """IBERT_PRETRAINED_MODEL_ARCHIVE_LIST""", """IBertForMaskedLM""", """IBertForMultipleChoice""", """IBertForQuestionAnswering""", """IBertForSequenceClassification""", """IBertForTokenClassification""", """IBertModel""", """IBertPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_ibert import IBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, IBertConfig, IBertOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_ibert import ( IBERT_PRETRAINED_MODEL_ARCHIVE_LIST, IBertForMaskedLM, IBertForMultipleChoice, IBertForQuestionAnswering, IBertForSequenceClassification, IBertForTokenClassification, IBertModel, IBertPreTrainedModel, ) else: import sys A_ : str = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
215
1
"""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(_lowerCamelCase ) __a = F.mse_loss(_lowerCamelCase , target.to(output.device ) ) if not do_backward: loss /= accelerator.gradient_accumulation_steps loss.backward() else: accelerator.backward(_lowerCamelCase ) def _lowerCamelCase( a , a=False ): set_seed(4_2 ) __a = RegressionModel() __a = deepcopy(_lowerCamelCase ) __a = RegressionDataset(length=8_0 ) __a = DataLoader(_lowerCamelCase , 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(_lowerCamelCase , lr_lambda=lambda a : epoch**0.65 ) __a = LambdaLR(_lowerCamelCase , lr_lambda=lambda a : epoch**0.65 ) # Make a copy of `model` if sched: __a = accelerator.prepare(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) else: __a = accelerator.prepare(_lowerCamelCase , _lowerCamelCase ) if sched: return (model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched) return model, ddp_model, dataloader def _lowerCamelCase( a ): __a = get_training_setup(_lowerCamelCase ) # Use a single batch __a = next(iter(_lowerCamelCase ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model __a = accelerator.gather((ddp_input, ddp_target) ) __a = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(_lowerCamelCase ): step_model(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) else: # Sync grads step_model(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # Since `no_sync` is a noop, `ddp_model` and `model` grads should always be in sync check_model_parameters(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) 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(_lowerCamelCase ) )] def _lowerCamelCase( a ): __a = get_training_setup(_lowerCamelCase ) # Use a single batch __a = next(iter(_lowerCamelCase ) ).values() for iteration in range(3 ): # Gather the distributed inputs and targs for the base model __a = accelerator.gather((ddp_input, ddp_target) ) __a = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # Do "gradient accumulation" (noop) if iteration % 2 == 0: # Accumulate grads locally with accelerator.no_sync(_lowerCamelCase ): step_model(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) else: # Sync grads step_model(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # 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(_lowerCamelCase ) )] def _lowerCamelCase( a=False , a=False ): __a = Accelerator( split_batches=_lowerCamelCase , dispatch_batches=_lowerCamelCase , gradient_accumulation_steps=2 ) # Test that context manager behaves properly __a = get_training_setup(_lowerCamelCase ) for iteration, batch in enumerate(_lowerCamelCase ): __a = batch.values() # Gather the distributed inputs and targs for the base model __a = accelerator.gather((ddp_input, ddp_target) ) __a = input.to(accelerator.device ), target.to(accelerator.device ) # Perform our initial ground truth step in non "DDP" step_model(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # Do "gradient accumulation" (noop) with accelerator.accumulate(_lowerCamelCase ): step_model(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # 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(_lowerCamelCase ) - 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(_lowerCamelCase ) )] GradientState._reset_state() def _lowerCamelCase( a=False , a=False ): __a = Accelerator( split_batches=_lowerCamelCase , dispatch_batches=_lowerCamelCase , gradient_accumulation_steps=2 ) # Test that context manager behaves properly __a = get_training_setup(_lowerCamelCase , _lowerCamelCase ) for iteration, batch in enumerate(_lowerCamelCase ): __a = batch.values() # Gather the distributed inputs and targs for the base model __a = accelerator.gather((ddp_input, ddp_target) ) __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(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) opt.step() if ((iteration + 1) % 2 == 0) or ((iteration + 1) == len(_lowerCamelCase )): 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(_lowerCamelCase ): step_model(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) 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(_lowerCamelCase )) if accelerator.num_processes > 1: check_model_parameters(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # 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(_lowerCamelCase , batch_size=1_6 ) __a = RegressionDataset(length=9_6 ) __a = DataLoader(_lowerCamelCase , batch_size=1_6 ) __a = accelerator.prepare(_lowerCamelCase , _lowerCamelCase ) assert accelerator.gradient_state.active_dataloader is None for iteration, _ in enumerate(_lowerCamelCase ): assert id(accelerator.gradient_state.active_dataloader ) == id(_lowerCamelCase ) if iteration < len(_lowerCamelCase ) - 1: assert not accelerator.gradient_state.end_of_dataloader if iteration == 1: for batch_num, _ in enumerate(_lowerCamelCase ): assert id(accelerator.gradient_state.active_dataloader ) == id(_lowerCamelCase ) if batch_num < len(_lowerCamelCase ) - 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(_lowerCamelCase ) 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(_lowerCamelCase ) 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(_lowerCamelCase , _lowerCamelCase ) # 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(_lowerCamelCase , _lowerCamelCase ) def _lowerCamelCase( a ): main() if __name__ == "__main__": main()
363
"""simple docstring""" import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEmbeddings, BertLayer, BertPooler, BertPreTrainedModel, ) def _lowerCamelCase( a ): __a = torch.exp(a ) __a = torch.sum(a , dim=1 ) # sum of exp(x_i) __a = torch.sum(x * exp_x , dim=1 ) # sum of x_i * exp(x_i) return torch.log(a ) - B / A class snake_case__ ( nn.Module ): def __init__( self , lowerCamelCase ): super().__init__() __a = config.output_attentions __a = config.output_hidden_states __a = nn.ModuleList([BertLayer(lowerCamelCase ) for _ in range(config.num_hidden_layers )] ) __a = nn.ModuleList([BertHighway(lowerCamelCase ) for _ in range(config.num_hidden_layers )] ) __a = [-1 for _ in range(config.num_hidden_layers )] def a__ ( self , lowerCamelCase ): if (type(lowerCamelCase ) is float) or (type(lowerCamelCase ) is int): for i in range(len(self.early_exit_entropy ) ): __a = x else: __a = x def a__ ( self , lowerCamelCase ): __a = pooler.state_dict() for highway in self.highway: for name, param in highway.pooler.state_dict().items(): param.copy_(loaded_model[name] ) def a__ ( self , lowerCamelCase , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , ): __a = () __a = () __a = () for i, layer_module in enumerate(self.layer ): if self.output_hidden_states: __a = all_hidden_states + (hidden_states,) __a = layer_module( lowerCamelCase , lowerCamelCase , head_mask[i] , lowerCamelCase , lowerCamelCase ) __a = layer_outputs[0] if self.output_attentions: __a = all_attentions + (layer_outputs[1],) __a = (hidden_states,) if self.output_hidden_states: __a = current_outputs + (all_hidden_states,) if self.output_attentions: __a = current_outputs + (all_attentions,) __a = self.highway[i](lowerCamelCase ) # logits, pooled_output if not self.training: __a = highway_exit[0] __a = entropy(lowerCamelCase ) __a = highway_exit + (highway_entropy,) # logits, hidden_states(?), entropy __a = all_highway_exits + (highway_exit,) if highway_entropy < self.early_exit_entropy[i]: __a = (highway_logits,) + current_outputs[1:] + (all_highway_exits,) raise HighwayException(lowerCamelCase , i + 1 ) else: __a = all_highway_exits + (highway_exit,) # Add last layer if self.output_hidden_states: __a = all_hidden_states + (hidden_states,) __a = (hidden_states,) if self.output_hidden_states: __a = outputs + (all_hidden_states,) if self.output_attentions: __a = outputs + (all_attentions,) __a = outputs + (all_highway_exits,) return outputs # last-layer hidden state, (all hidden states), (all attentions), all highway exits @add_start_docstrings( """The Bert Model transformer with early exiting (DeeBERT). """, snake_case_, ) class snake_case__ ( snake_case_ ): def __init__( self , lowerCamelCase ): super().__init__(lowerCamelCase ) __a = config __a = BertEmbeddings(lowerCamelCase ) __a = DeeBertEncoder(lowerCamelCase ) __a = BertPooler(lowerCamelCase ) self.init_weights() def a__ ( self ): self.encoder.init_highway_pooler(self.pooler ) def a__ ( self ): return self.embeddings.word_embeddings def a__ ( self , lowerCamelCase ): __a = value def a__ ( self , lowerCamelCase ): for layer, heads in heads_to_prune.items(): self.encoder.layer[layer].attention.prune_heads(lowerCamelCase ) @add_start_docstrings_to_model_forward(lowerCamelCase ) def a__ ( self , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , ): if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time" ) elif input_ids is not None: __a = input_ids.size() elif inputs_embeds is not None: __a = inputs_embeds.size()[:-1] else: raise ValueError("You have to specify either input_ids or inputs_embeds" ) __a = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: __a = torch.ones(lowerCamelCase , device=lowerCamelCase ) if encoder_attention_mask is None: __a = torch.ones(lowerCamelCase , device=lowerCamelCase ) if token_type_ids is None: __a = torch.zeros(lowerCamelCase , dtype=torch.long , device=lowerCamelCase ) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. __a = self.get_extended_attention_mask(lowerCamelCase , lowerCamelCase , lowerCamelCase ) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if encoder_attention_mask.dim() == 3: __a = encoder_attention_mask[:, None, :, :] if encoder_attention_mask.dim() == 2: __a = encoder_attention_mask[:, None, None, :] __a = encoder_extended_attention_mask.to( dtype=next(self.parameters() ).dtype ) # fp16 compatibility __a = (1.0 - encoder_extended_attention_mask) * -1_0000.0 # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] __a = self.get_head_mask(lowerCamelCase , self.config.num_hidden_layers ) __a = self.embeddings( input_ids=lowerCamelCase , position_ids=lowerCamelCase , token_type_ids=lowerCamelCase , inputs_embeds=lowerCamelCase ) __a = self.encoder( lowerCamelCase , attention_mask=lowerCamelCase , head_mask=lowerCamelCase , encoder_hidden_states=lowerCamelCase , encoder_attention_mask=lowerCamelCase , ) __a = encoder_outputs[0] __a = self.pooler(lowerCamelCase ) __a = ( sequence_output, pooled_output, ) + encoder_outputs[ 1: ] # add hidden_states and attentions if they are here return outputs # sequence_output, pooled_output, (hidden_states), (attentions), highway exits class snake_case__ ( snake_case_ ): def __init__( self , lowerCamelCase , lowerCamelCase ): __a = message __a = exit_layer # start from 1! class snake_case__ ( nn.Module ): def __init__( self , lowerCamelCase ): super().__init__() __a = BertPooler(lowerCamelCase ) __a = nn.Dropout(config.hidden_dropout_prob ) __a = nn.Linear(config.hidden_size , config.num_labels ) def a__ ( self , lowerCamelCase ): # Pooler __a = encoder_outputs[0] __a = self.pooler(lowerCamelCase ) # "return" pooler_output # BertModel __a = (pooler_input, pooler_output) + encoder_outputs[1:] # "return" bmodel_output # Dropout and classification __a = bmodel_output[1] __a = self.dropout(lowerCamelCase ) __a = self.classifier(lowerCamelCase ) return logits, pooled_output @add_start_docstrings( """Bert Model (with early exiting - DeeBERT) with a classifier on top, also takes care of multi-layer training. """, snake_case_, ) class snake_case__ ( snake_case_ ): def __init__( self , lowerCamelCase ): super().__init__(lowerCamelCase ) __a = config.num_labels __a = config.num_hidden_layers __a = DeeBertModel(lowerCamelCase ) __a = nn.Dropout(config.hidden_dropout_prob ) __a = nn.Linear(config.hidden_size , self.config.num_labels ) self.init_weights() @add_start_docstrings_to_model_forward(lowerCamelCase ) def a__ ( self , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=None , lowerCamelCase=-1 , lowerCamelCase=False , ): __a = self.num_layers try: __a = self.bert( lowerCamelCase , attention_mask=lowerCamelCase , token_type_ids=lowerCamelCase , position_ids=lowerCamelCase , head_mask=lowerCamelCase , inputs_embeds=lowerCamelCase , ) # sequence_output, pooled_output, (hidden_states), (attentions), highway exits __a = outputs[1] __a = self.dropout(lowerCamelCase ) __a = self.classifier(lowerCamelCase ) __a = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: __a = e.message __a = e.exit_layer __a = outputs[0] if not self.training: __a = entropy(lowerCamelCase ) __a = [] __a = [] if labels is not None: if self.num_labels == 1: # We are doing regression __a = MSELoss() __a = loss_fct(logits.view(-1 ) , labels.view(-1 ) ) else: __a = CrossEntropyLoss() __a = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) # work with highway exits __a = [] for highway_exit in outputs[-1]: __a = highway_exit[0] if not self.training: highway_logits_all.append(lowerCamelCase ) highway_entropy.append(highway_exit[2] ) if self.num_labels == 1: # We are doing regression __a = MSELoss() __a = loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) ) else: __a = CrossEntropyLoss() __a = loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) highway_losses.append(lowerCamelCase ) if train_highway: __a = (sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: __a = (loss,) + outputs if not self.training: __a = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: __a = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), (highway_exits)
268
0
import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def A ( a_ ) -> int: __UpperCamelCase : Optional[Any] =filter(lambda a_ : p.requires_grad ,model.parameters() ) __UpperCamelCase : Tuple =sum([np.prod(p.size() ) for p in model_parameters] ) return params A_ :Tuple = logging.getLogger(__name__) def A ( a_ ,a_ ) -> str: if metric == "rouge2": __UpperCamelCase : str ='{val_avg_rouge2:.4f}-{step_count}' elif metric == "bleu": __UpperCamelCase : Optional[int] ='{val_avg_bleu:.4f}-{step_count}' elif metric == "em": __UpperCamelCase : Optional[Any] ='{val_avg_em:.4f}-{step_count}' else: raise NotImplementedError( F'seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this' ' function.' ) __UpperCamelCase : Optional[Any] =ModelCheckpoint( dirpath=a_ ,filename=a_ ,monitor=F'val_{metric}' ,mode='max' ,save_top_k=3 ,every_n_epochs=1 ,) return checkpoint_callback def A ( a_ ,a_ ) -> List[Any]: return EarlyStopping( monitor=F'val_{metric}' ,mode='min' if 'loss' in metric else 'max' ,patience=a_ ,verbose=a_ ,) class __A ( pl.Callback ): """simple docstring""" def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" __UpperCamelCase : Optional[Any] ={f'lr_group_{i}': param['lr'] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(lowerCamelCase__ ) @rank_zero_only def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__=True ): """simple docstring""" logger.info(f'***** {type_path} results at step {trainer.global_step:05d} *****' ) __UpperCamelCase : Tuple =trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ['log', 'progress_bar', 'preds']} ) # Log results __UpperCamelCase : Optional[Any] =Path(pl_module.hparams.output_dir ) if type_path == "test": __UpperCamelCase : int =od / 'test_results.txt' __UpperCamelCase : Union[str, Any] =od / 'test_generations.txt' else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. __UpperCamelCase : Optional[Any] =od / f'{type_path}_results/{trainer.global_step:05d}.txt' __UpperCamelCase : Any =od / f'{type_path}_generations/{trainer.global_step:05d}.txt' results_file.parent.mkdir(exist_ok=lowerCamelCase__ ) generations_file.parent.mkdir(exist_ok=lowerCamelCase__ ) with open(lowerCamelCase__ , 'a+' ) as writer: for key in sorted(lowerCamelCase__ ): if key in ["log", "progress_bar", "preds"]: continue __UpperCamelCase : Optional[Any] =metrics[key] if isinstance(lowerCamelCase__ , torch.Tensor ): __UpperCamelCase : Dict =val.item() __UpperCamelCase : int =f'{key}: {val:.6f}\n' writer.write(lowerCamelCase__ ) if not save_generations: return if "preds" in metrics: __UpperCamelCase : List[str] ='\n'.join(metrics['preds'] ) generations_file.open('w+' ).write(lowerCamelCase__ ) @rank_zero_only def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" try: __UpperCamelCase : Optional[Any] =pl_module.model.model.num_parameters() except AttributeError: __UpperCamelCase : Optional[Any] =pl_module.model.num_parameters() __UpperCamelCase : Optional[Any] =count_trainable_parameters(lowerCamelCase__ ) # mp stands for million parameters trainer.logger.log_metrics({'n_params': npars, 'mp': npars / 1E6, 'grad_mp': n_trainable_pars / 1E6} ) @rank_zero_only def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(lowerCamelCase__ , lowerCamelCase__ , 'test' ) @rank_zero_only def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
71
import re def A ( a_ ) -> bool: __UpperCamelCase : Any =re.compile( r'^(?:0|94|\+94|0{2}94)' r'7(0|1|2|4|5|6|7|8)' r'(-| |)' r'\d{7}$' ) return bool(re.search(a_ ,a_ ) ) if __name__ == "__main__": A_ :List[str] = '''0094702343221''' print(is_sri_lankan_phone_number(phone))
71
1
import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin lowercase : List[Any] = get_tests_dir("fixtures/test_sentencepiece.model") if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right lowercase : Any = 250004 lowercase : Any = 250020 @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , unittest.TestCase ): """simple docstring""" lowercase : List[Any] = MBartTokenizer lowercase : List[str] = MBartTokenizerFast lowercase : List[Any] = True lowercase : List[Any] = True def __lowerCamelCase ( self ) -> List[str]: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing __UpperCamelCase : Dict = MBartTokenizer(__UpperCamelCase , keep_accents=__UpperCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) def __lowerCamelCase ( self ) -> Dict: '''simple docstring''' __UpperCamelCase : int = MBartTokenizer(__UpperCamelCase , keep_accents=__UpperCamelCase ) __UpperCamelCase : int = tokenizer.tokenize("This is a test" ) self.assertListEqual(__UpperCamelCase , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__UpperCamelCase ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) __UpperCamelCase : str = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( __UpperCamelCase , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) __UpperCamelCase : Dict = tokenizer.convert_tokens_to_ids(__UpperCamelCase ) self.assertListEqual( __UpperCamelCase , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) __UpperCamelCase : Optional[Any] = tokenizer.convert_ids_to_tokens(__UpperCamelCase ) self.assertListEqual( __UpperCamelCase , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) def __lowerCamelCase ( self ) -> str: '''simple docstring''' if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return __UpperCamelCase : Any = (self.rust_tokenizer_class, "hf-internal-testing/tiny-random-mbart", {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __UpperCamelCase : List[Any] = self.rust_tokenizer_class.from_pretrained(__UpperCamelCase , **__UpperCamelCase ) __UpperCamelCase : Dict = self.tokenizer_class.from_pretrained(__UpperCamelCase , **__UpperCamelCase ) __UpperCamelCase : List[Any] = tempfile.mkdtemp() __UpperCamelCase : List[Any] = tokenizer_r.save_pretrained(__UpperCamelCase ) __UpperCamelCase : List[str] = tokenizer_p.save_pretrained(__UpperCamelCase ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files ) ) __UpperCamelCase : str = tuple(f for f in tokenizer_r_files if "tokenizer.json" not in f ) self.assertSequenceEqual(__UpperCamelCase , __UpperCamelCase ) # Checks everything loads correctly in the same way __UpperCamelCase : Optional[Any] = tokenizer_r.from_pretrained(__UpperCamelCase ) __UpperCamelCase : int = tokenizer_p.from_pretrained(__UpperCamelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__UpperCamelCase , __UpperCamelCase ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(__UpperCamelCase ) # Save tokenizer rust, legacy_format=True __UpperCamelCase : Any = tempfile.mkdtemp() __UpperCamelCase : str = tokenizer_r.save_pretrained(__UpperCamelCase , legacy_format=__UpperCamelCase ) __UpperCamelCase : List[Any] = tokenizer_p.save_pretrained(__UpperCamelCase ) # Checks it save with the same files self.assertSequenceEqual(__UpperCamelCase , __UpperCamelCase ) # Checks everything loads correctly in the same way __UpperCamelCase : List[str] = tokenizer_r.from_pretrained(__UpperCamelCase ) __UpperCamelCase : int = tokenizer_p.from_pretrained(__UpperCamelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__UpperCamelCase , __UpperCamelCase ) ) shutil.rmtree(__UpperCamelCase ) # Save tokenizer rust, legacy_format=False __UpperCamelCase : Union[str, Any] = tempfile.mkdtemp() __UpperCamelCase : Union[str, Any] = tokenizer_r.save_pretrained(__UpperCamelCase , legacy_format=__UpperCamelCase ) __UpperCamelCase : Optional[int] = tokenizer_p.save_pretrained(__UpperCamelCase ) # Checks it saved the tokenizer.json file self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way __UpperCamelCase : Dict = tokenizer_r.from_pretrained(__UpperCamelCase ) __UpperCamelCase : Tuple = tokenizer_p.from_pretrained(__UpperCamelCase ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(__UpperCamelCase , __UpperCamelCase ) ) shutil.rmtree(__UpperCamelCase ) @require_torch @require_sentencepiece @require_tokenizers class SCREAMING_SNAKE_CASE__ ( unittest.TestCase ): """simple docstring""" lowercase : Optional[Any] = 'facebook/mbart-large-en-ro' lowercase : Union[str, Any] = [ ' UN Chief Says There Is No Military Solution in Syria', ' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.', ] lowercase : Tuple = [ 'Şeful ONU declară că nu există o soluţie militară în Siria', 'Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei' ' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor' ' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.', ] lowercase : List[str] = [8274, 127873, 25916, 7, 8622, 2071, 438, 67485, 53, 187895, 23, 51712, 2, EN_CODE] @classmethod def __lowerCamelCase ( cls ) -> List[Any]: '''simple docstring''' __UpperCamelCase : MBartTokenizer = MBartTokenizer.from_pretrained( cls.checkpoint_name , src_lang="en_XX" , tgt_lang="ro_RO" ) __UpperCamelCase : List[str] = 1 return cls def __lowerCamelCase ( self ) -> Tuple: '''simple docstring''' self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ar_AR"] , 25_00_01 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["en_EN"] , 25_00_04 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ro_RO"] , 25_00_20 ) def __lowerCamelCase ( self ) -> int: '''simple docstring''' __UpperCamelCase : str = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , __UpperCamelCase ) def __lowerCamelCase ( self ) -> Optional[int]: '''simple docstring''' self.assertIn(__UpperCamelCase , self.tokenizer.all_special_ids ) __UpperCamelCase : List[str] = [RO_CODE, 8_84, 90_19, 96, 9, 9_16, 8_67_92, 36, 1_87_43, 1_55_96, 5, 2] __UpperCamelCase : List[str] = self.tokenizer.decode(__UpperCamelCase , skip_special_tokens=__UpperCamelCase ) __UpperCamelCase : str = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=__UpperCamelCase ) self.assertEqual(__UpperCamelCase , __UpperCamelCase ) self.assertNotIn(self.tokenizer.eos_token , __UpperCamelCase ) def __lowerCamelCase ( self ) -> List[str]: '''simple docstring''' __UpperCamelCase : List[Any] = ["this is gunna be a long sentence " * 20] assert isinstance(src_text[0] , __UpperCamelCase ) __UpperCamelCase : Any = 10 __UpperCamelCase : Optional[int] = self.tokenizer(__UpperCamelCase , max_length=__UpperCamelCase , truncation=__UpperCamelCase ).input_ids[0] self.assertEqual(ids[-2] , 2 ) self.assertEqual(ids[-1] , __UpperCamelCase ) self.assertEqual(len(__UpperCamelCase ) , __UpperCamelCase ) def __lowerCamelCase ( self ) -> int: '''simple docstring''' self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["<mask>", "ar_AR"] ) , [25_00_26, 25_00_01] ) def __lowerCamelCase ( self ) -> List[str]: '''simple docstring''' __UpperCamelCase : Optional[Any] = tempfile.mkdtemp() __UpperCamelCase : Dict = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(__UpperCamelCase ) __UpperCamelCase : Optional[Any] = MBartTokenizer.from_pretrained(__UpperCamelCase ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , __UpperCamelCase ) @require_torch def __lowerCamelCase ( self ) -> int: '''simple docstring''' __UpperCamelCase : Optional[Any] = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=__UpperCamelCase , return_tensors="pt" ) __UpperCamelCase : Optional[int] = shift_tokens_right(batch["labels"] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE] assert batch.decoder_input_ids[1][0].tolist() == RO_CODE assert batch.decoder_input_ids[1][-1] == 2 assert batch.labels[1][-2:].tolist() == [2, RO_CODE] @require_torch def __lowerCamelCase ( self ) -> Optional[Any]: '''simple docstring''' __UpperCamelCase : Any = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=__UpperCamelCase , truncation=__UpperCamelCase , max_length=len(self.expected_src_tokens ) , return_tensors="pt" , ) __UpperCamelCase : List[Any] = shift_tokens_right(batch["labels"] , self.tokenizer.pad_token_id ) self.assertIsInstance(__UpperCamelCase , __UpperCamelCase ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) __UpperCamelCase : Optional[int] = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , __UpperCamelCase ) self.assertEqual(2 , batch.decoder_input_ids[0, -1] ) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id, EN_CODE] ) def __lowerCamelCase ( self ) -> Tuple: '''simple docstring''' __UpperCamelCase : Optional[int] = self.tokenizer(self.src_text , padding=__UpperCamelCase , truncation=__UpperCamelCase , max_length=3 , return_tensors="pt" ) __UpperCamelCase : Any = self.tokenizer( text_target=self.tgt_text , padding=__UpperCamelCase , truncation=__UpperCamelCase , max_length=10 , return_tensors="pt" ) __UpperCamelCase : str = targets["input_ids"] __UpperCamelCase : Union[str, Any] = shift_tokens_right(__UpperCamelCase , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def __lowerCamelCase ( self ) -> Any: '''simple docstring''' __UpperCamelCase : int = self.tokenizer._build_translation_inputs( "A test" , return_tensors="pt" , src_lang="en_XX" , tgt_lang="ar_AR" ) self.assertEqual( nested_simplify(__UpperCamelCase ) , { # A, test, EOS, en_XX "input_ids": [[62, 30_34, 2, 25_00_04]], "attention_mask": [[1, 1, 1, 1]], # ar_AR "forced_bos_token_id": 25_00_01, } , )
171
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowercase : Any = logging.get_logger(__name__) lowercase : Dict = {"vocab_file": "spm_char.model"} lowercase : Tuple = { "vocab_file": { "microsoft/speecht5_asr": "https://huggingface.co/microsoft/speecht5_asr/resolve/main/spm_char.model", "microsoft/speecht5_tts": "https://huggingface.co/microsoft/speecht5_tts/resolve/main/spm_char.model", "microsoft/speecht5_vc": "https://huggingface.co/microsoft/speecht5_vc/resolve/main/spm_char.model", } } lowercase : Union[str, Any] = { "microsoft/speecht5_asr": 1024, "microsoft/speecht5_tts": 1024, "microsoft/speecht5_vc": 1024, } class SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ): """simple docstring""" lowercase : Dict = VOCAB_FILES_NAMES lowercase : Tuple = PRETRAINED_VOCAB_FILES_MAP lowercase : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase : Optional[Any] = ['input_ids', 'attention_mask'] def __init__( self , __UpperCamelCase , __UpperCamelCase="<s>" , __UpperCamelCase="</s>" , __UpperCamelCase="<unk>" , __UpperCamelCase="<pad>" , __UpperCamelCase = None , **__UpperCamelCase , ) -> None: '''simple docstring''' __UpperCamelCase : Any = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__UpperCamelCase , eos_token=__UpperCamelCase , unk_token=__UpperCamelCase , pad_token=__UpperCamelCase , sp_model_kwargs=self.sp_model_kwargs , **__UpperCamelCase , ) __UpperCamelCase : List[Any] = vocab_file __UpperCamelCase : Dict = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__UpperCamelCase ) @property def __lowerCamelCase ( self ) -> List[Any]: '''simple docstring''' return self.sp_model.get_piece_size() def __lowerCamelCase ( self ) -> Optional[Any]: '''simple docstring''' __UpperCamelCase : Optional[int] = {self.convert_ids_to_tokens(__UpperCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> str: '''simple docstring''' __UpperCamelCase : Any = self.__dict__.copy() __UpperCamelCase : Union[str, Any] = None return state def __setstate__( self , __UpperCamelCase ) -> List[str]: '''simple docstring''' __UpperCamelCase : Dict = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): __UpperCamelCase : List[Any] = {} __UpperCamelCase : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __lowerCamelCase ( self , __UpperCamelCase ) -> List[str]: '''simple docstring''' return self.sp_model.encode(__UpperCamelCase , out_type=__UpperCamelCase ) def __lowerCamelCase ( self , __UpperCamelCase ) -> str: '''simple docstring''' return self.sp_model.piece_to_id(__UpperCamelCase ) def __lowerCamelCase ( self , __UpperCamelCase ) -> int: '''simple docstring''' __UpperCamelCase : Optional[Any] = self.sp_model.IdToPiece(__UpperCamelCase ) return token def __lowerCamelCase ( self , __UpperCamelCase ) -> Union[str, Any]: '''simple docstring''' __UpperCamelCase : Optional[Any] = [] __UpperCamelCase : Any = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(__UpperCamelCase ) + token __UpperCamelCase : Any = [] else: current_sub_tokens.append(__UpperCamelCase ) out_string += self.sp_model.decode(__UpperCamelCase ) return out_string.strip() def __lowerCamelCase ( self , __UpperCamelCase , __UpperCamelCase=None ) -> List[int]: '''simple docstring''' if token_ids_a is None: return token_ids_a + [self.eos_token_id] # We don't expect to process pairs, but leave the pair logic for API consistency return token_ids_a + token_ids_a + [self.eos_token_id] def __lowerCamelCase ( self , __UpperCamelCase , __UpperCamelCase = None , __UpperCamelCase = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__UpperCamelCase , token_ids_a=__UpperCamelCase , already_has_special_tokens=__UpperCamelCase ) __UpperCamelCase : str = [1] if token_ids_a is None: return ([0] * len(__UpperCamelCase )) + suffix_ones return ([0] * len(__UpperCamelCase )) + ([0] * len(__UpperCamelCase )) + suffix_ones def __lowerCamelCase ( self , __UpperCamelCase , __UpperCamelCase = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(__UpperCamelCase ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __UpperCamelCase : Optional[Any] = os.path.join( __UpperCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__UpperCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __UpperCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(__UpperCamelCase , "wb" ) as fi: __UpperCamelCase : Optional[Any] = self.sp_model.serialized_model_proto() fi.write(__UpperCamelCase ) return (out_vocab_file,)
171
1
"""simple docstring""" from __future__ import annotations def snake_case_ ( A_ : int | str ): '''simple docstring''' _lowerCamelCase : Tuple = str(A_ ) return n == n[::-1] def snake_case_ ( A_ : int = 1_00_00_00 ): '''simple docstring''' _lowerCamelCase : Dict = 0 for i in range(1, A_ ): if is_palindrome(A_ ) and is_palindrome(bin(A_ ).split('''b''' )[1] ): total += i return total if __name__ == "__main__": print(solution(int(str(input().strip()))))
72
import argparse from pathlib import Path from transformers import AutoConfig, AutoTokenizer, RagConfig, RagSequenceForGeneration, RagTokenForGeneration def _snake_case ( lowerCAmelCase : int , lowerCAmelCase : str , lowerCAmelCase : str , lowerCAmelCase : Path , lowerCAmelCase : str = None , lowerCAmelCase : str = None , lowerCAmelCase : str = None , ): """simple docstring""" if config_name_or_path is None: SCREAMING_SNAKE_CASE_ : Union[str, Any] = "facebook/rag-token-base" if model_type == "rag_token" else "facebook/rag-sequence-base" if generator_tokenizer_name_or_path is None: SCREAMING_SNAKE_CASE_ : Dict = generator_name_or_path if question_encoder_tokenizer_name_or_path is None: SCREAMING_SNAKE_CASE_ : Union[str, Any] = question_encoder_name_or_path SCREAMING_SNAKE_CASE_ : Union[str, Any] = RagTokenForGeneration if model_type == "rag_token" else RagSequenceForGeneration # Save model. SCREAMING_SNAKE_CASE_ : List[Any] = RagConfig.from_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Tuple = AutoConfig.from_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : int = AutoConfig.from_pretrained(lowerCAmelCase ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = gen_config SCREAMING_SNAKE_CASE_ : Optional[Any] = question_encoder_config SCREAMING_SNAKE_CASE_ : Dict = model_class.from_pretrained_question_encoder_generator( lowerCAmelCase , lowerCAmelCase , config=lowerCAmelCase ) rag_model.save_pretrained(lowerCAmelCase ) # Sanity check. model_class.from_pretrained(lowerCAmelCase ) # Save tokenizers. SCREAMING_SNAKE_CASE_ : Optional[Any] = AutoTokenizer.from_pretrained(lowerCAmelCase ) gen_tokenizer.save_pretrained(dest_dir / "generator_tokenizer/" ) SCREAMING_SNAKE_CASE_ : Union[str, Any] = AutoTokenizer.from_pretrained(lowerCAmelCase ) question_encoder_tokenizer.save_pretrained(dest_dir / "question_encoder_tokenizer/" ) if __name__ == "__main__": __lowerCamelCase : List[Any] = argparse.ArgumentParser() parser.add_argument( '''--model_type''', choices=['''rag_sequence''', '''rag_token'''], required=True, type=str, help='''RAG model type: rag_sequence, rag_token''', ) parser.add_argument('''--dest''', type=str, required=True, help='''Path to the output checkpoint directory.''') parser.add_argument('''--generator_name_or_path''', type=str, required=True, help='''Generator model identifier''') parser.add_argument( '''--question_encoder_name_or_path''', type=str, required=True, help='''Question encoder model identifier''' ) parser.add_argument( '''--generator_tokenizer_name_or_path''', type=str, help='''Generator tokenizer identifier, if not specified, resolves to ``generator_name_or_path``''', ) parser.add_argument( '''--question_encoder_tokenizer_name_or_path''', type=str, help='''Question encoder tokenizer identifier, if not specified, resolves to ``question_encoder_name_or_path``''', ) parser.add_argument( '''--config_name_or_path''', type=str, help=( '''Identifier of the model config to use, if not provided, resolves to a base config for a given''' ''' ``model_type``''' ), ) __lowerCamelCase : str = parser.parse_args() __lowerCamelCase : int = Path(args.dest) dest_dir.mkdir(exist_ok=True) consolidate( args.model_type, args.generator_name_or_path, args.question_encoder_name_or_path, dest_dir, args.config_name_or_path, args.generator_tokenizer_name_or_path, args.question_encoder_tokenizer_name_or_path, )
18
0
"""simple docstring""" import importlib.util import json import os import warnings from dataclasses import dataclass, field import torch from ..training_args import TrainingArguments from ..utils import cached_property, is_sagemaker_dp_enabled, logging a :List[str] = logging.get_logger(__name__) def _lowercase ( ) -> Union[str, Any]: # Get the sagemaker specific mp parameters from smp_options variable. SCREAMING_SNAKE_CASE__ : Any = os.getenv("""SM_HP_MP_PARAMETERS""" , """{}""" ) try: # Parse it and check the field "partitions" is included, it is required for model parallel. SCREAMING_SNAKE_CASE__ : Union[str, Any] = json.loads(__lowerCAmelCase ) if "partitions" not in smp_options: return False except json.JSONDecodeError: return False # Get the sagemaker specific framework parameters from mpi_options variable. SCREAMING_SNAKE_CASE__ : int = os.getenv("""SM_FRAMEWORK_PARAMS""" , """{}""" ) try: # Parse it and check the field "sagemaker_distributed_dataparallel_enabled". SCREAMING_SNAKE_CASE__ : Union[str, Any] = json.loads(__lowerCAmelCase ) if not mpi_options.get("""sagemaker_mpi_enabled""" , __lowerCAmelCase ): return False except json.JSONDecodeError: return False # Lastly, check if the `smdistributed` module is present. return importlib.util.find_spec("""smdistributed""" ) is not None if is_sagemaker_model_parallel_available(): import smdistributed.modelparallel.torch as smp smp.init() @dataclass class __a (UpperCamelCase_): '''simple docstring''' _SCREAMING_SNAKE_CASE :str = field( default="""""" , metadata={"""help""": """Used by the SageMaker launcher to send mp-specific args. Ignored in SageMakerTrainer"""} , ) def _a ( self ) -> List[str]: """simple docstring""" super().__post_init__() warnings.warn( """`SageMakerTrainingArguments` is deprecated and will be removed in v5 of Transformers. You can use """ """`TrainingArguments` instead.""" , _a , ) @cached_property def _a ( self ) -> "torch.device": """simple docstring""" logger.info("""PyTorch: setting up devices""" ) if torch.distributed.is_available() and torch.distributed.is_initialized() and self.local_rank == -1: logger.warning( """torch.distributed process group is initialized, but local_rank == -1. """ """In order to use Torch DDP, launch your script with `python -m torch.distributed.launch""" ) if self.no_cuda: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.device("""cpu""" ) SCREAMING_SNAKE_CASE__ : Tuple = 0 elif is_sagemaker_model_parallel_available(): SCREAMING_SNAKE_CASE__ : str = smp.local_rank() SCREAMING_SNAKE_CASE__ : List[str] = torch.device("""cuda""" , _a ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1 elif is_sagemaker_dp_enabled(): import smdistributed.dataparallel.torch.torch_smddp # noqa: F401 torch.distributed.init_process_group(backend="""smddp""" , timeout=self.ddp_timeout_delta ) SCREAMING_SNAKE_CASE__ : List[Any] = int(os.getenv("""SMDATAPARALLEL_LOCAL_RANK""" ) ) SCREAMING_SNAKE_CASE__ : Any = torch.device("""cuda""" , self.local_rank ) SCREAMING_SNAKE_CASE__ : Tuple = 1 elif self.local_rank == -1: # if n_gpu is > 1 we'll use nn.DataParallel. # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0` # Explicitly set CUDA to the first (index 0) CUDA device, otherwise `set_device` will # trigger an error that a device index is missing. Index 0 takes into account the # GPUs available in the environment, so `CUDA_VISIBLE_DEVICES=1,2` with `cuda:0` # will use the first GPU in that env, i.e. GPU#1 SCREAMING_SNAKE_CASE__ : List[Any] = torch.device("""cuda:0""" if torch.cuda.is_available() else """cpu""" ) # Sometimes the line in the postinit has not been run before we end up here, so just checking we're not at # the default value. SCREAMING_SNAKE_CASE__ : Tuple = torch.cuda.device_count() else: # Here, we'll use torch.distributed. # Initializes the distributed backend which will take care of synchronizing nodes/GPUs if not torch.distributed.is_initialized(): torch.distributed.init_process_group(backend="""nccl""" , timeout=self.ddp_timeout_delta ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.device("""cuda""" , self.local_rank ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 1 if device.type == "cuda": torch.cuda.set_device(_a ) return device @property def _a ( self ) -> List[Any]: """simple docstring""" if is_sagemaker_model_parallel_available(): return smp.dp_size() return super().world_size @property def _a ( self ) -> List[Any]: """simple docstring""" return not is_sagemaker_model_parallel_available() @property def _a ( self ) -> Optional[Any]: """simple docstring""" return False
56
"""simple docstring""" def _lowercase ( __lowerCAmelCase ) -> Tuple: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [0] * len(__lowerCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Any = [1] * len(__lowerCAmelCase ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(__lowerCAmelCase ) ): if indegree[i] == 0: queue.append(__lowerCAmelCase ) while queue: SCREAMING_SNAKE_CASE__ : str = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: SCREAMING_SNAKE_CASE__ : str = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(__lowerCAmelCase ) print(max(__lowerCAmelCase ) ) # Adjacency list of Graph a :int = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
56
1
'''simple docstring''' from collections.abc import Callable import numpy as np def lowercase_ ( lowerCAmelCase__ : Callable , lowerCAmelCase__ : float , lowerCAmelCase__ : float , lowerCAmelCase__ : float , lowerCAmelCase__ : float ): """simple docstring""" __UpperCAmelCase : List[Any] = int(np.ceil((x_end - xa) / step_size ) ) __UpperCAmelCase : Dict = np.zeros((n + 1,) ) __UpperCAmelCase : str = ya __UpperCAmelCase : str = xa for k in range(_lowerCAmelCase ): __UpperCAmelCase : int = y[k] + step_size * ode_func(_lowerCAmelCase , y[k] ) __UpperCAmelCase : Tuple = y[k] + ( (step_size / 2) * (ode_func(_lowerCAmelCase , y[k] ) + ode_func(x + step_size , _lowerCAmelCase )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
254
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch import math from dataclasses import dataclass from typing import Optional, Tuple, Union import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin, SchedulerOutput @dataclass class __magic_name__ ( lowerCamelCase__ ): """simple docstring""" __UpperCamelCase = 42 __UpperCamelCase = 42 class __magic_name__ ( lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" __UpperCamelCase = 1 @register_to_config def __init__( self :Union[str, Any] , snake_case :int = 2_000 , snake_case :float = 0.15 , snake_case :float = 0.01 , snake_case :float = 1348.0 , snake_case :float = 1e-5 , snake_case :int = 1 , ): '''simple docstring''' A_ : Dict = sigma_max # setable values A_ : List[Any] = None self.set_sigmas(snake_case , snake_case , snake_case , snake_case ) def SCREAMING_SNAKE_CASE ( self :Any , snake_case :torch.FloatTensor , snake_case :Optional[int] = None ): '''simple docstring''' return sample def SCREAMING_SNAKE_CASE ( self :Optional[Any] , snake_case :int , snake_case :float = None , snake_case :Union[str, torch.device] = None ): '''simple docstring''' A_ : Optional[Any] = sampling_eps if sampling_eps is not None else self.config.sampling_eps A_ : Tuple = torch.linspace(1 , snake_case , snake_case , device=snake_case ) def SCREAMING_SNAKE_CASE ( self :Dict , snake_case :int , snake_case :float = None , snake_case :float = None , snake_case :float = None ): '''simple docstring''' A_ : Union[str, Any] = sigma_min if sigma_min is not None else self.config.sigma_min A_ : Any = sigma_max if sigma_max is not None else self.config.sigma_max A_ : Dict = sampling_eps if sampling_eps is not None else self.config.sampling_eps if self.timesteps is None: self.set_timesteps(snake_case , snake_case ) A_ : str = sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps) A_ : Any = torch.exp(torch.linspace(math.log(snake_case ) , math.log(snake_case ) , snake_case ) ) A_ : str = torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps] ) def SCREAMING_SNAKE_CASE ( self :List[str] , snake_case :List[str] , snake_case :Dict ): '''simple docstring''' return torch.where( timesteps == 0 , torch.zeros_like(t.to(timesteps.device ) ) , self.discrete_sigmas[timesteps - 1].to(timesteps.device ) , ) def SCREAMING_SNAKE_CASE ( self :Union[str, Any] , snake_case :torch.FloatTensor , snake_case :int , snake_case :torch.FloatTensor , snake_case :Optional[torch.Generator] = None , snake_case :bool = True , ): '''simple docstring''' if self.timesteps is None: raise ValueError( "`self.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler" ) A_ : int = timestep * torch.ones( sample.shape[0] , device=sample.device ) # torch.repeat_interleave(timestep, sample.shape[0]) A_ : Optional[Any] = (timestep * (len(self.timesteps ) - 1)).long() # mps requires indices to be in the same device, so we use cpu as is the default with cuda A_ : Dict = timesteps.to(self.discrete_sigmas.device ) A_ : Optional[int] = self.discrete_sigmas[timesteps].to(sample.device ) A_ : int = self.get_adjacent_sigma(snake_case , snake_case ).to(sample.device ) A_ : Union[str, Any] = torch.zeros_like(snake_case ) A_ : Tuple = (sigma**2 - adjacent_sigma**2) ** 0.5 # equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x) # also equation 47 shows the analog from SDE models to ancestral sampling methods A_ : Optional[int] = diffusion.flatten() while len(diffusion.shape ) < len(sample.shape ): A_ : Tuple = diffusion.unsqueeze(-1 ) A_ : Optional[Any] = drift - diffusion**2 * model_output # equation 6: sample noise for the diffusion term of A_ : List[Any] = randn_tensor( sample.shape , layout=sample.layout , generator=snake_case , device=sample.device , dtype=sample.dtype ) A_ : List[Any] = sample - drift # subtract because `dt` is a small negative timestep # TODO is the variable diffusion the correct scaling term for the noise? A_ : Any = prev_sample_mean + diffusion * noise # add impact of diffusion field g if not return_dict: return (prev_sample, prev_sample_mean) return SdeVeOutput(prev_sample=snake_case , prev_sample_mean=snake_case ) def SCREAMING_SNAKE_CASE ( self :Tuple , snake_case :torch.FloatTensor , snake_case :torch.FloatTensor , snake_case :Optional[torch.Generator] = None , snake_case :bool = True , ): '''simple docstring''' if self.timesteps is None: raise ValueError( "`self.timesteps` is not set, you need to run 'set_timesteps' after creating the scheduler" ) # For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z" # sample noise for correction A_ : Dict = randn_tensor(sample.shape , layout=sample.layout , generator=snake_case ).to(sample.device ) # compute step size from the model_output, the noise, and the snr A_ : int = torch.norm(model_output.reshape(model_output.shape[0] , -1 ) , dim=-1 ).mean() A_ : List[Any] = torch.norm(noise.reshape(noise.shape[0] , -1 ) , dim=-1 ).mean() A_ : Dict = (self.config.snr * noise_norm / grad_norm) ** 2 * 2 A_ : Dict = step_size * torch.ones(sample.shape[0] ).to(sample.device ) # self.repeat_scalar(step_size, sample.shape[0]) # compute corrected sample: model_output term and noise term A_ : int = step_size.flatten() while len(step_size.shape ) < len(sample.shape ): A_ : str = step_size.unsqueeze(-1 ) A_ : Optional[Any] = sample + step_size * model_output A_ : Tuple = prev_sample_mean + ((step_size * 2) ** 0.5) * noise if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=snake_case ) def SCREAMING_SNAKE_CASE ( self :Tuple , snake_case :torch.FloatTensor , snake_case :torch.FloatTensor , snake_case :torch.FloatTensor , ): '''simple docstring''' A_ : Union[str, Any] = timesteps.to(original_samples.device ) A_ : List[Any] = self.discrete_sigmas.to(original_samples.device )[timesteps] A_ : List[Any] = ( noise * sigmas[:, None, None, None] if noise is not None else torch.randn_like(snake_case ) * sigmas[:, None, None, None] ) A_ : Optional[int] = noise + original_samples return noisy_samples def __len__( self :Union[str, Any] ): '''simple docstring''' return self.config.num_train_timesteps
300
0
import argparse import logging import os from datetime import datetime import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, TensorDataset from tqdm import tqdm from transformers import GPTaLMHeadModel lowercase__ : Dict = logging.getLogger(__name__) def SCREAMING_SNAKE_CASE ( __UpperCamelCase , __UpperCamelCase) -> Tuple: # save results if os.path.exists(__UpperCamelCase): if os.path.exists(os.path.join(__UpperCamelCase , "config.json")) and os.path.isfile( os.path.join(__UpperCamelCase , "config.json")): os.remove(os.path.join(__UpperCamelCase , "config.json")) if os.path.exists(os.path.join(__UpperCamelCase , "pytorch_model.bin")) and os.path.isfile( os.path.join(__UpperCamelCase , "pytorch_model.bin")): os.remove(os.path.join(__UpperCamelCase , "pytorch_model.bin")) else: os.makedirs(__UpperCamelCase) model.save_pretrained(__UpperCamelCase) def SCREAMING_SNAKE_CASE ( __UpperCamelCase , __UpperCamelCase=False) -> Optional[int]: a = 2 if unlogit: a = torch.pow(__UpperCamelCase , __UpperCamelCase) a = p * torch.log(__UpperCamelCase) a = 0 return -plogp.sum(dim=-1) def SCREAMING_SNAKE_CASE ( __UpperCamelCase) -> List[Any]: logger.info("lv, h >\t" + "\t".join(f'''{x + 1}''' for x in range(len(__UpperCamelCase)))) for row in range(len(__UpperCamelCase)): if tensor.dtype != torch.long: logger.info(f'''layer {row + 1}:\t''' + "\t".join(f'''{x:.5f}''' for x in tensor[row].cpu().data)) else: logger.info(f'''layer {row + 1}:\t''' + "\t".join(f'''{x:d}''' for x in tensor[row].cpu().data)) def SCREAMING_SNAKE_CASE ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase=True , __UpperCamelCase=True , __UpperCamelCase=None , __UpperCamelCase=False) -> str: a , a = model.config.num_hidden_layers, model.config.num_attention_heads a = torch.zeros(__UpperCamelCase , __UpperCamelCase).to(args.device) a = torch.zeros(__UpperCamelCase , __UpperCamelCase).to(args.device) if head_mask is None: a = torch.ones(__UpperCamelCase , __UpperCamelCase).to(args.device) head_mask.requires_grad_(requires_grad=__UpperCamelCase) # If actually pruned attention multi-head, set head mask to None to avoid shape mismatch if actually_pruned: a = None a = 0.0 a = 0.0 for step, inputs in enumerate(tqdm(__UpperCamelCase , desc="Iteration" , disable=args.local_rank not in [-1, 0])): a = tuple(t.to(args.device) for t in inputs) ((a) , ) = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) a = model(__UpperCamelCase , labels=__UpperCamelCase , head_mask=__UpperCamelCase) # (loss), lm_logits, presents, (all hidden_states), (attentions) a , a , a = ( outputs[0], outputs[1], outputs[-1], ) # Loss and logits are the first, attention the last loss.backward() # Backpropagate to populate the gradients in the head mask total_loss += loss.detach().cpu().numpy() if compute_entropy: for layer, attn in enumerate(__UpperCamelCase): a = entropy(attn.detach() , __UpperCamelCase) attn_entropy[layer] += masked_entropy.sum(-1).sum(0).sum(0).detach() if compute_importance: head_importance += head_mask.grad.abs().detach() tot_tokens += torch.ones_like(__UpperCamelCase).float().detach().sum().data # Normalize attn_entropy /= tot_tokens head_importance /= tot_tokens # Layerwise importance normalization if not args.dont_normalize_importance_by_layer: a = 2 a = torch.pow(torch.pow(__UpperCamelCase , __UpperCamelCase).sum(-1) , 1 / exponent) head_importance /= norm_by_layer.unsqueeze(-1) + 1e-20 if not args.dont_normalize_global_importance: a = (head_importance - head_importance.min()) / (head_importance.max() - head_importance.min()) # Print matrices if compute_entropy: logger.info("Attention entropies") print_ad_tensor(__UpperCamelCase) if compute_importance: logger.info("Head importance scores") print_ad_tensor(__UpperCamelCase) logger.info("Head ranked by importance scores") a = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device) a = torch.arange( head_importance.numel() , device=args.device) a = head_ranks.view_as(__UpperCamelCase) print_ad_tensor(__UpperCamelCase) return attn_entropy, head_importance, total_loss def SCREAMING_SNAKE_CASE ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase) -> Optional[Any]: a , a , a = compute_heads_importance(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , compute_entropy=__UpperCamelCase) a = 1 / loss # instead of downsteam score use the LM loss logger.info("Pruning: original score: %f, threshold: %f" , __UpperCamelCase , original_score * args.masking_threshold) a = torch.ones_like(__UpperCamelCase) a = max(1 , int(new_head_mask.numel() * args.masking_amount)) a = original_score while current_score >= original_score * args.masking_threshold: a = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads a = float("Inf") a = head_importance.view(-1).sort()[1] if len(__UpperCamelCase) <= num_to_mask: print("BREAK BY num_to_mask") break # mask heads a = current_heads_to_mask[:num_to_mask] logger.info("Heads to mask: %s" , str(current_heads_to_mask.tolist())) a = new_head_mask.view(-1) a = 0.0 a = new_head_mask.view_as(__UpperCamelCase) a = new_head_mask.clone().detach() print_ad_tensor(__UpperCamelCase) # Compute metric and head importance again a , a , a = compute_heads_importance( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , compute_entropy=__UpperCamelCase , head_mask=__UpperCamelCase) a = 1 / loss logger.info( "Masking: current score: %f, remaining heads %d (%.1f percents)" , __UpperCamelCase , new_head_mask.sum() , new_head_mask.sum() / new_head_mask.numel() * 1_00 , ) logger.info("Final head mask") print_ad_tensor(__UpperCamelCase) np.save(os.path.join(args.output_dir , "head_mask.npy") , head_mask.detach().cpu().numpy()) return head_mask def SCREAMING_SNAKE_CASE ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase) -> Optional[int]: a = datetime.now() a , a , a = compute_heads_importance( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , compute_entropy=__UpperCamelCase , compute_importance=__UpperCamelCase , head_mask=__UpperCamelCase) a = 1 / loss a = datetime.now() - before_time a = sum(p.numel() for p in model.parameters()) a = { layer: (1 - head_mask[layer].long()).nonzero().squeeze().tolist() for layer in range(len(__UpperCamelCase)) } for k, v in heads_to_prune.items(): if isinstance(__UpperCamelCase , __UpperCamelCase): a = [ v, ] assert sum(len(__UpperCamelCase) for h in heads_to_prune.values()) == (1 - head_mask.long()).sum().item() model.prune_heads(__UpperCamelCase) a = sum(p.numel() for p in model.parameters()) a = datetime.now() a , a , a = compute_heads_importance( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , compute_entropy=__UpperCamelCase , compute_importance=__UpperCamelCase , head_mask=__UpperCamelCase , actually_pruned=__UpperCamelCase , ) a = 1 / loss a = datetime.now() - before_time logger.info( "Pruning: original num of params: %.2e, after pruning %.2e (%.1f percents)" , __UpperCamelCase , __UpperCamelCase , pruned_num_params / original_num_params * 1_00 , ) logger.info("Pruning: score with masking: %f score with pruning: %f" , __UpperCamelCase , __UpperCamelCase) logger.info("Pruning: speed ratio (original timing / new timing): %f percents" , original_time / new_time * 1_00) save_model(__UpperCamelCase , args.output_dir) def SCREAMING_SNAKE_CASE ( ) -> Optional[int]: a = argparse.ArgumentParser() # Required parameters parser.add_argument( "--data_dir" , default=__UpperCamelCase , type=__UpperCamelCase , required=__UpperCamelCase , help="The input data dir. Should contain the .tsv files (or other data files) for the task." , ) parser.add_argument( "--model_name_or_path" , default=__UpperCamelCase , type=__UpperCamelCase , required=__UpperCamelCase , help="Path to pretrained model or model identifier from huggingface.co/models" , ) parser.add_argument( "--output_dir" , default=__UpperCamelCase , type=__UpperCamelCase , required=__UpperCamelCase , help="The output directory where the model predictions and checkpoints will be written." , ) # Other parameters parser.add_argument( "--config_name" , default="" , type=__UpperCamelCase , help="Pretrained config name or path if not the same as model_name_or_path" , ) parser.add_argument( "--tokenizer_name" , default="" , type=__UpperCamelCase , help="Pretrained tokenizer name or path if not the same as model_name_or_path" , ) parser.add_argument( "--cache_dir" , default=__UpperCamelCase , type=__UpperCamelCase , help="Where do you want to store the pre-trained models downloaded from s3" , ) parser.add_argument( "--data_subset" , type=__UpperCamelCase , default=-1 , help="If > 0: limit the data to a subset of data_subset instances.") parser.add_argument( "--overwrite_output_dir" , action="store_true" , help="Whether to overwrite data in output directory") parser.add_argument( "--overwrite_cache" , action="store_true" , help="Overwrite the cached training and evaluation sets") parser.add_argument( "--dont_normalize_importance_by_layer" , action="store_true" , help="Don't normalize importance score by layers") parser.add_argument( "--dont_normalize_global_importance" , action="store_true" , help="Don't normalize all importance scores between 0 and 1" , ) parser.add_argument( "--try_masking" , action="store_true" , help="Whether to try to mask head until a threshold of accuracy.") parser.add_argument( "--masking_threshold" , default=0.9 , type=__UpperCamelCase , help="masking threshold in term of metrics (stop masking when metric < threshold * original metric value)." , ) parser.add_argument( "--masking_amount" , default=0.1 , type=__UpperCamelCase , help="Amount to heads to masking at each masking step.") parser.add_argument("--metric_name" , default="acc" , type=__UpperCamelCase , help="Metric to use for head masking.") parser.add_argument( "--max_seq_length" , default=1_28 , type=__UpperCamelCase , help=( "The maximum total input sequence length after WordPiece tokenization. \n" "Sequences longer than this will be truncated, sequences shorter padded." ) , ) parser.add_argument("--batch_size" , default=1 , type=__UpperCamelCase , help="Batch size.") parser.add_argument("--seed" , type=__UpperCamelCase , default=42) parser.add_argument("--local_rank" , type=__UpperCamelCase , default=-1 , help="local_rank for distributed training on gpus") parser.add_argument("--no_cuda" , action="store_true" , help="Whether not to use CUDA when available") parser.add_argument("--server_ip" , type=__UpperCamelCase , default="" , help="Can be used for distant debugging.") parser.add_argument("--server_port" , type=__UpperCamelCase , default="" , help="Can be used for distant debugging.") a = parser.parse_args() if args.server_ip and args.server_port: # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script import ptvsd print("Waiting for debugger attach") ptvsd.enable_attach(address=(args.server_ip, args.server_port) , redirect_output=__UpperCamelCase) ptvsd.wait_for_attach() # Setup devices and distributed training if args.local_rank == -1 or args.no_cuda: a = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu") a = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank) a = torch.device("cuda" , args.local_rank) a = 1 torch.distributed.init_process_group(backend="nccl") # Initializes the distributed backend # Setup logging logging.basicConfig(level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN) logger.info("device: {} n_gpu: {}, distributed: {}".format(args.device , args.n_gpu , bool(args.local_rank != -1))) a = GPTaLMHeadModel.from_pretrained(args.model_name_or_path) # Distributed and parallel training model.to(args.device) if args.local_rank != -1: a = nn.parallel.DistributedDataParallel( __UpperCamelCase , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=__UpperCamelCase) elif args.n_gpu > 1: a = nn.DataParallel(__UpperCamelCase) # Print/save training arguments os.makedirs(args.output_dir , exist_ok=__UpperCamelCase) torch.save(__UpperCamelCase , os.path.join(args.output_dir , "run_args.bin")) logger.info("Training/evaluation parameters %s" , __UpperCamelCase) # Prepare dataset a = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa), ]) a = (torch.from_numpy(__UpperCamelCase),) a = TensorDataset(*__UpperCamelCase) a = RandomSampler(__UpperCamelCase) a = DataLoader(__UpperCamelCase , sampler=__UpperCamelCase , batch_size=args.batch_size) # Compute head entropy and importance score compute_heads_importance(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase) # Try head masking (set heads to zero until the score goes under a threshole) # and head pruning (remove masked heads and see the effect on the network) if args.try_masking and args.masking_threshold > 0.0 and args.masking_threshold < 1.0: a = mask_heads(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase) prune_heads(__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase) if __name__ == "__main__": main()
180
# Author: OMKAR PATHAK, Nwachukwu Chidiebere # Use a Python dictionary to construct the graph. from __future__ import annotations from pprint import pformat from typing import Generic, TypeVar lowercase__ : str = TypeVar("T") class a__ ( Generic[T] ): def __init__( self , A = True ) -> None: '''simple docstring''' a = {} # dictionary of lists a = directed def lowerCAmelCase_ ( self , A , A ) -> GraphAdjacencyList[T]: '''simple docstring''' if not self.directed: # For undirected graphs # if both source vertex and destination vertex are both present in the # adjacency list, add destination vertex to source vertex list of adjacent # vertices and add source vertex to destination vertex list of adjacent # vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(A ) self.adj_list[destination_vertex].append(A ) # if only source vertex is present in adjacency list, add destination vertex # to source vertex list of adjacent vertices, then create a new vertex with # destination vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(A ) a = [source_vertex] # if only destination vertex is present in adjacency list, add source vertex # to destination vertex list of adjacent vertices, then create a new vertex # with source vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif destination_vertex in self.adj_list: self.adj_list[destination_vertex].append(A ) a = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and assign a list # containing the destination vertex as it's first adjacent vertex also # create a new vertex with destination vertex as key and assign a list # containing the source vertex as it's first adjacent vertex. else: a = [destination_vertex] a = [source_vertex] else: # For directed graphs # if both source vertex and destination vertex are present in adjacency # list, add destination vertex to source vertex list of adjacent vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(A ) # if only source vertex is present in adjacency list, add destination # vertex to source vertex list of adjacent vertices and create a new vertex # with destination vertex as key, which has no adjacent vertex elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(A ) a = [] # if only destination vertex is present in adjacency list, create a new # vertex with source vertex as key and assign a list containing destination # vertex as first adjacent vertex elif destination_vertex in self.adj_list: a = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and a list containing # destination vertex as it's first adjacent vertex. Then create a new vertex # with destination vertex as key, which has no adjacent vertex else: a = [destination_vertex] a = [] return self def __repr__( self ) -> str: '''simple docstring''' return pformat(self.adj_list )
180
1
from ....utils import logging lowercase_ = logging.get_logger(__name__) class __UpperCamelCase ( lowerCAmelCase__ ): """simple docstring""" def __init__( self : List[str] , _A : int , _A : List[str]=None , _A : List[Any]=2048 ): """simple docstring""" __SCREAMING_SNAKE_CASE : Tuple = config.__dict__ __SCREAMING_SNAKE_CASE : Union[str, Any] = modal_hidden_size if num_labels: __SCREAMING_SNAKE_CASE : Tuple = num_labels
303
import sys from collections import defaultdict class __UpperCamelCase : """simple docstring""" def __init__( self : Union[str, Any] ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[int] = [] def UpperCAmelCase__ ( self : List[str] , _A : str ): """simple docstring""" return self.node_position[vertex] def UpperCAmelCase__ ( self : Dict , _A : List[str] , _A : Any ): """simple docstring""" __SCREAMING_SNAKE_CASE : Any = pos def UpperCAmelCase__ ( self : List[Any] , _A : Union[str, Any] , _A : List[Any] , _A : List[str] , _A : Union[str, Any] ): """simple docstring""" if start > size // 2 - 1: return else: if 2 * start + 2 >= size: __SCREAMING_SNAKE_CASE : Union[str, Any] = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: __SCREAMING_SNAKE_CASE : List[Any] = 2 * start + 1 else: __SCREAMING_SNAKE_CASE : Dict = 2 * start + 2 if heap[smallest_child] < heap[start]: __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Union[str, Any] = heap[smallest_child], positions[smallest_child] __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : List[str] = ( heap[start], positions[start], ) __SCREAMING_SNAKE_CASE, __SCREAMING_SNAKE_CASE : Tuple = temp, tempa __SCREAMING_SNAKE_CASE : Any = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , _A ) self.top_to_bottom(_A , _A , _A , _A ) def UpperCAmelCase__ ( self : Any , _A : Union[str, Any] , _A : Dict , _A : Optional[Any] , _A : str ): """simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = position[index] while index != 0: __SCREAMING_SNAKE_CASE : Optional[Any] = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: __SCREAMING_SNAKE_CASE : Optional[Any] = heap[parent] __SCREAMING_SNAKE_CASE : str = position[parent] self.set_position(position[parent] , _A ) else: __SCREAMING_SNAKE_CASE : List[str] = val __SCREAMING_SNAKE_CASE : List[str] = temp self.set_position(_A , _A ) break __SCREAMING_SNAKE_CASE : List[Any] = parent else: __SCREAMING_SNAKE_CASE : Tuple = val __SCREAMING_SNAKE_CASE : List[str] = temp self.set_position(_A , 0 ) def UpperCAmelCase__ ( self : List[str] , _A : Tuple , _A : Tuple ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = len(_A ) // 2 - 1 for i in range(_A , -1 , -1 ): self.top_to_bottom(_A , _A , len(_A ) , _A ) def UpperCAmelCase__ ( self : List[str] , _A : Dict , _A : Optional[int] ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[Any] = positions[0] __SCREAMING_SNAKE_CASE : Tuple = sys.maxsize self.top_to_bottom(_A , 0 , len(_A ) , _A ) return temp def a__ ( snake_case ): """simple docstring""" __SCREAMING_SNAKE_CASE : int = Heap() __SCREAMING_SNAKE_CASE : int = [0] * len(snake_case ) __SCREAMING_SNAKE_CASE : Dict = [-1] * len(snake_case ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph __SCREAMING_SNAKE_CASE : Dict = [] # Heap of Distance of vertices from their neighboring vertex __SCREAMING_SNAKE_CASE : Optional[int] = [] for vertex in range(len(snake_case ) ): distance_tv.append(sys.maxsize ) positions.append(snake_case ) heap.node_position.append(snake_case ) __SCREAMING_SNAKE_CASE : Union[str, Any] = [] __SCREAMING_SNAKE_CASE : str = 1 __SCREAMING_SNAKE_CASE : int = sys.maxsize for neighbor, distance in adjacency_list[0]: __SCREAMING_SNAKE_CASE : Optional[Any] = 0 __SCREAMING_SNAKE_CASE : Dict = distance heap.heapify(snake_case , snake_case ) for _ in range(1 , len(snake_case ) ): __SCREAMING_SNAKE_CASE : Tuple = heap.delete_minimum(snake_case , snake_case ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) __SCREAMING_SNAKE_CASE : List[Any] = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(snake_case )] ): __SCREAMING_SNAKE_CASE : int = distance heap.bottom_to_top( snake_case , heap.get_position(snake_case ) , snake_case , snake_case ) __SCREAMING_SNAKE_CASE : Any = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > lowercase_ = int(input("""Enter number of edges: """).strip()) lowercase_ = defaultdict(list) for _ in range(edges_number): lowercase_ = [int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
303
1
def lowerCamelCase_ ( _a , _a ): """simple docstring""" lowerCAmelCase__ : str = len(_a ) + 1 lowerCAmelCase__ : int = len(_a ) + 1 # dp is a 2d matrix where dp[i][j] denotes whether prefix string of # length i of input_string matches with prefix string of length j of # given pattern. # "dp" stands for dynamic programming. lowerCAmelCase__ : List[str] = [[0 for i in range(_a )] for j in range(_a )] # since string of zero length match pattern of zero length lowerCAmelCase__ : int = 1 # since pattern of zero length will never match with string of non-zero length for i in range(1 , _a ): lowerCAmelCase__ : Union[str, Any] = 0 # since string of zero length will match with pattern where there # is at least one * alternatively for j in range(1 , _a ): lowerCAmelCase__ : Tuple = dp[0][j - 2] if pattern[j - 1] == '''*''' else 0 # now using bottom-up approach to find for all remaining lengths for i in range(1 , _a ): for j in range(1 , _a ): if input_string[i - 1] == pattern[j - 1] or pattern[j - 1] == ".": lowerCAmelCase__ : int = dp[i - 1][j - 1] elif pattern[j - 1] == "*": if dp[i][j - 2] == 1: lowerCAmelCase__ : List[str] = 1 elif pattern[j - 2] in (input_string[i - 1], "."): lowerCAmelCase__ : Dict = dp[i - 1][j] else: lowerCAmelCase__ : Optional[Any] = 0 else: lowerCAmelCase__ : Optional[int] = 0 return bool(dp[-1][-1] ) if __name__ == "__main__": import doctest doctest.testmod() # inputing the strings # input_string = input("input a string :") # pattern = input("input a pattern :") lowerCamelCase = '''aab''' lowerCamelCase = '''c*a*b''' # using function to check whether given string matches the given pattern if match_pattern(input_string, pattern): print(f'''{input_string} matches the given pattern {pattern}''') else: print(f'''{input_string} does not match with the given pattern {pattern}''')
211
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase = logging.get_logger(__name__) lowerCamelCase = { '''facebook/dpr-ctx_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json''' ), '''facebook/dpr-question_encoder-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json''' ), '''facebook/dpr-reader-single-nq-base''': ( '''https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json''' ), '''facebook/dpr-ctx_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json''' ), '''facebook/dpr-question_encoder-multiset-base''': ( '''https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json''' ), '''facebook/dpr-reader-multiset-base''': ( '''https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json''' ), } class _a ( _lowercase): _a : List[Any] = '''dpr''' def __init__( self : List[str] , _SCREAMING_SNAKE_CASE : List[str]=3_0522 , _SCREAMING_SNAKE_CASE : Optional[int]=768 , _SCREAMING_SNAKE_CASE : List[str]=12 , _SCREAMING_SNAKE_CASE : Tuple=12 , _SCREAMING_SNAKE_CASE : str=3072 , _SCREAMING_SNAKE_CASE : Optional[Any]="gelu" , _SCREAMING_SNAKE_CASE : Dict=0.1 , _SCREAMING_SNAKE_CASE : Optional[int]=0.1 , _SCREAMING_SNAKE_CASE : List[str]=512 , _SCREAMING_SNAKE_CASE : int=2 , _SCREAMING_SNAKE_CASE : Optional[Any]=0.02 , _SCREAMING_SNAKE_CASE : Tuple=1E-12 , _SCREAMING_SNAKE_CASE : Union[str, Any]=0 , _SCREAMING_SNAKE_CASE : List[str]="absolute" , _SCREAMING_SNAKE_CASE : int = 0 , **_SCREAMING_SNAKE_CASE : Optional[Any] , )-> Optional[int]: super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) lowerCAmelCase__ : Union[str, Any] = vocab_size lowerCAmelCase__ : Tuple = hidden_size lowerCAmelCase__ : Union[str, Any] = num_hidden_layers lowerCAmelCase__ : List[Any] = num_attention_heads lowerCAmelCase__ : Optional[int] = hidden_act lowerCAmelCase__ : Optional[Any] = intermediate_size lowerCAmelCase__ : Optional[Any] = hidden_dropout_prob lowerCAmelCase__ : int = attention_probs_dropout_prob lowerCAmelCase__ : str = max_position_embeddings lowerCAmelCase__ : List[Any] = type_vocab_size lowerCAmelCase__ : Optional[int] = initializer_range lowerCAmelCase__ : List[str] = layer_norm_eps lowerCAmelCase__ : Dict = projection_dim lowerCAmelCase__ : int = position_embedding_type
211
1
"""simple docstring""" def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> list[list[float]]: '''simple docstring''' lowercase_ = [] for data in source_data: for i, el in enumerate(__lowerCAmelCase ): if len(__lowerCAmelCase ) < i + 1: data_lists.append([] ) data_lists[i].append(float(__lowerCAmelCase ) ) return data_lists def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase ) -> list[list[float]]: '''simple docstring''' lowercase_ = [] for dlist, weight in zip(__lowerCAmelCase , __lowerCAmelCase ): lowercase_ = min(__lowerCAmelCase ) lowercase_ = max(__lowerCAmelCase ) lowercase_ = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind)) ) except ZeroDivisionError: score.append(1 ) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind) ) except ZeroDivisionError: score.append(0 ) # weight not 0 or 1 else: lowercase_ = F'''Invalid weight of {weight:f} provided''' raise ValueError(__lowerCAmelCase ) score_lists.append(__lowerCAmelCase ) return score_lists def _SCREAMING_SNAKE_CASE (__lowerCAmelCase ) -> list[float]: '''simple docstring''' lowercase_ = [0 for i in range(len(score_lists[0] ) )] for slist in score_lists: for j, ele in enumerate(__lowerCAmelCase ): lowercase_ = final_scores[j] + ele return final_scores def _SCREAMING_SNAKE_CASE (__lowerCAmelCase , __lowerCAmelCase ) -> list[list[float]]: '''simple docstring''' lowercase_ = get_data(__lowerCAmelCase ) lowercase_ = calculate_each_score(__lowerCAmelCase , __lowerCAmelCase ) lowercase_ = generate_final_scores(__lowerCAmelCase ) # append scores to source data for i, ele in enumerate(__lowerCAmelCase ): source_data[i].append(__lowerCAmelCase ) return source_data
136
"""simple docstring""" from ...utils import logging from ..ta.modeling_tf_ta import TFTaEncoderModel, TFTaForConditionalGeneration, TFTaModel from .configuration_mta import MTaConfig UpperCAmelCase : List[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = "T5Config" class SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase ): lowercase__ = "mt5" lowercase__ = MTaConfig class SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase ): lowercase__ = "mt5" lowercase__ = MTaConfig class SCREAMING_SNAKE_CASE__ ( __UpperCAmelCase ): lowercase__ = "mt5" lowercase__ = MTaConfig
136
1
from collections import OrderedDict from typing import Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...feature_extraction_utils import FeatureExtractionMixin from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType, logging lowerCamelCase_ : Optional[Any] = logging.get_logger(__name__) lowerCamelCase_ : int = { """deepmind/language-perceiver""": """https://huggingface.co/deepmind/language-perceiver/resolve/main/config.json""", # See all Perceiver models at https://huggingface.co/models?filter=perceiver } class a__ ( __snake_case ): A__ : Dict = 'perceiver' def __init__( self , UpperCAmelCase=2_5_6 , UpperCAmelCase=1_2_8_0 , UpperCAmelCase=7_6_8 , UpperCAmelCase=1 , UpperCAmelCase=2_6 , UpperCAmelCase=8 , UpperCAmelCase=8 , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase="kv" , UpperCAmelCase=1 , UpperCAmelCase=1 , UpperCAmelCase="gelu" , UpperCAmelCase=0.1 , UpperCAmelCase=0.02 , UpperCAmelCase=1e-12 , UpperCAmelCase=True , UpperCAmelCase=2_6_2 , UpperCAmelCase=2_0_4_8 , UpperCAmelCase=5_6 , UpperCAmelCase=[3_6_8, 4_9_6] , UpperCAmelCase=1_6 , UpperCAmelCase=1_9_2_0 , UpperCAmelCase=1_6 , UpperCAmelCase=[1, 1_6, 2_2_4, 2_2_4] , **UpperCAmelCase , ) -> Optional[int]: super().__init__(**UpperCAmelCase ) __a = num_latents __a = d_latents __a = d_model __a = num_blocks __a = num_self_attends_per_block __a = num_self_attention_heads __a = num_cross_attention_heads __a = qk_channels __a = v_channels __a = cross_attention_shape_for_attention __a = self_attention_widening_factor __a = cross_attention_widening_factor __a = hidden_act __a = attention_probs_dropout_prob __a = initializer_range __a = layer_norm_eps __a = use_query_residual # masked language modeling attributes __a = vocab_size __a = max_position_embeddings # image classification attributes __a = image_size # flow attributes __a = train_size # multimodal autoencoding attributes __a = num_frames __a = audio_samples_per_frame __a = samples_per_patch __a = output_shape class a__ ( __snake_case ): @property def __SCREAMING_SNAKE_CASE ( self ) -> Mapping[str, Mapping[int, str]]: if self.task == "multiple-choice": __a = {0: 'batch', 1: 'choice', 2: 'sequence'} else: __a = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('inputs', dynamic_axis), ('attention_mask', dynamic_axis), ] ) @property def __SCREAMING_SNAKE_CASE ( self ) -> float: return 1e-4 def __SCREAMING_SNAKE_CASE ( self , UpperCAmelCase , UpperCAmelCase = -1 , UpperCAmelCase = -1 , UpperCAmelCase = -1 , UpperCAmelCase = False , UpperCAmelCase = None , UpperCAmelCase = 3 , UpperCAmelCase = 4_0 , UpperCAmelCase = 4_0 , ) -> Mapping[str, Any]: # copied from `transformers.onnx.config.OnnxConfig` and slightly altered/simplified if isinstance(UpperCAmelCase , UpperCAmelCase ): # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX __a = compute_effective_axis_dimension( UpperCAmelCase , 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 = preprocessor.num_special_tokens_to_add(UpperCAmelCase ) __a = compute_effective_axis_dimension( UpperCAmelCase , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=UpperCAmelCase ) # Generate dummy inputs according to compute batch and sequence __a = [' '.join(['a'] ) * seq_length] * batch_size __a = dict(preprocessor(UpperCAmelCase , return_tensors=UpperCAmelCase ) ) __a = inputs.pop('input_ids' ) return inputs elif isinstance(UpperCAmelCase , UpperCAmelCase ) and preprocessor.model_input_names[0] == "pixel_values": # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX __a = compute_effective_axis_dimension(UpperCAmelCase , fixed_dimension=OnnxConfig.default_fixed_batch ) __a = self._generate_dummy_images(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) __a = dict(preprocessor(images=UpperCAmelCase , return_tensors=UpperCAmelCase ) ) __a = inputs.pop('pixel_values' ) return inputs else: raise ValueError( 'Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor.' )
367
def lowerCAmelCase( __lowerCamelCase ): if not all(char in '01' for char in bin_string ): raise ValueError('Non-binary value was passed to the function' ) if not bin_string: raise ValueError('Empty string was passed to the function' ) __a = '' while len(__lowerCamelCase ) % 3 != 0: __a = '0' + bin_string __a = [ bin_string[index : index + 3] for index in range(len(__lowerCamelCase ) ) if index % 3 == 0 ] for bin_group in bin_string_in_3_list: __a = 0 for index, val in enumerate(__lowerCamelCase ): oct_val += int(2 ** (2 - index) * int(__lowerCamelCase ) ) oct_string += str(__lowerCamelCase ) return oct_string if __name__ == "__main__": from doctest import testmod testmod()
197
0
import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def snake_case__ ( SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : str=0.999 , SCREAMING_SNAKE_CASE_ : List[Any]="cosine" , ): '''simple docstring''' if alpha_transform_type == "cosine": def alpha_bar_fn(SCREAMING_SNAKE_CASE_ : Tuple ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(SCREAMING_SNAKE_CASE_ : List[str] ): return math.exp(t * -12.0 ) else: raise ValueError(f"""Unsupported alpha_tranform_type: {alpha_transform_type}""" ) lowercase__ : str = [] for i in range(SCREAMING_SNAKE_CASE_ ): lowercase__ : Optional[int] = i / num_diffusion_timesteps lowercase__ : List[Any] = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(SCREAMING_SNAKE_CASE_ ) / alpha_bar_fn(SCREAMING_SNAKE_CASE_ ) , SCREAMING_SNAKE_CASE_ ) ) return torch.tensor(SCREAMING_SNAKE_CASE_ , dtype=torch.floataa ) class SCREAMING_SNAKE_CASE__ (__snake_case , __snake_case ): __lowerCamelCase : List[str] = [e.name for e in KarrasDiffusionSchedulers] __lowerCamelCase : Any = 2 @register_to_config def __init__( self , a = 1000 , a = 0.00_085 , a = 0.012 , a = "linear" , a = None , a = "epsilon" , a = "linspace" , a = 0 , ): if trained_betas is not None: lowercase__ : List[str] = torch.tensor(lowerCamelCase_ , dtype=torch.floataa) elif beta_schedule == "linear": lowercase__ : Optional[Any] = torch.linspace(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , dtype=torch.floataa) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. lowercase__ : str = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , lowerCamelCase_ , dtype=torch.floataa) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule lowercase__ : List[str] = betas_for_alpha_bar(lowerCamelCase_) else: raise NotImplementedError(f"""{beta_schedule} does is not implemented for {self.__class__}""") lowercase__ : Tuple = 1.0 - self.betas lowercase__ : Any = torch.cumprod(self.alphas , dim=0) # set all values self.set_timesteps(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_) def snake_case_ ( self , a , a=None): if schedule_timesteps is None: lowercase__ : List[Any] = self.timesteps lowercase__ : Any = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter) == 0: lowercase__ : Dict = 1 if len(lowerCamelCase_) > 1 else 0 else: lowercase__ : Tuple = timestep.cpu().item() if torch.is_tensor(lowerCamelCase_) else timestep lowercase__ : List[str] = self._index_counter[timestep_int] return indices[pos].item() @property def snake_case_ ( self): if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def snake_case_ ( self , a , a , ): lowercase__ : Union[str, Any] = self.index_for_timestep(lowerCamelCase_) if self.state_in_first_order: lowercase__ : List[Any] = self.sigmas[step_index] else: lowercase__ : Optional[Any] = self.sigmas_interpol[step_index] lowercase__ : Dict = sample / ((sigma**2 + 1) ** 0.5) return sample def snake_case_ ( self , a , a = None , a = None , ): lowercase__ : Dict = num_inference_steps lowercase__ : Optional[int] = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": lowercase__ : List[str] = np.linspace(0 , num_train_timesteps - 1 , lowerCamelCase_ , dtype=lowerCamelCase_)[::-1].copy() elif self.config.timestep_spacing == "leading": lowercase__ : Any = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 lowercase__ : Union[str, Any] = (np.arange(0 , lowerCamelCase_) * step_ratio).round()[::-1].copy().astype(lowerCamelCase_) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": lowercase__ : Union[str, Any] = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 lowercase__ : Optional[Any] = (np.arange(lowerCamelCase_ , 0 , -step_ratio)).round().copy().astype(lowerCamelCase_) timesteps -= 1 else: raise ValueError( f"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.""") lowercase__ : Union[str, Any] = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5) lowercase__ : Tuple = torch.from_numpy(np.log(lowerCamelCase_)).to(lowerCamelCase_) lowercase__ : Dict = np.interp(lowerCamelCase_ , np.arange(0 , len(lowerCamelCase_)) , lowerCamelCase_) lowercase__ : List[str] = np.concatenate([sigmas, [0.0]]).astype(np.floataa) lowercase__ : Tuple = torch.from_numpy(lowerCamelCase_).to(device=lowerCamelCase_) # interpolate sigmas lowercase__ : Any = sigmas.log().lerp(sigmas.roll(1).log() , 0.5).exp() lowercase__ : int = torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2), sigmas[-1:]]) lowercase__ : Dict = torch.cat( [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2), sigmas_interpol[-1:]]) if str(lowerCamelCase_).startswith('mps'): # mps does not support float64 lowercase__ : Any = torch.from_numpy(lowerCamelCase_).to(lowerCamelCase_ , dtype=torch.floataa) else: lowercase__ : Optional[int] = torch.from_numpy(lowerCamelCase_).to(lowerCamelCase_) # interpolate timesteps lowercase__ : Optional[Any] = self.sigma_to_t(lowerCamelCase_).to(lowerCamelCase_ , dtype=timesteps.dtype) lowercase__ : Dict = torch.stack((timesteps_interpol[1:-1, None], timesteps[1:, None]) , dim=-1).flatten() lowercase__ : str = torch.cat([timesteps[:1], interleaved_timesteps]) lowercase__ : Dict = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter lowercase__ : Dict = defaultdict(lowerCamelCase_) def snake_case_ ( self , a): lowercase__ : Optional[Any] = sigma.log() # get distribution lowercase__ : str = log_sigma - self.log_sigmas[:, None] # get sigmas range lowercase__ : Union[str, Any] = dists.ge(0).cumsum(dim=0).argmax(dim=0).clamp(max=self.log_sigmas.shape[0] - 2) lowercase__ : List[Any] = low_idx + 1 lowercase__ : List[Any] = self.log_sigmas[low_idx] lowercase__ : Tuple = self.log_sigmas[high_idx] # interpolate sigmas lowercase__ : Any = (low - log_sigma) / (low - high) lowercase__ : Dict = w.clamp(0 , 1) # transform interpolation to time range lowercase__ : Optional[Any] = (1 - w) * low_idx + w * high_idx lowercase__ : Union[str, Any] = t.view(sigma.shape) return t @property def snake_case_ ( self): return self.sample is None def snake_case_ ( self , a , a , a , a = True , ): lowercase__ : Optional[int] = self.index_for_timestep(lowerCamelCase_) # advance index counter by 1 lowercase__ : List[str] = timestep.cpu().item() if torch.is_tensor(lowerCamelCase_) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: lowercase__ : Tuple = self.sigmas[step_index] lowercase__ : Any = self.sigmas_interpol[step_index + 1] lowercase__ : List[str] = self.sigmas[step_index + 1] else: # 2nd order / KDPM2's method lowercase__ : Optional[int] = self.sigmas[step_index - 1] lowercase__ : Optional[Any] = self.sigmas_interpol[step_index] lowercase__ : int = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API lowercase__ : Optional[int] = 0 lowercase__ : int = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": lowercase__ : List[str] = sigma_hat if self.state_in_first_order else sigma_interpol lowercase__ : Union[str, Any] = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": lowercase__ : int = sigma_hat if self.state_in_first_order else sigma_interpol lowercase__ : int = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": raise NotImplementedError('prediction_type not implemented yet: sample') else: raise ValueError( f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`""") if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order lowercase__ : Dict = (sample - pred_original_sample) / sigma_hat # 3. delta timestep lowercase__ : List[Any] = sigma_interpol - sigma_hat # store for 2nd order step lowercase__ : str = sample else: # DPM-Solver-2 # 2. Convert to an ODE derivative for 2nd order lowercase__ : Optional[Any] = (sample - pred_original_sample) / sigma_interpol # 3. delta timestep lowercase__ : Optional[int] = sigma_next - sigma_hat lowercase__ : Union[str, Any] = self.sample lowercase__ : Optional[int] = None lowercase__ : int = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=lowerCamelCase_) def snake_case_ ( self , a , a , a , ): lowercase__ : str = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype) if original_samples.device.type == "mps" and torch.is_floating_point(lowerCamelCase_): # mps does not support float64 lowercase__ : Dict = self.timesteps.to(original_samples.device , dtype=torch.floataa) lowercase__ : List[Any] = timesteps.to(original_samples.device , dtype=torch.floataa) else: lowercase__ : Dict = self.timesteps.to(original_samples.device) lowercase__ : List[str] = timesteps.to(original_samples.device) lowercase__ : str = [self.index_for_timestep(lowerCamelCase_ , lowerCamelCase_) for t in timesteps] lowercase__ : Optional[int] = sigmas[step_indices].flatten() while len(sigma.shape) < len(original_samples.shape): lowercase__ : int = sigma.unsqueeze(-1) lowercase__ : List[str] = original_samples + noise * sigma return noisy_samples def __len__( self): return self.config.num_train_timesteps
214
import argparse import torch from datasets import load_dataset from donut import DonutModel from transformers import ( DonutImageProcessor, DonutProcessor, DonutSwinConfig, DonutSwinModel, MBartConfig, MBartForCausalLM, VisionEncoderDecoderModel, XLMRobertaTokenizerFast, ) def a( A : Tuple ) -> Optional[Any]: """simple docstring""" a = model.config a = DonutSwinConfig( image_size=original_config.input_size , patch_size=4 , depths=original_config.encoder_layer , num_heads=[4, 8, 16, 32] , window_size=original_config.window_size , embed_dim=128 , ) a = MBartConfig( is_decoder=A , is_encoder_decoder=A , add_cross_attention=A , decoder_layers=original_config.decoder_layer , max_position_embeddings=original_config.max_position_embeddings , vocab_size=len( model.decoder.tokenizer ) , scale_embedding=A , add_final_layer_norm=A , ) return encoder_config, decoder_config def a( A : List[Any] ) -> Union[str, Any]: """simple docstring""" if "encoder.model" in name: a = name.replace("encoder.model" , "encoder" ) if "decoder.model" in name: a = name.replace("decoder.model" , "decoder" ) if "patch_embed.proj" in name: a = name.replace("patch_embed.proj" , "embeddings.patch_embeddings.projection" ) if "patch_embed.norm" in name: a = name.replace("patch_embed.norm" , "embeddings.norm" ) if name.startswith("encoder" ): if "layers" in name: a = "encoder." + name if "attn.proj" in name: a = name.replace("attn.proj" , "attention.output.dense" ) if "attn" in name and "mask" not in name: a = name.replace("attn" , "attention.self" ) if "norm1" in name: a = name.replace("norm1" , "layernorm_before" ) if "norm2" in name: a = name.replace("norm2" , "layernorm_after" ) if "mlp.fc1" in name: a = name.replace("mlp.fc1" , "intermediate.dense" ) if "mlp.fc2" in name: a = name.replace("mlp.fc2" , "output.dense" ) if name == "encoder.norm.weight": a = "encoder.layernorm.weight" if name == "encoder.norm.bias": a = "encoder.layernorm.bias" return name def a( A : Union[str, Any] , A : Tuple ) -> List[Any]: """simple docstring""" for key in orig_state_dict.copy().keys(): a = orig_state_dict.pop(A ) if "qkv" in key: a = key.split("." ) a = int(key_split[3] ) a = int(key_split[5] ) a = model.encoder.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: a = val[:dim, :] a = val[dim : dim * 2, :] a = val[-dim:, :] else: a = val[:dim] a = val[dim : dim * 2] a = val[-dim:] elif "attn_mask" in key or key in ["encoder.model.norm.weight", "encoder.model.norm.bias"]: # HuggingFace implementation doesn't use attn_mask buffer # and model doesn't use final LayerNorms for the encoder pass else: a = val return orig_state_dict def a( A : List[Any] , A : Tuple=None , A : List[Any]=False ) -> Optional[int]: """simple docstring""" a = DonutModel.from_pretrained(A ).eval() # load HuggingFace model a , a = get_configs(A ) a = DonutSwinModel(A ) a = MBartForCausalLM(A ) a = VisionEncoderDecoderModel(encoder=A , decoder=A ) model.eval() a = original_model.state_dict() a = convert_state_dict(A , A ) model.load_state_dict(A ) # verify results on scanned document a = load_dataset("hf-internal-testing/example-documents" ) a = dataset["test"][0]["image"].convert("RGB" ) a = XLMRobertaTokenizerFast.from_pretrained(A , from_slow=A ) a = DonutImageProcessor( do_align_long_axis=original_model.config.align_long_axis , size=original_model.config.input_size[::-1] ) a = DonutProcessor(A , A ) a = processor(A , return_tensors="pt" ).pixel_values if model_name == "naver-clova-ix/donut-base-finetuned-docvqa": a = "<s_docvqa><s_question>{user_input}</s_question><s_answer>" a = "When is the coffee break?" a = task_prompt.replace("{user_input}" , A ) elif model_name == "naver-clova-ix/donut-base-finetuned-rvlcdip": a = "<s_rvlcdip>" elif model_name in [ "naver-clova-ix/donut-base-finetuned-cord-v1", "naver-clova-ix/donut-base-finetuned-cord-v1-2560", ]: a = "<s_cord>" elif model_name == "naver-clova-ix/donut-base-finetuned-cord-v2": a = "s_cord-v2>" elif model_name == "naver-clova-ix/donut-base-finetuned-zhtrainticket": a = "<s_zhtrainticket>" elif model_name in ["naver-clova-ix/donut-proto", "naver-clova-ix/donut-base"]: # use a random prompt a = "hello world" else: raise ValueError("Model name not supported" ) a = original_model.decoder.tokenizer(A , add_special_tokens=A , return_tensors="pt" )[ "input_ids" ] a = original_model.encoder.model.patch_embed(A ) a , a = model.encoder.embeddings(A ) assert torch.allclose(A , A , atol=1e-3 ) # verify encoder hidden states a = original_model.encoder(A ) a = model.encoder(A ).last_hidden_state assert torch.allclose(A , A , atol=1e-2 ) # verify decoder hidden states a = original_model(A , A , A ).logits a = model(A , decoder_input_ids=A ).logits assert torch.allclose(A , A , atol=1e-3 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: print(f'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(A ) processor.save_pretrained(A ) if push_to_hub: model.push_to_hub("nielsr/" + model_name.split("/" )[-1] , commit_message="Update model" ) processor.push_to_hub("nielsr/" + model_name.split("/" )[-1] , commit_message="Update model" ) if __name__ == "__main__": _lowercase: Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="naver-clova-ix/donut-base-finetuned-docvqa", required=False, type=str, help="Name of the original model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, required=False, type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether or not to push the converted model and processor to the 🤗 hub.", ) _lowercase: Optional[Any] = parser.parse_args() convert_donut_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
227
0
'''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 __lowerCamelCase = logging.get_logger(__name__) if is_vision_available(): import PIL class A__ ( _snake_case ): lowercase = ["pixel_values"] def __init__( self , UpperCamelCase__ = True , UpperCamelCase__ = None , UpperCamelCase__ = PILImageResampling.BICUBIC , UpperCamelCase__ = True , UpperCamelCase__ = None , UpperCamelCase__ = True , UpperCamelCase__ = 1 / 255 , UpperCamelCase__ = True , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__ = True , **UpperCamelCase__ , ) -> None: '''simple docstring''' super().__init__(**UpperCamelCase__ ) A_ = size if size is not None else {"""shortest_edge""": 224} A_ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) A_ = crop_size if crop_size is not None else {"""height""": 224, """width""": 224} A_ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ , 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 snake_case_ ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = PILImageResampling.BICUBIC , UpperCamelCase__ = None , **UpperCamelCase__ , ) -> np.ndarray: '''simple docstring''' A_ = get_size_dict(UpperCamelCase__ , default_to_square=UpperCamelCase__ ) if "shortest_edge" not in size: raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}''' ) A_ = get_resize_output_image_size(UpperCamelCase__ , size=size["""shortest_edge"""] , default_to_square=UpperCamelCase__ ) return resize(UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def snake_case_ ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = None , **UpperCamelCase__ , ) -> np.ndarray: '''simple docstring''' A_ = get_size_dict(UpperCamelCase__ ) if "height" not in size or "width" not in size: raise ValueError(f'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' ) return center_crop(UpperCamelCase__ , size=(size["""height"""], size["""width"""]) , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def snake_case_ ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = None , **UpperCamelCase__ , ) -> int: '''simple docstring''' return rescale(UpperCamelCase__ , scale=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def snake_case_ ( self , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = None , **UpperCamelCase__ , ) -> np.ndarray: '''simple docstring''' return normalize(UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ , data_format=UpperCamelCase__ , **UpperCamelCase__ ) def snake_case_ ( self , UpperCamelCase__ , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__ = None , UpperCamelCase__ = ChannelDimension.FIRST , **UpperCamelCase__ , ) -> PIL.Image.Image: '''simple docstring''' 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(UpperCamelCase__ , param_name="""size""" , default_to_square=UpperCamelCase__ ) 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(UpperCamelCase__ , param_name="""crop_size""" , default_to_square=UpperCamelCase__ ) 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(UpperCamelCase__ ) if not valid_images(UpperCamelCase__ ): raise ValueError( """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """ """torch.Tensor, tf.Tensor or jax.ndarray.""" ) if do_resize and size is None: raise ValueError("""Size must be specified if do_resize is True.""" ) if do_center_crop and crop_size is None: raise ValueError("""Crop size must be specified if do_center_crop is True.""" ) if do_rescale and rescale_factor is None: raise ValueError("""Rescale factor must be specified if do_rescale is True.""" ) if do_normalize and (image_mean is None or image_std is None): raise ValueError("""Image mean and std must be specified if do_normalize is True.""" ) # PIL RGBA images are converted to RGB if do_convert_rgb: A_ = [convert_to_rgb(UpperCamelCase__ ) for image in images] # All transformations expect numpy arrays. A_ = [to_numpy_array(UpperCamelCase__ ) for image in images] if do_resize: A_ = [self.resize(image=UpperCamelCase__ , size=UpperCamelCase__ , resample=UpperCamelCase__ ) for image in images] if do_center_crop: A_ = [self.center_crop(image=UpperCamelCase__ , size=UpperCamelCase__ ) for image in images] if do_rescale: A_ = [self.rescale(image=UpperCamelCase__ , scale=UpperCamelCase__ ) for image in images] if do_normalize: A_ = [self.normalize(image=UpperCamelCase__ , mean=UpperCamelCase__ , std=UpperCamelCase__ ) for image in images] A_ = [to_channel_dimension_format(UpperCamelCase__ , UpperCamelCase__ ) for image in images] A_ = {"""pixel_values""": images} return BatchFeature(data=UpperCamelCase__ , tensor_type=UpperCamelCase__ )
101
'''simple docstring''' import requests __lowerCamelCase = '''''' # <-- Put your OpenWeatherMap appid here! __lowerCamelCase = '''https://api.openweathermap.org/data/2.5/''' def UpperCAmelCase__ ( UpperCAmelCase__ = "Chicago", UpperCAmelCase__ = APPID ) -> dict: return requests.get(URL_BASE + """weather""", params=locals() ).json() def UpperCAmelCase__ ( UpperCAmelCase__ = "Kolkata, India", UpperCAmelCase__ = APPID ) -> dict: return requests.get(URL_BASE + """forecast""", params=locals() ).json() def UpperCAmelCase__ ( UpperCAmelCase__ = 55.68, UpperCAmelCase__ = 12.57, UpperCAmelCase__ = APPID ) -> dict: return requests.get(URL_BASE + """onecall""", params=locals() ).json() if __name__ == "__main__": from pprint import pprint while True: __lowerCamelCase = input('''Enter a location:''').strip() if location: pprint(current_weather(location)) else: break
101
1
"""simple docstring""" import dataclasses import re import string from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple import numpy as np from . import residue_constants a__ : Optional[Any] = Mapping[str, np.ndarray] a__ : Optional[Any] = Mapping[str, Any] # Is a nested dict. a__ : Optional[int] = 0.01 @dataclasses.dataclass(frozen=UpperCamelCase) class UpperCamelCase_ : """simple docstring""" snake_case__ : np.ndarray # [num_res, num_atom_type, 3] # Amino-acid type for each residue represented as an integer between 0 and # 20, where 20 is 'X'. snake_case__ : np.ndarray # [num_res] # Binary float mask to indicate presence of a particular atom. 1.0 if an atom # is present and 0.0 if not. This should be used for loss masking. snake_case__ : np.ndarray # [num_res, num_atom_type] # Residue index as used in PDB. It is not necessarily continuous or 0-indexed. snake_case__ : np.ndarray # [num_res] # B-factors, or temperature factors, of each residue (in sq. angstroms units), # representing the displacement of the residue from its ground truth mean # value. snake_case__ : np.ndarray # [num_res, num_atom_type] # Chain indices for multi-chain predictions snake_case__ : Optional[np.ndarray] = None # Optional remark about the protein. Included as a comment in output PDB # files snake_case__ : Optional[str] = None # Templates used to generate this protein (prediction-only) snake_case__ : Optional[Sequence[str]] = None # Chain corresponding to each parent snake_case__ : Optional[Sequence[int]] = None def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = R"(\[[A-Z]+\]\n)" __SCREAMING_SNAKE_CASE = [tag.strip() for tag in re.split(lowerCAmelCase_ , lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0] __SCREAMING_SNAKE_CASE = zip(tags[0::2] , [l.split("\n" ) for l in tags[1::2]] ) __SCREAMING_SNAKE_CASE = ["N", "CA", "C"] __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None __SCREAMING_SNAKE_CASE = None for g in groups: if "[PRIMARY]" == g[0]: __SCREAMING_SNAKE_CASE = g[1][0].strip() for i in range(len(lowerCAmelCase_ ) ): if seq[i] not in residue_constants.restypes: __SCREAMING_SNAKE_CASE = "X" # FIXME: strings are immutable __SCREAMING_SNAKE_CASE = np.array( [residue_constants.restype_order.get(lowerCAmelCase_ , residue_constants.restype_num ) for res_symbol in seq] ) elif "[TERTIARY]" == g[0]: __SCREAMING_SNAKE_CASE = [] for axis in range(3 ): tertiary.append(list(map(lowerCAmelCase_ , g[1][axis].split() ) ) ) __SCREAMING_SNAKE_CASE = np.array(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = np.zeros((len(tertiary[0] ) // 3, residue_constants.atom_type_num, 3) ).astype(np.floataa ) for i, atom in enumerate(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = np.transpose(tertiary_np[:, i::3] ) atom_positions *= PICO_TO_ANGSTROM elif "[MASK]" == g[0]: __SCREAMING_SNAKE_CASE = np.array(list(map({"-": 0, "+": 1}.get , g[1][0].strip() ) ) ) __SCREAMING_SNAKE_CASE = np.zeros( ( len(lowerCAmelCase_ ), residue_constants.atom_type_num, ) ).astype(np.floataa ) for i, atom in enumerate(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = 1 atom_mask *= mask[..., None] assert aatype is not None return Protein( atom_positions=lowerCAmelCase_ , atom_mask=lowerCAmelCase_ , aatype=lowerCAmelCase_ , residue_index=np.arange(len(lowerCAmelCase_ ) ) , b_factors=lowerCAmelCase_ , ) def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ = 0 ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = prot.remark if remark is not None: pdb_headers.append(f"""REMARK {remark}""" ) __SCREAMING_SNAKE_CASE = prot.parents __SCREAMING_SNAKE_CASE = prot.parents_chain_index if parents is not None and parents_chain_index is not None: __SCREAMING_SNAKE_CASE = [p for i, p in zip(lowerCAmelCase_ , lowerCAmelCase_ ) if i == chain_id] if parents is None or len(lowerCAmelCase_ ) == 0: __SCREAMING_SNAKE_CASE = ["N/A"] pdb_headers.append(f"""PARENT {' '.join(lowerCAmelCase_ )}""" ) return pdb_headers def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = pdb_str.split("\n" ) __SCREAMING_SNAKE_CASE = prot.remark if remark is not None: out_pdb_lines.append(f"""REMARK {remark}""" ) __SCREAMING_SNAKE_CASE = 42 if prot.parents is not None and len(prot.parents ) > 0: __SCREAMING_SNAKE_CASE = [] if prot.parents_chain_index is not None: __SCREAMING_SNAKE_CASE = {} for p, i in zip(prot.parents , prot.parents_chain_index ): parent_dict.setdefault(str(lowerCAmelCase_ ) , [] ) parent_dict[str(lowerCAmelCase_ )].append(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = max([int(lowerCAmelCase_ ) for chain_idx in parent_dict] ) for i in range(max_idx + 1 ): __SCREAMING_SNAKE_CASE = parent_dict.get(str(lowerCAmelCase_ ) , ["N/A"] ) parents_per_chain.append(lowerCAmelCase_ ) else: parents_per_chain.append(list(prot.parents ) ) else: __SCREAMING_SNAKE_CASE = [["N/A"]] def make_parent_line(lowerCAmelCase_ ) -> str: return f"""PARENT {' '.join(lowerCAmelCase_ )}""" out_pdb_lines.append(make_parent_line(parents_per_chain[0] ) ) __SCREAMING_SNAKE_CASE = 0 for i, l in enumerate(lowerCAmelCase_ ): if "PARENT" not in l and "REMARK" not in l: out_pdb_lines.append(lowerCAmelCase_ ) if "TER" in l and "END" not in lines[i + 1]: chain_counter += 1 if not chain_counter >= len(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = parents_per_chain[chain_counter] else: __SCREAMING_SNAKE_CASE = ["N/A"] out_pdb_lines.append(make_parent_line(lowerCAmelCase_ ) ) return "\n".join(lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' __SCREAMING_SNAKE_CASE = residue_constants.restypes + ["X"] def res_atoa(lowerCAmelCase_ ) -> str: return residue_constants.restype_atoa.get(restypes[r] , "UNK" ) __SCREAMING_SNAKE_CASE = residue_constants.atom_types __SCREAMING_SNAKE_CASE = [] __SCREAMING_SNAKE_CASE = prot.atom_mask __SCREAMING_SNAKE_CASE = prot.aatype __SCREAMING_SNAKE_CASE = prot.atom_positions __SCREAMING_SNAKE_CASE = prot.residue_index.astype(np.intaa ) __SCREAMING_SNAKE_CASE = prot.b_factors __SCREAMING_SNAKE_CASE = prot.chain_index if np.any(aatype > residue_constants.restype_num ): raise ValueError("Invalid aatypes." ) __SCREAMING_SNAKE_CASE = get_pdb_headers(lowerCAmelCase_ ) if len(lowerCAmelCase_ ) > 0: pdb_lines.extend(lowerCAmelCase_ ) __SCREAMING_SNAKE_CASE = aatype.shape[0] __SCREAMING_SNAKE_CASE = 1 __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = string.ascii_uppercase __SCREAMING_SNAKE_CASE = None # Add all atom sites. for i in range(lowerCAmelCase_ ): __SCREAMING_SNAKE_CASE = res_atoa(aatype[i] ) for atom_name, pos, mask, b_factor in zip(lowerCAmelCase_ , atom_positions[i] , atom_mask[i] , b_factors[i] ): if mask < 0.5: continue __SCREAMING_SNAKE_CASE = "ATOM" __SCREAMING_SNAKE_CASE = atom_name if len(lowerCAmelCase_ ) == 4 else f""" {atom_name}""" __SCREAMING_SNAKE_CASE = "" __SCREAMING_SNAKE_CASE = "" __SCREAMING_SNAKE_CASE = 1.00 __SCREAMING_SNAKE_CASE = atom_name[0] # Protein supports only C, N, O, S, this works. __SCREAMING_SNAKE_CASE = "" __SCREAMING_SNAKE_CASE = "A" if chain_index is not None: __SCREAMING_SNAKE_CASE = chain_tags[chain_index[i]] # PDB is a columnar format, every space matters here! __SCREAMING_SNAKE_CASE = ( f"""{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}""" f"""{res_name_a:>3} {chain_tag:>1}""" f"""{residue_index[i]:>4}{insertion_code:>1} """ f"""{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}""" f"""{occupancy:>6.2f}{b_factor:>6.2f} """ f"""{element:>2}{charge:>2}""" ) pdb_lines.append(lowerCAmelCase_ ) atom_index += 1 __SCREAMING_SNAKE_CASE = i == n - 1 if chain_index is not None: if i != n - 1 and chain_index[i + 1] != prev_chain_index: __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = chain_index[i + 1] if should_terminate: # Close the chain. __SCREAMING_SNAKE_CASE = "TER" __SCREAMING_SNAKE_CASE = ( f"""{chain_end:<6}{atom_index:>5} {res_atoa(aatype[i] ):>3} {chain_tag:>1}{residue_index[i]:>4}""" ) pdb_lines.append(lowerCAmelCase_ ) atom_index += 1 if i != n - 1: # "prev" is a misnomer here. This happens at the beginning of # each new chain. pdb_lines.extend(get_pdb_headers(lowerCAmelCase_ , lowerCAmelCase_ ) ) pdb_lines.append("END" ) pdb_lines.append("" ) return "\n".join(lowerCAmelCase_ ) def UpperCAmelCase__ (lowerCAmelCase_ ): '''simple docstring''' return residue_constants.STANDARD_ATOM_MASK[prot.aatype] def UpperCAmelCase__ (lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = None , ): '''simple docstring''' return Protein( aatype=features["aatype"] , atom_positions=result["final_atom_positions"] , atom_mask=result["final_atom_mask"] , residue_index=features["residue_index"] + 1 , b_factors=b_factors if b_factors is not None else np.zeros_like(result["final_atom_mask"] ) , chain_index=lowerCAmelCase_ , remark=lowerCAmelCase_ , parents=lowerCAmelCase_ , parents_chain_index=lowerCAmelCase_ , )
54
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) a_ : Union[str, Any] = { """configuration_funnel""": ["""FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP""", """FunnelConfig"""], """convert_funnel_original_tf_checkpoint_to_pytorch""": [], """tokenization_funnel""": ["""FunnelTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : List[str] = ["""FunnelTokenizerFast"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Optional[int] = [ """FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST""", """FunnelBaseModel""", """FunnelForMaskedLM""", """FunnelForMultipleChoice""", """FunnelForPreTraining""", """FunnelForQuestionAnswering""", """FunnelForSequenceClassification""", """FunnelForTokenClassification""", """FunnelModel""", """FunnelPreTrainedModel""", """load_tf_weights_in_funnel""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a_ : Optional[Any] = [ """TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFFunnelBaseModel""", """TFFunnelForMaskedLM""", """TFFunnelForMultipleChoice""", """TFFunnelForPreTraining""", """TFFunnelForQuestionAnswering""", """TFFunnelForSequenceClassification""", """TFFunnelForTokenClassification""", """TFFunnelModel""", """TFFunnelPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_funnel import FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP, FunnelConfig from .tokenization_funnel import FunnelTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_funnel_fast import FunnelTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_funnel import ( FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, FunnelBaseModel, FunnelForMaskedLM, FunnelForMultipleChoice, FunnelForPreTraining, FunnelForQuestionAnswering, FunnelForSequenceClassification, FunnelForTokenClassification, FunnelModel, FunnelPreTrainedModel, load_tf_weights_in_funnel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_funnel import ( TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, TFFunnelPreTrainedModel, ) else: import sys a_ : str = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
75
0
import math from collections.abc import Iterator from itertools import takewhile def snake_case( __magic_name__ ) -> Tuple: '''simple docstring''' if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5 , int(math.sqrt(lowercase__ ) + 1 ) , 6 ): if number % i == 0 or number % (i + 2) == 0: return False return True def snake_case( ) -> Optional[Any]: '''simple docstring''' lowercase : List[Any] = 2 while True: if is_prime(lowercase__ ): yield num num += 1 def snake_case( __magic_name__ = 2_00_00_00 ) -> List[str]: '''simple docstring''' return sum(takewhile(lambda __magic_name__ : x < n , prime_generator() ) ) if __name__ == "__main__": print(f'''{solution() = }''')
362
import argparse import gc import json import os import shutil import warnings import torch from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer try: from transformers import LlamaTokenizerFast except ImportError as e: warnings.warn(e) warnings.warn( 'The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion' ) lowerCAmelCase_ = None lowerCAmelCase_ = { '7B': 1_10_08, '13B': 1_38_24, '30B': 1_79_20, '65B': 2_20_16, '70B': 2_86_72, } lowerCAmelCase_ = { '7B': 1, '7Bf': 1, '13B': 2, '13Bf': 2, '30B': 4, '65B': 8, '70B': 8, '70Bf': 8, } def snake_case( __magic_name__ , __magic_name__=1 , __magic_name__=2_56 ) -> List[Any]: '''simple docstring''' return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3 ) ) + multiple_of - 1) // multiple_of) def snake_case( __magic_name__ ) -> Union[str, Any]: '''simple docstring''' with open(__magic_name__ , '''r''' ) as f: return json.load(__magic_name__ ) def snake_case( __magic_name__ , __magic_name__ ) -> Optional[int]: '''simple docstring''' with open(__magic_name__ , '''w''' ) as f: json.dump(__magic_name__ , __magic_name__ ) def snake_case( __magic_name__ , __magic_name__ , __magic_name__ , __magic_name__=True ) -> Tuple: '''simple docstring''' os.makedirs(__magic_name__ , exist_ok=__magic_name__ ) lowercase : List[Any] = os.path.join(__magic_name__ , '''tmp''' ) os.makedirs(__magic_name__ , exist_ok=__magic_name__ ) lowercase : List[Any] = read_json(os.path.join(__magic_name__ , '''params.json''' ) ) lowercase : int = NUM_SHARDS[model_size] lowercase : str = params['''n_layers'''] lowercase : Optional[int] = params['''n_heads'''] lowercase : str = n_heads // num_shards lowercase : Dict = params['''dim'''] lowercase : int = dim // n_heads lowercase : List[str] = 1_0_0_0_0.0 lowercase : Optional[Any] = 1.0 / (base ** (torch.arange(0 , __magic_name__ , 2 ).float() / dims_per_head)) if "n_kv_heads" in params: lowercase : Optional[Any] = params['''n_kv_heads'''] # for GQA / MQA lowercase : Union[str, Any] = n_heads_per_shard // num_key_value_heads lowercase : Any = dim // num_key_value_heads else: # compatibility with other checkpoints lowercase : Optional[Any] = n_heads lowercase : str = n_heads_per_shard lowercase : Any = dim # permute for sliced rotary def permute(__magic_name__ , __magic_name__=n_heads , __magic_name__=dim , __magic_name__=dim ): return w.view(__magic_name__ , dima // n_heads // 2 , 2 , __magic_name__ ).transpose(1 , 2 ).reshape(__magic_name__ , __magic_name__ ) print(F"""Fetching all parameters from the checkpoint at {input_base_path}.""" ) # Load weights if model_size == "7B": # Not sharded # (The sharded implementation would also work, but this is simpler.) lowercase : Tuple = torch.load(os.path.join(__magic_name__ , '''consolidated.00.pth''' ) , map_location='''cpu''' ) else: # Sharded lowercase : str = [ torch.load(os.path.join(__magic_name__ , F"""consolidated.{i:02d}.pth""" ) , map_location='''cpu''' ) for i in range(__magic_name__ ) ] lowercase : Tuple = 0 lowercase : str = {'''weight_map''': {}} for layer_i in range(__magic_name__ ): lowercase : List[Any] = F"""pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin""" if model_size == "7B": # Unsharded lowercase : int = { F"""model.layers.{layer_i}.self_attn.q_proj.weight""": permute( loaded[F"""layers.{layer_i}.attention.wq.weight"""] ), F"""model.layers.{layer_i}.self_attn.k_proj.weight""": permute( loaded[F"""layers.{layer_i}.attention.wk.weight"""] ), F"""model.layers.{layer_i}.self_attn.v_proj.weight""": loaded[F"""layers.{layer_i}.attention.wv.weight"""], F"""model.layers.{layer_i}.self_attn.o_proj.weight""": loaded[F"""layers.{layer_i}.attention.wo.weight"""], F"""model.layers.{layer_i}.mlp.gate_proj.weight""": loaded[F"""layers.{layer_i}.feed_forward.w1.weight"""], F"""model.layers.{layer_i}.mlp.down_proj.weight""": loaded[F"""layers.{layer_i}.feed_forward.w2.weight"""], F"""model.layers.{layer_i}.mlp.up_proj.weight""": loaded[F"""layers.{layer_i}.feed_forward.w3.weight"""], F"""model.layers.{layer_i}.input_layernorm.weight""": loaded[F"""layers.{layer_i}.attention_norm.weight"""], F"""model.layers.{layer_i}.post_attention_layernorm.weight""": loaded[F"""layers.{layer_i}.ffn_norm.weight"""], } else: # Sharded # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned. lowercase : List[Any] = { F"""model.layers.{layer_i}.input_layernorm.weight""": loaded[0][ F"""layers.{layer_i}.attention_norm.weight""" ].clone(), F"""model.layers.{layer_i}.post_attention_layernorm.weight""": loaded[0][ F"""layers.{layer_i}.ffn_norm.weight""" ].clone(), } lowercase : Tuple = permute( torch.cat( [ loaded[i][F"""layers.{layer_i}.attention.wq.weight"""].view(__magic_name__ , __magic_name__ , __magic_name__ ) for i in range(__magic_name__ ) ] , dim=0 , ).reshape(__magic_name__ , __magic_name__ ) ) lowercase : Any = permute( torch.cat( [ loaded[i][F"""layers.{layer_i}.attention.wk.weight"""].view( __magic_name__ , __magic_name__ , __magic_name__ ) for i in range(__magic_name__ ) ] , dim=0 , ).reshape(__magic_name__ , __magic_name__ ) , __magic_name__ , __magic_name__ , __magic_name__ , ) lowercase : Any = torch.cat( [ loaded[i][F"""layers.{layer_i}.attention.wv.weight"""].view( __magic_name__ , __magic_name__ , __magic_name__ ) for i in range(__magic_name__ ) ] , dim=0 , ).reshape(__magic_name__ , __magic_name__ ) lowercase : int = torch.cat( [loaded[i][F"""layers.{layer_i}.attention.wo.weight"""] for i in range(__magic_name__ )] , dim=1 ) lowercase : str = torch.cat( [loaded[i][F"""layers.{layer_i}.feed_forward.w1.weight"""] for i in range(__magic_name__ )] , dim=0 ) lowercase : Any = torch.cat( [loaded[i][F"""layers.{layer_i}.feed_forward.w2.weight"""] for i in range(__magic_name__ )] , dim=1 ) lowercase : List[Any] = torch.cat( [loaded[i][F"""layers.{layer_i}.feed_forward.w3.weight"""] for i in range(__magic_name__ )] , dim=0 ) lowercase : List[Any] = inv_freq for k, v in state_dict.items(): lowercase : Tuple = filename param_count += v.numel() torch.save(__magic_name__ , os.path.join(__magic_name__ , __magic_name__ ) ) lowercase : Tuple = F"""pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin""" if model_size == "7B": # Unsharded lowercase : Optional[int] = { '''model.embed_tokens.weight''': loaded['''tok_embeddings.weight'''], '''model.norm.weight''': loaded['''norm.weight'''], '''lm_head.weight''': loaded['''output.weight'''], } else: lowercase : Tuple = { '''model.norm.weight''': loaded[0]['''norm.weight'''], '''model.embed_tokens.weight''': torch.cat( [loaded[i]['''tok_embeddings.weight'''] for i in range(__magic_name__ )] , dim=1 ), '''lm_head.weight''': torch.cat([loaded[i]['''output.weight'''] for i in range(__magic_name__ )] , dim=0 ), } for k, v in state_dict.items(): lowercase : Tuple = filename param_count += v.numel() torch.save(__magic_name__ , os.path.join(__magic_name__ , __magic_name__ ) ) # Write configs lowercase : Tuple = {'''total_size''': param_count * 2} write_json(__magic_name__ , os.path.join(__magic_name__ , '''pytorch_model.bin.index.json''' ) ) lowercase : Tuple = params['''ffn_dim_multiplier'''] if '''ffn_dim_multiplier''' in params else 1 lowercase : Tuple = params['''multiple_of'''] if '''multiple_of''' in params else 2_56 lowercase : List[Any] = LlamaConfig( hidden_size=__magic_name__ , intermediate_size=compute_intermediate_size(__magic_name__ , __magic_name__ , __magic_name__ ) , num_attention_heads=params['''n_heads'''] , num_hidden_layers=params['''n_layers'''] , rms_norm_eps=params['''norm_eps'''] , num_key_value_heads=__magic_name__ , ) config.save_pretrained(__magic_name__ ) # Make space so we can load the model properly now. del state_dict del loaded gc.collect() print('''Loading the checkpoint in a Llama model.''' ) lowercase : Dict = LlamaForCausalLM.from_pretrained(__magic_name__ , torch_dtype=torch.floataa , low_cpu_mem_usage=__magic_name__ ) # Avoid saving this as part of the config. del model.config._name_or_path print('''Saving in the Transformers format.''' ) model.save_pretrained(__magic_name__ , safe_serialization=__magic_name__ ) shutil.rmtree(__magic_name__ ) def snake_case( __magic_name__ , __magic_name__ ) -> Optional[int]: '''simple docstring''' lowercase : str = LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast print(F"""Saving a {tokenizer_class.__name__} to {tokenizer_path}.""" ) lowercase : Tuple = tokenizer_class(__magic_name__ ) tokenizer.save_pretrained(__magic_name__ ) def snake_case( ) -> Optional[Any]: '''simple docstring''' lowercase : List[str] = argparse.ArgumentParser() parser.add_argument( '''--input_dir''' , help='''Location of LLaMA weights, which contains tokenizer.model and model folders''' , ) parser.add_argument( '''--model_size''' , choices=['''7B''', '''7Bf''', '''13B''', '''13Bf''', '''30B''', '''65B''', '''70B''', '''70Bf''', '''tokenizer_only'''] , ) parser.add_argument( '''--output_dir''' , help='''Location to write HF model and tokenizer''' , ) parser.add_argument('''--safe_serialization''' , type=__magic_name__ , help='''Whether or not to save using `safetensors`.''' ) lowercase : List[str] = parser.parse_args() if args.model_size != "tokenizer_only": write_model( model_path=args.output_dir , input_base_path=os.path.join(args.input_dir , args.model_size ) , model_size=args.model_size , safe_serialization=args.safe_serialization , ) lowercase : Any = os.path.join(args.input_dir , '''tokenizer.model''' ) write_tokenizer(args.output_dir , __magic_name__ ) if __name__ == "__main__": main()
116
0
'''simple docstring''' import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, TrainingArguments from transformers.hf_argparser import make_choice_type_function, string_to_bool # Since Python 3.10, we can use the builtin `|` operator for Union types # See PEP 604: https://peps.python.org/pep-0604 __lowercase = sys.version_info >= (3, 1_0) def snake_case__ ( _A: Any=None , _A: Optional[int]=None ) -> int: '''simple docstring''' return field(default_factory=lambda: default , metadata=_A ) @dataclass class a__: '''simple docstring''' UpperCAmelCase_ : int UpperCAmelCase_ : float UpperCAmelCase_ : str UpperCAmelCase_ : bool @dataclass class a__: '''simple docstring''' UpperCAmelCase_ : int = 4_2 UpperCAmelCase_ : str = field(default='''toto''' , metadata={'''help''': '''help message'''} ) @dataclass class a__: '''simple docstring''' UpperCAmelCase_ : bool = False UpperCAmelCase_ : bool = True UpperCAmelCase_ : Optional[bool] = None class a__( lowerCAmelCase__ ): '''simple docstring''' UpperCAmelCase_ : str = '''titi''' UpperCAmelCase_ : Union[str, Any] = '''toto''' class a__( lowerCAmelCase__ ): '''simple docstring''' UpperCAmelCase_ : Optional[int] = '''titi''' UpperCAmelCase_ : List[str] = '''toto''' UpperCAmelCase_ : Dict = 4_2 @dataclass class a__: '''simple docstring''' UpperCAmelCase_ : BasicEnum = "toto" def a_ ( self): """simple docstring""" lowerCAmelCase = BasicEnum(self.foo) @dataclass class a__: '''simple docstring''' UpperCAmelCase_ : MixedTypeEnum = "toto" def a_ ( self): """simple docstring""" lowerCAmelCase = MixedTypeEnum(self.foo) @dataclass class a__: '''simple docstring''' UpperCAmelCase_ : Optional[int] = None UpperCAmelCase_ : Optional[float] = field(default=lowerCAmelCase__ , metadata={'''help''': '''help message'''} ) UpperCAmelCase_ : Optional[str] = None UpperCAmelCase_ : Optional[List[str]] = list_field(default=[] ) UpperCAmelCase_ : Optional[List[int]] = list_field(default=[] ) @dataclass class a__: '''simple docstring''' UpperCAmelCase_ : List[int] = list_field(default=[] ) UpperCAmelCase_ : List[int] = list_field(default=[1, 2, 3] ) UpperCAmelCase_ : List[str] = list_field(default=['''Hallo''', '''Bonjour''', '''Hello'''] ) UpperCAmelCase_ : List[float] = list_field(default=[0.1, 0.2, 0.3] ) @dataclass class a__: '''simple docstring''' UpperCAmelCase_ : List[int] = field() UpperCAmelCase_ : str = field() UpperCAmelCase_ : BasicEnum = field() def a_ ( self): """simple docstring""" lowerCAmelCase = BasicEnum(self.required_enum) @dataclass class a__: '''simple docstring''' UpperCAmelCase_ : int UpperCAmelCase_ : "BasicEnum" = field() UpperCAmelCase_ : "Optional[bool]" = None UpperCAmelCase_ : "str" = field(default='''toto''' , metadata={'''help''': '''help message'''} ) UpperCAmelCase_ : "List[str]" = list_field(default=['''Hallo''', '''Bonjour''', '''Hello'''] ) if is_python_no_less_than_3_10: @dataclass class a__: '''simple docstring''' UpperCAmelCase_ : bool = False UpperCAmelCase_ : bool = True UpperCAmelCase_ : bool | None = None @dataclass class a__: '''simple docstring''' UpperCAmelCase_ : int | None = None UpperCAmelCase_ : float | None = field(default=lowerCAmelCase__ , metadata={'''help''': '''help message'''} ) UpperCAmelCase_ : str | None = None UpperCAmelCase_ : list[str] | None = list_field(default=[] ) UpperCAmelCase_ : list[int] | None = list_field(default=[] ) class a__( unittest.TestCase ): '''simple docstring''' def a_ ( self , __lowerCAmelCase , __lowerCAmelCase): """simple docstring""" self.assertEqual(len(a._actions) , len(b._actions)) for x, y in zip(a._actions , b._actions): lowerCAmelCase = {k: v for k, v in vars(__lowerCAmelCase).items() if k != """container"""} lowerCAmelCase = {k: v for k, v in vars(__lowerCAmelCase).items() if k != """container"""} # Choices with mixed type have custom function as "type" # So we need to compare results directly for equality if xx.get("""choices""" , __lowerCAmelCase) and yy.get("""choices""" , __lowerCAmelCase): for expected_choice in yy["choices"] + xx["choices"]: self.assertEqual(xx["""type"""](__lowerCAmelCase) , yy["""type"""](__lowerCAmelCase)) del xx["type"], yy["type"] self.assertEqual(__lowerCAmelCase , __lowerCAmelCase) def a_ ( self): """simple docstring""" lowerCAmelCase = HfArgumentParser(__lowerCAmelCase) lowerCAmelCase = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=__lowerCAmelCase , required=__lowerCAmelCase) expected.add_argument("""--bar""" , type=__lowerCAmelCase , required=__lowerCAmelCase) expected.add_argument("""--baz""" , type=__lowerCAmelCase , required=__lowerCAmelCase) expected.add_argument("""--flag""" , type=__lowerCAmelCase , default=__lowerCAmelCase , const=__lowerCAmelCase , nargs="""?""") self.argparsersEqual(__lowerCAmelCase , __lowerCAmelCase) lowerCAmelCase = ["""--foo""", """1""", """--baz""", """quux""", """--bar""", """0.5"""] ((lowerCAmelCase) , ) = parser.parse_args_into_dataclasses(__lowerCAmelCase , look_for_args_file=__lowerCAmelCase) self.assertFalse(example.flag) def a_ ( self): """simple docstring""" lowerCAmelCase = HfArgumentParser(__lowerCAmelCase) lowerCAmelCase = argparse.ArgumentParser() expected.add_argument("""--foo""" , default=42 , type=__lowerCAmelCase) expected.add_argument("""--baz""" , default="""toto""" , type=__lowerCAmelCase , help="""help message""") self.argparsersEqual(__lowerCAmelCase , __lowerCAmelCase) def a_ ( self): """simple docstring""" lowerCAmelCase = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=__lowerCAmelCase , default=__lowerCAmelCase , const=__lowerCAmelCase , nargs="""?""") expected.add_argument("""--baz""" , type=__lowerCAmelCase , default=__lowerCAmelCase , const=__lowerCAmelCase , nargs="""?""") # A boolean no_* argument always has to come after its "default: True" regular counter-part # and its default must be set to False expected.add_argument("""--no_baz""" , action="""store_false""" , default=__lowerCAmelCase , dest="""baz""") expected.add_argument("""--opt""" , type=__lowerCAmelCase , default=__lowerCAmelCase) lowerCAmelCase = [WithDefaultBoolExample] if is_python_no_less_than_3_10: dataclass_types.append(__lowerCAmelCase) for dataclass_type in dataclass_types: lowerCAmelCase = HfArgumentParser(__lowerCAmelCase) self.argparsersEqual(__lowerCAmelCase , __lowerCAmelCase) lowerCAmelCase = parser.parse_args([]) self.assertEqual(__lowerCAmelCase , Namespace(foo=__lowerCAmelCase , baz=__lowerCAmelCase , opt=__lowerCAmelCase)) lowerCAmelCase = parser.parse_args(["""--foo""", """--no_baz"""]) self.assertEqual(__lowerCAmelCase , Namespace(foo=__lowerCAmelCase , baz=__lowerCAmelCase , opt=__lowerCAmelCase)) lowerCAmelCase = parser.parse_args(["""--foo""", """--baz"""]) self.assertEqual(__lowerCAmelCase , Namespace(foo=__lowerCAmelCase , baz=__lowerCAmelCase , opt=__lowerCAmelCase)) lowerCAmelCase = parser.parse_args(["""--foo""", """True""", """--baz""", """True""", """--opt""", """True"""]) self.assertEqual(__lowerCAmelCase , Namespace(foo=__lowerCAmelCase , baz=__lowerCAmelCase , opt=__lowerCAmelCase)) lowerCAmelCase = parser.parse_args(["""--foo""", """False""", """--baz""", """False""", """--opt""", """False"""]) self.assertEqual(__lowerCAmelCase , Namespace(foo=__lowerCAmelCase , baz=__lowerCAmelCase , opt=__lowerCAmelCase)) def a_ ( self): """simple docstring""" lowerCAmelCase = HfArgumentParser(__lowerCAmelCase) lowerCAmelCase = argparse.ArgumentParser() expected.add_argument( """--foo""" , default="""toto""" , choices=["""titi""", """toto""", 42] , type=make_choice_type_function(["""titi""", """toto""", 42]) , ) self.argparsersEqual(__lowerCAmelCase , __lowerCAmelCase) lowerCAmelCase = parser.parse_args([]) self.assertEqual(args.foo , """toto""") lowerCAmelCase = parser.parse_args_into_dataclasses([])[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.toto) lowerCAmelCase = parser.parse_args(["""--foo""", """titi"""]) self.assertEqual(args.foo , """titi""") lowerCAmelCase = parser.parse_args_into_dataclasses(["""--foo""", """titi"""])[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.titi) lowerCAmelCase = parser.parse_args(["""--foo""", """42"""]) self.assertEqual(args.foo , 42) lowerCAmelCase = parser.parse_args_into_dataclasses(["""--foo""", """42"""])[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo) def a_ ( self): """simple docstring""" @dataclass class a__: '''simple docstring''' UpperCAmelCase_ : Literal["titi", "toto", 4_2] = "toto" lowerCAmelCase = HfArgumentParser(__lowerCAmelCase) lowerCAmelCase = argparse.ArgumentParser() expected.add_argument( """--foo""" , default="""toto""" , choices=("""titi""", """toto""", 42) , type=make_choice_type_function(["""titi""", """toto""", 42]) , ) self.argparsersEqual(__lowerCAmelCase , __lowerCAmelCase) lowerCAmelCase = parser.parse_args([]) self.assertEqual(args.foo , """toto""") lowerCAmelCase = parser.parse_args(["""--foo""", """titi"""]) self.assertEqual(args.foo , """titi""") lowerCAmelCase = parser.parse_args(["""--foo""", """42"""]) self.assertEqual(args.foo , 42) def a_ ( self): """simple docstring""" lowerCAmelCase = HfArgumentParser(__lowerCAmelCase) lowerCAmelCase = argparse.ArgumentParser() expected.add_argument("""--foo_int""" , nargs="""+""" , default=[] , type=__lowerCAmelCase) expected.add_argument("""--bar_int""" , nargs="""+""" , default=[1, 2, 3] , type=__lowerCAmelCase) expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=__lowerCAmelCase) expected.add_argument("""--foo_float""" , nargs="""+""" , default=[0.1, 0.2, 0.3] , type=__lowerCAmelCase) self.argparsersEqual(__lowerCAmelCase , __lowerCAmelCase) lowerCAmelCase = parser.parse_args([]) self.assertEqual( __lowerCAmelCase , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=["""Hallo""", """Bonjour""", """Hello"""] , foo_float=[0.1, 0.2, 0.3]) , ) lowerCAmelCase = parser.parse_args("""--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7""".split()) self.assertEqual(__lowerCAmelCase , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=["""a""", """b""", """c"""] , foo_float=[0.1, 0.7])) def a_ ( self): """simple docstring""" lowerCAmelCase = argparse.ArgumentParser() expected.add_argument("""--foo""" , default=__lowerCAmelCase , type=__lowerCAmelCase) expected.add_argument("""--bar""" , default=__lowerCAmelCase , type=__lowerCAmelCase , help="""help message""") expected.add_argument("""--baz""" , default=__lowerCAmelCase , type=__lowerCAmelCase) expected.add_argument("""--ces""" , nargs="""+""" , default=[] , type=__lowerCAmelCase) expected.add_argument("""--des""" , nargs="""+""" , default=[] , type=__lowerCAmelCase) lowerCAmelCase = [OptionalExample] if is_python_no_less_than_3_10: dataclass_types.append(__lowerCAmelCase) for dataclass_type in dataclass_types: lowerCAmelCase = HfArgumentParser(__lowerCAmelCase) self.argparsersEqual(__lowerCAmelCase , __lowerCAmelCase) lowerCAmelCase = parser.parse_args([]) self.assertEqual(__lowerCAmelCase , Namespace(foo=__lowerCAmelCase , bar=__lowerCAmelCase , baz=__lowerCAmelCase , ces=[] , des=[])) lowerCAmelCase = parser.parse_args("""--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3""".split()) self.assertEqual(__lowerCAmelCase , Namespace(foo=12 , bar=3.14 , baz="""42""" , ces=["""a""", """b""", """c"""] , des=[1, 2, 3])) def a_ ( self): """simple docstring""" lowerCAmelCase = HfArgumentParser(__lowerCAmelCase) lowerCAmelCase = argparse.ArgumentParser() expected.add_argument("""--required_list""" , nargs="""+""" , type=__lowerCAmelCase , required=__lowerCAmelCase) expected.add_argument("""--required_str""" , type=__lowerCAmelCase , required=__lowerCAmelCase) expected.add_argument( """--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""]) , choices=["""titi""", """toto"""] , required=__lowerCAmelCase , ) self.argparsersEqual(__lowerCAmelCase , __lowerCAmelCase) def a_ ( self): """simple docstring""" lowerCAmelCase = HfArgumentParser(__lowerCAmelCase) lowerCAmelCase = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=__lowerCAmelCase , required=__lowerCAmelCase) expected.add_argument( """--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""]) , choices=["""titi""", """toto"""] , required=__lowerCAmelCase , ) expected.add_argument("""--opt""" , type=__lowerCAmelCase , default=__lowerCAmelCase) expected.add_argument("""--baz""" , default="""toto""" , type=__lowerCAmelCase , help="""help message""") expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=__lowerCAmelCase) self.argparsersEqual(__lowerCAmelCase , __lowerCAmelCase) def a_ ( self): """simple docstring""" lowerCAmelCase = HfArgumentParser(__lowerCAmelCase) lowerCAmelCase = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } lowerCAmelCase = parser.parse_dict(__lowerCAmelCase)[0] lowerCAmelCase = BasicExample(**__lowerCAmelCase) self.assertEqual(__lowerCAmelCase , __lowerCAmelCase) def a_ ( self): """simple docstring""" lowerCAmelCase = HfArgumentParser(__lowerCAmelCase) lowerCAmelCase = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, """extra""": 42, } self.assertRaises(__lowerCAmelCase , parser.parse_dict , __lowerCAmelCase , allow_extra_keys=__lowerCAmelCase) def a_ ( self): """simple docstring""" lowerCAmelCase = HfArgumentParser(__lowerCAmelCase) lowerCAmelCase = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase = os.path.join(__lowerCAmelCase , """temp_json""") os.mkdir(__lowerCAmelCase) with open(temp_local_path + """.json""" , """w+""") as f: json.dump(__lowerCAmelCase , __lowerCAmelCase) lowerCAmelCase = parser.parse_yaml_file(Path(temp_local_path + """.json"""))[0] lowerCAmelCase = BasicExample(**__lowerCAmelCase) self.assertEqual(__lowerCAmelCase , __lowerCAmelCase) def a_ ( self): """simple docstring""" lowerCAmelCase = HfArgumentParser(__lowerCAmelCase) lowerCAmelCase = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase = os.path.join(__lowerCAmelCase , """temp_yaml""") os.mkdir(__lowerCAmelCase) with open(temp_local_path + """.yaml""" , """w+""") as f: yaml.dump(__lowerCAmelCase , __lowerCAmelCase) lowerCAmelCase = parser.parse_yaml_file(Path(temp_local_path + """.yaml"""))[0] lowerCAmelCase = BasicExample(**__lowerCAmelCase) self.assertEqual(__lowerCAmelCase , __lowerCAmelCase) def a_ ( self): """simple docstring""" lowerCAmelCase = HfArgumentParser(__lowerCAmelCase) self.assertIsNotNone(__lowerCAmelCase)
272
'''simple docstring''' import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class a__( unittest.TestCase ): '''simple docstring''' @property def a_ ( self): """simple docstring""" torch.manual_seed(0) lowerCAmelCase = 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): """simple docstring""" lowerCAmelCase = self.dummy_uncond_unet lowerCAmelCase = PNDMScheduler() lowerCAmelCase = PNDMPipeline(unet=__lowerCAmelCase , scheduler=__lowerCAmelCase) pndm.to(__lowerCAmelCase) pndm.set_progress_bar_config(disable=__lowerCAmelCase) lowerCAmelCase = torch.manual_seed(0) lowerCAmelCase = pndm(generator=__lowerCAmelCase , num_inference_steps=20 , output_type="""numpy""").images lowerCAmelCase = torch.manual_seed(0) lowerCAmelCase = pndm(generator=__lowerCAmelCase , num_inference_steps=20 , output_type="""numpy""" , return_dict=__lowerCAmelCase)[0] lowerCAmelCase = image[0, -3:, -3:, -1] lowerCAmelCase = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) lowerCAmelCase = np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1E-2 @slow @require_torch class a__( unittest.TestCase ): '''simple docstring''' def a_ ( self): """simple docstring""" lowerCAmelCase = """google/ddpm-cifar10-32""" lowerCAmelCase = UNetaDModel.from_pretrained(__lowerCAmelCase) lowerCAmelCase = PNDMScheduler() lowerCAmelCase = PNDMPipeline(unet=__lowerCAmelCase , scheduler=__lowerCAmelCase) pndm.to(__lowerCAmelCase) pndm.set_progress_bar_config(disable=__lowerCAmelCase) lowerCAmelCase = torch.manual_seed(0) lowerCAmelCase = pndm(generator=__lowerCAmelCase , output_type="""numpy""").images lowerCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) lowerCAmelCase = np.array([0.1564, 0.14645, 0.1406, 0.14715, 0.12425, 0.14045, 0.13115, 0.12175, 0.125]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
272
1
"""simple docstring""" from __future__ import annotations def lowerCAmelCase__ ( UpperCamelCase__ ): '''simple docstring''' if not nums: return 0 _a : List[str] = nums[0] _a : Any = 0 for num in nums[1:]: _a , _a : Tuple = ( max_excluding + num, max(UpperCamelCase__ , UpperCamelCase__ ), ) return max(UpperCamelCase__ , UpperCamelCase__ ) if __name__ == "__main__": import doctest doctest.testmod()
324
"""simple docstring""" import os from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE, hf_cache_home _snake_case = HUGGINGFACE_HUB_CACHE _snake_case = 'config.json' _snake_case = 'diffusion_pytorch_model.bin' _snake_case = 'diffusion_flax_model.msgpack' _snake_case = 'model.onnx' _snake_case = 'diffusion_pytorch_model.safetensors' _snake_case = 'weights.pb' _snake_case = 'https://huggingface.co' _snake_case = default_cache_path _snake_case = 'diffusers_modules' _snake_case = os.getenv('HF_MODULES_CACHE', os.path.join(hf_cache_home, 'modules')) _snake_case = ['fp16', 'non-ema'] _snake_case = '.self_attn'
324
1
import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging UpperCAmelCase : List[Any] = logging.get_logger(__name__) UpperCAmelCase : List[str] = """▁""" UpperCAmelCase : Dict = { """vocab_file""": """vocab.json""", """spm_file""": """sentencepiece.bpe.model""", """tokenizer_config_file""": """tokenizer_config.json""", } UpperCAmelCase : List[Any] = { """vocab_file""": { """facebook/m2m100_418M""": """https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json""", """facebook/m2m100_1.2B""": """https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json""", }, """spm_file""": { """facebook/m2m100_418M""": """https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model""", """facebook/m2m100_1.2B""": """https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model""", }, """tokenizer_config_file""": { """facebook/m2m100_418M""": """https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json""", """facebook/m2m100_1.2B""": """https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json""", }, } UpperCAmelCase : Any = { """facebook/m2m100_418M""": 1024, } # fmt: off UpperCAmelCase : Optional[int] = { """m2m100""": ["""af""", """am""", """ar""", """ast""", """az""", """ba""", """be""", """bg""", """bn""", """br""", """bs""", """ca""", """ceb""", """cs""", """cy""", """da""", """de""", """el""", """en""", """es""", """et""", """fa""", """ff""", """fi""", """fr""", """fy""", """ga""", """gd""", """gl""", """gu""", """ha""", """he""", """hi""", """hr""", """ht""", """hu""", """hy""", """id""", """ig""", """ilo""", """is""", """it""", """ja""", """jv""", """ka""", """kk""", """km""", """kn""", """ko""", """lb""", """lg""", """ln""", """lo""", """lt""", """lv""", """mg""", """mk""", """ml""", """mn""", """mr""", """ms""", """my""", """ne""", """nl""", """no""", """ns""", """oc""", """or""", """pa""", """pl""", """ps""", """pt""", """ro""", """ru""", """sd""", """si""", """sk""", """sl""", """so""", """sq""", """sr""", """ss""", """su""", """sv""", """sw""", """ta""", """th""", """tl""", """tn""", """tr""", """uk""", """ur""", """uz""", """vi""", """wo""", """xh""", """yi""", """yo""", """zh""", """zu"""], """wmt21""": ["""en""", """ha""", """is""", """ja""", """cs""", """ru""", """zh""", """de"""] } class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Union[str, Any] = VOCAB_FILES_NAMES _lowercase : Optional[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowercase : int = PRETRAINED_VOCAB_FILES_MAP _lowercase : Dict = ["""input_ids""", """attention_mask"""] _lowercase : List[int] = [] _lowercase : List[int] = [] def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=None , lowerCAmelCase__=None , lowerCAmelCase__="<s>" , lowerCAmelCase__="</s>" , lowerCAmelCase__="</s>" , lowerCAmelCase__="<pad>" , lowerCAmelCase__="<unk>" , lowerCAmelCase__="m2m100" , lowerCAmelCase__ = None , lowerCAmelCase__=8 , **lowerCAmelCase__ , ) -> None: '''simple docstring''' a__ : Union[str, Any] ={} if sp_model_kwargs is None else sp_model_kwargs a__ : List[str] =language_codes a__ : str =FAIRSEQ_LANGUAGE_CODES[language_codes] a__ : Union[str, Any] ={lang_code: F'''__{lang_code}__''' for lang_code in fairseq_language_code} a__ : Union[str, Any] =kwargs.get("additional_special_tokens" , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(lowerCAmelCase__ ) for lang_code in fairseq_language_code if self.get_lang_token(lowerCAmelCase__ ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=lowerCAmelCase__ , tgt_lang=lowerCAmelCase__ , bos_token=lowerCAmelCase__ , eos_token=lowerCAmelCase__ , sep_token=lowerCAmelCase__ , unk_token=lowerCAmelCase__ , pad_token=lowerCAmelCase__ , language_codes=lowerCAmelCase__ , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=lowerCAmelCase__ , **lowerCAmelCase__ , ) a__ : Dict =vocab_file a__ : Optional[int] =load_json(lowerCAmelCase__ ) a__ : Optional[Any] ={v: k for k, v in self.encoder.items()} a__ : Union[str, Any] =spm_file a__ : Optional[Any] =load_spm(lowerCAmelCase__ , self.sp_model_kwargs ) a__ : int =len(self.encoder ) a__ : Union[str, Any] ={ self.get_lang_token(lowerCAmelCase__ ): self.encoder_size + i for i, lang_code in enumerate(lowerCAmelCase__ ) } a__ : int ={lang_code: self.encoder_size + i for i, lang_code in enumerate(lowerCAmelCase__ )} a__ : Optional[Any] ={v: k for k, v in self.lang_token_to_id.items()} a__ : Dict =src_lang if src_lang is not None else "en" a__ : List[Any] =tgt_lang a__ : Dict =self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) a__ : Optional[Any] =num_madeup_words @property def _lowercase ( self ) -> int: '''simple docstring''' return len(self.encoder ) + len(self.lang_token_to_id ) @property def _lowercase ( self ) -> str: '''simple docstring''' return self._src_lang @src_lang.setter def _lowercase ( self , lowerCAmelCase__ ) -> None: '''simple docstring''' a__ : Optional[Any] =new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _lowercase ( self , lowerCAmelCase__ ) -> List[str]: '''simple docstring''' return self.sp_model.encode(lowerCAmelCase__ , out_type=lowerCAmelCase__ ) def _lowercase ( self , lowerCAmelCase__ ) -> Tuple: '''simple docstring''' if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(lowerCAmelCase__ , self.encoder[self.unk_token] ) def _lowercase ( self , lowerCAmelCase__ ) -> str: '''simple docstring''' if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(lowerCAmelCase__ , self.unk_token ) def _lowercase ( self , lowerCAmelCase__ ) -> Any: '''simple docstring''' a__ : int =[] a__ : str ="" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(lowerCAmelCase__ ) + token a__ : Optional[int] =[] else: current_sub_tokens.append(lowerCAmelCase__ ) out_string += self.sp_model.decode(lowerCAmelCase__ ) return out_string.strip() def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None , lowerCAmelCase__ = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=lowerCAmelCase__ , token_ids_a=lowerCAmelCase__ , already_has_special_tokens=lowerCAmelCase__ ) a__ : List[str] =[1] * len(self.prefix_tokens ) a__ : Any =[1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(lowerCAmelCase__ )) + suffix_ones return prefix_ones + ([0] * len(lowerCAmelCase__ )) + ([0] * len(lowerCAmelCase__ )) + suffix_ones def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> List[int]: '''simple docstring''' if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _lowercase ( self ) -> Dict: '''simple docstring''' a__ : Any ={self.convert_ids_to_tokens(lowerCAmelCase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> Dict: '''simple docstring''' a__ : Optional[int] =self.__dict__.copy() a__ : Dict =None return state def __setstate__( self , lowerCAmelCase__ ) -> None: '''simple docstring''' a__ : Tuple =d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): a__ : List[Any] ={} a__ : List[str] =load_spm(self.spm_file , self.sp_model_kwargs ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = None ) -> Tuple[str]: '''simple docstring''' a__ : Any =Path(lowerCAmelCase__ ) if not save_dir.is_dir(): raise OSError(F'''{save_directory} should be a directory''' ) a__ : str =save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"] ) a__ : List[str] =save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"] ) save_json(self.encoder , lowerCAmelCase__ ) if os.path.abspath(self.spm_file ) != os.path.abspath(lowerCAmelCase__ ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , lowerCAmelCase__ ) elif not os.path.isfile(self.spm_file ): with open(lowerCAmelCase__ , "wb" ) as fi: a__ : Optional[Any] =self.sp_model.serialized_model_proto() fi.write(lowerCAmelCase__ ) return (str(lowerCAmelCase__ ), str(lowerCAmelCase__ )) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ = "en" , lowerCAmelCase__ = None , lowerCAmelCase__ = "ro" , **lowerCAmelCase__ , ) -> BatchEncoding: '''simple docstring''' a__ : List[Any] =src_lang a__ : Any =tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(lowerCAmelCase__ , lowerCAmelCase__ , **lowerCAmelCase__ ) def _lowercase ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , **lowerCAmelCase__ ) -> str: '''simple docstring''' if src_lang is None or tgt_lang is None: raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" ) a__ : int =src_lang a__ : Any =self(lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ , **lowerCAmelCase__ ) a__ : Union[str, Any] =self.get_lang_id(lowerCAmelCase__ ) a__ : Tuple =tgt_lang_id return inputs def _lowercase ( self ) -> Tuple: '''simple docstring''' self.set_src_lang_special_tokens(self.src_lang ) def _lowercase ( self ) -> List[Any]: '''simple docstring''' self.set_tgt_lang_special_tokens(self.tgt_lang ) def _lowercase ( self , lowerCAmelCase__ ) -> None: '''simple docstring''' a__ : Union[str, Any] =self.get_lang_token(lowerCAmelCase__ ) a__ : str =self.lang_token_to_id[lang_token] a__ : Optional[int] =[self.cur_lang_id] a__ : List[Any] =[self.eos_token_id] def _lowercase ( self , lowerCAmelCase__ ) -> None: '''simple docstring''' a__ : int =self.get_lang_token(lowerCAmelCase__ ) a__ : Optional[Any] =self.lang_token_to_id[lang_token] a__ : int =[self.cur_lang_id] a__ : Optional[Any] =[self.eos_token_id] def _lowercase ( self , lowerCAmelCase__ ) -> str: '''simple docstring''' return self.lang_code_to_token[lang] def _lowercase ( self , lowerCAmelCase__ ) -> int: '''simple docstring''' a__ : Optional[int] =self.get_lang_token(lowerCAmelCase__ ) return self.lang_token_to_id[lang_token] def _A ( SCREAMING_SNAKE_CASE : str , SCREAMING_SNAKE_CASE : Dict[str, Any] ): """simple docstring""" a__ : int =sentencepiece.SentencePieceProcessor(**SCREAMING_SNAKE_CASE ) spm.Load(str(SCREAMING_SNAKE_CASE ) ) return spm def _A ( SCREAMING_SNAKE_CASE : str ): """simple docstring""" with open(SCREAMING_SNAKE_CASE , "r" ) as f: return json.load(SCREAMING_SNAKE_CASE ) def _A ( SCREAMING_SNAKE_CASE : int , SCREAMING_SNAKE_CASE : str ): """simple docstring""" with open(SCREAMING_SNAKE_CASE , "w" ) as f: json.dump(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , indent=2 )
95
from __future__ import annotations import math import numpy as np from numpy.linalg import norm def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase, _UpperCAmelCase ) -> float: '''simple docstring''' return math.sqrt(sum(pow(a - b, 2 ) for a, b in zip(_UpperCAmelCase, _UpperCAmelCase ) ) ) def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase, _UpperCAmelCase ) -> list[list[list[float] | float]]: '''simple docstring''' if dataset.ndim != value_array.ndim: lowerCAmelCase : List[Any] = ( 'Wrong input data\'s dimensions... ' f"dataset : {dataset.ndim}, value_array : {value_array.ndim}" ) raise ValueError(_UpperCAmelCase ) try: if dataset.shape[1] != value_array.shape[1]: lowerCAmelCase : Dict = ( 'Wrong input data\'s shape... ' f"dataset : {dataset.shape[1]}, value_array : {value_array.shape[1]}" ) raise ValueError(_UpperCAmelCase ) except IndexError: if dataset.ndim != value_array.ndim: raise TypeError('Wrong shape' ) if dataset.dtype != value_array.dtype: lowerCAmelCase : Any = ( 'Input data have different datatype... ' f"dataset : {dataset.dtype}, value_array : {value_array.dtype}" ) raise TypeError(_UpperCAmelCase ) lowerCAmelCase : int = [] for value in value_array: lowerCAmelCase : Tuple = euclidean(_UpperCAmelCase, dataset[0] ) lowerCAmelCase : Tuple = dataset[0].tolist() for dataset_value in dataset[1:]: lowerCAmelCase : Dict = euclidean(_UpperCAmelCase, _UpperCAmelCase ) if dist > temp_dist: lowerCAmelCase : Tuple = temp_dist lowerCAmelCase : Tuple = dataset_value.tolist() answer.append([vector, dist] ) return answer def SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase, _UpperCAmelCase ) -> float: '''simple docstring''' return np.dot(_UpperCAmelCase, _UpperCAmelCase ) / (norm(_UpperCAmelCase ) * norm(_UpperCAmelCase )) if __name__ == "__main__": import doctest doctest.testmod()
138
0
"""simple docstring""" from __future__ import annotations from collections.abc import Callable def lowerCamelCase_ ( lowerCAmelCase: Callable[[int | float], int | float] , lowerCAmelCase: int | float , lowerCAmelCase: int | float , lowerCAmelCase: int = 1_00 , )-> float: _snake_case : Tuple = x_start _snake_case : Optional[int] = fnc(lowerCAmelCase ) _snake_case : List[str] = 0.0 for _ in range(lowerCAmelCase ): # Approximates small segments of curve as linear and solve # for trapezoidal area _snake_case : Any = (x_end - x_start) / steps + xa _snake_case : Union[str, Any] = fnc(lowerCAmelCase ) area += abs(fxa + fxa ) * (xa - xa) / 2 # Increment step _snake_case : Optional[Any] = xa _snake_case : Tuple = fxa return area if __name__ == "__main__": def lowerCamelCase_ ( lowerCAmelCase: List[str] )-> List[Any]: return x**3 + x**2 print("""f(x) = x^3 + x^2""") print("""The area between the curve, x = -5, x = 5 and the x axis is:""") lowerCAmelCase_ = 10 while i <= 10_0000: print(F"""with {i} steps: {trapezoidal_area(f, -5, 5, i)}""") i *= 10
351
from ..utils import DummyObject, requires_backends class _lowerCAmelCase ( metaclass=UpperCAmelCase_ ): '''simple docstring''' a_ : Optional[int] =["""speech"""] def __init__( self : Optional[int] , *UpperCamelCase : int , **UpperCamelCase : str ): '''simple docstring''' requires_backends(self , ['speech'] ) class _lowerCAmelCase ( metaclass=UpperCAmelCase_ ): '''simple docstring''' a_ : Optional[Any] =["""speech"""] def __init__( self : Any , *UpperCamelCase : Any , **UpperCamelCase : List[Any] ): '''simple docstring''' requires_backends(self , ['speech'] )
260
0
'''simple docstring''' import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class a : def __init__( self : str , lowercase_ : Any , lowercase_ : Dict=2 , lowercase_ : Optional[Any]=True , lowercase_ : Optional[int]=False , lowercase_ : List[Any]=10 , lowercase_ : Dict=3 , lowercase_ : str=32 * 4 , lowercase_ : Dict=32 * 6 , lowercase_ : Union[str, Any]=4 , lowercase_ : str=32 , ): snake_case_ = parent snake_case_ = batch_size snake_case_ = is_training snake_case_ = use_auxiliary_loss snake_case_ = num_queries snake_case_ = num_channels snake_case_ = min_size snake_case_ = max_size snake_case_ = num_labels snake_case_ = mask_feature_size def A_ ( self : Optional[Any] ): snake_case_ = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( lowercase_ ) snake_case_ = torch.ones([self.batch_size, self.min_size, self.max_size] , device=lowercase_ ) snake_case_ = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=lowercase_ ) > 0.5 ).float() snake_case_ = (torch.rand((self.batch_size, self.num_labels) , device=lowercase_ ) > 0.5).long() snake_case_ = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def A_ ( self : Any ): return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=128 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def A_ ( self : List[Any] ): snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ = self.prepare_config_and_inputs() snake_case_ = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask} return config, inputs_dict def A_ ( self : Any , lowercase_ : int , lowercase_ : Tuple ): snake_case_ = output.encoder_hidden_states snake_case_ = output.pixel_decoder_hidden_states snake_case_ = output.transformer_decoder_hidden_states self.parent.assertTrue(len(lowercase_ ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(lowercase_ ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(lowercase_ ) , config.decoder_config.decoder_layers ) def A_ ( self : Any , lowercase_ : Union[str, Any] , lowercase_ : Tuple , lowercase_ : Any , lowercase_ : List[str]=False ): with torch.no_grad(): snake_case_ = MaskFormerModel(config=lowercase_ ) model.to(lowercase_ ) model.eval() snake_case_ = model(pixel_values=lowercase_ , pixel_mask=lowercase_ ) snake_case_ = model(lowercase_ , output_hidden_states=lowercase_ ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(lowercase_ , lowercase_ ) def A_ ( self : Optional[int] , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] , lowercase_ : str , lowercase_ : Tuple , lowercase_ : Union[str, Any] ): snake_case_ = MaskFormerForInstanceSegmentation(config=lowercase_ ) model.to(lowercase_ ) model.eval() def comm_check_on_output(lowercase_ : Union[str, Any] ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): snake_case_ = model(pixel_values=lowercase_ , pixel_mask=lowercase_ ) snake_case_ = model(lowercase_ ) comm_check_on_output(lowercase_ ) snake_case_ = model( pixel_values=lowercase_ , pixel_mask=lowercase_ , mask_labels=lowercase_ , class_labels=lowercase_ ) comm_check_on_output(lowercase_ ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class a ( _lowerCamelCase , _lowerCamelCase , unittest.TestCase ): snake_case_ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () snake_case_ = ( {"feature-extraction": MaskFormerModel, "image-segmentation": MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def A_ ( self : Union[str, Any] ): snake_case_ = MaskFormerModelTester(self ) snake_case_ = ConfigTester(self , config_class=lowercase_ , has_text_modality=lowercase_ ) def A_ ( self : Any ): self.config_tester.run_common_tests() def A_ ( self : Dict ): snake_case_ ,snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(lowercase_ , **lowercase_ , output_hidden_states=lowercase_ ) def A_ ( self : Tuple ): snake_case_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*lowercase_ ) @unittest.skip(reason='''MaskFormer does not use inputs_embeds''' ) def A_ ( self : List[Any] ): pass @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' ) def A_ ( self : str ): pass @unittest.skip(reason='''MaskFormer is not a generative model''' ) def A_ ( self : Tuple ): pass @unittest.skip(reason='''MaskFormer does not use token embeddings''' ) def A_ ( self : Optional[Any] ): pass @require_torch_multi_gpu @unittest.skip( reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def A_ ( self : List[str] ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def A_ ( self : Union[str, Any] ): pass def A_ ( self : str ): snake_case_ ,snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(lowercase_ ) snake_case_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case_ = [*signature.parameters.keys()] snake_case_ = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , lowercase_ ) @slow def A_ ( self : List[str] ): for model_name in ["facebook/maskformer-swin-small-coco"]: snake_case_ = MaskFormerModel.from_pretrained(lowercase_ ) self.assertIsNotNone(lowercase_ ) def A_ ( self : Optional[int] ): snake_case_ = (self.model_tester.min_size,) * 2 snake_case_ = { '''pixel_values''': torch.randn((2, 3, *size) , device=lowercase_ ), '''mask_labels''': torch.randn((2, 10, *size) , device=lowercase_ ), '''class_labels''': torch.zeros(2 , 10 , device=lowercase_ ).long(), } snake_case_ = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(lowercase_ ) snake_case_ = model(**lowercase_ ) self.assertTrue(outputs.loss is not None ) def A_ ( self : List[str] ): snake_case_ ,snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(lowercase_ , **lowercase_ , output_hidden_states=lowercase_ ) def A_ ( self : str ): snake_case_ ,snake_case_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case_ = model_class(lowercase_ ).to(lowercase_ ) snake_case_ = model(**lowercase_ , output_attentions=lowercase_ ) self.assertTrue(outputs.attentions is not None ) def A_ ( self : Dict ): if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss snake_case_ = self.all_model_classes[1] snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ = self.model_tester.prepare_config_and_inputs() snake_case_ = model_class(lowercase_ ) model.to(lowercase_ ) model.train() snake_case_ = model(lowercase_ , mask_labels=lowercase_ , class_labels=lowercase_ ).loss loss.backward() def A_ ( self : List[str] ): # only MaskFormerForInstanceSegmentation has the loss snake_case_ = self.all_model_classes[1] snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ ,snake_case_ = self.model_tester.prepare_config_and_inputs() snake_case_ = True snake_case_ = True snake_case_ = model_class(lowercase_ ) model.to(lowercase_ ) model.train() snake_case_ = model(lowercase_ , mask_labels=lowercase_ , class_labels=lowercase_ ) snake_case_ = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() snake_case_ = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't snake_case_ = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() snake_case_ = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=lowercase_ ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) a : List[Any] = 1E-4 def __magic_name__ ( ) -> Optional[int]: '''simple docstring''' snake_case_ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @slow class a ( unittest.TestCase ): @cached_property def A_ ( self : Tuple ): return ( MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' ) if is_vision_available() else None ) def A_ ( self : Optional[int] ): snake_case_ = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(lowercase_ ) snake_case_ = self.default_image_processor snake_case_ = prepare_img() snake_case_ = image_processor(lowercase_ , return_tensors='''pt''' ).to(lowercase_ ) snake_case_ = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(lowercase_ , (1, 3, 800, 1088) ) with torch.no_grad(): snake_case_ = model(**lowercase_ ) snake_case_ = torch.tensor( [[-0.0482, 0.9228, 0.4951], [-0.2547, 0.8017, 0.8527], [-0.0069, 0.3385, -0.0089]] ).to(lowercase_ ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , lowercase_ , atol=lowercase_ ) ) snake_case_ = torch.tensor( [[-0.8422, -0.8434, -0.9718], [-1.0144, -0.5565, -0.4195], [-1.0038, -0.4484, -0.1961]] ).to(lowercase_ ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , lowercase_ , atol=lowercase_ ) ) snake_case_ = torch.tensor( [[0.2852, -0.0159, 0.9735], [0.6254, 0.1858, 0.8529], [-0.0680, -0.4116, 1.8413]] ).to(lowercase_ ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , lowercase_ , atol=lowercase_ ) ) def A_ ( self : List[str] ): snake_case_ = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(lowercase_ ) .eval() ) snake_case_ = self.default_image_processor snake_case_ = prepare_img() snake_case_ = image_processor(lowercase_ , return_tensors='''pt''' ).to(lowercase_ ) snake_case_ = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(lowercase_ , (1, 3, 800, 1088) ) with torch.no_grad(): snake_case_ = model(**lowercase_ ) # masks_queries_logits snake_case_ = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) snake_case_ = [ [-1.373_7124, -1.772_4937, -1.936_4233], [-1.597_7281, -1.986_7939, -2.152_3695], [-1.579_5398, -1.926_9832, -2.09_3942], ] snake_case_ = torch.tensor(lowercase_ ).to(lowercase_ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , lowercase_ , atol=lowercase_ ) ) # class_queries_logits snake_case_ = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) snake_case_ = torch.tensor( [ [1.6_512e00, -5.2_572e00, -3.3_519e00], [3.6_169e-02, -5.9_025e00, -2.9_313e00], [1.0_766e-04, -7.7_630e00, -5.1_263e00], ] ).to(lowercase_ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , lowercase_ , atol=lowercase_ ) ) def A_ ( self : Any ): snake_case_ = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' ) .to(lowercase_ ) .eval() ) snake_case_ = self.default_image_processor snake_case_ = prepare_img() snake_case_ = image_processor(lowercase_ , return_tensors='''pt''' ).to(lowercase_ ) snake_case_ = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0 ) # check size self.assertEqual(lowercase_ , (1, 3, 800, 1088) ) with torch.no_grad(): snake_case_ = model(**lowercase_ ) # masks_queries_logits snake_case_ = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) snake_case_ = [[-0.9046, -2.6366, -4.6062], [-3.4179, -5.7890, -8.8057], [-4.9179, -7.6560, -10.7711]] snake_case_ = torch.tensor(lowercase_ ).to(lowercase_ ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , lowercase_ , atol=lowercase_ ) ) # class_queries_logits snake_case_ = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) snake_case_ = torch.tensor( [[4.7188, -3.2585, -2.8857], [6.6871, -2.9181, -1.2487], [7.2449, -2.2764, -2.1874]] ).to(lowercase_ ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , lowercase_ , atol=lowercase_ ) ) def A_ ( self : Dict ): snake_case_ = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(lowercase_ ) .eval() ) snake_case_ = self.default_image_processor snake_case_ = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors='''pt''' , ) snake_case_ = inputs['''pixel_values'''].to(lowercase_ ) snake_case_ = [el.to(lowercase_ ) for el in inputs['''mask_labels''']] snake_case_ = [el.to(lowercase_ ) for el in inputs['''class_labels''']] with torch.no_grad(): snake_case_ = model(**lowercase_ ) self.assertTrue(outputs.loss is not None )
56
"""simple docstring""" from __future__ import annotations _a : List[str] = 10 def SCREAMING_SNAKE_CASE ( _lowerCamelCase : list[int] ) -> list[int]: _lowerCAmelCase : Optional[int] = 1 _lowerCAmelCase : Union[str, Any] = max(_lowerCamelCase ) while placement <= max_digit: # declare and initialize empty buckets _lowerCAmelCase : list[list] = [[] for _ in range(_lowerCamelCase )] # split list_of_ints between the buckets for i in list_of_ints: _lowerCAmelCase : Tuple = int((i / placement) % RADIX ) buckets[tmp].append(_lowerCamelCase ) # put each buckets' contents into list_of_ints _lowerCAmelCase : List[str] = 0 for b in range(_lowerCamelCase ): for i in buckets[b]: _lowerCAmelCase : Any = i a += 1 # move to next placement *= RADIX return list_of_ints if __name__ == "__main__": import doctest doctest.testmod()
44
0
"""simple docstring""" def lowercase__(A ) ->bool: """simple docstring""" if number < 0: raise ValueError("number must not be negative" ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
371
"""simple docstring""" from __future__ import annotations def lowercase__(A , A ) ->list[str]: """simple docstring""" if partitions <= 0: raise ValueError("partitions must be a positive number!" ) if partitions > number_of_bytes: raise ValueError("partitions can not > number_of_bytes!" ) lowercase__ : List[str]= number_of_bytes // partitions lowercase__ : Dict= [] for i in range(A ): lowercase__ : Union[str, Any]= i * bytes_per_partition + 1 lowercase__ : Any= ( number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition ) allocation_list.append(f'''{start_bytes}-{end_bytes}''' ) return allocation_list if __name__ == "__main__": import doctest doctest.testmod()
150
0
import argparse import collections import numpy as np import torch from flax import traverse_util from tax import checkpoints from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( A_ ,A_ ,A_): return params[F"{prefix}/{prefix}/relpos_bias/rel_embedding"][:, i, :] def lowerCAmelCase_ ( A_ ,A_ ,A_ ,A_="attention"): UpperCamelCase__: Tuple = np.ascontiguousarray(params[F"{prefix}/{prefix}/{layer_name}/key/kernel"][:, i, :, :]) UpperCamelCase__: Tuple = k_tmp.reshape(k_tmp.shape[0] ,k_tmp.shape[1] * k_tmp.shape[2]) UpperCamelCase__: Optional[int] = np.ascontiguousarray(params[F"{prefix}/{prefix}/{layer_name}/out/kernel"][:, i, :, :]) UpperCamelCase__: Any = o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1] ,o_tmp.shape[2]) UpperCamelCase__: Optional[int] = np.ascontiguousarray(params[F"{prefix}/{prefix}/{layer_name}/query/kernel"][:, i, :, :]) UpperCamelCase__: Dict = q_tmp.reshape(q_tmp.shape[0] ,q_tmp.shape[1] * q_tmp.shape[2]) UpperCamelCase__: Any = np.ascontiguousarray(params[F"{prefix}/{prefix}/{layer_name}/value/kernel"][:, i, :, :]) UpperCamelCase__: List[str] = v_tmp.reshape(v_tmp.shape[0] ,v_tmp.shape[1] * v_tmp.shape[2]) return k, o, q, v def lowerCAmelCase_ ( A_ ,A_ ,A_ ,A_=False): if split_mlp_wi: UpperCamelCase__: int = params[F"{prefix}/{prefix}/mlp/wi_0/kernel"][:, i, :] UpperCamelCase__: List[Any] = params[F"{prefix}/{prefix}/mlp/wi_1/kernel"][:, i, :] UpperCamelCase__: Union[str, Any] = (wi_a, wi_a) else: UpperCamelCase__: Optional[int] = params[F"{prefix}/{prefix}/mlp/wi/kernel"][:, i, :] UpperCamelCase__: List[Any] = params[F"{prefix}/{prefix}/mlp/wo/kernel"][:, i, :] return wi, wo def lowerCAmelCase_ ( A_ ,A_ ,A_ ,A_): return params[F"{prefix}/{prefix}/{layer_name}/scale"][:, i] def lowerCAmelCase_ ( A_ ,*, A_ ,A_ ,A_ = False): UpperCamelCase__: Optional[int] = traverse_util.flatten_dict(variables["target"]) UpperCamelCase__: Union[str, Any] = {"/".join(A_): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi UpperCamelCase__: str = "encoder/encoder/mlp/wi_0/kernel" in old print("Split MLP:" ,A_) UpperCamelCase__: Optional[int] = collections.OrderedDict() # Shared embeddings. UpperCamelCase__: int = old["token_embedder/embedding"] # Encoder. for i in range(A_): # Block i, layer 0 (Self Attention). UpperCamelCase__: int = tax_layer_norm_lookup(A_ ,A_ ,"encoder" ,"pre_attention_layer_norm") UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__: List[Any] = tax_attention_lookup(A_ ,A_ ,"encoder" ,"attention") UpperCamelCase__: Optional[Any] = layer_norm UpperCamelCase__: List[Any] = k.T UpperCamelCase__: Union[str, Any] = o.T UpperCamelCase__: List[str] = q.T UpperCamelCase__: Optional[Any] = v.T # Block i, layer 1 (MLP). UpperCamelCase__: List[str] = tax_layer_norm_lookup(A_ ,A_ ,"encoder" ,"pre_mlp_layer_norm") UpperCamelCase__ , UpperCamelCase__: List[Any] = tax_mlp_lookup(A_ ,A_ ,"encoder" ,A_) UpperCamelCase__: Any = layer_norm if split_mlp_wi: UpperCamelCase__: List[str] = wi[0].T UpperCamelCase__: List[str] = wi[1].T else: UpperCamelCase__: Optional[int] = wi.T UpperCamelCase__: Dict = wo.T if scalable_attention: # convert the rel_embedding of each layer UpperCamelCase__: str = tax_relpos_bias_lookup( A_ ,A_ ,"encoder").T UpperCamelCase__: str = old["encoder/encoder_norm/scale"] if not scalable_attention: UpperCamelCase__: Optional[int] = tax_relpos_bias_lookup( A_ ,0 ,"encoder").T UpperCamelCase__: Tuple = tax_relpos_bias_lookup( A_ ,0 ,"decoder").T if not is_encoder_only: # Decoder. for i in range(A_): # Block i, layer 0 (Self Attention). UpperCamelCase__: Dict = tax_layer_norm_lookup(A_ ,A_ ,"decoder" ,"pre_self_attention_layer_norm") UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__: Tuple = tax_attention_lookup(A_ ,A_ ,"decoder" ,"self_attention") UpperCamelCase__: List[Any] = layer_norm UpperCamelCase__: Any = k.T UpperCamelCase__: Any = o.T UpperCamelCase__: str = q.T UpperCamelCase__: Tuple = v.T # Block i, layer 1 (Cross Attention). UpperCamelCase__: List[str] = tax_layer_norm_lookup(A_ ,A_ ,"decoder" ,"pre_cross_attention_layer_norm") UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__: str = tax_attention_lookup(A_ ,A_ ,"decoder" ,"encoder_decoder_attention") UpperCamelCase__: Tuple = layer_norm UpperCamelCase__: Optional[Any] = k.T UpperCamelCase__: Tuple = o.T UpperCamelCase__: Any = q.T UpperCamelCase__: int = v.T # Block i, layer 2 (MLP). UpperCamelCase__: Optional[int] = tax_layer_norm_lookup(A_ ,A_ ,"decoder" ,"pre_mlp_layer_norm") UpperCamelCase__ , UpperCamelCase__: Union[str, Any] = tax_mlp_lookup(A_ ,A_ ,"decoder" ,A_) UpperCamelCase__: List[str] = layer_norm if split_mlp_wi: UpperCamelCase__: Dict = wi[0].T UpperCamelCase__: List[Any] = wi[1].T else: UpperCamelCase__: Any = wi.T UpperCamelCase__: Dict = wo.T if scalable_attention: # convert the rel_embedding of each layer UpperCamelCase__: List[str] = tax_relpos_bias_lookup(A_ ,A_ ,"decoder").T UpperCamelCase__: int = old["decoder/decoder_norm/scale"] # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: UpperCamelCase__: Union[str, Any] = old["decoder/logits_dense/kernel"].T return new def lowerCAmelCase_ ( A_ ,A_): UpperCamelCase__: Optional[int] = collections.OrderedDict([(k, torch.from_numpy(v.copy())) for (k, v) in converted_params.items()]) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: UpperCamelCase__: Optional[int] = state_dict["shared.weight"] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: UpperCamelCase__: Any = state_dict["shared.weight"] if "lm_head.weight" not in state_dict: # For old 1.0 models. print("Using shared word embeddings as lm_head.") UpperCamelCase__: Union[str, Any] = state_dict["shared.weight"] return state_dict def lowerCAmelCase_ ( A_ ,A_ ,A_ ,A_ ,A_): UpperCamelCase__: Dict = checkpoints.load_tax_checkpoint(A_) UpperCamelCase__: Optional[Any] = convert_tax_to_pytorch( A_ ,num_layers=config.num_layers ,is_encoder_only=A_ ,scalable_attention=A_) UpperCamelCase__: str = make_state_dict(A_ ,A_) model.load_state_dict(A_ ,strict=A_) def lowerCAmelCase_ ( A_ ,A_ ,A_ ,A_ = False ,A_ = False ,): UpperCamelCase__: Any = MTaConfig.from_json_file(A_) print(F"Building PyTorch model from configuration: {config}") # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: UpperCamelCase__: Dict = UMTaEncoderModel(A_) else: UpperCamelCase__: int = UMTaForConditionalGeneration(A_) # Load weights from tf checkpoint load_tax_weights_in_ta(A_ ,A_ ,A_ ,A_ ,A_) # Save pytorch-model print(F"Save PyTorch model to {pytorch_dump_path}") model.save_pretrained(A_) # Verify that we can load the checkpoint. model.from_pretrained(A_) print("Done") if __name__ == "__main__": A__: str = argparse.ArgumentParser(description='''Converts a native T5X checkpoint into a PyTorch checkpoint.''') # Required parameters parser.add_argument( '''--t5x_checkpoint_path''', default=None, type=str, required=True, help='''Path to the T5X checkpoint.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.''', ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--is_encoder_only''', action='''store_true''', help='''Check if the model is encoder-decoder model''', default=False ) parser.add_argument( '''--scalable_attention''', action='''store_true''', help='''Whether the model uses scaled attention (umt5 model)''', default=False, ) A__: int = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only, args.scalable_attention, )
149
from torch import nn def lowerCAmelCase_ ( A_): if act_fn in ["swish", "silu"]: return nn.SiLU() elif act_fn == "mish": return nn.Mish() elif act_fn == "gelu": return nn.GELU() else: raise ValueError(F"Unsupported activation function: {act_fn}")
149
1
'''simple docstring''' import pprint import requests lowerCAmelCase__ = '''https://zenquotes.io/api''' def _A ( ): """simple docstring""" return requests.get(API_ENDPOINT_URL + '''/today''' ).json() def _A ( ): """simple docstring""" return requests.get(API_ENDPOINT_URL + '''/random''' ).json() if __name__ == "__main__": lowerCAmelCase__ = random_quotes() pprint.pprint(response)
52
'''simple docstring''' # Function to print upper half of diamond (pyramid) def _A ( A__ ): """simple docstring""" for i in range(0 , A__ ): for _ in range(0 , n - i - 1 ): # printing spaces print(''' ''' , end='''''' ) for _ in range(0 , i + 1 ): # printing stars print('''* ''' , end='''''' ) print() def _A ( A__ ): """simple docstring""" for i in range(A__ , 0 , -1 ): for _ in range(A__ , 0 , -1 ): # printing stars print('''* ''' , end='''''' ) print() for _ in range(n - i + 1 , 0 , -1 ): # printing spaces print(''' ''' , end='''''' ) def _A ( A__ ): """simple docstring""" if n <= 0: print(''' ... .... nothing printing :(''' ) return floyd(A__ ) # upper half reverse_floyd(A__ ) # lower half if __name__ == "__main__": print(R'''| /\ | |- | |- |--| |\ /| |-''') print(R'''|/ \| |- |_ |_ |__| | \/ | |_''') lowerCAmelCase__ = 1 while K: lowerCAmelCase__ = int(input('''enter the number and , and see the magic : ''')) print() pretty_print(user_number) lowerCAmelCase__ = int(input('''press 0 to exit... and 1 to continue...''')) print('''Good Bye...''')
52
1
"""simple docstring""" import os a = {'I': 1, 'V': 5, 'X': 1_0, 'L': 5_0, 'C': 1_0_0, 'D': 5_0_0, 'M': 1_0_0_0} def lowercase (snake_case__ : List[Any] ) -> int: '''simple docstring''' lowerCAmelCase = 0 lowerCAmelCase = 0 while index < len(UpperCamelCase__ ) - 1: lowerCAmelCase = SYMBOLS[numerals[index]] lowerCAmelCase = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def lowercase (snake_case__ : Optional[Any] ) -> str: '''simple docstring''' lowerCAmelCase = """""" lowerCAmelCase = num // 1_000 numerals += m_count * "M" num %= 1_000 lowerCAmelCase = num // 100 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 100 lowerCAmelCase = num // 10 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 10 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def lowercase (snake_case__ : Any = "/p089_roman.txt" ) -> int: '''simple docstring''' lowerCAmelCase = 0 with open(os.path.dirname(UpperCamelCase__ ) + roman_numerals_filename ) as filea: lowerCAmelCase = filea.readlines() for line in lines: lowerCAmelCase = line.strip() lowerCAmelCase = parse_roman_numerals(UpperCamelCase__ ) lowerCAmelCase = generate_roman_numerals(UpperCamelCase__ ) savings += len(UpperCamelCase__ ) - len(UpperCamelCase__ ) return savings if __name__ == "__main__": print(f"""{solution() = }""")
155
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __UpperCAmelCase ={ "configuration_clap": [ "CLAP_PRETRAINED_MODEL_ARCHIVE_LIST", "ClapAudioConfig", "ClapConfig", "ClapTextConfig", ], "processing_clap": ["ClapProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase =[ "CLAP_PRETRAINED_MODEL_ARCHIVE_LIST", "ClapModel", "ClapPreTrainedModel", "ClapTextModel", "ClapTextModelWithProjection", "ClapAudioModel", "ClapAudioModelWithProjection", ] __UpperCAmelCase =["ClapFeatureExtractor"] if TYPE_CHECKING: from .configuration_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioConfig, ClapConfig, ClapTextConfig, ) from .processing_clap import ClapProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clap import ClapFeatureExtractor from .modeling_clap import ( CLAP_PRETRAINED_MODEL_ARCHIVE_LIST, ClapAudioModel, ClapAudioModelWithProjection, ClapModel, ClapPreTrainedModel, ClapTextModel, ClapTextModelWithProjection, ) else: import sys __UpperCAmelCase =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
67
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCamelCase_ = logging.get_logger(__name__) lowerCamelCase_ = { '''MIT/ast-finetuned-audioset-10-10-0.4593''': ( '''https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json''' ), } class UpperCamelCase_ (__A ): __magic_name__ = '''audio-spectrogram-transformer''' def __init__( self : Any , lowerCAmelCase_ : Dict=768 , lowerCAmelCase_ : Any=12 , lowerCAmelCase_ : Optional[Any]=12 , lowerCAmelCase_ : Dict=3_072 , lowerCAmelCase_ : Any="gelu" , lowerCAmelCase_ : Dict=0.0 , lowerCAmelCase_ : Tuple=0.0 , lowerCAmelCase_ : int=0.0_2 , lowerCAmelCase_ : Optional[Any]=1e-12 , lowerCAmelCase_ : Any=16 , lowerCAmelCase_ : str=True , lowerCAmelCase_ : Optional[Any]=10 , lowerCAmelCase_ : List[Any]=10 , lowerCAmelCase_ : Dict=1_024 , lowerCAmelCase_ : Optional[Any]=128 , **lowerCAmelCase_ : Optional[Any] , ) -> int: super().__init__(**lowerCAmelCase_ ) UpperCAmelCase_ : Optional[Any] = hidden_size UpperCAmelCase_ : int = num_hidden_layers UpperCAmelCase_ : Optional[Any] = num_attention_heads UpperCAmelCase_ : Optional[int] = intermediate_size UpperCAmelCase_ : Dict = hidden_act UpperCAmelCase_ : str = hidden_dropout_prob UpperCAmelCase_ : Dict = attention_probs_dropout_prob UpperCAmelCase_ : List[Any] = initializer_range UpperCAmelCase_ : List[Any] = layer_norm_eps UpperCAmelCase_ : Tuple = patch_size UpperCAmelCase_ : List[Any] = qkv_bias UpperCAmelCase_ : Dict = frequency_stride UpperCAmelCase_ : List[str] = time_stride UpperCAmelCase_ : Optional[Any] = max_length UpperCAmelCase_ : Optional[int] = num_mel_bins
365
"""simple docstring""" from math import factorial def snake_case ( A__ = 1_00 ): return sum(int(A__ ) for x in str(factorial(A__ ) ) ) if __name__ == "__main__": print(solution(int(input('''Enter the Number: ''').strip())))
253
0
"""simple docstring""" import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_decord, require_tf, require_torch, require_torch_or_tf, require_vision, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf @require_vision @require_decord class _UpperCAmelCase ( unittest.TestCase ): a__ : List[Any] = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING def a ( self : int , _lowercase : int , _lowercase : List[str] , _lowercase : Union[str, Any] ): __UpperCAmelCase = hf_hub_download( repo_id='''nateraw/video-demo''' , filename='''archery.mp4''' , repo_type='''dataset''' ) __UpperCAmelCase = VideoClassificationPipeline(model=_lowercase , image_processor=_lowercase , top_k=2 ) __UpperCAmelCase = [ example_video_filepath, '''https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4''', ] return video_classifier, examples def a ( self : List[Any] , _lowercase : Any , _lowercase : Dict ): for example in examples: __UpperCAmelCase = video_classifier(_lowercase ) self.assertEqual( _lowercase , [ {'''score''': ANY(_lowercase ), '''label''': ANY(_lowercase )}, {'''score''': ANY(_lowercase ), '''label''': ANY(_lowercase )}, ] , ) @require_torch def a ( self : Any ): __UpperCAmelCase = '''hf-internal-testing/tiny-random-VideoMAEForVideoClassification''' __UpperCAmelCase = VideoMAEFeatureExtractor( size={'''shortest_edge''': 10} , crop_size={'''height''': 10, '''width''': 10} ) __UpperCAmelCase = pipeline( '''video-classification''' , model=_lowercase , feature_extractor=_lowercase , frame_sampling_rate=4 ) __UpperCAmelCase = hf_hub_download(repo_id='''nateraw/video-demo''' , filename='''archery.mp4''' , repo_type='''dataset''' ) __UpperCAmelCase = video_classifier(_lowercase , top_k=2 ) self.assertEqual( nested_simplify(_lowercase , decimals=4 ) , [{'''score''': 0.5_199, '''label''': '''LABEL_0'''}, {'''score''': 0.4_801, '''label''': '''LABEL_1'''}] , ) __UpperCAmelCase = video_classifier( [ video_file_path, video_file_path, ] , top_k=2 , ) self.assertEqual( nested_simplify(_lowercase , decimals=4 ) , [ [{'''score''': 0.5_199, '''label''': '''LABEL_0'''}, {'''score''': 0.4_801, '''label''': '''LABEL_1'''}], [{'''score''': 0.5_199, '''label''': '''LABEL_0'''}, {'''score''': 0.4_801, '''label''': '''LABEL_1'''}], ] , ) @require_tf def a ( self : int ): pass
332
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowercase : str = logging.get_logger(__name__) _lowercase : Dict = { 'microsoft/swinv2-tiny-patch4-window8-256': ( 'https://huggingface.co/microsoft/swinv2-tiny-patch4-window8-256/resolve/main/config.json' ), } class _UpperCAmelCase ( _lowerCAmelCase ): a__ : Tuple = "swinv2" a__ : List[Any] = { "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers", } def __init__( self : Any , _lowercase : List[Any]=2_24 , _lowercase : int=4 , _lowercase : Optional[int]=3 , _lowercase : Optional[Any]=96 , _lowercase : Optional[int]=[2, 2, 6, 2] , _lowercase : Optional[int]=[3, 6, 12, 24] , _lowercase : str=7 , _lowercase : Union[str, Any]=4.0 , _lowercase : List[str]=True , _lowercase : List[Any]=0.0 , _lowercase : Dict=0.0 , _lowercase : List[Any]=0.1 , _lowercase : Union[str, Any]="gelu" , _lowercase : Tuple=False , _lowercase : Optional[int]=0.02 , _lowercase : List[Any]=1E-5 , _lowercase : Tuple=32 , **_lowercase : Optional[int] , ): super().__init__(**_lowercase ) __UpperCAmelCase = image_size __UpperCAmelCase = patch_size __UpperCAmelCase = num_channels __UpperCAmelCase = embed_dim __UpperCAmelCase = depths __UpperCAmelCase = len(_lowercase ) __UpperCAmelCase = num_heads __UpperCAmelCase = window_size __UpperCAmelCase = mlp_ratio __UpperCAmelCase = qkv_bias __UpperCAmelCase = hidden_dropout_prob __UpperCAmelCase = attention_probs_dropout_prob __UpperCAmelCase = drop_path_rate __UpperCAmelCase = hidden_act __UpperCAmelCase = use_absolute_embeddings __UpperCAmelCase = layer_norm_eps __UpperCAmelCase = initializer_range __UpperCAmelCase = encoder_stride # we set the hidden_size attribute in order to make Swinv2 work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model __UpperCAmelCase = int(embed_dim * 2 ** (len(_lowercase ) - 1) ) __UpperCAmelCase = (0, 0, 0, 0)
332
1
import os from argparse import ArgumentParser from typing import List import torch.utils.data from datasets import Dataset, IterableDataset from datasets.distributed import split_dataset_by_node snake_case : Any = 4 snake_case : str = 3 class _snake_case ( _snake_case ): pass def __lowerCamelCase ( UpperCAmelCase_ : List[str] ): """simple docstring""" for shard in shards: for i in range(UpperCAmelCase_ ): yield {"i": i, "shard": shard} def __lowerCamelCase ( ): """simple docstring""" a :List[Any] = int(os.environ['''RANK'''] ) a :Optional[Any] = int(os.environ['''WORLD_SIZE'''] ) a :List[Any] = ArgumentParser() parser.add_argument('''--streaming''' , type=UpperCAmelCase_ ) parser.add_argument('''--local_rank''' , type=UpperCAmelCase_ ) parser.add_argument('''--num_workers''' , type=UpperCAmelCase_ , default=0 ) a :Tuple = parser.parse_args() a :Union[str, Any] = args.streaming a :Optional[int] = args.num_workers a :Dict = {'''shards''': [F'''shard_{shard_idx}''' for shard_idx in range(UpperCAmelCase_ )]} a :Dict = IterableDataset.from_generator(UpperCAmelCase_ , gen_kwargs=UpperCAmelCase_ ) if not streaming: a :Union[str, Any] = Dataset.from_list(list(UpperCAmelCase_ ) ) a :List[Any] = split_dataset_by_node(UpperCAmelCase_ , rank=UpperCAmelCase_ , world_size=UpperCAmelCase_ ) a :Optional[int] = torch.utils.data.DataLoader(UpperCAmelCase_ , num_workers=UpperCAmelCase_ ) a :Tuple = NUM_SHARDS * NUM_ITEMS_PER_SHARD a :Union[str, Any] = full_size // world_size expected_local_size += int(rank < (full_size % world_size) ) a :str = sum(1 for _ in dataloader ) if local_size != expected_local_size: raise FailedTestError(F'''local_size {local_size} != expected_local_size {expected_local_size}''' ) if __name__ == "__main__": main()
281
def __lowerCamelCase ( UpperCAmelCase_ : int ): """simple docstring""" if not isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): raise TypeError('''Input value must be an \'int\' type''' ) a :Optional[int] = 0 while number: position += 1 number >>= 1 return position if __name__ == "__main__": import doctest doctest.testmod()
281
1
import numpy as np import datasets SCREAMING_SNAKE_CASE__ = """ Compute the Mahalanobis Distance Mahalonobis distance is the distance between a point and a distribution. And not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance. It was introduced by Prof. P. C. Mahalanobis in 1936 and has been used in various statistical applications ever since [source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/] """ SCREAMING_SNAKE_CASE__ = """\ @article{de2000mahalanobis, title={The mahalanobis distance}, author={De Maesschalck, Roy and Jouan-Rimbaud, Delphine and Massart, D{\'e}sir{\'e} L}, journal={Chemometrics and intelligent laboratory systems}, volume={50}, number={1}, pages={1--18}, year={2000}, publisher={Elsevier} } """ SCREAMING_SNAKE_CASE__ = """ Args: X: List of datapoints to be compared with the `reference_distribution`. reference_distribution: List of datapoints from the reference distribution we want to compare to. Returns: mahalanobis: The Mahalonobis distance for each datapoint in `X`. Examples: >>> mahalanobis_metric = datasets.load_metric(\"mahalanobis\") >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]]) >>> print(results) {'mahalanobis': array([0.5])} """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A__ ( datasets.Metric ): def a__ ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'X': datasets.Sequence(datasets.Value('float' , id='sequence' ) , id='X' ), } ) , ) def a__ ( self : int , _UpperCAmelCase : List[Any] , _UpperCAmelCase : Any ) -> Any: """simple docstring""" __lowercase = np.array(_UpperCAmelCase ) __lowercase = np.array(_UpperCAmelCase ) # Assert that arrays are 2D if len(X.shape ) != 2: raise ValueError('Expected `X` to be a 2D vector' ) if len(reference_distribution.shape ) != 2: raise ValueError('Expected `reference_distribution` to be a 2D vector' ) if reference_distribution.shape[0] < 2: raise ValueError( 'Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension' ) # Get mahalanobis distance for each prediction __lowercase = X - np.mean(_UpperCAmelCase ) __lowercase = np.cov(reference_distribution.T ) try: __lowercase = np.linalg.inv(_UpperCAmelCase ) except np.linalg.LinAlgError: __lowercase = np.linalg.pinv(_UpperCAmelCase ) __lowercase = np.dot(_UpperCAmelCase , _UpperCAmelCase ) __lowercase = np.dot(_UpperCAmelCase , X_minus_mu.T ).diagonal() return {"mahalanobis": mahal_dist}
325
def __SCREAMING_SNAKE_CASE ( SCREAMING_SNAKE_CASE : Optional[Any] , SCREAMING_SNAKE_CASE : List[Any] ) -> List[str]: __lowercase = [0 for i in range(r + 1 )] # nc0 = 1 __lowercase = 1 for i in range(1 , n + 1 ): # to compute current row from previous row. __lowercase = min(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) while j > 0: c[j] += c[j - 1] j -= 1 return c[r] print(binomial_coefficient(n=10, r=5))
325
1
import unittest import numpy as np def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = None , ) -> np.ndarray: _lowercase : int = np.shape(lowerCamelCase_ ) _lowercase : List[Any] = np.shape(lowerCamelCase_ ) _lowercase : Dict = np.shape(lowerCamelCase_ ) if shape_a[0] != shape_b[0]: _lowercase : Union[str, Any] = ( 'Expected the same number of rows for A and B. ' F'''Instead found A of size {shape_a} and B of size {shape_b}''' ) raise ValueError(lowerCamelCase_ ) if shape_b[1] != shape_c[1]: _lowercase : str = ( 'Expected the same number of columns for B and C. ' F'''Instead found B of size {shape_b} and C of size {shape_c}''' ) raise ValueError(lowerCamelCase_ ) _lowercase : int = pseudo_inv if a_inv is None: try: _lowercase : int = np.linalg.inv(lowerCamelCase_ ) except np.linalg.LinAlgError: raise ValueError( 'Input matrix A is not invertible. Cannot compute Schur complement.' ) return mat_c - mat_b.T @ a_inv @ mat_b class _lowerCamelCase( unittest.TestCase ): def UpperCamelCase ( self) -> None: """simple docstring""" _lowercase : Dict = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) _lowercase : int = np.array([[0, 3], [3, 0], [2, 3]]) _lowercase : Optional[Any] = np.array([[2, 1], [6, 3]]) _lowercase : Dict = schur_complement(lowerCamelCase, lowerCamelCase, lowerCamelCase) _lowercase : List[str] = np.block([[a, b], [b.T, c]]) _lowercase : str = np.linalg.det(lowerCamelCase) _lowercase : Any = np.linalg.det(lowerCamelCase) _lowercase : Union[str, Any] = np.linalg.det(lowerCamelCase) self.assertAlmostEqual(lowerCamelCase, det_a * det_s) def UpperCamelCase ( self) -> None: """simple docstring""" _lowercase : Union[str, Any] = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) _lowercase : Tuple = np.array([[0, 3], [3, 0], [2, 3]]) _lowercase : List[str] = np.array([[2, 1], [6, 3]]) with self.assertRaises(lowerCamelCase): schur_complement(lowerCamelCase, lowerCamelCase, lowerCamelCase) def UpperCamelCase ( self) -> None: """simple docstring""" _lowercase : Optional[Any] = np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]) _lowercase : str = np.array([[0, 3], [3, 0], [2, 3]]) _lowercase : List[str] = np.array([[2, 1, 3], [6, 3, 5]]) with self.assertRaises(lowerCamelCase): schur_complement(lowerCamelCase, lowerCamelCase, lowerCamelCase) if __name__ == "__main__": import doctest doctest.testmod() unittest.main()
84
import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class _lowerCamelCase( _a, unittest.TestCase ): lowercase_ : List[str] = CTRLTokenizer lowercase_ : Union[str, Any] = False lowercase_ : Optional[int] = False def UpperCamelCase ( self) -> List[str]: """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt _lowercase : List[Any] = ['adapt', 're@@', 'a@@', 'apt', 'c@@', 't', '<unk>'] _lowercase : List[Any] = dict(zip(lowerCamelCase, range(len(lowerCamelCase)))) _lowercase : Optional[int] = ['#version: 0.2', 'a p', 'ap t</w>', 'r e', 'a d', 'ad apt</w>', ''] _lowercase : Union[str, Any] = {'unk_token': '<unk>'} _lowercase : int = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES['vocab_file']) _lowercase : List[str] = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES['merges_file']) with open(self.vocab_file, 'w', encoding='utf-8') as fp: fp.write(json.dumps(lowerCamelCase) + '\n') with open(self.merges_file, 'w', encoding='utf-8') as fp: fp.write('\n'.join(lowerCamelCase)) def UpperCamelCase ( self, **lowerCamelCase) -> List[str]: """simple docstring""" kwargs.update(self.special_tokens_map) return CTRLTokenizer.from_pretrained(self.tmpdirname, **lowerCamelCase) def UpperCamelCase ( self, lowerCamelCase) -> Optional[int]: """simple docstring""" _lowercase : Tuple = 'adapt react readapt apt' _lowercase : Tuple = 'adapt react readapt apt' return input_text, output_text def UpperCamelCase ( self) -> List[str]: """simple docstring""" _lowercase : Optional[int] = CTRLTokenizer(self.vocab_file, self.merges_file, **self.special_tokens_map) _lowercase : List[str] = 'adapt react readapt apt' _lowercase : Optional[Any] = 'adapt re@@ a@@ c@@ t re@@ adapt apt'.split() _lowercase : Optional[Any] = tokenizer.tokenize(lowerCamelCase) self.assertListEqual(lowerCamelCase, lowerCamelCase) _lowercase : List[str] = tokens + [tokenizer.unk_token] _lowercase : int = [0, 1, 2, 4, 5, 1, 0, 3, 6] self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCamelCase), lowerCamelCase)
84
1
"""simple docstring""" def __a ( __lowerCamelCase = 100_0000 ): UpperCAmelCase_ : int = 1 UpperCAmelCase_ : Tuple = 1 UpperCAmelCase_ : Any = {1: 1} for inputa in range(2, __lowerCamelCase ): UpperCAmelCase_ : Any = 0 UpperCAmelCase_ : List[Any] = inputa while True: if number in counters: counter += counters[number] break if number % 2 == 0: number //= 2 counter += 1 else: UpperCAmelCase_ : Union[str, Any] = (3 * number) + 1 counter += 1 if inputa not in counters: UpperCAmelCase_ : str = counter if counter > pre_counter: UpperCAmelCase_ : str = inputa UpperCAmelCase_ : str = counter return largest_number if __name__ == "__main__": print(solution(int(input().strip())))
61
"""simple docstring""" from ...utils import is_torch_available, is_transformers_available if is_transformers_available() and is_torch_available(): from .pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings, VQDiffusionPipeline
61
1
'''simple docstring''' import json import os import unittest from transformers.models.ctrl.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class UpperCAmelCase_ ( _a , unittest.TestCase ): """simple docstring""" lowercase = CTRLTokenizer lowercase = False lowercase = False def lowerCamelCase ( self : Union[str, Any] ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt snake_case__ : str = ["""adapt""", """re@@""", """a@@""", """apt""", """c@@""", """t""", """<unk>"""] snake_case__ : int = dict(zip(snake_case_ , range(len(snake_case_ ) ) ) ) snake_case__ : List[str] = ["""#version: 0.2""", """a p""", """ap t</w>""", """r e""", """a d""", """ad apt</w>""", """"""] snake_case__ : Optional[int] = {"""unk_token""": """<unk>"""} snake_case__ : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) snake_case__ : int = 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(snake_case_ ) + """\n""" ) with open(self.merges_file , """w""" , encoding="""utf-8""" ) as fp: fp.write("""\n""".join(snake_case_ ) ) def lowerCamelCase ( self : Union[str, Any] , **snake_case_ : List[str] ): kwargs.update(self.special_tokens_map ) return CTRLTokenizer.from_pretrained(self.tmpdirname , **snake_case_ ) def lowerCamelCase ( self : Union[str, Any] , snake_case_ : Optional[int] ): snake_case__ : str = """adapt react readapt apt""" snake_case__ : Union[str, Any] = """adapt react readapt apt""" return input_text, output_text def lowerCamelCase ( self : Optional[Any] ): snake_case__ : Union[str, Any] = CTRLTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) snake_case__ : Union[str, Any] = """adapt react readapt apt""" snake_case__ : Any = """adapt re@@ a@@ c@@ t re@@ adapt apt""".split() snake_case__ : Union[str, Any] = tokenizer.tokenize(snake_case_ ) self.assertListEqual(snake_case_ , snake_case_ ) snake_case__ : int = tokens + [tokenizer.unk_token] snake_case__ : List[str] = [0, 1, 2, 4, 5, 1, 0, 3, 6] self.assertListEqual(tokenizer.convert_tokens_to_ids(snake_case_ ) , snake_case_ )
351
'''simple docstring''' import re from filelock import FileLock try: import nltk __a = True except (ImportError, ModuleNotFoundError): __a = False if NLTK_AVAILABLE: with FileLock(".lock") as lock: nltk.download("punkt", quiet=True) def __snake_case( _lowerCAmelCase ) -> str: re.sub("""<n>""" , """""" , _lowerCAmelCase ) # remove pegasus newline char assert NLTK_AVAILABLE, "nltk must be installed to separate newlines between sentences. (pip install nltk)" return "\n".join(nltk.sent_tokenize(_lowerCAmelCase ) )
43
0
def lowercase( ) -> int: '''simple docstring''' return [ a * b * (1000 - a - b) for a in range(1 , 999 ) for b in range(UpperCamelCase_ , 999 ) if (a * a + b * b == (1000 - a - b) ** 2) ][0] if __name__ == "__main__": print(F'''{solution() = }''')
343
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class SCREAMING_SNAKE_CASE_ ( __lowerCAmelCase , unittest.TestCase ): __lowerCAmelCase = ShapEPipeline __lowerCAmelCase = ["""prompt"""] __lowerCAmelCase = ["""prompt"""] __lowerCAmelCase = [ """num_images_per_prompt""", """num_inference_steps""", """generator""", """latents""", """guidance_scale""", """frame_size""", """output_type""", """return_dict""", ] __lowerCAmelCase = False @property def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" return 32 @property def lowerCamelCase_ ( self : List[str] ): """simple docstring""" return 32 @property def lowerCamelCase_ ( self : str ): """simple docstring""" return self.time_input_dim * 4 @property def lowerCamelCase_ ( self : str ): """simple docstring""" return 8 @property def lowerCamelCase_ ( self : int ): """simple docstring""" UpperCamelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) return tokenizer @property def lowerCamelCase_ ( self : Dict ): """simple docstring""" torch.manual_seed(0 ) UpperCamelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(lowerCamelCase_ ) @property def lowerCamelCase_ ( self : List[str] ): """simple docstring""" torch.manual_seed(0 ) UpperCamelCase = { """num_attention_heads""": 2, """attention_head_dim""": 16, """embedding_dim""": self.time_input_dim, """num_embeddings""": 32, """embedding_proj_dim""": self.text_embedder_hidden_size, """time_embed_dim""": self.time_embed_dim, """num_layers""": 1, """clip_embed_dim""": self.time_input_dim * 2, """additional_embeddings""": 0, """time_embed_act_fn""": """gelu""", """norm_in_type""": """layer""", """encoder_hid_proj_type""": None, """added_emb_type""": None, } UpperCamelCase = PriorTransformer(**lowerCamelCase_ ) return model @property def lowerCamelCase_ ( self : Union[str, Any] ): """simple docstring""" torch.manual_seed(0 ) UpperCamelCase = { """param_shapes""": ( (self.renderer_dim, 93), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), """d_latent""": self.time_input_dim, """d_hidden""": self.renderer_dim, """n_output""": 12, """background""": ( 0.1, 0.1, 0.1, ), } UpperCamelCase = ShapERenderer(**lowerCamelCase_ ) return model def lowerCamelCase_ ( self : Dict ): """simple docstring""" UpperCamelCase = self.dummy_prior UpperCamelCase = self.dummy_text_encoder UpperCamelCase = self.dummy_tokenizer UpperCamelCase = self.dummy_renderer UpperCamelCase = HeunDiscreteScheduler( beta_schedule="""exp""" , num_train_timesteps=1024 , prediction_type="""sample""" , use_karras_sigmas=lowerCamelCase_ , clip_sample=lowerCamelCase_ , clip_sample_range=1.0 , ) UpperCamelCase = { """prior""": prior, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """renderer""": renderer, """scheduler""": scheduler, } return components def lowerCamelCase_ ( self : int , lowerCamelCase_ : Any , lowerCamelCase_ : Union[str, Any]=0 ): """simple docstring""" if str(lowerCamelCase_ ).startswith("""mps""" ): UpperCamelCase = torch.manual_seed(lowerCamelCase_ ) else: UpperCamelCase = torch.Generator(device=lowerCamelCase_ ).manual_seed(lowerCamelCase_ ) UpperCamelCase = { """prompt""": """horse""", """generator""": generator, """num_inference_steps""": 1, """frame_size""": 32, """output_type""": """np""", } return inputs def lowerCamelCase_ ( self : int ): """simple docstring""" UpperCamelCase = """cpu""" UpperCamelCase = self.get_dummy_components() UpperCamelCase = self.pipeline_class(**lowerCamelCase_ ) UpperCamelCase = pipe.to(lowerCamelCase_ ) pipe.set_progress_bar_config(disable=lowerCamelCase_ ) UpperCamelCase = pipe(**self.get_dummy_inputs(lowerCamelCase_ ) ) UpperCamelCase = output.images[0] UpperCamelCase = image[0, -3:, -3:, -1] assert image.shape == (20, 32, 32, 3) UpperCamelCase = np.array( [ 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, 0.0_0_0_3_9_2_1_6, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def lowerCamelCase_ ( self : Tuple ): """simple docstring""" self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" UpperCamelCase = torch_device == """cpu""" UpperCamelCase = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=lowerCamelCase_ , relax_max_difference=lowerCamelCase_ , ) def lowerCamelCase_ ( self : Dict ): """simple docstring""" UpperCamelCase = self.get_dummy_components() UpperCamelCase = self.pipeline_class(**lowerCamelCase_ ) UpperCamelCase = pipe.to(lowerCamelCase_ ) pipe.set_progress_bar_config(disable=lowerCamelCase_ ) UpperCamelCase = 1 UpperCamelCase = 2 UpperCamelCase = self.get_dummy_inputs(lowerCamelCase_ ) for key in inputs.keys(): if key in self.batch_params: UpperCamelCase = batch_size * [inputs[key]] UpperCamelCase = pipe(**lowerCamelCase_ , num_images_per_prompt=lowerCamelCase_ )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): def lowerCamelCase_ ( self : Tuple ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase_ ( self : Any ): """simple docstring""" UpperCamelCase = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/shap_e/test_shap_e_np_out.npy""" ) UpperCamelCase = ShapEPipeline.from_pretrained("""openai/shap-e""" ) UpperCamelCase = pipe.to(lowerCamelCase_ ) pipe.set_progress_bar_config(disable=lowerCamelCase_ ) UpperCamelCase = torch.Generator(device=lowerCamelCase_ ).manual_seed(0 ) UpperCamelCase = pipe( """a shark""" , generator=lowerCamelCase_ , guidance_scale=1_5.0 , num_inference_steps=64 , frame_size=64 , output_type="""np""" , ).images[0] assert images.shape == (20, 64, 64, 3) assert_mean_pixel_difference(lowerCamelCase_ , lowerCamelCase_ )
343
1
# Imports import numpy as np class lowerCAmelCase : '''simple docstring''' def __init__( self : Optional[int] , __a : Dict=None , __a : Union[str, Any]=None , __a : Union[str, Any]=None , __a : Optional[Any]=None , __a : Optional[int]=None ) -> Optional[Any]: """simple docstring""" self.set_matricies(red=__A , green=__A , blue=__A , red_edge=__A , nir=__A ) def lowerCAmelCase ( self : Any , __a : Optional[int]=None , __a : Union[str, Any]=None , __a : List[Any]=None , __a : Any=None , __a : str=None ) -> Optional[Any]: """simple docstring""" if red is not None: __lowercase : Tuple = red if green is not None: __lowercase : List[str] = green if blue is not None: __lowercase : List[Any] = blue if red_edge is not None: __lowercase : int = red_edge if nir is not None: __lowercase : Optional[int] = nir return True def lowerCAmelCase ( self : Tuple , __a : Union[str, Any]="" , __a : List[Any]=None , __a : List[Any]=None , __a : Optional[Any]=None , __a : int=None , __a : List[Any]=None ) -> str: """simple docstring""" self.set_matricies(red=__A , green=__A , blue=__A , red_edge=__A , nir=__A ) __lowercase : List[Any] = { '''ARVI2''': self.arvaa, '''CCCI''': self.ccci, '''CVI''': self.cvi, '''GLI''': self.gli, '''NDVI''': self.ndvi, '''BNDVI''': self.bndvi, '''redEdgeNDVI''': self.red_edge_ndvi, '''GNDVI''': self.gndvi, '''GBNDVI''': self.gbndvi, '''GRNDVI''': self.grndvi, '''RBNDVI''': self.rbndvi, '''PNDVI''': self.pndvi, '''ATSAVI''': self.atsavi, '''BWDRVI''': self.bwdrvi, '''CIgreen''': self.ci_green, '''CIrededge''': self.ci_rededge, '''CI''': self.ci, '''CTVI''': self.ctvi, '''GDVI''': self.gdvi, '''EVI''': self.evi, '''GEMI''': self.gemi, '''GOSAVI''': self.gosavi, '''GSAVI''': self.gsavi, '''Hue''': self.hue, '''IVI''': self.ivi, '''IPVI''': self.ipvi, '''I''': self.i, '''RVI''': self.rvi, '''MRVI''': self.mrvi, '''MSAVI''': self.m_savi, '''NormG''': self.norm_g, '''NormNIR''': self.norm_nir, '''NormR''': self.norm_r, '''NGRDI''': self.ngrdi, '''RI''': self.ri, '''S''': self.s, '''IF''': self._if, '''DVI''': self.dvi, '''TVI''': self.tvi, '''NDRE''': self.ndre, } try: return funcs[index]() except KeyError: print("""Index not in the list!""" ) return False def lowerCAmelCase ( self : List[str] ) -> Any: """simple docstring""" return -0.18 + (1.17 * ((self.nir - self.red) / (self.nir + self.red))) def lowerCAmelCase ( self : List[Any] ) -> Optional[int]: """simple docstring""" return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / ( (self.nir - self.red) / (self.nir + self.red) ) def lowerCAmelCase ( self : List[str] ) -> Tuple: """simple docstring""" return self.nir * (self.red / (self.green**2)) def lowerCAmelCase ( self : str ) -> Dict: """simple docstring""" return (2 * self.green - self.red - self.blue) / ( 2 * self.green + self.red + self.blue ) def lowerCAmelCase ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" return (self.nir - self.red) / (self.nir + self.red) def lowerCAmelCase ( self : int ) -> str: """simple docstring""" return (self.nir - self.blue) / (self.nir + self.blue) def lowerCAmelCase ( self : Optional[int] ) -> int: """simple docstring""" return (self.redEdge - self.red) / (self.redEdge + self.red) def lowerCAmelCase ( self : Optional[Any] ) -> str: """simple docstring""" return (self.nir - self.green) / (self.nir + self.green) def lowerCAmelCase ( self : str ) -> Union[str, Any]: """simple docstring""" return (self.nir - (self.green + self.blue)) / ( self.nir + (self.green + self.blue) ) def lowerCAmelCase ( self : List[Any] ) -> int: """simple docstring""" return (self.nir - (self.green + self.red)) / ( self.nir + (self.green + self.red) ) def lowerCAmelCase ( self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red)) def lowerCAmelCase ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" return (self.nir - (self.green + self.red + self.blue)) / ( self.nir + (self.green + self.red + self.blue) ) def lowerCAmelCase ( self : Tuple , __a : Tuple=0.08 , __a : Optional[int]=1.22 , __a : Any=0.03 ) -> Union[str, Any]: """simple docstring""" return a * ( (self.nir - a * self.red - b) / (a * self.nir + self.red - a * b + x * (1 + a**2)) ) def lowerCAmelCase ( self : List[str] ) -> str: """simple docstring""" return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue) def lowerCAmelCase ( self : Optional[int] ) -> Optional[int]: """simple docstring""" return (self.nir / self.green) - 1 def lowerCAmelCase ( self : Tuple ) -> Union[str, Any]: """simple docstring""" return (self.nir / self.redEdge) - 1 def lowerCAmelCase ( self : int ) -> Optional[Any]: """simple docstring""" return (self.red - self.blue) / self.red def lowerCAmelCase ( self : Tuple ) -> str: """simple docstring""" __lowercase : str = self.ndvi() return ((ndvi + 0.5) / (abs(ndvi + 0.5 ))) * (abs(ndvi + 0.5 ) ** (1 / 2)) def lowerCAmelCase ( self : Tuple ) -> str: """simple docstring""" return self.nir - self.green def lowerCAmelCase ( self : List[Any] ) -> Tuple: """simple docstring""" return 2.5 * ( (self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1) ) def lowerCAmelCase ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" __lowercase : str = (2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) / ( self.nir + self.red + 0.5 ) return n * (1 - 0.25 * n) - (self.red - 0.125) / (1 - self.red) def lowerCAmelCase ( self : Dict , __a : List[Any]=0.16 ) -> str: """simple docstring""" return (self.nir - self.green) / (self.nir + self.green + y) def lowerCAmelCase ( self : Tuple , __a : Dict=0.5 ) -> Tuple: """simple docstring""" return ((self.nir - self.green) / (self.nir + self.green + n)) * (1 + n) def lowerCAmelCase ( self : Optional[int] ) -> str: """simple docstring""" return np.arctan( ((2 * self.red - self.green - self.blue) / 30.5) * (self.green - self.blue) ) def lowerCAmelCase ( self : List[str] , __a : Optional[int]=None , __a : Any=None ) -> Tuple: """simple docstring""" return (self.nir - b) / (a * self.red) def lowerCAmelCase ( self : List[str] ) -> List[Any]: """simple docstring""" return (self.nir / ((self.nir + self.red) / 2)) * (self.ndvi() + 1) def lowerCAmelCase ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" return (self.red + self.green + self.blue) / 30.5 def lowerCAmelCase ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" return self.nir / self.red def lowerCAmelCase ( self : str ) -> Union[str, Any]: """simple docstring""" return (self.rvi() - 1) / (self.rvi() + 1) def lowerCAmelCase ( self : Any ) -> Union[str, Any]: """simple docstring""" return ( (2 * self.nir + 1) - ((2 * self.nir + 1) ** 2 - 8 * (self.nir - self.red)) ** (1 / 2) ) / 2 def lowerCAmelCase ( self : Union[str, Any] ) -> Dict: """simple docstring""" return self.green / (self.nir + self.red + self.green) def lowerCAmelCase ( self : Tuple ) -> List[str]: """simple docstring""" return self.nir / (self.nir + self.red + self.green) def lowerCAmelCase ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" return self.red / (self.nir + self.red + self.green) def lowerCAmelCase ( self : Dict ) -> Optional[int]: """simple docstring""" return (self.green - self.red) / (self.green + self.red) def lowerCAmelCase ( self : Union[str, Any] ) -> Any: """simple docstring""" return (self.red - self.green) / (self.red + self.green) def lowerCAmelCase ( self : str ) -> Optional[int]: """simple docstring""" __lowercase : int = np.max([np.max(self.red ), np.max(self.green ), np.max(self.blue )] ) __lowercase : Optional[Any] = np.min([np.min(self.red ), np.min(self.green ), np.min(self.blue )] ) return (max_value - min_value) / max_value def lowerCAmelCase ( self : Any ) -> Any: """simple docstring""" return (2 * self.red - self.green - self.blue) / (self.green - self.blue) def lowerCAmelCase ( self : int ) -> Optional[int]: """simple docstring""" return self.nir / self.red def lowerCAmelCase ( self : Optional[int] ) -> int: """simple docstring""" return (self.ndvi() + 0.5) ** (1 / 2) def lowerCAmelCase ( self : Any ) -> Optional[Any]: """simple docstring""" return (self.nir - self.redEdge) / (self.nir + self.redEdge)
361
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( WavaVecaConformerConfig, WavaVecaConformerForCTC, WavaVecaConformerForPreTraining, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() lowerCamelCase : Optional[int] = logging.get_logger(__name__) lowerCamelCase : str = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.linear_k''': '''encoder.layers.*.self_attn.linear_k''', '''self_attn.linear_v''': '''encoder.layers.*.self_attn.linear_v''', '''self_attn.linear_q''': '''encoder.layers.*.self_attn.linear_q''', '''self_attn.pos_bias_u''': '''encoder.layers.*.self_attn.pos_bias_u''', '''self_attn.pos_bias_v''': '''encoder.layers.*.self_attn.pos_bias_v''', '''self_attn.linear_out''': '''encoder.layers.*.self_attn.linear_out''', '''self_attn.linear_pos''': '''encoder.layers.*.self_attn.linear_pos''', '''self_attn.rotary_emb''': '''encoder.embed_positions''', '''self_attn_layer_norm''': '''encoder.layers.*.self_attn_layer_norm''', '''conv_module.pointwise_conv1''': '''encoder.layers.*.conv_module.pointwise_conv1''', '''conv_module.pointwise_conv2''': '''encoder.layers.*.conv_module.pointwise_conv2''', '''conv_module.depthwise_conv''': '''encoder.layers.*.conv_module.depthwise_conv''', '''conv_module.batch_norm''': '''encoder.layers.*.conv_module.batch_norm''', '''conv_module.layer_norm''': '''encoder.layers.*.conv_module.layer_norm''', '''ffn1.w_1''': '''encoder.layers.*.ffn1.intermediate_dense''', '''ffn1.w_2''': '''encoder.layers.*.ffn1.output_dense''', '''ffn1.layer_norm''': '''encoder.layers.*.ffn1_layer_norm''', '''ffn2.w_1''': '''encoder.layers.*.ffn2.intermediate_dense''', '''ffn2.w_2''': '''encoder.layers.*.ffn2.output_dense''', '''ffn2.layer_norm''': '''encoder.layers.*.ffn2_layer_norm''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } lowerCamelCase : Optional[Any] = [ '''lm_head''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def snake_case_ ( lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : int , lowerCAmelCase_ : str , lowerCAmelCase_ : int ): for attribute in key.split(""".""" ): __lowercase : List[str] = getattr(lowerCAmelCase_ , lowerCAmelCase_ ) if weight_type is not None: __lowercase : Union[str, Any] = getattr(lowerCAmelCase_ , lowerCAmelCase_ ).shape else: __lowercase : Dict = hf_pointer.shape if hf_shape != value.shape: raise ValueError( F"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be" F" {value.shape} for {full_name}" ) if weight_type == "weight": __lowercase : Dict = value elif weight_type == "weight_g": __lowercase : Union[str, Any] = value elif weight_type == "weight_v": __lowercase : List[Any] = value elif weight_type == "bias": __lowercase : int = value elif weight_type == "running_mean": __lowercase : List[Any] = value elif weight_type == "running_var": __lowercase : int = value elif weight_type == "num_batches_tracked": __lowercase : int = value elif weight_type == "inv_freq": __lowercase : Optional[Any] = value else: __lowercase : Any = value logger.info(F"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." ) def snake_case_ ( lowerCAmelCase_ : Tuple , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Union[str, Any] ): __lowercase : str = [] __lowercase : Any = fairseq_model.state_dict() __lowercase : List[str] = hf_model.wavaveca_conformer.feature_extractor for name, value in fairseq_dict.items(): __lowercase : Optional[Any] = False if "conv_layers" in name: load_conv_layer( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , hf_model.config.feat_extract_norm == """group""" , ) __lowercase : List[str] = True else: for key, mapped_key in MAPPING.items(): __lowercase : Any = """wav2vec2_conformer.""" + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: __lowercase : Tuple = True if "*" in mapped_key: __lowercase : List[Any] = name.split(lowerCAmelCase_ )[0].split(""".""" )[-2] __lowercase : Any = mapped_key.replace("""*""" , lowerCAmelCase_ ) if "pos_bias_u" in name: __lowercase : Any = None elif "pos_bias_v" in name: __lowercase : Tuple = None elif "weight_g" in name: __lowercase : Union[str, Any] = """weight_g""" elif "weight_v" in name: __lowercase : Dict = """weight_v""" elif "bias" in name: __lowercase : Union[str, Any] = """bias""" elif "weight" in name: # TODO: don't match quantizer.weight_proj __lowercase : str = """weight""" elif "running_mean" in name: __lowercase : str = """running_mean""" elif "inv_freq" in name: __lowercase : List[Any] = """inv_freq""" elif "running_var" in name: __lowercase : Any = """running_var""" elif "num_batches_tracked" in name: __lowercase : Any = """num_batches_tracked""" else: __lowercase : Optional[int] = None set_recursively(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) continue if not is_used: unused_weights.append(lowerCAmelCase_ ) logger.warning(F"Unused weights: {unused_weights}" ) def snake_case_ ( lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : List[Any] , lowerCAmelCase_ : Optional[Any] ): __lowercase : List[Any] = full_name.split("""conv_layers.""" )[-1] __lowercase : int = name.split(""".""" ) __lowercase : Optional[Any] = int(items[0] ) __lowercase : List[str] = int(items[1] ) if type_id == 0: if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.bias.data.shape: raise ValueError( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found." ) __lowercase : Union[str, Any] = value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].conv.weight.data.shape: raise ValueError( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found." ) __lowercase : List[str] = value logger.info(F"Feat extract conv layer {layer_id} was initialized from {full_name}." ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape: raise ValueError( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape} was found." ) __lowercase : Union[str, Any] = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) elif "weight" in name: if value.shape != feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape: raise ValueError( F"{full_name} has size {value.shape}, but" F" {feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape} was found." ) __lowercase : Dict = value logger.info(F"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." ) else: unused_weights.append(lowerCAmelCase_ ) @torch.no_grad() def snake_case_ ( lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Any , lowerCAmelCase_ : Tuple=None , lowerCAmelCase_ : Any=None , lowerCAmelCase_ : Dict=True ): if config_path is not None: __lowercase : List[Any] = WavaVecaConformerConfig.from_pretrained(lowerCAmelCase_ , hidden_act="""swish""" ) else: __lowercase : List[Any] = WavaVecaConformerConfig() if "rope" in checkpoint_path: __lowercase : Tuple = """rotary""" if is_finetuned: if dict_path: __lowercase : Any = Dictionary.load(lowerCAmelCase_ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __lowercase : List[Any] = target_dict.pad_index __lowercase : Optional[int] = target_dict.bos_index __lowercase : List[Any] = target_dict.eos_index __lowercase : List[str] = len(target_dict.symbols ) __lowercase : Union[str, Any] = os.path.join(lowerCAmelCase_ , """vocab.json""" ) if not os.path.isdir(lowerCAmelCase_ ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(lowerCAmelCase_ ) ) return os.makedirs(lowerCAmelCase_ , exist_ok=lowerCAmelCase_ ) __lowercase : Tuple = target_dict.indices # fairseq has the <pad> and <s> switched __lowercase : int = 0 __lowercase : Any = 1 with open(lowerCAmelCase_ , """w""" , encoding="""utf-8""" ) as vocab_handle: json.dump(lowerCAmelCase_ , lowerCAmelCase_ ) __lowercase : Dict = WavaVecaCTCTokenizer( lowerCAmelCase_ , 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=lowerCAmelCase_ , ) __lowercase : List[Any] = True if config.feat_extract_norm == """layer""" else False __lowercase : Optional[Any] = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=lowerCAmelCase_ , return_attention_mask=lowerCAmelCase_ , ) __lowercase : Optional[int] = WavaVecaProcessor(feature_extractor=lowerCAmelCase_ , tokenizer=lowerCAmelCase_ ) processor.save_pretrained(lowerCAmelCase_ ) __lowercase : Union[str, Any] = WavaVecaConformerForCTC(lowerCAmelCase_ ) else: __lowercase : Optional[Any] = WavaVecaConformerForPreTraining(lowerCAmelCase_ ) if is_finetuned: __lowercase , __lowercase , __lowercase : Optional[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] )} ) else: __lowercase : List[Any] = argparse.Namespace(task="""audio_pretraining""" ) __lowercase : Optional[Any] = fairseq.tasks.setup_task(lowerCAmelCase_ ) __lowercase , __lowercase , __lowercase : List[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] , task=lowerCAmelCase_ ) __lowercase : Dict = model[0].eval() recursively_load_weights(lowerCAmelCase_ , lowerCAmelCase_ , not is_finetuned ) hf_wavavec.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": lowerCamelCase : int = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) lowerCamelCase : Any = parser.parse_args() convert_wavaveca_conformer_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
306
0
"""simple docstring""" import warnings from ...utils import logging from .image_processing_deformable_detr import DeformableDetrImageProcessor snake_case_ = logging.get_logger(__name__) class A_ ( SCREAMING_SNAKE_CASE_ ): """simple docstring""" def __init__( self :Tuple , *lowercase_ :Any , **lowercase_ :str ) -> None: warnings.warn( 'The class DeformableDetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use DeformableDetrImageProcessor instead.' , lowercase_ , ) super().__init__(*lowercase_ , **lowercase_ )
78
"""simple docstring""" import json import logging import os import socket import git import numpy as np import torch logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO, ) snake_case_ = logging.getLogger(__name__) def _lowerCAmelCase ( lowercase_ ): UpperCAmelCase = git.Repo(search_parent_directories=lowercase_ ) UpperCAmelCase = { 'repo_id': str(lowercase_ ), 'repo_sha': str(repo.head.object.hexsha ), 'repo_branch': str(repo.active_branch ), } with open(os.path.join(lowercase_ , 'git_log.json' ) , 'w' ) as f: json.dump(lowercase_ , lowercase_ , indent=4 ) def _lowerCAmelCase ( lowercase_ ): if params.n_gpu <= 0: UpperCAmelCase = 0 UpperCAmelCase = -1 UpperCAmelCase = True UpperCAmelCase = False return assert torch.cuda.is_available() logger.info('Initializing GPUs' ) if params.n_gpu > 1: assert params.local_rank != -1 UpperCAmelCase = int(os.environ['WORLD_SIZE'] ) UpperCAmelCase = int(os.environ['N_GPU_NODE'] ) UpperCAmelCase = int(os.environ['RANK'] ) # number of nodes / node ID UpperCAmelCase = params.world_size // params.n_gpu_per_node UpperCAmelCase = params.global_rank // params.n_gpu_per_node UpperCAmelCase = True assert params.n_nodes == int(os.environ['N_NODES'] ) assert params.node_id == int(os.environ['NODE_RANK'] ) # local job (single GPU) else: assert params.local_rank == -1 UpperCAmelCase = 1 UpperCAmelCase = 0 UpperCAmelCase = 0 UpperCAmelCase = 0 UpperCAmelCase = 1 UpperCAmelCase = 1 UpperCAmelCase = False # sanity checks assert params.n_nodes >= 1 assert 0 <= params.node_id < params.n_nodes assert 0 <= params.local_rank <= params.global_rank < params.world_size assert params.world_size == params.n_nodes * params.n_gpu_per_node # define whether this is the master process / if we are in multi-node distributed mode UpperCAmelCase = params.node_id == 0 and params.local_rank == 0 UpperCAmelCase = params.n_nodes > 1 # summary UpperCAmelCase = F"""--- Global rank: {params.global_rank} - """ logger.info(PREFIX + 'Number of nodes: %i' % params.n_nodes ) logger.info(PREFIX + 'Node ID : %i' % params.node_id ) logger.info(PREFIX + 'Local rank : %i' % params.local_rank ) logger.info(PREFIX + 'World size : %i' % params.world_size ) logger.info(PREFIX + 'GPUs per node : %i' % params.n_gpu_per_node ) logger.info(PREFIX + 'Master : %s' % str(params.is_master ) ) logger.info(PREFIX + 'Multi-node : %s' % str(params.multi_node ) ) logger.info(PREFIX + 'Multi-GPU : %s' % str(params.multi_gpu ) ) logger.info(PREFIX + 'Hostname : %s' % socket.gethostname() ) # set GPU device torch.cuda.set_device(params.local_rank ) # initialize multi-GPU if params.multi_gpu: logger.info('Initializing PyTorch distributed' ) torch.distributed.init_process_group( init_method='env://' , backend='nccl' , ) def _lowerCAmelCase ( lowercase_ ): np.random.seed(args.seed ) torch.manual_seed(args.seed ) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed )
78
1
"""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 ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_outputs import ( BaseModelOutputWithNoAttention, BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention, ) from ...modeling_utils import PreTrainedModel from ...utils import logging from .configuration_regnet import RegNetConfig _lowercase : List[str] = logging.get_logger(__name__) # General docstring _lowercase : Union[str, Any] = "RegNetConfig" # Base docstring _lowercase : Optional[Any] = "facebook/regnet-y-040" _lowercase : List[str] = [1, 1_0_8_8, 7, 7] # Image classification docstring _lowercase : List[Any] = "facebook/regnet-y-040" _lowercase : Any = "tabby, tabby cat" _lowercase : List[Any] = [ "facebook/regnet-y-040", # See all regnet models at https://huggingface.co/models?filter=regnet ] class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Optional[Any], lowerCamelCase : int, lowerCamelCase : int, lowerCamelCase : int = 3, lowerCamelCase : int = 1, lowerCamelCase : int = 1, lowerCamelCase : Optional[str] = "relu", )-> Dict: super().__init__() lowerCamelCase__ : str =nn.Convad( lowerCamelCase, lowerCamelCase, kernel_size=lowerCamelCase, stride=lowerCamelCase, padding=kernel_size // 2, groups=lowerCamelCase, bias=lowerCamelCase, ) lowerCamelCase__ : str =nn.BatchNormad(lowerCamelCase ) lowerCamelCase__ : Dict =ACTaFN[activation] if activation is not None else nn.Identity() def snake_case ( self : Any, lowerCamelCase : List[str] )-> Optional[Any]: lowerCamelCase__ : Optional[int] =self.convolution(lowerCamelCase ) lowerCamelCase__ : List[str] =self.normalization(lowerCamelCase ) lowerCamelCase__ : int =self.activation(lowerCamelCase ) return hidden_state class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Tuple, lowerCamelCase : RegNetConfig )-> Tuple: super().__init__() lowerCamelCase__ : List[Any] =RegNetConvLayer( config.num_channels, config.embedding_size, kernel_size=3, stride=2, activation=config.hidden_act ) lowerCamelCase__ : Union[str, Any] =config.num_channels def snake_case ( self : Optional[int], lowerCamelCase : Optional[Any] )-> int: lowerCamelCase__ : Dict =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.''' ) lowerCamelCase__ : int =self.embedder(lowerCamelCase ) return hidden_state class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Dict, lowerCamelCase : int, lowerCamelCase : int, lowerCamelCase : int = 2 )-> Any: super().__init__() lowerCamelCase__ : Dict =nn.Convad(lowerCamelCase, lowerCamelCase, kernel_size=1, stride=lowerCamelCase, bias=lowerCamelCase ) lowerCamelCase__ : Optional[int] =nn.BatchNormad(lowerCamelCase ) def snake_case ( self : int, lowerCamelCase : Tensor )-> Tensor: lowerCamelCase__ : List[str] =self.convolution(lowerCamelCase ) lowerCamelCase__ : str =self.normalization(lowerCamelCase ) return hidden_state class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Tuple, lowerCamelCase : int, lowerCamelCase : int )-> Optional[Any]: super().__init__() lowerCamelCase__ : List[str] =nn.AdaptiveAvgPoolad((1, 1) ) lowerCamelCase__ : List[Any] =nn.Sequential( nn.Convad(lowerCamelCase, lowerCamelCase, kernel_size=1 ), nn.ReLU(), nn.Convad(lowerCamelCase, lowerCamelCase, kernel_size=1 ), nn.Sigmoid(), ) def snake_case ( self : Dict, lowerCamelCase : Optional[int] )-> str: # b c h w -> b c 1 1 lowerCamelCase__ : Optional[int] =self.pooler(lowerCamelCase ) lowerCamelCase__ : Union[str, Any] =self.attention(lowerCamelCase ) lowerCamelCase__ : Optional[int] =hidden_state * attention return hidden_state class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : str, lowerCamelCase : RegNetConfig, lowerCamelCase : int, lowerCamelCase : int, lowerCamelCase : int = 1 )-> Optional[int]: super().__init__() lowerCamelCase__ : Any =in_channels != out_channels or stride != 1 lowerCamelCase__ : Optional[Any] =max(1, out_channels // config.groups_width ) lowerCamelCase__ : Any =( RegNetShortCut(lowerCamelCase, lowerCamelCase, stride=lowerCamelCase ) if should_apply_shortcut else nn.Identity() ) lowerCamelCase__ : Optional[Any] =nn.Sequential( RegNetConvLayer(lowerCamelCase, lowerCamelCase, kernel_size=1, activation=config.hidden_act ), RegNetConvLayer(lowerCamelCase, lowerCamelCase, stride=lowerCamelCase, groups=lowerCamelCase, activation=config.hidden_act ), RegNetConvLayer(lowerCamelCase, lowerCamelCase, kernel_size=1, activation=lowerCamelCase ), ) lowerCamelCase__ : str =ACTaFN[config.hidden_act] def snake_case ( self : Union[str, Any], lowerCamelCase : str )-> List[Any]: lowerCamelCase__ : Any =hidden_state lowerCamelCase__ : Optional[Any] =self.layer(lowerCamelCase ) lowerCamelCase__ : Dict =self.shortcut(lowerCamelCase ) hidden_state += residual lowerCamelCase__ : str =self.activation(lowerCamelCase ) return hidden_state class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : int, lowerCamelCase : RegNetConfig, lowerCamelCase : int, lowerCamelCase : int, lowerCamelCase : int = 1 )-> Any: super().__init__() lowerCamelCase__ : Optional[Any] =in_channels != out_channels or stride != 1 lowerCamelCase__ : Any =max(1, out_channels // config.groups_width ) lowerCamelCase__ : Dict =( RegNetShortCut(lowerCamelCase, lowerCamelCase, stride=lowerCamelCase ) if should_apply_shortcut else nn.Identity() ) lowerCamelCase__ : Dict =nn.Sequential( RegNetConvLayer(lowerCamelCase, lowerCamelCase, kernel_size=1, activation=config.hidden_act ), RegNetConvLayer(lowerCamelCase, lowerCamelCase, stride=lowerCamelCase, groups=lowerCamelCase, activation=config.hidden_act ), RegNetSELayer(lowerCamelCase, reduced_channels=int(round(in_channels / 4 ) ) ), RegNetConvLayer(lowerCamelCase, lowerCamelCase, kernel_size=1, activation=lowerCamelCase ), ) lowerCamelCase__ : Optional[int] =ACTaFN[config.hidden_act] def snake_case ( self : str, lowerCamelCase : int )-> Dict: lowerCamelCase__ : Dict =hidden_state lowerCamelCase__ : Any =self.layer(lowerCamelCase ) lowerCamelCase__ : Optional[Any] =self.shortcut(lowerCamelCase ) hidden_state += residual lowerCamelCase__ : Tuple =self.activation(lowerCamelCase ) return hidden_state class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : Any, lowerCamelCase : RegNetConfig, lowerCamelCase : int, lowerCamelCase : int, lowerCamelCase : int = 2, lowerCamelCase : int = 2, )-> List[Any]: super().__init__() lowerCamelCase__ : Optional[int] =RegNetXLayer if config.layer_type == '''x''' else RegNetYLayer lowerCamelCase__ : Optional[Any] =nn.Sequential( # downsampling is done in the first layer with stride of 2 layer( lowerCamelCase, lowerCamelCase, lowerCamelCase, stride=lowerCamelCase, ), *[layer(lowerCamelCase, lowerCamelCase, lowerCamelCase ) for _ in range(depth - 1 )], ) def snake_case ( self : List[str], lowerCamelCase : int )-> Optional[Any]: lowerCamelCase__ : Optional[Any] =self.layers(lowerCamelCase ) return hidden_state class __SCREAMING_SNAKE_CASE ( nn.Module ): '''simple docstring''' def __init__( self : int, lowerCamelCase : RegNetConfig )-> Union[str, Any]: super().__init__() lowerCamelCase__ : Optional[Any] =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( RegNetStage( lowerCamelCase, config.embedding_size, config.hidden_sizes[0], stride=2 if config.downsample_in_first_stage else 1, depth=config.depths[0], ) ) lowerCamelCase__ : List[Any] =zip(config.hidden_sizes, config.hidden_sizes[1:] ) for (in_channels, out_channels), depth in zip(lowerCamelCase, config.depths[1:] ): self.stages.append(RegNetStage(lowerCamelCase, lowerCamelCase, lowerCamelCase, depth=lowerCamelCase ) ) def snake_case ( self : Union[str, Any], lowerCamelCase : Tensor, lowerCamelCase : bool = False, lowerCamelCase : bool = True )-> BaseModelOutputWithNoAttention: lowerCamelCase__ : Union[str, Any] =() if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: lowerCamelCase__ : Tuple =hidden_states + (hidden_state,) lowerCamelCase__ : List[Any] =stage_module(lowerCamelCase ) if output_hidden_states: lowerCamelCase__ : List[Any] =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 __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ): '''simple docstring''' _a = RegNetConfig _a = 'regnet' _a = 'pixel_values' _a = True def snake_case ( self : Optional[Any], lowerCamelCase : Optional[Any] )-> List[Any]: 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 snake_case ( self : Optional[int], lowerCamelCase : Any, lowerCamelCase : str=False )-> Union[str, Any]: if isinstance(lowerCamelCase, lowerCamelCase ): lowerCamelCase__ : List[str] =value _lowercase : int = r"\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n" _lowercase : Optional[int] = r"\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConvNextImageProcessor.__call__`] for details.\n\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.\n" @add_start_docstrings( 'The bare RegNet model outputting raw features without any specific head on top.' , lowerCAmelCase_ , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Optional[int], lowerCamelCase : Dict )-> Tuple: super().__init__(lowerCamelCase ) lowerCamelCase__ : Optional[int] =config lowerCamelCase__ : Union[str, Any] =RegNetEmbeddings(lowerCamelCase ) lowerCamelCase__ : Tuple =RegNetEncoder(lowerCamelCase ) lowerCamelCase__ : Any =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 snake_case ( self : int, lowerCamelCase : Tensor, lowerCamelCase : Optional[bool] = None, lowerCamelCase : Optional[bool] = None )-> BaseModelOutputWithPoolingAndNoAttention: lowerCamelCase__ : int =( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCamelCase__ : Optional[int] =return_dict if return_dict is not None else self.config.use_return_dict lowerCamelCase__ : Optional[int] =self.embedder(lowerCamelCase ) lowerCamelCase__ : Tuple =self.encoder( lowerCamelCase, output_hidden_states=lowerCamelCase, return_dict=lowerCamelCase ) lowerCamelCase__ : Dict =encoder_outputs[0] lowerCamelCase__ : str =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( '\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , lowerCAmelCase_ , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet class __SCREAMING_SNAKE_CASE ( lowerCAmelCase_ ): '''simple docstring''' def __init__( self : Optional[int], lowerCamelCase : List[Any] )-> Optional[int]: super().__init__(lowerCamelCase ) lowerCamelCase__ : Dict =config.num_labels lowerCamelCase__ : Union[str, Any] =RegNetModel(lowerCamelCase ) # classification head lowerCamelCase__ : Optional[int] =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 snake_case ( self : Optional[Any], lowerCamelCase : Optional[torch.FloatTensor] = None, lowerCamelCase : Optional[torch.LongTensor] = None, lowerCamelCase : Optional[bool] = None, lowerCamelCase : Optional[bool] = None, )-> ImageClassifierOutputWithNoAttention: lowerCamelCase__ : str =return_dict if return_dict is not None else self.config.use_return_dict lowerCamelCase__ : List[Any] =self.regnet(lowerCamelCase, output_hidden_states=lowerCamelCase, return_dict=lowerCamelCase ) lowerCamelCase__ : List[Any] =outputs.pooler_output if return_dict else outputs[1] lowerCamelCase__ : Tuple =self.classifier(lowerCamelCase ) lowerCamelCase__ : Dict =None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: lowerCamelCase__ : int ='''regression''' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): lowerCamelCase__ : List[Any] ='''single_label_classification''' else: lowerCamelCase__ : Dict ='''multi_label_classification''' if self.config.problem_type == "regression": lowerCamelCase__ : Optional[int] =MSELoss() if self.num_labels == 1: lowerCamelCase__ : List[str] =loss_fct(logits.squeeze(), labels.squeeze() ) else: lowerCamelCase__ : int =loss_fct(lowerCamelCase, lowerCamelCase ) elif self.config.problem_type == "single_label_classification": lowerCamelCase__ : List[Any] =CrossEntropyLoss() lowerCamelCase__ : Optional[int] =loss_fct(logits.view(-1, self.num_labels ), labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": lowerCamelCase__ : Union[str, Any] =BCEWithLogitsLoss() lowerCamelCase__ : Optional[Any] =loss_fct(lowerCamelCase, lowerCamelCase ) if not return_dict: lowerCamelCase__ : Dict =(logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=lowerCamelCase, logits=lowerCamelCase, hidden_states=outputs.hidden_states )
272
"""simple docstring""" from typing import List import jiwer import jiwer.transforms as tr from packaging import version import datasets from datasets.config import PY_VERSION if PY_VERSION < version.parse("3.8"): import importlib_metadata else: import importlib.metadata as importlib_metadata _lowercase : List[str] = "" if version.parse(importlib_metadata.version("jiwer")) < version.parse("2.3.0"): class __SCREAMING_SNAKE_CASE ( tr.AbstractTransform ): '''simple docstring''' def __init__( self : List[Any], lowerCamelCase : str = " " )-> List[str]: lowerCamelCase__ : List[str] =sentence_delimiter def snake_case ( self : Any, lowerCamelCase : str )-> Optional[Any]: return list(lowerCamelCase ) def snake_case ( self : Optional[Any], lowerCamelCase : List[str] )-> Tuple: lowerCamelCase__ : Optional[int] =[] for sent_idx, sentence in enumerate(lowerCamelCase ): chars.extend(self.process_string(lowerCamelCase ) ) if self.sentence_delimiter is not None and self.sentence_delimiter != "" and sent_idx < len(lowerCamelCase ) - 1: chars.append(self.sentence_delimiter ) return chars _lowercase : Optional[int] = tr.Compose( [tr.RemoveMultipleSpaces(), tr.Strip(), SentencesToListOfCharacters(SENTENCE_DELIMITER)] ) else: _lowercase : List[str] = tr.Compose( [ tr.RemoveMultipleSpaces(), tr.Strip(), tr.ReduceToSingleSentence(SENTENCE_DELIMITER), tr.ReduceToListOfListOfChars(), ] ) _lowercase : Dict = "\\n@inproceedings{inproceedings,\n author = {Morris, Andrew and Maier, Viktoria and Green, Phil},\n year = {2004},\n month = {01},\n pages = {},\n title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.}\n}\n" _lowercase : List[Any] = "\\nCharacter error rate (CER) is a common metric of the performance of an automatic speech recognition system.\n\nCER is similar to Word Error Rate (WER), but operates on character instead of word. Please refer to docs of WER for further information.\n\nCharacter error rate can be computed as:\n\nCER = (S + D + I) / N = (S + D + I) / (S + D + C)\n\nwhere\n\nS is the number of substitutions,\nD is the number of deletions,\nI is the number of insertions,\nC is the number of correct characters,\nN is the number of characters in the reference (N=S+D+C).\n\nCER's output is not always a number between 0 and 1, in particular when there is a high number of insertions. This value is often associated to the percentage of characters that were incorrectly predicted. The lower the value, the better the\nperformance of the ASR system with a CER of 0 being a perfect score.\n" _lowercase : Dict = "\nComputes CER score of transcribed segments against references.\nArgs:\n references: list of references for each speech input.\n predictions: list of transcribtions to score.\n concatenate_texts: Whether or not to concatenate sentences before evaluation, set to True for more accurate result.\nReturns:\n (float): the character error rate\n\nExamples:\n\n >>> predictions = [\"this is the prediction\", \"there is an other sample\"]\n >>> references = [\"this is the reference\", \"there is another one\"]\n >>> cer = datasets.load_metric(\"cer\")\n >>> cer_score = cer.compute(predictions=predictions, references=references)\n >>> print(cer_score)\n 0.34146341463414637\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __SCREAMING_SNAKE_CASE ( datasets.Metric ): '''simple docstring''' def snake_case ( self : Dict )-> Optional[Any]: return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { '''predictions''': datasets.Value('''string''', id='''sequence''' ), '''references''': datasets.Value('''string''', id='''sequence''' ), } ), codebase_urls=['''https://github.com/jitsi/jiwer/'''], reference_urls=[ '''https://en.wikipedia.org/wiki/Word_error_rate''', '''https://sites.google.com/site/textdigitisation/qualitymeasures/computingerrorrates''', ], ) def snake_case ( self : Optional[Any], lowerCamelCase : Union[str, Any], lowerCamelCase : List[str], lowerCamelCase : Dict=False )-> List[Any]: if concatenate_texts: return jiwer.compute_measures( lowerCamelCase, lowerCamelCase, truth_transform=lowerCamelCase, hypothesis_transform=lowerCamelCase, )["wer"] lowerCamelCase__ : Optional[Any] =0 lowerCamelCase__ : Union[str, Any] =0 for prediction, reference in zip(lowerCamelCase, lowerCamelCase ): lowerCamelCase__ : int =jiwer.compute_measures( lowerCamelCase, lowerCamelCase, truth_transform=lowerCamelCase, hypothesis_transform=lowerCamelCase, ) incorrect += measures["substitutions"] + measures["deletions"] + measures["insertions"] total += measures["substitutions"] + measures["deletions"] + measures["hits"] return incorrect / total
272
1
import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing the experiment tracking capability, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## a_ = 16 a_ = 32 def _a ( UpperCamelCase_ : Accelerator , UpperCamelCase_ : int = 16 ) -> Dict: """simple docstring""" lowerCAmelCase__ = AutoTokenizer.from_pretrained("bert-base-cased" ) lowerCAmelCase__ = load_dataset("glue" , "mrpc" ) def tokenize_function(UpperCamelCase_ : Any ): # max_length=None => use the model max length (it's actually the default) lowerCAmelCase__ = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=UpperCamelCase_ , max_length=UpperCamelCase_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): lowerCAmelCase__ = datasets.map( UpperCamelCase_ , batched=UpperCamelCase_ , remove_columns=["idx", "sentence1", "sentence2"] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library lowerCAmelCase__ = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(UpperCamelCase_ : List[str] ): # On TPU it's best to pad everything to the same length or training will be very slow. lowerCAmelCase__ = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": lowerCAmelCase__ = 16 elif accelerator.mixed_precision != "no": lowerCAmelCase__ = 8 else: lowerCAmelCase__ = None return tokenizer.pad( UpperCamelCase_ , padding="longest" , max_length=UpperCamelCase_ , pad_to_multiple_of=UpperCamelCase_ , return_tensors="pt" , ) # Instantiate dataloaders. lowerCAmelCase__ = DataLoader( tokenized_datasets["train"] , shuffle=UpperCamelCase_ , collate_fn=UpperCamelCase_ , batch_size=UpperCamelCase_ ) lowerCAmelCase__ = DataLoader( tokenized_datasets["validation"] , shuffle=UpperCamelCase_ , collate_fn=UpperCamelCase_ , batch_size=UpperCamelCase_ ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('''TESTING_MOCKED_DATALOADERS''', None) == "1": from accelerate.test_utils.training import mocked_dataloaders a_ = mocked_dataloaders # noqa: F811 def _a ( UpperCamelCase_ : Any , UpperCamelCase_ : Tuple ) -> str: """simple docstring""" if os.environ.get("TESTING_MOCKED_DATALOADERS" , UpperCamelCase_ ) == "1": lowerCAmelCase__ = 2 # Initialize Accelerator # New Code # # We pass in "all" to `log_with` to grab all available trackers in the environment # Note: If using a custom `Tracker` class, should be passed in here such as: # >>> log_with = ["all", MyCustomTrackerClassInstance()] if args.with_tracking: lowerCAmelCase__ = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with="all" , project_dir=args.project_dir ) else: lowerCAmelCase__ = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs lowerCAmelCase__ = config["lr"] lowerCAmelCase__ = int(config["num_epochs"] ) lowerCAmelCase__ = int(config["seed"] ) lowerCAmelCase__ = int(config["batch_size"] ) set_seed(UpperCamelCase_ ) lowerCAmelCase__ , lowerCAmelCase__ = get_dataloaders(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase__ = evaluate.load("glue" , "mrpc" ) # If the batch size is too big we use gradient accumulation lowerCAmelCase__ = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: lowerCAmelCase__ = batch_size // MAX_GPU_BATCH_SIZE lowerCAmelCase__ = MAX_GPU_BATCH_SIZE # Instantiate the model (we build the model here so that the seed also control new weights initialization) lowerCAmelCase__ = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=UpperCamelCase_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). lowerCAmelCase__ = model.to(accelerator.device ) # Instantiate optimizer lowerCAmelCase__ = AdamW(params=model.parameters() , lr=UpperCamelCase_ ) # Instantiate scheduler lowerCAmelCase__ = get_linear_schedule_with_warmup( optimizer=UpperCamelCase_ , num_warmup_steps=100 , num_training_steps=(len(UpperCamelCase_ ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = accelerator.prepare( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # New Code # # We need to initialize the trackers we use. Overall configurations can also be stored if args.with_tracking: lowerCAmelCase__ = os.path.split(UpperCamelCase_ )[-1].split("." )[0] accelerator.init_trackers(UpperCamelCase_ , UpperCamelCase_ ) # Now we train the model for epoch in range(UpperCamelCase_ ): model.train() # New Code # # For our tracking example, we will log the total loss of each epoch if args.with_tracking: lowerCAmelCase__ = 0 for step, batch in enumerate(UpperCamelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) lowerCAmelCase__ = model(**UpperCamelCase_ ) lowerCAmelCase__ = outputs.loss # New Code # if args.with_tracking: total_loss += loss.detach().float() lowerCAmelCase__ = loss / gradient_accumulation_steps accelerator.backward(UpperCamelCase_ ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(UpperCamelCase_ ): # We could avoid this line since we set the accelerator with `device_placement=True` (the default). batch.to(accelerator.device ) with torch.no_grad(): lowerCAmelCase__ = model(**UpperCamelCase_ ) lowerCAmelCase__ = outputs.logits.argmax(dim=-1 ) lowerCAmelCase__ , lowerCAmelCase__ = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=UpperCamelCase_ , references=UpperCamelCase_ , ) lowerCAmelCase__ = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(F"epoch {epoch}:" , UpperCamelCase_ ) # New Code # # To actually log, we call `Accelerator.log` # The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int` if args.with_tracking: accelerator.log( { "accuracy": eval_metric["accuracy"], "f1": eval_metric["f1"], "train_loss": total_loss.item() / len(UpperCamelCase_ ), "epoch": epoch, } , step=UpperCamelCase_ , ) # New Code # # When a run is finished, you should call `accelerator.end_training()` # to close all of the open trackers if args.with_tracking: accelerator.end_training() def _a ( ) -> Union[str, Any]: """simple docstring""" lowerCAmelCase__ = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=UpperCamelCase_ , default=UpperCamelCase_ , choices=["no", "fp16", "bf16", "fp8"] , help="Whether to use mixed precision. Choose" "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." "and an Nvidia Ampere GPU." , ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) parser.add_argument( "--with_tracking" , action="store_true" , help="Whether to load in all available experiment trackers from the environment and use them for logging." , ) parser.add_argument( "--project_dir" , type=UpperCamelCase_ , default="logs" , help="Location on where to store experiment tracking logs` and relevent project information" , ) lowerCAmelCase__ = parser.parse_args() lowerCAmelCase__ = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(UpperCamelCase_ , UpperCamelCase_ ) if __name__ == "__main__": main()
340
'''simple docstring''' # Copyright (c) 2021-, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #################################################################################################### # # Note: If when running this conversion script you're getting an exception: # ModuleNotFoundError: No module named 'megatron.model.enums' # you need to tell python where to find the clone of Megatron-LM, e.g.: # # cd /tmp # git clone https://github.com/NVIDIA/Megatron-LM # PYTHONPATH=/tmp/Megatron-LM python src/transformers/models/megatron_gpt2/convert_megatron_gpt2_checkpoint.py ... # # if you already have it cloned elsewhere, simply adjust the path to the existing path # # If the training was done using a Megatron-LM fork, e.g., # https://github.com/microsoft/Megatron-DeepSpeed/ then chances are that you need to have that one # in your path, i.e., /path/to/Megatron-DeepSpeed/ # import argparse import os import re import zipfile import torch from transformers import AutoTokenizer, GPTaConfig def a_ ( lowerCamelCase : int , lowerCamelCase : Optional[Any] , lowerCamelCase : Union[str, Any]=0 ): # Format the message. if name is None: lowerCAmelCase = None else: lowerCAmelCase = '.' * max(0 , spaces - 2 ) + '# {:' + str(50 - spaces ) + 's}' lowerCAmelCase = fmt.format(lowerCamelCase ) # Print and recurse (if needed). if isinstance(lowerCamelCase , lowerCamelCase ): if msg is not None: print(lowerCamelCase ) for k in val.keys(): recursive_print(lowerCamelCase , val[k] , spaces + 2 ) elif isinstance(lowerCamelCase , torch.Tensor ): print(lowerCamelCase , ':' , val.size() ) else: print(lowerCamelCase , ':' , lowerCamelCase ) def a_ ( lowerCamelCase : Optional[int] , lowerCamelCase : List[str] , lowerCamelCase : List[Any] , lowerCamelCase : Dict , lowerCamelCase : Tuple ): # Permutes layout of param tensor to [num_splits * num_heads * hidden_size, :] # for compatibility with later versions of NVIDIA Megatron-LM. # The inverse operation is performed inside Megatron-LM to read checkpoints: # https://github.com/NVIDIA/Megatron-LM/blob/v2.4/megatron/checkpointing.py#L209 # If param is the weight tensor of the self-attention block, the returned tensor # will have to be transposed one more time to be read by HuggingFace GPT2. lowerCAmelCase = param.size() if checkpoint_version == 1.0: # version 1.0 stores [num_heads * hidden_size * num_splits, :] lowerCAmelCase = (num_heads, hidden_size, num_splits) + input_shape[1:] lowerCAmelCase = param.view(*lowerCamelCase ) lowerCAmelCase = param.transpose(0 , 2 ) lowerCAmelCase = param.transpose(1 , 2 ).contiguous() elif checkpoint_version >= 2.0: # other versions store [num_heads * num_splits * hidden_size, :] lowerCAmelCase = (num_heads, num_splits, hidden_size) + input_shape[1:] lowerCAmelCase = param.view(*lowerCamelCase ) lowerCAmelCase = param.transpose(0 , 1 ).contiguous() lowerCAmelCase = param.view(*lowerCamelCase ) return param def a_ ( lowerCamelCase : Optional[int] , lowerCamelCase : Optional[int] , lowerCamelCase : str ): # The converted output model. lowerCAmelCase = {} # old versions did not store training args lowerCAmelCase = input_state_dict.get('args' , lowerCamelCase ) if ds_args is not None: # do not make the user write a config file when the exact dimensions/sizes are already in the checkpoint # from pprint import pprint # pprint(vars(ds_args)) lowerCAmelCase = ds_args.padded_vocab_size lowerCAmelCase = ds_args.max_position_embeddings lowerCAmelCase = ds_args.hidden_size lowerCAmelCase = ds_args.num_layers lowerCAmelCase = ds_args.num_attention_heads lowerCAmelCase = ds_args.ffn_hidden_size # pprint(config) # The number of heads. lowerCAmelCase = config.n_head # The hidden_size per head. lowerCAmelCase = config.n_embd // config.n_head # Megatron-LM checkpoint version if "checkpoint_version" in input_state_dict.keys(): lowerCAmelCase = input_state_dict['checkpoint_version'] else: lowerCAmelCase = 0.0 # The model. lowerCAmelCase = input_state_dict['model'] # The language model. lowerCAmelCase = model['language_model'] # The embeddings. lowerCAmelCase = lm['embedding'] # The word embeddings. lowerCAmelCase = embeddings['word_embeddings']['weight'] # Truncate the embedding table to vocab_size rows. lowerCAmelCase = word_embeddings[: config.vocab_size, :] lowerCAmelCase = word_embeddings # The position embeddings. lowerCAmelCase = embeddings['position_embeddings']['weight'] # Read the causal mask dimension (seqlen). [max_sequence_length, hidden_size] lowerCAmelCase = pos_embeddings.size(0 ) if n_positions != config.n_positions: raise ValueError( f'''pos_embeddings.max_sequence_length={n_positions} and config.n_positions={config.n_positions} don\'t match''' ) # Store the position embeddings. lowerCAmelCase = pos_embeddings # The transformer. lowerCAmelCase = lm['transformer'] if 'transformer' in lm.keys() else lm['encoder'] # The regex to extract layer names. lowerCAmelCase = re.compile(R'layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)' ) # The simple map of names for "automated" rules. lowerCAmelCase = { 'attention.dense': '.attn.c_proj.', 'self_attention.dense': '.attn.c_proj.', 'mlp.dense_h_to_4h': '.mlp.c_fc.', 'mlp.dense_4h_to_h': '.mlp.c_proj.', } # Extract the layers. for key, val in transformer.items(): # Match the name. lowerCAmelCase = layer_re.match(lowerCamelCase ) # Stop if that's not a layer if m is None: break # The index of the layer. lowerCAmelCase = int(m.group(1 ) ) # The name of the operation. lowerCAmelCase = m.group(2 ) # Is it a weight or a bias? lowerCAmelCase = m.group(3 ) # The name of the layer. lowerCAmelCase = f'''transformer.h.{layer_idx}''' # For layernorm(s), simply store the layer norm. if op_name.endswith('layernorm' ): lowerCAmelCase = 'ln_1' if op_name.startswith('input' ) else 'ln_2' lowerCAmelCase = val # Transpose the QKV matrix. elif ( op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value" ) and weight_or_bias == "weight": # Insert a tensor of 1x1xDxD bias. lowerCAmelCase = torch.tril(torch.ones((n_positions, n_positions) , dtype=torch.floataa ) ).view( 1 , 1 , lowerCamelCase , lowerCamelCase ) lowerCAmelCase = causal_mask # Insert a "dummy" tensor for masked_bias. lowerCAmelCase = torch.tensor(-1e4 , dtype=torch.floataa ) lowerCAmelCase = masked_bias lowerCAmelCase = fix_query_key_value_ordering(lowerCamelCase , lowerCamelCase , 3 , lowerCamelCase , lowerCamelCase ) # Megatron stores (3*D) x D but transformers-GPT2 expects D x 3*D. lowerCAmelCase = out_val.transpose(0 , 1 ).contiguous() # Store. lowerCAmelCase = out_val # Transpose the bias. elif ( op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value" ) and weight_or_bias == "bias": lowerCAmelCase = fix_query_key_value_ordering(lowerCamelCase , lowerCamelCase , 3 , lowerCamelCase , lowerCamelCase ) # Store. No change of shape. lowerCAmelCase = out_val # Transpose the weights. elif weight_or_bias == "weight": lowerCAmelCase = megatron_to_transformers[op_name] lowerCAmelCase = val.transpose(0 , 1 ) # Copy the bias. elif weight_or_bias == "bias": lowerCAmelCase = megatron_to_transformers[op_name] lowerCAmelCase = val # DEBUG. assert config.n_layer == layer_idx + 1 # The final layernorm. lowerCAmelCase = transformer['final_layernorm.weight'] lowerCAmelCase = transformer['final_layernorm.bias'] # For LM head, transformers' wants the matrix to weight embeddings. lowerCAmelCase = word_embeddings # It should be done! return output_state_dict def a_ ( ): # Create the argument parser. lowerCAmelCase = argparse.ArgumentParser() parser.add_argument('--print-checkpoint-structure' , action='store_true' ) parser.add_argument( 'path_to_checkpoint' , type=lowerCamelCase , help='Path to the checkpoint file (.zip archive or direct .pt file)' , ) parser.add_argument( '--config_file' , default='' , type=lowerCamelCase , help='An optional config json file describing the pre-trained model.' , ) lowerCAmelCase = parser.parse_args() # Extract the basename. lowerCAmelCase = os.path.dirname(args.path_to_checkpoint ) # Load the model. # the .zip is very optional, let's keep it for backward compatibility print(f'''Extracting PyTorch state dictionary from {args.path_to_checkpoint}''' ) if args.path_to_checkpoint.endswith('.zip' ): with zipfile.ZipFile(args.path_to_checkpoint , 'r' ) as checkpoint: with checkpoint.open('release/mp_rank_00/model_optim_rng.pt' ) as pytorch_dict: lowerCAmelCase = torch.load(lowerCamelCase , map_location='cpu' ) else: lowerCAmelCase = torch.load(args.path_to_checkpoint , map_location='cpu' ) lowerCAmelCase = input_state_dict.get('args' , lowerCamelCase ) # Read the config, or default to the model released by NVIDIA. if args.config_file == "": if ds_args is not None: if ds_args.bias_gelu_fusion: lowerCAmelCase = 'gelu_fast' elif ds_args.openai_gelu: lowerCAmelCase = 'gelu_new' else: lowerCAmelCase = 'gelu' else: # in the very early days this used to be "gelu_new" lowerCAmelCase = 'gelu_new' # Spell out all parameters in case the defaults change. lowerCAmelCase = GPTaConfig( vocab_size=50257 , n_positions=1024 , n_embd=1024 , n_layer=24 , n_head=16 , n_inner=4096 , activation_function=lowerCamelCase , resid_pdrop=0.1 , embd_pdrop=0.1 , attn_pdrop=0.1 , layer_norm_epsilon=1e-5 , initializer_range=0.02 , summary_type='cls_index' , summary_use_proj=lowerCamelCase , summary_activation=lowerCamelCase , summary_proj_to_labels=lowerCamelCase , summary_first_dropout=0.1 , scale_attn_weights=lowerCamelCase , use_cache=lowerCamelCase , bos_token_id=50256 , eos_token_id=50256 , ) else: lowerCAmelCase = GPTaConfig.from_json_file(args.config_file ) lowerCAmelCase = ['GPT2LMHeadModel'] # Convert. print('Converting' ) lowerCAmelCase = convert_megatron_checkpoint(lowerCamelCase , lowerCamelCase , lowerCamelCase ) # Print the structure of converted state dict. if args.print_checkpoint_structure: recursive_print(lowerCamelCase , lowerCamelCase ) # Add tokenizer class info to config # see https://github.com/huggingface/transformers/issues/13906) if ds_args is not None: lowerCAmelCase = ds_args.tokenizer_type if tokenizer_type == "GPT2BPETokenizer": lowerCAmelCase = 'gpt2' elif tokenizer_type == "PretrainedFromHF": lowerCAmelCase = ds_args.tokenizer_name_or_path else: raise ValueError(f'''Unrecognized tokenizer_type {tokenizer_type}''' ) else: lowerCAmelCase = 'gpt2' lowerCAmelCase = AutoTokenizer.from_pretrained(lowerCamelCase ) lowerCAmelCase = type(lowerCamelCase ).__name__ lowerCAmelCase = tokenizer_class # Store the config to file. print('Saving config' ) config.save_pretrained(lowerCamelCase ) # Save tokenizer based on args print(f'''Adding {tokenizer_class} tokenizer files''' ) tokenizer.save_pretrained(lowerCamelCase ) # Store the state_dict to file. lowerCAmelCase = os.path.join(lowerCamelCase , 'pytorch_model.bin' ) print(f'''Saving checkpoint to "{output_checkpoint_file}"''' ) torch.save(lowerCamelCase , lowerCamelCase ) #################################################################################################### if __name__ == "__main__": main() ####################################################################################################
4
0
'''simple docstring''' from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional from packaging import version if TYPE_CHECKING: from ... import PreTrainedTokenizer, TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast, PatchingSpec from ...utils import is_torch_available, logging __a = logging.get_logger(__name__) __a = { "bigscience/bloom": "https://huggingface.co/bigscience/bloom/resolve/main/config.json", "bigscience/bloom-560m": "https://huggingface.co/bigscience/bloom-560m/blob/main/config.json", "bigscience/bloom-1b1": "https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json", "bigscience/bloom-1b7": "https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json", "bigscience/bloom-3b": "https://huggingface.co/bigscience/bloom-3b/blob/main/config.json", "bigscience/bloom-7b1": "https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json", } class UpperCAmelCase_ ( _a ): """simple docstring""" lowercase = "bloom" lowercase = ["past_key_values"] lowercase = { "num_hidden_layers": "n_layer", "num_attention_heads": "n_head", } def __init__( self : str , snake_case_ : Union[str, Any]=250_880 , snake_case_ : Optional[Any]=64 , snake_case_ : Any=2 , snake_case_ : int=8 , snake_case_ : Optional[Any]=1E-5 , snake_case_ : int=0.02 , snake_case_ : Dict=True , snake_case_ : List[Any]=1 , snake_case_ : Tuple=2 , snake_case_ : Any=False , snake_case_ : str=0.0 , snake_case_ : Any=0.0 , snake_case_ : List[str]=1 , snake_case_ : Union[str, Any]=False , **snake_case_ : int , ): snake_case__ : Any = vocab_size # Backward compatibility with n_embed kwarg snake_case__ : Dict = kwargs.pop("""n_embed""" , snake_case_ ) snake_case__ : Union[str, Any] = hidden_size if n_embed is None else n_embed snake_case__ : List[str] = n_layer snake_case__ : Dict = n_head snake_case__ : Any = layer_norm_epsilon snake_case__ : Tuple = initializer_range snake_case__ : Any = use_cache snake_case__ : int = pretraining_tp snake_case__ : List[str] = apply_residual_connection_post_layernorm snake_case__ : Optional[Any] = hidden_dropout snake_case__ : Dict = attention_dropout snake_case__ : List[str] = bos_token_id snake_case__ : Optional[Any] = eos_token_id snake_case__ : Any = slow_but_exact super().__init__(bos_token_id=snake_case_ , eos_token_id=snake_case_ , **snake_case_ ) class UpperCAmelCase_ ( _a ): """simple docstring""" lowercase = version.parse("1.12" ) def __init__( self : Union[str, Any] , snake_case_ : PretrainedConfig , snake_case_ : str = "default" , snake_case_ : List[PatchingSpec] = None , snake_case_ : bool = False , ): super().__init__(snake_case_ , task=snake_case_ , patching_specs=snake_case_ , use_past=snake_case_ ) if not getattr(self._config , """pad_token_id""" , snake_case_ ): # TODO: how to do that better? snake_case__ : Optional[Any] = 0 @property def lowerCamelCase ( self : str ): snake_case__ : Union[str, Any] = OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}} ) if self.use_past: # BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344 self.fill_with_past_key_values_(snake_case_ , direction="""inputs""" , inverted_values_shape=snake_case_ ) snake_case__ : Optional[int] = {0: """batch""", 1: """past_sequence + sequence"""} else: snake_case__ : List[str] = {0: """batch""", 1: """sequence"""} return common_inputs @property def lowerCamelCase ( self : Optional[int] ): return self._config.n_layer @property def lowerCamelCase ( self : Optional[Any] ): return self._config.n_head @property def lowerCamelCase ( self : str ): return 1E-3 def lowerCamelCase ( self : Tuple , snake_case_ : "PreTrainedTokenizer" , snake_case_ : int = -1 , snake_case_ : int = -1 , snake_case_ : bool = False , snake_case_ : Optional["TensorType"] = None , ): snake_case__ : str = super(snake_case_ , self ).generate_dummy_inputs( snake_case_ , batch_size=snake_case_ , seq_length=snake_case_ , is_pair=snake_case_ , framework=snake_case_ ) # We need to order the input in the way they appears in the forward() snake_case__ : List[Any] = OrderedDict({"""input_ids""": common_inputs["""input_ids"""]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch snake_case__ , snake_case__ : Any = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values snake_case__ : Dict = seqlen + 2 snake_case__ : str = self._config.hidden_size // self.num_attention_heads snake_case__ : List[Any] = ( batch * self.num_attention_heads, head_dim, past_key_values_length, ) snake_case__ : Optional[int] = ( batch * self.num_attention_heads, past_key_values_length, head_dim, ) snake_case__ : str = [ (torch.zeros(snake_case_ ), torch.zeros(snake_case_ )) for _ in range(self.num_layers ) ] snake_case__ : str = common_inputs["""attention_mask"""] if self.use_past: snake_case__ : Dict = ordered_inputs["""attention_mask"""].dtype snake_case__ : Optional[Any] = torch.cat( [ordered_inputs["""attention_mask"""], torch.ones(snake_case_ , snake_case_ , dtype=snake_case_ )] , dim=1 ) return ordered_inputs @property def lowerCamelCase ( self : Optional[int] ): return 13
43
'''simple docstring''' import unittest from transformers import DonutProcessor __a = "naver-clova-ix/donut-base" class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def lowerCamelCase ( self : List[str] ): snake_case__ : Optional[Any] = DonutProcessor.from_pretrained(snake_case_ ) def lowerCamelCase ( self : List[Any] ): snake_case__ : Any = { """name""": """John Doe""", """age""": """99""", """city""": """Atlanta""", """state""": """GA""", """zip""": """30301""", """phone""": """123-4567""", """nicknames""": [{"""nickname""": """Johnny"""}, {"""nickname""": """JD"""}], } snake_case__ : str = ( """<s_name>John Doe</s_name><s_age>99</s_age><s_city>Atlanta</s_city>""" """<s_state>GA</s_state><s_zip>30301</s_zip><s_phone>123-4567</s_phone>""" """<s_nicknames><s_nickname>Johnny</s_nickname>""" """<sep/><s_nickname>JD</s_nickname></s_nicknames>""" ) snake_case__ : Optional[Any] = self.processor.tokenajson(snake_case_ ) self.assertDictEqual(snake_case_ , snake_case_ )
43
1
"""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() _a = logging.get_logger(__name__) def _A ( UpperCamelCase_ : List[str]) -> Optional[Any]: '''simple docstring''' __lowercase = MobileViTConfig() # size of the architecture if "mobilevit_s" in mobilevit_name: __lowercase = [144, 192, 240] __lowercase = [16, 32, 64, 96, 128, 160, 640] elif "mobilevit_xs" in mobilevit_name: __lowercase = [96, 120, 144] __lowercase = [16, 32, 48, 64, 80, 96, 384] elif "mobilevit_xxs" in mobilevit_name: __lowercase = [64, 80, 96] __lowercase = [16, 16, 24, 48, 64, 80, 320] __lowercase = 0.05 __lowercase = 2.0 if mobilevit_name.startswith("deeplabv3_"): __lowercase = 512 __lowercase = 16 __lowercase = 21 __lowercase = "pascal-voc-id2label.json" else: __lowercase = 1000 __lowercase = "imagenet-1k-id2label.json" __lowercase = "huggingface/label-files" __lowercase = json.load(open(hf_hub_download(UpperCamelCase_, UpperCamelCase_, repo_type="dataset"), "r")) __lowercase = {int(UpperCamelCase_): v for k, v in idalabel.items()} __lowercase = idalabel __lowercase = {v: k for k, v in idalabel.items()} return config def _A ( UpperCamelCase_ : int, UpperCamelCase_ : Dict=False) -> Optional[Any]: '''simple docstring''' for i in range(1, 6): if F"""layer_{i}.""" in name: __lowercase = name.replace(F"""layer_{i}.""", F"""encoder.layer.{i - 1}.""") if "conv_1." in name: __lowercase = name.replace("conv_1.", "conv_stem.") if ".block." in name: __lowercase = name.replace(".block.", ".") if "exp_1x1" in name: __lowercase = name.replace("exp_1x1", "expand_1x1") if "red_1x1" in name: __lowercase = name.replace("red_1x1", "reduce_1x1") if ".local_rep.conv_3x3." in name: __lowercase = name.replace(".local_rep.conv_3x3.", ".conv_kxk.") if ".local_rep.conv_1x1." in name: __lowercase = name.replace(".local_rep.conv_1x1.", ".conv_1x1.") if ".norm." in name: __lowercase = name.replace(".norm.", ".normalization.") if ".conv." in name: __lowercase = name.replace(".conv.", ".convolution.") if ".conv_proj." in name: __lowercase = name.replace(".conv_proj.", ".conv_projection.") for i in range(0, 2): for j in range(0, 4): if F""".{i}.{j}.""" in name: __lowercase = 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: __lowercase = name.replace(F""".{i}.{j}.""", F""".{i}.""") if "expand_1x1" in name: __lowercase = name.replace("expand_1x1", "downsampling_layer.expand_1x1") if "conv_3x3" in name: __lowercase = name.replace("conv_3x3", "downsampling_layer.conv_3x3") if "reduce_1x1" in name: __lowercase = name.replace("reduce_1x1", "downsampling_layer.reduce_1x1") for i in range(2, 5): if F""".global_rep.{i}.weight""" in name: __lowercase = name.replace(F""".global_rep.{i}.weight""", ".layernorm.weight") if F""".global_rep.{i}.bias""" in name: __lowercase = name.replace(F""".global_rep.{i}.bias""", ".layernorm.bias") if ".global_rep." in name: __lowercase = name.replace(".global_rep.", ".transformer.") if ".pre_norm_mha.0." in name: __lowercase = name.replace(".pre_norm_mha.0.", ".layernorm_before.") if ".pre_norm_mha.1.out_proj." in name: __lowercase = name.replace(".pre_norm_mha.1.out_proj.", ".attention.output.dense.") if ".pre_norm_ffn.0." in name: __lowercase = name.replace(".pre_norm_ffn.0.", ".layernorm_after.") if ".pre_norm_ffn.1." in name: __lowercase = name.replace(".pre_norm_ffn.1.", ".intermediate.dense.") if ".pre_norm_ffn.4." in name: __lowercase = name.replace(".pre_norm_ffn.4.", ".output.dense.") if ".transformer." in name: __lowercase = name.replace(".transformer.", ".transformer.layer.") if ".aspp_layer." in name: __lowercase = name.replace(".aspp_layer.", ".") if ".aspp_pool." in name: __lowercase = name.replace(".aspp_pool.", ".") if "seg_head." in name: __lowercase = name.replace("seg_head.", "segmentation_head.") if "segmentation_head.classifier.classifier." in name: __lowercase = name.replace("segmentation_head.classifier.classifier.", "segmentation_head.classifier.") if "classifier.fc." in name: __lowercase = name.replace("classifier.fc.", "classifier.") elif (not base_model) and ("segmentation_head." not in name): __lowercase = "mobilevit." + name return name def _A ( UpperCamelCase_ : str, UpperCamelCase_ : Dict, UpperCamelCase_ : Any=False) -> Tuple: '''simple docstring''' if base_model: __lowercase = "" else: __lowercase = "mobilevit." for key in orig_state_dict.copy().keys(): __lowercase = orig_state_dict.pop(UpperCamelCase_) if key[:8] == "encoder.": __lowercase = key[8:] if "qkv" in key: __lowercase = key.split(".") __lowercase = int(key_split[0][6:]) - 1 __lowercase = int(key_split[3]) __lowercase = model.get_submodule(F"""{model_prefix}encoder.layer.{layer_num}""") __lowercase = layer.transformer.layer[transformer_num].attention.attention.all_head_size __lowercase = ( F"""{model_prefix}encoder.layer.{layer_num}.transformer.layer.{transformer_num}.attention.attention.""" ) if "weight" in key: __lowercase = val[:dim, :] __lowercase = val[dim : dim * 2, :] __lowercase = val[-dim:, :] else: __lowercase = val[:dim] __lowercase = val[dim : dim * 2] __lowercase = val[-dim:] else: __lowercase = val return orig_state_dict def _A ( ) -> Tuple: '''simple docstring''' __lowercase = "http://images.cocodataset.org/val2017/000000039769.jpg" __lowercase = Image.open(requests.get(UpperCamelCase_, stream=UpperCamelCase_).raw) return im @torch.no_grad() def _A ( UpperCamelCase_ : Tuple, UpperCamelCase_ : Any, UpperCamelCase_ : Tuple, UpperCamelCase_ : Any=False) -> str: '''simple docstring''' __lowercase = get_mobilevit_config(UpperCamelCase_) # load original state_dict __lowercase = torch.load(UpperCamelCase_, map_location="cpu") # load 🤗 model if mobilevit_name.startswith("deeplabv3_"): __lowercase = MobileViTForSemanticSegmentation(UpperCamelCase_).eval() else: __lowercase = MobileViTForImageClassification(UpperCamelCase_).eval() __lowercase = convert_state_dict(UpperCamelCase_, UpperCamelCase_) model.load_state_dict(UpperCamelCase_) # Check outputs on an image, prepared by MobileViTImageProcessor __lowercase = MobileViTImageProcessor(crop_size=config.image_size, size=config.image_size + 32) __lowercase = image_processor(images=prepare_img(), return_tensors="pt") __lowercase = model(**UpperCamelCase_) __lowercase = outputs.logits if mobilevit_name.startswith("deeplabv3_"): assert logits.shape == (1, 21, 32, 32) if mobilevit_name == "deeplabv3_mobilevit_s": __lowercase = torch.tensor( [ [[6.2_065, 6.1_292, 6.2_070], [6.1_079, 6.1_254, 6.1_747], [6.0_042, 6.1_071, 6.1_034]], [[-6.9_253, -6.8_653, -7.0_398], [-7.3_218, -7.3_983, -7.3_670], [-7.1_961, -7.2_482, -7.1_569]], [[-4.4_723, -4.4_348, -4.3_769], [-5.3_629, -5.4_632, -5.4_598], [-5.1_587, -5.3_402, -5.5_059]], ]) elif mobilevit_name == "deeplabv3_mobilevit_xs": __lowercase = torch.tensor( [ [[5.4_449, 5.5_733, 5.6_314], [5.1_815, 5.3_930, 5.5_963], [5.1_656, 5.4_333, 5.4_853]], [[-9.4_423, -9.7_766, -9.6_714], [-9.1_581, -9.5_720, -9.5_519], [-9.1_006, -9.6_458, -9.5_703]], [[-7.7_721, -7.3_716, -7.1_583], [-8.4_599, -8.0_624, -7.7_944], [-8.4_172, -7.8_366, -7.5_025]], ]) elif mobilevit_name == "deeplabv3_mobilevit_xxs": __lowercase = torch.tensor( [ [[6.9_811, 6.9_743, 7.3_123], [7.1_777, 7.1_931, 7.3_938], [7.5_633, 7.8_050, 7.8_901]], [[-10.5_536, -10.2_332, -10.2_924], [-10.2_336, -9.8_624, -9.5_964], [-10.8_840, -10.8_158, -10.6_659]], [[-3.4_938, -3.0_631, -2.8_620], [-3.4_205, -2.8_135, -2.6_875], [-3.4_179, -2.7_945, -2.8_750]], ]) else: raise ValueError(F"""Unknown mobilevit_name: {mobilevit_name}""") assert torch.allclose(logits[0, :3, :3, :3], UpperCamelCase_, atol=1E-4) else: assert logits.shape == (1, 1000) if mobilevit_name == "mobilevit_s": __lowercase = torch.tensor([-0.9_866, 0.2_392, -1.1_241]) elif mobilevit_name == "mobilevit_xs": __lowercase = torch.tensor([-2.4_761, -0.9_399, -1.9_587]) elif mobilevit_name == "mobilevit_xxs": __lowercase = torch.tensor([-1.9_364, -1.2_327, -0.4_653]) else: raise ValueError(F"""Unknown mobilevit_name: {mobilevit_name}""") assert torch.allclose(logits[0, :3], UpperCamelCase_, atol=1E-4) Path(UpperCamelCase_).mkdir(exist_ok=UpperCamelCase_) print(F"""Saving model {mobilevit_name} to {pytorch_dump_folder_path}""") model.save_pretrained(UpperCamelCase_) print(F"""Saving image processor to {pytorch_dump_folder_path}""") image_processor.save_pretrained(UpperCamelCase_) if push_to_hub: __lowercase = { "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...") __lowercase = model_mapping[mobilevit_name] image_processor.push_to_hub(UpperCamelCase_, organization="apple") model.push_to_hub(UpperCamelCase_, organization="apple") if __name__ == "__main__": _a = 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.' ) _a = parser.parse_args() convert_movilevit_checkpoint( args.mobilevit_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
17
import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput _SCREAMING_SNAKE_CASE : List[str] = logging.getLogger(__name__) if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class A__ ( snake_case__ ): """simple docstring""" def __init__( self , *__snake_case , __snake_case=None , __snake_case=None , __snake_case=None , **__snake_case ): super().__init__(*__snake_case , **__snake_case ) snake_case = eval_examples snake_case = post_process_function snake_case = quant_trainer_args snake_case = 1_2_8 # default number of calibration samples def a_ ( self , __snake_case=None ): if calib_dataset is None and self.calib_dataset is None: raise ValueError('''Trainer: calibration requires an calib_dataset.''' ) snake_case = calib_dataset if calib_dataset is not None else self.calib_dataset snake_case = self._remove_unused_columns(__snake_case , description='''Calibration''' ) return DataLoader( __snake_case , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=__snake_case , ) def a_ ( self , __snake_case=None ): snake_case = self.train_dataset if calib_dataset is None else calib_dataset snake_case = self.get_calib_dataloader(__snake_case ) snake_case = self.model quant_trainer.configure_model(__snake_case , self.quant_trainer_args , calib=__snake_case ) model.eval() quant_trainer.enable_calibration(__snake_case ) logger.info('''***** Running calibration *****''' ) logger.info(F''' Num examples = {self.calib_num}''' ) logger.info(F''' Batch size = {calib_dataloader.batch_size}''' ) for step, inputs in enumerate(__snake_case ): # Prediction step snake_case , snake_case , snake_case = self.prediction_step(__snake_case , __snake_case , prediction_loss_only=__snake_case ) if (step + 1) * calib_dataloader.batch_size >= self.calib_num: break quant_trainer.finish_calibration(__snake_case , self.quant_trainer_args ) snake_case = model def a_ ( self , __snake_case=None , __snake_case=None , __snake_case=None , __snake_case = "eval" ): snake_case = self.eval_dataset if eval_dataset is None else eval_dataset snake_case = self.get_eval_dataloader(__snake_case ) snake_case = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. snake_case = self.compute_metrics snake_case = None snake_case = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: snake_case = eval_loop( __snake_case , description='''Evaluation''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__snake_case , ) finally: snake_case = compute_metrics if self.post_process_function is not None and self.compute_metrics is not None: snake_case = self.post_process_function(__snake_case , __snake_case , output.predictions ) snake_case = self.compute_metrics(__snake_case ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): snake_case = metrics.pop(__snake_case ) self.log(__snake_case ) else: snake_case = {} if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report() ) snake_case = self.callback_handler.on_evaluate(self.args , self.state , self.control , __snake_case ) return metrics def a_ ( self , __snake_case , __snake_case , __snake_case=None , __snake_case = "test" ): snake_case = self.get_test_dataloader(__snake_case ) # Temporarily disable metric computation, we will do it in the loop here. snake_case = self.compute_metrics snake_case = None snake_case = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: snake_case = eval_loop( __snake_case , description='''Prediction''' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=__snake_case , ) finally: snake_case = compute_metrics if self.post_process_function is None or self.compute_metrics is None: return output snake_case = self.post_process_function(__snake_case , __snake_case , output.predictions , '''predict''' ) snake_case = self.compute_metrics(__snake_case ) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys() ): if not key.startswith(F'''{metric_key_prefix}_''' ): snake_case = metrics.pop(__snake_case ) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=__snake_case ) def a_ ( self , __snake_case="./" ): snake_case = self.eval_dataset snake_case = self.get_eval_dataloader(__snake_case ) snake_case = next(iter(__snake_case ) ) # saving device - to make it consistent snake_case = torch.device('''cuda''' if torch.cuda.is_available() else '''cpu''' ) # convert to tuple snake_case = tuple(v.to(__snake_case ) for k, v in batch.items() ) logger.info('''Converting model to be onnx compatible''' ) from pytorch_quantization.nn import TensorQuantizer snake_case = True snake_case = self.model.to(__snake_case ) model.eval() model.float() snake_case = model.module if hasattr(__snake_case , '''module''' ) else model quant_trainer.configure_model(__snake_case , self.quant_trainer_args ) snake_case = os.path.join(__snake_case , '''model.onnx''' ) logger.info(F'''exporting model to {output_model_file}''' ) snake_case = {0: '''batch_size''', 1: '''seq_len'''} torch.onnx.export( __snake_case , __snake_case , __snake_case , export_params=__snake_case , opset_version=1_3 , do_constant_folding=__snake_case , input_names=['''input_ids''', '''attention_mask''', '''token_type_ids'''] , output_names=['''output_start_logits''', '''output_end_logits'''] , dynamic_axes={ '''input_ids''': axes, '''attention_mask''': axes, '''token_type_ids''': axes, '''output_start_logits''': axes, '''output_end_logits''': axes, } , verbose=__snake_case , ) logger.info('''onnx export finished''' )
127
0
"""simple docstring""" import copy import json import os import tempfile from transformers import is_torch_available from .test_configuration_utils import config_common_kwargs class UpperCamelCase ( snake_case_ ): def __init__( self : Union[str, Any] , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int=None , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : List[str]=None , **UpperCAmelCase__ : str ) -> int: _a : str = parent _a : Union[str, Any] = config_class _a : List[Any] = has_text_modality _a : List[Any] = kwargs _a : List[Any] = common_properties def _lowercase ( self : int ) -> Tuple: _a : List[str] = self.config_class(**self.inputs_dict ) _a : Dict = ( ["""hidden_size""", """num_attention_heads""", """num_hidden_layers"""] if self.common_properties is None else self.common_properties ) # Add common fields for text models if self.has_text_modality: common_properties.extend(["""vocab_size"""] ) # Test that config has the common properties as getters for prop in common_properties: self.parent.assertTrue(hasattr(UpperCAmelCase__ , UpperCAmelCase__ ) , msg=f"""`{prop}` does not exist""" ) # Test that config has the common properties as setter for idx, name in enumerate(UpperCAmelCase__ ): try: setattr(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ ) self.parent.assertEqual( getattr(UpperCAmelCase__ , UpperCAmelCase__ ) , UpperCAmelCase__ , msg=f"""`{name} value {idx} expected, but was {getattr(UpperCAmelCase__ , UpperCAmelCase__ )}""" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass # Test if config class can be called with Config(prop_name=..) for idx, name in enumerate(UpperCAmelCase__ ): try: _a : Optional[int] = self.config_class(**{name: idx} ) self.parent.assertEqual( getattr(UpperCAmelCase__ , UpperCAmelCase__ ) , UpperCAmelCase__ , msg=f"""`{name} value {idx} expected, but was {getattr(UpperCAmelCase__ , UpperCAmelCase__ )}""" ) except NotImplementedError: # Some models might not be able to implement setters for common_properties # In that case, a NotImplementedError is raised pass def _lowercase ( self : Optional[int] ) -> Optional[Any]: _a : Optional[Any] = self.config_class(**self.inputs_dict ) _a : List[str] = json.loads(config.to_json_string() ) for key, value in self.inputs_dict.items(): self.parent.assertEqual(obj[key] , UpperCAmelCase__ ) def _lowercase ( self : int ) -> List[str]: _a : Optional[Any] = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: _a : Tuple = os.path.join(UpperCAmelCase__ , """config.json""" ) config_first.to_json_file(UpperCAmelCase__ ) _a : List[str] = self.config_class.from_json_file(UpperCAmelCase__ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _lowercase ( self : Union[str, Any] ) -> Dict: _a : Dict = self.config_class(**self.inputs_dict ) with tempfile.TemporaryDirectory() as tmpdirname: config_first.save_pretrained(UpperCAmelCase__ ) _a : Dict = self.config_class.from_pretrained(UpperCAmelCase__ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _lowercase ( self : Dict ) -> Tuple: _a : List[Any] = self.config_class(**self.inputs_dict ) _a : Any = """test""" with tempfile.TemporaryDirectory() as tmpdirname: _a : List[Any] = os.path.join(UpperCAmelCase__ , UpperCAmelCase__ ) config_first.save_pretrained(UpperCAmelCase__ ) _a : List[Any] = self.config_class.from_pretrained(UpperCAmelCase__ , subfolder=UpperCAmelCase__ ) self.parent.assertEqual(config_second.to_dict() , config_first.to_dict() ) def _lowercase ( self : List[str] ) -> Union[str, Any]: _a : Tuple = self.config_class(**self.inputs_dict , num_labels=5 ) self.parent.assertEqual(len(config.idalabel ) , 5 ) self.parent.assertEqual(len(config.labelaid ) , 5 ) _a : Union[str, Any] = 3 self.parent.assertEqual(len(config.idalabel ) , 3 ) self.parent.assertEqual(len(config.labelaid ) , 3 ) def _lowercase ( self : Tuple ) -> List[str]: if self.config_class.is_composition: return _a : str = self.config_class() self.parent.assertIsNotNone(UpperCAmelCase__ ) def _lowercase ( self : List[Any] ) -> Optional[Any]: _a : Dict = copy.deepcopy(UpperCAmelCase__ ) _a : Any = self.config_class(**UpperCAmelCase__ ) _a : str = [] for key, value in config_common_kwargs.items(): if key == "torch_dtype": if not is_torch_available(): continue else: import torch if config.torch_dtype != torch.floataa: wrong_values.append(("""torch_dtype""", config.torch_dtype, torch.floataa) ) elif getattr(UpperCAmelCase__ , UpperCAmelCase__ ) != value: wrong_values.append((key, getattr(UpperCAmelCase__ , UpperCAmelCase__ ), value) ) if len(UpperCAmelCase__ ) > 0: _a : List[Any] = """\n""".join([f"""- {v[0]}: got {v[1]} instead of {v[2]}""" for v in wrong_values] ) raise ValueError(f"""The following keys were not properly set in the config:\n{errors}""" ) def _lowercase ( self : int ) -> Union[str, Any]: self.create_and_test_config_common_properties() self.create_and_test_config_to_json_string() self.create_and_test_config_to_json_file() self.create_and_test_config_from_and_save_pretrained() self.create_and_test_config_from_and_save_pretrained_subfolder() self.create_and_test_config_with_num_labels() self.check_config_can_be_init_without_params() self.check_config_arguments_init()
324
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) _snake_case = { 'configuration_vision_encoder_decoder': ['VisionEncoderDecoderConfig', 'VisionEncoderDecoderOnnxConfig'] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ['VisionEncoderDecoderModel'] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ['TFVisionEncoderDecoderModel'] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _snake_case = ['FlaxVisionEncoderDecoderModel'] if TYPE_CHECKING: from .configuration_vision_encoder_decoder import VisionEncoderDecoderConfig, VisionEncoderDecoderOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vision_encoder_decoder import VisionEncoderDecoderModel try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_vision_encoder_decoder import TFVisionEncoderDecoderModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_vision_encoder_decoder import FlaxVisionEncoderDecoderModel else: import sys _snake_case = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
324
1
'''simple docstring''' from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class _UpperCamelCase : '''simple docstring''' lowerCAmelCase__ = 42 # [batch_size x 3] lowerCAmelCase__ = 42 # [batch_size x 3] lowerCAmelCase__ = 42 # [batch_size x 3] lowerCAmelCase__ = 42 # [batch_size x 3] lowerCAmelCase__ = 42 lowerCAmelCase__ = 42 lowerCAmelCase__ = 42 lowerCAmelCase__ = 42 lowerCAmelCase__ = 42 def __lowerCamelCase ( self : List[Any]): '''simple docstring''' 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 __lowerCamelCase ( self : str): '''simple docstring''' return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa)) def __lowerCamelCase ( self : int): '''simple docstring''' return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa)) def __lowerCamelCase ( self : List[str]): '''simple docstring''' __lowercase =torch.arange(self.height * self.width) __lowercase =torch.stack( [ pixel_indices % self.width, torch.div(_A , self.width , rounding_mode='trunc'), ] , axis=1 , ) return coords @property def __lowerCamelCase ( self : Dict): '''simple docstring''' __lowercase , *__lowercase =self.shape __lowercase =int(np.prod(_A)) __lowercase =self.get_image_coords() __lowercase =torch.broadcast_to(coords.unsqueeze(0) , [batch_size * inner_batch_size, *coords.shape]) __lowercase =self.get_camera_rays(_A) __lowercase =rays.view(_A , inner_batch_size * self.height * self.width , 2 , 3) return rays def __lowerCamelCase ( self : Optional[int] , _lowerCAmelCase : List[str]): '''simple docstring''' __lowercase , *__lowercase , __lowercase =coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] __lowercase =coords.view(_A , -1 , 2) __lowercase =self.resolution() __lowercase =self.fov() __lowercase =(flat.float() / (res - 1)) * 2 - 1 __lowercase =fracs * torch.tan(fov / 2) __lowercase =fracs.view(_A , -1 , 2) __lowercase =( self.z.view(_A , 1 , 3) + self.x.view(_A , 1 , 3) * fracs[:, :, :1] + self.y.view(_A , 1 , 3) * fracs[:, :, 1:] ) __lowercase =directions / directions.norm(dim=-1 , keepdim=_A) __lowercase =torch.stack( [ torch.broadcast_to(self.origin.view(_A , 1 , 3) , [batch_size, directions.shape[1], 3]), directions, ] , dim=2 , ) return rays.view(_A , *_A , 2 , 3) def __lowerCamelCase ( self : str , _lowerCAmelCase : int , _lowerCAmelCase : Union[str, Any]): '''simple docstring''' 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=_A , height=_A , x_fov=self.x_fov , y_fov=self.y_fov , ) def _A ( _lowerCAmelCase ): """simple docstring""" __lowercase =[] __lowercase =[] __lowercase =[] __lowercase =[] for theta in np.linspace(0 , 2 * np.pi , num=20 ): __lowercase =np.array([np.sin(__lowerCamelCase ), np.cos(__lowerCamelCase ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) __lowercase =-z * 4 __lowercase =np.array([np.cos(__lowerCamelCase ), -np.sin(__lowerCamelCase ), 0.0] ) __lowercase =np.cross(__lowerCamelCase , __lowerCamelCase ) origins.append(__lowerCamelCase ) xs.append(__lowerCamelCase ) ys.append(__lowerCamelCase ) zs.append(__lowerCamelCase ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(__lowerCamelCase , axis=0 ) ).float() , x=torch.from_numpy(np.stack(__lowerCamelCase , axis=0 ) ).float() , y=torch.from_numpy(np.stack(__lowerCamelCase , axis=0 ) ).float() , z=torch.from_numpy(np.stack(__lowerCamelCase , axis=0 ) ).float() , width=__lowerCamelCase , height=__lowerCamelCase , x_fov=0.7 , y_fov=0.7 , shape=(1, len(__lowerCamelCase )) , )
166
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) __UpperCAmelCase = { "configuration_layoutlmv2": ["LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP", "LayoutLMv2Config"], "processing_layoutlmv2": ["LayoutLMv2Processor"], "tokenization_layoutlmv2": ["LayoutLMv2Tokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ["LayoutLMv2TokenizerFast"] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = ["LayoutLMv2FeatureExtractor"] __UpperCAmelCase = ["LayoutLMv2ImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __UpperCAmelCase = [ "LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST", "LayoutLMv2ForQuestionAnswering", "LayoutLMv2ForSequenceClassification", "LayoutLMv2ForTokenClassification", "LayoutLMv2Layer", "LayoutLMv2Model", "LayoutLMv2PreTrainedModel", ] if TYPE_CHECKING: from .configuration_layoutlmva import LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor, LayoutLMvaImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaLayer, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) else: import sys __UpperCAmelCase = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
299
0
import argparse import math import traceback import dateutil.parser as date_parser import requests def A_ ( _UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Dict = {} SCREAMING_SNAKE_CASE_: List[str] = job["started_at"] SCREAMING_SNAKE_CASE_: Optional[int] = job["completed_at"] SCREAMING_SNAKE_CASE_: str = date_parser.parse(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Optional[int] = date_parser.parse(_UpperCAmelCase ) SCREAMING_SNAKE_CASE_: Dict = round((end_datetime - start_datetime).total_seconds() / 6_0.0 ) SCREAMING_SNAKE_CASE_: Optional[int] = start SCREAMING_SNAKE_CASE_: int = end SCREAMING_SNAKE_CASE_: str = duration_in_min return job_info def A_ ( _UpperCAmelCase , _UpperCAmelCase=None ): SCREAMING_SNAKE_CASE_: List[str] = None if token is not None: SCREAMING_SNAKE_CASE_: str = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"} SCREAMING_SNAKE_CASE_: str = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100" SCREAMING_SNAKE_CASE_: Union[str, Any] = requests.get(_UpperCAmelCase , headers=_UpperCAmelCase ).json() SCREAMING_SNAKE_CASE_: List[str] = {} try: job_time.update({job["name"]: extract_time_from_single_job(_UpperCAmelCase ) for job in result["jobs"]} ) SCREAMING_SNAKE_CASE_: List[Any] = math.ceil((result["total_count"] - 1_00) / 1_00 ) for i in range(_UpperCAmelCase ): SCREAMING_SNAKE_CASE_: Tuple = requests.get(url + f"&page={i + 2}" , headers=_UpperCAmelCase ).json() job_time.update({job["name"]: extract_time_from_single_job(_UpperCAmelCase ) for job in result["jobs"]} ) return job_time except Exception: print(f"Unknown error, could not fetch links:\n{traceback.format_exc()}" ) return {} if __name__ == "__main__": lowerCAmelCase : Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument("""--workflow_run_id""", type=str, required=True, help="""A GitHub Actions workflow run id.""") lowerCAmelCase : Union[str, Any] = parser.parse_args() lowerCAmelCase : Any = get_job_time(args.workflow_run_id) lowerCAmelCase : Any = dict(sorted(job_time.items(), key=lambda item: item[1]["duration"], reverse=True)) for k, v in job_time.items(): print(f'''{k}: {v['duration']}''')
127
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowerCAmelCase : Optional[int] = {"""configuration_yolos""": ["""YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP""", """YolosConfig""", """YolosOnnxConfig"""]} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : Any = ["""YolosFeatureExtractor"""] lowerCAmelCase : Tuple = ["""YolosImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase : Any = [ """YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST""", """YolosForObjectDetection""", """YolosModel""", """YolosPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_yolos import YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP, YolosConfig, YolosOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_yolos import YolosFeatureExtractor from .image_processing_yolos import YolosImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_yolos import ( YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST, YolosForObjectDetection, YolosModel, YolosPreTrainedModel, ) else: import sys lowerCAmelCase : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
127
1
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __A ( A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : Optional[Any] = LayoutLMTokenizer lowerCAmelCase : List[Any] = LayoutLMTokenizerFast lowerCAmelCase : Dict = True lowerCAmelCase : Union[str, Any] = True def UpperCAmelCase ( self : List[Any] ) -> List[str]: """simple docstring""" super().setUp() lowercase__ : Optional[Any] = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] lowercase__ : List[Any] = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file ,'''w''' ,encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def UpperCAmelCase ( self : List[Any] ,**_snake_case : Optional[Any] ) -> str: """simple docstring""" return LayoutLMTokenizer.from_pretrained(self.tmpdirname ,**_snake_case ) def UpperCAmelCase ( self : str ,_snake_case : Any ) -> List[Any]: """simple docstring""" lowercase__ : Dict = '''UNwant\u00E9d,running''' lowercase__ : Optional[Any] = '''unwanted, running''' return input_text, output_text def UpperCAmelCase ( self : Optional[Any] ) -> Optional[int]: """simple docstring""" lowercase__ : Union[str, Any] = self.tokenizer_class(self.vocab_file ) lowercase__ : Optional[int] = tokenizer.tokenize('''UNwant\u00E9d,running''' ) self.assertListEqual(_snake_case ,['''un''', '''##want''', '''##ed''', ''',''', '''runn''', '''##ing'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_snake_case ) ,[7, 4, 5, 10, 8, 9] ) def UpperCAmelCase ( self : Dict ) -> int: """simple docstring""" pass
16
"""simple docstring""" import warnings from ...utils import logging from .image_processing_mobilevit import MobileViTImageProcessor lowerCAmelCase_ = logging.get_logger(__name__) class __A ( A_ ): '''simple docstring''' def __init__( self : Dict ,*_snake_case : Any ,**_snake_case : str ) -> None: """simple docstring""" warnings.warn( '''The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers.''' ''' Please use MobileViTImageProcessor instead.''' ,_snake_case ,) super().__init__(*_snake_case ,**_snake_case )
16
1
import torch from transformers import CamembertForMaskedLM, CamembertTokenizer def UpperCAmelCase_ ( __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : int , __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : List[str]=5 ) -> Union[str, Any]: # Adapted from https://github.com/pytorch/fairseq/blob/master/fairseq/models/roberta/hub_interface.py assert masked_input.count('<mask>' ) == 1 SCREAMING_SNAKE_CASE_ = torch.tensor(tokenizer.encode(snake_case_ , add_special_tokens=snake_case_ ) ).unsqueeze(0 ) # Batch size 1 SCREAMING_SNAKE_CASE_ = model(snake_case_ )[0] # The last hidden-state is the first element of the output tuple SCREAMING_SNAKE_CASE_ = (input_ids.squeeze() == tokenizer.mask_token_id).nonzero().item() SCREAMING_SNAKE_CASE_ = logits[0, masked_index, :] SCREAMING_SNAKE_CASE_ = logits.softmax(dim=0 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = prob.topk(k=snake_case_ , dim=0 ) SCREAMING_SNAKE_CASE_ = ' '.join( [tokenizer.convert_ids_to_tokens(indices[i].item() ) for i in range(len(snake_case_ ) )] ) SCREAMING_SNAKE_CASE_ = tokenizer.mask_token SCREAMING_SNAKE_CASE_ = [] for index, predicted_token_bpe in enumerate(topk_predicted_token_bpe.split(' ' ) ): SCREAMING_SNAKE_CASE_ = predicted_token_bpe.replace('\u2581' , ' ' ) if " {0}".format(snake_case_ ) in masked_input: topk_filled_outputs.append( ( masked_input.replace(' {0}'.format(snake_case_ ) , snake_case_ ), values[index].item(), predicted_token, ) ) else: topk_filled_outputs.append( ( masked_input.replace(snake_case_ , snake_case_ ), values[index].item(), predicted_token, ) ) return topk_filled_outputs lowerCamelCase__ : Any = CamembertTokenizer.from_pretrained('camembert-base') lowerCamelCase__ : Optional[Any] = CamembertForMaskedLM.from_pretrained('camembert-base') model.eval() lowerCamelCase__ : int = 'Le camembert est <mask> :)' print(fill_mask(masked_input, model, tokenizer, topk=3))
370
import argparse import requests import torch from PIL import Image from transformers import CLIPProcessor, GroupViTConfig, GroupViTModel def UpperCAmelCase_ ( __UpperCAmelCase : List[str] ) -> List[Any]: # vision encoder if "img_encoder.pos_embed" in name: SCREAMING_SNAKE_CASE_ = name.replace('img_encoder.pos_embed' , 'vision_model.embeddings.position_embeddings' ) if "img_encoder.patch_embed.proj" in name: SCREAMING_SNAKE_CASE_ = name.replace('img_encoder.patch_embed.proj' , 'vision_model.embeddings.patch_embeddings.projection' ) if "img_encoder.patch_embed.norm" in name: SCREAMING_SNAKE_CASE_ = name.replace('img_encoder.patch_embed.norm' , 'vision_model.embeddings.layernorm' ) if "img_encoder.layers" in name: SCREAMING_SNAKE_CASE_ = name.replace('img_encoder.layers' , 'vision_model.encoder.stages' ) if "blocks" in name and "res" not in name: SCREAMING_SNAKE_CASE_ = name.replace('blocks' , 'layers' ) if "attn" in name and "pre_assign" not in name: SCREAMING_SNAKE_CASE_ = name.replace('attn' , 'self_attn' ) if "proj" in name and "self_attn" in name and "text" not in name: SCREAMING_SNAKE_CASE_ = name.replace('proj' , 'out_proj' ) if "pre_assign_attn.attn.proj" in name: SCREAMING_SNAKE_CASE_ = name.replace('pre_assign_attn.attn.proj' , 'pre_assign_attn.attn.out_proj' ) if "norm1" in name: SCREAMING_SNAKE_CASE_ = name.replace('norm1' , 'layer_norm1' ) if "norm2" in name and "pre_assign" not in name: SCREAMING_SNAKE_CASE_ = name.replace('norm2' , 'layer_norm2' ) if "img_encoder.norm" in name: SCREAMING_SNAKE_CASE_ = name.replace('img_encoder.norm' , 'vision_model.layernorm' ) # text encoder if "text_encoder.token_embedding" in name: SCREAMING_SNAKE_CASE_ = name.replace('text_encoder.token_embedding' , 'text_model.embeddings.token_embedding' ) if "text_encoder.positional_embedding" in name: SCREAMING_SNAKE_CASE_ = name.replace('text_encoder.positional_embedding' , 'text_model.embeddings.position_embedding.weight' ) if "text_encoder.transformer.resblocks." in name: SCREAMING_SNAKE_CASE_ = name.replace('text_encoder.transformer.resblocks.' , 'text_model.encoder.layers.' ) if "ln_1" in name: SCREAMING_SNAKE_CASE_ = name.replace('ln_1' , 'layer_norm1' ) if "ln_2" in name: SCREAMING_SNAKE_CASE_ = name.replace('ln_2' , 'layer_norm2' ) if "c_fc" in name: SCREAMING_SNAKE_CASE_ = name.replace('c_fc' , 'fc1' ) if "c_proj" in name: SCREAMING_SNAKE_CASE_ = name.replace('c_proj' , 'fc2' ) if "text_encoder" in name: SCREAMING_SNAKE_CASE_ = name.replace('text_encoder' , 'text_model' ) if "ln_final" in name: SCREAMING_SNAKE_CASE_ = name.replace('ln_final' , 'final_layer_norm' ) # projection layers if "img_projector.linear_hidden." in name: SCREAMING_SNAKE_CASE_ = name.replace('img_projector.linear_hidden.' , 'visual_projection.' ) if "img_projector.linear_out." in name: SCREAMING_SNAKE_CASE_ = name.replace('img_projector.linear_out.' , 'visual_projection.3.' ) if "text_projector.linear_hidden" in name: SCREAMING_SNAKE_CASE_ = name.replace('text_projector.linear_hidden' , 'text_projection' ) if "text_projector.linear_out" in name: SCREAMING_SNAKE_CASE_ = name.replace('text_projector.linear_out' , 'text_projection.3' ) return name def UpperCAmelCase_ ( __UpperCAmelCase : Union[str, Any] , __UpperCAmelCase : int ) -> List[str]: for key in orig_state_dict.copy().keys(): SCREAMING_SNAKE_CASE_ = orig_state_dict.pop(__UpperCAmelCase ) if "qkv" in key: # weights and biases of the key, value and query projections of vision encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors SCREAMING_SNAKE_CASE_ = key.split('.' ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = int(key_split[2] ), int(key_split[4] ) SCREAMING_SNAKE_CASE_ = config.vision_config.hidden_size if "weight" in key: SCREAMING_SNAKE_CASE_ = val[:dim, :] SCREAMING_SNAKE_CASE_ = val[dim : dim * 2, :] SCREAMING_SNAKE_CASE_ = val[-dim:, :] else: SCREAMING_SNAKE_CASE_ = val[:dim] SCREAMING_SNAKE_CASE_ = val[dim : dim * 2] SCREAMING_SNAKE_CASE_ = val[-dim:] elif "in_proj" in key: # weights and biases of the key, value and query projections of text encoder's attention layers require special treatment: # we need to split them up into separate matrices/vectors SCREAMING_SNAKE_CASE_ = key.split('.' ) SCREAMING_SNAKE_CASE_ = int(key_split[3] ) SCREAMING_SNAKE_CASE_ = config.text_config.hidden_size if "weight" in key: SCREAMING_SNAKE_CASE_ = val[:dim, :] SCREAMING_SNAKE_CASE_ = val[ dim : dim * 2, : ] SCREAMING_SNAKE_CASE_ = val[-dim:, :] else: SCREAMING_SNAKE_CASE_ = val[:dim] SCREAMING_SNAKE_CASE_ = val[dim : dim * 2] SCREAMING_SNAKE_CASE_ = val[-dim:] else: SCREAMING_SNAKE_CASE_ = rename_key(__UpperCAmelCase ) # squeeze if necessary if ( "text_projection.0" in new_name or "text_projection.3" in new_name or "visual_projection.0" in new_name or "visual_projection.3" in new_name ): SCREAMING_SNAKE_CASE_ = val.squeeze_() else: SCREAMING_SNAKE_CASE_ = val return orig_state_dict def UpperCAmelCase_ ( ) -> List[Any]: SCREAMING_SNAKE_CASE_ = 'http://images.cocodataset.org/val2017/000000039769.jpg' SCREAMING_SNAKE_CASE_ = Image.open(requests.get(__UpperCAmelCase , stream=__UpperCAmelCase ).raw ) return im @torch.no_grad() def UpperCAmelCase_ ( __UpperCAmelCase : int , __UpperCAmelCase : str , __UpperCAmelCase : Dict="groupvit-gcc-yfcc" , __UpperCAmelCase : Any=False ) -> Optional[int]: SCREAMING_SNAKE_CASE_ = GroupViTConfig() SCREAMING_SNAKE_CASE_ = GroupViTModel(__UpperCAmelCase ).eval() SCREAMING_SNAKE_CASE_ = torch.load(__UpperCAmelCase , map_location='cpu' )['model'] SCREAMING_SNAKE_CASE_ = convert_state_dict(__UpperCAmelCase , __UpperCAmelCase ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = model.load_state_dict(__UpperCAmelCase , strict=__UpperCAmelCase ) assert missing_keys == ["text_model.embeddings.position_ids"] assert (unexpected_keys == ["multi_label_logit_scale"]) or (len(__UpperCAmelCase ) == 0) # verify result SCREAMING_SNAKE_CASE_ = CLIPProcessor.from_pretrained('openai/clip-vit-base-patch32' ) SCREAMING_SNAKE_CASE_ = prepare_img() SCREAMING_SNAKE_CASE_ = processor(text=['a photo of a cat', 'a photo of a dog'] , images=__UpperCAmelCase , padding=__UpperCAmelCase , return_tensors='pt' ) with torch.no_grad(): SCREAMING_SNAKE_CASE_ = model(**__UpperCAmelCase ) if model_name == "groupvit-gcc-yfcc": SCREAMING_SNAKE_CASE_ = torch.tensor([[1_3.3_5_2_3, 6.3_6_2_9]] ) elif model_name == "groupvit-gcc-redcaps": SCREAMING_SNAKE_CASE_ = torch.tensor([[1_6.1_8_7_3, 8.6_2_3_0]] ) else: raise ValueError(f"Model name {model_name} not supported." ) assert torch.allclose(outputs.logits_per_image , __UpperCAmelCase , atol=1E-3 ) processor.save_pretrained(__UpperCAmelCase ) model.save_pretrained(__UpperCAmelCase ) print('Successfully saved processor and model to' , __UpperCAmelCase ) if push_to_hub: print('Pushing to the hub...' ) processor.push_to_hub(__UpperCAmelCase , organization='nielsr' ) model.push_to_hub(__UpperCAmelCase , organization='nielsr' ) if __name__ == "__main__": lowerCamelCase__ : int = argparse.ArgumentParser() parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to dump the processor and PyTorch model.' ) parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to GroupViT checkpoint') parser.add_argument( '--model_name', default='groupvit-gccy-fcc', type=str, help='Name of the model. Expecting either \'groupvit-gcc-yfcc\' or \'groupvit-gcc-redcaps\'', ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model and processor to the 🤗 hub using the provided `model_name`.', ) lowerCamelCase__ : List[str] = parser.parse_args() convert_groupvit_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.model_name, args.push_to_hub)
210
0
import argparse import json from typing import List from ltp import LTP from transformers import BertTokenizer def lowerCamelCase_ ( _a ): """simple docstring""" if ( (cp >= 0x4E00 and cp <= 0x9FFF) or (cp >= 0x3400 and cp <= 0x4DBF) # or (cp >= 0x2_0000 and cp <= 0x2_A6DF) # or (cp >= 0x2_A700 and cp <= 0x2_B73F) # or (cp >= 0x2_B740 and cp <= 0x2_B81F) # or (cp >= 0x2_B820 and cp <= 0x2_CEAF) # or (cp >= 0xF900 and cp <= 0xFAFF) or (cp >= 0x2_F800 and cp <= 0x2_FA1F) # ): # return True return False def lowerCamelCase_ ( _a ): """simple docstring""" for char in word: lowerCAmelCase__ : Tuple = ord(_a ) if not _is_chinese_char(_a ): return 0 return 1 def lowerCamelCase_ ( _a ): """simple docstring""" lowerCAmelCase__ : str = set() for token in tokens: lowerCAmelCase__ : List[str] = len(_a ) > 1 and is_chinese(_a ) if chinese_word: word_set.add(_a ) lowerCAmelCase__ : List[Any] = list(_a ) return word_list def lowerCamelCase_ ( _a , _a ): """simple docstring""" if not chinese_word_set: return bert_tokens lowerCAmelCase__ : Dict = max([len(_a ) for w in chinese_word_set] ) lowerCAmelCase__ : List[Any] = bert_tokens lowerCAmelCase__ , lowerCAmelCase__ : Optional[int] = 0, len(_a ) while start < end: lowerCAmelCase__ : Optional[int] = True if is_chinese(bert_word[start] ): lowerCAmelCase__ : int = min(end - start , _a ) for i in range(_a , 1 , -1 ): lowerCAmelCase__ : Tuple = ''''''.join(bert_word[start : start + i] ) if whole_word in chinese_word_set: for j in range(start + 1 , start + i ): lowerCAmelCase__ : Optional[int] = '''##''' + bert_word[j] lowerCAmelCase__ : Optional[int] = start + i lowerCAmelCase__ : Optional[Any] = False break if single_word: start += 1 return bert_word def lowerCamelCase_ ( _a , _a , _a ): """simple docstring""" lowerCAmelCase__ : Dict = [] for i in range(0 , len(_a ) , 100 ): lowerCAmelCase__ : List[Any] = ltp_tokenizer.seg(lines[i : i + 100] )[0] lowerCAmelCase__ : str = [get_chinese_word(_a ) for r in res] ltp_res.extend(_a ) assert len(_a ) == len(_a ) lowerCAmelCase__ : Dict = [] for i in range(0 , len(_a ) , 100 ): lowerCAmelCase__ : Tuple = bert_tokenizer(lines[i : i + 100] , add_special_tokens=_a , truncation=_a , max_length=512 ) bert_res.extend(res['''input_ids'''] ) assert len(_a ) == len(_a ) lowerCAmelCase__ : Dict = [] for input_ids, chinese_word in zip(_a , _a ): lowerCAmelCase__ : List[Any] = [] for id in input_ids: lowerCAmelCase__ : Any = bert_tokenizer._convert_id_to_token(_a ) input_tokens.append(_a ) lowerCAmelCase__ : Any = add_sub_symbol(_a , _a ) lowerCAmelCase__ : Optional[int] = [] # We only save pos of chinese subwords start with ##, which mean is part of a whole word. for i, token in enumerate(_a ): if token[:2] == "##": lowerCAmelCase__ : List[Any] = token[2:] # save chinese tokens' pos if len(_a ) == 1 and _is_chinese_char(ord(_a ) ): ref_id.append(_a ) ref_ids.append(_a ) assert len(_a ) == len(_a ) return ref_ids def lowerCamelCase_ ( _a ): """simple docstring""" with open(args.file_name , '''r''' , encoding='''utf-8''' ) as f: lowerCAmelCase__ : Dict = f.readlines() lowerCAmelCase__ : Tuple = [line.strip() for line in data if len(_a ) > 0 and not line.isspace()] # avoid delimiter like '\u2029' lowerCAmelCase__ : str = LTP(args.ltp ) # faster in GPU device lowerCAmelCase__ : int = BertTokenizer.from_pretrained(args.bert ) lowerCAmelCase__ : Union[str, Any] = prepare_ref(_a , _a , _a ) with open(args.save_path , '''w''' , encoding='''utf-8''' ) as f: lowerCAmelCase__ : Any = [json.dumps(_a ) + '''\n''' for ref in ref_ids] f.writelines(_a ) if __name__ == "__main__": lowerCamelCase = argparse.ArgumentParser(description='''prepare_chinese_ref''') parser.add_argument( '''--file_name''', type=str, default='''./resources/chinese-demo.txt''', help='''file need process, same as training data in lm''', ) parser.add_argument( '''--ltp''', type=str, default='''./resources/ltp''', help='''resources for LTP tokenizer, usually a path''' ) parser.add_argument('''--bert''', type=str, default='''./resources/robert''', help='''resources for Bert tokenizer''') parser.add_argument('''--save_path''', type=str, default='''./resources/ref.txt''', help='''path to save res''') lowerCamelCase = parser.parse_args() main(args)
131
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available lowerCamelCase = { '''configuration_bloom''': ['''BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BloomConfig''', '''BloomOnnxConfig'''], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase = ['''BloomTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCamelCase = [ '''BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BloomForCausalLM''', '''BloomModel''', '''BloomPreTrainedModel''', '''BloomForSequenceClassification''', '''BloomForTokenClassification''', '''BloomForQuestionAnswering''', ] if TYPE_CHECKING: from .configuration_bloom import BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP, BloomConfig, BloomOnnxConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bloom_fast import BloomTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bloom import ( BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST, BloomForCausalLM, BloomForQuestionAnswering, BloomForSequenceClassification, BloomForTokenClassification, BloomModel, BloomPreTrainedModel, ) else: import sys lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
131
1
'''simple docstring''' def __lowercase ( __lowercase , __lowercase ) -> Optional[Any]: '''simple docstring''' _A = (boundary[1] - boundary[0]) / steps _A = boundary[0] _A = boundary[1] _A = make_points(__lowercase , __lowercase , __lowercase ) _A = 0.0 y += (h / 2.0) * f(__lowercase ) for i in x_i: # print(i) y += h * f(__lowercase ) y += (h / 2.0) * f(__lowercase ) return y def __lowercase ( __lowercase , __lowercase , __lowercase ) -> Optional[Any]: '''simple docstring''' _A = a + h while x < (b - h): yield x _A = x + h def __lowercase ( __lowercase ) -> Tuple: # enter your function here '''simple docstring''' _A = (x - 0) * (x - 0) return y def __lowercase ( ) -> List[Any]: '''simple docstring''' _A = 0.0 # Lower bound of integration _A = 1.0 # Upper bound of integration _A = 10.0 # define number of steps or resolution _A = [a, b] # define boundary of integration _A = method_a(__lowercase , __lowercase ) print(F'''y = {y}''' ) if __name__ == "__main__": main()
174
'''simple docstring''' import gc import random import unittest import torch from diffusers import ( IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ) from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference from . import IFPipelineTesterMixin @skip_mps class _UpperCAmelCase ( snake_case_ , snake_case_ , unittest.TestCase ): """simple docstring""" snake_case = IFPipeline snake_case = TEXT_TO_IMAGE_PARAMS - {'''width''', '''height''', '''latents'''} snake_case = TEXT_TO_IMAGE_BATCH_PARAMS snake_case = PipelineTesterMixin.required_optional_params - {'''latents'''} def lowerCAmelCase ( self : Union[str, Any] ): '''simple docstring''' return self._get_dummy_components() def lowerCAmelCase ( self : int , __UpperCAmelCase : str , __UpperCAmelCase : List[Any]=0 ): '''simple docstring''' if str(__UpperCAmelCase ).startswith("mps" ): _A = torch.manual_seed(__UpperCAmelCase ) else: _A = torch.Generator(device=__UpperCAmelCase ).manual_seed(__UpperCAmelCase ) _A = { "prompt": "A painting of a squirrel eating a burger", "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs def lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' self._test_save_load_optional_components() @unittest.skipIf(torch_device != "cuda" , reason="float16 requires CUDA" ) def lowerCAmelCase ( self : Dict ): '''simple docstring''' super().test_save_load_floataa(expected_max_diff=1E-1 ) def lowerCAmelCase ( self : Tuple ): '''simple docstring''' self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def lowerCAmelCase ( self : Union[str, Any] ): '''simple docstring''' self._test_save_load_local() def lowerCAmelCase ( self : str ): '''simple docstring''' self._test_inference_batch_single_identical( expected_max_diff=1E-2 , ) @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def lowerCAmelCase ( self : int ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @slow @require_torch_gpu class _UpperCAmelCase ( unittest.TestCase ): """simple docstring""" def lowerCAmelCase ( self : Any ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : Tuple ): '''simple docstring''' _A = IFPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0" , variant="fp16" , torch_dtype=torch.floataa ) _A = IFSuperResolutionPipeline.from_pretrained( "DeepFloyd/IF-II-L-v1.0" , variant="fp16" , torch_dtype=torch.floataa , text_encoder=__UpperCAmelCase , tokenizer=__UpperCAmelCase ) # pre compute text embeddings and remove T5 to save memory pipe_a.text_encoder.to("cuda" ) _A , _A = pipe_a.encode_prompt("anime turtle" , device="cuda" ) del pipe_a.tokenizer del pipe_a.text_encoder gc.collect() _A = None _A = None pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # img2img _A = IFImgaImgPipeline(**pipe_a.components ) _A = IFImgaImgSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_imgaimg(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) pipe_a.remove_all_hooks() pipe_a.remove_all_hooks() # inpainting _A = IFInpaintingPipeline(**pipe_a.components ) _A = IFInpaintingSuperResolutionPipeline(**pipe_a.components ) pipe_a.enable_model_cpu_offload() pipe_a.enable_model_cpu_offload() pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) pipe_a.unet.set_attn_processor(AttnAddedKVProcessor() ) self._test_if_inpainting(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) def lowerCAmelCase ( self : List[str] , __UpperCAmelCase : int , __UpperCAmelCase : str , __UpperCAmelCase : Optional[Any] , __UpperCAmelCase : int ): '''simple docstring''' _start_torch_memory_measurement() _A = torch.Generator(device="cpu" ).manual_seed(0 ) _A = pipe_a( prompt_embeds=__UpperCAmelCase , negative_prompt_embeds=__UpperCAmelCase , num_inference_steps=2 , generator=__UpperCAmelCase , output_type="np" , ) _A = output.images[0] assert image.shape == (64, 64, 3) _A = torch.cuda.max_memory_allocated() assert mem_bytes < 13 * 10**9 _A = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy" ) assert_mean_pixel_difference(__UpperCAmelCase , __UpperCAmelCase ) # pipeline 2 _start_torch_memory_measurement() _A = torch.Generator(device="cpu" ).manual_seed(0 ) _A = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(__UpperCAmelCase ) _A = pipe_a( prompt_embeds=__UpperCAmelCase , negative_prompt_embeds=__UpperCAmelCase , image=__UpperCAmelCase , generator=__UpperCAmelCase , num_inference_steps=2 , output_type="np" , ) _A = output.images[0] assert image.shape == (256, 256, 3) _A = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 _A = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy" ) assert_mean_pixel_difference(__UpperCAmelCase , __UpperCAmelCase ) def lowerCAmelCase ( self : Tuple , __UpperCAmelCase : Any , __UpperCAmelCase : List[Any] , __UpperCAmelCase : List[Any] , __UpperCAmelCase : List[str] ): '''simple docstring''' _start_torch_memory_measurement() _A = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(__UpperCAmelCase ) _A = torch.Generator(device="cpu" ).manual_seed(0 ) _A = pipe_a( prompt_embeds=__UpperCAmelCase , negative_prompt_embeds=__UpperCAmelCase , image=__UpperCAmelCase , num_inference_steps=2 , generator=__UpperCAmelCase , output_type="np" , ) _A = output.images[0] assert image.shape == (64, 64, 3) _A = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 _A = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy" ) assert_mean_pixel_difference(__UpperCAmelCase , __UpperCAmelCase ) # pipeline 2 _start_torch_memory_measurement() _A = torch.Generator(device="cpu" ).manual_seed(0 ) _A = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(__UpperCAmelCase ) _A = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(__UpperCAmelCase ) _A = pipe_a( prompt_embeds=__UpperCAmelCase , negative_prompt_embeds=__UpperCAmelCase , image=__UpperCAmelCase , original_image=__UpperCAmelCase , generator=__UpperCAmelCase , num_inference_steps=2 , output_type="np" , ) _A = output.images[0] assert image.shape == (256, 256, 3) _A = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 _A = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy" ) assert_mean_pixel_difference(__UpperCAmelCase , __UpperCAmelCase ) def lowerCAmelCase ( self : Optional[int] , __UpperCAmelCase : Dict , __UpperCAmelCase : Dict , __UpperCAmelCase : Tuple , __UpperCAmelCase : Optional[int] ): '''simple docstring''' _start_torch_memory_measurement() _A = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(__UpperCAmelCase ) _A = floats_tensor((1, 3, 64, 64) , rng=random.Random(1 ) ).to(__UpperCAmelCase ) _A = torch.Generator(device="cpu" ).manual_seed(0 ) _A = pipe_a( prompt_embeds=__UpperCAmelCase , negative_prompt_embeds=__UpperCAmelCase , image=__UpperCAmelCase , mask_image=__UpperCAmelCase , num_inference_steps=2 , generator=__UpperCAmelCase , output_type="np" , ) _A = output.images[0] assert image.shape == (64, 64, 3) _A = torch.cuda.max_memory_allocated() assert mem_bytes < 10 * 10**9 _A = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy" ) assert_mean_pixel_difference(__UpperCAmelCase , __UpperCAmelCase ) # pipeline 2 _start_torch_memory_measurement() _A = torch.Generator(device="cpu" ).manual_seed(0 ) _A = floats_tensor((1, 3, 64, 64) , rng=random.Random(0 ) ).to(__UpperCAmelCase ) _A = floats_tensor((1, 3, 256, 256) , rng=random.Random(0 ) ).to(__UpperCAmelCase ) _A = floats_tensor((1, 3, 256, 256) , rng=random.Random(1 ) ).to(__UpperCAmelCase ) _A = pipe_a( prompt_embeds=__UpperCAmelCase , negative_prompt_embeds=__UpperCAmelCase , image=__UpperCAmelCase , mask_image=__UpperCAmelCase , original_image=__UpperCAmelCase , generator=__UpperCAmelCase , num_inference_steps=2 , output_type="np" , ) _A = output.images[0] assert image.shape == (256, 256, 3) _A = torch.cuda.max_memory_allocated() assert mem_bytes < 4 * 10**9 _A = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy" ) assert_mean_pixel_difference(__UpperCAmelCase , __UpperCAmelCase ) def __lowercase ( ) -> List[str]: '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats()
174
1
import warnings from functools import wraps from typing import Callable def lowercase_( SCREAMING_SNAKE_CASE_ ): '''simple docstring''' @wraps(SCREAMING_SNAKE_CASE_ ) def _inner_fn(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ): warnings.warn( (f"""'{fn.__name__}' is experimental and might be subject to breaking changes in the future.""") , SCREAMING_SNAKE_CASE_ , ) return fn(*SCREAMING_SNAKE_CASE_ , **SCREAMING_SNAKE_CASE_ ) return _inner_fn
283
# Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.whisper import WhisperForConditionalGeneration, WhisperProcessor from .base import PipelineTool class UpperCAmelCase_ ( UpperCamelCase ): '''simple docstring''' __A : Dict = "openai/whisper-base" __A : str = ( "This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the " "transcribed text." ) __A : Any = "transcriber" __A : Any = WhisperProcessor __A : int = WhisperForConditionalGeneration __A : Any = ["audio"] __A : List[str] = ["text"] def _snake_case ( self , __A ): """simple docstring""" return self.pre_processor(__A , return_tensors="pt" ).input_features def _snake_case ( self , __A ): """simple docstring""" return self.model.generate(inputs=__A ) def _snake_case ( self , __A ): """simple docstring""" return self.pre_processor.batch_decode(__A , skip_special_tokens=__A )[0]
283
1
'''simple docstring''' import os import sys import warnings from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen from ..table import array_cast from ..utils.file_utils import is_local_path from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: import PIL.Image from .features import FeatureType lowercase__ : Optional[List[str]] = None lowercase__ : Optional[Any] = '<' if sys.byteorder == 'little' else '>' # Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image lowercase__ : Dict = [ np.dtype('''|b1'''), np.dtype('''|u1'''), np.dtype('''<u2'''), np.dtype('''>u2'''), np.dtype('''<i2'''), np.dtype('''>i2'''), np.dtype('''<u4'''), np.dtype('''>u4'''), np.dtype('''<i4'''), np.dtype('''>i4'''), np.dtype('''<f4'''), np.dtype('''>f4'''), np.dtype('''<f8'''), np.dtype('''>f8'''), ] @dataclass class SCREAMING_SNAKE_CASE : lowerCAmelCase = True lowerCAmelCase = None # Automatically constructed lowerCAmelCase = '''PIL.Image.Image''' lowerCAmelCase = pa.struct({'''bytes''': pa.binary(), '''path''': pa.string()} ) lowerCAmelCase = field(default='''Image''' , init=__SCREAMING_SNAKE_CASE , repr=__SCREAMING_SNAKE_CASE ) def __call__( self): '''simple docstring''' return self.pa_type def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase): '''simple docstring''' if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support encoding images, please install \'Pillow\'.') if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE): __A : Dict = np.array(_SCREAMING_SNAKE_CASE) if isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE): return {"path": value, "bytes": None} elif isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE): return {"path": None, "bytes": value} elif isinstance(_SCREAMING_SNAKE_CASE , np.ndarray): # convert the image array to PNG/TIFF bytes return encode_np_array(_SCREAMING_SNAKE_CASE) elif isinstance(_SCREAMING_SNAKE_CASE , PIL.Image.Image): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(_SCREAMING_SNAKE_CASE) elif value.get('path') is not None and os.path.isfile(value['path']): # we set "bytes": None to not duplicate the data if they're already available locally return {"bytes": None, "path": value.get('path')} elif value.get('bytes') is not None or value.get('path') is not None: # store the image bytes, and path is used to infer the image format using the file extension return {"bytes": value.get('bytes'), "path": value.get('path')} else: raise ValueError( F'An image sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.') def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase , _UpperCAmelCase=None): '''simple docstring''' if not self.decode: raise RuntimeError('Decoding is disabled for this feature. Please use Image(decode=True) instead.') if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support decoding images, please install \'Pillow\'.') if token_per_repo_id is None: __A : Optional[int] = {} __A : Union[str, Any] = value["path"], value["bytes"] if bytes_ is None: if path is None: raise ValueError(F'An image should have one of \'path\' or \'bytes\' but both are None in {value}.') else: if is_local_path(_SCREAMING_SNAKE_CASE): __A : str = PIL.Image.open(_SCREAMING_SNAKE_CASE) else: __A : Optional[int] = path.split('::')[-1] try: __A : Optional[int] = string_to_dict(_SCREAMING_SNAKE_CASE , config.HUB_DATASETS_URL)["repo_id"] __A : List[Any] = token_per_repo_id.get(_SCREAMING_SNAKE_CASE) except ValueError: __A : str = None with xopen(_SCREAMING_SNAKE_CASE , 'rb' , use_auth_token=_SCREAMING_SNAKE_CASE) as f: __A : List[str] = BytesIO(f.read()) __A : Dict = PIL.Image.open(bytes_) else: __A : List[str] = PIL.Image.open(BytesIO(bytes_)) image.load() # to avoid "Too many open files" errors return image def SCREAMING_SNAKE_CASE ( self): '''simple docstring''' from .features import Value return ( self if self.decode else { "bytes": Value('binary'), "path": Value('string'), } ) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase): '''simple docstring''' if pa.types.is_string(storage.type): __A : str = pa.array([None] * len(_SCREAMING_SNAKE_CASE) , type=pa.binary()) __A : Any = pa.StructArray.from_arrays([bytes_array, storage] , ['bytes', 'path'] , mask=storage.is_null()) elif pa.types.is_binary(storage.type): __A : List[str] = pa.array([None] * len(_SCREAMING_SNAKE_CASE) , type=pa.string()) __A : Any = pa.StructArray.from_arrays([storage, path_array] , ['bytes', 'path'] , mask=storage.is_null()) elif pa.types.is_struct(storage.type): if storage.type.get_field_index('bytes') >= 0: __A : Union[str, Any] = storage.field('bytes') else: __A : List[str] = pa.array([None] * len(_SCREAMING_SNAKE_CASE) , type=pa.binary()) if storage.type.get_field_index('path') >= 0: __A : Any = storage.field('path') else: __A : str = pa.array([None] * len(_SCREAMING_SNAKE_CASE) , type=pa.string()) __A : Tuple = pa.StructArray.from_arrays([bytes_array, path_array] , ['bytes', 'path'] , mask=storage.is_null()) elif pa.types.is_list(storage.type): __A : Dict = pa.array( [encode_np_array(np.array(_SCREAMING_SNAKE_CASE))['bytes'] if arr is not None else None for arr in storage.to_pylist()] , type=pa.binary() , ) __A : Optional[int] = pa.array([None] * len(_SCREAMING_SNAKE_CASE) , type=pa.string()) __A : Dict = pa.StructArray.from_arrays( [bytes_array, path_array] , ['bytes', 'path'] , mask=bytes_array.is_null()) return array_cast(_SCREAMING_SNAKE_CASE , self.pa_type) def SCREAMING_SNAKE_CASE ( self , _UpperCAmelCase): '''simple docstring''' @no_op_if_value_is_null def path_to_bytes(_UpperCAmelCase): with xopen(_SCREAMING_SNAKE_CASE , 'rb') as f: __A : List[Any] = f.read() return bytes_ __A : int = pa.array( [ (path_to_bytes(x['path']) if x['bytes'] is None else x['bytes']) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) __A : List[Any] = pa.array( [os.path.basename(_SCREAMING_SNAKE_CASE) if path is not None else None for path in storage.field('path').to_pylist()] , type=pa.string() , ) __A : str = pa.StructArray.from_arrays([bytes_array, path_array] , ['bytes', 'path'] , mask=bytes_array.is_null()) return array_cast(_SCREAMING_SNAKE_CASE , self.pa_type) def _lowerCAmelCase ( ) -> List[str]: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support encoding images, please install \'Pillow\'.' ) global _IMAGE_COMPRESSION_FORMATS if _IMAGE_COMPRESSION_FORMATS is None: PIL.Image.init() __A : Dict = list(set(PIL.Image.OPEN.keys() ) & set(PIL.Image.SAVE.keys() ) ) return _IMAGE_COMPRESSION_FORMATS def _lowerCAmelCase ( __snake_case : str ) -> bytes: __A : Union[str, Any] = BytesIO() if image.format in list_image_compression_formats(): __A : List[Any] = image.format else: __A : List[Any] = "PNG" if image.mode in ["1", "L", "LA", "RGB", "RGBA"] else "TIFF" image.save(__snake_case , format=__snake_case ) return buffer.getvalue() def _lowerCAmelCase ( __snake_case : Optional[Any] ) -> dict: if hasattr(__snake_case , 'filename' ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(__snake_case )} def _lowerCAmelCase ( __snake_case : List[str] ) -> dict: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support encoding images, please install \'Pillow\'.' ) __A : str = array.dtype __A : Optional[Any] = dtype.byteorder if dtype.byteorder != "=" else _NATIVE_BYTEORDER __A : Optional[Any] = dtype.kind __A : List[Any] = dtype.itemsize __A : Optional[Any] = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: __A : Dict = np.dtype('|u1' ) if dtype_kind not in ["u", "i"]: raise TypeError( f'Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.' ) if dtype is not dest_dtype: warnings.warn(f'Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'' ) # Exact match elif dtype in _VALID_IMAGE_ARRAY_DTPYES: __A : List[Any] = dtype else: # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually) while dtype_itemsize >= 1: __A : List[str] = dtype_byteorder + dtype_kind + str(__snake_case ) __A : Union[str, Any] = np.dtype(__snake_case ) if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES: warnings.warn(f'Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\'' ) break else: dtype_itemsize //= 2 if dest_dtype is None: raise TypeError( f'Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}' ) __A : Union[str, Any] = PIL.Image.fromarray(array.astype(__snake_case ) ) return {"path": None, "bytes": image_to_bytes(__snake_case )} def _lowerCAmelCase ( __snake_case : Optional[Any] ) -> List[dict]: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support encoding images, please install \'Pillow\'.' ) if objs: __A : str = first_non_null_value(__snake_case ) if isinstance(__snake_case , __snake_case ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(__snake_case , np.ndarray ): __A : List[Any] = no_op_if_value_is_null(__snake_case ) return [obj_to_image_dict_func(__snake_case ) for obj in objs] elif isinstance(__snake_case , PIL.Image.Image ): __A : int = no_op_if_value_is_null(__snake_case ) return [obj_to_image_dict_func(__snake_case ) for obj in objs] else: return objs else: return objs
364
'''simple docstring''' lowercase__ : Any = {'''a''': ['''c''', '''b'''], '''b''': ['''d''', '''e'''], '''c''': [], '''d''': [], '''e''': []} lowercase__ : List[Any] = ['''a''', '''b''', '''c''', '''d''', '''e'''] def _lowerCAmelCase ( __snake_case : str , __snake_case : Tuple , __snake_case : int ) -> Tuple: __A : List[str] = start # add current to visited visited.append(__snake_case ) __A : Optional[int] = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: __A : int = topological_sort(__snake_case , __snake_case , __snake_case ) # if all neighbors visited add current to sort sort.append(__snake_case ) # if all vertices haven't been visited select a new one to visit if len(__snake_case ) != len(__snake_case ): for vertice in vertices: if vertice not in visited: __A : Dict = topological_sort(__snake_case , __snake_case , __snake_case ) # return sort return sort if __name__ == "__main__": lowercase__ : Tuple = topological_sort('''a''', [], []) print(sort)
190
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() lowercase : Optional[Any] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( __A , __A=False ) -> int: _snake_case = [] 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" _snake_case = [(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 SCREAMING_SNAKE_CASE__ ( __A , __A , __A=False ) -> Union[str, Any]: for i in range(config.num_hidden_layers ): if base_model: _snake_case = '' else: _snake_case = 'vit.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) _snake_case = state_dict.pop(F'blocks.{i}.attn.qkv.weight' ) _snake_case = state_dict.pop(F'blocks.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict _snake_case = in_proj_weight[ : config.hidden_size, : ] _snake_case = in_proj_bias[: config.hidden_size] _snake_case = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] _snake_case = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] _snake_case = in_proj_weight[ -config.hidden_size :, : ] _snake_case = in_proj_bias[-config.hidden_size :] def SCREAMING_SNAKE_CASE__ ( __A ) -> List[str]: _snake_case = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(__A , __A ) def SCREAMING_SNAKE_CASE__ ( __A , __A , __A ) -> Optional[int]: _snake_case = dct.pop(__A ) _snake_case = val def SCREAMING_SNAKE_CASE__ ( ) -> Any: _snake_case = 'http://images.cocodataset.org/val2017/000000039769.jpg' _snake_case = Image.open(requests.get(__A , stream=__A ).raw ) return im @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( __A , __A , __A=True ) -> Optional[int]: _snake_case = ViTConfig() # patch_size if model_name[-1] == "8": _snake_case = 8 # set labels if required if not base_model: _snake_case = 1_000 _snake_case = 'huggingface/label-files' _snake_case = 'imagenet-1k-id2label.json' _snake_case = json.load(open(hf_hub_download(__A , __A , repo_type='dataset' ) , 'r' ) ) _snake_case = {int(__A ): v for k, v in idalabel.items()} _snake_case = idalabel _snake_case = {v: k for k, v in idalabel.items()} # size of the architecture if model_name in ["dino_vits8", "dino_vits16"]: _snake_case = 384 _snake_case = 1_536 _snake_case = 12 _snake_case = 6 # load original model from torch hub _snake_case = torch.hub.load('facebookresearch/dino:main' , __A ) original_model.eval() # load state_dict of original model, remove and rename some keys _snake_case = original_model.state_dict() if base_model: remove_classification_head_(__A ) _snake_case = 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: _snake_case = ViTModel(__A , add_pooling_layer=__A ).eval() else: _snake_case = ViTForImageClassification(__A ).eval() model.load_state_dict(__A ) # Check outputs on an image, prepared by ViTImageProcessor _snake_case = ViTImageProcessor() _snake_case = image_processor(images=prepare_img() , return_tensors='pt' ) _snake_case = encoding['pixel_values'] _snake_case = model(__A ) if base_model: _snake_case = original_model(__A ) assert torch.allclose(__A , outputs.last_hidden_state[:, 0, :] , atol=1e-1 ) else: _snake_case = 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__": lowercase : List[str] = 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) lowercase : Union[str, Any] = parser.parse_args() convert_vit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.base_model)
42
import torch from diffusers import DDPMScheduler from .test_schedulers import SchedulerCommonTest class UpperCAmelCase_ ( __lowercase ): """simple docstring""" UpperCAmelCase__ : List[Any] = (DDPMScheduler,) def __lowercase ( self , **_a ) -> Any: _a : List[Any] = { '''num_train_timesteps''': 1_0_0_0, '''beta_start''': 0.0001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''variance_type''': '''fixed_small''', '''clip_sample''': True, } config.update(**_a ) return config def __lowercase ( self ) -> Any: for timesteps in [1, 5, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=_a ) def __lowercase ( self ) -> List[Any]: for beta_start, beta_end in zip([0.0001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=_a , beta_end=_a ) def __lowercase ( self ) -> List[str]: for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=_a ) def __lowercase ( self ) -> Optional[Any]: for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=_a ) def __lowercase ( self ) -> str: for clip_sample in [True, False]: self.check_over_configs(clip_sample=_a ) def __lowercase ( self ) -> Dict: self.check_over_configs(thresholding=_a ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=_a , prediction_type=_a , sample_max_value=_a , ) def __lowercase ( self ) -> Optional[Any]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=_a ) def __lowercase ( self ) -> int: for t in [0, 5_0_0, 9_9_9]: self.check_over_forward(time_step=_a ) def __lowercase ( self ) -> int: _a : int = self.scheduler_classes[0] _a : List[Any] = self.get_scheduler_config() _a : Dict = scheduler_class(**_a ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(4_8_7 ) - 0.0_0979 ) ) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(9_9_9 ) - 0.02 ) ) < 1e-5 def __lowercase ( self ) -> Tuple: _a : int = self.scheduler_classes[0] _a : int = self.get_scheduler_config() _a : int = scheduler_class(**_a ) _a : Optional[int] = len(_a ) _a : Optional[Any] = self.dummy_model() _a : str = self.dummy_sample_deter _a : Union[str, Any] = torch.manual_seed(0 ) for t in reversed(range(_a ) ): # 1. predict noise residual _a : str = model(_a , _a ) # 2. predict previous mean of sample x_t-1 _a : Optional[int] = scheduler.step(_a , _a , _a , generator=_a ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance _a : List[Any] = pred_prev_sample _a : str = torch.sum(torch.abs(_a ) ) _a : Optional[Any] = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 258.9606 ) < 1e-2 assert abs(result_mean.item() - 0.3372 ) < 1e-3 def __lowercase ( self ) -> Optional[Any]: _a : Optional[int] = self.scheduler_classes[0] _a : Optional[Any] = self.get_scheduler_config(prediction_type='''v_prediction''' ) _a : Union[str, Any] = scheduler_class(**_a ) _a : Dict = len(_a ) _a : int = self.dummy_model() _a : Tuple = self.dummy_sample_deter _a : List[Any] = torch.manual_seed(0 ) for t in reversed(range(_a ) ): # 1. predict noise residual _a : Dict = model(_a , _a ) # 2. predict previous mean of sample x_t-1 _a : int = scheduler.step(_a , _a , _a , generator=_a ).prev_sample # if t > 0: # noise = self.dummy_sample_deter # variance = scheduler.get_variance(t) ** (0.5) * noise # # sample = pred_prev_sample + variance _a : str = pred_prev_sample _a : str = torch.sum(torch.abs(_a ) ) _a : Tuple = torch.mean(torch.abs(_a ) ) assert abs(result_sum.item() - 202.0296 ) < 1e-2 assert abs(result_mean.item() - 0.2631 ) < 1e-3 def __lowercase ( self ) -> Dict: _a : Union[str, Any] = self.scheduler_classes[0] _a : Tuple = self.get_scheduler_config() _a : Any = scheduler_class(**_a ) _a : Optional[Any] = [1_0_0, 8_7, 5_0, 1, 0] scheduler.set_timesteps(timesteps=_a ) _a : Optional[int] = scheduler.timesteps for i, timestep in enumerate(_a ): if i == len(_a ) - 1: _a : Dict = -1 else: _a : Tuple = timesteps[i + 1] _a : Optional[Any] = scheduler.previous_timestep(_a ) _a : Optional[Any] = prev_t.item() self.assertEqual(_a , _a ) def __lowercase ( self ) -> Optional[Any]: _a : Dict = self.scheduler_classes[0] _a : List[str] = self.get_scheduler_config() _a : Tuple = scheduler_class(**_a ) _a : str = [1_0_0, 8_7, 5_0, 5_1, 0] with self.assertRaises(_a , msg='''`custom_timesteps` must be in descending order.''' ): scheduler.set_timesteps(timesteps=_a ) def __lowercase ( self ) -> str: _a : List[str] = self.scheduler_classes[0] _a : List[str] = self.get_scheduler_config() _a : Dict = scheduler_class(**_a ) _a : Union[str, Any] = [1_0_0, 8_7, 5_0, 1, 0] _a : Optional[Any] = len(_a ) with self.assertRaises(_a , msg='''Can only pass one of `num_inference_steps` or `custom_timesteps`.''' ): scheduler.set_timesteps(num_inference_steps=_a , timesteps=_a ) def __lowercase ( self ) -> Optional[int]: _a : Dict = self.scheduler_classes[0] _a : Union[str, Any] = self.get_scheduler_config() _a : int = scheduler_class(**_a ) _a : str = [scheduler.config.num_train_timesteps] with self.assertRaises( _a , msg='''`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}''' , ): scheduler.set_timesteps(timesteps=_a )
235
0
from __future__ import annotations from typing import Any class SCREAMING_SNAKE_CASE : def __init__( self : str , a : int )-> None: """simple docstring""" lowercase__ = num_of_nodes lowercase__ = [] lowercase__ = {} def SCREAMING_SNAKE_CASE_ ( self : Dict , a : int , a : int , a : int )-> None: """simple docstring""" self.m_edges.append([u_node, v_node, weight] ) def SCREAMING_SNAKE_CASE_ ( self : Dict , a : int )-> int: """simple docstring""" if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def SCREAMING_SNAKE_CASE_ ( self : Any , a : int )-> None: """simple docstring""" if self.m_component[u_node] != u_node: for k in self.m_component: lowercase__ = self.find_component(a ) def SCREAMING_SNAKE_CASE_ ( self : Optional[int] , a : list[int] , a : int , a : int )-> None: """simple docstring""" if component_size[u_node] <= component_size[v_node]: lowercase__ = v_node component_size[v_node] += component_size[u_node] self.set_component(a ) elif component_size[u_node] >= component_size[v_node]: lowercase__ = self.find_component(a ) component_size[u_node] += component_size[v_node] self.set_component(a ) def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] )-> None: """simple docstring""" lowercase__ = [] lowercase__ = 0 lowercase__ = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) lowercase__ = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: lowercase__ , lowercase__ , lowercase__ = edge lowercase__ = self.m_component[u] lowercase__ = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): lowercase__ = [u, v, w] for edge in minimum_weight_edge: if isinstance(a , a ): lowercase__ , lowercase__ , lowercase__ = edge lowercase__ = self.m_component[u] lowercase__ = self.m_component[v] if u_component != v_component: mst_weight += w self.union(a , a , a ) print(f"""Added edge [{u} - {v}]\nAdded weight: {w}\n""" ) num_of_components -= 1 lowercase__ = [-1] * self.m_num_of_nodes print(f"""The total weight of the minimal spanning tree is: {mst_weight}""" ) def __UpperCamelCase () -> None: pass if __name__ == "__main__": import doctest doctest.testmod()
269
import unittest import numpy as np from transformers import DistilBertConfig, 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.distilbert.modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, ) class SCREAMING_SNAKE_CASE (unittest.TestCase ): def __init__( self : List[str] , a : Dict , a : Optional[int]=13 , a : int=7 , a : List[str]=True , a : Any=True , a : Dict=True , a : List[Any]=True , a : List[str]=99 , a : Dict=32 , a : List[str]=5 , a : Tuple=4 , a : Optional[int]=37 , a : Union[str, Any]="gelu" , a : Optional[Any]=0.1 , a : Optional[int]=0.1 , a : Optional[Any]=512 , a : Dict=16 , a : Any=2 , a : Tuple=0.02 , a : Optional[Any]=4 , )-> int: """simple docstring""" lowercase__ = parent lowercase__ = batch_size lowercase__ = seq_length lowercase__ = is_training lowercase__ = use_attention_mask lowercase__ = use_token_type_ids lowercase__ = use_labels lowercase__ = vocab_size lowercase__ = hidden_size lowercase__ = num_hidden_layers lowercase__ = num_attention_heads lowercase__ = intermediate_size lowercase__ = hidden_act lowercase__ = hidden_dropout_prob lowercase__ = attention_probs_dropout_prob lowercase__ = max_position_embeddings lowercase__ = type_vocab_size lowercase__ = type_sequence_label_size lowercase__ = initializer_range lowercase__ = num_choices def SCREAMING_SNAKE_CASE_ ( self : Union[str, Any] )-> Union[str, Any]: """simple docstring""" lowercase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase__ = None if self.use_attention_mask: lowercase__ = random_attention_mask([self.batch_size, self.seq_length] ) lowercase__ = DistilBertConfig( vocab_size=self.vocab_size , dim=self.hidden_size , n_layers=self.num_hidden_layers , n_heads=self.num_attention_heads , hidden_dim=self.intermediate_size , hidden_act=self.hidden_act , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , tie_weights_=a , ) return config, input_ids, attention_mask def SCREAMING_SNAKE_CASE_ ( self : Optional[Any] )-> Any: """simple docstring""" lowercase__ = self.prepare_config_and_inputs() lowercase__ , lowercase__ , lowercase__ = config_and_inputs lowercase__ = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict @require_flax class SCREAMING_SNAKE_CASE (UpperCAmelCase , unittest.TestCase ): _UpperCamelCase : List[Any] = ( ( FlaxDistilBertModel, FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertForQuestionAnswering, ) if is_flax_available() else () ) def SCREAMING_SNAKE_CASE_ ( self : Dict )-> List[str]: """simple docstring""" lowercase__ = FlaxDistilBertModelTester(self ) @slow def SCREAMING_SNAKE_CASE_ ( self : List[str] )-> int: """simple docstring""" for model_class_name in self.all_model_classes: lowercase__ = model_class_name.from_pretrained('distilbert-base-uncased' ) lowercase__ = model(np.ones((1, 1) ) ) self.assertIsNotNone(a ) @require_flax class SCREAMING_SNAKE_CASE (unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self : List[str] )-> List[str]: """simple docstring""" lowercase__ = FlaxDistilBertModel.from_pretrained('distilbert-base-uncased' ) lowercase__ = np.array([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]] ) lowercase__ = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) lowercase__ = model(a , attention_mask=a )[0] lowercase__ = (1, 11, 768) self.assertEqual(output.shape , a ) lowercase__ = np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]] ) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] , a , atol=1E-4 ) )
269
1
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_speech_available, is_torch_available, ) lowercase__ :Optional[Any] = { "configuration_trocr": ["TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP", "TrOCRConfig"], "processing_trocr": ["TrOCRProcessor"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ :Optional[int] = [ "TROCR_PRETRAINED_MODEL_ARCHIVE_LIST", "TrOCRForCausalLM", "TrOCRPreTrainedModel", ] if TYPE_CHECKING: from .configuration_trocr import TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP, TrOCRConfig from .processing_trocr import TrOCRProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_trocr import TROCR_PRETRAINED_MODEL_ARCHIVE_LIST, TrOCRForCausalLM, TrOCRPreTrainedModel else: import sys lowercase__ :List[Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
101
import argparse import torch from ...utils import logging from . import AlbertConfig, AlbertForPreTraining, load_tf_weights_in_albert logging.set_verbosity_info() def snake_case ( snake_case__ :int , snake_case__ :List[str] , snake_case__ :Union[str, Any]) -> str: # Initialise PyTorch model _A = AlbertConfig.from_json_file(snake_case__) print(F'''Building PyTorch model from configuration: {config}''') _A = AlbertForPreTraining(snake_case__) # Load weights from tf checkpoint load_tf_weights_in_albert(snake_case__ , snake_case__ , snake_case__) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''') torch.save(model.state_dict() , snake_case__) if __name__ == "__main__": _SCREAMING_SNAKE_CASE = 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( '--albert_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained ALBERT 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 = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.albert_config_file, args.pytorch_dump_path)
180
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase__ :List[str] = logging.get_logger(__name__) lowercase__ :List[Any] = { "roberta-base": "https://huggingface.co/roberta-base/resolve/main/config.json", "roberta-large": "https://huggingface.co/roberta-large/resolve/main/config.json", "roberta-large-mnli": "https://huggingface.co/roberta-large-mnli/resolve/main/config.json", "distilroberta-base": "https://huggingface.co/distilroberta-base/resolve/main/config.json", "roberta-base-openai-detector": "https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json", "roberta-large-openai-detector": "https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json", } class lowercase ( SCREAMING_SNAKE_CASE__ ): lowercase_ : Optional[int] ='''roberta''' def __init__( self ,A__=5_0_2_6_5 ,A__=7_6_8 ,A__=1_2 ,A__=1_2 ,A__=3_0_7_2 ,A__="gelu" ,A__=0.1 ,A__=0.1 ,A__=5_1_2 ,A__=2 ,A__=0.02 ,A__=1E-12 ,A__=1 ,A__=0 ,A__=2 ,A__="absolute" ,A__=True ,A__=None ,**A__ ,): super().__init__(pad_token_id=A__ ,bos_token_id=A__ ,eos_token_id=A__ ,**A__) lowercase = vocab_size lowercase = hidden_size lowercase = num_hidden_layers lowercase = num_attention_heads lowercase = hidden_act lowercase = intermediate_size lowercase = hidden_dropout_prob lowercase = attention_probs_dropout_prob lowercase = max_position_embeddings lowercase = type_vocab_size lowercase = initializer_range lowercase = layer_norm_eps lowercase = position_embedding_type lowercase = use_cache lowercase = classifier_dropout class lowercase ( SCREAMING_SNAKE_CASE__ ): @property def A__ ( self): if self.task == "multiple-choice": lowercase = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: lowercase = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ])
97
from statistics import mean import numpy as np def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): '''simple docstring''' lowercase = 0 # Number of processes finished lowercase = 0 # Displays the finished process. # If it is 0, the performance is completed if it is 1, before the performance. lowercase = [0] * no_of_process # List to include calculation results lowercase = [0] * no_of_process # Sort by arrival time. lowercase = [burst_time[i] for i in np.argsort(lowerCAmelCase__ )] lowercase = [process_name[i] for i in np.argsort(lowerCAmelCase__ )] arrival_time.sort() while no_of_process > finished_process_count: lowercase = 0 while finished_process[i] == 1: i += 1 if current_time < arrival_time[i]: lowercase = arrival_time[i] lowercase = 0 # Index showing the location of the process being performed lowercase = 0 # Saves the current response ratio. lowercase = 0 for i in range(0 , lowerCAmelCase__ ): if finished_process[i] == 0 and arrival_time[i] <= current_time: lowercase = (burst_time[i] + (current_time - arrival_time[i])) / burst_time[ i ] if response_ratio < temp: lowercase = temp lowercase = i # Calculate the turn around time lowercase = current_time + burst_time[loc] - arrival_time[loc] current_time += burst_time[loc] # Indicates that the process has been performed. lowercase = 1 # Increase finished_process_count by 1 finished_process_count += 1 return turn_around_time def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ): '''simple docstring''' lowercase = [0] * no_of_process for i in range(0 , lowerCAmelCase__ ): lowercase = turn_around_time[i] - burst_time[i] return waiting_time if __name__ == "__main__": lowercase__ :Dict = 5 lowercase__ :str = ["A", "B", "C", "D", "E"] lowercase__ :Optional[int] = [1, 2, 3, 4, 5] lowercase__ :List[Any] = [1, 2, 3, 4, 5] lowercase__ :List[str] = calculate_turn_around_time( process_name, arrival_time, burst_time, no_of_process ) lowercase__ :List[Any] = calculate_waiting_time( process_name, turn_around_time, burst_time, no_of_process ) print("Process name \tArrival time \tBurst time \tTurn around time \tWaiting time") for i in range(0, no_of_process): print( F'{process_name[i]}\t\t{arrival_time[i]}\t\t{burst_time[i]}\t\t' F'{turn_around_time[i]}\t\t\t{waiting_time[i]}' ) print(F'average waiting time : {mean(waiting_time):.5f}') print(F'average turn around time : {mean(turn_around_time):.5f}')
97
1
"""simple docstring""" def lowerCAmelCase_ ( snake_case_ : str ) ->Dict: lowerCamelCase__ , lowerCamelCase__ : Optional[int] =[], [] while len(snake_case_ ) > 1: lowerCamelCase__ , lowerCamelCase__ : Optional[int] =min(snake_case_ ), max(snake_case_ ) start.append(snake_case_ ) end.append(snake_case_ ) collection.remove(snake_case_ ) collection.remove(snake_case_ ) end.reverse() return start + collection + end if __name__ == "__main__": lowerCAmelCase = input("""Enter numbers separated by a comma:\n""").strip() lowerCAmelCase = [int(item) for item in user_input.split(""",""")] print(*merge_sort(unsorted), sep=""",""")
126
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL lowerCAmelCase = logging.get_logger(__name__) class A_ ( A__ ): """simple docstring""" SCREAMING_SNAKE_CASE_ = ["""pixel_values"""] def __init__( self :Union[str, Any] , lowerCamelCase_ :bool = True , lowerCamelCase_ :Dict[str, int] = None , lowerCamelCase_ :int = 0.9 , lowerCamelCase_ :PILImageResampling = PILImageResampling.BICUBIC , lowerCamelCase_ :bool = True , lowerCamelCase_ :Dict[str, int] = None , lowerCamelCase_ :Union[int, float] = 1 / 255 , lowerCamelCase_ :bool = True , lowerCamelCase_ :bool = True , lowerCamelCase_ :Optional[Union[float, List[float]]] = None , lowerCamelCase_ :Optional[Union[float, List[float]]] = None , **lowerCamelCase_ :Tuple , ): """simple docstring""" super().__init__(**lowerCamelCase_ ) lowerCamelCase__ : str =size if size is not None else {'shortest_edge': 224} lowerCamelCase__ : List[str] =get_size_dict(lowerCamelCase_ , default_to_square=lowerCamelCase_ ) lowerCamelCase__ : Union[str, Any] =crop_size if crop_size is not None else {'height': 224, 'width': 224} lowerCamelCase__ : str =get_size_dict(lowerCamelCase_ , param_name='crop_size' ) lowerCamelCase__ : Tuple =do_resize lowerCamelCase__ : List[Any] =size lowerCamelCase__ : List[str] =crop_pct lowerCamelCase__ : Union[str, Any] =resample lowerCamelCase__ : List[str] =do_center_crop lowerCamelCase__ : List[str] =crop_size lowerCamelCase__ : List[Any] =do_rescale lowerCamelCase__ : List[str] =rescale_factor lowerCamelCase__ : Tuple =do_normalize lowerCamelCase__ : int =image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN lowerCamelCase__ : List[Any] =image_std if image_std is not None else IMAGENET_DEFAULT_STD def UpperCAmelCase__ ( self :Any , lowerCamelCase_ :np.ndarray , lowerCamelCase_ :Dict[str, int] , lowerCamelCase_ :Optional[float] = None , lowerCamelCase_ :PILImageResampling = PILImageResampling.BICUBIC , lowerCamelCase_ :Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase_ :Any , ): """simple docstring""" lowerCamelCase__ : Union[str, Any] =get_size_dict(lowerCamelCase_ , default_to_square=lowerCamelCase_ ) if "shortest_edge" not in size and ("height" not in size or "width" not in size): raise ValueError(f"""size must contain 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}""" ) if crop_pct is not None: if "shortest_edge" in size: lowerCamelCase__ : Optional[int] =int(size['shortest_edge'] / crop_pct ) elif "height" in size and "width" in size: if size["height"] == size["width"]: lowerCamelCase__ : Union[str, Any] =int(size['height'] / crop_pct ) else: lowerCamelCase__ : Any =(int(size['height'] / crop_pct ), int(size['width'] / crop_pct )) else: raise ValueError('Invalid size for resize: {}'.format(lowerCamelCase_ ) ) lowerCamelCase__ : Tuple =get_resize_output_image_size(lowerCamelCase_ , size=lowerCamelCase_ , default_to_square=lowerCamelCase_ ) else: if "shortest_edge" in size: lowerCamelCase__ : str =get_resize_output_image_size(lowerCamelCase_ , size=size['shortest_edge'] , default_to_square=lowerCamelCase_ ) elif "height" in size and "width" in size: lowerCamelCase__ : Union[str, Any] =(size['height'], size['width']) else: raise ValueError('Invalid size for resize: {}'.format(lowerCamelCase_ ) ) return resize(lowerCamelCase_ , size=lowerCamelCase_ , resample=lowerCamelCase_ , data_format=lowerCamelCase_ , **lowerCamelCase_ ) def UpperCAmelCase__ ( self :Any , lowerCamelCase_ :np.ndarray , lowerCamelCase_ :Dict[str, int] , lowerCamelCase_ :Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase_ :str , ): """simple docstring""" lowerCamelCase__ : Tuple =get_size_dict(lowerCamelCase_ ) if "height" not in size or "width" not in size: raise ValueError(f"""size must contain 'height' and 'width' as keys. Got {size.keys()}""" ) return center_crop(lowerCamelCase_ , size=(size['height'], size['width']) , data_format=lowerCamelCase_ , **lowerCamelCase_ ) def UpperCAmelCase__ ( self :int , lowerCamelCase_ :np.ndarray , lowerCamelCase_ :Union[int, float] , lowerCamelCase_ :Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase_ :List[str] , ): """simple docstring""" return rescale(lowerCamelCase_ , scale=lowerCamelCase_ , data_format=lowerCamelCase_ , **lowerCamelCase_ ) def UpperCAmelCase__ ( self :List[Any] , lowerCamelCase_ :np.ndarray , lowerCamelCase_ :Union[float, List[float]] , lowerCamelCase_ :Union[float, List[float]] , lowerCamelCase_ :Optional[Union[str, ChannelDimension]] = None , **lowerCamelCase_ :Tuple , ): """simple docstring""" return normalize(lowerCamelCase_ , mean=lowerCamelCase_ , std=lowerCamelCase_ , data_format=lowerCamelCase_ , **lowerCamelCase_ ) def UpperCAmelCase__ ( self :Any , lowerCamelCase_ :ImageInput , lowerCamelCase_ :bool = None , lowerCamelCase_ :Dict[str, int] = None , lowerCamelCase_ :int = None , lowerCamelCase_ :PILImageResampling = None , lowerCamelCase_ :bool = None , lowerCamelCase_ :Dict[str, int] = None , lowerCamelCase_ :bool = None , lowerCamelCase_ :float = None , lowerCamelCase_ :bool = None , lowerCamelCase_ :Optional[Union[float, List[float]]] = None , lowerCamelCase_ :Optional[Union[float, List[float]]] = None , lowerCamelCase_ :Optional[Union[str, TensorType]] = None , lowerCamelCase_ :ChannelDimension = ChannelDimension.FIRST , **lowerCamelCase_ :List[str] , ): """simple docstring""" lowerCamelCase__ : Dict =do_resize if do_resize is not None else self.do_resize lowerCamelCase__ : Union[str, Any] =crop_pct if crop_pct is not None else self.crop_pct lowerCamelCase__ : Tuple =resample if resample is not None else self.resample lowerCamelCase__ : Any =do_center_crop if do_center_crop is not None else self.do_center_crop lowerCamelCase__ : Optional[Any] =do_rescale if do_rescale is not None else self.do_rescale lowerCamelCase__ : Optional[int] =rescale_factor if rescale_factor is not None else self.rescale_factor lowerCamelCase__ : Optional[Any] =do_normalize if do_normalize is not None else self.do_normalize lowerCamelCase__ : List[str] =image_mean if image_mean is not None else self.image_mean lowerCamelCase__ : List[Any] =image_std if image_std is not None else self.image_std lowerCamelCase__ : int =size if size is not None else self.size lowerCamelCase__ : Tuple =get_size_dict(lowerCamelCase_ , default_to_square=lowerCamelCase_ ) lowerCamelCase__ : Dict =crop_size if crop_size is not None else self.crop_size lowerCamelCase__ : str =get_size_dict(lowerCamelCase_ , param_name='crop_size' ) lowerCamelCase__ : Dict =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 or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_center_crop and crop_pct is None: raise ValueError('Crop_pct 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. lowerCamelCase__ : List[str] =[to_numpy_array(lowerCamelCase_ ) for image in images] if do_resize: lowerCamelCase__ : Tuple =[self.resize(image=lowerCamelCase_ , size=lowerCamelCase_ , crop_pct=lowerCamelCase_ , resample=lowerCamelCase_ ) for image in images] if do_center_crop: lowerCamelCase__ : Union[str, Any] =[self.center_crop(image=lowerCamelCase_ , size=lowerCamelCase_ ) for image in images] if do_rescale: lowerCamelCase__ : str =[self.rescale(image=lowerCamelCase_ , scale=lowerCamelCase_ ) for image in images] if do_normalize: lowerCamelCase__ : Optional[Any] =[self.normalize(image=lowerCamelCase_ , mean=lowerCamelCase_ , std=lowerCamelCase_ ) for image in images] lowerCamelCase__ : Optional[Any] =[to_channel_dimension_format(lowerCamelCase_ , lowerCamelCase_ ) for image in images] lowerCamelCase__ : List[str] ={'pixel_values': images} return BatchFeature(data=lowerCamelCase_ , tensor_type=lowerCamelCase_ )
126
1
import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, TrainingArguments from transformers.hf_argparser import make_choice_type_function, string_to_bool # Since Python 3.10, we can use the builtin `|` operator for Union types # See PEP 604: https://peps.python.org/pep-0604 __UpperCamelCase : Optional[int] = sys.version_info >= (3, 10) def __A ( __lowerCamelCase=None , __lowerCamelCase=None ) -> List[str]: return field(default_factory=lambda: default , metadata=__lowerCamelCase ) @dataclass class __lowerCAmelCase : UpperCamelCase__ = 42 UpperCamelCase__ = 42 UpperCamelCase__ = 42 UpperCamelCase__ = 42 @dataclass class __lowerCAmelCase : UpperCamelCase__ = 42 UpperCamelCase__ = field(default='''toto''' , metadata={'''help''': '''help message'''} ) @dataclass class __lowerCAmelCase : UpperCamelCase__ = False UpperCamelCase__ = True UpperCamelCase__ = None class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = '''titi''' UpperCamelCase__ = '''toto''' class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = '''titi''' UpperCamelCase__ = '''toto''' UpperCamelCase__ = 42 @dataclass class __lowerCAmelCase : UpperCamelCase__ = "toto" def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = BasicEnum(self.foo ) @dataclass class __lowerCAmelCase : UpperCamelCase__ = "toto" def lowerCamelCase__ ( self :str ): '''simple docstring''' a = MixedTypeEnum(self.foo ) @dataclass class __lowerCAmelCase : UpperCamelCase__ = None UpperCamelCase__ = field(default=__magic_name__ , metadata={'''help''': '''help message'''} ) UpperCamelCase__ = None UpperCamelCase__ = list_field(default=[] ) UpperCamelCase__ = list_field(default=[] ) @dataclass class __lowerCAmelCase : UpperCamelCase__ = list_field(default=[] ) UpperCamelCase__ = list_field(default=[1, 2, 3] ) UpperCamelCase__ = list_field(default=['''Hallo''', '''Bonjour''', '''Hello'''] ) UpperCamelCase__ = list_field(default=[0.1, 0.2, 0.3] ) @dataclass class __lowerCAmelCase : UpperCamelCase__ = field() UpperCamelCase__ = field() UpperCamelCase__ = field() def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a = BasicEnum(self.required_enum ) @dataclass class __lowerCAmelCase : UpperCamelCase__ = 42 UpperCamelCase__ = field() UpperCamelCase__ = None UpperCamelCase__ = field(default='''toto''' , metadata={'''help''': '''help message'''} ) UpperCamelCase__ = list_field(default=['''Hallo''', '''Bonjour''', '''Hello'''] ) if is_python_no_less_than_3_10: @dataclass class __lowerCAmelCase : UpperCamelCase__ = False UpperCamelCase__ = True UpperCamelCase__ = None @dataclass class __lowerCAmelCase : UpperCamelCase__ = None UpperCamelCase__ = field(default=__magic_name__ , metadata={'''help''': '''help message'''} ) UpperCamelCase__ = None UpperCamelCase__ = list_field(default=[] ) UpperCamelCase__ = list_field(default=[] ) class __lowerCAmelCase ( unittest.TestCase ): def lowerCamelCase__ ( self :List[str] , __magic_name__ :argparse.ArgumentParser , __magic_name__ :argparse.ArgumentParser ): '''simple docstring''' self.assertEqual(len(a._actions ) , len(b._actions ) ) for x, y in zip(a._actions , b._actions ): a = {k: v for k, v in vars(__magic_name__ ).items() if k != """container"""} a = {k: v for k, v in vars(__magic_name__ ).items() if k != """container"""} # Choices with mixed type have custom function as "type" # So we need to compare results directly for equality if xx.get("""choices""" , __magic_name__ ) and yy.get("""choices""" , __magic_name__ ): for expected_choice in yy["choices"] + xx["choices"]: self.assertEqual(xx["""type"""](__magic_name__ ) , yy["""type"""](__magic_name__ ) ) del xx["type"], yy["type"] self.assertEqual(__magic_name__ , __magic_name__ ) def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = HfArgumentParser(__magic_name__ ) a = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument("""--bar""" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument("""--baz""" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument("""--flag""" , type=__magic_name__ , default=__magic_name__ , const=__magic_name__ , nargs="""?""" ) self.argparsersEqual(__magic_name__ , __magic_name__ ) a = ["""--foo""", """1""", """--baz""", """quux""", """--bar""", """0.5"""] ((a) , ) = parser.parse_args_into_dataclasses(__magic_name__ , look_for_args_file=__magic_name__ ) self.assertFalse(example.flag ) def lowerCamelCase__ ( self :Tuple ): '''simple docstring''' a = HfArgumentParser(__magic_name__ ) a = argparse.ArgumentParser() expected.add_argument("""--foo""" , default=42 , type=__magic_name__ ) expected.add_argument("""--baz""" , default="""toto""" , type=__magic_name__ , help="""help message""" ) self.argparsersEqual(__magic_name__ , __magic_name__ ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=__magic_name__ , default=__magic_name__ , const=__magic_name__ , nargs="""?""" ) expected.add_argument("""--baz""" , type=__magic_name__ , default=__magic_name__ , const=__magic_name__ , nargs="""?""" ) # A boolean no_* argument always has to come after its "default: True" regular counter-part # and its default must be set to False expected.add_argument("""--no_baz""" , action="""store_false""" , default=__magic_name__ , dest="""baz""" ) expected.add_argument("""--opt""" , type=__magic_name__ , default=__magic_name__ ) a = [WithDefaultBoolExample] if is_python_no_less_than_3_10: dataclass_types.append(__magic_name__ ) for dataclass_type in dataclass_types: a = HfArgumentParser(__magic_name__ ) self.argparsersEqual(__magic_name__ , __magic_name__ ) a = parser.parse_args([] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) a = parser.parse_args(["""--foo""", """--no_baz"""] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) a = parser.parse_args(["""--foo""", """--baz"""] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) a = parser.parse_args(["""--foo""", """True""", """--baz""", """True""", """--opt""", """True"""] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) a = parser.parse_args(["""--foo""", """False""", """--baz""", """False""", """--opt""", """False"""] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , baz=__magic_name__ , opt=__magic_name__ ) ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = HfArgumentParser(__magic_name__ ) a = argparse.ArgumentParser() expected.add_argument( """--foo""" , default="""toto""" , choices=["""titi""", """toto""", 42] , type=make_choice_type_function(["""titi""", """toto""", 42] ) , ) self.argparsersEqual(__magic_name__ , __magic_name__ ) a = parser.parse_args([] ) self.assertEqual(args.foo , """toto""" ) a = parser.parse_args_into_dataclasses([] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.toto ) a = parser.parse_args(["""--foo""", """titi"""] ) self.assertEqual(args.foo , """titi""" ) a = parser.parse_args_into_dataclasses(["""--foo""", """titi"""] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.titi ) a = parser.parse_args(["""--foo""", """42"""] ) self.assertEqual(args.foo , 42 ) a = parser.parse_args_into_dataclasses(["""--foo""", """42"""] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo ) def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' @dataclass class __lowerCAmelCase : UpperCamelCase__ = "toto" a = HfArgumentParser(__magic_name__ ) a = argparse.ArgumentParser() expected.add_argument( """--foo""" , default="""toto""" , choices=("""titi""", """toto""", 42) , type=make_choice_type_function(["""titi""", """toto""", 42] ) , ) self.argparsersEqual(__magic_name__ , __magic_name__ ) a = parser.parse_args([] ) self.assertEqual(args.foo , """toto""" ) a = parser.parse_args(["""--foo""", """titi"""] ) self.assertEqual(args.foo , """titi""" ) a = parser.parse_args(["""--foo""", """42"""] ) self.assertEqual(args.foo , 42 ) def lowerCamelCase__ ( self :Optional[int] ): '''simple docstring''' a = HfArgumentParser(__magic_name__ ) a = argparse.ArgumentParser() expected.add_argument("""--foo_int""" , nargs="""+""" , default=[] , type=__magic_name__ ) expected.add_argument("""--bar_int""" , nargs="""+""" , default=[1, 2, 3] , type=__magic_name__ ) expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=__magic_name__ ) expected.add_argument("""--foo_float""" , nargs="""+""" , default=[0.1, 0.2, 0.3] , type=__magic_name__ ) self.argparsersEqual(__magic_name__ , __magic_name__ ) a = parser.parse_args([] ) self.assertEqual( __magic_name__ , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=["""Hallo""", """Bonjour""", """Hello"""] , foo_float=[0.1, 0.2, 0.3] ) , ) a = parser.parse_args("""--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7""".split() ) self.assertEqual(__magic_name__ , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=["""a""", """b""", """c"""] , foo_float=[0.1, 0.7] ) ) def lowerCamelCase__ ( self :Union[str, Any] ): '''simple docstring''' a = argparse.ArgumentParser() expected.add_argument("""--foo""" , default=__magic_name__ , type=__magic_name__ ) expected.add_argument("""--bar""" , default=__magic_name__ , type=__magic_name__ , help="""help message""" ) expected.add_argument("""--baz""" , default=__magic_name__ , type=__magic_name__ ) expected.add_argument("""--ces""" , nargs="""+""" , default=[] , type=__magic_name__ ) expected.add_argument("""--des""" , nargs="""+""" , default=[] , type=__magic_name__ ) a = [OptionalExample] if is_python_no_less_than_3_10: dataclass_types.append(__magic_name__ ) for dataclass_type in dataclass_types: a = HfArgumentParser(__magic_name__ ) self.argparsersEqual(__magic_name__ , __magic_name__ ) a = parser.parse_args([] ) self.assertEqual(__magic_name__ , Namespace(foo=__magic_name__ , bar=__magic_name__ , baz=__magic_name__ , ces=[] , des=[] ) ) a = parser.parse_args("""--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3""".split() ) self.assertEqual(__magic_name__ , Namespace(foo=12 , bar=3.14 , baz="""42""" , ces=["""a""", """b""", """c"""] , des=[1, 2, 3] ) ) def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a = HfArgumentParser(__magic_name__ ) a = argparse.ArgumentParser() expected.add_argument("""--required_list""" , nargs="""+""" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument("""--required_str""" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument( """--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""] ) , choices=["""titi""", """toto"""] , required=__magic_name__ , ) self.argparsersEqual(__magic_name__ , __magic_name__ ) def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' a = HfArgumentParser(__magic_name__ ) a = argparse.ArgumentParser() expected.add_argument("""--foo""" , type=__magic_name__ , required=__magic_name__ ) expected.add_argument( """--required_enum""" , type=make_choice_type_function(["""titi""", """toto"""] ) , choices=["""titi""", """toto"""] , required=__magic_name__ , ) expected.add_argument("""--opt""" , type=__magic_name__ , default=__magic_name__ ) expected.add_argument("""--baz""" , default="""toto""" , type=__magic_name__ , help="""help message""" ) expected.add_argument("""--foo_str""" , nargs="""+""" , default=["""Hallo""", """Bonjour""", """Hello"""] , type=__magic_name__ ) self.argparsersEqual(__magic_name__ , __magic_name__ ) def lowerCamelCase__ ( self :Optional[Any] ): '''simple docstring''' a = HfArgumentParser(__magic_name__ ) a = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } a = parser.parse_dict(__magic_name__ )[0] a = BasicExample(**__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = HfArgumentParser(__magic_name__ ) a = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, """extra""": 42, } self.assertRaises(__magic_name__ , parser.parse_dict , __magic_name__ , allow_extra_keys=__magic_name__ ) def lowerCamelCase__ ( self :Any ): '''simple docstring''' a = HfArgumentParser(__magic_name__ ) a = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: a = os.path.join(__magic_name__ , """temp_json""" ) os.mkdir(__magic_name__ ) with open(temp_local_path + """.json""" , """w+""" ) as f: json.dump(__magic_name__ , __magic_name__ ) a = parser.parse_yaml_file(Path(temp_local_path + """.json""" ) )[0] a = BasicExample(**__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ ) def lowerCamelCase__ ( self :str ): '''simple docstring''' a = HfArgumentParser(__magic_name__ ) a = { """foo""": 12, """bar""": 3.14, """baz""": """42""", """flag""": True, } with tempfile.TemporaryDirectory() as tmp_dir: a = os.path.join(__magic_name__ , """temp_yaml""" ) os.mkdir(__magic_name__ ) with open(temp_local_path + """.yaml""" , """w+""" ) as f: yaml.dump(__magic_name__ , __magic_name__ ) a = parser.parse_yaml_file(Path(temp_local_path + """.yaml""" ) )[0] a = BasicExample(**__magic_name__ ) self.assertEqual(__magic_name__ , __magic_name__ ) def lowerCamelCase__ ( self :Dict ): '''simple docstring''' a = HfArgumentParser(__magic_name__ ) self.assertIsNotNone(__magic_name__ )
347
import warnings from typing import Dict, List, Optional, Tuple from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __UpperCamelCase : Dict = logging.get_logger(__name__) class __lowerCAmelCase ( __magic_name__ ): UpperCamelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self :List[str] , __magic_name__ :int="</s>" , __magic_name__ :List[Any]="<unk>" , __magic_name__ :Optional[Any]="<pad>" , __magic_name__ :Optional[int]=125 , __magic_name__ :List[str]=None , **__magic_name__ :List[str] , ): '''simple docstring''' if extra_ids > 0 and additional_special_tokens is None: a = [F'<extra_id_{i}>' for i in range(__magic_name__ )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens a = len(set(filter(lambda __magic_name__ : bool("""extra_id""" in str(__magic_name__ ) ) , __magic_name__ ) ) ) if extra_tokens != extra_ids: raise ValueError( F'Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are' """ provided to ByT5Tokenizer. In this case the additional_special_tokens must include the""" """ extra_ids tokens""" ) a = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else pad_token a = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else eos_token a = AddedToken(__magic_name__ , lstrip=__magic_name__ , rstrip=__magic_name__ ) if isinstance(__magic_name__ , __magic_name__ ) else unk_token super().__init__( eos_token=__magic_name__ , unk_token=__magic_name__ , pad_token=__magic_name__ , extra_ids=__magic_name__ , additional_special_tokens=__magic_name__ , **__magic_name__ , ) a = extra_ids a = 2**8 # utf is 8 bits # define special tokens dict a = { self.pad_token: 0, self.eos_token: 1, self.unk_token: 2, } a = len(self.special_tokens_encoder ) a = len(__magic_name__ ) for i, token in enumerate(__magic_name__ ): a = self.vocab_size + i - n a = {v: k for k, v in self.special_tokens_encoder.items()} @property def lowerCamelCase__ ( self :List[Any] ): '''simple docstring''' return self._utf_vocab_size + self._num_special_tokens + self._extra_ids def lowerCamelCase__ ( self :Any , __magic_name__ :List[int] , __magic_name__ :Optional[List[int]] = None , __magic_name__ :bool = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__magic_name__ , token_ids_a=__magic_name__ , already_has_special_tokens=__magic_name__ ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(__magic_name__ )) + [1] return ([0] * len(__magic_name__ )) + [1] + ([0] * len(__magic_name__ )) + [1] def lowerCamelCase__ ( self :str , __magic_name__ :List[int] ): '''simple docstring''' if len(__magic_name__ ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( F'This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated' """ eos tokens being added.""" ) return token_ids else: return token_ids + [self.eos_token_id] def lowerCamelCase__ ( self :Union[str, Any] , __magic_name__ :List[int] , __magic_name__ :Optional[List[int]] = None ): '''simple docstring''' a = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def lowerCamelCase__ ( self :Union[str, Any] , __magic_name__ :List[int] , __magic_name__ :Optional[List[int]] = None ): '''simple docstring''' a = self._add_eos_if_not_present(__magic_name__ ) if token_ids_a is None: return token_ids_a else: a = self._add_eos_if_not_present(__magic_name__ ) return token_ids_a + token_ids_a def lowerCamelCase__ ( self :List[str] , __magic_name__ :str ): '''simple docstring''' a = [chr(__magic_name__ ) for i in text.encode("""utf-8""" )] return tokens def lowerCamelCase__ ( self :Tuple , __magic_name__ :str ): '''simple docstring''' if token in self.special_tokens_encoder: a = self.special_tokens_encoder[token] elif token in self.added_tokens_encoder: a = self.added_tokens_encoder[token] elif len(__magic_name__ ) != 1: a = self.unk_token_id else: a = ord(__magic_name__ ) + self._num_special_tokens return token_id def lowerCamelCase__ ( self :List[str] , __magic_name__ :Dict ): '''simple docstring''' if index in self.special_tokens_decoder: a = self.special_tokens_decoder[index] else: a = chr(index - self._num_special_tokens ) return token def lowerCamelCase__ ( self :Tuple , __magic_name__ :Optional[int] ): '''simple docstring''' a = b"""""" for token in tokens: if token in self.special_tokens_decoder: a = self.special_tokens_decoder[token].encode("""utf-8""" ) elif token in self.added_tokens_decoder: a = self.special_tokens_decoder[token].encode("""utf-8""" ) elif token in self.special_tokens_encoder: a = token.encode("""utf-8""" ) elif token in self.added_tokens_encoder: a = token.encode("""utf-8""" ) else: a = bytes([ord(__magic_name__ )] ) bstring += tok_string a = bstring.decode("""utf-8""" , errors="""ignore""" ) return string def lowerCamelCase__ ( self :Optional[Any] , __magic_name__ :str , __magic_name__ :Optional[str] = None ): '''simple docstring''' return ()
347
1
import unittest from transformers import GPTSwaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin _snake_case = get_tests_dir('''fixtures/test_sentencepiece_with_bytefallback.model''') @require_sentencepiece @require_tokenizers class _snake_case ( _lowercase , unittest.TestCase ): lowerCamelCase__: int = GPTSwaTokenizer lowerCamelCase__: Union[str, Any] = False lowerCamelCase__: int = True lowerCamelCase__: int = False def _lowerCamelCase ( self: Tuple ) -> List[Any]: super().setUp() # We have a SentencePiece fixture for testing __UpperCAmelCase : Union[str, Any] = GPTSwaTokenizer(__lowerCamelCase , eos_token="<unk>" , bos_token="<unk>" , pad_token="<unk>" ) tokenizer.save_pretrained(self.tmpdirname ) def _lowerCamelCase ( self: Union[str, Any] , __lowerCamelCase: Union[str, Any] ) -> str: __UpperCAmelCase : Union[str, Any] = "This is a test" __UpperCAmelCase : Tuple = "This is a test" return input_text, output_text def _lowerCamelCase ( self: List[Any] ) -> Optional[int]: __UpperCAmelCase : Any = "<s>" __UpperCAmelCase : int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__lowerCamelCase ) , __lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__lowerCamelCase ) , __lowerCamelCase ) def _lowerCamelCase ( self: Union[str, Any] ) -> Any: __UpperCAmelCase : str = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "j" ) self.assertEqual(len(__lowerCamelCase ) , 20_00 ) def _lowerCamelCase ( self: Any ) -> Any: self.assertEqual(self.get_tokenizer().vocab_size , 20_00 ) def _lowerCamelCase ( self: List[str] ) -> List[Any]: __UpperCAmelCase : Tuple = GPTSwaTokenizer(__lowerCamelCase ) __UpperCAmelCase : List[str] = tokenizer.tokenize("This is a test" ) self.assertListEqual(__lowerCamelCase , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCamelCase ) , [4_65, 2_87, 2_65, 6_31, 8_42] ) __UpperCAmelCase : List[Any] = tokenizer.tokenize("I was born in 92000, and this is falsé." ) # fmt: off self.assertListEqual( __lowerCamelCase , ["▁I", "▁was", "▁bor", "n", "▁in", "▁", "<0x39>", "2", "0", "0", "0", ",", "▁and", "▁this", "▁is", "▁f", "al", "s", "<0xC3>", "<0xA9>", "."] , ) # fmt: on __UpperCAmelCase : Any = tokenizer.convert_tokens_to_ids(__lowerCamelCase ) self.assertListEqual( __lowerCamelCase , [2_62, 2_72, 15_25, 2_86, 2_71, 2_68, 60, 9_16, 6_33, 6_33, 6_33, 2_59, 2_66, 3_01, 2_87, 3_84, 3_67, 2_63, 1_98, 1_72, 2_60] , ) __UpperCAmelCase : List[Any] = tokenizer.convert_ids_to_tokens(__lowerCamelCase ) # fmt: off self.assertListEqual( __lowerCamelCase , ["▁I", "▁was", "▁bor", "n", "▁in", "▁", "<0x39>", "2", "0", "0", "0", ",", "▁and", "▁this", "▁is", "▁f", "al", "s", "<0xC3>", "<0xA9>", "."] ) # fmt: on def _lowerCamelCase ( self: List[Any] ) -> Tuple: __UpperCAmelCase : List[str] = GPTSwaTokenizer(__lowerCamelCase ) __UpperCAmelCase : str = ["This is a test", "I was born in 92000, and this is falsé."] __UpperCAmelCase : str = [ [4_65, 2_87, 2_65, 6_31, 8_42], [2_62, 2_72, 15_25, 2_86, 2_71, 2_68, 60, 9_16, 6_33, 6_33, 6_33, 2_59, 2_66, 3_01, 2_87, 3_84, 3_67, 2_63, 1_98, 1_72, 2_60], ] # Test that encode_fast returns the same as tokenize + convert_tokens_to_ids for text, expected_ids in zip(__lowerCamelCase , __lowerCamelCase ): self.assertListEqual(tokenizer.encode_fast(__lowerCamelCase ) , __lowerCamelCase ) # Test that decode_fast returns the input text for text, token_ids in zip(__lowerCamelCase , __lowerCamelCase ): self.assertEqual(tokenizer.decode_fast(__lowerCamelCase ) , __lowerCamelCase ) @slow def _lowerCamelCase ( self: Optional[Any] ) -> str: __UpperCAmelCase : str = [ "<|python|>def fibonacci(n)\n if n < 0:\n print('Incorrect input')", "Hey there, how are you doing this fine day?", "This is a text with a trailing spaces followed by a dot .", "Häj sväjs lillebrör! =)", "Det är inget fel på Mr. Cool", ] # fmt: off __UpperCAmelCase : Union[str, Any] = {"input_ids": [[6_34_23, 5, 68_11, 1_49_54, 2_82, 8_16, 38_21, 6_34_66, 6_34_25, 6_34_62, 18, 6_39_78, 6_78, 3_01, 13_20, 6_34_23, 6_34_55, 6_34_58, 18, 6_39_82, 42_46, 39_40, 19_01, 4_77_89, 55_47, 1_89_94], [1_96_30, 11_00, 6_34_46, 13_42, 6_33, 5_44, 44_88, 5_93, 51_02, 24_16, 6_34_95, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [16_52, 4_28, 2_68, 19_36, 5_15, 2_68, 5_85_93, 2_24_13, 91_06, 5_46, 2_68, 3_32_13, 6_39_79, 6_98, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [5_51_30, 6_34_50, 9_24, 6_34_49, 22_49, 40_62, 15_58, 3_18, 6_35_04, 2_14_98, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [5_09, 3_77, 28_27, 25_59, 3_32, 65_75, 6_34_43, 2_68_01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "token_type_ids": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # fmt: on self.tokenizer_integration_test_util( expected_encoding=__lowerCamelCase , model_name="AI-Sweden/gpt-sw3-126m" , sequences=__lowerCamelCase , )
157
from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def _UpperCamelCase ( snake_case__, snake_case__, snake_case__ = False ) -> list[float]: if radian_mode: return [magnitude * cos(snake_case__ ), magnitude * sin(snake_case__ )] return [magnitude * cos(radians(snake_case__ ) ), magnitude * sin(radians(snake_case__ ) )] def _UpperCamelCase ( snake_case__, snake_case__, snake_case__ = 10**-1 ) -> bool: __UpperCAmelCase : NDArray[floataa] = cross(snake_case__, snake_case__ ) __UpperCAmelCase : float = sum(snake_case__ ) return abs(snake_case__ ) < eps if __name__ == "__main__": # Test to check if it works _snake_case = array( [ polar_force(7_1_8.4, 180 - 30), polar_force(8_7_9.5_4, 45), polar_force(100, -90), ] ) _snake_case = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg _snake_case = array( [ polar_force(30 * 9.8_1, 15), polar_force(215, 180 - 45), polar_force(264, 90 - 30), ] ) _snake_case = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg _snake_case = array([[0, -2000], [0, -1200], [0, 15600], [0, -12400]]) _snake_case = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
157
1
from collections import OrderedDict from typing import Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...feature_extraction_utils import FeatureExtractionMixin from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType, logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { '''deepmind/language-perceiver''': '''https://huggingface.co/deepmind/language-perceiver/resolve/main/config.json''', # See all Perceiver models at https://huggingface.co/models?filter=perceiver } class __UpperCAmelCase (_UpperCAmelCase ): __snake_case : int = "perceiver" def __init__( self: List[str] , UpperCAmelCase_: Dict=256 , UpperCAmelCase_: Optional[Any]=1_280 , UpperCAmelCase_: List[str]=768 , UpperCAmelCase_: Any=1 , UpperCAmelCase_: Union[str, Any]=26 , UpperCAmelCase_: int=8 , UpperCAmelCase_: Optional[int]=8 , UpperCAmelCase_: Union[str, Any]=None , UpperCAmelCase_: List[Any]=None , UpperCAmelCase_: Tuple="kv" , UpperCAmelCase_: Union[str, Any]=1 , UpperCAmelCase_: List[str]=1 , UpperCAmelCase_: Any="gelu" , UpperCAmelCase_: Optional[int]=0.1 , UpperCAmelCase_: Tuple=0.02 , UpperCAmelCase_: int=1E-12 , UpperCAmelCase_: str=True , UpperCAmelCase_: Optional[int]=262 , UpperCAmelCase_: str=2_048 , UpperCAmelCase_: Tuple=56 , UpperCAmelCase_: Dict=[368, 496] , UpperCAmelCase_: Optional[Any]=16 , UpperCAmelCase_: List[str]=1_920 , UpperCAmelCase_: Tuple=16 , UpperCAmelCase_: Union[str, Any]=[1, 16, 224, 224] , **UpperCAmelCase_: Tuple , ): '''simple docstring''' super().__init__(**UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = num_latents _SCREAMING_SNAKE_CASE = d_latents _SCREAMING_SNAKE_CASE = d_model _SCREAMING_SNAKE_CASE = num_blocks _SCREAMING_SNAKE_CASE = num_self_attends_per_block _SCREAMING_SNAKE_CASE = num_self_attention_heads _SCREAMING_SNAKE_CASE = num_cross_attention_heads _SCREAMING_SNAKE_CASE = qk_channels _SCREAMING_SNAKE_CASE = v_channels _SCREAMING_SNAKE_CASE = cross_attention_shape_for_attention _SCREAMING_SNAKE_CASE = self_attention_widening_factor _SCREAMING_SNAKE_CASE = cross_attention_widening_factor _SCREAMING_SNAKE_CASE = hidden_act _SCREAMING_SNAKE_CASE = attention_probs_dropout_prob _SCREAMING_SNAKE_CASE = initializer_range _SCREAMING_SNAKE_CASE = layer_norm_eps _SCREAMING_SNAKE_CASE = use_query_residual # masked language modeling attributes _SCREAMING_SNAKE_CASE = vocab_size _SCREAMING_SNAKE_CASE = max_position_embeddings # image classification attributes _SCREAMING_SNAKE_CASE = image_size # flow attributes _SCREAMING_SNAKE_CASE = train_size # multimodal autoencoding attributes _SCREAMING_SNAKE_CASE = num_frames _SCREAMING_SNAKE_CASE = audio_samples_per_frame _SCREAMING_SNAKE_CASE = samples_per_patch _SCREAMING_SNAKE_CASE = output_shape class __UpperCAmelCase (_UpperCAmelCase ): @property def UpperCamelCase ( self: str ): '''simple docstring''' if self.task == "multiple-choice": _SCREAMING_SNAKE_CASE = {0: """batch""", 1: """choice""", 2: """sequence"""} else: _SCREAMING_SNAKE_CASE = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""inputs""", dynamic_axis), ("""attention_mask""", dynamic_axis), ] ) @property def UpperCamelCase ( self: Optional[int] ): '''simple docstring''' return 1E-4 def UpperCamelCase ( self: Union[str, Any] , UpperCAmelCase_: Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , UpperCAmelCase_: int = -1 , UpperCAmelCase_: int = -1 , UpperCAmelCase_: int = -1 , UpperCAmelCase_: bool = False , UpperCAmelCase_: Optional[TensorType] = None , UpperCAmelCase_: int = 3 , UpperCAmelCase_: int = 40 , UpperCAmelCase_: int = 40 , ): '''simple docstring''' if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ): # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX _SCREAMING_SNAKE_CASE = compute_effective_axis_dimension( UpperCAmelCase_ , 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 _SCREAMING_SNAKE_CASE = preprocessor.num_special_tokens_to_add(UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = compute_effective_axis_dimension( UpperCAmelCase_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=UpperCAmelCase_ ) # Generate dummy inputs according to compute batch and sequence _SCREAMING_SNAKE_CASE = [""" """.join(["""a"""] ) * seq_length] * batch_size _SCREAMING_SNAKE_CASE = dict(preprocessor(UpperCAmelCase_ , return_tensors=UpperCAmelCase_ ) ) _SCREAMING_SNAKE_CASE = inputs.pop("""input_ids""" ) return inputs elif isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) and preprocessor.model_input_names[0] == "pixel_values": # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX _SCREAMING_SNAKE_CASE = compute_effective_axis_dimension(UpperCAmelCase_ , fixed_dimension=OnnxConfig.default_fixed_batch ) _SCREAMING_SNAKE_CASE = self._generate_dummy_images(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = dict(preprocessor(images=UpperCAmelCase_ , return_tensors=UpperCAmelCase_ ) ) _SCREAMING_SNAKE_CASE = inputs.pop("""pixel_values""" ) return inputs else: raise ValueError( """Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor.""" )
125
import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class __UpperCAmelCase (_UpperCAmelCase ,unittest.TestCase ): __snake_case : int = TransfoXLTokenizer __snake_case : Tuple = False __snake_case : List[Any] = False def UpperCamelCase ( self: int ): '''simple docstring''' super().setUp() _SCREAMING_SNAKE_CASE = [ """<unk>""", """[CLS]""", """[SEP]""", """want""", """unwanted""", """wa""", """un""", """running""", """,""", """low""", """l""", ] _SCREAMING_SNAKE_CASE = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["""vocab_file"""] ) with open(self.vocab_file , """w""" , encoding="""utf-8""" ) as vocab_writer: vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens] ) ) def UpperCamelCase ( self: Any , **UpperCAmelCase_: Optional[Any] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **UpperCAmelCase_ ) def UpperCamelCase ( self: Optional[int] , UpperCAmelCase_: List[str] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = """<unk> UNwanted , running""" _SCREAMING_SNAKE_CASE = """<unk> unwanted, running""" return input_text, output_text def UpperCamelCase ( self: Union[str, Any] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = tokenizer.tokenize("""<unk> UNwanted , running""" ) self.assertListEqual(UpperCAmelCase_ , ["""<unk>""", """unwanted""", """,""", """running"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase_ ) , [0, 4, 8, 7] ) def UpperCamelCase ( self: int ): '''simple docstring''' _SCREAMING_SNAKE_CASE = TransfoXLTokenizer(lower_case=UpperCAmelCase_ ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo ! how \n Are yoU ? """ ) , ["""hello""", """!""", """how""", """are""", """you""", """?"""] ) def UpperCamelCase ( self: Optional[Any] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = TransfoXLTokenizer(lower_case=UpperCAmelCase_ ) self.assertListEqual( tokenizer.tokenize(""" \tHeLLo ! how \n Are yoU ? """ ) , ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""] ) def UpperCamelCase ( self: List[str] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = TransfoXLTokenizer(lower_case=UpperCAmelCase_ ) _SCREAMING_SNAKE_CASE = """Hello (bracket) and side-scrolled [and] Henry's $5,000 with 3.34 m. What's up!?""" _SCREAMING_SNAKE_CASE = [ """Hello""", """(""", """bracket""", """)""", """and""", """side""", """@-@""", """scrolled""", """[""", """and""", """]""", """Henry""", """'s""", """$""", """5""", """@,@""", """000""", """with""", """3""", """@.@""", """34""", """m""", """.""", """What""", """'s""", """up""", """!""", """?""", ] self.assertListEqual(tokenizer.tokenize(UpperCAmelCase_ ) , UpperCAmelCase_ ) self.assertEqual(tokenizer.convert_tokens_to_string(UpperCAmelCase_ ) , UpperCAmelCase_ ) def UpperCamelCase ( self: List[str] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.get_tokenizer() _SCREAMING_SNAKE_CASE = len(UpperCAmelCase_ ) tokenizer.add_tokens(["""new1""", """new2"""] ) tokenizer.move_added_token("""new1""" , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(UpperCAmelCase_ ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode("""new1""" ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , """new1""" )
125
1
"""simple docstring""" from math import isqrt, loga def lowerCamelCase__ ( __snake_case ) -> list[int]: """simple docstring""" _UpperCamelCase = [True] * max_number for i in range(2, isqrt(max_number - 1 ) + 1 ): if is_prime[i]: for j in range(i**2, __snake_case, __snake_case ): _UpperCamelCase = False return [i for i in range(2, __snake_case ) if is_prime[i]] def lowerCamelCase__ ( __snake_case = 80_08_00, __snake_case = 80_08_00 ) -> int: """simple docstring""" _UpperCamelCase = degree * loga(__snake_case ) _UpperCamelCase = int(__snake_case ) _UpperCamelCase = calculate_prime_numbers(__snake_case ) _UpperCamelCase = 0 _UpperCamelCase = 0 _UpperCamelCase = len(__snake_case ) - 1 while left < right: while ( prime_numbers[right] * loga(prime_numbers[left] ) + prime_numbers[left] * loga(prime_numbers[right] ) > upper_bound ): right -= 1 hybrid_integers_count += right - left left += 1 return hybrid_integers_count if __name__ == "__main__": print(F"""{solution() = }""")
194
"""simple docstring""" from typing import List, Union import numpy as np from ..tokenization_utils import TruncationStrategy from ..utils import add_end_docstrings, logging from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline _a = logging.get_logger(__name__) class _UpperCAmelCase( lowerCamelCase ): def UpperCAmelCase ( self , __a) -> Tuple: '''simple docstring''' if isinstance(__a , __a): _UpperCamelCase = [label.strip() for label in labels.split(''',''') if label.strip()] return labels def __call__( self , __a , __a , __a) -> Optional[int]: '''simple docstring''' if len(__a) == 0 or len(__a) == 0: raise ValueError('''You must include at least one label and at least one sequence.''') if hypothesis_template.format(labels[0]) == hypothesis_template: raise ValueError( ( '''The provided hypothesis_template "{}" was not able to be formatted with the target labels. ''' '''Make sure the passed template includes formatting syntax such as {{}} where the label should go.''' ).format(__a)) if isinstance(__a , __a): _UpperCamelCase = [sequences] _UpperCamelCase = [] for sequence in sequences: sequence_pairs.extend([[sequence, hypothesis_template.format(__a)] for label in labels]) return sequence_pairs, sequences @add_end_docstrings(lowerCamelCase ) class _UpperCAmelCase( lowerCamelCase ): def __init__( self , __a=ZeroShotClassificationArgumentHandler() , *__a , **__a) -> List[str]: '''simple docstring''' _UpperCamelCase = args_parser super().__init__(*__a , **__a) if self.entailment_id == -1: logger.warning( '''Failed to determine \'entailment\' label id from the label2id mapping in the model config. Setting to ''' '''-1. Define a descriptive label2id mapping in the model config to ensure correct outputs.''') @property def UpperCAmelCase ( self) -> List[str]: '''simple docstring''' for label, ind in self.model.config.labelaid.items(): if label.lower().startswith('''entail'''): return ind return -1 def UpperCAmelCase ( self , __a , __a=True , __a=True , __a=TruncationStrategy.ONLY_FIRST , **__a) -> List[Any]: '''simple docstring''' _UpperCamelCase = self.framework if self.tokenizer.pad_token is None: # Override for tokenizers not supporting padding logger.error( '''Tokenizer was not supporting padding necessary for zero-shot, attempting to use ''' ''' `pad_token=eos_token`''') _UpperCamelCase = self.tokenizer.eos_token try: _UpperCamelCase = self.tokenizer( __a , add_special_tokens=__a , return_tensors=__a , padding=__a , truncation=__a , ) except Exception as e: if "too short" in str(__a): # tokenizers might yell that we want to truncate # to a value that is not even reached by the input. # In that case we don't want to truncate. # It seems there's not a really better way to catch that # exception. _UpperCamelCase = self.tokenizer( __a , add_special_tokens=__a , return_tensors=__a , padding=__a , truncation=TruncationStrategy.DO_NOT_TRUNCATE , ) else: raise e return inputs def UpperCAmelCase ( self , **__a) -> Any: '''simple docstring''' if kwargs.get('''multi_class''' , __a) is not None: _UpperCamelCase = kwargs['''multi_class'''] logger.warning( '''The `multi_class` argument has been deprecated and renamed to `multi_label`. ''' '''`multi_class` will be removed in a future version of Transformers.''') _UpperCamelCase = {} if "candidate_labels" in kwargs: _UpperCamelCase = self._args_parser._parse_labels(kwargs['''candidate_labels''']) if "hypothesis_template" in kwargs: _UpperCamelCase = kwargs['''hypothesis_template'''] _UpperCamelCase = {} if "multi_label" in kwargs: _UpperCamelCase = kwargs['''multi_label'''] return preprocess_params, {}, postprocess_params def __call__( self , __a , *__a , **__a , ) -> int: '''simple docstring''' if len(__a) == 0: pass elif len(__a) == 1 and "candidate_labels" not in kwargs: _UpperCamelCase = args[0] else: raise ValueError(F'''Unable to understand extra arguments {args}''') return super().__call__(__a , **__a) def UpperCAmelCase ( self , __a , __a=None , __a="This example is {}.") -> Dict: '''simple docstring''' _UpperCamelCase , _UpperCamelCase = self._args_parser(__a , __a , __a) for i, (candidate_label, sequence_pair) in enumerate(zip(__a , __a)): _UpperCamelCase = self._parse_and_tokenize([sequence_pair]) yield { "candidate_label": candidate_label, "sequence": sequences[0], "is_last": i == len(__a) - 1, **model_input, } def UpperCAmelCase ( self , __a) -> List[Any]: '''simple docstring''' _UpperCamelCase = inputs['''candidate_label'''] _UpperCamelCase = inputs['''sequence'''] _UpperCamelCase = {k: inputs[k] for k in self.tokenizer.model_input_names} _UpperCamelCase = self.model(**__a) _UpperCamelCase = { '''candidate_label''': candidate_label, '''sequence''': sequence, '''is_last''': inputs['''is_last'''], **outputs, } return model_outputs def UpperCAmelCase ( self , __a , __a=False) -> Dict: '''simple docstring''' _UpperCamelCase = [outputs['''candidate_label'''] for outputs in model_outputs] _UpperCamelCase = [outputs['''sequence'''] for outputs in model_outputs] _UpperCamelCase = np.concatenate([output['''logits'''].numpy() for output in model_outputs]) _UpperCamelCase = logits.shape[0] _UpperCamelCase = len(__a) _UpperCamelCase = N // n _UpperCamelCase = logits.reshape((num_sequences, n, -1)) if multi_label or len(__a) == 1: # softmax over the entailment vs. contradiction dim for each label independently _UpperCamelCase = self.entailment_id _UpperCamelCase = -1 if entailment_id == 0 else 0 _UpperCamelCase = reshaped_outputs[..., [contradiction_id, entailment_id]] _UpperCamelCase = np.exp(__a) / np.exp(__a).sum(-1 , keepdims=__a) _UpperCamelCase = scores[..., 1] else: # softmax the "entailment" logits over all candidate labels _UpperCamelCase = reshaped_outputs[..., self.entailment_id] _UpperCamelCase = np.exp(__a) / np.exp(__a).sum(-1 , keepdims=__a) _UpperCamelCase = list(reversed(scores[0].argsort())) return { "sequence": sequences[0], "labels": [candidate_labels[i] for i in top_inds], "scores": scores[0, top_inds].tolist(), }
194
1
'''simple docstring''' import unittest from transformers import 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 from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST, OpenAIGPTConfig, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification, OpenAIGPTLMHeadModel, OpenAIGPTModel, ) class lowerCAmelCase__ : def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=13 , __SCREAMING_SNAKE_CASE=7 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=99 , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=5 , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=37 , __SCREAMING_SNAKE_CASE="gelu" , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=0.1 , __SCREAMING_SNAKE_CASE=5_12 , __SCREAMING_SNAKE_CASE=16 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=4 , __SCREAMING_SNAKE_CASE=None , ): """simple docstring""" lowercase_ : Union[str, Any] = parent lowercase_ : Optional[Any] = batch_size lowercase_ : Union[str, Any] = seq_length lowercase_ : Union[str, Any] = is_training lowercase_ : Tuple = use_token_type_ids lowercase_ : Any = use_labels lowercase_ : Tuple = vocab_size lowercase_ : Optional[Any] = hidden_size lowercase_ : str = num_hidden_layers lowercase_ : Dict = num_attention_heads lowercase_ : Any = intermediate_size lowercase_ : List[str] = hidden_act lowercase_ : Optional[int] = hidden_dropout_prob lowercase_ : Optional[int] = attention_probs_dropout_prob lowercase_ : List[str] = max_position_embeddings lowercase_ : int = type_vocab_size lowercase_ : Optional[Any] = type_sequence_label_size lowercase_ : Union[str, Any] = initializer_range lowercase_ : Any = num_labels lowercase_ : Optional[Any] = num_choices lowercase_ : Optional[int] = scope lowercase_ : List[Any] = self.vocab_size - 1 def _snake_case ( self ): """simple docstring""" lowercase_ : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowercase_ : Dict = None if self.use_token_type_ids: lowercase_ : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowercase_ : List[str] = None lowercase_ : str = None lowercase_ : List[str] = None if self.use_labels: lowercase_ : List[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase_ : Any = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowercase_ : str = ids_tensor([self.batch_size] , self.num_choices ) lowercase_ : Optional[Any] = OpenAIGPTConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) lowercase_ : str = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, head_mask, token_type_ids, sequence_labels, token_labels, choice_labels, ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : int = OpenAIGPTModel(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() lowercase_ : str = model(__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , head_mask=__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = model(__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = OpenAIGPTLMHeadModel(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() lowercase_ : List[str] = model(__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : int = OpenAIGPTDoubleHeadsModel(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() lowercase_ : Optional[int] = model(__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Any = self.num_labels lowercase_ : List[str] = OpenAIGPTForSequenceClassification(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() lowercase_ : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase_ : List[Any] = model(__SCREAMING_SNAKE_CASE , token_type_ids=__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[Any] = self.prepare_config_and_inputs() ( ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ( lowercase_ ) , ) : Optional[int] = config_and_inputs lowercase_ : Union[str, Any] = { '''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''head_mask''': head_mask, } return config, inputs_dict @require_torch class lowerCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): lowerCAmelCase_ = ( (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification) if is_torch_available() else () ) lowerCAmelCase_ = ( (OpenAIGPTLMHeadModel,) if is_torch_available() else () ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly lowerCAmelCase_ = ( { '''feature-extraction''': OpenAIGPTModel, '''text-classification''': OpenAIGPTForSequenceClassification, '''text-generation''': OpenAIGPTLMHeadModel, '''zero-shot''': OpenAIGPTForSequenceClassification, } if is_torch_available() else {} ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a # tiny config could not be created. return True return False def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=False ): """simple docstring""" lowercase_ : int = super()._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , return_labels=__SCREAMING_SNAKE_CASE ) if return_labels: if model_class.__name__ == "OpenAIGPTDoubleHeadsModel": lowercase_ : int = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length) , dtype=torch.long , device=__SCREAMING_SNAKE_CASE , ) lowercase_ : Optional[Any] = inputs_dict['''labels'''] lowercase_ : Tuple = inputs_dict['''labels'''] lowercase_ : Union[str, Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.num_choices) , dtype=torch.long , device=__SCREAMING_SNAKE_CASE , ) lowercase_ : Tuple = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__SCREAMING_SNAKE_CASE ) return inputs_dict def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = OpenAIGPTModelTester(self ) lowercase_ : Dict = ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , n_embd=37 ) def _snake_case ( self ): """simple docstring""" self.config_tester.run_common_tests() def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_model(*__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_double_lm_head_model(*__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*__SCREAMING_SNAKE_CASE ) @slow def _snake_case ( self ): """simple docstring""" for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase_ : str = OpenAIGPTModel.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) @require_torch class lowerCAmelCase__ ( unittest.TestCase ): @slow def _snake_case ( self ): """simple docstring""" lowercase_ : Any = OpenAIGPTLMHeadModel.from_pretrained('''openai-gpt''' ) model.to(__SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = torch.tensor([[4_81, 47_35, 5_44]] , dtype=torch.long , device=__SCREAMING_SNAKE_CASE ) # the president is lowercase_ : List[Any] = [ 4_81, 47_35, 5_44, 2_46, 9_63, 8_70, 7_62, 2_39, 2_44, 4_04_77, 2_44, 2_49, 7_19, 8_81, 4_87, 5_44, 2_40, 2_44, 6_03, 4_81, ] # the president is a very good man. " \n " i\'m sure he is, " said the lowercase_ : Tuple = model.generate(__SCREAMING_SNAKE_CASE , do_sample=__SCREAMING_SNAKE_CASE ) self.assertListEqual(output_ids[0].tolist() , __SCREAMING_SNAKE_CASE )
264
'''simple docstring''' import logging import os from .state import PartialState class lowerCAmelCase__ ( logging.LoggerAdapter ): @staticmethod def _snake_case ( __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Optional[Any] = PartialState() return not main_process_only or (main_process_only and state.is_main_process) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" if PartialState._shared_state == {}: raise RuntimeError( '''You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.''' ) lowercase_ : Tuple = kwargs.pop('''main_process_only''' , __SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = kwargs.pop('''in_order''' , __SCREAMING_SNAKE_CASE ) if self.isEnabledFor(__SCREAMING_SNAKE_CASE ): if self._should_log(__SCREAMING_SNAKE_CASE ): lowercase_ , lowercase_ : Optional[Any] = self.process(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.logger.log(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) elif in_order: lowercase_ : Optional[Any] = PartialState() for i in range(state.num_processes ): if i == state.process_index: lowercase_ , lowercase_ : Optional[int] = self.process(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) self.logger.log(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) state.wait_for_everyone() def snake_case_ ( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str = None ): """simple docstring""" if log_level is None: lowercase_ : Any = os.environ.get('''ACCELERATE_LOG_LEVEL''' , __SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = logging.getLogger(__SCREAMING_SNAKE_CASE ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(__SCREAMING_SNAKE_CASE , {} )
264
1
'''simple docstring''' # Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING import numpy as np import pyarrow as pa from .. import config from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import torch class a ( TensorFormatter[Mapping, "torch.Tensor", Mapping] ): def __init__( self : Dict , lowercase_ : List[str]=None , **lowercase_ : Union[str, Any] ): super().__init__(features=lowercase_ ) snake_case_ = torch_tensor_kwargs import torch # noqa import torch at initialization def A_ ( self : str , lowercase_ : str ): import torch if isinstance(lowercase_ , lowercase_ ) and column: if all( isinstance(lowercase_ , torch.Tensor ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return torch.stack(lowercase_ ) return column def A_ ( self : Any , lowercase_ : Tuple ): import torch if isinstance(lowercase_ , (str, bytes, type(lowercase_ )) ): return value elif isinstance(lowercase_ , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() snake_case_ = {} if isinstance(lowercase_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): snake_case_ = {'''dtype''': torch.intaa} elif isinstance(lowercase_ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): snake_case_ = {'''dtype''': torch.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(lowercase_ , PIL.Image.Image ): snake_case_ = np.asarray(lowercase_ ) return torch.tensor(lowercase_ , **{**default_dtype, **self.torch_tensor_kwargs} ) def A_ ( self : List[Any] , lowercase_ : Optional[int] ): import torch # support for torch, tf, jax etc. if hasattr(lowercase_ , '''__array__''' ) and not isinstance(lowercase_ , torch.Tensor ): snake_case_ = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(lowercase_ , np.ndarray ): if data_struct.dtype == object: # torch tensors cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(lowercase_ ) for substruct in data_struct] ) elif isinstance(lowercase_ , (list, tuple) ): return self._consolidate([self.recursive_tensorize(lowercase_ ) for substruct in data_struct] ) return self._tensorize(lowercase_ ) def A_ ( self : Optional[Any] , lowercase_ : dict ): return map_nested(self._recursive_tensorize , lowercase_ , map_list=lowercase_ ) def A_ ( self : Dict , lowercase_ : pa.Table ): snake_case_ = self.numpy_arrow_extractor().extract_row(lowercase_ ) snake_case_ = self.python_features_decoder.decode_row(lowercase_ ) return self.recursive_tensorize(lowercase_ ) def A_ ( self : List[Any] , lowercase_ : pa.Table ): snake_case_ = self.numpy_arrow_extractor().extract_column(lowercase_ ) snake_case_ = self.python_features_decoder.decode_column(lowercase_ , pa_table.column_names[0] ) snake_case_ = self.recursive_tensorize(lowercase_ ) snake_case_ = self._consolidate(lowercase_ ) return column def A_ ( self : str , lowercase_ : pa.Table ): snake_case_ = self.numpy_arrow_extractor().extract_batch(lowercase_ ) snake_case_ = self.python_features_decoder.decode_batch(lowercase_ ) snake_case_ = self.recursive_tensorize(lowercase_ ) for column_name in batch: snake_case_ = self._consolidate(batch[column_name] ) return batch
56
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCAmelCase__ = { '''configuration_xlm''': ['''XLM_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLMConfig''', '''XLMOnnxConfig'''], '''tokenization_xlm''': ['''XLMTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase__ = [ '''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: UpperCAmelCase__ = [ '''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 UpperCAmelCase__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
5
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available snake_case__ = { """configuration_tapas""": ["""TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TapasConfig"""], """tokenization_tapas""": ["""TapasTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case__ = [ """TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST""", """TapasForMaskedLM""", """TapasForQuestionAnswering""", """TapasForSequenceClassification""", """TapasModel""", """TapasPreTrainedModel""", """load_tf_weights_in_tapas""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case__ = [ """TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFTapasForMaskedLM""", """TFTapasForQuestionAnswering""", """TFTapasForSequenceClassification""", """TFTapasModel""", """TFTapasPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_tapas import TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP, TapasConfig from .tokenization_tapas import TapasTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tapas import ( TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TapasForMaskedLM, TapasForQuestionAnswering, TapasForSequenceClassification, TapasModel, TapasPreTrainedModel, load_tf_weights_in_tapas, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_tapas import ( TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST, TFTapasForMaskedLM, TFTapasForQuestionAnswering, TFTapasForSequenceClassification, TFTapasModel, TFTapasPreTrainedModel, ) else: import sys snake_case__ = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
352
'''simple docstring''' import io import itertools import json from dataclasses import dataclass from typing import Optional import pyarrow as pa import pyarrow.json as paj import datasets from datasets.table import table_cast from datasets.utils.file_utils import readline snake_case__ = datasets.utils.logging.get_logger(__name__) @dataclass class UpperCamelCase_ (datasets.BuilderConfig ): """simple docstring""" _lowerCAmelCase = None _lowerCAmelCase = "utf-8" _lowerCAmelCase = None _lowerCAmelCase = None _lowerCAmelCase = True # deprecated _lowerCAmelCase = None # deprecated _lowerCAmelCase = 1_0 << 2_0 # 10MB _lowerCAmelCase = None class UpperCamelCase_ (datasets.ArrowBasedBuilder ): """simple docstring""" _lowerCAmelCase = JsonConfig def _a ( self : int ): """simple docstring""" if self.config.block_size is not None: logger.warning('''The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead''' ) A_ : List[Any] = self.config.block_size if self.config.use_threads is not True: logger.warning( '''The JSON loader parameter `use_threads` is deprecated and doesn\'t have any effect anymore.''' ) if self.config.newlines_in_values is not None: raise ValueError('''The JSON loader parameter `newlines_in_values` is no longer supported''' ) return datasets.DatasetInfo(features=self.config.features ) def _a ( self : Any , _lowerCamelCase : List[str] ): """simple docstring""" if not self.config.data_files: raise ValueError(f'At least one data file must be specified, but got data_files={self.config.data_files}' ) A_ : int = dl_manager.download_and_extract(self.config.data_files ) if isinstance(_lowerCamelCase , (str, list, tuple) ): A_ : Union[str, Any] = data_files if isinstance(_lowerCamelCase , _lowerCamelCase ): A_ : List[str] = [files] A_ : List[Any] = [dl_manager.iter_files(_lowerCamelCase ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={'''files''': files} )] A_ : Tuple = [] for split_name, files in data_files.items(): if isinstance(_lowerCamelCase , _lowerCamelCase ): A_ : int = [files] A_ : Union[str, Any] = [dl_manager.iter_files(_lowerCamelCase ) for file in files] splits.append(datasets.SplitGenerator(name=_lowerCamelCase , gen_kwargs={'''files''': files} ) ) return splits def _a ( self : int , _lowerCamelCase : pa.Table ): """simple docstring""" if self.config.features is not None: # adding missing columns for column_name in set(self.config.features ) - set(pa_table.column_names ): A_ : Optional[int] = self.config.features.arrow_schema.field(_lowerCamelCase ).type A_ : Optional[int] = pa_table.append_column(_lowerCamelCase , pa.array([None] * len(_lowerCamelCase ) , type=_lowerCamelCase ) ) # more expensive cast to support nested structures with keys in a different order # allows str <-> int/float or str to Audio for example A_ : str = table_cast(_lowerCamelCase , self.config.features.arrow_schema ) return pa_table def _a ( self : List[str] , _lowerCamelCase : int ): """simple docstring""" for file_idx, file in enumerate(itertools.chain.from_iterable(_lowerCamelCase ) ): # If the file is one json object and if we need to look at the list of items in one specific field if self.config.field is not None: with open(_lowerCamelCase , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: A_ : int = json.load(_lowerCamelCase ) # We keep only the field we are interested in A_ : List[str] = dataset[self.config.field] # We accept two format: a list of dicts or a dict of lists if isinstance(_lowerCamelCase , (list, tuple) ): A_ : int = set().union(*[row.keys() for row in dataset] ) A_ : List[str] = {col: [row.get(_lowerCamelCase ) for row in dataset] for col in keys} else: A_ : Tuple = dataset A_ : Dict = pa.Table.from_pydict(_lowerCamelCase ) yield file_idx, self._cast_table(_lowerCamelCase ) # If the file has one json object per line else: with open(_lowerCamelCase , '''rb''' ) as f: A_ : int = 0 # Use block_size equal to the chunk size divided by 32 to leverage multithreading # Set a default minimum value of 16kB if the chunk size is really small A_ : int = max(self.config.chunksize // 32 , 16 << 10 ) A_ : int = ( self.config.encoding_errors if self.config.encoding_errors is not None else '''strict''' ) while True: A_ : Any = f.read(self.config.chunksize ) if not batch: break # Finish current line try: batch += f.readline() except (AttributeError, io.UnsupportedOperation): batch += readline(_lowerCamelCase ) # PyArrow only accepts utf-8 encoded bytes if self.config.encoding != "utf-8": A_ : Optional[Any] = batch.decode(self.config.encoding , errors=_lowerCamelCase ).encode('''utf-8''' ) try: while True: try: A_ : List[Any] = paj.read_json( io.BytesIO(_lowerCamelCase ) , read_options=paj.ReadOptions(block_size=_lowerCamelCase ) ) break except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e: if ( isinstance(_lowerCamelCase , pa.ArrowInvalid ) and "straddling" not in str(_lowerCamelCase ) or block_size > len(_lowerCamelCase ) ): raise else: # Increase the block size in case it was too small. # The block size will be reset for the next file. logger.debug( f'Batch of {len(_lowerCamelCase )} bytes couldn\'t be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}.' ) block_size *= 2 except pa.ArrowInvalid as e: try: with open( _lowerCamelCase , encoding=self.config.encoding , errors=self.config.encoding_errors ) as f: A_ : Optional[Any] = json.load(_lowerCamelCase ) except json.JSONDecodeError: logger.error(f'Failed to read file \'{file}\' with error {type(_lowerCamelCase )}: {e}' ) raise e # If possible, parse the file as a list of json objects and exit the loop if isinstance(_lowerCamelCase , _lowerCamelCase ): # list is the only sequence type supported in JSON try: A_ : Optional[int] = set().union(*[row.keys() for row in dataset] ) A_ : Tuple = {col: [row.get(_lowerCamelCase ) for row in dataset] for col in keys} A_ : int = pa.Table.from_pydict(_lowerCamelCase ) except (pa.ArrowInvalid, AttributeError) as e: logger.error(f'Failed to read file \'{file}\' with error {type(_lowerCamelCase )}: {e}' ) raise ValueError(f'Not able to read records in the JSON file at {file}.' ) from None yield file_idx, self._cast_table(_lowerCamelCase ) break else: logger.error(f'Failed to read file \'{file}\' with error {type(_lowerCamelCase )}: {e}' ) raise ValueError( f'Not able to read records in the JSON file at {file}. ' f'You should probably indicate the field of the JSON file containing your records. ' f'This JSON file contain the following fields: {str(list(dataset.keys() ) )}. ' f'Select the correct one and provide it as `field=\'XXX\'` to the dataset loading method. ' ) from None # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(_lowerCamelCase ) batch_idx += 1
4
0
from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase_ = logging.get_logger(__name__) lowerCAmelCase_ = { '''microsoft/biogpt''': '''https://huggingface.co/microsoft/biogpt/resolve/main/config.json''', # See all BioGPT models at https://huggingface.co/models?filter=biogpt } class __lowerCAmelCase ( _a ): lowerCamelCase_ : Tuple = '''biogpt''' def __init__(self , __magic_name__=4_2384 , __magic_name__=1024 , __magic_name__=24 , __magic_name__=16 , __magic_name__=4096 , __magic_name__="gelu" , __magic_name__=0.1 , __magic_name__=0.1 , __magic_name__=1024 , __magic_name__=0.02 , __magic_name__=1e-12 , __magic_name__=True , __magic_name__=True , __magic_name__=0.0 , __magic_name__=0.0 , __magic_name__=1 , __magic_name__=0 , __magic_name__=2 , **__magic_name__ , ) -> Optional[int]: '''simple docstring''' snake_case_ : Optional[int] = vocab_size snake_case_ : int = max_position_embeddings snake_case_ : Union[str, Any] = hidden_size snake_case_ : Dict = num_hidden_layers snake_case_ : int = num_attention_heads snake_case_ : Union[str, Any] = intermediate_size snake_case_ : Optional[Any] = hidden_act snake_case_ : Dict = hidden_dropout_prob snake_case_ : Optional[int] = attention_probs_dropout_prob snake_case_ : Dict = initializer_range snake_case_ : List[str] = layer_norm_eps snake_case_ : List[str] = scale_embedding snake_case_ : int = use_cache snake_case_ : str = layerdrop snake_case_ : Optional[Any] = activation_dropout super().__init__(pad_token_id=__magic_name__ , bos_token_id=__magic_name__ , eos_token_id=__magic_name__ , **__magic_name__ )
279
import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand lowerCAmelCase_ = ( '''4S 3H 2C 7S 5H''', '''9D 8H 2C 6S 7H''', '''2D 6D 9D TH 7D''', '''TC 8C 2S JH 6C''', '''JH 8S TH AH QH''', '''TS KS 5S 9S AC''', '''KD 6S 9D TH AD''', '''KS 8D 4D 9S 4S''', # pair '''8C 4S KH JS 4D''', # pair '''QH 8H KD JH 8S''', # pair '''KC 4H KS 2H 8D''', # pair '''KD 4S KC 3H 8S''', # pair '''AH 8S AS KC JH''', # pair '''3H 4C 4H 3S 2H''', # 2 pairs '''5S 5D 2C KH KH''', # 2 pairs '''3C KH 5D 5S KH''', # 2 pairs '''AS 3C KH AD KH''', # 2 pairs '''7C 7S 3S 7H 5S''', # 3 of a kind '''7C 7S KH 2H 7H''', # 3 of a kind '''AC KH QH AH AS''', # 3 of a kind '''2H 4D 3C AS 5S''', # straight (low ace) '''3C 5C 4C 2C 6H''', # straight '''6S 8S 7S 5H 9H''', # straight '''JS QS 9H TS KH''', # straight '''QC KH TS JS AH''', # straight (high ace) '''8C 9C 5C 3C TC''', # flush '''3S 8S 9S 5S KS''', # flush '''4C 5C 9C 8C KC''', # flush '''JH 8H AH KH QH''', # flush '''3D 2H 3H 2C 2D''', # full house '''2H 2C 3S 3H 3D''', # full house '''KH KC 3S 3H 3D''', # full house '''JC 6H JS JD JH''', # 4 of a kind '''JC 7H JS JD JH''', # 4 of a kind '''JC KH JS JD JH''', # 4 of a kind '''2S AS 4S 5S 3S''', # straight flush (low ace) '''2D 6D 3D 4D 5D''', # straight flush '''5C 6C 3C 7C 4C''', # straight flush '''JH 9H TH KH QH''', # straight flush '''JH AH TH KH QH''', # royal flush (high ace straight flush) ) lowerCAmelCase_ = ( ('''2H 3H 4H 5H 6H''', '''KS AS TS QS JS''', '''Loss'''), ('''2H 3H 4H 5H 6H''', '''AS AD AC AH JD''', '''Win'''), ('''AS AH 2H AD AC''', '''JS JD JC JH 3D''', '''Win'''), ('''2S AH 2H AS AC''', '''JS JD JC JH AD''', '''Loss'''), ('''2S AH 2H AS AC''', '''2H 3H 5H 6H 7H''', '''Win'''), ('''AS 3S 4S 8S 2S''', '''2H 3H 5H 6H 7H''', '''Win'''), ('''2H 3H 5H 6H 7H''', '''2S 3H 4H 5S 6C''', '''Win'''), ('''2S 3H 4H 5S 6C''', '''3D 4C 5H 6H 2S''', '''Tie'''), ('''2S 3H 4H 5S 6C''', '''AH AC 5H 6H AS''', '''Win'''), ('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H AS''', '''Loss'''), ('''2S 2H 4H 5S 4C''', '''AH AC 5H 6H 7S''', '''Win'''), ('''6S AD 7H 4S AS''', '''AH AC 5H 6H 7S''', '''Loss'''), ('''2S AH 4H 5S KC''', '''AH AC 5H 6H 7S''', '''Loss'''), ('''2S 3H 6H 7S 9C''', '''7H 3C TH 6H 9S''', '''Loss'''), ('''4S 5H 6H TS AC''', '''3S 5H 6H TS AC''', '''Win'''), ('''2S AH 4H 5S 6C''', '''AD 4C 5H 6H 2C''', '''Tie'''), ('''AS AH 3H AD AC''', '''AS AH 2H AD AC''', '''Win'''), ('''AH AC 5H 5C QS''', '''AH AC 5H 5C KS''', '''Loss'''), ('''AH AC 5H 5C QS''', '''KH KC 5H 5C QS''', '''Win'''), ('''7C 7S KH 2H 7H''', '''3C 3S AH 2H 3H''', '''Win'''), ('''3C 3S AH 2H 3H''', '''7C 7S KH 2H 7H''', '''Loss'''), ('''6H 5H 4H 3H 2H''', '''5H 4H 3H 2H AH''', '''Win'''), ('''5H 4H 3H 2H AH''', '''5H 4H 3H 2H AH''', '''Tie'''), ('''5H 4H 3H 2H AH''', '''6H 5H 4H 3H 2H''', '''Loss'''), ('''AH AD KS KC AC''', '''AH KD KH AC KC''', '''Win'''), ('''2H 4D 3C AS 5S''', '''2H 4D 3C 6S 5S''', '''Loss'''), ('''2H 3S 3C 3H 2S''', '''3S 3C 2S 2H 2D''', '''Win'''), ('''4D 6D 5D 2D JH''', '''3S 8S 3H TC KH''', '''Loss'''), ('''4S 6C 8S 3S 7S''', '''AD KS 2D 7D 7C''', '''Loss'''), ('''6S 4C 7H 8C 3H''', '''5H JC AH 9D 9C''', '''Loss'''), ('''9D 9H JH TC QH''', '''3C 2S JS 5C 7H''', '''Win'''), ('''2H TC 8S AD 9S''', '''4H TS 7H 2C 5C''', '''Win'''), ('''9D 3S 2C 7S 7C''', '''JC TD 3C TC 9H''', '''Loss'''), ) lowerCAmelCase_ = ( ('''2H 3H 4H 5H 6H''', True), ('''AS AH 2H AD AC''', False), ('''2H 3H 5H 6H 7H''', True), ('''KS AS TS QS JS''', True), ('''8H 9H QS JS TH''', False), ('''AS 3S 4S 8S 2S''', True), ) lowerCAmelCase_ = ( ('''2H 3H 4H 5H 6H''', True), ('''AS AH 2H AD AC''', False), ('''2H 3H 5H 6H 7H''', False), ('''KS AS TS QS JS''', True), ('''8H 9H QS JS TH''', True), ) lowerCAmelCase_ = ( ('''2H 4D 3C AS 5S''', True, [5, 4, 3, 2, 1_4]), ('''2H 5D 3C AS 5S''', False, [1_4, 5, 5, 3, 2]), ('''JH QD KC AS TS''', False, [1_4, 1_3, 1_2, 1_1, 1_0]), ('''9D 3S 2C 7S 7C''', False, [9, 7, 7, 3, 2]), ) lowerCAmelCase_ = ( ('''JH AH TH KH QH''', 0), ('''JH 9H TH KH QH''', 0), ('''JC KH JS JD JH''', 7), ('''KH KC 3S 3H 3D''', 6), ('''8C 9C 5C 3C TC''', 0), ('''JS QS 9H TS KH''', 0), ('''7C 7S KH 2H 7H''', 3), ('''3C KH 5D 5S KH''', 2), ('''QH 8H KD JH 8S''', 1), ('''2D 6D 9D TH 7D''', 0), ) lowerCAmelCase_ = ( ('''JH AH TH KH QH''', 2_3), ('''JH 9H TH KH QH''', 2_2), ('''JC KH JS JD JH''', 2_1), ('''KH KC 3S 3H 3D''', 2_0), ('''8C 9C 5C 3C TC''', 1_9), ('''JS QS 9H TS KH''', 1_8), ('''7C 7S KH 2H 7H''', 1_7), ('''3C KH 5D 5S KH''', 1_6), ('''QH 8H KD JH 8S''', 1_5), ('''2D 6D 9D TH 7D''', 1_4), ) def lowerCamelCase_ ( ) -> Dict: """simple docstring""" snake_case_ , snake_case_ : Any = randrange(len(_UpperCamelCase ) ), randrange(len(_UpperCamelCase ) ) snake_case_ : Any = ['''Loss''', '''Tie''', '''Win'''][(play >= oppo) + (play > oppo)] snake_case_ , snake_case_ : Tuple = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def lowerCamelCase_ ( _UpperCamelCase = 100 ) -> str: """simple docstring""" return (generate_random_hand() for _ in range(_UpperCamelCase )) @pytest.mark.parametrize('''hand, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> int: """simple docstring""" assert PokerHand(_UpperCamelCase )._is_flush() == expected @pytest.mark.parametrize('''hand, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Optional[int]: """simple docstring""" assert PokerHand(_UpperCamelCase )._is_straight() == expected @pytest.mark.parametrize('''hand, expected, card_values''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Tuple: """simple docstring""" snake_case_ : str = PokerHand(_UpperCamelCase ) assert player._is_five_high_straight() == expected assert player._card_values == card_values @pytest.mark.parametrize('''hand, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> int: """simple docstring""" assert PokerHand(_UpperCamelCase )._is_same_kind() == expected @pytest.mark.parametrize('''hand, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase ) -> Optional[int]: """simple docstring""" assert PokerHand(_UpperCamelCase )._hand_type == expected @pytest.mark.parametrize('''hand, other, expected''' , _UpperCamelCase ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Any: """simple docstring""" assert PokerHand(_UpperCamelCase ).compare_with(PokerHand(_UpperCamelCase ) ) == expected @pytest.mark.parametrize('''hand, other, expected''' , generate_random_hands() ) def lowerCamelCase_ ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Optional[Any]: """simple docstring""" assert PokerHand(_UpperCamelCase ).compare_with(PokerHand(_UpperCamelCase ) ) == expected def lowerCamelCase_ ( ) -> str: """simple docstring""" snake_case_ : Dict = [PokerHand(_UpperCamelCase ) for hand in SORTED_HANDS] snake_case_ : str = poker_hands.copy() shuffle(_UpperCamelCase ) snake_case_ : List[str] = chain(sorted(_UpperCamelCase ) ) for index, hand in enumerate(_UpperCamelCase ): assert hand == poker_hands[index] def lowerCamelCase_ ( ) -> Dict: """simple docstring""" snake_case_ : Union[str, Any] = [PokerHand('''2D AC 3H 4H 5S''' ), PokerHand('''2S 3H 4H 5S 6C''' )] pokerhands.sort(reverse=_UpperCamelCase ) assert pokerhands[0].__str__() == "2S 3H 4H 5S 6C" def lowerCamelCase_ ( ) -> str: """simple docstring""" snake_case_ : Dict = PokerHand('''2C 4S AS 3D 5C''' ) snake_case_ : str = True snake_case_ : Tuple = [5, 4, 3, 2, 14] for _ in range(10 ): assert pokerhand._is_five_high_straight() == expected assert pokerhand._card_values == expected_card_values def lowerCamelCase_ ( ) -> List[str]: """simple docstring""" snake_case_ : List[str] = 0 snake_case_ : Union[str, Any] = os.path.abspath(os.path.dirname(_UpperCamelCase ) ) snake_case_ : Dict = os.path.join(_UpperCamelCase , '''poker_hands.txt''' ) with open(_UpperCamelCase ) as file_hand: for line in file_hand: snake_case_ : Dict = line[:14].strip() snake_case_ : List[str] = line[15:].strip() snake_case_ , snake_case_ : str = PokerHand(_UpperCamelCase ), PokerHand(_UpperCamelCase ) snake_case_ : int = player.compare_with(_UpperCamelCase ) if output == "Win": answer += 1 assert answer == 376
279
1
import datasets SCREAMING_SNAKE_CASE : str = "\\n@InProceedings{conneau2018xnli,\n author = \"Conneau, Alexis\n and Rinott, Ruty\n and Lample, Guillaume\n and Williams, Adina\n and Bowman, Samuel R.\n and Schwenk, Holger\n and Stoyanov, Veselin\",\n title = \"XNLI: Evaluating Cross-lingual Sentence Representations\",\n booktitle = \"Proceedings of the 2018 Conference on Empirical Methods\n in Natural Language Processing\",\n year = \"2018\",\n publisher = \"Association for Computational Linguistics\",\n location = \"Brussels, Belgium\",\n}\n" SCREAMING_SNAKE_CASE : List[Any] = "\\nXNLI is a subset of a few thousand examples from MNLI which has been translated\ninto a 14 different languages (some low-ish resource). As with MNLI, the goal is\nto predict textual entailment (does sentence A imply/contradict/neither sentence\nB) and is a classification task (given two sentences, predict one of three\nlabels).\n" SCREAMING_SNAKE_CASE : Optional[int] = "\nComputes XNLI score which is just simple accuracy.\nArgs:\n predictions: Predicted labels.\n references: Ground truth labels.\nReturns:\n 'accuracy': accuracy\nExamples:\n\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> xnli_metric = datasets.load_metric(\"xnli\")\n >>> results = xnli_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0}\n" def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ ) -> Optional[Any]: return (preds == labels).mean() @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class _lowerCamelCase( datasets.Metric ): def UpperCamelCase ( self) -> List[str]: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { 'predictions': datasets.Value('int64' if self.config_name != 'sts-b' else 'float32'), 'references': datasets.Value('int64' if self.config_name != 'sts-b' else 'float32'), }), codebase_urls=[], reference_urls=[], format='numpy', ) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase) -> Optional[int]: """simple docstring""" return {"accuracy": simple_accuracy(lowerCamelCase, lowerCamelCase)}
84
from __future__ import annotations def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_ = None ) -> list[list[str]]: _lowercase : Optional[Any] = word_bank or [] # create a table _lowercase : int = len(lowerCamelCase_ ) + 1 _lowercase : list[list[list[str]]] = [] for _ in range(lowerCamelCase_ ): table.append([] ) # seed value _lowercase : Union[str, Any] = [[]] # because empty string has empty combination # iterate through the indices for i in range(lowerCamelCase_ ): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(lowerCamelCase_ )] == word: _lowercase : list[list[str]] = [ [word, *way] for way in table[i] ] # adds the word to every combination the current position holds # now,push that combination to the table[i+len(word)] table[i + len(lowerCamelCase_ )] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(lowerCamelCase_ )]: combination.reverse() return table[len(lowerCamelCase_ )] if __name__ == "__main__": print(all_construct("jwajalapa", ["jwa", "j", "w", "a", "la", "lapa"])) print(all_construct("rajamati", ["s", "raj", "amat", "raja", "ma", "i", "t"])) print( all_construct( "hexagonosaurus", ["h", "ex", "hex", "ag", "ago", "ru", "auru", "rus", "go", "no", "o", "s"], ) )
84
1
import math import tensorflow as tf from packaging import version def lowerCAmelCase_ ( __A ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase__ = tf.convert_to_tensor(__A ) UpperCAmelCase__ = 0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0 ), x.dtype ) )) return x * cdf def lowerCAmelCase_ ( __A ) -> Optional[int]: '''simple docstring''' UpperCAmelCase__ = tf.convert_to_tensor(__A ) UpperCAmelCase__ = tf.cast(math.pi, x.dtype ) UpperCAmelCase__ = tf.cast(0.044715, x.dtype ) UpperCAmelCase__ = 0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi ) * (x + coeff * tf.pow(__A, 3 )) )) return x * cdf def lowerCAmelCase_ ( __A ) -> Any: '''simple docstring''' UpperCAmelCase__ = tf.convert_to_tensor(__A ) return x * tf.tanh(tf.math.softplus(__A ) ) def lowerCAmelCase_ ( __A ) -> List[Any]: '''simple docstring''' UpperCAmelCase__ = tf.convert_to_tensor(__A ) UpperCAmelCase__ = tf.cast(0.044715, x.dtype ) UpperCAmelCase__ = tf.cast(0.7978845608, x.dtype ) return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x) )) def lowerCAmelCase_ ( __A ) -> Optional[int]: '''simple docstring''' UpperCAmelCase__ = tf.convert_to_tensor(__A ) UpperCAmelCase__ = tf.cast(1.702, x.dtype ) return x * tf.math.sigmoid(coeff * x ) def lowerCAmelCase_ ( __A ) -> Dict: '''simple docstring''' return tf.clip_by_value(_gelu(__A ), -10, 10 ) def lowerCAmelCase_ ( __A, __A=-1 ) -> Dict: '''simple docstring''' UpperCAmelCase__ , UpperCAmelCase__ = tf.split(__A, 2, axis=__A ) return a * tf.math.sigmoid(__A ) if version.parse(tf.version.VERSION) >= version.parse('2.4'): def lowerCAmelCase_ ( __A ) -> Optional[Any]: '''simple docstring''' return tf.keras.activations.gelu(__A, approximate=__A ) UpperCamelCase__ = tf.keras.activations.gelu UpperCamelCase__ = approximate_gelu_wrap else: UpperCamelCase__ = _gelu UpperCamelCase__ = _gelu_new UpperCamelCase__ = { 'gelu': gelu, 'gelu_10': gelu_aa, 'gelu_fast': gelu_fast, 'gelu_new': gelu_new, 'glu': glu, 'mish': mish, 'quick_gelu': quick_gelu, 'relu': tf.keras.activations.relu, 'sigmoid': tf.keras.activations.sigmoid, 'silu': tf.keras.activations.swish, 'swish': tf.keras.activations.swish, 'tanh': tf.keras.activations.tanh, } def lowerCAmelCase_ ( __A ) -> Tuple: '''simple docstring''' if activation_string in ACTaFN: return ACTaFN[activation_string] else: raise KeyError(f"""function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}""" )
65
import warnings from typing import Any, Dict, List, Optional, Union import numpy as np from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function from ...feature_extraction_sequence_utils import SequenceFeatureExtractor from ...feature_extraction_utils import BatchFeature from ...utils import PaddingStrategy, TensorType, logging UpperCamelCase__ = logging.get_logger(__name__) class A ( UpperCAmelCase_ ): __UpperCAmelCase : int = ['input_values', 'attention_mask'] def __init__(self : Any , __UpperCAmelCase : int = 1 , __UpperCAmelCase : int = 1_6_0_0_0 , __UpperCAmelCase : float = 0.0 , __UpperCAmelCase : bool = False , __UpperCAmelCase : int = 8_0 , __UpperCAmelCase : int = 1_6 , __UpperCAmelCase : int = 6_4 , __UpperCAmelCase : str = "hann_window" , __UpperCAmelCase : float = 1.0 , __UpperCAmelCase : float = 8_0 , __UpperCAmelCase : float = 7_6_0_0 , __UpperCAmelCase : float = 1E-10 , __UpperCAmelCase : int = 2 , __UpperCAmelCase : bool = True , **__UpperCAmelCase : Any , ) -> str: """simple docstring""" super().__init__(feature_size=__UpperCAmelCase , sampling_rate=__UpperCAmelCase , padding_value=__UpperCAmelCase , **__UpperCAmelCase ) UpperCAmelCase__ = do_normalize UpperCAmelCase__ = return_attention_mask UpperCAmelCase__ = num_mel_bins UpperCAmelCase__ = hop_length UpperCAmelCase__ = win_length UpperCAmelCase__ = win_function UpperCAmelCase__ = frame_signal_scale UpperCAmelCase__ = fmin UpperCAmelCase__ = fmax UpperCAmelCase__ = mel_floor UpperCAmelCase__ = reduction_factor UpperCAmelCase__ = win_length * sampling_rate // 1_0_0_0 UpperCAmelCase__ = hop_length * sampling_rate // 1_0_0_0 UpperCAmelCase__ = optimal_fft_length(self.sample_size ) UpperCAmelCase__ = (self.n_fft // 2) + 1 UpperCAmelCase__ = window_function(window_length=self.sample_size , name=self.win_function , periodic=__UpperCAmelCase ) UpperCAmelCase__ = mel_filter_bank( num_frequency_bins=self.n_freqs , num_mel_filters=self.num_mel_bins , min_frequency=self.fmin , max_frequency=self.fmax , sampling_rate=self.sampling_rate , norm="slaney" , mel_scale="slaney" , ) if frame_signal_scale != 1.0: warnings.warn( "The argument `frame_signal_scale` is deprecated and will be removed in version 4.30.0 of Transformers" , __UpperCAmelCase , ) if reduction_factor != 2.0: warnings.warn( "The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers" , __UpperCAmelCase , ) @staticmethod # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm def lowercase_ (__UpperCAmelCase : List[np.ndarray] , __UpperCAmelCase : List[np.ndarray] , __UpperCAmelCase : float = 0.0 ) -> List[np.ndarray]: """simple docstring""" if attention_mask is not None: UpperCAmelCase__ = np.array(__UpperCAmelCase , np.intaa ) UpperCAmelCase__ = [] for vector, length in zip(__UpperCAmelCase , attention_mask.sum(-1 ) ): UpperCAmelCase__ = (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1E-7 ) if length < normed_slice.shape[0]: UpperCAmelCase__ = padding_value normed_input_values.append(__UpperCAmelCase ) else: UpperCAmelCase__ = [(x - x.mean()) / np.sqrt(x.var() + 1E-7 ) for x in input_values] return normed_input_values def lowercase_ (self : Optional[int] , __UpperCAmelCase : np.ndarray , ) -> np.ndarray: """simple docstring""" UpperCAmelCase__ = spectrogram( __UpperCAmelCase , window=self.window , frame_length=self.sample_size , hop_length=self.sample_stride , fft_length=self.n_fft , mel_filters=self.mel_filters , mel_floor=self.mel_floor , log_mel="log10" , ) return log_mel_spec.T def __call__(self : Any , __UpperCAmelCase : Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None , __UpperCAmelCase : Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None , __UpperCAmelCase : Union[bool, str, PaddingStrategy] = False , __UpperCAmelCase : Optional[int] = None , __UpperCAmelCase : bool = False , __UpperCAmelCase : Optional[int] = None , __UpperCAmelCase : Optional[bool] = None , __UpperCAmelCase : Optional[Union[str, TensorType]] = None , __UpperCAmelCase : Optional[int] = None , **__UpperCAmelCase : str , ) -> BatchFeature: """simple docstring""" if audio is None and audio_target is None: raise ValueError("You must provide either `audio` or `audio_target` values." ) if sampling_rate is not None: if sampling_rate != self.sampling_rate: raise ValueError( f"""The model corresponding to this feature extractor: {self} was trained using a sampling rate of""" f""" {self.sampling_rate}. Please make sure that the provided audio input was sampled with""" f""" {self.sampling_rate} and not {sampling_rate}.""" ) else: logger.warning( "It is strongly recommended to pass the ``sampling_rate`` argument to this function. " "Failing to do so can result in silent errors that might be hard to debug." ) if audio is not None: UpperCAmelCase__ = self._process_audio( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase , ) else: UpperCAmelCase__ = None if audio_target is not None: UpperCAmelCase__ = self._process_audio( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , **__UpperCAmelCase , ) if inputs is None: return inputs_target else: UpperCAmelCase__ = inputs_target["input_values"] UpperCAmelCase__ = inputs_target.get("attention_mask" ) if decoder_attention_mask is not None: UpperCAmelCase__ = decoder_attention_mask return inputs def lowercase_ (self : Optional[int] , __UpperCAmelCase : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , __UpperCAmelCase : bool = False , __UpperCAmelCase : Union[bool, str, PaddingStrategy] = False , __UpperCAmelCase : Optional[int] = None , __UpperCAmelCase : bool = False , __UpperCAmelCase : Optional[int] = None , __UpperCAmelCase : Optional[bool] = None , __UpperCAmelCase : Optional[Union[str, TensorType]] = None , **__UpperCAmelCase : Any , ) -> BatchFeature: """simple docstring""" UpperCAmelCase__ = isinstance(__UpperCAmelCase , np.ndarray ) and len(speech.shape ) > 1 if is_batched_numpy and len(speech.shape ) > 2: raise ValueError(f"""Only mono-channel audio is supported for input to {self}""" ) UpperCAmelCase__ = is_batched_numpy or ( isinstance(__UpperCAmelCase , (list, tuple) ) and (isinstance(speech[0] , (np.ndarray, tuple, list) )) ) if is_batched: UpperCAmelCase__ = [np.asarray(__UpperCAmelCase , dtype=np.floataa ) for speech in speech] elif not is_batched and not isinstance(__UpperCAmelCase , np.ndarray ): UpperCAmelCase__ = np.asarray(__UpperCAmelCase , dtype=np.floataa ) elif isinstance(__UpperCAmelCase , np.ndarray ) and speech.dtype is np.dtype(np.floataa ): UpperCAmelCase__ = speech.astype(np.floataa ) # always return batch if not is_batched: UpperCAmelCase__ = [speech] # needed to make pad() work on spectrogram inputs UpperCAmelCase__ = self.feature_size # convert into correct format for padding if is_target: UpperCAmelCase__ = [self._extract_mel_features(__UpperCAmelCase ) for waveform in speech] UpperCAmelCase__ = BatchFeature({"input_values": features} ) UpperCAmelCase__ = self.num_mel_bins else: UpperCAmelCase__ = BatchFeature({"input_values": speech} ) UpperCAmelCase__ = self.pad( __UpperCAmelCase , padding=__UpperCAmelCase , max_length=__UpperCAmelCase , truncation=__UpperCAmelCase , pad_to_multiple_of=__UpperCAmelCase , return_attention_mask=__UpperCAmelCase , **__UpperCAmelCase , ) UpperCAmelCase__ = feature_size_hack # convert input values to correct format UpperCAmelCase__ = padded_inputs["input_values"] if not isinstance(input_values[0] , np.ndarray ): UpperCAmelCase__ = [np.asarray(__UpperCAmelCase , dtype=np.floataa ) for array in input_values] elif ( not isinstance(__UpperCAmelCase , np.ndarray ) and isinstance(input_values[0] , np.ndarray ) and input_values[0].dtype is np.dtype(np.floataa ) ): UpperCAmelCase__ = [array.astype(np.floataa ) for array in input_values] elif isinstance(__UpperCAmelCase , np.ndarray ) and input_values.dtype is np.dtype(np.floataa ): UpperCAmelCase__ = input_values.astype(np.floataa ) # convert attention_mask to correct format UpperCAmelCase__ = padded_inputs.get("attention_mask" ) if attention_mask is not None: UpperCAmelCase__ = [np.asarray(__UpperCAmelCase , dtype=np.intaa ) for array in attention_mask] # zero-mean and unit-variance normalization if not is_target and self.do_normalize: UpperCAmelCase__ = ( attention_mask if self._get_padding_strategies(__UpperCAmelCase , max_length=__UpperCAmelCase ) is not PaddingStrategy.DO_NOT_PAD else None ) UpperCAmelCase__ = self.zero_mean_unit_var_norm( padded_inputs["input_values"] , attention_mask=__UpperCAmelCase , padding_value=self.padding_value ) if return_tensors is not None: UpperCAmelCase__ = padded_inputs.convert_to_tensors(__UpperCAmelCase ) return padded_inputs def lowercase_ (self : Tuple ) -> Dict[str, Any]: """simple docstring""" UpperCAmelCase__ = super().to_dict() # Don't serialize these as they are derived from the other properties. UpperCAmelCase__ = ["window", "mel_filters", "sample_size", "sample_stride", "n_fft", "n_freqs"] for name in names: if name in output: del output[name] return output
65
1
'''simple docstring''' from typing import Optional import numpy as np import torch from torch import nn from transformers import GPTaConfig, GPTaLMHeadModel from transformers.modeling_utils import ModuleUtilsMixin from ...configuration_utils import ConfigMixin, register_to_config from ...models import ModelMixin class lowercase_ ( A , A , A ): """simple docstring""" lowerCamelCase_ = [r'''h\.\d+\.attn\.bias''', r'''h\.\d+\.attn\.masked_bias'''] @register_to_config def __init__( self : List[Any] , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : Optional[int] = None , __lowerCamelCase : int = 5_0_2_5_7 , __lowerCamelCase : int = 1_0_2_4 , __lowerCamelCase : int = 7_6_8 , __lowerCamelCase : int = 1_2 , __lowerCamelCase : int = 1_2 , __lowerCamelCase : Optional[int] = None , __lowerCamelCase : str = "gelu_new" , __lowerCamelCase : float = 0.1 , __lowerCamelCase : float = 0.1 , __lowerCamelCase : float = 0.1 , __lowerCamelCase : float = 1e-5 , __lowerCamelCase : float = 0.0_2 , __lowerCamelCase : bool = True , __lowerCamelCase : bool = True , __lowerCamelCase : bool = False , __lowerCamelCase : bool = False , ): """simple docstring""" super().__init__() _SCREAMING_SNAKE_CASE = prefix_length if prefix_inner_dim != n_embd and prefix_hidden_dim is None: raise ValueError( F"""`prefix_hidden_dim` cannot be `None` when `prefix_inner_dim`: {prefix_hidden_dim} and""" F""" `n_embd`: {n_embd} are not equal.""" ) _SCREAMING_SNAKE_CASE = prefix_inner_dim _SCREAMING_SNAKE_CASE = prefix_hidden_dim _SCREAMING_SNAKE_CASE = ( nn.Linear(self.prefix_inner_dim , self.prefix_hidden_dim ) if self.prefix_hidden_dim is not None else nn.Identity() ) _SCREAMING_SNAKE_CASE = ( nn.Linear(self.prefix_hidden_dim , __lowerCamelCase ) if self.prefix_hidden_dim is not None else nn.Identity() ) _SCREAMING_SNAKE_CASE = GPTaConfig( vocab_size=__lowerCamelCase , n_positions=__lowerCamelCase , n_embd=__lowerCamelCase , n_layer=__lowerCamelCase , n_head=__lowerCamelCase , n_inner=__lowerCamelCase , activation_function=__lowerCamelCase , resid_pdrop=__lowerCamelCase , embd_pdrop=__lowerCamelCase , attn_pdrop=__lowerCamelCase , layer_norm_epsilon=__lowerCamelCase , initializer_range=__lowerCamelCase , scale_attn_weights=__lowerCamelCase , use_cache=__lowerCamelCase , scale_attn_by_inverse_layer_idx=__lowerCamelCase , reorder_and_upcast_attn=__lowerCamelCase , ) _SCREAMING_SNAKE_CASE = GPTaLMHeadModel(__lowerCamelCase ) def lowerCAmelCase_ ( self : int , __lowerCamelCase : torch.Tensor , __lowerCamelCase : torch.Tensor , __lowerCamelCase : Optional[torch.Tensor] = None , __lowerCamelCase : Optional[torch.Tensor] = None , ): """simple docstring""" _SCREAMING_SNAKE_CASE = self.transformer.transformer.wte(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = self.encode_prefix(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = self.decode_prefix(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = torch.cat((prefix_embeds, embedding_text) , dim=1 ) if labels is not None: _SCREAMING_SNAKE_CASE = self.get_dummy_token(input_ids.shape[0] , input_ids.device ) _SCREAMING_SNAKE_CASE = torch.cat((dummy_token, input_ids) , dim=1 ) _SCREAMING_SNAKE_CASE = self.transformer(inputs_embeds=__lowerCamelCase , labels=__lowerCamelCase , attention_mask=__lowerCamelCase ) if self.prefix_hidden_dim is not None: return out, hidden else: return out def lowerCAmelCase_ ( self : List[Any] , __lowerCamelCase : int , __lowerCamelCase : torch.device ): """simple docstring""" return torch.zeros(__lowerCamelCase , self.prefix_length , dtype=torch.intaa , device=__lowerCamelCase ) def lowerCAmelCase_ ( self : Dict , __lowerCamelCase : int ): """simple docstring""" return self.encode_prefix(__lowerCamelCase ) @torch.no_grad() def lowerCAmelCase_ ( self : Optional[int] , __lowerCamelCase : Optional[int] , __lowerCamelCase : Tuple , __lowerCamelCase : Optional[Any] ): """simple docstring""" _SCREAMING_SNAKE_CASE = torch.split(__lowerCamelCase , 1 , dim=0 ) _SCREAMING_SNAKE_CASE = [] _SCREAMING_SNAKE_CASE = [] for feature in features: _SCREAMING_SNAKE_CASE = self.decode_prefix(feature.to(__lowerCamelCase ) ) # back to the clip feature # Only support beam search for now _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE = self.generate_beam( input_embeds=__lowerCamelCase , device=__lowerCamelCase , eos_token_id=__lowerCamelCase ) generated_tokens.append(output_tokens[0] ) generated_seq_lengths.append(seq_lengths[0] ) _SCREAMING_SNAKE_CASE = torch.stack(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = torch.stack(__lowerCamelCase ) return generated_tokens, generated_seq_lengths @torch.no_grad() def lowerCAmelCase_ ( self : List[str] , __lowerCamelCase : Any=None , __lowerCamelCase : Optional[Any]=None , __lowerCamelCase : Tuple=None , __lowerCamelCase : int = 5 , __lowerCamelCase : int = 6_7 , __lowerCamelCase : float = 1.0 , __lowerCamelCase : Optional[int] = None , ): """simple docstring""" _SCREAMING_SNAKE_CASE = eos_token_id _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = torch.ones(__lowerCamelCase , device=__lowerCamelCase , dtype=torch.int ) _SCREAMING_SNAKE_CASE = torch.zeros(__lowerCamelCase , device=__lowerCamelCase , dtype=torch.bool ) if input_embeds is not None: _SCREAMING_SNAKE_CASE = input_embeds else: _SCREAMING_SNAKE_CASE = self.transformer.transformer.wte(__lowerCamelCase ) for i in range(__lowerCamelCase ): _SCREAMING_SNAKE_CASE = self.transformer(inputs_embeds=__lowerCamelCase ) _SCREAMING_SNAKE_CASE = outputs.logits _SCREAMING_SNAKE_CASE = logits[:, -1, :] / (temperature if temperature > 0 else 1.0) _SCREAMING_SNAKE_CASE = logits.softmax(-1 ).log() if scores is None: _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE = logits.topk(__lowerCamelCase , -1 ) _SCREAMING_SNAKE_CASE = generated.expand(__lowerCamelCase , *generated.shape[1:] ) _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE = next_tokens.permute(1 , 0 ), scores.squeeze(0 ) if tokens is None: _SCREAMING_SNAKE_CASE = next_tokens else: _SCREAMING_SNAKE_CASE = tokens.expand(__lowerCamelCase , *tokens.shape[1:] ) _SCREAMING_SNAKE_CASE = torch.cat((tokens, next_tokens) , dim=1 ) else: _SCREAMING_SNAKE_CASE = -float(np.inf ) _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = scores[:, None] + logits seq_lengths[~is_stopped] += 1 _SCREAMING_SNAKE_CASE = scores_sum / seq_lengths[:, None] _SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE = scores_sum_average.view(-1 ).topk(__lowerCamelCase , -1 ) _SCREAMING_SNAKE_CASE = next_tokens // scores_sum.shape[1] _SCREAMING_SNAKE_CASE = seq_lengths[next_tokens_source] _SCREAMING_SNAKE_CASE = next_tokens % scores_sum.shape[1] _SCREAMING_SNAKE_CASE = next_tokens.unsqueeze(1 ) _SCREAMING_SNAKE_CASE = tokens[next_tokens_source] _SCREAMING_SNAKE_CASE = torch.cat((tokens, next_tokens) , dim=1 ) _SCREAMING_SNAKE_CASE = generated[next_tokens_source] _SCREAMING_SNAKE_CASE = scores_sum_average * seq_lengths _SCREAMING_SNAKE_CASE = is_stopped[next_tokens_source] _SCREAMING_SNAKE_CASE = self.transformer.transformer.wte(next_tokens.squeeze() ).view(generated.shape[0] , 1 , -1 ) _SCREAMING_SNAKE_CASE = torch.cat((generated, next_token_embed) , dim=1 ) _SCREAMING_SNAKE_CASE = is_stopped + next_tokens.eq(__lowerCamelCase ).squeeze() if is_stopped.all(): break _SCREAMING_SNAKE_CASE = scores / seq_lengths _SCREAMING_SNAKE_CASE = scores.argsort(descending=__lowerCamelCase ) # tokens tensors are already padded to max_seq_length _SCREAMING_SNAKE_CASE = [tokens[i] for i in order] _SCREAMING_SNAKE_CASE = torch.stack(__lowerCamelCase , dim=0 ) _SCREAMING_SNAKE_CASE = torch.tensor([seq_lengths[i] for i in order] , dtype=seq_lengths.dtype ) return output_texts, seq_lengths
111
'''simple docstring''' from collections.abc import Sequence def SCREAMING_SNAKE_CASE_ ( __A : Sequence[int] | None = None ) -> int: if nums is None or not nums: raise ValueError("Input sequence should not be empty" ) _SCREAMING_SNAKE_CASE = nums[0] for i in range(1 , len(__A ) ): _SCREAMING_SNAKE_CASE = nums[i] _SCREAMING_SNAKE_CASE = max(__A , ans + num , __A ) return ans if __name__ == "__main__": import doctest doctest.testmod() # Try on a sample input from the user lowerCamelCase_ = int(input('Enter number of elements : ').strip()) lowerCamelCase_ = list(map(int, input('\nEnter the numbers : ').strip().split()))[:n] print(max_subsequence_sum(array))
111
1
"""simple docstring""" import os import unittest from tempfile import TemporaryDirectory import torch import torch.nn as nn from accelerate.utils import ( OffloadedWeightsLoader, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, ) class SCREAMING_SNAKE_CASE_ ( nn.Module ): """simple docstring""" def __init__( self): super().__init__() __SCREAMING_SNAKE_CASE = nn.Linear(3 , 4) __SCREAMING_SNAKE_CASE = nn.BatchNormad(4) __SCREAMING_SNAKE_CASE = nn.Linear(4 , 5) def snake_case_ ( self , lowerCAmelCase__): return self.lineara(self.batchnorm(self.lineara(lowerCAmelCase__))) class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): """simple docstring""" def snake_case_ ( self): __SCREAMING_SNAKE_CASE = ModelForTest() with TemporaryDirectory() as tmp_dir: offload_state_dict(lowerCAmelCase__ , model.state_dict()) __SCREAMING_SNAKE_CASE = os.path.join(lowerCAmelCase__ , """index.json""") self.assertTrue(os.path.isfile(lowerCAmelCase__)) # TODO: add tests on what is inside the index for key in ["linear1.weight", "linear1.bias", "linear2.weight", "linear2.bias"]: __SCREAMING_SNAKE_CASE = os.path.join(lowerCAmelCase__ , f"{key}.dat") self.assertTrue(os.path.isfile(lowerCAmelCase__)) # TODO: add tests on the fact weights are properly loaded def snake_case_ ( self): __SCREAMING_SNAKE_CASE = [torch.floataa, torch.floataa, torch.bfloataa] for dtype in dtypes: __SCREAMING_SNAKE_CASE = torch.randn(2 , 3 , dtype=lowerCAmelCase__) with TemporaryDirectory() as tmp_dir: __SCREAMING_SNAKE_CASE = offload_weight(lowerCAmelCase__ , """weight""" , lowerCAmelCase__ , {}) __SCREAMING_SNAKE_CASE = os.path.join(lowerCAmelCase__ , """weight.dat""") self.assertTrue(os.path.isfile(lowerCAmelCase__)) self.assertDictEqual(lowerCAmelCase__ , {"""weight""": {"""shape""": [2, 3], """dtype""": str(lowerCAmelCase__).split(""".""")[1]}}) __SCREAMING_SNAKE_CASE = load_offloaded_weight(lowerCAmelCase__ , index["""weight"""]) self.assertTrue(torch.equal(lowerCAmelCase__ , lowerCAmelCase__)) def snake_case_ ( self): __SCREAMING_SNAKE_CASE = ModelForTest() __SCREAMING_SNAKE_CASE = model.state_dict() __SCREAMING_SNAKE_CASE = {k: v for k, v in state_dict.items() if """linear2""" not in k} __SCREAMING_SNAKE_CASE = {k: v for k, v in state_dict.items() if """linear2""" in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(lowerCAmelCase__ , lowerCAmelCase__) __SCREAMING_SNAKE_CASE = OffloadedWeightsLoader(state_dict=lowerCAmelCase__ , save_folder=lowerCAmelCase__) # Every key is there with the right value self.assertEqual(sorted(lowerCAmelCase__) , sorted(state_dict.keys())) for key, param in state_dict.items(): self.assertTrue(torch.allclose(lowerCAmelCase__ , weight_map[key])) __SCREAMING_SNAKE_CASE = {k: v for k, v in state_dict.items() if """weight""" in k} __SCREAMING_SNAKE_CASE = {k: v for k, v in state_dict.items() if """weight""" not in k} with TemporaryDirectory() as tmp_dir: offload_state_dict(lowerCAmelCase__ , lowerCAmelCase__) __SCREAMING_SNAKE_CASE = OffloadedWeightsLoader(state_dict=lowerCAmelCase__ , save_folder=lowerCAmelCase__) # Every key is there with the right value self.assertEqual(sorted(lowerCAmelCase__) , sorted(state_dict.keys())) for key, param in state_dict.items(): self.assertTrue(torch.allclose(lowerCAmelCase__ , weight_map[key])) with TemporaryDirectory() as tmp_dir: offload_state_dict(lowerCAmelCase__ , lowerCAmelCase__) # Duplicates are removed __SCREAMING_SNAKE_CASE = OffloadedWeightsLoader(state_dict=lowerCAmelCase__ , save_folder=lowerCAmelCase__) # Every key is there with the right value self.assertEqual(sorted(lowerCAmelCase__) , sorted(state_dict.keys())) for key, param in state_dict.items(): self.assertTrue(torch.allclose(lowerCAmelCase__ , weight_map[key])) def snake_case_ ( self): __SCREAMING_SNAKE_CASE = {"""a.1""": 0, """a.10""": 1, """a.2""": 2} __SCREAMING_SNAKE_CASE = extract_submodules_state_dict(lowerCAmelCase__ , ["""a.1""", """a.2"""]) self.assertDictEqual(lowerCAmelCase__ , {"""a.1""": 0, """a.2""": 2}) __SCREAMING_SNAKE_CASE = {"""a.1.a""": 0, """a.10.a""": 1, """a.2.a""": 2} __SCREAMING_SNAKE_CASE = extract_submodules_state_dict(lowerCAmelCase__ , ["""a.1""", """a.2"""]) self.assertDictEqual(lowerCAmelCase__ , {"""a.1.a""": 0, """a.2.a""": 2})
100
"""simple docstring""" from __future__ import annotations from numpy import array, cos, cross, floataa, radians, sin from numpy.typing import NDArray def lowercase ( A_ , A_ , A_ = False )-> list[float]: '''simple docstring''' if radian_mode: return [magnitude * cos(A_ ), magnitude * sin(A_ )] return [magnitude * cos(radians(A_ ) ), magnitude * sin(radians(A_ ) )] def lowercase ( A_ , A_ , A_ = 10**-1 )-> bool: '''simple docstring''' a : NDArray[floataa] = cross(A_ , A_ ) a : float = sum(A_ ) return abs(A_ ) < eps if __name__ == "__main__": # Test to check if it works __lowercase = array( [ polar_force(7_18.4, 180 - 30), polar_force(8_79.54, 45), polar_force(100, -90), ] ) __lowercase = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem 1 in image_data/2D_problems.jpg __lowercase = array( [ polar_force(30 * 9.81, 15), polar_force(215, 180 - 45), polar_force(264, 90 - 30), ] ) __lowercase = array([[0, 0], [0, 0], [0, 0]]) assert in_static_equilibrium(forces, location) # Problem in image_data/2D_problems_1.jpg __lowercase = array([[0, -2000], [0, -1200], [0, 15600], [0, -12400]]) __lowercase = array([[0, 0], [6, 0], [10, 0], [12, 0]]) assert in_static_equilibrium(forces, location) import doctest doctest.testmod()
40
0
from dataclasses import dataclass, field from typing import Tuple from ..utils import cached_property, is_torch_available, is_torch_tpu_available, logging, requires_backends from .benchmark_args_utils import BenchmarkArguments if is_torch_available(): import torch if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm A : Any = logging.get_logger(__name__) @dataclass class A ( SCREAMING_SNAKE_CASE__ ): '''simple docstring''' A__ = [ '''no_inference''', '''no_cuda''', '''no_tpu''', '''no_speed''', '''no_memory''', '''no_env_print''', '''no_multi_process''', ] def __init__(self : List[Any] , **_UpperCAmelCase : Optional[int] ) -> Union[str, Any]: """simple docstring""" for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: lowercase__ = deprecated_arg[3:] setattr(self , A__ , not kwargs.pop(A__ ) ) logger.warning( f'''{deprecated_arg} is depreciated. Please use --no_{positive_arg} or''' f''' {positive_arg}={kwargs[positive_arg]}''' ) lowercase__ = kwargs.pop("""torchscript""" , self.torchscript ) lowercase__ = kwargs.pop("""torch_xla_tpu_print_metrics""" , self.torch_xla_tpu_print_metrics ) lowercase__ = kwargs.pop("""fp16_opt_level""" , self.fpaa_opt_level ) super().__init__(**A__ ) A__ = field(default=SCREAMING_SNAKE_CASE__ , metadata={'''help''': '''Trace the models using torchscript'''} ) A__ = field(default=SCREAMING_SNAKE_CASE__ , metadata={'''help''': '''Print Xla/PyTorch tpu metrics'''} ) A__ = field( default='''O1''' , metadata={ '''help''': ( '''For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\']. ''' '''See details at https://nvidia.github.io/apex/amp.html''' ) } , ) @cached_property def lowerCamelCase__ (self : Any ) -> str: """simple docstring""" requires_backends(self , ["""torch"""] ) logger.info("""PyTorch: setting up devices""" ) if not self.cuda: lowercase__ = torch.device("""cpu""" ) lowercase__ = 0 elif is_torch_tpu_available(): lowercase__ = xm.xla_device() lowercase__ = 0 else: lowercase__ = torch.device("""cuda""" if torch.cuda.is_available() else """cpu""" ) lowercase__ = torch.cuda.device_count() return device, n_gpu @property def lowerCamelCase__ (self : List[str] ) -> List[Any]: """simple docstring""" return is_torch_tpu_available() and self.tpu @property def lowerCamelCase__ (self : Tuple ) -> int: """simple docstring""" requires_backends(self , ["""torch"""] ) # TODO(PVP): currently only single GPU is supported return torch.cuda.current_device() @property def lowerCamelCase__ (self : Union[str, Any] ) -> Optional[int]: """simple docstring""" requires_backends(self , ["""torch"""] ) return self._setup_devices[0] @property def lowerCamelCase__ (self : Union[str, Any] ) -> Dict: """simple docstring""" requires_backends(self , ["""torch"""] ) return self._setup_devices[1] @property def lowerCamelCase__ (self : List[Any] ) -> Tuple: """simple docstring""" return self.n_gpu > 0
359
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A : Optional[Any] = logging.get_logger(__name__) A : Tuple = { 'YituTech/conv-bert-base': 'https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json', 'YituTech/conv-bert-medium-small': ( 'https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json' ), 'YituTech/conv-bert-small': 'https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json', # See all ConvBERT models at https://huggingface.co/models?filter=convbert } class A ( UpperCAmelCase__ ): '''simple docstring''' A__ = '''convbert''' def __init__(self : str , _UpperCAmelCase : Union[str, Any]=3_0522 , _UpperCAmelCase : Dict=768 , _UpperCAmelCase : Optional[int]=12 , _UpperCAmelCase : List[str]=12 , _UpperCAmelCase : str=3072 , _UpperCAmelCase : Tuple="gelu" , _UpperCAmelCase : Optional[int]=0.1 , _UpperCAmelCase : int=0.1 , _UpperCAmelCase : str=512 , _UpperCAmelCase : Dict=2 , _UpperCAmelCase : int=0.02 , _UpperCAmelCase : Tuple=1E-1_2 , _UpperCAmelCase : Dict=1 , _UpperCAmelCase : Optional[Any]=0 , _UpperCAmelCase : List[str]=2 , _UpperCAmelCase : str=768 , _UpperCAmelCase : List[Any]=2 , _UpperCAmelCase : Optional[Any]=9 , _UpperCAmelCase : List[Any]=1 , _UpperCAmelCase : Union[str, Any]=None , **_UpperCAmelCase : List[Any] , ) -> List[str]: """simple docstring""" super().__init__( pad_token_id=_UpperCAmelCase , bos_token_id=_UpperCAmelCase , eos_token_id=_UpperCAmelCase , **_UpperCAmelCase , ) lowercase__ = vocab_size lowercase__ = hidden_size lowercase__ = num_hidden_layers lowercase__ = num_attention_heads lowercase__ = intermediate_size lowercase__ = hidden_act lowercase__ = hidden_dropout_prob lowercase__ = attention_probs_dropout_prob lowercase__ = max_position_embeddings lowercase__ = type_vocab_size lowercase__ = initializer_range lowercase__ = layer_norm_eps lowercase__ = embedding_size lowercase__ = head_ratio lowercase__ = conv_kernel_size lowercase__ = num_groups lowercase__ = classifier_dropout class A ( UpperCAmelCase__ ): '''simple docstring''' @property def lowerCamelCase__ (self : Any ) -> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": lowercase__ = {0: """batch""", 1: """choice""", 2: """sequence"""} else: lowercase__ = {0: """batch""", 1: """sequence"""} return OrderedDict( [ ("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis), ] )
146
0
'''simple docstring''' from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging _SCREAMING_SNAKE_CASE = logging.get_logger(__name__) class lowerCAmelCase_ ( __lowerCAmelCase ): __lowerCamelCase : Any = ["pixel_values"] def __init__( self , _lowerCAmelCase = True , _lowerCAmelCase = 1 / 255 , _lowerCAmelCase = True , _lowerCAmelCase = 8 , **_lowerCAmelCase , ) -> Dict: super().__init__(**lowerCamelCase_ ) _lowerCAmelCase = do_rescale _lowerCAmelCase = rescale_factor _lowerCAmelCase = do_pad _lowerCAmelCase = pad_size def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = None , **_lowerCAmelCase ) -> List[str]: return rescale(lowerCamelCase_ , scale=lowerCamelCase_ , data_format=lowerCamelCase_ , **lowerCamelCase_ ) def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase = None ) -> Any: _lowerCAmelCase , _lowerCAmelCase = get_image_size(lowerCamelCase_ ) _lowerCAmelCase = (old_height // size + 1) * size - old_height _lowerCAmelCase = (old_width // size + 1) * size - old_width return pad(lowerCamelCase_ , ((0, pad_height), (0, pad_width)) , mode="symmetric" , data_format=lowerCamelCase_ ) def _snake_case ( self , _lowerCAmelCase , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = None , _lowerCAmelCase = ChannelDimension.FIRST , **_lowerCAmelCase , ) -> List[Any]: _lowerCAmelCase = do_rescale if do_rescale is not None else self.do_rescale _lowerCAmelCase = rescale_factor if rescale_factor is not None else self.rescale_factor _lowerCAmelCase = do_pad if do_pad is not None else self.do_pad _lowerCAmelCase = pad_size if pad_size is not None else self.pad_size _lowerCAmelCase = 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_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) # All transformations expect numpy arrays. _lowerCAmelCase = [to_numpy_array(lowerCamelCase_ ) for image in images] if do_rescale: _lowerCAmelCase = [self.rescale(image=lowerCamelCase_ , scale=lowerCamelCase_ ) for image in images] if do_pad: _lowerCAmelCase = [self.pad(lowerCamelCase_ , size=lowerCamelCase_ ) for image in images] _lowerCAmelCase = [to_channel_dimension_format(lowerCamelCase_ , lowerCamelCase_ ) for image in images] _lowerCAmelCase = {"pixel_values": images} return BatchFeature(data=lowerCamelCase_ , tensor_type=lowerCamelCase_ )
158
import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, FEATURE_EXTRACTOR_MAPPING, AutoConfig, AutoFeatureExtractor, WavaVecaConfig, WavaVecaFeatureExtractor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils""")) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 _SCREAMING_SNAKE_CASE = get_tests_dir("""fixtures""") _SCREAMING_SNAKE_CASE = get_tests_dir("""fixtures/dummy_feature_extractor_config.json""") _SCREAMING_SNAKE_CASE = get_tests_dir("""fixtures/dummy-config.json""") class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): def lowerCamelCase_ ( self : Any ): """simple docstring""" UpperCamelCase = 0 def lowerCamelCase_ ( self : str ): """simple docstring""" UpperCamelCase = AutoFeatureExtractor.from_pretrained("""facebook/wav2vec2-base-960h""" ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : Tuple ): """simple docstring""" UpperCamelCase = AutoFeatureExtractor.from_pretrained(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : int ): """simple docstring""" with tempfile.TemporaryDirectory() as tmpdirname: UpperCamelCase = WavaVecaConfig() # remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally UpperCamelCase = AutoFeatureExtractor.from_pretrained(lowerCamelCase_ ).to_dict() config_dict.pop("""feature_extractor_type""" ) UpperCamelCase = WavaVecaFeatureExtractor(**lowerCamelCase_ ) # save in new folder model_config.save_pretrained(lowerCamelCase_ ) config.save_pretrained(lowerCamelCase_ ) UpperCamelCase = AutoFeatureExtractor.from_pretrained(lowerCamelCase_ ) # make sure private variable is not incorrectly saved UpperCamelCase = json.loads(config.to_json_string() ) self.assertTrue("""_processor_class""" not in dict_as_saved ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase = AutoFeatureExtractor.from_pretrained(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) def lowerCamelCase_ ( self : Union[str, Any] ): """simple docstring""" with self.assertRaisesRegex( lowerCamelCase_ , """bert-base is not a local folder and is not a valid model identifier""" ): UpperCamelCase = AutoFeatureExtractor.from_pretrained("""bert-base""" ) def lowerCamelCase_ ( self : Dict ): """simple docstring""" with self.assertRaisesRegex( lowerCamelCase_ , R"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)""" ): UpperCamelCase = AutoFeatureExtractor.from_pretrained(lowerCamelCase_ , revision="""aaaaaa""" ) def lowerCamelCase_ ( self : List[str] ): """simple docstring""" with self.assertRaisesRegex( lowerCamelCase_ , """hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.""" , ): UpperCamelCase = AutoFeatureExtractor.from_pretrained("""hf-internal-testing/config-no-model""" ) def lowerCamelCase_ ( self : Optional[Any] ): """simple docstring""" with self.assertRaises(lowerCamelCase_ ): UpperCamelCase = AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" ) # If remote code is disabled, we can't load this config. with self.assertRaises(lowerCamelCase_ ): UpperCamelCase = AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" , trust_remote_code=lowerCamelCase_ ) UpperCamelCase = AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" , trust_remote_code=lowerCamelCase_ ) self.assertEqual(feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) # Test feature extractor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained(lowerCamelCase_ ) UpperCamelCase = AutoFeatureExtractor.from_pretrained(lowerCamelCase_ , trust_remote_code=lowerCamelCase_ ) self.assertEqual(reloaded_feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) def lowerCamelCase_ ( self : List[str] ): """simple docstring""" try: AutoConfig.register("""custom""" , lowerCamelCase_ ) AutoFeatureExtractor.register(lowerCamelCase_ , lowerCamelCase_ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(lowerCamelCase_ ): AutoFeatureExtractor.register(lowerCamelCase_ , lowerCamelCase_ ) # Now that the config is registered, it can be used as any other config with the auto-API UpperCamelCase = CustomFeatureExtractor.from_pretrained(lowerCamelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: feature_extractor.save_pretrained(lowerCamelCase_ ) UpperCamelCase = AutoFeatureExtractor.from_pretrained(lowerCamelCase_ ) self.assertIsInstance(lowerCamelCase_ , lowerCamelCase_ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig] def lowerCamelCase_ ( self : Any ): """simple docstring""" class SCREAMING_SNAKE_CASE_ ( __lowerCAmelCase ): __lowerCAmelCase = True try: AutoConfig.register("""custom""" , lowerCamelCase_ ) AutoFeatureExtractor.register(lowerCamelCase_ , lowerCamelCase_ ) # If remote code is not set, the default is to use local UpperCamelCase = AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" ) self.assertEqual(feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) self.assertTrue(feature_extractor.is_local ) # If remote code is disabled, we load the local one. UpperCamelCase = AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" , trust_remote_code=lowerCamelCase_ ) self.assertEqual(feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) self.assertTrue(feature_extractor.is_local ) # If remote is enabled, we load from the Hub UpperCamelCase = AutoFeatureExtractor.from_pretrained( """hf-internal-testing/test_dynamic_feature_extractor""" , trust_remote_code=lowerCamelCase_ ) self.assertEqual(feature_extractor.__class__.__name__ , """NewFeatureExtractor""" ) self.assertTrue(not hasattr(lowerCamelCase_ , """is_local""" ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content: del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]
343
0
"""simple docstring""" import re def UpperCamelCase_ ( lowerCAmelCase__ : str ) -> bool: """simple docstring""" lowerCAmelCase_ : str = re.compile( R'^(?:0|94|\+94|0{2}94)' R'7(0|1|2|4|5|6|7|8)' R'(-| |)' R'\d{7}$' ) return bool(re.search(lowerCAmelCase__ , lowerCAmelCase__ ) ) if __name__ == "__main__": lowercase__ : Optional[int] = """0094702343221""" print(is_sri_lankan_phone_number(phone))
289
"""simple docstring""" import os from bleurt import score # From: git+https://github.com/google-research/bleurt.git import datasets lowercase__ : Tuple = datasets.logging.get_logger(__name__) lowercase__ : List[Any] = """\ @inproceedings{bleurt, title={BLEURT: Learning Robust Metrics for Text Generation}, author={Thibault Sellam and Dipanjan Das and Ankur P. Parikh}, booktitle={ACL}, year={2020}, url={https://arxiv.org/abs/2004.04696} } """ lowercase__ : Tuple = """\ BLEURT a learnt evaluation metric for Natural Language Generation. It is built using multiple phases of transfer learning starting from a pretrained BERT model (Devlin et al. 2018) and then employing another pre-training phrase using synthetic data. Finally it is trained on WMT human annotations. You may run BLEURT out-of-the-box or fine-tune it for your specific application (the latter is expected to perform better). See the project's README at https://github.com/google-research/bleurt#readme for more information. """ lowercase__ : List[Any] = """ BLEURT score. Args: `predictions` (list of str): prediction/candidate sentences `references` (list of str): reference sentences `checkpoint` BLEURT checkpoint. Will default to BLEURT-tiny if None. Returns: 'scores': List of scores. Examples: >>> predictions = [\"hello there\", \"general kenobi\"] >>> references = [\"hello there\", \"general kenobi\"] >>> bleurt = datasets.load_metric(\"bleurt\") >>> results = bleurt.compute(predictions=predictions, references=references) >>> print([round(v, 2) for v in results[\"scores\"]]) [1.03, 1.04] """ lowercase__ : List[Any] = { """bleurt-tiny-128""": """https://storage.googleapis.com/bleurt-oss/bleurt-tiny-128.zip""", """bleurt-tiny-512""": """https://storage.googleapis.com/bleurt-oss/bleurt-tiny-512.zip""", """bleurt-base-128""": """https://storage.googleapis.com/bleurt-oss/bleurt-base-128.zip""", """bleurt-base-512""": """https://storage.googleapis.com/bleurt-oss/bleurt-base-512.zip""", """bleurt-large-128""": """https://storage.googleapis.com/bleurt-oss/bleurt-large-128.zip""", """bleurt-large-512""": """https://storage.googleapis.com/bleurt-oss/bleurt-large-512.zip""", """BLEURT-20-D3""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D3.zip""", """BLEURT-20-D6""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D6.zip""", """BLEURT-20-D12""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20-D12.zip""", """BLEURT-20""": """https://storage.googleapis.com/bleurt-oss-21/BLEURT-20.zip""", } @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class UpperCamelCase__ ( datasets.Metric ): """simple docstring""" def SCREAMING_SNAKE_CASE__ ( self : List[str] ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='https://github.com/google-research/bleurt' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence' ), 'references': datasets.Value('string' , id='sequence' ), } ) , codebase_urls=['https://github.com/google-research/bleurt'] , reference_urls=['https://github.com/google-research/bleurt', 'https://arxiv.org/abs/2004.04696'] , ) def SCREAMING_SNAKE_CASE__ ( self : str , SCREAMING_SNAKE_CASE_ : str ): # check that config name specifies a valid BLEURT model if self.config_name == "default": logger.warning( 'Using default BLEURT-Base checkpoint for sequence maximum length 128. ' 'You can use a bigger model for better results with e.g.: datasets.load_metric(\'bleurt\', \'bleurt-large-512\').' ) lowerCAmelCase_ : List[Any] = 'bleurt-base-128' if self.config_name.lower() in CHECKPOINT_URLS: lowerCAmelCase_ : List[Any] = self.config_name.lower() elif self.config_name.upper() in CHECKPOINT_URLS: lowerCAmelCase_ : Tuple = self.config_name.upper() else: raise KeyError( F"{self.config_name} model not found. You should supply the name of a model checkpoint for bleurt in {CHECKPOINT_URLS.keys()}" ) # download the model checkpoint specified by self.config_name and set up the scorer lowerCAmelCase_ : List[Any] = dl_manager.download_and_extract(CHECKPOINT_URLS[checkpoint_name] ) lowerCAmelCase_ : List[str] = score.BleurtScorer(os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) def SCREAMING_SNAKE_CASE__ ( self : str , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Any ): lowerCAmelCase_ : Tuple = self.scorer.score(references=SCREAMING_SNAKE_CASE_ , candidates=SCREAMING_SNAKE_CASE_ ) return {"scores": scores}
289
1
'''simple docstring''' import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class lowercase__ ( lowercase ): lowercase__ = None lowercase__ = None @property def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' return self.feat_extract_tester.prepare_feat_extract_dict() def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' _UpperCamelCase : Optional[Any] = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ ,'feature_size' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ ,'sampling_rate' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_ ,'padding_value' ) ) def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' _UpperCamelCase : int = self.feat_extract_tester.prepare_inputs_for_common() _UpperCamelCase : Dict = self.feature_extraction_class(**self.feat_extract_dict ) _UpperCamelCase : Optional[Any] = feat_extract.model_input_names[0] _UpperCamelCase : Dict = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(SCREAMING_SNAKE_CASE_ ) == len(SCREAMING_SNAKE_CASE_ ) for x, y in zip(SCREAMING_SNAKE_CASE_ ,processed_features[input_name] ) ) ) _UpperCamelCase : int = self.feat_extract_tester.prepare_inputs_for_common(equal_length=SCREAMING_SNAKE_CASE_ ) _UpperCamelCase : Any = BatchFeature({input_name: speech_inputs} ,tensor_type='np' ) _UpperCamelCase : Tuple = processed_features[input_name] if len(batch_features_input.shape ) < 3: _UpperCamelCase : str = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_torch def UpperCamelCase_ ( self : List[Any] ): '''simple docstring''' _UpperCamelCase : List[Any] = self.feat_extract_tester.prepare_inputs_for_common(equal_length=SCREAMING_SNAKE_CASE_ ) _UpperCamelCase : Dict = self.feature_extraction_class(**self.feat_extract_dict ) _UpperCamelCase : Tuple = feat_extract.model_input_names[0] _UpperCamelCase : List[Any] = BatchFeature({input_name: speech_inputs} ,tensor_type='pt' ) _UpperCamelCase : Dict = processed_features[input_name] if len(batch_features_input.shape ) < 3: _UpperCamelCase : Tuple = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) @require_tf def UpperCamelCase_ ( self : Any ): '''simple docstring''' _UpperCamelCase : Dict = self.feat_extract_tester.prepare_inputs_for_common(equal_length=SCREAMING_SNAKE_CASE_ ) _UpperCamelCase : int = self.feature_extraction_class(**self.feat_extract_dict ) _UpperCamelCase : Tuple = feat_extract.model_input_names[0] _UpperCamelCase : Union[str, Any] = BatchFeature({input_name: speech_inputs} ,tensor_type='tf' ) _UpperCamelCase : List[Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: _UpperCamelCase : Any = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) ) def UpperCamelCase_ ( self : List[str] ,lowerCamelCase__ : Union[str, Any]=False ): '''simple docstring''' def _inputs_have_equal_length(lowerCamelCase__ : Union[str, Any] ): _UpperCamelCase : Optional[int] = len(input[0] ) for input_slice in input[1:]: if len(SCREAMING_SNAKE_CASE_ ) != length: return False return True def _inputs_are_equal(lowerCamelCase__ : List[Any] ,lowerCamelCase__ : str ): if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ): return False for input_slice_a, input_slice_a in zip(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ): if not np.allclose(np.asarray(SCREAMING_SNAKE_CASE_ ) ,np.asarray(SCREAMING_SNAKE_CASE_ ) ,atol=1E-3 ): return False return True _UpperCamelCase : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_dict ) _UpperCamelCase : int = self.feat_extract_tester.prepare_inputs_for_common(numpify=SCREAMING_SNAKE_CASE_ ) _UpperCamelCase : List[Any] = feat_extract.model_input_names[0] _UpperCamelCase : Any = BatchFeature({input_name: speech_inputs} ) _UpperCamelCase : Tuple = self.feat_extract_tester.seq_length_diff _UpperCamelCase : Tuple = self.feat_extract_tester.max_seq_length + pad_diff _UpperCamelCase : Dict = self.feat_extract_tester.min_seq_length _UpperCamelCase : Optional[Any] = self.feat_extract_tester.batch_size _UpperCamelCase : List[str] = self.feat_extract_tester.feature_size # test padding for List[int] + numpy _UpperCamelCase : List[str] = feat_extract.pad(SCREAMING_SNAKE_CASE_ ,padding=SCREAMING_SNAKE_CASE_ ) _UpperCamelCase : str = input_a[input_name] _UpperCamelCase : Tuple = feat_extract.pad(SCREAMING_SNAKE_CASE_ ,padding='longest' ) _UpperCamelCase : int = input_a[input_name] _UpperCamelCase : Any = feat_extract.pad(SCREAMING_SNAKE_CASE_ ,padding='max_length' ,max_length=len(speech_inputs[-1] ) ) _UpperCamelCase : str = input_a[input_name] _UpperCamelCase : Any = feat_extract.pad(SCREAMING_SNAKE_CASE_ ,padding='longest' ,return_tensors='np' ) _UpperCamelCase : List[Any] = input_a[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(SCREAMING_SNAKE_CASE_ ): feat_extract.pad(SCREAMING_SNAKE_CASE_ ,padding='max_length' )[input_name] _UpperCamelCase : Union[str, Any] = feat_extract.pad( SCREAMING_SNAKE_CASE_ ,padding='max_length' ,max_length=SCREAMING_SNAKE_CASE_ ,return_tensors='np' ) _UpperCamelCase : Dict = input_a[input_name] self.assertFalse(_inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ) ) self.assertTrue(_inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ) ) self.assertTrue(_inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ) ) self.assertTrue(_inputs_are_equal(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) ) self.assertTrue(len(input_a[0] ) == pad_min_length ) self.assertTrue(len(input_a[1] ) == pad_min_length + pad_diff ) self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0] )) ) self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size ) # test padding for `pad_to_multiple_of` for List[int] + numpy _UpperCamelCase : List[str] = feat_extract.pad(SCREAMING_SNAKE_CASE_ ,pad_to_multiple_of=10 ) _UpperCamelCase : Optional[Any] = input_a[input_name] _UpperCamelCase : List[Any] = feat_extract.pad(SCREAMING_SNAKE_CASE_ ,padding='longest' ,pad_to_multiple_of=10 ) _UpperCamelCase : Dict = input_a[input_name] _UpperCamelCase : str = feat_extract.pad( SCREAMING_SNAKE_CASE_ ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=SCREAMING_SNAKE_CASE_ ) _UpperCamelCase : Optional[int] = input_a[input_name] _UpperCamelCase : Any = feat_extract.pad( SCREAMING_SNAKE_CASE_ ,padding='max_length' ,pad_to_multiple_of=10 ,max_length=SCREAMING_SNAKE_CASE_ ,return_tensors='np' ,) _UpperCamelCase : List[str] = input_a[input_name] self.assertTrue(all(len(SCREAMING_SNAKE_CASE_ ) % 10 == 0 for x in input_a ) ) self.assertTrue(_inputs_are_equal(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) ) _UpperCamelCase : int = pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 self.assertTrue(all(len(SCREAMING_SNAKE_CASE_ ) == expected_mult_pad_length for x in input_a ) ) self.assertEqual(input_a.shape[:2] ,(batch_size, expected_mult_pad_length) ) if feature_size > 1: self.assertTrue(input_a.shape[2] == feature_size ) # Check padding value is correct _UpperCamelCase : List[Any] = (np.ones(self.feat_extract_tester.feature_size ) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_a[0] )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1E-3 ) self.assertTrue( abs( np.asarray(input_a[1] )[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1E-3 ) self.assertTrue( abs( np.asarray(input_a[2] )[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1E-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1E-3 ) self.assertTrue( abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length) ) < 1E-3 ) def UpperCamelCase_ ( self : Optional[Any] ,lowerCamelCase__ : Tuple=False ): '''simple docstring''' def _inputs_have_equal_length(lowerCamelCase__ : Union[str, Any] ): _UpperCamelCase : List[str] = len(input[0] ) for input_slice in input[1:]: if len(SCREAMING_SNAKE_CASE_ ) != length: return False return True def _inputs_are_equal(lowerCamelCase__ : List[Any] ,lowerCamelCase__ : int ): if len(SCREAMING_SNAKE_CASE_ ) != len(SCREAMING_SNAKE_CASE_ ): return False for input_slice_a, input_slice_a in zip(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ): if not np.allclose(np.asarray(SCREAMING_SNAKE_CASE_ ) ,np.asarray(SCREAMING_SNAKE_CASE_ ) ,atol=1E-3 ): return False return True _UpperCamelCase : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_dict ) _UpperCamelCase : Union[str, Any] = self.feat_extract_tester.prepare_inputs_for_common(numpify=SCREAMING_SNAKE_CASE_ ) _UpperCamelCase : Tuple = feat_extract.model_input_names[0] _UpperCamelCase : Any = BatchFeature({input_name: speech_inputs} ) # truncate to smallest _UpperCamelCase : int = feat_extract.pad( SCREAMING_SNAKE_CASE_ ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,truncation=SCREAMING_SNAKE_CASE_ ) _UpperCamelCase : Dict = input_a[input_name] _UpperCamelCase : Optional[Any] = feat_extract.pad(SCREAMING_SNAKE_CASE_ ,padding='max_length' ,max_length=len(speech_inputs[0] ) ) _UpperCamelCase : List[str] = input_a[input_name] self.assertTrue(_inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ) ) self.assertFalse(_inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ) ) # truncate to smallest with np _UpperCamelCase : Dict = feat_extract.pad( SCREAMING_SNAKE_CASE_ ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ,truncation=SCREAMING_SNAKE_CASE_ ,) _UpperCamelCase : Any = input_a[input_name] _UpperCamelCase : List[Any] = feat_extract.pad( SCREAMING_SNAKE_CASE_ ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,return_tensors='np' ) _UpperCamelCase : List[Any] = input_a[input_name] self.assertTrue(_inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ) ) self.assertTrue(input_a.shape[1] == len(speech_inputs[0] ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ) ) # truncate to middle _UpperCamelCase : str = feat_extract.pad( SCREAMING_SNAKE_CASE_ ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=SCREAMING_SNAKE_CASE_ ,return_tensors='np' ,) _UpperCamelCase : int = input_a[input_name] _UpperCamelCase : Tuple = feat_extract.pad( SCREAMING_SNAKE_CASE_ ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,truncation=SCREAMING_SNAKE_CASE_ ) _UpperCamelCase : Optional[Any] = input_a[input_name] _UpperCamelCase : Any = feat_extract.pad( SCREAMING_SNAKE_CASE_ ,padding='max_length' ,max_length=len(speech_inputs[1] ) ,return_tensors='np' ) _UpperCamelCase : Any = input_a[input_name] self.assertTrue(input_a.shape[1] == len(speech_inputs[1] ) ) self.assertTrue(_inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ) ) self.assertTrue(_inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ) ) self.assertTrue(_inputs_are_equal(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ) ) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ) ) self.assertTrue(len(input_a[-1] ) == len(speech_inputs[-1] ) ) # padding has to be max_length when setting `truncation=True` with self.assertRaises(SCREAMING_SNAKE_CASE_ ): feat_extract.pad(SCREAMING_SNAKE_CASE_ ,truncation=SCREAMING_SNAKE_CASE_ )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(SCREAMING_SNAKE_CASE_ ): feat_extract.pad(SCREAMING_SNAKE_CASE_ ,padding='longest' ,truncation=SCREAMING_SNAKE_CASE_ )[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(SCREAMING_SNAKE_CASE_ ): feat_extract.pad(SCREAMING_SNAKE_CASE_ ,padding='longest' ,truncation=SCREAMING_SNAKE_CASE_ )[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(SCREAMING_SNAKE_CASE_ ): feat_extract.pad(SCREAMING_SNAKE_CASE_ ,padding='max_length' ,truncation=SCREAMING_SNAKE_CASE_ )[input_name] # test truncation for `pad_to_multiple_of` for List[int] + numpy _UpperCamelCase : Any = 12 _UpperCamelCase : Tuple = feat_extract.pad( SCREAMING_SNAKE_CASE_ ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=SCREAMING_SNAKE_CASE_ ,truncation=SCREAMING_SNAKE_CASE_ ,) _UpperCamelCase : Tuple = input_a[input_name] _UpperCamelCase : List[Any] = feat_extract.pad( SCREAMING_SNAKE_CASE_ ,padding='max_length' ,max_length=len(speech_inputs[0] ) ,pad_to_multiple_of=SCREAMING_SNAKE_CASE_ ,) _UpperCamelCase : Optional[int] = input_a[input_name] # retrieve expected_length as multiple of pad_to_multiple_of _UpperCamelCase : int = len(speech_inputs[0] ) if expected_length % pad_to_multiple_of != 0: _UpperCamelCase : Any = ((len(speech_inputs[0] ) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_a[0] ) == expected_length ) self.assertTrue(_inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ) ) self.assertFalse(_inputs_have_equal_length(SCREAMING_SNAKE_CASE_ ) ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' self._check_padding(numpify=SCREAMING_SNAKE_CASE_ ) def UpperCamelCase_ ( self : Optional[Any] ): '''simple docstring''' self._check_padding(numpify=SCREAMING_SNAKE_CASE_ ) def UpperCamelCase_ ( self : str ): '''simple docstring''' self._check_truncation(numpify=SCREAMING_SNAKE_CASE_ ) def UpperCamelCase_ ( self : Dict ): '''simple docstring''' self._check_truncation(numpify=SCREAMING_SNAKE_CASE_ ) @require_torch def UpperCamelCase_ ( self : Dict ): '''simple docstring''' _UpperCamelCase : Optional[Any] = self.feature_extraction_class(**self.feat_extract_dict ) _UpperCamelCase : Tuple = self.feat_extract_tester.prepare_inputs_for_common() _UpperCamelCase : Optional[int] = feat_extract.model_input_names[0] _UpperCamelCase : int = BatchFeature({input_name: speech_inputs} ) _UpperCamelCase : List[str] = feat_extract.pad(SCREAMING_SNAKE_CASE_ ,padding='longest' ,return_tensors='np' )[input_name] _UpperCamelCase : str = feat_extract.pad(SCREAMING_SNAKE_CASE_ ,padding='longest' ,return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1E-2 ) @require_tf def UpperCamelCase_ ( self : int ): '''simple docstring''' _UpperCamelCase : Optional[Any] = self.feature_extraction_class(**self.feat_extract_dict ) _UpperCamelCase : int = self.feat_extract_tester.prepare_inputs_for_common() _UpperCamelCase : Any = feat_extract.model_input_names[0] _UpperCamelCase : Any = BatchFeature({input_name: speech_inputs} ) _UpperCamelCase : Union[str, Any] = feat_extract.pad(SCREAMING_SNAKE_CASE_ ,padding='longest' ,return_tensors='np' )[input_name] _UpperCamelCase : Optional[int] = feat_extract.pad(SCREAMING_SNAKE_CASE_ ,padding='longest' ,return_tensors='tf' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_tf.numpy().astype(np.floataa ).sum() ) < 1E-2 ) def UpperCamelCase_ ( self : Tuple ): '''simple docstring''' _UpperCamelCase : List[str] = self.feat_extract_dict _UpperCamelCase : Dict = True _UpperCamelCase : Optional[Any] = self.feature_extraction_class(**SCREAMING_SNAKE_CASE_ ) _UpperCamelCase : List[str] = self.feat_extract_tester.prepare_inputs_for_common() _UpperCamelCase : Dict = [len(SCREAMING_SNAKE_CASE_ ) for x in speech_inputs] _UpperCamelCase : List[str] = feat_extract.model_input_names[0] _UpperCamelCase : int = BatchFeature({input_name: speech_inputs} ) _UpperCamelCase : List[str] = feat_extract.pad(SCREAMING_SNAKE_CASE_ ,padding='longest' ,return_tensors='np' ) self.assertIn('attention_mask' ,SCREAMING_SNAKE_CASE_ ) self.assertListEqual(list(processed.attention_mask.shape ) ,list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() ,SCREAMING_SNAKE_CASE_ ) def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' _UpperCamelCase : Dict = self.feat_extract_dict _UpperCamelCase : Tuple = True _UpperCamelCase : List[Any] = self.feature_extraction_class(**SCREAMING_SNAKE_CASE_ ) _UpperCamelCase : Tuple = self.feat_extract_tester.prepare_inputs_for_common() _UpperCamelCase : Any = [len(SCREAMING_SNAKE_CASE_ ) for x in speech_inputs] _UpperCamelCase : Optional[int] = feat_extract.model_input_names[0] _UpperCamelCase : Union[str, Any] = BatchFeature({input_name: speech_inputs} ) _UpperCamelCase : Optional[Any] = min(SCREAMING_SNAKE_CASE_ ) _UpperCamelCase : int = feat_extract.pad( SCREAMING_SNAKE_CASE_ ,padding='max_length' ,max_length=SCREAMING_SNAKE_CASE_ ,truncation=SCREAMING_SNAKE_CASE_ ,return_tensors='np' ) self.assertIn('attention_mask' ,SCREAMING_SNAKE_CASE_ ) self.assertListEqual( list(processed_pad.attention_mask.shape ) ,[processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() ,[max_length for x in speech_inputs] )
83
import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class UpperCAmelCase_ ( lowercase, unittest.TestCase ): """simple docstring""" UpperCamelCase_ : int =DDIMPipeline UpperCamelCase_ : str =UNCONDITIONAL_IMAGE_GENERATION_PARAMS UpperCamelCase_ : str =PipelineTesterMixin.required_optional_params - { 'num_images_per_prompt', 'latents', 'callback', 'callback_steps', } UpperCamelCase_ : Optional[Any] =UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS UpperCamelCase_ : List[str] =False def UpperCAmelCase ( self ) -> Any: torch.manual_seed(0 ) UpperCamelCase :Optional[int] = 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''') , ) UpperCamelCase :Dict = DDIMScheduler() UpperCamelCase :Any = {'''unet''': unet, '''scheduler''': scheduler} return components def UpperCAmelCase ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=0 ) -> Any: if str(SCREAMING_SNAKE_CASE_ ).startswith('''mps''' ): UpperCamelCase :List[Any] = torch.manual_seed(SCREAMING_SNAKE_CASE_ ) else: UpperCamelCase :List[Any] = torch.Generator(device=SCREAMING_SNAKE_CASE_ ).manual_seed(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = { '''batch_size''': 1, '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def UpperCAmelCase ( self ) -> Dict: UpperCamelCase :Optional[int] = '''cpu''' UpperCamelCase :Union[str, Any] = self.get_dummy_components() UpperCamelCase :Optional[Any] = self.pipeline_class(**SCREAMING_SNAKE_CASE_ ) pipe.to(SCREAMING_SNAKE_CASE_ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Union[str, Any] = pipe(**SCREAMING_SNAKE_CASE_ ).images UpperCamelCase :str = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) UpperCamelCase :Tuple = np.array( [1.000e00, 5.717e-01, 4.717e-01, 1.000e00, 0.000e00, 1.000e00, 3.000e-04, 0.000e00, 9.000e-04] ) UpperCamelCase :List[str] = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE_ , 1e-3 ) def UpperCAmelCase ( self ) -> int: super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 ) def UpperCAmelCase ( self ) -> Optional[int]: super().test_save_load_local(expected_max_difference=3e-3 ) def UpperCAmelCase ( self ) -> Any: super().test_save_load_optional_components(expected_max_difference=3e-3 ) def UpperCAmelCase ( self ) -> str: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class UpperCAmelCase_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase ( self ) -> Union[str, Any]: UpperCamelCase :int = '''google/ddpm-cifar10-32''' UpperCamelCase :Union[str, Any] = UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = DDIMScheduler() UpperCamelCase :Tuple = DDIMPipeline(unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) ddim.to(SCREAMING_SNAKE_CASE_ ) ddim.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Dict = torch.manual_seed(0 ) UpperCamelCase :Optional[int] = ddim(generator=SCREAMING_SNAKE_CASE_ , eta=0.0 , output_type='''numpy''' ).images UpperCamelCase :int = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCamelCase :Tuple = np.array([0.1723, 0.1617, 0.1600, 0.1626, 0.1497, 0.1513, 0.1505, 0.1442, 0.1453] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 def UpperCAmelCase ( self ) -> int: UpperCamelCase :Optional[Any] = '''google/ddpm-ema-bedroom-256''' UpperCamelCase :Any = UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :int = DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = DDIMPipeline(unet=SCREAMING_SNAKE_CASE_ , scheduler=SCREAMING_SNAKE_CASE_ ) ddpm.to(SCREAMING_SNAKE_CASE_ ) ddpm.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_ ) UpperCamelCase :Optional[int] = torch.manual_seed(0 ) UpperCamelCase :Optional[int] = ddpm(generator=SCREAMING_SNAKE_CASE_ , output_type='''numpy''' ).images UpperCamelCase :Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) UpperCamelCase :Dict = np.array([0.0060, 0.0201, 0.0344, 0.0024, 0.0018, 0.0002, 0.0022, 0.0000, 0.0069] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
259
0
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DeformableDetrImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): def __init__( self : Dict , snake_case__ : Tuple , snake_case__ : List[str]=7 , snake_case__ : List[str]=3 , snake_case__ : List[str]=3_0 , snake_case__ : Any=4_0_0 , snake_case__ : str=True , snake_case__ : Optional[int]=None , snake_case__ : Union[str, Any]=True , snake_case__ : List[Any]=[0.5, 0.5, 0.5] , snake_case__ : List[str]=[0.5, 0.5, 0.5] , snake_case__ : int=True , snake_case__ : Optional[Any]=1 / 2_5_5 , snake_case__ : Optional[Any]=True , ): '''simple docstring''' # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p UpperCAmelCase__ : Optional[int] = size if size is not None else {"shortest_edge": 1_8, "longest_edge": 1_3_3_3} UpperCAmelCase__ : Union[str, Any] = parent UpperCAmelCase__ : str = batch_size UpperCAmelCase__ : Tuple = num_channels UpperCAmelCase__ : str = min_resolution UpperCAmelCase__ : Union[str, Any] = max_resolution UpperCAmelCase__ : Optional[Any] = do_resize UpperCAmelCase__ : Union[str, Any] = size UpperCAmelCase__ : List[str] = do_normalize UpperCAmelCase__ : List[Any] = image_mean UpperCAmelCase__ : List[Any] = image_std UpperCAmelCase__ : List[str] = do_rescale UpperCAmelCase__ : Dict = rescale_factor UpperCAmelCase__ : Dict = do_pad def __a ( self : Tuple ): '''simple docstring''' return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def __a ( self : Optional[Any] , snake_case__ : Optional[int] , snake_case__ : List[Any]=False ): '''simple docstring''' if not batched: UpperCAmelCase__ : int = image_inputs[0] if isinstance(snake_case__ , Image.Image ): UpperCAmelCase__ , UpperCAmelCase__ : List[Any] = image.size else: UpperCAmelCase__ , UpperCAmelCase__ : Optional[Any] = image.shape[1], image.shape[2] if w < h: UpperCAmelCase__ : Optional[Any] = int(self.size["shortest_edge"] * h / w ) UpperCAmelCase__ : Tuple = self.size["shortest_edge"] elif w > h: UpperCAmelCase__ : Optional[int] = self.size["shortest_edge"] UpperCAmelCase__ : Any = int(self.size["shortest_edge"] * w / h ) else: UpperCAmelCase__ : Union[str, Any] = self.size["shortest_edge"] UpperCAmelCase__ : Tuple = self.size["shortest_edge"] else: UpperCAmelCase__ : List[str] = [] for image in image_inputs: UpperCAmelCase__ , UpperCAmelCase__ : Any = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) UpperCAmelCase__ : str = max(snake_case__ , key=lambda snake_case__ : item[0] )[0] UpperCAmelCase__ : List[str] = max(snake_case__ , key=lambda snake_case__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class lowerCAmelCase__ ( __magic_name__ , unittest.TestCase ): SCREAMING_SNAKE_CASE_ =DeformableDetrImageProcessor if is_vision_available() else None def __a ( self : Union[str, Any] ): '''simple docstring''' UpperCAmelCase__ : str = DeformableDetrImageProcessingTester(self ) @property def __a ( self : List[str] ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def __a ( self : List[str] ): '''simple docstring''' UpperCAmelCase__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(snake_case__ , "image_mean" ) ) self.assertTrue(hasattr(snake_case__ , "image_std" ) ) self.assertTrue(hasattr(snake_case__ , "do_normalize" ) ) self.assertTrue(hasattr(snake_case__ , "do_resize" ) ) self.assertTrue(hasattr(snake_case__ , "do_rescale" ) ) self.assertTrue(hasattr(snake_case__ , "do_pad" ) ) self.assertTrue(hasattr(snake_case__ , "size" ) ) def __a ( self : Optional[Any] ): '''simple docstring''' UpperCAmelCase__ : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 1_8, "longest_edge": 1_3_3_3} ) self.assertEqual(image_processor.do_pad , snake_case__ ) UpperCAmelCase__ : Optional[Any] = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=snake_case__ ) self.assertEqual(image_processor.size , {"shortest_edge": 4_2, "longest_edge": 8_4} ) self.assertEqual(image_processor.do_pad , snake_case__ ) def __a ( self : List[str] ): '''simple docstring''' pass def __a ( self : Dict ): '''simple docstring''' # Initialize image_processing UpperCAmelCase__ : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCAmelCase__ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case__ ) for image in image_inputs: self.assertIsInstance(snake_case__ , Image.Image ) # Test not batched input UpperCAmelCase__ : Any = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values UpperCAmelCase__ , UpperCAmelCase__ : Tuple = self.image_processor_tester.get_expected_values(snake_case__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCAmelCase__ , UpperCAmelCase__ : List[str] = self.image_processor_tester.get_expected_values(snake_case__ , batched=snake_case__ ) UpperCAmelCase__ : Tuple = image_processing(snake_case__ , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __a ( self : Optional[int] ): '''simple docstring''' # Initialize image_processing UpperCAmelCase__ : Any = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCAmelCase__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case__ , numpify=snake_case__ ) for image in image_inputs: self.assertIsInstance(snake_case__ , np.ndarray ) # Test not batched input UpperCAmelCase__ : Any = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values UpperCAmelCase__ , UpperCAmelCase__ : Any = self.image_processor_tester.get_expected_values(snake_case__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCAmelCase__ : str = image_processing(snake_case__ , return_tensors="pt" ).pixel_values UpperCAmelCase__ , UpperCAmelCase__ : Optional[int] = self.image_processor_tester.get_expected_values(snake_case__ , batched=snake_case__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __a ( self : Union[str, Any] ): '''simple docstring''' # Initialize image_processing UpperCAmelCase__ : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCAmelCase__ : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=snake_case__ , torchify=snake_case__ ) for image in image_inputs: self.assertIsInstance(snake_case__ , torch.Tensor ) # Test not batched input UpperCAmelCase__ : int = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values UpperCAmelCase__ , UpperCAmelCase__ : Union[str, Any] = self.image_processor_tester.get_expected_values(snake_case__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCAmelCase__ : List[str] = image_processing(snake_case__ , return_tensors="pt" ).pixel_values UpperCAmelCase__ , UpperCAmelCase__ : Tuple = self.image_processor_tester.get_expected_values(snake_case__ , batched=snake_case__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def __a ( self : List[Any] ): '''simple docstring''' # prepare image and target UpperCAmelCase__ : Tuple = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt" , "r" ) as f: UpperCAmelCase__ : Optional[Any] = json.loads(f.read() ) UpperCAmelCase__ : Optional[Any] = {"image_id": 3_9_7_6_9, "annotations": target} # encode them UpperCAmelCase__ : Optional[Any] = DeformableDetrImageProcessor() UpperCAmelCase__ : Tuple = image_processing(images=snake_case__ , annotations=snake_case__ , return_tensors="pt" ) # verify pixel values UpperCAmelCase__ : Tuple = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding["pixel_values"].shape , snake_case__ ) UpperCAmelCase__ : Tuple = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , snake_case__ , atol=1e-4 ) ) # verify area UpperCAmelCase__ : List[Any] = 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"] , snake_case__ ) ) # verify boxes UpperCAmelCase__ : Union[str, Any] = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , snake_case__ ) UpperCAmelCase__ : Union[str, Any] = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , snake_case__ , atol=1e-3 ) ) # verify image_id UpperCAmelCase__ : Union[str, Any] = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , snake_case__ ) ) # verify is_crowd UpperCAmelCase__ : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , snake_case__ ) ) # verify class_labels UpperCAmelCase__ : Union[str, Any] = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , snake_case__ ) ) # verify orig_size UpperCAmelCase__ : Tuple = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , snake_case__ ) ) # verify size UpperCAmelCase__ : Tuple = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , snake_case__ ) ) @slow def __a ( self : Optional[Any] ): '''simple docstring''' # prepare image, target and masks_path UpperCAmelCase__ : Tuple = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt" , "r" ) as f: UpperCAmelCase__ : List[str] = json.loads(f.read() ) UpperCAmelCase__ : Tuple = {"file_name": "000000039769.png", "image_id": 3_9_7_6_9, "segments_info": target} UpperCAmelCase__ : int = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic" ) # encode them UpperCAmelCase__ : List[str] = DeformableDetrImageProcessor(format="coco_panoptic" ) UpperCAmelCase__ : List[Any] = image_processing(images=snake_case__ , annotations=snake_case__ , masks_path=snake_case__ , return_tensors="pt" ) # verify pixel values UpperCAmelCase__ : int = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding["pixel_values"].shape , snake_case__ ) UpperCAmelCase__ : List[Any] = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3] , snake_case__ , atol=1e-4 ) ) # verify area UpperCAmelCase__ : Optional[int] = 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"] , snake_case__ ) ) # verify boxes UpperCAmelCase__ : int = torch.Size([6, 4] ) self.assertEqual(encoding["labels"][0]["boxes"].shape , snake_case__ ) UpperCAmelCase__ : Dict = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0] , snake_case__ , atol=1e-3 ) ) # verify image_id UpperCAmelCase__ : str = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"] , snake_case__ ) ) # verify is_crowd UpperCAmelCase__ : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"] , snake_case__ ) ) # verify class_labels UpperCAmelCase__ : List[str] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"] , snake_case__ ) ) # verify masks UpperCAmelCase__ : List[Any] = 8_2_2_8_7_3 self.assertEqual(encoding["labels"][0]["masks"].sum().item() , snake_case__ ) # verify orig_size UpperCAmelCase__ : str = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"] , snake_case__ ) ) # verify size UpperCAmelCase__ : Optional[Any] = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding["labels"][0]["size"] , snake_case__ ) )
298
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available _lowerCAmelCase : Tuple = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCAmelCase : Dict = ["""MLukeTokenizer"""] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mluke import MLukeTokenizer else: import sys _lowerCAmelCase : List[str] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
298
1
from collections import defaultdict from typing import Optional from ..image_utils import load_image from ..utils import ( add_end_docstrings, is_torch_available, logging, requires_backends, ) from .base import PIPELINE_INIT_ARGS, ChunkPipeline if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING __snake_case :List[Any] = logging.get_logger(__name__) @add_end_docstrings(__UpperCAmelCase ) class _A ( __UpperCAmelCase ): def __init__( self : Dict , **__SCREAMING_SNAKE_CASE : Tuple): '''simple docstring''' super().__init__(**__SCREAMING_SNAKE_CASE) requires_backends(self , '''vision''') requires_backends(self , '''torch''') if self.framework != "pt": raise ValueError(F'The {self.__class__} is only available in PyTorch.') self.check_model_type(__SCREAMING_SNAKE_CASE) def _lowerCamelCase ( self : Any , **__SCREAMING_SNAKE_CASE : Any): '''simple docstring''' __a = {} __a = {} __a = {} # preprocess args if "points_per_batch" in kwargs: __a = kwargs['''points_per_batch'''] if "points_per_crop" in kwargs: __a = kwargs['''points_per_crop'''] if "crops_n_layers" in kwargs: __a = kwargs['''crops_n_layers'''] if "crop_overlap_ratio" in kwargs: __a = kwargs['''crop_overlap_ratio'''] if "crop_n_points_downscale_factor" in kwargs: __a = kwargs['''crop_n_points_downscale_factor'''] # postprocess args if "pred_iou_thresh" in kwargs: __a = kwargs['''pred_iou_thresh'''] if "stability_score_offset" in kwargs: __a = kwargs['''stability_score_offset'''] if "mask_threshold" in kwargs: __a = kwargs['''mask_threshold'''] if "stability_score_thresh" in kwargs: __a = kwargs['''stability_score_thresh'''] if "crops_nms_thresh" in kwargs: __a = kwargs['''crops_nms_thresh'''] if "output_rle_mask" in kwargs: __a = kwargs['''output_rle_mask'''] if "output_bboxes_mask" in kwargs: __a = kwargs['''output_bboxes_mask'''] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self : Union[str, Any] , __SCREAMING_SNAKE_CASE : int , *__SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : Tuple=None , __SCREAMING_SNAKE_CASE : Any=None , **__SCREAMING_SNAKE_CASE : str): '''simple docstring''' return super().__call__(__SCREAMING_SNAKE_CASE , *__SCREAMING_SNAKE_CASE , num_workers=__SCREAMING_SNAKE_CASE , batch_size=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE) def _lowerCamelCase ( self : Dict , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : Any=64 , __SCREAMING_SNAKE_CASE : int = 0 , __SCREAMING_SNAKE_CASE : float = 512 / 1_500 , __SCREAMING_SNAKE_CASE : Optional[int] = 32 , __SCREAMING_SNAKE_CASE : Optional[int] = 1 , ): '''simple docstring''' __a = load_image(__SCREAMING_SNAKE_CASE) __a = self.image_processor.size['''longest_edge'''] __a , __a , __a , __a = self.image_processor.generate_crop_boxes( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) __a = self.image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors='''pt''') with self.device_placement(): if self.framework == "pt": __a = self.get_inference_context() with inference_context(): __a = self._ensure_tensor_on_device(__SCREAMING_SNAKE_CASE , device=self.device) __a = self.model.get_image_embeddings(model_inputs.pop('''pixel_values''')) __a = image_embeddings __a = grid_points.shape[1] __a = points_per_batch if points_per_batch is not None else n_points if points_per_batch <= 0: raise ValueError( '''Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. ''' '''To return all points at once, set points_per_batch to None''') for i in range(0 , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE): __a = grid_points[:, i : i + points_per_batch, :, :] __a = input_labels[:, i : i + points_per_batch] __a = i == n_points - points_per_batch yield { "input_points": batched_points, "input_labels": labels, "input_boxes": crop_boxes, "is_last": is_last, **model_inputs, } def _lowerCamelCase ( self : Any , __SCREAMING_SNAKE_CASE : Optional[Any] , __SCREAMING_SNAKE_CASE : int=0.88 , __SCREAMING_SNAKE_CASE : List[Any]=0.95 , __SCREAMING_SNAKE_CASE : List[Any]=0 , __SCREAMING_SNAKE_CASE : int=1 , ): '''simple docstring''' __a = model_inputs.pop('''input_boxes''') __a = model_inputs.pop('''is_last''') __a = model_inputs.pop('''original_sizes''').tolist() __a = model_inputs.pop('''reshaped_input_sizes''').tolist() __a = self.model(**__SCREAMING_SNAKE_CASE) # post processing happens here in order to avoid CPU GPU copies of ALL the masks __a = model_outputs['''pred_masks'''] __a = self.image_processor.post_process_masks( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , binarize=__SCREAMING_SNAKE_CASE) __a = model_outputs['''iou_scores'''] __a , __a , __a = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def _lowerCamelCase ( self : int , __SCREAMING_SNAKE_CASE : Dict , __SCREAMING_SNAKE_CASE : Dict=False , __SCREAMING_SNAKE_CASE : Tuple=False , __SCREAMING_SNAKE_CASE : int=0.7 , ): '''simple docstring''' __a = [] __a = [] __a = [] for model_output in model_outputs: all_scores.append(model_output.pop('''iou_scores''')) all_masks.extend(model_output.pop('''masks''')) all_boxes.append(model_output.pop('''boxes''')) __a = torch.cat(__SCREAMING_SNAKE_CASE) __a = torch.cat(__SCREAMING_SNAKE_CASE) __a , __a , __a , __a = self.image_processor.post_process_for_mask_generation( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) __a = defaultdict(__SCREAMING_SNAKE_CASE) for output in model_outputs: for k, v in output.items(): extra[k].append(__SCREAMING_SNAKE_CASE) __a = {} if output_rle_mask: __a = rle_mask if output_bboxes_mask: __a = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
49
import logging from transformers.configuration_utils import PretrainedConfig __snake_case :Any = logging.getLogger(__name__) class _A ( __UpperCAmelCase ): UpperCamelCase__ : Optional[Any] = '''masked_bert''' def __init__( self : str , __SCREAMING_SNAKE_CASE : int=30_522 , __SCREAMING_SNAKE_CASE : str=768 , __SCREAMING_SNAKE_CASE : List[str]=12 , __SCREAMING_SNAKE_CASE : Any=12 , __SCREAMING_SNAKE_CASE : Union[str, Any]=3_072 , __SCREAMING_SNAKE_CASE : List[Any]="gelu" , __SCREAMING_SNAKE_CASE : int=0.1 , __SCREAMING_SNAKE_CASE : Dict=0.1 , __SCREAMING_SNAKE_CASE : Optional[Any]=512 , __SCREAMING_SNAKE_CASE : Optional[int]=2 , __SCREAMING_SNAKE_CASE : Dict=0.02 , __SCREAMING_SNAKE_CASE : List[Any]=1E-12 , __SCREAMING_SNAKE_CASE : Union[str, Any]=0 , __SCREAMING_SNAKE_CASE : List[str]="topK" , __SCREAMING_SNAKE_CASE : List[Any]="constant" , __SCREAMING_SNAKE_CASE : int=0.0 , **__SCREAMING_SNAKE_CASE : List[Any] , ): '''simple docstring''' super().__init__(pad_token_id=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE) __a = vocab_size __a = hidden_size __a = num_hidden_layers __a = num_attention_heads __a = hidden_act __a = intermediate_size __a = hidden_dropout_prob __a = attention_probs_dropout_prob __a = max_position_embeddings __a = type_vocab_size __a = initializer_range __a = layer_norm_eps __a = pruning_method __a = mask_init __a = mask_scale
49
1
'''simple docstring''' import unittest from transformers import DebertaVaTokenizer, DebertaVaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin _SCREAMING_SNAKE_CASE : str = get_tests_dir("fixtures/spiece.model") @require_sentencepiece @require_tokenizers class _snake_case ( lowercase_ , unittest.TestCase ): lowerCAmelCase_ : int = DebertaVaTokenizer lowerCAmelCase_ : Optional[int] = DebertaVaTokenizerFast lowerCAmelCase_ : Any = True lowerCAmelCase_ : Optional[int] = True def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing snake_case_ = DebertaVaTokenizer(a__ , unk_token="<unk>" ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCAmelCase__ ( self , a__ ) -> Any: '''simple docstring''' snake_case_ = "this is a test" snake_case_ = "this is a test" return input_text, output_text def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = "<pad>" snake_case_ = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a__ ) , a__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a__ ) , a__ ) def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' snake_case_ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<pad>" ) self.assertEqual(vocab_keys[1] , "<unk>" ) self.assertEqual(vocab_keys[-1] , "[PAD]" ) self.assertEqual(len(a__ ) , 30_001 ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 30_000 ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = " \tHeLLo!how \n Are yoU? " snake_case_ = ["▁hello", "!", "how", "▁are", "▁you", "?"] # fmt: on snake_case_ = DebertaVaTokenizer(a__ , do_lower_case=a__ ) snake_case_ = tokenizer.convert_ids_to_tokens(tokenizer.encode(a__ , add_special_tokens=a__ ) ) self.assertListEqual(a__ , a__ ) snake_case_ = DebertaVaTokenizerFast(a__ , do_lower_case=a__ ) snake_case_ = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(a__ , add_special_tokens=a__ ) ) self.assertListEqual(a__ , a__ ) @unittest.skip("There is an inconsistency between slow and fast tokenizer due to a bug in the fast one." ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' pass @unittest.skip("There is an inconsistency between slow and fast tokenizer due to a bug in the fast one." ) def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' pass def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = "I was born in 92000, and this is falsé." snake_case_ = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on snake_case_ = DebertaVaTokenizer(a__ , split_by_punct=a__ ) snake_case_ = tokenizer.convert_ids_to_tokens(tokenizer.encode(a__ , add_special_tokens=a__ ) ) self.assertListEqual(a__ , a__ ) snake_case_ = DebertaVaTokenizerFast(a__ , split_by_punct=a__ ) snake_case_ = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(a__ , add_special_tokens=a__ ) ) self.assertListEqual(a__ , a__ ) def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ = "I was born in 92000, and this is falsé." snake_case_ = ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on snake_case_ = DebertaVaTokenizer(a__ , do_lower_case=a__ , split_by_punct=a__ ) snake_case_ = tokenizer.convert_ids_to_tokens(tokenizer.encode(a__ , add_special_tokens=a__ ) ) self.assertListEqual(a__ , a__ ) snake_case_ = DebertaVaTokenizerFast(a__ , do_lower_case=a__ , split_by_punct=a__ ) snake_case_ = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(a__ , add_special_tokens=a__ ) ) self.assertListEqual(a__ , a__ ) def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' snake_case_ = "I was born in 92000, and this is falsé." snake_case_ = ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", ".", ] # fmt: on snake_case_ = DebertaVaTokenizer(a__ , do_lower_case=a__ , split_by_punct=a__ ) snake_case_ = tokenizer.convert_ids_to_tokens(tokenizer.encode(a__ , add_special_tokens=a__ ) ) self.assertListEqual(a__ , a__ ) snake_case_ = DebertaVaTokenizerFast(a__ , do_lower_case=a__ , split_by_punct=a__ ) snake_case_ = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(a__ , add_special_tokens=a__ ) ) self.assertListEqual(a__ , a__ ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = "I was born in 92000, and this is falsé." snake_case_ = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", ".", ] # fmt: on snake_case_ = DebertaVaTokenizer(a__ , do_lower_case=a__ , split_by_punct=a__ ) snake_case_ = tokenizer.convert_ids_to_tokens(tokenizer.encode(a__ , add_special_tokens=a__ ) ) self.assertListEqual(a__ , a__ ) snake_case_ = DebertaVaTokenizerFast(a__ , do_lower_case=a__ , split_by_punct=a__ ) snake_case_ = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(a__ , add_special_tokens=a__ ) ) self.assertListEqual(a__ , a__ ) def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ = " \tHeLLo!how \n Are yoU? " snake_case_ = ["▁", "<unk>", "e", "<unk>", "o", "!", "how", "▁", "<unk>", "re", "▁yo", "<unk>", "?"] # fmt: on snake_case_ = DebertaVaTokenizer(a__ , do_lower_case=a__ , split_by_punct=a__ ) snake_case_ = tokenizer.convert_ids_to_tokens(tokenizer.encode(a__ , add_special_tokens=a__ ) ) self.assertListEqual(a__ , a__ ) snake_case_ = DebertaVaTokenizerFast(a__ , do_lower_case=a__ , split_by_punct=a__ ) snake_case_ = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(a__ , add_special_tokens=a__ ) ) self.assertListEqual(a__ , a__ ) def lowerCAmelCase__ ( self ) -> str: '''simple docstring''' snake_case_ = self.get_tokenizer() snake_case_ = self.get_rust_tokenizer() snake_case_ = "I was born in 92000, and this is falsé." snake_case_ = tokenizer.convert_ids_to_tokens(tokenizer.encode(a__ , add_special_tokens=a__ ) ) snake_case_ = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(a__ , add_special_tokens=a__ ) ) self.assertListEqual(a__ , a__ ) snake_case_ = tokenizer.encode(a__ , add_special_tokens=a__ ) snake_case_ = rust_tokenizer.encode(a__ , add_special_tokens=a__ ) self.assertListEqual(a__ , a__ ) snake_case_ = self.get_rust_tokenizer() snake_case_ = tokenizer.encode(a__ ) snake_case_ = rust_tokenizer.encode(a__ ) self.assertListEqual(a__ , a__ ) def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ = "This is a test" snake_case_ = [13, 1, 4_398, 25, 21, 1_289] snake_case_ = ["▁", "T", "his", "▁is", "▁a", "▁test"] snake_case_ = ["▁", "<unk>", "his", "▁is", "▁a", "▁test"] snake_case_ = DebertaVaTokenizer(a__ , keep_accents=a__ ) snake_case_ = DebertaVaTokenizerFast(a__ , keep_accents=a__ ) snake_case_ = tokenizer.encode(a__ , add_special_tokens=a__ ) self.assertListEqual(a__ , a__ ) snake_case_ = tokenizer.tokenize(a__ ) self.assertListEqual(a__ , a__ ) snake_case_ = tokenizer.convert_ids_to_tokens(a__ ) self.assertListEqual(a__ , a__ ) snake_case_ = rust_tokenizer.encode(a__ , add_special_tokens=a__ ) self.assertListEqual(a__ , a__ ) snake_case_ = rust_tokenizer.tokenize(a__ ) self.assertListEqual(a__ , a__ ) snake_case_ = rust_tokenizer.convert_ids_to_tokens(a__ ) self.assertListEqual(a__ , a__ ) # fmt: off snake_case_ = "I was born in 92000, and this is falsé." snake_case_ = [13, 1, 23, 386, 19, 561, 3_050, 15, 17, 48, 25, 8_256, 18, 1, 9] snake_case_ = ["▁", "I", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "é", ".", ] snake_case_ = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", ".", ] # fmt: on snake_case_ = tokenizer.encode(a__ , add_special_tokens=a__ ) self.assertListEqual(a__ , a__ ) snake_case_ = tokenizer.tokenize(a__ ) self.assertListEqual(a__ , a__ ) snake_case_ = tokenizer.convert_ids_to_tokens(a__ ) self.assertListEqual(a__ , a__ ) snake_case_ = rust_tokenizer.encode(a__ , add_special_tokens=a__ ) self.assertListEqual(a__ , a__ ) snake_case_ = rust_tokenizer.tokenize(a__ ) self.assertListEqual(a__ , a__ ) snake_case_ = rust_tokenizer.convert_ids_to_tokens(a__ ) self.assertListEqual(a__ , a__ ) def lowerCAmelCase__ ( self ) -> List[str]: '''simple docstring''' snake_case_ = DebertaVaTokenizer(a__ ) snake_case_ = tokenizer.encode("sequence builders" ) snake_case_ = tokenizer.encode("multi-sequence build" ) snake_case_ = tokenizer.build_inputs_with_special_tokens(a__ ) snake_case_ = tokenizer.build_inputs_with_special_tokens(a__ , a__ ) self.assertEqual([tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] , a__ ) self.assertEqual( [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [tokenizer.sep_token_id] , a__ , ) @slow def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ = {"input_ids": [[1, 39_867, 36, 19_390, 486, 27, 35_052, 81_436, 18, 60_685, 1_225, 7, 35_052, 81_436, 18, 9_367, 16_899, 18, 15_937, 53, 594, 773, 18, 16_287, 30_465, 36, 15_937, 6, 41_139, 38, 36_979, 60_763, 191, 6, 34_132, 99, 6, 50_538, 390, 43_230, 6, 34_132, 2_779, 20_850, 14, 699, 1_072, 1_194, 36, 382, 10_901, 53, 7, 699, 1_072, 2_084, 36, 20_422, 630, 53, 19, 105, 3_049, 1_896, 1_053, 16_899, 1_506, 11, 37_978, 4_243, 7, 1_237, 31_869, 200, 16_566, 654, 6, 35_052, 81_436, 7, 55_630, 13_593, 4, 2], [1, 26, 15_011, 13, 667, 8, 1_053, 18, 23_611, 1_237, 72_356, 12_820, 34, 104_134, 1_209, 35, 13_313, 6_627, 21, 202, 347, 7, 164, 2_399, 11, 46, 4_485, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 5, 1_232, 2_864, 15_785, 14_951, 105, 5, 8_581, 1_250, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "token_type_ids": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a__ , model_name="microsoft/deberta-v2-xlarge" , revision="ad6e42c1532ddf3a15c39246b63f5559d558b670" , )
353
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging _SCREAMING_SNAKE_CASE : Any = logging.get_logger(__name__) _SCREAMING_SNAKE_CASE : int = { "alibaba-damo/mgp-str-base": "https://huggingface.co/alibaba-damo/mgp-str-base/resolve/main/config.json", } class _snake_case ( lowercase_ ): lowerCAmelCase_ : Union[str, Any] = "mgp-str" def __init__( self , a__=[32, 128] , a__=4 , a__=3 , a__=27 , a__=38 , a__=50_257 , a__=30_522 , a__=768 , a__=12 , a__=12 , a__=4.0 , a__=True , a__=False , a__=1e-5 , a__=0.0 , a__=0.0 , a__=0.0 , a__=False , a__=0.0_2 , **a__ , ) -> Union[str, Any]: '''simple docstring''' super().__init__(**a__ ) snake_case_ = image_size snake_case_ = patch_size snake_case_ = num_channels snake_case_ = max_token_length snake_case_ = num_character_labels snake_case_ = num_bpe_labels snake_case_ = num_wordpiece_labels snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = mlp_ratio snake_case_ = distilled snake_case_ = layer_norm_eps snake_case_ = drop_rate snake_case_ = qkv_bias snake_case_ = attn_drop_rate snake_case_ = drop_path_rate snake_case_ = output_aa_attentions snake_case_ = initializer_range
92
0
'''simple docstring''' import argparse import torch from transformers import ( EncodecConfig, EncodecFeatureExtractor, EncodecModel, logging, ) # checkpoints downloaded from: # https://dl.fbaipublicfiles.com/encodec/v0/encodec_24khz-d7cc33bc.th # https://huggingface.co/facebook/musicgen-small/resolve/main/compression_state_dict.bin # https://dl.fbaipublicfiles.com/encodec/v0/encodec_48khz-7e698e3e.th logging.set_verbosity_info() __lowerCAmelCase = logging.get_logger('''transformers.models.encodec''') __lowerCAmelCase = { '''quantizer.vq.layers.*._codebook.inited''': '''quantizer.layers.*.codebook.inited''', '''quantizer.vq.layers.*._codebook.cluster_size''': '''quantizer.layers.*.codebook.cluster_size''', '''quantizer.vq.layers.*._codebook.embed''': '''quantizer.layers.*.codebook.embed''', '''quantizer.vq.layers.*._codebook.embed_avg''': '''quantizer.layers.*.codebook.embed_avg''', } __lowerCAmelCase = { '''encoder.model.0.conv.conv''': '''encoder.layers.0.conv''', '''encoder.model.1.block.1.conv.conv''': '''encoder.layers.1.block.1.conv''', '''encoder.model.1.block.3.conv.conv''': '''encoder.layers.1.block.3.conv''', '''encoder.model.1.shortcut.conv.conv''': '''encoder.layers.1.shortcut.conv''', '''encoder.model.3.conv.conv''': '''encoder.layers.3.conv''', '''encoder.model.4.block.1.conv.conv''': '''encoder.layers.4.block.1.conv''', '''encoder.model.4.block.3.conv.conv''': '''encoder.layers.4.block.3.conv''', '''encoder.model.4.shortcut.conv.conv''': '''encoder.layers.4.shortcut.conv''', '''encoder.model.6.conv.conv''': '''encoder.layers.6.conv''', '''encoder.model.7.block.1.conv.conv''': '''encoder.layers.7.block.1.conv''', '''encoder.model.7.block.3.conv.conv''': '''encoder.layers.7.block.3.conv''', '''encoder.model.7.shortcut.conv.conv''': '''encoder.layers.7.shortcut.conv''', '''encoder.model.9.conv.conv''': '''encoder.layers.9.conv''', '''encoder.model.10.block.1.conv.conv''': '''encoder.layers.10.block.1.conv''', '''encoder.model.10.block.3.conv.conv''': '''encoder.layers.10.block.3.conv''', '''encoder.model.10.shortcut.conv.conv''': '''encoder.layers.10.shortcut.conv''', '''encoder.model.12.conv.conv''': '''encoder.layers.12.conv''', '''encoder.model.13.lstm''': '''encoder.layers.13.lstm''', '''encoder.model.15.conv.conv''': '''encoder.layers.15.conv''', } __lowerCAmelCase = { '''encoder.model.0.conv.norm''': '''encoder.layers.0.norm''', '''encoder.model.1.block.1.conv.norm''': '''encoder.layers.1.block.1.norm''', '''encoder.model.1.block.3.conv.norm''': '''encoder.layers.1.block.3.norm''', '''encoder.model.1.shortcut.conv.norm''': '''encoder.layers.1.shortcut.norm''', '''encoder.model.3.conv.norm''': '''encoder.layers.3.norm''', '''encoder.model.4.block.1.conv.norm''': '''encoder.layers.4.block.1.norm''', '''encoder.model.4.block.3.conv.norm''': '''encoder.layers.4.block.3.norm''', '''encoder.model.4.shortcut.conv.norm''': '''encoder.layers.4.shortcut.norm''', '''encoder.model.6.conv.norm''': '''encoder.layers.6.norm''', '''encoder.model.7.block.1.conv.norm''': '''encoder.layers.7.block.1.norm''', '''encoder.model.7.block.3.conv.norm''': '''encoder.layers.7.block.3.norm''', '''encoder.model.7.shortcut.conv.norm''': '''encoder.layers.7.shortcut.norm''', '''encoder.model.9.conv.norm''': '''encoder.layers.9.norm''', '''encoder.model.10.block.1.conv.norm''': '''encoder.layers.10.block.1.norm''', '''encoder.model.10.block.3.conv.norm''': '''encoder.layers.10.block.3.norm''', '''encoder.model.10.shortcut.conv.norm''': '''encoder.layers.10.shortcut.norm''', '''encoder.model.12.conv.norm''': '''encoder.layers.12.norm''', '''encoder.model.15.conv.norm''': '''encoder.layers.15.norm''', } __lowerCAmelCase = { '''decoder.model.0.conv.conv''': '''decoder.layers.0.conv''', '''decoder.model.1.lstm''': '''decoder.layers.1.lstm''', '''decoder.model.3.convtr.convtr''': '''decoder.layers.3.conv''', '''decoder.model.4.block.1.conv.conv''': '''decoder.layers.4.block.1.conv''', '''decoder.model.4.block.3.conv.conv''': '''decoder.layers.4.block.3.conv''', '''decoder.model.4.shortcut.conv.conv''': '''decoder.layers.4.shortcut.conv''', '''decoder.model.6.convtr.convtr''': '''decoder.layers.6.conv''', '''decoder.model.7.block.1.conv.conv''': '''decoder.layers.7.block.1.conv''', '''decoder.model.7.block.3.conv.conv''': '''decoder.layers.7.block.3.conv''', '''decoder.model.7.shortcut.conv.conv''': '''decoder.layers.7.shortcut.conv''', '''decoder.model.9.convtr.convtr''': '''decoder.layers.9.conv''', '''decoder.model.10.block.1.conv.conv''': '''decoder.layers.10.block.1.conv''', '''decoder.model.10.block.3.conv.conv''': '''decoder.layers.10.block.3.conv''', '''decoder.model.10.shortcut.conv.conv''': '''decoder.layers.10.shortcut.conv''', '''decoder.model.12.convtr.convtr''': '''decoder.layers.12.conv''', '''decoder.model.13.block.1.conv.conv''': '''decoder.layers.13.block.1.conv''', '''decoder.model.13.block.3.conv.conv''': '''decoder.layers.13.block.3.conv''', '''decoder.model.13.shortcut.conv.conv''': '''decoder.layers.13.shortcut.conv''', '''decoder.model.15.conv.conv''': '''decoder.layers.15.conv''', } __lowerCAmelCase = { '''decoder.model.0.conv.norm''': '''decoder.layers.0.norm''', '''decoder.model.3.convtr.norm''': '''decoder.layers.3.norm''', '''decoder.model.4.block.1.conv.norm''': '''decoder.layers.4.block.1.norm''', '''decoder.model.4.block.3.conv.norm''': '''decoder.layers.4.block.3.norm''', '''decoder.model.4.shortcut.conv.norm''': '''decoder.layers.4.shortcut.norm''', '''decoder.model.6.convtr.norm''': '''decoder.layers.6.norm''', '''decoder.model.7.block.1.conv.norm''': '''decoder.layers.7.block.1.norm''', '''decoder.model.7.block.3.conv.norm''': '''decoder.layers.7.block.3.norm''', '''decoder.model.7.shortcut.conv.norm''': '''decoder.layers.7.shortcut.norm''', '''decoder.model.9.convtr.norm''': '''decoder.layers.9.norm''', '''decoder.model.10.block.1.conv.norm''': '''decoder.layers.10.block.1.norm''', '''decoder.model.10.block.3.conv.norm''': '''decoder.layers.10.block.3.norm''', '''decoder.model.10.shortcut.conv.norm''': '''decoder.layers.10.shortcut.norm''', '''decoder.model.12.convtr.norm''': '''decoder.layers.12.norm''', '''decoder.model.13.block.1.conv.norm''': '''decoder.layers.13.block.1.norm''', '''decoder.model.13.block.3.conv.norm''': '''decoder.layers.13.block.3.norm''', '''decoder.model.13.shortcut.conv.norm''': '''decoder.layers.13.shortcut.norm''', '''decoder.model.15.conv.norm''': '''decoder.layers.15.norm''', } __lowerCAmelCase = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_DECODER, } __lowerCAmelCase = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_ENCODER_48K, **MAPPING_DECODER, **MAPPING_DECODER_48K, } __lowerCAmelCase = [] __lowerCAmelCase = [] def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> Any: for attribute in key.split('.' ): _a : Optional[int] = getattr(lowerCAmelCase_ , lowerCAmelCase_ ) if weight_type is not None: _a : int = getattr(lowerCAmelCase_ , lowerCAmelCase_ ).shape else: _a : Any = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f"""Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": _a : Any = value elif weight_type == "weight_g": _a : Tuple = value elif weight_type == "weight_v": _a : Tuple = value elif weight_type == "bias": _a : Union[str, Any] = value elif weight_type == "running_mean": _a : int = value elif weight_type == "running_var": _a : Union[str, Any] = value elif weight_type == "num_batches_tracked": _a : Tuple = value elif weight_type == "weight_ih_l0": _a : Tuple = value elif weight_type == "weight_hh_l0": _a : int = value elif weight_type == "bias_ih_l0": _a : str = value elif weight_type == "bias_hh_l0": _a : Optional[int] = value elif weight_type == "weight_ih_l1": _a : Any = value elif weight_type == "weight_hh_l1": _a : Optional[Any] = value elif weight_type == "bias_ih_l1": _a : Any = value elif weight_type == "bias_hh_l1": _a : str = value else: _a : Optional[int] = value logger.info(f"""{key + ('.' + weight_type if weight_type is not None else '')} was initialized from {full_name}.""" ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> Union[str, Any]: for key in ignore_keys: if key.endswith('.*' ): if name.startswith(key[:-1] ): return True elif ".*." in key: _a , _a : Union[str, Any] = key.split('.*.' ) if prefix in name and suffix in name: return True elif key in name: return True return False def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> Dict: _a : Union[str, Any] = [] if model_name == "encodec_24khz" or "encodec_32khz": _a : Tuple = MAPPING_24K elif model_name == "encodec_48khz": _a : str = MAPPING_48K else: raise ValueError(f"""Unsupported model: {model_name}""" ) for name, value in orig_dict.items(): if should_ignore(lowerCAmelCase_ , lowerCAmelCase_ ): logger.info(f"""{name} was ignored""" ) continue _a : List[Any] = False for key, mapped_key in MAPPING.items(): if "*" in key: _a , _a : Optional[Any] = key.split('.*.' ) if prefix in name and suffix in name: _a : Tuple = suffix if key in name: # HACK otherwise .embed gets initialized with .embed_avg too if key.endswith('embed' ) and name.endswith('embed_avg' ): continue _a : Union[str, Any] = True if "*" in mapped_key: _a : List[Any] = name.split(lowerCAmelCase_ )[0].split('.' )[-2] _a : Any = mapped_key.replace('*' , lowerCAmelCase_ ) if "weight_g" in name: _a : str = 'weight_g' elif "weight_v" in name: _a : Optional[int] = 'weight_v' elif "weight_ih_l0" in name: _a : List[str] = 'weight_ih_l0' elif "weight_hh_l0" in name: _a : Dict = 'weight_hh_l0' elif "bias_ih_l0" in name: _a : Tuple = 'bias_ih_l0' elif "bias_hh_l0" in name: _a : Optional[Any] = 'bias_hh_l0' elif "weight_ih_l1" in name: _a : Dict = 'weight_ih_l1' elif "weight_hh_l1" in name: _a : Dict = 'weight_hh_l1' elif "bias_ih_l1" in name: _a : Optional[Any] = 'bias_ih_l1' elif "bias_hh_l1" in name: _a : Optional[Any] = 'bias_hh_l1' elif "bias" in name: _a : Tuple = 'bias' elif "weight" in name: _a : List[str] = 'weight' elif "running_mean" in name: _a : Optional[Any] = 'running_mean' elif "running_var" in name: _a : int = 'running_var' elif "num_batches_tracked" in name: _a : List[Any] = 'num_batches_tracked' else: _a : List[str] = None set_recursively(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) continue if not is_used: unused_weights.append(lowerCAmelCase_ ) logger.warning(f"""Unused weights: {unused_weights}""" ) @torch.no_grad() def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None , lowerCAmelCase_=None , ) -> Union[str, Any]: if config_path is not None: _a : Optional[Any] = EncodecConfig.from_pretrained(lowerCAmelCase_ ) else: _a : int = EncodecConfig() if model_name == "encodec_24khz": pass # config is already correct elif model_name == "encodec_32khz": _a : Dict = [8, 5, 4, 4] _a : Optional[int] = [2.2] _a : Optional[Any] = 64 _a : Any = 32000 _a : Dict = 2048 _a : Dict = False _a : List[Any] = False _a : List[Any] = False elif model_name == "encodec_48khz": _a : Optional[int] = [8, 5, 4, 2] _a : Optional[Any] = [3.0, 6.0, 12.0, 24.0] _a : str = 48000 _a : Optional[int] = 2 _a : List[str] = False _a : List[Any] = 'time_group_norm' _a : Optional[int] = True _a : str = 1.0 _a : List[Any] = 0.01 else: raise ValueError(f"""Unknown model name: {model_name}""" ) _a : Optional[int] = EncodecModel(lowerCAmelCase_ ) _a : List[Any] = EncodecFeatureExtractor( feature_size=config.audio_channels , sampling_rate=config.sampling_rate , chunk_length_s=config.chunk_length_s , overlap=config.overlap , ) feature_extractor.save_pretrained(lowerCAmelCase_ ) _a : Tuple = torch.load(lowerCAmelCase_ ) if "best_state" in original_checkpoint: # we might have a training state saved, in which case discard the yaml results and just retain the weights _a : Union[str, Any] = original_checkpoint['best_state'] recursively_load_weights(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) model.save_pretrained(lowerCAmelCase_ ) if repo_id: print('Pushing to the hub...' ) feature_extractor.push_to_hub(lowerCAmelCase_ ) model.push_to_hub(lowerCAmelCase_ ) if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() parser.add_argument( '''--model''', default='''encodec_24khz''', type=str, help='''The model to convert. Should be one of \'encodec_24khz\', \'encodec_32khz\', \'encodec_48khz\'.''', ) parser.add_argument('''--checkpoint_path''', required=True, default=None, type=str, help='''Path to original checkpoint''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--pytorch_dump_folder_path''', required=True, default=None, type=str, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.''' ) __lowerCAmelCase = parser.parse_args() convert_checkpoint( args.model, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
89
from abc import ABC, abstractmethod from argparse import ArgumentParser class __snake_case ( _lowerCamelCase ): @staticmethod @abstractmethod def __a ( __UpperCamelCase ) -> Dict: '''simple docstring''' raise NotImplementedError() @abstractmethod def __a ( self ) -> Optional[int]: '''simple docstring''' raise NotImplementedError()
143
0
'''simple docstring''' import argparse import json from collections import OrderedDict from functools import partial from pathlib import Path import timm import torch from huggingface_hub import hf_hub_download from transformers import LevitConfig, LevitForImageClassificationWithTeacher, LevitImageProcessor from transformers.utils import logging logging.set_verbosity_info() _UpperCamelCase = logging.get_logger() def lowercase_ ( lowerCAmelCase__ : int , lowerCAmelCase__ : str , lowerCAmelCase__ : LevitConfig , lowerCAmelCase__ : Path , lowerCAmelCase__ : bool = True ): """simple docstring""" print(f'Converting {name}...' ) with torch.no_grad(): if hidden_sizes == 128: if name[-1] == "S": __UpperCAmelCase : List[Any] = timm.create_model("""levit_128s""" , pretrained=lowerCAmelCase__ ) else: __UpperCAmelCase : Tuple = timm.create_model("""levit_128""" , pretrained=lowerCAmelCase__ ) if hidden_sizes == 192: __UpperCAmelCase : Any = timm.create_model("""levit_192""" , pretrained=lowerCAmelCase__ ) if hidden_sizes == 256: __UpperCAmelCase : List[str] = timm.create_model("""levit_256""" , pretrained=lowerCAmelCase__ ) if hidden_sizes == 384: __UpperCAmelCase : Tuple = timm.create_model("""levit_384""" , pretrained=lowerCAmelCase__ ) from_model.eval() __UpperCAmelCase : List[Any] = LevitForImageClassificationWithTeacher(lowerCAmelCase__ ).eval() __UpperCAmelCase : List[Any] = OrderedDict() __UpperCAmelCase : Optional[Any] = from_model.state_dict() __UpperCAmelCase : int = list(from_model.state_dict().keys() ) __UpperCAmelCase : str = list(our_model.state_dict().keys() ) print(len(lowerCAmelCase__ ) , len(lowerCAmelCase__ ) ) for i in range(len(lowerCAmelCase__ ) ): __UpperCAmelCase : Tuple = weights[og_keys[i]] our_model.load_state_dict(lowerCAmelCase__ ) __UpperCAmelCase : Any = torch.randn((2, 3, 224, 224) ) __UpperCAmelCase : Optional[Any] = from_model(lowerCAmelCase__ ) __UpperCAmelCase : Optional[Any] = our_model(lowerCAmelCase__ ).logits assert torch.allclose(lowerCAmelCase__ , lowerCAmelCase__ ), "The model logits don't match the original one." __UpperCAmelCase : Any = name print(lowerCAmelCase__ ) if push_to_hub: our_model.save_pretrained(save_directory / checkpoint_name ) __UpperCAmelCase : Tuple = LevitImageProcessor() image_processor.save_pretrained(save_directory / checkpoint_name ) print(f'Pushed {checkpoint_name}' ) def lowercase_ ( lowerCAmelCase__ : Path , lowerCAmelCase__ : str = None , lowerCAmelCase__ : bool = True ): """simple docstring""" __UpperCAmelCase : Optional[Any] = """imagenet-1k-id2label.json""" __UpperCAmelCase : str = 1000 __UpperCAmelCase : List[str] = (1, num_labels) __UpperCAmelCase : Optional[int] = """huggingface/label-files""" __UpperCAmelCase : Optional[int] = num_labels __UpperCAmelCase : List[Any] = json.load(open(hf_hub_download(lowerCAmelCase__ , lowerCAmelCase__ , repo_type="""dataset""" ) , """r""" ) ) __UpperCAmelCase : Optional[int] = {int(lowerCAmelCase__ ): v for k, v in idalabel.items()} __UpperCAmelCase : List[str] = idalabel __UpperCAmelCase : List[str] = {v: k for k, v in idalabel.items()} __UpperCAmelCase : Optional[Any] = partial(lowerCAmelCase__ , num_labels=lowerCAmelCase__ , idalabel=lowerCAmelCase__ , labelaid=lowerCAmelCase__ ) __UpperCAmelCase : Optional[Any] = { """levit-128S""": 128, """levit-128""": 128, """levit-192""": 192, """levit-256""": 256, """levit-384""": 384, } __UpperCAmelCase : str = { """levit-128S""": ImageNetPreTrainedConfig( hidden_sizes=[128, 256, 384] , num_attention_heads=[4, 6, 8] , depths=[2, 3, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), """levit-128""": ImageNetPreTrainedConfig( hidden_sizes=[128, 256, 384] , num_attention_heads=[4, 8, 12] , depths=[4, 4, 4] , key_dim=[16, 16, 16] , drop_path_rate=0 , ), """levit-192""": ImageNetPreTrainedConfig( hidden_sizes=[192, 288, 384] , num_attention_heads=[3, 5, 6] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), """levit-256""": ImageNetPreTrainedConfig( hidden_sizes=[256, 384, 512] , num_attention_heads=[4, 6, 8] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0 , ), """levit-384""": ImageNetPreTrainedConfig( hidden_sizes=[384, 512, 768] , num_attention_heads=[6, 9, 12] , depths=[4, 4, 4] , key_dim=[32, 32, 32] , drop_path_rate=0.1 , ), } if model_name: convert_weight_and_push( names_to_hidden_sizes[model_name] , lowerCAmelCase__ , names_to_config[model_name] , lowerCAmelCase__ , lowerCAmelCase__ ) else: for model_name, config in names_to_config.items(): convert_weight_and_push(names_to_hidden_sizes[model_name] , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) return config, expected_shape if __name__ == "__main__": _UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--model_name''', default=None, type=str, help='''The name of the model you wish to convert, it must be one of the supported Levit* architecture,''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default='''levit-dump-folder/''', type=Path, required=False, help='''Path to the output PyTorch model directory.''', ) parser.add_argument('''--push_to_hub''', action='''store_true''', help='''Push model and image processor to the hub''') parser.add_argument( '''--no-push_to_hub''', dest='''push_to_hub''', action='''store_false''', help='''Do not push model and image processor to the hub''', ) _UpperCamelCase = parser.parse_args() _UpperCamelCase = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
16
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) _UpperCamelCase = { '''configuration_owlvit''': [ '''OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''OwlViTConfig''', '''OwlViTOnnxConfig''', '''OwlViTTextConfig''', '''OwlViTVisionConfig''', ], '''processing_owlvit''': ['''OwlViTProcessor'''], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = ['''OwlViTFeatureExtractor'''] _UpperCamelCase = ['''OwlViTImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _UpperCamelCase = [ '''OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''OwlViTModel''', '''OwlViTPreTrainedModel''', '''OwlViTTextModel''', '''OwlViTVisionModel''', '''OwlViTForObjectDetection''', ] if TYPE_CHECKING: from .configuration_owlvit import ( OWLVIT_PRETRAINED_CONFIG_ARCHIVE_MAP, OwlViTConfig, OwlViTOnnxConfig, OwlViTTextConfig, OwlViTVisionConfig, ) from .processing_owlvit import OwlViTProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_owlvit import OwlViTFeatureExtractor from .image_processing_owlvit import OwlViTImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_owlvit import ( OWLVIT_PRETRAINED_MODEL_ARCHIVE_LIST, OwlViTForObjectDetection, OwlViTModel, OwlViTPreTrainedModel, OwlViTTextModel, OwlViTVisionModel, ) else: import sys _UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
16
1
"""simple docstring""" _SCREAMING_SNAKE_CASE : str = """ # Transformers installation ! pip install transformers datasets # To install from source instead of the last release, comment the command above and uncomment the following one. # ! pip install git+https://github.com/huggingface/transformers.git """ _SCREAMING_SNAKE_CASE : List[str] = [{"""type""": """code""", """content""": INSTALL_CONTENT}] _SCREAMING_SNAKE_CASE : Optional[Any] = { """{processor_class}""": """FakeProcessorClass""", """{model_class}""": """FakeModelClass""", """{object_class}""": """FakeObjectClass""", }
183
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_fnet import FNetTokenizer else: _A : Union[str, Any] = None _A : str = logging.get_logger(__name__) _A : Tuple = {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""} _A : Optional[Any] = { """vocab_file""": { """google/fnet-base""": """https://huggingface.co/google/fnet-base/resolve/main/spiece.model""", """google/fnet-large""": """https://huggingface.co/google/fnet-large/resolve/main/spiece.model""", }, """tokenizer_file""": { """google/fnet-base""": """https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json""", """google/fnet-large""": """https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json""", }, } _A : Optional[Any] = { """google/fnet-base""": 5_12, """google/fnet-large""": 5_12, } _A : List[str] = """▁""" class a__ ( a_ ): __lowerCAmelCase = VOCAB_FILES_NAMES __lowerCAmelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCAmelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCAmelCase = ["""input_ids""", """token_type_ids"""] __lowerCAmelCase = FNetTokenizer def __init__( self , _a=None , _a=None , _a=False , _a=True , _a=True , _a="<unk>" , _a="[SEP]" , _a="<pad>" , _a="[CLS]" , _a="[MASK]" , **_a , ): # Mask token behave like a normal word, i.e. include the space before it and # is included in the raw text, there should be a match in a non-normalized sentence. lowercase : int = ( AddedToken(_a , lstrip=_a , rstrip=_a , normalized=_a ) if isinstance(_a , _a ) else mask_token ) super().__init__( _a , tokenizer_file=_a , do_lower_case=_a , remove_space=_a , keep_accents=_a , unk_token=_a , sep_token=_a , pad_token=_a , cls_token=_a , mask_token=_a , **_a , ) lowercase : Dict = do_lower_case lowercase : Union[str, Any] = remove_space lowercase : Any = keep_accents lowercase : List[Any] = vocab_file lowercase : Union[str, Any] = False if not self.vocab_file else True def __magic_name__ ( self , _a , _a = None ): lowercase : Optional[Any] = [self.sep_token_id] lowercase : str = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def __magic_name__ ( self , _a , _a = None ): lowercase : Any = [self.sep_token_id] lowercase : Dict = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def __magic_name__ ( self , _a , _a = None ): if not os.path.isdir(_a ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return lowercase : Optional[Any] = os.path.join( _a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_a ): copyfile(self.vocab_file , _a ) return (out_vocab_file,)
202
0
import argparse import os import re import packaging.version lowercase__ ='examples/' lowercase__ ={ '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'), } lowercase__ ={ 'init': 'src/diffusers/__init__.py', 'setup': 'setup.py', } lowercase__ ='README.md' def __UpperCamelCase ( lowerCAmelCase__ : Any , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : str ): with open(lowerCAmelCase__ , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: __a : str = f.read() __a : List[str] = REPLACE_PATTERNS[pattern] __a : str = replace.replace('''VERSION''' , lowerCAmelCase__ ) __a : List[str] = re_pattern.sub(lowerCAmelCase__ , lowerCAmelCase__ ) with open(lowerCAmelCase__ , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.write(lowerCAmelCase__ ) def __UpperCamelCase ( lowerCAmelCase__ : Any ): for folder, directories, fnames in os.walk(lowerCAmelCase__ ): # 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(lowerCAmelCase__ , lowerCAmelCase__ ) , lowerCAmelCase__ , pattern='''examples''' ) def __UpperCamelCase ( lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[Any]=False ): for pattern, fname in REPLACE_FILES.items(): update_version_in_file(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) if not patch: update_version_in_examples(lowerCAmelCase__ ) def __UpperCamelCase ( ): __a : Optional[Any] = '''🤗 Transformers currently provides the following architectures''' __a : Any = '''1. Want to contribute a new model?''' with open(lowerCAmelCase__ , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: __a : Union[str, Any] = f.readlines() # Find the start of the list. __a : Optional[Any] = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 __a : str = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith('''1.''' ): __a : List[str] = lines[index].replace( '''https://huggingface.co/docs/diffusers/main/model_doc''' , '''https://huggingface.co/docs/diffusers/model_doc''' , ) index += 1 with open(lowerCAmelCase__ , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(lowerCAmelCase__ ) def __UpperCamelCase ( ): with open(REPLACE_FILES['''init'''] , '''r''' ) as f: __a : List[str] = f.read() __a : Optional[Any] = REPLACE_PATTERNS['''init'''][0].search(lowerCAmelCase__ ).groups()[0] return packaging.version.parse(lowerCAmelCase__ ) def __UpperCamelCase ( lowerCAmelCase__ : List[Any]=False ): __a : Any = 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 : List[str] = default_version.base_version elif patch: __a : Tuple = f"{default_version.major}.{default_version.minor}.{default_version.micro + 1}" else: __a : Tuple = f"{default_version.major}.{default_version.minor + 1}.0" # Now let's ask nicely if that's the right one. __a : List[str] = input(f"Which version are you releasing? [{default_version}]" ) if len(lowerCAmelCase__ ) == 0: __a : Optional[int] = default_version print(f"Updating version to {version}." ) global_version_update(lowerCAmelCase__ , patch=lowerCAmelCase__ ) def __UpperCamelCase ( ): __a : List[Any] = get_version() __a : Optional[int] = f"{current_version.major}.{current_version.minor + 1}.0.dev0" __a : Any = current_version.base_version # Check with the user we got that right. __a : Tuple = input(f"Which version are we developing now? [{dev_version}]" ) if len(lowerCAmelCase__ ) == 0: __a : Optional[Any] = dev_version print(f"Updating version to {version}." ) global_version_update(lowerCAmelCase__ ) # print("Cleaning main README, don't forget to run `make fix-copies`.") # clean_main_ref_in_model_list() if __name__ == "__main__": lowercase__ =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.') lowercase__ =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()
359
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowercase__ ={ 'configuration_data2vec_audio': ['DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Data2VecAudioConfig'], 'configuration_data2vec_text': [ 'DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Data2VecTextConfig', 'Data2VecTextOnnxConfig', ], 'configuration_data2vec_vision': [ 'DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Data2VecVisionConfig', 'Data2VecVisionOnnxConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ =[ 'DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecAudioForAudioFrameClassification', 'Data2VecAudioForCTC', 'Data2VecAudioForSequenceClassification', 'Data2VecAudioForXVector', 'Data2VecAudioModel', 'Data2VecAudioPreTrainedModel', ] lowercase__ =[ 'DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecTextForCausalLM', 'Data2VecTextForMaskedLM', 'Data2VecTextForMultipleChoice', 'Data2VecTextForQuestionAnswering', 'Data2VecTextForSequenceClassification', 'Data2VecTextForTokenClassification', 'Data2VecTextModel', 'Data2VecTextPreTrainedModel', ] lowercase__ =[ 'DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST', 'Data2VecVisionForImageClassification', 'Data2VecVisionForMaskedImageModeling', 'Data2VecVisionForSemanticSegmentation', 'Data2VecVisionModel', 'Data2VecVisionPreTrainedModel', ] if is_tf_available(): lowercase__ =[ 'TFData2VecVisionForImageClassification', 'TFData2VecVisionForSemanticSegmentation', 'TFData2VecVisionModel', 'TFData2VecVisionPreTrainedModel', ] if TYPE_CHECKING: from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig from .configuration_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecTextConfig, DataaVecTextOnnxConfig, ) from .configuration_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecVisionConfig, DataaVecVisionOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_dataavec_audio import ( DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecAudioForAudioFrameClassification, DataaVecAudioForCTC, DataaVecAudioForSequenceClassification, DataaVecAudioForXVector, DataaVecAudioModel, DataaVecAudioPreTrainedModel, ) from .modeling_dataavec_text import ( DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecTextForCausalLM, DataaVecTextForMaskedLM, DataaVecTextForMultipleChoice, DataaVecTextForQuestionAnswering, DataaVecTextForSequenceClassification, DataaVecTextForTokenClassification, DataaVecTextModel, DataaVecTextPreTrainedModel, ) from .modeling_dataavec_vision import ( DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST, DataaVecVisionForImageClassification, DataaVecVisionForMaskedImageModeling, DataaVecVisionForSemanticSegmentation, DataaVecVisionModel, DataaVecVisionPreTrainedModel, ) if is_tf_available(): from .modeling_tf_dataavec_vision import ( TFDataaVecVisionForImageClassification, TFDataaVecVisionForSemanticSegmentation, TFDataaVecVisionModel, TFDataaVecVisionPreTrainedModel, ) else: import sys lowercase__ =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
90
0
"""simple docstring""" class lowerCAmelCase__ : '''simple docstring''' def __init__( self : List[str] , lowercase_ : Optional[int]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[Any] = arr.split(''',''') def _SCREAMING_SNAKE_CASE ( self : int): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = [int(self.array[0])] * len(self.array) SCREAMING_SNAKE_CASE_ : Optional[int] = [int(self.array[0])] * len(self.array) for i in range(1 , len(self.array)): SCREAMING_SNAKE_CASE_ : Dict = max( int(self.array[i]) + sum_value[i - 1] , int(self.array[i])) SCREAMING_SNAKE_CASE_ : int = max(sum_value[i] , rear[i - 1]) return rear[len(self.array) - 1] if __name__ == "__main__": UpperCAmelCase_ : Any = input("""please input some numbers:""") UpperCAmelCase_ : int = SubArray(whole_array) UpperCAmelCase_ : Optional[Any] = array.solve_sub_array() print(("""the results is:""", re))
91
"""simple docstring""" from math import factorial def _A (__a = 20 ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE_ : Dict = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... SCREAMING_SNAKE_CASE_ : List[str] = n // 2 return int(factorial(__a ) / (factorial(__a ) * factorial(n - k )) ) if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution(20)) else: try: UpperCAmelCase_ : List[str] = int(sys.argv[1]) print(solution(n)) except ValueError: print("""Invalid entry - please enter a number.""")
91
1
"""simple docstring""" import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class lowerCamelCase ( _UpperCAmelCase ): def __init__( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_=13 , SCREAMING_SNAKE_CASE_=7 , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=False , SCREAMING_SNAKE_CASE_=True , SCREAMING_SNAKE_CASE_=99 , SCREAMING_SNAKE_CASE_=32 , SCREAMING_SNAKE_CASE_=5 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=64 , SCREAMING_SNAKE_CASE_="gelu" , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=0.1 , SCREAMING_SNAKE_CASE_=512 , SCREAMING_SNAKE_CASE_=16 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=0.02 , SCREAMING_SNAKE_CASE_=3 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=None , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=2 , SCREAMING_SNAKE_CASE_=4 , SCREAMING_SNAKE_CASE_=1 , ): UpperCamelCase : Tuple = parent UpperCamelCase : Optional[int] = batch_size UpperCamelCase : Optional[Any] = seq_length UpperCamelCase : int = is_training UpperCamelCase : Union[str, Any] = use_input_mask UpperCamelCase : Union[str, Any] = use_token_type_ids UpperCamelCase : Dict = use_labels UpperCamelCase : Union[str, Any] = vocab_size UpperCamelCase : Union[str, Any] = hidden_size UpperCamelCase : Tuple = num_hidden_layers UpperCamelCase : Any = num_attention_heads UpperCamelCase : int = intermediate_size UpperCamelCase : str = hidden_act UpperCamelCase : Optional[Any] = hidden_dropout_prob UpperCamelCase : str = attention_probs_dropout_prob UpperCamelCase : List[Any] = max_position_embeddings UpperCamelCase : Optional[Any] = type_vocab_size UpperCamelCase : int = type_sequence_label_size UpperCamelCase : Dict = initializer_range UpperCamelCase : Dict = num_labels UpperCamelCase : Tuple = num_choices UpperCamelCase : Optional[int] = scope UpperCamelCase : List[Any] = q_groups UpperCamelCase : Tuple = k_groups UpperCamelCase : Any = v_groups UpperCamelCase : List[str] = post_attention_groups UpperCamelCase : Tuple = intermediate_groups UpperCamelCase : int = output_groups def a_ ( self ): UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCamelCase : Tuple = None if self.use_input_mask: UpperCamelCase : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) UpperCamelCase : Optional[int] = None UpperCamelCase : List[Any] = None UpperCamelCase : Dict = None if self.use_labels: UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCamelCase : Tuple = ids_tensor([self.batch_size] , self.num_choices ) UpperCamelCase : Dict = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def a_ ( self ): return SqueezeBertConfig( embedding_size=self.hidden_size , 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 , attention_probs_dropout_prob=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , q_groups=self.q_groups , k_groups=self.k_groups , v_groups=self.v_groups , post_attention_groups=self.post_attention_groups , intermediate_groups=self.intermediate_groups , output_groups=self.output_groups , ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[str] = SqueezeBertModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Any = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Union[str, Any] = SqueezeBertForMaskedLM(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : List[Any] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : List[Any] = SqueezeBertForQuestionAnswering(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : str = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , start_positions=SCREAMING_SNAKE_CASE_ , end_positions=SCREAMING_SNAKE_CASE_ ) 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 , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : str = self.num_labels UpperCamelCase : Optional[Any] = SqueezeBertForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Union[str, Any] = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Any = self.num_labels UpperCamelCase : str = SqueezeBertForTokenClassification(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Dict = model(SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def a_ ( self , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): UpperCamelCase : Optional[int] = self.num_choices UpperCamelCase : Tuple = SqueezeBertForMultipleChoice(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() UpperCamelCase : Union[str, Any] = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Union[str, Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCamelCase : Tuple = model( SCREAMING_SNAKE_CASE_ , attention_mask=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def a_ ( self ): UpperCamelCase : Optional[int] = self.prepare_config_and_inputs() ((UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase) , (UpperCamelCase)) : Optional[int] = config_and_inputs UpperCamelCase : Optional[int] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowerCamelCase ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): lowercase : Dict = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) lowercase : Dict = ( { 'feature-extraction': SqueezeBertModel, 'fill-mask': SqueezeBertForMaskedLM, 'question-answering': SqueezeBertForQuestionAnswering, 'text-classification': SqueezeBertForSequenceClassification, 'token-classification': SqueezeBertForTokenClassification, 'zero-shot': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) lowercase : Dict = False lowercase : str = True lowercase : str = False def a_ ( self ): UpperCamelCase : Any = SqueezeBertModelTester(self ) UpperCamelCase : List[Any] = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , dim=37 ) def a_ ( self ): self.config_tester.run_common_tests() def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*SCREAMING_SNAKE_CASE_ ) def a_ ( self ): UpperCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*SCREAMING_SNAKE_CASE_ ) @slow def a_ ( self ): for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : Optional[Any] = SqueezeBertModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @require_sentencepiece @require_tokenizers @require_torch class lowerCamelCase ( unittest.TestCase ): @slow def a_ ( self ): UpperCamelCase : Optional[Any] = SqueezeBertForSequenceClassification.from_pretrained("""squeezebert/squeezebert-mnli""" ) UpperCamelCase : Dict = torch.tensor([[1, 2_9414, 232, 328, 740, 1140, 1_2695, 69, 13, 1588, 2]] ) UpperCamelCase : List[str] = model(SCREAMING_SNAKE_CASE_ )[0] UpperCamelCase : Optional[Any] = torch.Size((1, 3) ) self.assertEqual(output.shape , SCREAMING_SNAKE_CASE_ ) UpperCamelCase : Optional[int] = torch.tensor([[0.6401, -0.0349, -0.6041]] ) self.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , atol=1e-4 ) )
27
"""simple docstring""" def A_ ( snake_case_ : list[int] ): '''simple docstring''' if not numbers: return 0 if not isinstance(snake_case_ ,(list, tuple) ) or not all( isinstance(snake_case_ ,snake_case_ ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) UpperCamelCase : int = numbers[0] for i in range(1 ,len(snake_case_ ) ): # update the maximum and minimum subarray products UpperCamelCase : List[str] = numbers[i] if number < 0: UpperCamelCase , UpperCamelCase : Optional[int] = min_till_now, max_till_now UpperCamelCase : Dict = max(snake_case_ ,max_till_now * number ) UpperCamelCase : Union[str, Any] = min(snake_case_ ,min_till_now * number ) # update the maximum product found till now UpperCamelCase : Union[str, Any] = max(snake_case_ ,snake_case_ ) return max_prod
27
1
def __a ( SCREAMING_SNAKE_CASE ) -> str: '''simple docstring''' __UpperCAmelCase = len(SCREAMING_SNAKE_CASE ) __UpperCAmelCase = sum(SCREAMING_SNAKE_CASE ) __UpperCAmelCase = [[False for x in range(s + 1 )] for y in range(n + 1 )] for i in range(1 , n + 1 ): __UpperCAmelCase = True for i in range(1 , s + 1 ): __UpperCAmelCase = False for i in range(1 , n + 1 ): for j in range(1 , s + 1 ): __UpperCAmelCase = dp[i][j - 1] if arr[i - 1] <= j: __UpperCAmelCase = dp[i][j] or dp[i - 1][j - arr[i - 1]] for j in range(int(s / 2 ) , -1 , -1 ): if dp[n][j] is True: __UpperCAmelCase = s - 2 * j break return diff
333
def __a ( SCREAMING_SNAKE_CASE ) -> set: '''simple docstring''' __UpperCAmelCase = set() # edges = list of graph's edges __UpperCAmelCase = get_edges(SCREAMING_SNAKE_CASE ) # While there are still elements in edges list, take an arbitrary edge # (from_node, to_node) and add his extremity to chosen_vertices and then # remove all arcs adjacent to the from_node and to_node while edges: __UpperCAmelCase , __UpperCAmelCase = edges.pop() chosen_vertices.add(SCREAMING_SNAKE_CASE ) chosen_vertices.add(SCREAMING_SNAKE_CASE ) for edge in edges.copy(): if from_node in edge or to_node in edge: edges.discard(SCREAMING_SNAKE_CASE ) return chosen_vertices def __a ( SCREAMING_SNAKE_CASE ) -> set: '''simple docstring''' __UpperCAmelCase = set() for from_node, to_nodes in graph.items(): for to_node in to_nodes: edges.add((from_node, to_node) ) return edges if __name__ == "__main__": import doctest doctest.testmod() # graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} # print(f"Matching vertex cover:\n{matching_min_vertex_cover(graph)}")
333
1
import argparse import os from pathlib import Path from typing import Dict import tensorflow as tf import torch from tqdm import tqdm from transformers import PegasusConfig, PegasusForConditionalGeneration, PegasusTokenizer from transformers.models.pegasus.configuration_pegasus import DEFAULTS, task_specific_params a__: Any = [ # replace left string with right string to get the relevant state_dict key (identical state dict to bart) ['memory_attention', 'encoder_attn'], ['attention', 'attn'], ['/', '.'], ['.LayerNorm.gamma', '_layer_norm.weight'], ['.LayerNorm.beta', '_layer_norm.bias'], ['r.layer_', 'r.layers.'], ['output_proj', 'out_proj'], ['ffn.dense_1.', 'fc2.'], ['ffn.dense.', 'fc1.'], ['ffn_layer_norm', 'final_layer_norm'], ['kernel', 'weight'], ['encoder_layer_norm.', 'encoder.layer_norm.'], ['decoder_layer_norm.', 'decoder.layer_norm.'], ['embeddings.weights', 'shared.weight'], ] def UpperCamelCase__( UpperCamelCase__ : Tuple )->Union[str, Any]: for pegasus_name, hf_name in PATTERNS: A__ = k.replace(_UpperCAmelCase , _UpperCAmelCase ) return k def UpperCamelCase__( UpperCamelCase__ : str , UpperCamelCase__ : Tuple )->PegasusForConditionalGeneration: A__ = DEFAULTS.copy() cfg_kwargs.update(_UpperCAmelCase ) A__ = PegasusConfig(**_UpperCAmelCase ) A__ = PegasusForConditionalGeneration(_UpperCAmelCase ) A__ = torch_model.model.state_dict() A__ = {} for k, v in tf_weights.items(): A__ = rename_state_dict_key(_UpperCAmelCase ) if new_k not in sd: raise ValueError(f"could not find new key {new_k} in state dict. (converted from {k})" ) if "dense" in k or "proj" in new_k: A__ = v.T A__ = torch.tensor(_UpperCAmelCase , dtype=sd[new_k].dtype ) assert v.shape == sd[new_k].shape, f"{new_k}, {k}, {v.shape}, {sd[new_k].shape}" # make sure embedding.padding_idx is respected A__ = torch.zeros_like(mapping['''shared.weight'''][cfg.pad_token_id + 1] ) A__ = mapping['shared.weight'] A__ = mapping['shared.weight'] A__ = {k: torch.zeros_like(_UpperCAmelCase ) for k, v in sd.items() if k.endswith('''bias''' ) and k not in mapping} mapping.update(**_UpperCAmelCase ) A__ = torch_model.model.load_state_dict(_UpperCAmelCase , strict=_UpperCAmelCase ) A__ = [ k for k in missing if k not in ['encoder.embed_positions.weight', 'decoder.embed_positions.weight'] ] assert unexpected_missing == [], f"no matches found for the following torch keys {unexpected_missing}" assert extra == [], f"no matches found for the following tf keys {extra}" return torch_model def UpperCamelCase__( UpperCamelCase__ : List[Any]="./ckpt/aeslc/model.ckpt-32000" )->Dict: A__ = tf.train.list_variables(_UpperCAmelCase ) A__ = {} A__ = ['Adafactor', 'global_step'] for name, shape in tqdm(_UpperCAmelCase , desc='''converting tf checkpoint to dict''' ): A__ = any(pat in name for pat in ignore_name ) if skip_key: continue A__ = tf.train.load_variable(_UpperCAmelCase , _UpperCAmelCase ) A__ = array return tf_weights def UpperCamelCase__( UpperCamelCase__ : Any , UpperCamelCase__ : str )->Optional[Any]: A__ = Path(_UpperCAmelCase ).parent.name A__ = task_specific_params[f"summarization_{dataset}"]['max_position_embeddings'] A__ = PegasusTokenizer.from_pretrained('''sshleifer/pegasus''' , model_max_length=_UpperCAmelCase ) assert tok.model_max_length == desired_max_model_length tok.save_pretrained(_UpperCAmelCase ) # convert model A__ = get_tf_weights_as_numpy(_UpperCAmelCase ) A__ = task_specific_params[f"summarization_{dataset}"] if dataset == "large": A__ = task_specific_params A__ = convert_pegasus(_UpperCAmelCase , _UpperCAmelCase ) torch_model.save_pretrained(_UpperCAmelCase ) A__ = torch_model.state_dict() sd.pop('''model.decoder.embed_positions.weight''' ) sd.pop('''model.encoder.embed_positions.weight''' ) torch.save(_UpperCAmelCase , Path(_UpperCAmelCase ) / '''pytorch_model.bin''' ) if __name__ == "__main__": a__: int = argparse.ArgumentParser() # Required parameters parser.add_argument('tf_ckpt_path', type=str, help='passed to tf.train.list_variables') parser.add_argument('save_dir', default=None, type=str, help='Path to the output PyTorch model.') a__: int = parser.parse_args() if args.save_dir is None: a__: int = Path(args.tf_ckpt_path).parent.name a__: str = os.path.join('pegasus', dataset) convert_pegasus_ckpt_to_pytorch(args.tf_ckpt_path, args.save_dir)
358
# DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion # and https://github.com/hojonathanho/diffusion import math from dataclasses import dataclass from typing import List, Optional, Tuple, Union import numpy as np import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.schedulers.scheduling_utils import SchedulerMixin from diffusers.utils import BaseOutput, deprecate @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ ): __SCREAMING_SNAKE_CASE = 42 __SCREAMING_SNAKE_CASE = None def UpperCamelCase__( UpperCamelCase__ : List[Any] , UpperCamelCase__ : Tuple=0.999 , UpperCamelCase__ : Optional[int]="cosine" , )->Optional[Any]: if alpha_transform_type == "cosine": def alpha_bar_fn(UpperCamelCase__ : List[str] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(UpperCamelCase__ : Union[str, Any] ): return math.exp(t * -12.0 ) else: raise ValueError(f"Unsupported alpha_tranform_type: {alpha_transform_type}" ) A__ = [] for i in range(UpperCamelCase__ ): A__ = i / num_diffusion_timesteps A__ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(UpperCamelCase__ ) / alpha_bar_fn(UpperCamelCase__ ) , UpperCamelCase__ ) ) return torch.tensor(UpperCamelCase__ , dtype=torch.floataa ) class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ , UpperCamelCase__ ): __SCREAMING_SNAKE_CASE = 1 @register_to_config def __init__( self,__lowerCamelCase = 1000,__lowerCamelCase = 0.0001,__lowerCamelCase = 0.02,__lowerCamelCase = "linear",__lowerCamelCase = None,__lowerCamelCase = True,__lowerCamelCase = True,__lowerCamelCase = 0,__lowerCamelCase = "epsilon",__lowerCamelCase = 1.0,**__lowerCamelCase,): if kwargs.get('''set_alpha_to_one''',__lowerCamelCase ) is not None: A__ = ( '''The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead.''' ) deprecate('''set_alpha_to_one''','''1.0.0''',__lowerCamelCase,standard_warn=__lowerCamelCase ) A__ = kwargs['''set_alpha_to_one'''] if trained_betas is not None: A__ = torch.tensor(__lowerCamelCase,dtype=torch.floataa ) elif beta_schedule == "linear": A__ = torch.linspace(__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. A__ = ( torch.linspace(beta_start**0.5,beta_end**0.5,__lowerCamelCase,dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule A__ = betas_for_alpha_bar(__lowerCamelCase ) else: raise NotImplementedError(f"{beta_schedule} does is not implemented for {self.__class__}" ) A__ = 1.0 - self.betas A__ = torch.cumprod(self.alphas,dim=0 ) # At every step in inverted ddim, we are looking into the next alphas_cumprod # For the final step, there is no next alphas_cumprod, and the index is out of bounds # `set_alpha_to_zero` decides whether we set this parameter simply to zero # in this case, self.step() just output the predicted noise # or whether we use the final alpha of the "non-previous" one. A__ = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1] # standard deviation of the initial noise distribution A__ = 1.0 # setable values A__ = None A__ = torch.from_numpy(np.arange(0,__lowerCamelCase ).copy().astype(np.intaa ) ) def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase = None ): return sample def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase = None ): if num_inference_steps > self.config.num_train_timesteps: raise ValueError( f"`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:" f" {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle" f" maximal {self.config.num_train_timesteps} timesteps." ) A__ = num_inference_steps A__ = self.config.num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 A__ = (np.arange(0,__lowerCamelCase ) * step_ratio).round().copy().astype(np.intaa ) A__ = torch.from_numpy(__lowerCamelCase ).to(__lowerCamelCase ) self.timesteps += self.config.steps_offset def UpperCamelCase ( self,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase,__lowerCamelCase = 0.0,__lowerCamelCase = False,__lowerCamelCase = None,__lowerCamelCase = True,): # 1. get previous step value (=t+1) A__ = timestep + self.config.num_train_timesteps // self.num_inference_steps # 2. compute alphas, betas # change original implementation to exactly match noise levels for analogous forward process A__ = self.alphas_cumprod[timestep] A__ = ( self.alphas_cumprod[prev_timestep] if prev_timestep < self.config.num_train_timesteps else self.final_alpha_cumprod ) A__ = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf if self.config.prediction_type == "epsilon": A__ = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 A__ = model_output elif self.config.prediction_type == "sample": A__ = model_output A__ = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5 elif self.config.prediction_type == "v_prediction": A__ = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output A__ = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or" ''' `v_prediction`''' ) # 4. Clip or threshold "predicted x_0" if self.config.clip_sample: A__ = pred_original_sample.clamp( -self.config.clip_sample_range,self.config.clip_sample_range ) # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf A__ = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon # 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf A__ = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction if not return_dict: return (prev_sample, pred_original_sample) return DDIMSchedulerOutput(prev_sample=__lowerCamelCase,pred_original_sample=__lowerCamelCase ) def __len__( self ): return self.config.num_train_timesteps
39
0