code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase : Tuple = logging.get_logger(__name__) lowercase : Tuple = { """google/vit-base-patch16-224""": """https://huggingface.co/vit-base-patch16-224/resolve/main/config.json""", # See all ViT models at https://huggingface.co/models?filter=vit } class __snake_case ( lowerCAmelCase ): _a : Tuple= "vit" def __init__( self ,snake_case=768 ,snake_case=12 ,snake_case=12 ,snake_case=3072 ,snake_case="gelu" ,snake_case=0.0 ,snake_case=0.0 ,snake_case=0.02 ,snake_case=1e-12 ,snake_case=224 ,snake_case=16 ,snake_case=3 ,snake_case=True ,snake_case=16 ,**snake_case ,): '''simple docstring''' super().__init__(**snake_case ) lowercase : Union[str, Any] = hidden_size lowercase : int = num_hidden_layers lowercase : Optional[int] = num_attention_heads lowercase : Optional[Any] = intermediate_size lowercase : str = hidden_act lowercase : Tuple = hidden_dropout_prob lowercase : Dict = attention_probs_dropout_prob lowercase : Tuple = initializer_range lowercase : int = layer_norm_eps lowercase : Optional[Any] = image_size lowercase : Any = patch_size lowercase : List[Any] = num_channels lowercase : Dict = qkv_bias lowercase : List[Any] = encoder_stride class __snake_case ( lowerCAmelCase ): _a : Union[str, Any]= version.parse("1.11" ) @property def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' return OrderedDict( [ ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}), ] ) @property def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' return 1e-4
20
'''simple docstring''' import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { '''microsoft/conditional-detr-resnet-50''': ( '''https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json''' ), } class __magic_name__ ( _UpperCamelCase ): lowerCAmelCase : Any = 'conditional_detr' lowerCAmelCase : List[str] = ['past_key_values'] lowerCAmelCase : Optional[int] = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : Optional[int] ,_UpperCAmelCase : Optional[int]=True ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : List[Any]=3 ,_UpperCAmelCase : List[Any]=300 ,_UpperCAmelCase : Dict=6 ,_UpperCAmelCase : List[str]=2048 ,_UpperCAmelCase : Optional[int]=8 ,_UpperCAmelCase : List[Any]=6 ,_UpperCAmelCase : Optional[int]=2048 ,_UpperCAmelCase : Dict=8 ,_UpperCAmelCase : int=0.0 ,_UpperCAmelCase : Optional[Any]=0.0 ,_UpperCAmelCase : Optional[Any]=True ,_UpperCAmelCase : str="relu" ,_UpperCAmelCase : Tuple=256 ,_UpperCAmelCase : Optional[int]=0.1 ,_UpperCAmelCase : str=0.0 ,_UpperCAmelCase : Optional[int]=0.0 ,_UpperCAmelCase : Union[str, Any]=0.02 ,_UpperCAmelCase : List[str]=1.0 ,_UpperCAmelCase : Any=False ,_UpperCAmelCase : int="sine" ,_UpperCAmelCase : List[str]="resnet50" ,_UpperCAmelCase : Optional[int]=True ,_UpperCAmelCase : str=False ,_UpperCAmelCase : str=2 ,_UpperCAmelCase : int=5 ,_UpperCAmelCase : Optional[int]=2 ,_UpperCAmelCase : str=1 ,_UpperCAmelCase : Union[str, Any]=1 ,_UpperCAmelCase : List[str]=2 ,_UpperCAmelCase : Union[str, Any]=5 ,_UpperCAmelCase : List[Any]=2 ,_UpperCAmelCase : Optional[int]=0.25 ,**_UpperCAmelCase : Tuple ,): if backbone_config is not None and use_timm_backbone: raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.' ) if not use_timm_backbone: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) _a : Optional[Any] = CONFIG_MAPPING['resnet'](out_features=['stage4'] ) elif isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : str = backbone_config.get('model_type' ) _a : Union[str, Any] = CONFIG_MAPPING[backbone_model_type] _a : List[Any] = config_class.from_dict(_UpperCAmelCase ) _a : Tuple = use_timm_backbone _a : Union[str, Any] = backbone_config _a : List[Any] = num_channels _a : Union[str, Any] = num_queries _a : Optional[Any] = d_model _a : Tuple = encoder_ffn_dim _a : Dict = encoder_layers _a : List[str] = encoder_attention_heads _a : Union[str, Any] = decoder_ffn_dim _a : Optional[int] = decoder_layers _a : int = decoder_attention_heads _a : Optional[int] = dropout _a : Tuple = attention_dropout _a : List[Any] = activation_dropout _a : str = activation_function _a : Optional[Any] = init_std _a : Union[str, Any] = init_xavier_std _a : List[Any] = encoder_layerdrop _a : List[Any] = decoder_layerdrop _a : Dict = encoder_layers _a : List[Any] = auxiliary_loss _a : Optional[int] = position_embedding_type _a : List[Any] = backbone _a : Optional[int] = use_pretrained_backbone _a : Optional[int] = dilation # Hungarian matcher _a : Tuple = class_cost _a : str = bbox_cost _a : Any = giou_cost # Loss coefficients _a : Tuple = mask_loss_coefficient _a : Dict = dice_loss_coefficient _a : Tuple = cls_loss_coefficient _a : Any = bbox_loss_coefficient _a : Dict = giou_loss_coefficient _a : Union[str, Any] = focal_alpha super().__init__(is_encoder_decoder=_UpperCAmelCase ,**_UpperCAmelCase ) @property def __lowercase ( self : Dict ): return self.encoder_attention_heads @property def __lowercase ( self : str ): return self.d_model def __lowercase ( self : int ): _a : List[str] = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: _a : Dict = self.backbone_config.to_dict() _a : Union[str, Any] = self.__class__.model_type return output class __magic_name__ ( _UpperCamelCase ): lowerCAmelCase : str = version.parse('1.11' ) @property def __lowercase ( self : Dict ): return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('pixel_mask', {0: 'batch'}), ] ) @property def __lowercase ( self : Any ): return 1E-5 @property def __lowercase ( self : List[Any] ): return 12
89
0
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE : List[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE : Optional[Any] = { "edbeeching/decision-transformer-gym-hopper-medium": ( "https://huggingface.co/edbeeching/decision-transformer-gym-hopper-medium/resolve/main/config.json" ), # See all DecisionTransformer models at https://huggingface.co/models?filter=decision_transformer } class _lowerCamelCase( _a ): lowercase_ : int = """decision_transformer""" lowercase_ : str = ["""past_key_values"""] lowercase_ : str = { """max_position_embeddings""": """n_positions""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self, lowerCamelCase=17, lowerCamelCase=4, lowerCamelCase=1_28, lowerCamelCase=40_96, lowerCamelCase=True, lowerCamelCase=1, lowerCamelCase=10_24, lowerCamelCase=3, lowerCamelCase=1, lowerCamelCase=None, lowerCamelCase="relu", lowerCamelCase=0.1, lowerCamelCase=0.1, lowerCamelCase=0.1, lowerCamelCase=1E-5, lowerCamelCase=0.0_2, lowerCamelCase=True, lowerCamelCase=True, lowerCamelCase=5_02_56, lowerCamelCase=5_02_56, lowerCamelCase=False, lowerCamelCase=False, **lowerCamelCase, ) -> List[Any]: """simple docstring""" _lowercase : List[str] = state_dim _lowercase : Any = act_dim _lowercase : List[Any] = hidden_size _lowercase : int = max_ep_len _lowercase : Tuple = action_tanh _lowercase : Any = vocab_size _lowercase : int = n_positions _lowercase : Dict = n_layer _lowercase : Tuple = n_head _lowercase : Optional[int] = n_inner _lowercase : Optional[Any] = activation_function _lowercase : str = resid_pdrop _lowercase : List[Any] = embd_pdrop _lowercase : Optional[int] = attn_pdrop _lowercase : Any = layer_norm_epsilon _lowercase : List[Any] = initializer_range _lowercase : int = scale_attn_weights _lowercase : Optional[Any] = use_cache _lowercase : Union[str, Any] = scale_attn_by_inverse_layer_idx _lowercase : Tuple = reorder_and_upcast_attn _lowercase : Optional[int] = bos_token_id _lowercase : int = eos_token_id super().__init__(bos_token_id=lowerCamelCase, eos_token_id=lowerCamelCase, **lowerCamelCase)
21
'''simple docstring''' import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __magic_name__ : def __init__( self : List[str] ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : List[str]=13 ,_UpperCAmelCase : Any=32 ,_UpperCAmelCase : Union[str, Any]=3 ,_UpperCAmelCase : Optional[int]=4 ,_UpperCAmelCase : Optional[Any]=[10, 20, 30, 40] ,_UpperCAmelCase : Tuple=[2, 2, 3, 2] ,_UpperCAmelCase : Optional[int]=True ,_UpperCAmelCase : Optional[int]=True ,_UpperCAmelCase : Union[str, Any]=37 ,_UpperCAmelCase : Optional[int]="gelu" ,_UpperCAmelCase : Optional[Any]=10 ,_UpperCAmelCase : Tuple=0.02 ,_UpperCAmelCase : Any=["stage2", "stage3", "stage4"] ,_UpperCAmelCase : Any=[2, 3, 4] ,_UpperCAmelCase : Tuple=None ,): _a : Optional[Any] = parent _a : List[Any] = batch_size _a : str = image_size _a : Union[str, Any] = num_channels _a : List[Any] = num_stages _a : Dict = hidden_sizes _a : int = depths _a : Tuple = is_training _a : List[str] = use_labels _a : Dict = intermediate_size _a : int = hidden_act _a : int = num_labels _a : Any = initializer_range _a : Tuple = out_features _a : int = out_indices _a : List[Any] = scope def __lowercase ( self : Dict ): _a : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _a : Union[str, Any] = None if self.use_labels: _a : Tuple = ids_tensor([self.batch_size] ,self.num_labels ) _a : str = self.get_config() return config, pixel_values, labels def __lowercase ( self : Any ): return ConvNextVaConfig( num_channels=self.num_channels ,hidden_sizes=self.hidden_sizes ,depths=self.depths ,num_stages=self.num_stages ,hidden_act=self.hidden_act ,is_decoder=_UpperCAmelCase ,initializer_range=self.initializer_range ,out_features=self.out_features ,out_indices=self.out_indices ,num_labels=self.num_labels ,) def __lowercase ( self : Tuple ,_UpperCAmelCase : Any ,_UpperCAmelCase : Any ,_UpperCAmelCase : Optional[Any] ): _a : Optional[Any] = ConvNextVaModel(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : Any = model(_UpperCAmelCase ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape ,(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) ,) def __lowercase ( self : Tuple ,_UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : int ): _a : List[Any] = ConvNextVaForImageClassification(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : List[str] = model(_UpperCAmelCase ,labels=_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def __lowercase ( self : str ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ): _a : Optional[int] = ConvNextVaBackbone(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : Dict = model(_UpperCAmelCase ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) ,len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) ,[self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) ,len(config.out_features ) ) self.parent.assertListEqual(model.channels ,config.hidden_sizes[1:] ) # verify backbone works with out_features=None _a : Tuple = None _a : List[Any] = ConvNextVaBackbone(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : List[str] = model(_UpperCAmelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) ,1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) ,[self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) ,1 ) self.parent.assertListEqual(model.channels ,[config.hidden_sizes[-1]] ) def __lowercase ( self : Optional[Any] ): _a : Any = self.prepare_config_and_inputs() _a , _a , _a : Union[str, Any] = config_and_inputs _a : Any = {'pixel_values': pixel_values} return config, inputs_dict def __lowercase ( self : str ): _a : Tuple = self.prepare_config_and_inputs() _a , _a , _a : Tuple = config_and_inputs _a : List[Any] = {'pixel_values': pixel_values, 'labels': labels} return config, inputs_dict @require_torch class __magic_name__ ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): lowerCAmelCase : str = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) lowerCAmelCase : str = ( {'feature-extraction': ConvNextVaModel, 'image-classification': ConvNextVaForImageClassification} if is_torch_available() else {} ) lowerCAmelCase : int = False lowerCAmelCase : str = False lowerCAmelCase : Optional[Any] = False lowerCAmelCase : List[str] = False lowerCAmelCase : Optional[int] = False def __lowercase ( self : List[Any] ): _a : str = ConvNextVaModelTester(self ) _a : Tuple = ConfigTester(self ,config_class=_UpperCAmelCase ,has_text_modality=_UpperCAmelCase ,hidden_size=37 ) def __lowercase ( self : Optional[Any] ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __lowercase ( self : str ): return @unittest.skip(reason='ConvNextV2 does not use inputs_embeds' ) def __lowercase ( self : List[Any] ): pass @unittest.skip(reason='ConvNextV2 does not support input and output embeddings' ) def __lowercase ( self : Optional[int] ): pass @unittest.skip(reason='ConvNextV2 does not use feedforward chunking' ) def __lowercase ( self : Any ): pass def __lowercase ( self : List[str] ): if not self.model_tester.is_training: return for model_class in self.all_model_classes: _a , _a : List[Any] = self.model_tester.prepare_config_and_inputs_with_labels() _a : Any = True if model_class.__name__ in [ *get_values(_UpperCAmelCase ), *get_values(_UpperCAmelCase ), ]: continue _a : Optional[Any] = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.train() _a : str = self._prepare_for_class(_UpperCAmelCase ,_UpperCAmelCase ,return_labels=_UpperCAmelCase ) _a : Optional[int] = model(**_UpperCAmelCase ).loss loss.backward() def __lowercase ( self : str ): if not self.model_tester.is_training: return for model_class in self.all_model_classes: _a , _a : Optional[Any] = self.model_tester.prepare_config_and_inputs_with_labels() _a : Optional[int] = False _a : Tuple = True if ( model_class.__name__ in [*get_values(_UpperCAmelCase ), *get_values(_UpperCAmelCase )] or not model_class.supports_gradient_checkpointing ): continue _a : Tuple = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.gradient_checkpointing_enable() model.train() _a : Any = self._prepare_for_class(_UpperCAmelCase ,_UpperCAmelCase ,return_labels=_UpperCAmelCase ) _a : List[Any] = model(**_UpperCAmelCase ).loss loss.backward() def __lowercase ( self : List[Any] ): _a , _a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : int = model_class(_UpperCAmelCase ) _a : Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _a : Dict = [*signature.parameters.keys()] _a : int = ['pixel_values'] self.assertListEqual(arg_names[:1] ,_UpperCAmelCase ) def __lowercase ( self : int ): _a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase ) def __lowercase ( self : Any ): def check_hidden_states_output(_UpperCAmelCase : List[Any] ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Dict ): _a : Union[str, Any] = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() with torch.no_grad(): _a : List[Any] = model(**self._prepare_for_class(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Any = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _a : str = self.model_tester.num_stages self.assertEqual(len(_UpperCAmelCase ) ,expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) ,[self.model_tester.image_size // 4, self.model_tester.image_size // 4] ,) _a , _a : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : int = True check_hidden_states_output(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _a : Optional[Any] = True check_hidden_states_output(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) def __lowercase ( self : List[Any] ): _a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase ) @slow def __lowercase ( self : int ): for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Any = ConvNextVaModel.from_pretrained(_UpperCAmelCase ) self.assertIsNotNone(_UpperCAmelCase ) def __lowerCamelCase ( ) -> List[Any]: _a : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class __magic_name__ ( unittest.TestCase ): @cached_property def __lowercase ( self : Optional[Any] ): return AutoImageProcessor.from_pretrained('facebook/convnextv2-tiny-1k-224' ) if is_vision_available() else None @slow def __lowercase ( self : Any ): _a : List[str] = ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224' ).to(_UpperCAmelCase ) _a : Optional[int] = self.default_image_processor _a : str = prepare_img() _a : str = preprocessor(images=_UpperCAmelCase ,return_tensors='pt' ).to(_UpperCAmelCase ) # forward pass with torch.no_grad(): _a : Dict = model(**_UpperCAmelCase ) # verify the logits _a : Optional[Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape ,_UpperCAmelCase ) _a : Optional[Any] = torch.tensor([0.99_96, 0.19_66, -0.43_86] ).to(_UpperCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,_UpperCAmelCase ,atol=1E-4 ) )
89
0
'''simple docstring''' from collections.abc import Iterator, MutableMapping from dataclasses import dataclass from typing import Generic, TypeVar __SCREAMING_SNAKE_CASE :int = TypeVar('''KEY''') __SCREAMING_SNAKE_CASE :List[Any] = TypeVar('''VAL''') @dataclass(frozen=lowerCAmelCase_ , slots=lowerCAmelCase_ ) class A_ ( Generic[KEY, VAL] ): _lowerCamelCase : KEY _lowerCamelCase : VAL class A_ ( _Item ): def __init__( self : List[Any] ): super().__init__(snake_case_ , snake_case_ ) def __bool__( self : List[Any] ): return False __SCREAMING_SNAKE_CASE :Dict = _DeletedItem() class A_ ( MutableMapping[KEY, VAL] ): def __init__( self : str , snake_case_ : int = 8 , snake_case_ : float = 0.7_5 ): _UpperCAmelCase = initial_block_size _UpperCAmelCase = [None] * initial_block_size assert 0.0 < capacity_factor < 1.0 _UpperCAmelCase = capacity_factor _UpperCAmelCase = 0 def lowercase ( self : Any , snake_case_ : KEY ): return hash(snake_case_ ) % len(self._buckets ) def lowercase ( self : List[Any] , snake_case_ : int ): return (ind + 1) % len(self._buckets ) def lowercase ( self : Any , snake_case_ : int , snake_case_ : KEY , snake_case_ : VAL ): _UpperCAmelCase = self._buckets[ind] if not stored: _UpperCAmelCase = _Item(snake_case_ , snake_case_ ) self._len += 1 return True elif stored.key == key: _UpperCAmelCase = _Item(snake_case_ , snake_case_ ) return True else: return False def lowercase ( self : Optional[Any] ): _UpperCAmelCase = len(self._buckets ) * self._capacity_factor return len(self ) >= int(snake_case_ ) def lowercase ( self : Tuple ): if len(self._buckets ) <= self._initial_block_size: return False _UpperCAmelCase = len(self._buckets ) * self._capacity_factor / 2 return len(self ) < limit def lowercase ( self : str , snake_case_ : int ): _UpperCAmelCase = self._buckets _UpperCAmelCase = [None] * new_size _UpperCAmelCase = 0 for item in old_buckets: if item: self._add_item(item.key , item.val ) def lowercase ( self : Dict ): self._resize(len(self._buckets ) * 2 ) def lowercase ( self : Optional[Any] ): self._resize(len(self._buckets ) // 2 ) def lowercase ( self : List[Any] , snake_case_ : KEY ): _UpperCAmelCase = self._get_bucket_index(snake_case_ ) for _ in range(len(self._buckets ) ): yield ind _UpperCAmelCase = self._get_next_ind(snake_case_ ) def lowercase ( self : Optional[int] , snake_case_ : KEY , snake_case_ : VAL ): for ind in self._iterate_buckets(snake_case_ ): if self._try_set(snake_case_ , snake_case_ , snake_case_ ): break def __setitem__( self : Tuple , snake_case_ : KEY , snake_case_ : VAL ): if self._is_full(): self._size_up() self._add_item(snake_case_ , snake_case_ ) def __delitem__( self : Optional[int] , snake_case_ : KEY ): for ind in self._iterate_buckets(snake_case_ ): _UpperCAmelCase = self._buckets[ind] if item is None: raise KeyError(snake_case_ ) if item is _deleted: continue if item.key == key: _UpperCAmelCase = _deleted self._len -= 1 break if self._is_sparse(): self._size_down() def __getitem__( self : Dict , snake_case_ : KEY ): for ind in self._iterate_buckets(snake_case_ ): _UpperCAmelCase = self._buckets[ind] if item is None: break if item is _deleted: continue if item.key == key: return item.val raise KeyError(snake_case_ ) def __len__( self : List[Any] ): return self._len def __iter__( self : Union[str, Any] ): yield from (item.key for item in self._buckets if item) def __repr__( self : Optional[int] ): _UpperCAmelCase = " ,".join( f'{item.key}: {item.val}' for item in self._buckets if item ) return f'HashMap({val_string})'
22
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCAmelCase = { '''configuration_lilt''': ['''LILT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LiltConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''LILT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''LiltForQuestionAnswering''', '''LiltForSequenceClassification''', '''LiltForTokenClassification''', '''LiltModel''', '''LiltPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_lilt import LILT_PRETRAINED_CONFIG_ARCHIVE_MAP, LiltConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lilt import ( LILT_PRETRAINED_MODEL_ARCHIVE_LIST, LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, LiltPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
89
0
'''simple docstring''' import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as transformers_logging sys.path.append(os.path.join(os.getcwd())) # noqa: E402 # isort:skip from utils_rag import exact_match_score, fa_score # noqa: E402 # isort:skip UpperCamelCase__: Union[str, Any] = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) transformers_logging.set_verbosity_info() def snake_case_ ( _lowerCAmelCase : str ) -> Optional[int]: if "token" in model_name_or_path: return "rag_token" if "sequence" in model_name_or_path: return "rag_sequence" if "bart" in model_name_or_path: return "bart" return None def snake_case_ ( _lowerCAmelCase : Dict , _lowerCAmelCase : Optional[int] , _lowerCAmelCase : str ) -> Dict: return max(metric_fn(_lowerCAmelCase , _lowerCAmelCase ) for gt in ground_truths ) def snake_case_ ( _lowerCAmelCase : Any , _lowerCAmelCase : List[str] , _lowerCAmelCase : Optional[int] ) -> List[str]: UpperCAmelCase : str = [line.strip() for line in open(_lowerCAmelCase , '''r''' ).readlines()] UpperCAmelCase : Optional[Any] = [] if args.gold_data_mode == "qa": UpperCAmelCase : Optional[int] = pd.read_csv(_lowerCAmelCase , sep='''\t''' , header=_lowerCAmelCase ) for answer_list in data[1]: UpperCAmelCase : int = ast.literal_eval(_lowerCAmelCase ) answers.append(_lowerCAmelCase ) else: UpperCAmelCase : int = [line.strip() for line in open(_lowerCAmelCase , '''r''' ).readlines()] UpperCAmelCase : Optional[Any] = [[reference] for reference in references] UpperCAmelCase : Optional[int] = 0 for prediction, ground_truths in zip(_lowerCAmelCase , _lowerCAmelCase ): total += 1 em += metric_max_over_ground_truths(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) fa += metric_max_over_ground_truths(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) UpperCAmelCase : Union[str, Any] = 1_0_0.0 * em / total UpperCAmelCase : Any = 1_0_0.0 * fa / total logger.info(f"""F1: {fa:.2f}""" ) logger.info(f"""EM: {em:.2f}""" ) def snake_case_ ( _lowerCAmelCase : List[Any] , _lowerCAmelCase : Dict , _lowerCAmelCase : Optional[int] ) -> Optional[Any]: UpperCAmelCase : Union[str, Any] = args.k UpperCAmelCase : Tuple = [line.strip() for line in open(_lowerCAmelCase , '''r''' ).readlines()] UpperCAmelCase : Tuple = [line.strip() for line in open(_lowerCAmelCase , '''r''' ).readlines()] UpperCAmelCase : Any = 0 for hypo, reference in zip(_lowerCAmelCase , _lowerCAmelCase ): UpperCAmelCase : Dict = set(hypo.split('''\t''' )[:k] ) UpperCAmelCase : Optional[Any] = set(reference.split('''\t''' ) ) total += 1 em += len(hypo_provenance & ref_provenance ) / k UpperCAmelCase : str = 1_0_0.0 * em / total logger.info(f"""Precision@{k}: {em: .2f}""" ) def snake_case_ ( _lowerCAmelCase : Any , _lowerCAmelCase : int , _lowerCAmelCase : Dict ) -> Optional[int]: def strip_title(_lowerCAmelCase : Optional[int] ): if title.startswith('''"''' ): UpperCAmelCase : Tuple = title[1:] if title.endswith('''"''' ): UpperCAmelCase : Optional[Any] = title[:-1] return title UpperCAmelCase : Union[str, Any] = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( _lowerCAmelCase , return_tensors='''pt''' , padding=_lowerCAmelCase , truncation=_lowerCAmelCase , )['''input_ids'''].to(args.device ) UpperCAmelCase : str = rag_model.rag.question_encoder(_lowerCAmelCase ) UpperCAmelCase : Union[str, Any] = question_enc_outputs[0] UpperCAmelCase : Any = rag_model.retriever( _lowerCAmelCase , question_enc_pool_output.cpu().detach().to(torch.floataa ).numpy() , prefix=rag_model.rag.generator.config.prefix , n_docs=rag_model.config.n_docs , return_tensors='''pt''' , ) UpperCAmelCase : int = rag_model.retriever.index.get_doc_dicts(result.doc_ids ) UpperCAmelCase : int = [] for docs in all_docs: UpperCAmelCase : Optional[int] = [strip_title(_lowerCAmelCase ) for title in docs['''title''']] provenance_strings.append('''\t'''.join(_lowerCAmelCase ) ) return provenance_strings def snake_case_ ( _lowerCAmelCase : Optional[int] , _lowerCAmelCase : Any , _lowerCAmelCase : Dict ) -> List[str]: with torch.no_grad(): UpperCAmelCase : Any = rag_model.retriever.question_encoder_tokenizer.batch_encode_plus( _lowerCAmelCase , return_tensors='''pt''' , padding=_lowerCAmelCase , truncation=_lowerCAmelCase ) UpperCAmelCase : Union[str, Any] = inputs_dict.input_ids.to(args.device ) UpperCAmelCase : Union[str, Any] = inputs_dict.attention_mask.to(args.device ) UpperCAmelCase : Optional[int] = rag_model.generate( # rag_model overwrites generate _lowerCAmelCase , attention_mask=_lowerCAmelCase , num_beams=args.num_beams , min_length=args.min_length , max_length=args.max_length , early_stopping=_lowerCAmelCase , num_return_sequences=1 , bad_words_ids=[[0, 0]] , ) UpperCAmelCase : str = rag_model.retriever.generator_tokenizer.batch_decode(_lowerCAmelCase , skip_special_tokens=_lowerCAmelCase ) if args.print_predictions: for q, a in zip(_lowerCAmelCase , _lowerCAmelCase ): logger.info('''Q: {} - A: {}'''.format(_lowerCAmelCase , _lowerCAmelCase ) ) return answers def snake_case_ ( ) -> List[Any]: UpperCAmelCase : Any = argparse.ArgumentParser() parser.add_argument( '''--model_type''' , choices=['''rag_sequence''', '''rag_token''', '''bart'''] , type=_lowerCAmelCase , help=( '''RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the''' ''' model_name_or_path''' ) , ) parser.add_argument( '''--index_name''' , default=_lowerCAmelCase , choices=['''exact''', '''compressed''', '''legacy'''] , type=_lowerCAmelCase , help='''RAG model retriever type''' , ) parser.add_argument( '''--index_path''' , default=_lowerCAmelCase , type=_lowerCAmelCase , help='''Path to the retrieval index''' , ) parser.add_argument('''--n_docs''' , default=5 , type=_lowerCAmelCase , help='''Number of retrieved docs''' ) parser.add_argument( '''--model_name_or_path''' , default=_lowerCAmelCase , type=_lowerCAmelCase , required=_lowerCAmelCase , help='''Path to pretrained checkpoints or model identifier from huggingface.co/models''' , ) parser.add_argument( '''--eval_mode''' , choices=['''e2e''', '''retrieval'''] , default='''e2e''' , type=_lowerCAmelCase , help=( '''Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates''' ''' precision@k.''' ) , ) parser.add_argument('''--k''' , default=1 , type=_lowerCAmelCase , help='''k for the precision@k calculation''' ) parser.add_argument( '''--evaluation_set''' , default=_lowerCAmelCase , type=_lowerCAmelCase , required=_lowerCAmelCase , help='''Path to a file containing evaluation samples''' , ) parser.add_argument( '''--gold_data_path''' , default=_lowerCAmelCase , type=_lowerCAmelCase , required=_lowerCAmelCase , help='''Path to a tab-separated file with gold samples''' , ) parser.add_argument( '''--gold_data_mode''' , default='''qa''' , type=_lowerCAmelCase , choices=['''qa''', '''ans'''] , help=( '''Format of the gold data file''' '''qa - a single line in the following format: question [tab] answer_list''' '''ans - a single line of the gold file contains the expected answer string''' ) , ) parser.add_argument( '''--predictions_path''' , type=_lowerCAmelCase , default='''predictions.txt''' , help='''Name of the predictions file, to be stored in the checkpoints directory''' , ) parser.add_argument( '''--eval_all_checkpoints''' , action='''store_true''' , help='''Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number''' , ) parser.add_argument( '''--eval_batch_size''' , default=8 , type=_lowerCAmelCase , help='''Batch size per GPU/CPU for evaluation.''' , ) parser.add_argument( '''--recalculate''' , help='''Recalculate predictions even if the prediction file exists''' , action='''store_true''' , ) parser.add_argument( '''--num_beams''' , default=4 , type=_lowerCAmelCase , help='''Number of beams to be used when generating answers''' , ) parser.add_argument('''--min_length''' , default=1 , type=_lowerCAmelCase , help='''Min length of the generated answers''' ) parser.add_argument('''--max_length''' , default=50 , type=_lowerCAmelCase , help='''Max length of the generated answers''' ) parser.add_argument( '''--print_predictions''' , action='''store_true''' , help='''If True, prints predictions while evaluating.''' , ) parser.add_argument( '''--print_docs''' , action='''store_true''' , help='''If True, prints docs retried while generating.''' , ) UpperCAmelCase : Any = parser.parse_args() UpperCAmelCase : str = torch.device('''cuda''' if torch.cuda.is_available() else '''cpu''' ) return args def snake_case_ ( _lowerCAmelCase : Union[str, Any] ) -> int: UpperCAmelCase : int = {} if args.model_type is None: UpperCAmelCase : Union[str, Any] = infer_model_type(args.model_name_or_path ) assert args.model_type is not None if args.model_type.startswith('''rag''' ): UpperCAmelCase : Optional[Any] = RagTokenForGeneration if args.model_type == '''rag_token''' else RagSequenceForGeneration UpperCAmelCase : Dict = args.n_docs if args.index_name is not None: UpperCAmelCase : Dict = args.index_name if args.index_path is not None: UpperCAmelCase : str = args.index_path else: UpperCAmelCase : int = BartForConditionalGeneration UpperCAmelCase : Optional[Any] = ( [f.path for f in os.scandir(args.model_name_or_path ) if f.is_dir()] if args.eval_all_checkpoints else [args.model_name_or_path] ) logger.info('''Evaluate the following checkpoints: %s''' , _lowerCAmelCase ) UpperCAmelCase : str = get_scores if args.eval_mode == '''e2e''' else get_precision_at_k UpperCAmelCase : Any = evaluate_batch_eae if args.eval_mode == '''e2e''' else evaluate_batch_retrieval for checkpoint in checkpoints: if os.path.exists(args.predictions_path ) and (not args.recalculate): logger.info('''Calculating metrics based on an existing predictions file: {}'''.format(args.predictions_path ) ) score_fn(_lowerCAmelCase , args.predictions_path , args.gold_data_path ) continue logger.info('''***** Running evaluation for {} *****'''.format(_lowerCAmelCase ) ) logger.info(''' Batch size = %d''' , args.eval_batch_size ) logger.info(''' Predictions will be stored under {}'''.format(args.predictions_path ) ) if args.model_type.startswith('''rag''' ): UpperCAmelCase : int = RagRetriever.from_pretrained(_lowerCAmelCase , **_lowerCAmelCase ) UpperCAmelCase : Optional[Any] = model_class.from_pretrained(_lowerCAmelCase , retriever=_lowerCAmelCase , **_lowerCAmelCase ) model.retriever.init_retrieval() else: UpperCAmelCase : Union[str, Any] = model_class.from_pretrained(_lowerCAmelCase , **_lowerCAmelCase ) model.to(args.device ) with open(args.evaluation_set , '''r''' ) as eval_file, open(args.predictions_path , '''w''' ) as preds_file: UpperCAmelCase : List[str] = [] for line in tqdm(_lowerCAmelCase ): questions.append(line.strip() ) if len(_lowerCAmelCase ) == args.eval_batch_size: UpperCAmelCase : Any = evaluate_batch_fn(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) preds_file.write('''\n'''.join(_lowerCAmelCase ) + '''\n''' ) preds_file.flush() UpperCAmelCase : str = [] if len(_lowerCAmelCase ) > 0: UpperCAmelCase : Optional[int] = evaluate_batch_fn(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) preds_file.write('''\n'''.join(_lowerCAmelCase ) ) preds_file.flush() score_fn(_lowerCAmelCase , args.predictions_path , args.gold_data_path ) if __name__ == "__main__": UpperCamelCase__: List[str] = get_args() main(args)
23
'''simple docstring''' import math def __lowerCamelCase ( lowerCAmelCase_ ) -> bool: _a : Optional[int] = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(lowerCAmelCase_ ) def __lowerCamelCase ( lowerCAmelCase_ = 1 / 12345 ) -> int: _a : int = 0 _a : Optional[Any] = 0 _a : int = 3 while True: _a : Tuple = (integer**2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(lowerCAmelCase_ ): _a : Union[str, Any] = int(lowerCAmelCase_ ) total_partitions += 1 if check_partition_perfect(lowerCAmelCase_ ): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return int(lowerCAmelCase_ ) integer += 1 if __name__ == "__main__": print(f"""{solution() = }""")
89
0
import logging import os import sys from dataclasses import dataclass, field from typing import Optional from seqaseq_trainer import SeqaSeqTrainer from seqaseq_training_args import SeqaSeqTrainingArguments import transformers from transformers import ( AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer, HfArgumentParser, MBartTokenizer, MBartTokenizerFast, set_seed, ) from transformers.trainer_utils import EvaluationStrategy, is_main_process from transformers.training_args import ParallelMode from utils import ( SeqaSeqDataCollator, SeqaSeqDataset, assert_all_frozen, build_compute_metrics_fn, check_output_dir, freeze_embeds, freeze_params, lmap, save_json, use_task_specific_params, write_txt_file, ) snake_case_ = logging.getLogger(__name__) @dataclass class SCREAMING_SNAKE_CASE__ : A_ : str = field( metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} ) A_ : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'Pretrained config name or path if not the same as model_name'} ) A_ : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} ) A_ : Optional[str] = field( default=_UpperCAmelCase , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , ) A_ : bool = field(default=_UpperCAmelCase , metadata={'help': 'Whether tp freeze the encoder.'} ) A_ : bool = field(default=_UpperCAmelCase , metadata={'help': 'Whether to freeze the embeddings.'} ) @dataclass class SCREAMING_SNAKE_CASE__ : A_ : str = field( metadata={'help': 'The input data dir. Should contain the .tsv files (or other data files) for the task.'} ) A_ : Optional[str] = field( default='summarization' , metadata={'help': 'Task name, summarization (or summarization_{dataset} for pegasus) or translation'} , ) A_ : Optional[int] = field( default=1_024 , metadata={ 'help': ( 'The maximum total input sequence length after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) A_ : Optional[int] = field( default=128 , metadata={ 'help': ( 'The maximum total sequence length for target text after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) A_ : Optional[int] = field( default=142 , metadata={ 'help': ( 'The maximum total sequence length for validation target text after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded. ' 'This argument is also used to override the ``max_length`` param of ``model.generate``, which is used ' 'during ``evaluate`` and ``predict``.' ) } , ) A_ : Optional[int] = field( default=142 , metadata={ 'help': ( 'The maximum total sequence length for test target text after tokenization. Sequences longer ' 'than this will be truncated, sequences shorter will be padded.' ) } , ) A_ : Optional[int] = field(default=-1 , metadata={'help': '# training examples. -1 means use all.'} ) A_ : Optional[int] = field(default=-1 , metadata={'help': '# validation examples. -1 means use all.'} ) A_ : Optional[int] = field(default=-1 , metadata={'help': '# test examples. -1 means use all.'} ) A_ : Optional[str] = field(default=_UpperCAmelCase , metadata={'help': 'Source language id for translation.'} ) A_ : Optional[str] = field(default=_UpperCAmelCase , metadata={'help': 'Target language id for translation.'} ) A_ : Optional[int] = field(default=_UpperCAmelCase , metadata={'help': '# num_beams to use for evaluation.'} ) A_ : bool = field( default=_UpperCAmelCase , metadata={'help': 'If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined.'} , ) def lowerCamelCase__ ( snake_case_ : List[Any] , snake_case_ : List[str] , snake_case_ : Dict ) -> str: logger.info(f"""***** {split} metrics *****""" ) for key in sorted(metrics.keys() ): logger.info(f""" {key} = {metrics[key]}""" ) save_json(snake_case_ , os.path.join(snake_case_ , f"""{split}_results.json""" ) ) def lowerCamelCase__ ( ) -> Optional[Any]: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. __snake_case = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith('''.json''' ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. __snake_case , __snake_case , __snake_case = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: __snake_case , __snake_case , __snake_case = parser.parse_args_into_dataclasses() check_output_dir(snake_case_ ) # Setup logging logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''' , datefmt='''%m/%d/%Y %H:%M:%S''' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s''' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() logger.info('''Training/evaluation parameters %s''' , snake_case_ ) # Set seed set_seed(training_args.seed ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. __snake_case = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) __snake_case = ('''encoder_layerdrop''', '''decoder_layerdrop''', '''dropout''', '''attention_dropout''') for p in extra_model_params: if getattr(snake_case_ , snake_case_ , snake_case_ ): assert hasattr(snake_case_ , snake_case_ ), f"""({config.__class__.__name__}) doesn't have a `{p}` attribute""" setattr(snake_case_ , snake_case_ , getattr(snake_case_ , snake_case_ ) ) __snake_case = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , ) __snake_case = AutoModelForSeqaSeqLM.from_pretrained( model_args.model_name_or_path , from_tf='''.ckpt''' in model_args.model_name_or_path , config=snake_case_ , cache_dir=model_args.cache_dir , ) # use task specific params use_task_specific_params(snake_case_ , data_args.task ) # set num_beams for evaluation if data_args.eval_beams is None: __snake_case = model.config.num_beams # set decoder_start_token_id for MBart if model.config.decoder_start_token_id is None and isinstance(snake_case_ , (MBartTokenizer, MBartTokenizerFast) ): assert ( data_args.tgt_lang is not None and data_args.src_lang is not None ), "mBart requires --tgt_lang and --src_lang" if isinstance(snake_case_ , snake_case_ ): __snake_case = tokenizer.lang_code_to_id[data_args.tgt_lang] else: __snake_case = tokenizer.convert_tokens_to_ids(data_args.tgt_lang ) if model_args.freeze_embeds: freeze_embeds(snake_case_ ) if model_args.freeze_encoder: freeze_params(model.get_encoder() ) assert_all_frozen(model.get_encoder() ) __snake_case = SeqaSeqDataset # Get datasets __snake_case = ( dataset_class( snake_case_ , type_path='''train''' , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_train else None ) __snake_case = ( dataset_class( snake_case_ , type_path='''val''' , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO else None ) __snake_case = ( dataset_class( snake_case_ , type_path='''test''' , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or '''''' , ) if training_args.do_predict else None ) # Initialize our Trainer __snake_case = ( build_compute_metrics_fn(data_args.task , snake_case_ ) if training_args.predict_with_generate else None ) __snake_case = SeqaSeqTrainer( model=snake_case_ , args=snake_case_ , data_args=snake_case_ , train_dataset=snake_case_ , eval_dataset=snake_case_ , data_collator=SeqaSeqDataCollator( snake_case_ , snake_case_ , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=snake_case_ , tokenizer=snake_case_ , ) __snake_case = {} # Training if training_args.do_train: logger.info('''*** Train ***''' ) __snake_case = trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) __snake_case = train_result.metrics __snake_case = data_args.n_train trainer.save_model() # this also saves the tokenizer if trainer.is_world_process_zero(): handle_metrics('''train''' , snake_case_ , training_args.output_dir ) all_metrics.update(snake_case_ ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , '''trainer_state.json''' ) ) # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) tokenizer.save_pretrained(training_args.output_dir ) # Evaluation if training_args.do_eval: logger.info('''*** Evaluate ***''' ) __snake_case = trainer.evaluate(metric_key_prefix='''val''' ) __snake_case = data_args.n_val __snake_case = round(metrics['''val_loss'''] , 4 ) if trainer.is_world_process_zero(): handle_metrics('''val''' , snake_case_ , training_args.output_dir ) all_metrics.update(snake_case_ ) if training_args.do_predict: logger.info('''*** Predict ***''' ) __snake_case = trainer.predict(test_dataset=snake_case_ , metric_key_prefix='''test''' ) __snake_case = test_output.metrics __snake_case = data_args.n_test if trainer.is_world_process_zero(): __snake_case = round(metrics['''test_loss'''] , 4 ) handle_metrics('''test''' , snake_case_ , training_args.output_dir ) all_metrics.update(snake_case_ ) if training_args.predict_with_generate: __snake_case = tokenizer.batch_decode( test_output.predictions , skip_special_tokens=snake_case_ , clean_up_tokenization_spaces=snake_case_ ) __snake_case = lmap(str.strip , snake_case_ ) write_txt_file(snake_case_ , os.path.join(training_args.output_dir , '''test_generations.txt''' ) ) if trainer.is_world_process_zero(): save_json(snake_case_ , os.path.join(training_args.output_dir , '''all_results.json''' ) ) return all_metrics def lowerCamelCase__ ( snake_case_ : Optional[Any] ) -> Tuple: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
24
'''simple docstring''' import argparse import json import torch from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=1 ) -> Dict: if n_shave_prefix_segments >= 0: return ".".join(path.split('.' )[n_shave_prefix_segments:] ) else: return ".".join(path.split('.' )[:n_shave_prefix_segments] ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=0 ) -> Tuple: _a : Any = [] for old_item in old_list: _a : Union[str, Any] = old_item.replace('in_layers.0' , 'norm1' ) _a : Optional[int] = new_item.replace('in_layers.2' , 'conv1' ) _a : str = new_item.replace('out_layers.0' , 'norm2' ) _a : List[str] = new_item.replace('out_layers.3' , 'conv2' ) _a : str = new_item.replace('emb_layers.1' , 'time_emb_proj' ) _a : Tuple = new_item.replace('skip_connection' , 'conv_shortcut' ) _a : Any = shave_segments(lowerCAmelCase_ , n_shave_prefix_segments=lowerCAmelCase_ ) mapping.append({'old': old_item, 'new': new_item} ) return mapping def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=0 ) -> Any: _a : List[str] = [] for old_item in old_list: _a : List[Any] = old_item _a : Optional[int] = new_item.replace('norm.weight' , 'group_norm.weight' ) _a : Optional[Any] = new_item.replace('norm.bias' , 'group_norm.bias' ) _a : Any = new_item.replace('proj_out.weight' , 'proj_attn.weight' ) _a : Optional[Any] = new_item.replace('proj_out.bias' , 'proj_attn.bias' ) _a : Optional[int] = shave_segments(lowerCAmelCase_ , n_shave_prefix_segments=lowerCAmelCase_ ) mapping.append({'old': old_item, 'new': new_item} ) return mapping def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None , lowerCAmelCase_=None , lowerCAmelCase_=None ) -> Any: assert isinstance(lowerCAmelCase_ , lowerCAmelCase_ ), "Paths should be a list of dicts containing 'old' and 'new' keys." # Splits the attention layers into three variables. if attention_paths_to_split is not None: for path, path_map in attention_paths_to_split.items(): _a : Optional[Any] = old_checkpoint[path] _a : Optional[Any] = old_tensor.shape[0] // 3 _a : Any = (-1, channels) if len(old_tensor.shape ) == 3 else (-1) _a : int = old_tensor.shape[0] // config['num_head_channels'] // 3 _a : str = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:] ) _a , _a , _a : Tuple = old_tensor.split(channels // num_heads , dim=1 ) _a : Dict = query.reshape(lowerCAmelCase_ ) _a : str = key.reshape(lowerCAmelCase_ ) _a : Optional[int] = value.reshape(lowerCAmelCase_ ) for path in paths: _a : Dict = path['new'] # These have already been assigned if attention_paths_to_split is not None and new_path in attention_paths_to_split: continue # Global renaming happens here _a : Any = new_path.replace('middle_block.0' , 'mid_block.resnets.0' ) _a : str = new_path.replace('middle_block.1' , 'mid_block.attentions.0' ) _a : Union[str, Any] = new_path.replace('middle_block.2' , 'mid_block.resnets.1' ) if additional_replacements is not None: for replacement in additional_replacements: _a : int = new_path.replace(replacement['old'] , replacement['new'] ) # proj_attn.weight has to be converted from conv 1D to linear if "proj_attn.weight" in new_path: _a : List[str] = old_checkpoint[path['old']][:, :, 0] else: _a : Dict = old_checkpoint[path['old']] def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> List[Any]: _a : Optional[int] = {} _a : Dict = checkpoint['time_embed.0.weight'] _a : Tuple = checkpoint['time_embed.0.bias'] _a : Union[str, Any] = checkpoint['time_embed.2.weight'] _a : List[str] = checkpoint['time_embed.2.bias'] _a : List[str] = checkpoint['input_blocks.0.0.weight'] _a : Union[str, Any] = checkpoint['input_blocks.0.0.bias'] _a : Optional[int] = checkpoint['out.0.weight'] _a : int = checkpoint['out.0.bias'] _a : List[str] = checkpoint['out.2.weight'] _a : Optional[int] = checkpoint['out.2.bias'] # Retrieves the keys for the input blocks only _a : Optional[int] = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'input_blocks' in layer} ) _a : Dict = { layer_id: [key for key in checkpoint if f"""input_blocks.{layer_id}""" in key] for layer_id in range(lowerCAmelCase_ ) } # Retrieves the keys for the middle blocks only _a : List[Any] = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'middle_block' in layer} ) _a : Union[str, Any] = { layer_id: [key for key in checkpoint if f"""middle_block.{layer_id}""" in key] for layer_id in range(lowerCAmelCase_ ) } # Retrieves the keys for the output blocks only _a : Optional[int] = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'output_blocks' in layer} ) _a : str = { layer_id: [key for key in checkpoint if f"""output_blocks.{layer_id}""" in key] for layer_id in range(lowerCAmelCase_ ) } for i in range(1 , lowerCAmelCase_ ): _a : List[Any] = (i - 1) // (config['num_res_blocks'] + 1) _a : Optional[int] = (i - 1) % (config['num_res_blocks'] + 1) _a : Optional[int] = [key for key in input_blocks[i] if f"""input_blocks.{i}.0""" in key] _a : Optional[Any] = [key for key in input_blocks[i] if f"""input_blocks.{i}.1""" in key] if f"""input_blocks.{i}.0.op.weight""" in checkpoint: _a : List[Any] = checkpoint[ f"""input_blocks.{i}.0.op.weight""" ] _a : Union[str, Any] = checkpoint[ f"""input_blocks.{i}.0.op.bias""" ] continue _a : Any = renew_resnet_paths(lowerCAmelCase_ ) _a : List[str] = {'old': f"""input_blocks.{i}.0""", 'new': f"""down_blocks.{block_id}.resnets.{layer_in_block_id}"""} _a : Optional[Any] = {'old': 'resnets.2.op', 'new': 'downsamplers.0.op'} assign_to_checkpoint( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , additional_replacements=[meta_path, resnet_op] , config=lowerCAmelCase_ ) if len(lowerCAmelCase_ ): _a : List[str] = renew_attention_paths(lowerCAmelCase_ ) _a : List[Any] = { 'old': f"""input_blocks.{i}.1""", 'new': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}""", } _a : Optional[Any] = { f"""input_blocks.{i}.1.qkv.bias""": { 'key': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias""", 'query': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias""", 'value': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias""", }, f"""input_blocks.{i}.1.qkv.weight""": { 'key': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight""", 'query': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight""", 'value': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight""", }, } assign_to_checkpoint( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , additional_replacements=[meta_path] , attention_paths_to_split=lowerCAmelCase_ , config=lowerCAmelCase_ , ) _a : str = middle_blocks[0] _a : Tuple = middle_blocks[1] _a : Any = middle_blocks[2] _a : List[Any] = renew_resnet_paths(lowerCAmelCase_ ) assign_to_checkpoint(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , config=lowerCAmelCase_ ) _a : Any = renew_resnet_paths(lowerCAmelCase_ ) assign_to_checkpoint(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , config=lowerCAmelCase_ ) _a : int = renew_attention_paths(lowerCAmelCase_ ) _a : int = { 'middle_block.1.qkv.bias': { 'key': 'mid_block.attentions.0.key.bias', 'query': 'mid_block.attentions.0.query.bias', 'value': 'mid_block.attentions.0.value.bias', }, 'middle_block.1.qkv.weight': { 'key': 'mid_block.attentions.0.key.weight', 'query': 'mid_block.attentions.0.query.weight', 'value': 'mid_block.attentions.0.value.weight', }, } assign_to_checkpoint( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , attention_paths_to_split=lowerCAmelCase_ , config=lowerCAmelCase_ ) for i in range(lowerCAmelCase_ ): _a : List[str] = i // (config['num_res_blocks'] + 1) _a : Any = i % (config['num_res_blocks'] + 1) _a : Union[str, Any] = [shave_segments(lowerCAmelCase_ , 2 ) for name in output_blocks[i]] _a : Optional[Any] = {} for layer in output_block_layers: _a , _a : str = layer.split('.' )[0], shave_segments(lowerCAmelCase_ , 1 ) if layer_id in output_block_list: output_block_list[layer_id].append(lowerCAmelCase_ ) else: _a : str = [layer_name] if len(lowerCAmelCase_ ) > 1: _a : str = [key for key in output_blocks[i] if f"""output_blocks.{i}.0""" in key] _a : Optional[Any] = [key for key in output_blocks[i] if f"""output_blocks.{i}.1""" in key] _a : Dict = renew_resnet_paths(lowerCAmelCase_ ) _a : str = renew_resnet_paths(lowerCAmelCase_ ) _a : Optional[int] = {'old': f"""output_blocks.{i}.0""", 'new': f"""up_blocks.{block_id}.resnets.{layer_in_block_id}"""} assign_to_checkpoint(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , additional_replacements=[meta_path] , config=lowerCAmelCase_ ) if ["conv.weight", "conv.bias"] in output_block_list.values(): _a : List[Any] = list(output_block_list.values() ).index(['conv.weight', 'conv.bias'] ) _a : Tuple = checkpoint[ f"""output_blocks.{i}.{index}.conv.weight""" ] _a : List[str] = checkpoint[ f"""output_blocks.{i}.{index}.conv.bias""" ] # Clear attentions as they have been attributed above. if len(lowerCAmelCase_ ) == 2: _a : Union[str, Any] = [] if len(lowerCAmelCase_ ): _a : Tuple = renew_attention_paths(lowerCAmelCase_ ) _a : str = { 'old': f"""output_blocks.{i}.1""", 'new': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}""", } _a : List[Any] = { f"""output_blocks.{i}.1.qkv.bias""": { 'key': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias""", 'query': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias""", 'value': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias""", }, f"""output_blocks.{i}.1.qkv.weight""": { 'key': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight""", 'query': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight""", 'value': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight""", }, } assign_to_checkpoint( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , additional_replacements=[meta_path] , attention_paths_to_split=to_split if any('qkv' in key for key in attentions ) else None , config=lowerCAmelCase_ , ) else: _a : List[Any] = renew_resnet_paths(lowerCAmelCase_ , n_shave_prefix_segments=1 ) for path in resnet_0_paths: _a : int = '.'.join(['output_blocks', str(lowerCAmelCase_ ), path['old']] ) _a : Union[str, Any] = '.'.join(['up_blocks', str(lowerCAmelCase_ ), 'resnets', str(lowerCAmelCase_ ), path['new']] ) _a : Union[str, Any] = checkpoint[old_path] return new_checkpoint if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the architecture.''', ) parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') __lowerCAmelCase = parser.parse_args() __lowerCAmelCase = torch.load(args.checkpoint_path) with open(args.config_file) as f: __lowerCAmelCase = json.loads(f.read()) __lowerCAmelCase = convert_ldm_checkpoint(checkpoint, config) if "ldm" in config: del config["ldm"] __lowerCAmelCase = UNetaDModel(**config) model.load_state_dict(converted_checkpoint) try: __lowerCAmelCase = DDPMScheduler.from_config('''/'''.join(args.checkpoint_path.split('''/''')[:-1])) __lowerCAmelCase = VQModel.from_pretrained('''/'''.join(args.checkpoint_path.split('''/''')[:-1])) __lowerCAmelCase = LDMPipeline(unet=model, scheduler=scheduler, vae=vqvae) pipe.save_pretrained(args.dump_path) except: # noqa: E722 model.save_pretrained(args.dump_path)
89
0
"""simple docstring""" from __future__ import annotations from random import random from typing import Generic, TypeVar UpperCAmelCase__ : Optional[int] = TypeVar('KT') UpperCAmelCase__ : Any = TypeVar('VT') class lowerCAmelCase_ (Generic[KT, VT] ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE__ = "root" , SCREAMING_SNAKE_CASE__ = None ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = key SCREAMING_SNAKE_CASE__ : Dict = value SCREAMING_SNAKE_CASE__ : list[Node[KT, VT]] = [] def __repr__(self ) -> str: """simple docstring""" return F'''Node({self.key}: {self.value})''' @property def __magic_name__ (self ) -> int: """simple docstring""" return len(self.forward ) class lowerCAmelCase_ (Generic[KT, VT] ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE__ = 0.5 , SCREAMING_SNAKE_CASE__ = 16 ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Node[KT, VT] = Node[KT, VT]() SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 SCREAMING_SNAKE_CASE__ : Tuple = p SCREAMING_SNAKE_CASE__ : List[Any] = max_level def __str__(self ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = list(self ) if len(SCREAMING_SNAKE_CASE__ ) == 0: return F'''SkipList(level={self.level})''' SCREAMING_SNAKE_CASE__ : Dict = max((len(str(SCREAMING_SNAKE_CASE__ ) ) for item in items) , default=4 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = max(SCREAMING_SNAKE_CASE__ , 4 ) + 4 SCREAMING_SNAKE_CASE__ : Tuple = self.head SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : List[Any] = node.forward.copy() lines.append(F'''[{node.key}]'''.ljust(SCREAMING_SNAKE_CASE__ , """-""" ) + """* """ * len(SCREAMING_SNAKE_CASE__ ) ) lines.append(""" """ * label_size + """| """ * len(SCREAMING_SNAKE_CASE__ ) ) while len(node.forward ) != 0: SCREAMING_SNAKE_CASE__ : Union[str, Any] = node.forward[0] lines.append( F'''[{node.key}]'''.ljust(SCREAMING_SNAKE_CASE__ , """-""" ) + """ """.join(str(n.key ) if n.key == node.key else """|""" for n in forwards ) ) lines.append(""" """ * label_size + """| """ * len(SCREAMING_SNAKE_CASE__ ) ) SCREAMING_SNAKE_CASE__ : List[Any] = node.forward lines.append("""None""".ljust(SCREAMING_SNAKE_CASE__ ) + """* """ * len(SCREAMING_SNAKE_CASE__ ) ) return F'''SkipList(level={self.level})\n''' + "\n".join(SCREAMING_SNAKE_CASE__ ) def __iter__(self ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.head while len(node.forward ) != 0: yield node.forward[0].key SCREAMING_SNAKE_CASE__ : Tuple = node.forward[0] def __magic_name__ (self ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = 1 while random() < self.p and level < self.max_level: level += 1 return level def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> tuple[Node[KT, VT] | None, list[Node[KT, VT]]]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : List[str] = self.head for i in reversed(range(self.level ) ): # i < node.level - When node level is lesser than `i` decrement `i`. # node.forward[i].key < key - Jumping to node with key value higher # or equal to searched key would result # in skipping searched key. while i < node.level and node.forward[i].key < key: SCREAMING_SNAKE_CASE__ : str = node.forward[i] # Each leftmost node (relative to searched node) will potentially have to # be updated. update_vector.append(SCREAMING_SNAKE_CASE__ ) update_vector.reverse() # Note that we were inserting values in reverse order. # len(node.forward) != 0 - If current node doesn't contain any further # references then searched key is not present. # node.forward[0].key == key - Next node key should be equal to search key # if key is present. if len(node.forward ) != 0 and node.forward[0].key == key: return node.forward[0], update_vector else: return None, update_vector def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self._locate_node(SCREAMING_SNAKE_CASE__ ) if node is not None: for i, update_node in enumerate(SCREAMING_SNAKE_CASE__ ): # Remove or replace all references to removed node. if update_node.level > i and update_node.forward[i].key == key: if node.level > i: SCREAMING_SNAKE_CASE__ : Dict = node.forward[i] else: SCREAMING_SNAKE_CASE__ : Optional[Any] = update_node.forward[:i] def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = self._locate_node(SCREAMING_SNAKE_CASE__ ) if node is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = value else: SCREAMING_SNAKE_CASE__ : str = self.random_level() if level > self.level: # After level increase we have to add additional nodes to head. for _ in range(self.level - 1 , SCREAMING_SNAKE_CASE__ ): update_vector.append(self.head ) SCREAMING_SNAKE_CASE__ : Optional[Any] = level SCREAMING_SNAKE_CASE__ : int = Node(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for i, update_node in enumerate(update_vector[:level] ): # Change references to pass through new node. if update_node.level > i: new_node.forward.append(update_node.forward[i] ) if update_node.level < i + 1: update_node.forward.append(SCREAMING_SNAKE_CASE__ ) else: SCREAMING_SNAKE_CASE__ : Dict = new_node def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> VT | None: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self._locate_node(SCREAMING_SNAKE_CASE__ ) if node is not None: return node.value return None def lowercase_ ( ): SCREAMING_SNAKE_CASE__ : List[Any] = SkipList() skip_list.insert("""Key1""" ,3 ) skip_list.insert("""Key2""" ,12 ) skip_list.insert("""Key3""" ,41 ) skip_list.insert("""Key4""" ,-19 ) SCREAMING_SNAKE_CASE__ : Optional[int] = skip_list.head SCREAMING_SNAKE_CASE__ : Tuple = {} while node.level != 0: SCREAMING_SNAKE_CASE__ : List[Any] = node.forward[0] SCREAMING_SNAKE_CASE__ : int = node.value assert len(_snake_case ) == 4 assert all_values["Key1"] == 3 assert all_values["Key2"] == 12 assert all_values["Key3"] == 41 assert all_values["Key4"] == -19 def lowercase_ ( ): SCREAMING_SNAKE_CASE__ : str = SkipList() skip_list.insert("""Key1""" ,10 ) skip_list.insert("""Key1""" ,12 ) skip_list.insert("""Key5""" ,7 ) skip_list.insert("""Key7""" ,10 ) skip_list.insert("""Key10""" ,5 ) skip_list.insert("""Key7""" ,7 ) skip_list.insert("""Key5""" ,5 ) skip_list.insert("""Key10""" ,10 ) SCREAMING_SNAKE_CASE__ : List[str] = skip_list.head SCREAMING_SNAKE_CASE__ : Dict = {} while node.level != 0: SCREAMING_SNAKE_CASE__ : List[str] = node.forward[0] SCREAMING_SNAKE_CASE__ : Tuple = node.value if len(_snake_case ) != 4: print() assert len(_snake_case ) == 4 assert all_values["Key1"] == 12 assert all_values["Key7"] == 7 assert all_values["Key5"] == 5 assert all_values["Key10"] == 10 def lowercase_ ( ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = SkipList() assert skip_list.find("""Some key""" ) is None def lowercase_ ( ): SCREAMING_SNAKE_CASE__ : str = SkipList() skip_list.insert("""Key2""" ,20 ) assert skip_list.find("""Key2""" ) == 20 skip_list.insert("""Some Key""" ,10 ) skip_list.insert("""Key2""" ,8 ) skip_list.insert("""V""" ,13 ) assert skip_list.find("""Y""" ) is None assert skip_list.find("""Key2""" ) == 8 assert skip_list.find("""Some Key""" ) == 10 assert skip_list.find("""V""" ) == 13 def lowercase_ ( ): SCREAMING_SNAKE_CASE__ : Optional[int] = SkipList() skip_list.delete("""Some key""" ) assert len(skip_list.head.forward ) == 0 def lowercase_ ( ): SCREAMING_SNAKE_CASE__ : Dict = SkipList() skip_list.insert("""Key1""" ,12 ) skip_list.insert("""V""" ,13 ) skip_list.insert("""X""" ,14 ) skip_list.insert("""Key2""" ,15 ) skip_list.delete("""V""" ) skip_list.delete("""Key2""" ) assert skip_list.find("""V""" ) is None assert skip_list.find("""Key2""" ) is None def lowercase_ ( ): SCREAMING_SNAKE_CASE__ : Any = SkipList() skip_list.insert("""Key1""" ,12 ) skip_list.insert("""V""" ,13 ) skip_list.insert("""X""" ,14 ) skip_list.insert("""Key2""" ,15 ) skip_list.delete("""V""" ) assert skip_list.find("""V""" ) is None assert skip_list.find("""X""" ) == 14 assert skip_list.find("""Key1""" ) == 12 assert skip_list.find("""Key2""" ) == 15 skip_list.delete("""X""" ) assert skip_list.find("""V""" ) is None assert skip_list.find("""X""" ) is None assert skip_list.find("""Key1""" ) == 12 assert skip_list.find("""Key2""" ) == 15 skip_list.delete("""Key1""" ) assert skip_list.find("""V""" ) is None assert skip_list.find("""X""" ) is None assert skip_list.find("""Key1""" ) is None assert skip_list.find("""Key2""" ) == 15 skip_list.delete("""Key2""" ) assert skip_list.find("""V""" ) is None assert skip_list.find("""X""" ) is None assert skip_list.find("""Key1""" ) is None assert skip_list.find("""Key2""" ) is None def lowercase_ ( ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = SkipList() skip_list.insert("""Key1""" ,12 ) skip_list.insert("""V""" ,13 ) skip_list.insert("""X""" ,142 ) skip_list.insert("""Key2""" ,15 ) skip_list.delete("""X""" ) def traverse_keys(_snake_case ): yield node.key for forward_node in node.forward: yield from traverse_keys(_snake_case ) assert len(set(traverse_keys(skip_list.head ) ) ) == 4 def lowercase_ ( ): def is_sorted(_snake_case ): return all(next_item >= item for item, next_item in zip(_snake_case ,lst[1:] ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = SkipList() for i in range(10 ): skip_list.insert(_snake_case ,_snake_case ) assert is_sorted(list(_snake_case ) ) skip_list.delete(5 ) skip_list.delete(8 ) skip_list.delete(2 ) assert is_sorted(list(_snake_case ) ) skip_list.insert(-12 ,-12 ) skip_list.insert(77 ,77 ) assert is_sorted(list(_snake_case ) ) def lowercase_ ( ): for _ in range(100 ): # Repeat test 100 times due to the probabilistic nature of skip list # random values == random bugs test_insert() test_insert_overrides_existing_value() test_searching_empty_list_returns_none() test_search() test_deleting_item_from_empty_list_do_nothing() test_deleted_items_are_not_founded_by_find_method() test_delete_removes_only_given_key() test_delete_doesnt_leave_dead_nodes() test_iter_always_yields_sorted_values() def lowercase_ ( ): SCREAMING_SNAKE_CASE__ : List[str] = SkipList() skip_list.insert(2 ,"""2""" ) skip_list.insert(4 ,"""4""" ) skip_list.insert(6 ,"""4""" ) skip_list.insert(4 ,"""5""" ) skip_list.insert(8 ,"""4""" ) skip_list.insert(9 ,"""4""" ) skip_list.delete(4 ) print(_snake_case ) if __name__ == "__main__": import doctest doctest.testmod() main()
25
'''simple docstring''' import datetime import platform import subprocess from typing import Optional, Tuple, Union import numpy as np def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> np.array: _a : Optional[int] = f"""{sampling_rate}""" _a : Any = '1' _a : Optional[int] = 'f32le' _a : Any = [ 'ffmpeg', '-i', 'pipe:0', '-ac', ac, '-ar', ar, '-f', format_for_conversion, '-hide_banner', '-loglevel', 'quiet', 'pipe:1', ] try: with subprocess.Popen(lowerCAmelCase_ , stdin=subprocess.PIPE , stdout=subprocess.PIPE ) as ffmpeg_process: _a : int = ffmpeg_process.communicate(lowerCAmelCase_ ) except FileNotFoundError as error: raise ValueError('ffmpeg was not found but is required to load audio files from filename' ) from error _a : int = output_stream[0] _a : List[str] = np.frombuffer(lowerCAmelCase_ , np.floataa ) if audio.shape[0] == 0: raise ValueError('Malformed soundfile' ) return audio def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = "f32le" , ) -> Union[str, Any]: _a : List[str] = f"""{sampling_rate}""" _a : List[str] = '1' if format_for_conversion == "s16le": _a : List[Any] = 2 elif format_for_conversion == "f32le": _a : Dict = 4 else: raise ValueError(f"""Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`""" ) _a : Any = platform.system() if system == "Linux": _a : Union[str, Any] = 'alsa' _a : Union[str, Any] = 'default' elif system == "Darwin": _a : Any = 'avfoundation' _a : Optional[int] = ':0' elif system == "Windows": _a : str = 'dshow' _a : Tuple = 'default' _a : str = [ 'ffmpeg', '-f', format_, '-i', input_, '-ac', ac, '-ar', ar, '-f', format_for_conversion, '-fflags', 'nobuffer', '-hide_banner', '-loglevel', 'quiet', 'pipe:1', ] _a : Any = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample _a : Union[str, Any] = _ffmpeg_stream(lowerCAmelCase_ , lowerCAmelCase_ ) for item in iterator: yield item def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = "f32le" , ) -> str: if stream_chunk_s is not None: _a : str = stream_chunk_s else: _a : List[str] = chunk_length_s _a : int = ffmpeg_microphone(lowerCAmelCase_ , lowerCAmelCase_ , format_for_conversion=lowerCAmelCase_ ) if format_for_conversion == "s16le": _a : Optional[Any] = np.intaa _a : List[Any] = 2 elif format_for_conversion == "f32le": _a : Tuple = np.floataa _a : Any = 4 else: raise ValueError(f"""Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`""" ) if stride_length_s is None: _a : str = chunk_length_s / 6 _a : Any = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample if isinstance(lowerCAmelCase_ , (int, float) ): _a : List[str] = [stride_length_s, stride_length_s] _a : str = int(round(sampling_rate * stride_length_s[0] ) ) * size_of_sample _a : List[str] = int(round(sampling_rate * stride_length_s[1] ) ) * size_of_sample _a : Any = datetime.datetime.now() _a : Dict = datetime.timedelta(seconds=lowerCAmelCase_ ) for item in chunk_bytes_iter(lowerCAmelCase_ , lowerCAmelCase_ , stride=(stride_left, stride_right) , stream=lowerCAmelCase_ ): # Put everything back in numpy scale _a : List[Any] = np.frombuffer(item['raw'] , dtype=lowerCAmelCase_ ) _a : List[str] = ( item['stride'][0] // size_of_sample, item['stride'][1] // size_of_sample, ) _a : Union[str, Any] = sampling_rate audio_time += delta if datetime.datetime.now() > audio_time + 10 * delta: # We're late !! SKIP continue yield item def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = False ) -> List[Any]: _a : Tuple = B'' _a , _a : str = stride if stride_left + stride_right >= chunk_len: raise ValueError( f"""Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}""" ) _a : Optional[int] = 0 for raw in iterator: acc += raw if stream and len(lowerCAmelCase_ ) < chunk_len: _a : str = (_stride_left, 0) yield {"raw": acc[:chunk_len], "stride": stride, "partial": True} else: while len(lowerCAmelCase_ ) >= chunk_len: # We are flushing the accumulator _a : Union[str, Any] = (_stride_left, stride_right) _a : Dict = {'raw': acc[:chunk_len], 'stride': stride} if stream: _a : List[str] = False yield item _a : int = stride_left _a : List[Any] = acc[chunk_len - stride_left - stride_right :] # Last chunk if len(lowerCAmelCase_ ) > stride_left: _a : str = {'raw': acc, 'stride': (_stride_left, 0)} if stream: _a : str = False yield item def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> Tuple: _a : Optional[Any] = 2**24 # 16Mo try: with subprocess.Popen(lowerCAmelCase_ , stdout=subprocess.PIPE , bufsize=lowerCAmelCase_ ) as ffmpeg_process: while True: _a : Any = ffmpeg_process.stdout.read(lowerCAmelCase_ ) if raw == b"": break yield raw except FileNotFoundError as error: raise ValueError('ffmpeg was not found but is required to stream audio files from filename' ) from error
89
0
import shutil import tempfile import unittest import numpy as np import pytest from transformers.testing_utils import require_vision from transformers.utils import is_vision_available if is_vision_available(): from PIL import Image from transformers import ( AutoProcessor, BertTokenizerFast, BlipImageProcessor, GPTaTokenizer, InstructBlipProcessor, PreTrainedTokenizerFast, ) @require_vision class lowercase ( unittest.TestCase ): def a__ ( self ) -> Optional[Any]: _A : str = tempfile.mkdtemp() _A : List[Any] = BlipImageProcessor() _A : Optional[Any] = GPTaTokenizer.from_pretrained("""hf-internal-testing/tiny-random-GPT2Model""" ) _A : Tuple = BertTokenizerFast.from_pretrained("""hf-internal-testing/tiny-random-bert""" ) _A : Any = InstructBlipProcessor(_a , _a , _a ) processor.save_pretrained(self.tmpdirname ) def a__ ( self , **_a ) -> Optional[Any]: return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).tokenizer def a__ ( self , **_a ) -> int: return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).image_processor def a__ ( self , **_a ) -> Any: return AutoProcessor.from_pretrained(self.tmpdirname , **_a ).qformer_tokenizer def a__ ( self ) -> int: shutil.rmtree(self.tmpdirname ) def a__ ( self ) -> Optional[Any]: _A : int = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] _A : Any = [Image.fromarray(np.moveaxis(_a , 0 , -1 ) ) for x in image_inputs] return image_inputs def a__ ( self ) -> Union[str, Any]: _A : Tuple = InstructBlipProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() , qformer_tokenizer=self.get_qformer_tokenizer() , ) processor.save_pretrained(self.tmpdirname ) _A : Union[str, Any] = self.get_tokenizer(bos_token="""(BOS)""" , eos_token="""(EOS)""" ) _A : Tuple = self.get_image_processor(do_normalize=_a , padding_value=1.0 ) _A : Tuple = InstructBlipProcessor.from_pretrained( self.tmpdirname , bos_token="""(BOS)""" , eos_token="""(EOS)""" , do_normalize=_a , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _a ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _a ) self.assertIsInstance(processor.qformer_tokenizer , _a ) def a__ ( self ) -> Dict: _A : int = self.get_image_processor() _A : Dict = self.get_tokenizer() _A : Dict = self.get_qformer_tokenizer() _A : int = InstructBlipProcessor( tokenizer=_a , image_processor=_a , qformer_tokenizer=_a ) _A : Optional[Any] = self.prepare_image_inputs() _A : List[Any] = image_processor(_a , return_tensors="""np""" ) _A : str = processor(images=_a , return_tensors="""np""" ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def a__ ( self ) -> Union[str, Any]: _A : Optional[int] = self.get_image_processor() _A : Optional[int] = self.get_tokenizer() _A : List[Any] = self.get_qformer_tokenizer() _A : List[Any] = InstructBlipProcessor( tokenizer=_a , image_processor=_a , qformer_tokenizer=_a ) _A : Optional[int] = """lower newer""" _A : List[str] = processor(text=_a ) _A : str = tokenizer(_a , return_token_type_ids=_a ) _A : List[str] = qformer_tokenizer(_a , return_token_type_ids=_a ) for key in encoded_tokens.keys(): self.assertListEqual(encoded_tokens[key] , encoded_processor[key] ) for key in encoded_tokens_qformer.keys(): self.assertListEqual(encoded_tokens_qformer[key] , encoded_processor["""qformer_""" + key] ) def a__ ( self ) -> List[str]: _A : Any = self.get_image_processor() _A : List[str] = self.get_tokenizer() _A : Dict = self.get_qformer_tokenizer() _A : List[str] = InstructBlipProcessor( tokenizer=_a , image_processor=_a , qformer_tokenizer=_a ) _A : Tuple = """lower newer""" _A : Optional[int] = self.prepare_image_inputs() _A : Any = processor(text=_a , images=_a ) self.assertListEqual( list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """qformer_input_ids""", """qformer_attention_mask""", """pixel_values"""] , ) # test if it raises when no input is passed with pytest.raises(_a ): processor() def a__ ( self ) -> Dict: _A : Dict = self.get_image_processor() _A : Any = self.get_tokenizer() _A : str = self.get_qformer_tokenizer() _A : int = InstructBlipProcessor( tokenizer=_a , image_processor=_a , qformer_tokenizer=_a ) _A : Tuple = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] _A : List[str] = processor.batch_decode(_a ) _A : Optional[Any] = tokenizer.batch_decode(_a ) self.assertListEqual(_a , _a ) def a__ ( self ) -> str: _A : List[Any] = self.get_image_processor() _A : Optional[int] = self.get_tokenizer() _A : int = self.get_qformer_tokenizer() _A : List[Any] = InstructBlipProcessor( tokenizer=_a , image_processor=_a , qformer_tokenizer=_a ) _A : Dict = """lower newer""" _A : int = self.prepare_image_inputs() _A : int = processor(text=_a , images=_a ) self.assertListEqual( list(inputs.keys() ) , ["""input_ids""", """attention_mask""", """qformer_input_ids""", """qformer_attention_mask""", """pixel_values"""] , )
26
'''simple docstring''' __lowerCAmelCase = { '''A''': ['''B''', '''C''', '''E'''], '''B''': ['''A''', '''D''', '''E'''], '''C''': ['''A''', '''F''', '''G'''], '''D''': ['''B'''], '''E''': ['''A''', '''B''', '''D'''], '''F''': ['''C'''], '''G''': ['''C'''], } def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> list[str]: _a : List[Any] = set() # keep track of all the paths to be checked _a : Any = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue _a : Tuple = queue.pop(0 ) # get the last node from the path _a : Tuple = path[-1] if node not in explored: _a : Optional[Any] = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: _a : Any = list(lowerCAmelCase_ ) new_path.append(lowerCAmelCase_ ) queue.append(lowerCAmelCase_ ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(lowerCAmelCase_ ) # in case there's no path between the 2 nodes return [] def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> int: if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 _a : Optional[int] = [start] _a : Dict = set(lowerCAmelCase_ ) # Keep tab on distances from `start` node. _a : Dict = {start: 0, target: -1} while queue: _a : List[str] = queue.pop(0 ) if node == target: _a : Any = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(lowerCAmelCase_ ) queue.append(lowerCAmelCase_ ) _a : Any = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, '''G''', '''D''')) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, '''G''', '''D''')) # returns 4
89
0
'''simple docstring''' import os import unicodedata from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging __lowercase : str = logging.get_logger(__name__) __lowercase : int = {'vocab_file': 'spiece.model'} __lowercase : int = { 'vocab_file': { 'albert-base-v1': 'https://huggingface.co/albert-base-v1/resolve/main/spiece.model', 'albert-large-v1': 'https://huggingface.co/albert-large-v1/resolve/main/spiece.model', 'albert-xlarge-v1': 'https://huggingface.co/albert-xlarge-v1/resolve/main/spiece.model', 'albert-xxlarge-v1': 'https://huggingface.co/albert-xxlarge-v1/resolve/main/spiece.model', 'albert-base-v2': 'https://huggingface.co/albert-base-v2/resolve/main/spiece.model', 'albert-large-v2': 'https://huggingface.co/albert-large-v2/resolve/main/spiece.model', 'albert-xlarge-v2': 'https://huggingface.co/albert-xlarge-v2/resolve/main/spiece.model', 'albert-xxlarge-v2': 'https://huggingface.co/albert-xxlarge-v2/resolve/main/spiece.model', } } __lowercase : Union[str, Any] = { 'albert-base-v1': 5_12, 'albert-large-v1': 5_12, 'albert-xlarge-v1': 5_12, 'albert-xxlarge-v1': 5_12, 'albert-base-v2': 5_12, 'albert-large-v2': 5_12, 'albert-xlarge-v2': 5_12, 'albert-xxlarge-v2': 5_12, } __lowercase : Any = '▁' class __UpperCamelCase ( lowerCAmelCase_ ): A_ = VOCAB_FILES_NAMES A_ = PRETRAINED_VOCAB_FILES_MAP A_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__( self , __a , __a=True , __a=True , __a=False , __a="[CLS]" , __a="[SEP]" , __a="<unk>" , __a="[SEP]" , __a="<pad>" , __a="[CLS]" , __a="[MASK]" , __a = None , **__a , ): '''simple docstring''' __a : List[str] = ( AddedToken(__a , lstrip=__a , rstrip=__a , normalized=__a ) if isinstance(__a , __a ) else mask_token ) __a : Dict = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=__a , remove_space=__a , keep_accents=__a , bos_token=__a , eos_token=__a , unk_token=__a , sep_token=__a , pad_token=__a , cls_token=__a , mask_token=__a , sp_model_kwargs=self.sp_model_kwargs , **__a , ) __a : Any = do_lower_case __a : Any = remove_space __a : Optional[Any] = keep_accents __a : Union[str, Any] = vocab_file __a : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__a ) @property def __UpperCAmelCase ( self ): '''simple docstring''' return len(self.sp_model ) def __UpperCAmelCase ( self ): '''simple docstring''' __a : Optional[int] = {self.convert_ids_to_tokens(__a ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ): '''simple docstring''' __a : List[Any] = self.__dict__.copy() __a : List[str] = None return state def __setstate__( self , __a ): '''simple docstring''' __a : Optional[Any] = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): __a : Optional[Any] = {} __a : Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' if self.remove_space: __a : Union[str, Any] = ' '.join(inputs.strip().split() ) else: __a : Dict = inputs __a : Optional[Any] = outputs.replace('``' , '"' ).replace('\'\'' , '"' ) if not self.keep_accents: __a : Optional[Any] = unicodedata.normalize('NFKD' , __a ) __a : List[str] = ''.join([c for c in outputs if not unicodedata.combining(__a )] ) if self.do_lower_case: __a : Tuple = outputs.lower() return outputs def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : Dict = self.preprocess_text(__a ) __a : Tuple = self.sp_model.encode(__a , out_type=__a ) __a : List[Any] = [] for piece in pieces: if len(__a ) > 1 and piece[-1] == str(',' ) and piece[-2].isdigit(): __a : List[str] = self.sp_model.EncodeAsPieces(piece[:-1].replace(__a , '' ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: __a : int = cur_pieces[1:] else: __a : str = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(__a ) else: new_pieces.append(__a ) return new_pieces def __UpperCAmelCase ( self , __a ): '''simple docstring''' return self.sp_model.PieceToId(__a ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' return self.sp_model.IdToPiece(__a ) def __UpperCAmelCase ( self , __a ): '''simple docstring''' __a : Optional[int] = [] __a : List[Any] = '' __a : int = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__a ) + token __a : List[Any] = True __a : Union[str, Any] = [] else: current_sub_tokens.append(__a ) __a : Union[str, Any] = False out_string += self.sp_model.decode(__a ) return out_string.strip() def __UpperCAmelCase ( self , __a , __a = None ): '''simple docstring''' __a : Optional[int] = [self.sep_token_id] __a : Optional[int] = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def __UpperCAmelCase ( self , __a , __a = None , __a = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__a , token_ids_a=__a , already_has_special_tokens=__a ) if token_ids_a is not None: return [1] + ([0] * len(__a )) + [1] + ([0] * len(__a )) + [1] return [1] + ([0] * len(__a )) + [1] def __UpperCAmelCase ( self , __a , __a = None ): '''simple docstring''' __a : Dict = [self.sep_token_id] __a : 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 __UpperCAmelCase ( self , __a , __a = None ): '''simple docstring''' if not os.path.isdir(__a ): logger.error(f"""Vocabulary path ({save_directory}) should be a directory""" ) return __a : Tuple = 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 ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __a ) elif not os.path.isfile(self.vocab_file ): with open(__a , 'wb' ) as fi: __a : int = self.sp_model.serialized_model_proto() fi.write(__a ) return (out_vocab_file,)
27
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __lowerCAmelCase = {'''configuration_swin''': ['''SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SwinConfig''', '''SwinOnnxConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''SWIN_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SwinForImageClassification''', '''SwinForMaskedImageModeling''', '''SwinModel''', '''SwinPreTrainedModel''', '''SwinBackbone''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFSwinForImageClassification''', '''TFSwinForMaskedImageModeling''', '''TFSwinModel''', '''TFSwinPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_swin import SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinConfig, SwinOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swin import ( SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, SwinBackbone, SwinForImageClassification, SwinForMaskedImageModeling, SwinModel, SwinPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_swin import ( TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, TFSwinForImageClassification, TFSwinForMaskedImageModeling, TFSwinModel, TFSwinPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
89
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_glpn import GLPNImageProcessor _lowerCamelCase : str = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE ( _a ): """simple docstring""" def __init__( self : List[Any] , *UpperCamelCase__ : Optional[int] , **UpperCamelCase__ : List[str] ): """simple docstring""" warnings.warn( 'The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use GLPNImageProcessor instead.' , UpperCamelCase__ , ) super().__init__(*UpperCamelCase__ , **UpperCamelCase__ )
28
'''simple docstring''' import unittest from transformers import BarthezTokenizer, BarthezTokenizerFast, BatchEncoding from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers @require_sentencepiece @slow # see https://github.com/huggingface/transformers/issues/11457 class __magic_name__ ( _UpperCamelCase , unittest.TestCase ): lowerCAmelCase : Optional[int] = BarthezTokenizer lowerCAmelCase : int = BarthezTokenizerFast lowerCAmelCase : Dict = True lowerCAmelCase : str = True def __lowercase ( self : List[Any] ): super().setUp() _a : List[Any] = BarthezTokenizerFast.from_pretrained('moussaKam/mbarthez' ) tokenizer.save_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ,legacy_format=_UpperCAmelCase ) _a : Union[str, Any] = tokenizer def __lowercase ( self : Tuple ): _a : Optional[Any] = '<pad>' _a : List[Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_UpperCAmelCase ) ,_UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_UpperCAmelCase ) ,_UpperCAmelCase ) def __lowercase ( self : str ): _a : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] ,'<s>' ) self.assertEqual(vocab_keys[1] ,'<pad>' ) self.assertEqual(vocab_keys[-1] ,'<mask>' ) self.assertEqual(len(_UpperCAmelCase ) ,101122 ) def __lowercase ( self : Dict ): self.assertEqual(self.get_tokenizer().vocab_size ,101122 ) @require_torch def __lowercase ( self : Dict ): _a : Any = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] _a : Dict = [0, 57, 3018, 70307, 91, 2] _a : Dict = self.tokenizer( _UpperCAmelCase ,max_length=len(_UpperCAmelCase ) ,padding=_UpperCAmelCase ,truncation=_UpperCAmelCase ,return_tensors='pt' ) self.assertIsInstance(_UpperCAmelCase ,_UpperCAmelCase ) self.assertEqual((2, 6) ,batch.input_ids.shape ) self.assertEqual((2, 6) ,batch.attention_mask.shape ) _a : Tuple = batch.input_ids.tolist()[0] self.assertListEqual(_UpperCAmelCase ,_UpperCAmelCase ) def __lowercase ( self : Optional[Any] ): if not self.test_rust_tokenizer: return _a : str = self.get_tokenizer() _a : List[str] = self.get_rust_tokenizer() _a : Dict = 'I was born in 92000, and this is falsé.' _a : List[Any] = tokenizer.tokenize(_UpperCAmelCase ) _a : Tuple = rust_tokenizer.tokenize(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase ,_UpperCAmelCase ) _a : Optional[Any] = tokenizer.encode(_UpperCAmelCase ,add_special_tokens=_UpperCAmelCase ) _a : Optional[int] = rust_tokenizer.encode(_UpperCAmelCase ,add_special_tokens=_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase ,_UpperCAmelCase ) _a : Union[str, Any] = self.get_rust_tokenizer() _a : Any = tokenizer.encode(_UpperCAmelCase ) _a : Optional[int] = rust_tokenizer.encode(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase ,_UpperCAmelCase ) @slow def __lowercase ( self : Optional[int] ): # fmt: off _a : Optional[int] = {'input_ids': [[0, 490, 14328, 4507, 354, 47, 43669, 95, 25, 78117, 20215, 19779, 190, 22, 400, 4, 35343, 80310, 603, 86, 24937, 105, 33438, 94762, 196, 39642, 7, 15, 15933, 173, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 10534, 87, 25, 66, 3358, 196, 55289, 8, 82961, 81, 2204, 75203, 7, 15, 763, 12956, 216, 178, 14328, 9595, 1377, 69693, 7, 448, 71021, 196, 18106, 1437, 13974, 108, 9083, 4, 49315, 7, 39, 86, 1326, 2793, 46333, 4, 448, 196, 74588, 7, 49315, 7, 39, 21, 822, 38470, 74, 21, 66723, 62480, 8, 22050, 5, 2]], '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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # moussaKam/mbarthez is a french model. So we also use french texts. _a : Optional[Any] = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=_UpperCAmelCase ,model_name='moussaKam/mbarthez' ,revision='c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6' ,sequences=_UpperCAmelCase ,)
89
0
import argparse from pathlib import Path import fairseq import torch from fairseq.models.xmod import XMODModel as FairseqXmodModel from packaging import version from transformers import XmodConfig, XmodForMaskedLM, XmodForSequenceClassification from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse('0.12.2'): raise Exception('requires fairseq >= 0.12.2') if version.parse(fairseq.__version__) > version.parse('2'): raise Exception('requires fairseq < v2') logging.set_verbosity_info() __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = 'Hello, World!' __UpperCAmelCase = 'en_XX' def lowercase__ ( __snake_case : str , __snake_case : str , __snake_case : bool ): '''simple docstring''' UpperCAmelCase_ : Any = Path('data_bin' ) UpperCAmelCase_ : Any = FairseqXmodModel.from_pretrained( model_name_or_path=str(Path(__snake_case ).parent ) , checkpoint_file=Path(__snake_case ).name , _name='xmod_base' , arch='xmod_base' , task='multilingual_masked_lm' , data_name_or_path=str(__snake_case ) , bpe='sentencepiece' , sentencepiece_model=str(Path(__snake_case ).parent / 'sentencepiece.bpe.model' ) , src_dict=str(data_dir / 'dict.txt' ) , ) xmod.eval() # disable dropout print(__snake_case ) UpperCAmelCase_ : Dict = xmod.model.encoder.sentence_encoder UpperCAmelCase_ : Dict = XmodConfig( vocab_size=xmod_sent_encoder.embed_tokens.num_embeddings , hidden_size=xmod.cfg.model.encoder_embed_dim , num_hidden_layers=xmod.cfg.model.encoder_layers , num_attention_heads=xmod.cfg.model.encoder_attention_heads , intermediate_size=xmod.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=514 , type_vocab_size=1 , layer_norm_eps=1E-5 , pre_norm=xmod.cfg.model.encoder_normalize_before , adapter_reduction_factor=getattr(xmod.cfg.model , 'bottleneck' , 2 ) , adapter_layer_norm=xmod.cfg.model.adapter_layer_norm , adapter_reuse_layer_norm=xmod.cfg.model.adapter_reuse_layer_norm , ln_before_adapter=xmod.cfg.model.ln_before_adapter , languages=xmod.cfg.model.languages , ) if classification_head: UpperCAmelCase_ : Optional[Any] = xmod.model.classification_heads['mnli'].out_proj.weight.shape[0] print('Our X-MOD config:' , __snake_case ) UpperCAmelCase_ : int = XmodForSequenceClassification(__snake_case ) if classification_head else XmodForMaskedLM(__snake_case ) model.eval() # Now let's copy all the weights. # Embeddings UpperCAmelCase_ : Optional[int] = xmod_sent_encoder.embed_tokens.weight UpperCAmelCase_ : Optional[int] = xmod_sent_encoder.embed_positions.weight UpperCAmelCase_ : Optional[Any] = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c xmod doesn't use them. UpperCAmelCase_ : List[str] = xmod_sent_encoder.layernorm_embedding.weight UpperCAmelCase_ : Dict = xmod_sent_encoder.layernorm_embedding.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer UpperCAmelCase_ : Dict = model.roberta.encoder.layer[i] UpperCAmelCase_ : List[Any] = xmod_sent_encoder.layers[i] # self attention UpperCAmelCase_ : Dict = layer.attention.self if not ( xmod_layer.self_attn.k_proj.weight.data.shape == xmod_layer.self_attn.q_proj.weight.data.shape == xmod_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ): raise AssertionError('Dimensions of self-attention weights do not match.' ) UpperCAmelCase_ : Optional[int] = xmod_layer.self_attn.q_proj.weight UpperCAmelCase_ : Optional[int] = xmod_layer.self_attn.q_proj.bias UpperCAmelCase_ : Tuple = xmod_layer.self_attn.k_proj.weight UpperCAmelCase_ : Optional[Any] = xmod_layer.self_attn.k_proj.bias UpperCAmelCase_ : Union[str, Any] = xmod_layer.self_attn.v_proj.weight UpperCAmelCase_ : List[str] = xmod_layer.self_attn.v_proj.bias # self-attention output UpperCAmelCase_ : int = layer.attention.output if self_output.dense.weight.shape != xmod_layer.self_attn.out_proj.weight.shape: raise AssertionError('Dimensions of self-attention output weights do not match.' ) UpperCAmelCase_ : List[str] = xmod_layer.self_attn.out_proj.weight UpperCAmelCase_ : List[str] = xmod_layer.self_attn.out_proj.bias UpperCAmelCase_ : Any = xmod_layer.self_attn_layer_norm.weight UpperCAmelCase_ : Dict = xmod_layer.self_attn_layer_norm.bias # intermediate UpperCAmelCase_ : Optional[Any] = layer.intermediate if intermediate.dense.weight.shape != xmod_layer.fca.weight.shape: raise AssertionError('Dimensions of intermediate weights do not match.' ) UpperCAmelCase_ : str = xmod_layer.fca.weight UpperCAmelCase_ : str = xmod_layer.fca.bias # output UpperCAmelCase_ : Tuple = layer.output if bert_output.dense.weight.shape != xmod_layer.fca.weight.shape: raise AssertionError('Dimensions of feed-forward weights do not match.' ) UpperCAmelCase_ : Dict = xmod_layer.fca.weight UpperCAmelCase_ : Union[str, Any] = xmod_layer.fca.bias UpperCAmelCase_ : List[Any] = xmod_layer.final_layer_norm.weight UpperCAmelCase_ : List[Any] = xmod_layer.final_layer_norm.bias if bert_output.adapter_layer_norm is not None: UpperCAmelCase_ : Tuple = xmod_layer.adapter_layer_norm.weight UpperCAmelCase_ : List[Any] = xmod_layer.adapter_layer_norm.bias if sorted(bert_output.adapter_modules.keys() ) != sorted(xmod_layer.adapter_modules.keys() ): raise AssertionError('Lists of language adapters do not match.' ) for lang_code, adapter in xmod_layer.adapter_modules.items(): UpperCAmelCase_ : Optional[int] = bert_output.adapter_modules[lang_code] UpperCAmelCase_ : Any = xmod_layer.adapter_modules[lang_code] UpperCAmelCase_ : Any = from_adapter.fca.weight UpperCAmelCase_ : str = from_adapter.fca.bias UpperCAmelCase_ : List[Any] = from_adapter.fca.weight UpperCAmelCase_ : List[str] = from_adapter.fca.bias # end of layer if xmod_sent_encoder.layer_norm is not None: UpperCAmelCase_ : str = xmod_sent_encoder.layer_norm.weight UpperCAmelCase_ : List[Any] = xmod_sent_encoder.layer_norm.bias if classification_head: UpperCAmelCase_ : List[Any] = xmod.model.classification_heads['mnli'].dense.weight UpperCAmelCase_ : str = xmod.model.classification_heads['mnli'].dense.bias UpperCAmelCase_ : int = xmod.model.classification_heads['mnli'].out_proj.weight UpperCAmelCase_ : str = xmod.model.classification_heads['mnli'].out_proj.bias else: # LM Head UpperCAmelCase_ : List[Any] = xmod.model.encoder.lm_head.dense.weight UpperCAmelCase_ : Optional[Any] = xmod.model.encoder.lm_head.dense.bias UpperCAmelCase_ : List[str] = xmod.model.encoder.lm_head.layer_norm.weight UpperCAmelCase_ : Any = xmod.model.encoder.lm_head.layer_norm.bias UpperCAmelCase_ : Optional[Any] = xmod.model.encoder.lm_head.weight UpperCAmelCase_ : str = xmod.model.encoder.lm_head.bias # Let's check that we get the same results. UpperCAmelCase_ : List[Any] = xmod.encode(__snake_case ).unsqueeze(0 ) # batch of size 1 model.roberta.set_default_language(__snake_case ) UpperCAmelCase_ : Any = model(__snake_case )[0] if classification_head: UpperCAmelCase_ : int = xmod.model.classification_heads['mnli'](xmod.extract_features(__snake_case ) ) else: UpperCAmelCase_ : Optional[Any] = xmod.model(__snake_case , lang_id=[SAMPLE_LANGUAGE] )[0] print(our_output.shape , their_output.shape ) UpperCAmelCase_ : int = torch.max(torch.abs(our_output - their_output ) ).item() print(F"max_absolute_diff = {max_absolute_diff}" ) # ~ 1e-7 UpperCAmelCase_ : Union[str, Any] = torch.allclose(__snake_case , __snake_case , atol=1E-3 ) print('Do both models output the same tensors?' , '🔥' if success else '💩' ) if not success: raise Exception('Something went wRoNg' ) Path(__snake_case ).mkdir(parents=__snake_case , exist_ok=__snake_case ) print(F"Saving model to {pytorch_dump_folder_path}" ) model.save_pretrained(__snake_case ) if __name__ == "__main__": __UpperCAmelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--xmod_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--classification_head', action='store_true', help='Whether to convert a final classification head.' ) __UpperCAmelCase = parser.parse_args() convert_xmod_checkpoint_to_pytorch( args.xmod_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
29
'''simple docstring''' import subprocess import sys from transformers import BertConfig, BertModel, BertTokenizer, pipeline from transformers.testing_utils import TestCasePlus, require_torch class __magic_name__ ( _UpperCamelCase ): @require_torch def __lowercase ( self : Tuple ): # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched _a : Optional[int] = '\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n ' _a : List[str] = '\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n ' _a : Tuple = '\nimport socket\ndef offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn\'t access internet")\nsocket.socket = offline_socket\n ' # Force fetching the files so that we can use the cache _a : List[Any] = 'hf-internal-testing/tiny-random-bert' BertConfig.from_pretrained(_UpperCAmelCase ) BertModel.from_pretrained(_UpperCAmelCase ) BertTokenizer.from_pretrained(_UpperCAmelCase ) pipeline(task='fill-mask' ,model=_UpperCAmelCase ) # baseline - just load from_pretrained with normal network _a : Optional[int] = [sys.executable, '-c', '\n'.join([load, run, mock] )] # should succeed _a : Tuple = self.get_env() # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files _a : int = '1' _a : List[Any] = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) @require_torch def __lowercase ( self : Any ): # python one-liner segments # this must be loaded before socket.socket is monkey-patched _a : Dict = '\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n ' _a : Optional[int] = '\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n ' _a : Optional[Any] = '\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet")\nsocket.socket = offline_socket\n ' # Force fetching the files so that we can use the cache _a : int = 'hf-internal-testing/tiny-random-bert' BertConfig.from_pretrained(_UpperCAmelCase ) BertModel.from_pretrained(_UpperCAmelCase ) BertTokenizer.from_pretrained(_UpperCAmelCase ) pipeline(task='fill-mask' ,model=_UpperCAmelCase ) # baseline - just load from_pretrained with normal network _a : Optional[int] = [sys.executable, '-c', '\n'.join([load, run, mock] )] # should succeed _a : str = self.get_env() _a : Optional[Any] = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) @require_torch def __lowercase ( self : List[str] ): # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched _a : Union[str, Any] = '\nfrom transformers import BertConfig, BertModel, BertTokenizer\n ' _a : Optional[Any] = '\nmname = "hf-internal-testing/tiny-random-bert-sharded"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nprint("success")\n ' _a : str = '\nimport socket\ndef offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled")\nsocket.socket = offline_socket\n ' # baseline - just load from_pretrained with normal network _a : Optional[Any] = [sys.executable, '-c', '\n'.join([load, run] )] # should succeed _a : Dict = self.get_env() _a : int = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) # next emulate no network _a : List[Any] = [sys.executable, '-c', '\n'.join([load, mock, run] )] # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this. # env["TRANSFORMERS_OFFLINE"] = "0" # result = subprocess.run(cmd, env=env, check=False, capture_output=True) # self.assertEqual(result.returncode, 1, result.stderr) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files _a : int = '1' _a : Any = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) @require_torch def __lowercase ( self : int ): _a : Optional[Any] = '\nfrom transformers import pipeline\n ' _a : str = '\nmname = "hf-internal-testing/tiny-random-bert"\npipe = pipeline(model=mname)\n ' _a : List[str] = '\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled")\nsocket.socket = offline_socket\n ' _a : List[Any] = self.get_env() _a : Dict = '1' _a : Dict = [sys.executable, '-c', '\n'.join([load, mock, run] )] _a : str = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,1 ,result.stderr ) self.assertIn( 'You cannot infer task automatically within `pipeline` when using offline mode' ,result.stderr.decode().replace('\n' ,'' ) ,) @require_torch def __lowercase ( self : int ): _a : Optional[int] = '\nfrom transformers import AutoModel\n ' _a : List[Any] = '\nmname = "hf-internal-testing/test_dynamic_model"\nAutoModel.from_pretrained(mname, trust_remote_code=True)\nprint("success")\n ' # baseline - just load from_pretrained with normal network _a : Union[str, Any] = [sys.executable, '-c', '\n'.join([load, run] )] # should succeed _a : Tuple = self.get_env() _a : List[str] = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files _a : Optional[Any] = '1' _a : Any = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() )
89
0
import inspect import os import re from transformers.configuration_utils import PretrainedConfig from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py __a = 'src/transformers' # This is to make sure the transformers module imported is the one in the repo. __a = direct_transformers_import(PATH_TO_TRANSFORMERS) __a = transformers.models.auto.configuration_auto.CONFIG_MAPPING __a = { # used to compute the property `self.chunk_length` 'EncodecConfig': ['overlap'], # used as `self.bert_model = BertModel(config, ...)` 'DPRConfig': True, # not used in modeling files, but it's an important information 'FSMTConfig': ['langs'], # used internally in the configuration class file 'GPTNeoConfig': ['attention_types'], # used internally in the configuration class file 'EsmConfig': ['is_folding_model'], # used during training (despite we don't have training script for these models yet) 'Mask2FormerConfig': ['ignore_value'], # `ignore_value` used during training (despite we don't have training script for these models yet) # `norm` used in conversion script (despite not using in the modeling file) 'OneFormerConfig': ['ignore_value', 'norm'], # used during preprocessing and collation, see `collating_graphormer.py` 'GraphormerConfig': ['spatial_pos_max'], # used internally in the configuration class file 'T5Config': ['feed_forward_proj'], # used internally in the configuration class file # `tokenizer_class` get default value `T5Tokenizer` intentionally 'MT5Config': ['feed_forward_proj', 'tokenizer_class'], 'UMT5Config': ['feed_forward_proj', 'tokenizer_class'], # used internally in the configuration class file 'LongT5Config': ['feed_forward_proj'], # used internally in the configuration class file 'SwitchTransformersConfig': ['feed_forward_proj'], # having default values other than `1e-5` - we can't fix them without breaking 'BioGptConfig': ['layer_norm_eps'], # having default values other than `1e-5` - we can't fix them without breaking 'GLPNConfig': ['layer_norm_eps'], # having default values other than `1e-5` - we can't fix them without breaking 'SegformerConfig': ['layer_norm_eps'], # having default values other than `1e-5` - we can't fix them without breaking 'CvtConfig': ['layer_norm_eps'], # having default values other than `1e-5` - we can't fix them without breaking 'PerceiverConfig': ['layer_norm_eps'], # used internally to calculate the feature size 'InformerConfig': ['num_static_real_features', 'num_time_features'], # used internally to calculate the feature size 'TimeSeriesTransformerConfig': ['num_static_real_features', 'num_time_features'], # used internally to calculate the feature size 'AutoformerConfig': ['num_static_real_features', 'num_time_features'], # used internally to calculate `mlp_dim` 'SamVisionConfig': ['mlp_ratio'], # For (head) training, but so far not implemented 'ClapAudioConfig': ['num_classes'], # Not used, but providing useful information to users 'SpeechT5HifiGanConfig': ['sampling_rate'], } # TODO (ydshieh): Check the failing cases, try to fix them or move some cases to the above block once we are sure SPECIAL_CASES_TO_ALLOW.update( { 'CLIPSegConfig': True, 'DeformableDetrConfig': True, 'DetaConfig': True, 'DinatConfig': True, 'DonutSwinConfig': True, 'EfficientFormerConfig': True, 'FSMTConfig': True, 'JukeboxConfig': True, 'LayoutLMv2Config': True, 'MaskFormerSwinConfig': True, 'MT5Config': True, 'NatConfig': True, 'OneFormerConfig': True, 'PerceiverConfig': True, 'RagConfig': True, 'SpeechT5Config': True, 'SwinConfig': True, 'Swin2SRConfig': True, 'Swinv2Config': True, 'SwitchTransformersConfig': True, 'TableTransformerConfig': True, 'TapasConfig': True, 'TransfoXLConfig': True, 'UniSpeechConfig': True, 'UniSpeechSatConfig': True, 'WavLMConfig': True, 'WhisperConfig': True, # TODO: @Arthur (for `alignment_head` and `alignment_layer`) 'JukeboxPriorConfig': True, # TODO: @Younes (for `is_decoder`) 'Pix2StructTextConfig': True, } ) def a ( snake_case__: Dict , snake_case__: Optional[Any] , snake_case__: Tuple , snake_case__: Tuple ): '''simple docstring''' lowercase_ = False for attribute in attributes: for modeling_source in source_strings: # check if we can find `config.xxx`, `getattr(config, "xxx", ...)` or `getattr(self.config, "xxx", ...)` if ( F'''config.{attribute}''' in modeling_source or F'''getattr(config, "{attribute}"''' in modeling_source or F'''getattr(self.config, "{attribute}"''' in modeling_source ): lowercase_ = True # Deal with multi-line cases elif ( re.search( rF'''getattr[ \t\v\n\r\f]*\([ \t\v\n\r\f]*(self\.)?config,[ \t\v\n\r\f]*"{attribute}"''' , snake_case__ , ) is not None ): lowercase_ = True # `SequenceSummary` is called with `SequenceSummary(config)` elif attribute in [ "summary_type", "summary_use_proj", "summary_activation", "summary_last_dropout", "summary_proj_to_labels", "summary_first_dropout", ]: if "SequenceSummary" in modeling_source: lowercase_ = True if attribute_used: break if attribute_used: break # common and important attributes, even if they do not always appear in the modeling files lowercase_ = [ '''bos_index''', '''eos_index''', '''pad_index''', '''unk_index''', '''mask_index''', '''image_size''', '''use_cache''', '''out_features''', '''out_indices''', ] lowercase_ = ['''encoder_no_repeat_ngram_size'''] # Special cases to be allowed lowercase_ = True if not attribute_used: lowercase_ = False for attribute in attributes: # Allow if the default value in the configuration class is different from the one in `PretrainedConfig` if attribute in ["is_encoder_decoder"] and default_value is True: lowercase_ = True elif attribute in ["tie_word_embeddings"] and default_value is False: lowercase_ = True # Allow cases without checking the default value in the configuration class elif attribute in attributes_to_allow + attributes_used_in_generation: lowercase_ = True elif attribute.endswith('''_token_id''' ): lowercase_ = True # configuration class specific cases if not case_allowed: lowercase_ = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__ , [] ) lowercase_ = allowed_cases is True or attribute in allowed_cases return attribute_used or case_allowed def a ( snake_case__: Dict ): '''simple docstring''' lowercase_ = dict(inspect.signature(config_class.__init__ ).parameters ) lowercase_ = [x for x in list(signature.keys() ) if x not in ['''self''', '''kwargs''']] lowercase_ = [signature[param].default for param in parameter_names] # If `attribute_map` exists, an attribute can have different names to be used in the modeling files, and as long # as one variant is used, the test should pass lowercase_ = {} if len(config_class.attribute_map ) > 0: lowercase_ = {v: k for k, v in config_class.attribute_map.items()} # Get the path to modeling source files lowercase_ = inspect.getsourcefile(snake_case__ ) lowercase_ = os.path.dirname(snake_case__ ) # Let's check against all frameworks: as long as one framework uses an attribute, we are good. lowercase_ = [os.path.join(snake_case__ , snake_case__ ) for fn in os.listdir(snake_case__ ) if fn.startswith('''modeling_''' )] # Get the source code strings lowercase_ = [] for path in modeling_paths: if os.path.isfile(snake_case__ ): with open(snake_case__ ) as fp: modeling_sources.append(fp.read() ) lowercase_ = [] for config_param, default_value in zip(snake_case__ , snake_case__ ): # `attributes` here is all the variant names for `config_param` lowercase_ = [config_param] # some configuration classes have non-empty `attribute_map`, and both names could be used in the # corresponding modeling files. As long as one of them appears, it is fine. if config_param in reversed_attribute_map: attributes.append(reversed_attribute_map[config_param] ) if not check_attribute_being_used(snake_case__ , snake_case__ , snake_case__ , snake_case__ ): unused_attributes.append(attributes[0] ) return sorted(snake_case__ ) def a ( ): '''simple docstring''' lowercase_ = {} for _config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in _config_class.__module__: continue # Some config classes are not in `CONFIG_MAPPING` (e.g. `CLIPVisionConfig`, `Blip2VisionConfig`, etc.) lowercase_ = [ cls for name, cls in inspect.getmembers( inspect.getmodule(_config_class ) , lambda snake_case__ : inspect.isclass(snake_case__ ) and issubclass(snake_case__ , snake_case__ ) and inspect.getmodule(snake_case__ ) == inspect.getmodule(_config_class ) , ) ] for config_class in config_classes_in_module: lowercase_ = check_config_attributes_being_used(snake_case__ ) if len(snake_case__ ) > 0: lowercase_ = unused_attributes if len(snake_case__ ) > 0: lowercase_ = '''The following configuration classes contain unused attributes in the corresponding modeling files:\n''' for name, attributes in configs_with_unused_attributes.items(): error += F'''{name}: {attributes}\n''' raise ValueError(snake_case__ ) if __name__ == "__main__": check_config_attributes()
30
'''simple docstring''' def __lowerCamelCase ( ) -> Tuple: for n in range(1 , 1000000 ): yield n * (n + 1) // 2 def __lowerCamelCase ( lowerCAmelCase_ ) -> List[Any]: _a : Any = 1 _a : Tuple = 2 while i * i <= n: _a : Tuple = 0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def __lowerCamelCase ( ) -> str: return next(i for i in triangle_number_generator() if count_divisors(lowerCAmelCase_ ) > 500 ) if __name__ == "__main__": print(solution())
89
0
'''simple docstring''' import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDict from datasets.iterable_dataset import IterableDataset from datasets.load import dataset_module_factory, import_main_class from datasets.utils.file_utils import cached_path __SCREAMING_SNAKE_CASE : Union[str, Any] = [ {"""dataset""": """wikipedia""", """config_name""": """20220301.de"""}, {"""dataset""": """wikipedia""", """config_name""": """20220301.en"""}, {"""dataset""": """wikipedia""", """config_name""": """20220301.fr"""}, {"""dataset""": """wikipedia""", """config_name""": """20220301.frr"""}, {"""dataset""": """wikipedia""", """config_name""": """20220301.it"""}, {"""dataset""": """wikipedia""", """config_name""": """20220301.simple"""}, {"""dataset""": """snli""", """config_name""": """plain_text"""}, {"""dataset""": """eli5""", """config_name""": """LFQA_reddit"""}, {"""dataset""": """wiki40b""", """config_name""": """en"""}, {"""dataset""": """wiki_dpr""", """config_name""": """psgs_w100.nq.compressed"""}, {"""dataset""": """wiki_dpr""", """config_name""": """psgs_w100.nq.no_index"""}, {"""dataset""": """wiki_dpr""", """config_name""": """psgs_w100.multiset.no_index"""}, {"""dataset""": """natural_questions""", """config_name""": """default"""}, ] def UpperCamelCase_ ( _UpperCAmelCase : Optional[int]=True ) -> Tuple: """simple docstring""" if with_config: return [ { "testcase_name": d["dataset"] + "/" + d["config_name"], "dataset": d["dataset"], "config_name": d["config_name"], } for d in DATASETS_ON_HF_GCP ] else: return [ {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP} ] @parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=snake_case__ ) ) class lowerCamelCase_ (snake_case__ ): '''simple docstring''' __UpperCamelCase: Optional[Any] = None __UpperCamelCase: int = None def _A ( self : str , A : str , A : List[Any] ): with TemporaryDirectory() as tmp_dir: _UpperCAmelCase : int = dataset_module_factory(A , cache_dir=A ) _UpperCAmelCase : List[Any] = import_main_class(dataset_module.module_path , dataset=A ) _UpperCAmelCase : DatasetBuilder = builder_cls( cache_dir=A , config_name=A , hash=dataset_module.hash , ) _UpperCAmelCase : Tuple = "/".join( [ HF_GCP_BASE_URL, builder_instance._relative_data_dir(with_hash=A ).replace(os.sep , "/" ), config.DATASET_INFO_FILENAME, ] ) _UpperCAmelCase : Optional[Any] = cached_path(A , cache_dir=A ) self.assertTrue(os.path.exists(A ) ) @pytest.mark.integration def UpperCamelCase_ ( _UpperCAmelCase : List[Any] ) -> Tuple: """simple docstring""" _UpperCAmelCase : int = tmp_path_factory.mktemp("test_hf_gcp" ) / "test_wikipedia_simple" _UpperCAmelCase : Union[str, Any] = dataset_module_factory("wikipedia" , cache_dir=_UpperCAmelCase ) _UpperCAmelCase : str = import_main_class(dataset_module.module_path ) _UpperCAmelCase : DatasetBuilder = builder_cls( cache_dir=_UpperCAmelCase , config_name="20220301.frr" , hash=dataset_module.hash , ) # use the HF cloud storage, not the original download_and_prepare that uses apache-beam _UpperCAmelCase : Dict = None builder_instance.download_and_prepare() _UpperCAmelCase : List[str] = builder_instance.as_dataset() assert ds @pytest.mark.integration def UpperCamelCase_ ( _UpperCAmelCase : Optional[Any] ) -> Dict: """simple docstring""" _UpperCAmelCase : List[str] = dataset_module_factory("wikipedia" , cache_dir=_UpperCAmelCase ) _UpperCAmelCase : List[Any] = import_main_class(dataset_module.module_path , dataset=_UpperCAmelCase ) _UpperCAmelCase : DatasetBuilder = builder_cls( cache_dir=_UpperCAmelCase , config_name="20220301.frr" , hash=dataset_module.hash , ) _UpperCAmelCase : Dict = builder_instance.as_streaming_dataset() assert ds assert isinstance(_UpperCAmelCase , _UpperCAmelCase ) assert "train" in ds assert isinstance(ds["train"] , _UpperCAmelCase ) assert next(iter(ds["train"] ) )
31
'''simple docstring''' import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class __magic_name__ ( _UpperCamelCase ): def __init__( self : Optional[int] ,_UpperCAmelCase : Union[str, "sqlalchemy.sql.Selectable"] ,_UpperCAmelCase : Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] ,_UpperCAmelCase : Optional[Features] = None ,_UpperCAmelCase : str = None ,_UpperCAmelCase : bool = False ,**_UpperCAmelCase : Dict ,): super().__init__(features=_UpperCAmelCase ,cache_dir=_UpperCAmelCase ,keep_in_memory=_UpperCAmelCase ,**_UpperCAmelCase ) _a : Tuple = Sql( cache_dir=_UpperCAmelCase ,features=_UpperCAmelCase ,sql=_UpperCAmelCase ,con=_UpperCAmelCase ,**_UpperCAmelCase ,) def __lowercase ( self : Dict ): _a : Optional[Any] = None _a : Dict = None _a : Dict = None _a : Optional[int] = None self.builder.download_and_prepare( download_config=_UpperCAmelCase ,download_mode=_UpperCAmelCase ,verification_mode=_UpperCAmelCase ,base_path=_UpperCAmelCase ,) # Build dataset for splits _a : List[str] = self.builder.as_dataset( split='train' ,verification_mode=_UpperCAmelCase ,in_memory=self.keep_in_memory ) return dataset class __magic_name__ : def __init__( self : Optional[int] ,_UpperCAmelCase : Dataset ,_UpperCAmelCase : str ,_UpperCAmelCase : Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] ,_UpperCAmelCase : Optional[int] = None ,_UpperCAmelCase : Optional[int] = None ,**_UpperCAmelCase : Dict ,): if num_proc is not None and num_proc <= 0: raise ValueError(F"""num_proc {num_proc} must be an integer > 0.""" ) _a : Dict = dataset _a : List[Any] = name _a : Tuple = con _a : Union[str, Any] = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE _a : List[Any] = num_proc _a : Tuple = to_sql_kwargs def __lowercase ( self : List[Any] ): _a : Tuple = self.to_sql_kwargs.pop('sql' ,_UpperCAmelCase ) _a : str = self.to_sql_kwargs.pop('con' ,_UpperCAmelCase ) _a : Optional[Any] = self.to_sql_kwargs.pop('index' ,_UpperCAmelCase ) _a : Any = self._write(index=_UpperCAmelCase ,**self.to_sql_kwargs ) return written def __lowercase ( self : Optional[int] ,_UpperCAmelCase : Dict ): _a , _a , _a : Any = args _a : Tuple = {**to_sql_kwargs, 'if_exists': 'append'} if offset > 0 else to_sql_kwargs _a : Dict = query_table( table=self.dataset.data ,key=slice(_UpperCAmelCase ,offset + self.batch_size ) ,indices=self.dataset._indices ,) _a : Tuple = batch.to_pandas() _a : Dict = df.to_sql(self.name ,self.con ,index=_UpperCAmelCase ,**_UpperCAmelCase ) return num_rows or len(_UpperCAmelCase ) def __lowercase ( self : int ,_UpperCAmelCase : Optional[int] ,**_UpperCAmelCase : List[Any] ): _a : Union[str, Any] = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 ,len(self.dataset ) ,self.batch_size ) ,unit='ba' ,disable=not logging.is_progress_bar_enabled() ,desc='Creating SQL from Arrow format' ,): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: _a , _a : List[Any] = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql ,[(offset, index, to_sql_kwargs) for offset in range(0 ,_UpperCAmelCase ,_UpperCAmelCase )] ,) ,total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size ,unit='ba' ,disable=not logging.is_progress_bar_enabled() ,desc='Creating SQL from Arrow format' ,): written += num_rows return written
89
0
import argparse import pytorch_lightning as pl import torch from torch import nn from transformers import LongformerForQuestionAnswering, LongformerModel class SCREAMING_SNAKE_CASE__ ( pl.LightningModule ): def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Dict: super().__init__() a_ : Union[str, Any] = model a_ : int = 2 a_ : Optional[int] = nn.Linear(self.model.config.hidden_size , self.num_labels ) def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict: pass def SCREAMING_SNAKE_CASE_ ( __A : str , __A : str , __A : str ) -> int: """simple docstring""" a_ : Optional[Any] = LongformerModel.from_pretrained(__A ) a_ : Optional[int] = LightningModel(__A ) a_ : Union[str, Any] = torch.load(__A , map_location=torch.device('cpu' ) ) lightning_model.load_state_dict(ckpt['state_dict'] ) # init longformer question answering model a_ : Optional[Any] = LongformerForQuestionAnswering.from_pretrained(__A ) # transfer weights longformer_for_qa.longformer.load_state_dict(lightning_model.model.state_dict() ) longformer_for_qa.qa_outputs.load_state_dict(lightning_model.qa_outputs.state_dict() ) longformer_for_qa.eval() # save model longformer_for_qa.save_pretrained(__A ) print(F"""Conversion successful. Model saved under {pytorch_dump_folder_path}""" ) if __name__ == "__main__": UpperCAmelCase_ : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--longformer_model', default=None, type=str, required=True, help='model identifier of longformer. Should be either `longformer-base-4096` or `longformer-large-4096`.', ) parser.add_argument( '--longformer_question_answering_ckpt_path', default=None, type=str, required=True, help='Path the official PyTorch Lightning Checkpoint.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) UpperCAmelCase_ : Optional[int] = parser.parse_args() convert_longformer_qa_checkpoint_to_pytorch( args.longformer_model, args.longformer_question_answering_ckpt_path, args.pytorch_dump_folder_path )
32
'''simple docstring''' from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> np.ndarray: _a : Union[str, Any] = cva.getAffineTransform(lowerCAmelCase_ , lowerCAmelCase_ ) return cva.warpAffine(lowerCAmelCase_ , lowerCAmelCase_ , (rows, cols) ) if __name__ == "__main__": # read original image __lowerCAmelCase = cva.imread( str(Path(__file__).resolve().parent.parent / '''image_data''' / '''lena.jpg''') ) # turn image in gray scale value __lowerCAmelCase = cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape __lowerCAmelCase , __lowerCAmelCase = gray_img.shape # set different points to rotate image __lowerCAmelCase = np.array([[50, 50], [200, 50], [50, 200]], np.floataa) __lowerCAmelCase = np.array([[10, 100], [200, 50], [100, 250]], np.floataa) __lowerCAmelCase = np.array([[50, 50], [150, 50], [120, 200]], np.floataa) __lowerCAmelCase = np.array([[10, 100], [80, 50], [180, 250]], np.floataa) # add all rotated images in a list __lowerCAmelCase = [ gray_img, get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), ] # plot different image rotations __lowerCAmelCase = plt.figure(1) __lowerCAmelCase = ['''Original''', '''Rotation 1''', '''Rotation 2''', '''Rotation 3'''] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, '''gray''') plt.title(titles[i]) plt.axis('''off''') plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
89
0
"""simple docstring""" 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 : List[str] = logging.get_logger(__name__) @dataclass class _UpperCAmelCase ( _A ): SCREAMING_SNAKE_CASE_ : Any = [ "no_inference", "no_cuda", "no_tpu", "no_speed", "no_memory", "no_env_print", "no_multi_process", ] def __init__( self : str , **A : List[Any] ) -> Union[str, Any]: for deprecated_arg in self.deprecated_args: if deprecated_arg in kwargs: lowercase_ : List[str] = 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_ : Optional[Any] = kwargs.pop('''torchscript''' , self.torchscript ) lowercase_ : Tuple = kwargs.pop('''torch_xla_tpu_print_metrics''' , self.torch_xla_tpu_print_metrics ) lowercase_ : Any = kwargs.pop('''fp16_opt_level''' , self.fpaa_opt_level ) super().__init__(**A ) SCREAMING_SNAKE_CASE_ : bool = field(default=_A , metadata={"help": "Trace the models using torchscript"} ) SCREAMING_SNAKE_CASE_ : bool = field(default=_A , metadata={"help": "Print Xla/PyTorch tpu metrics"} ) SCREAMING_SNAKE_CASE_ : str = 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 A ( self : Optional[Any] ) -> Tuple["torch.device", int]: requires_backends(self , ['''torch'''] ) logger.info('''PyTorch: setting up devices''' ) if not self.cuda: lowercase_ : List[Any] = torch.device('''cpu''' ) lowercase_ : Optional[int] = 0 elif is_torch_tpu_available(): lowercase_ : Optional[Any] = xm.xla_device() lowercase_ : Union[str, Any] = 0 else: lowercase_ : Tuple = torch.device('''cuda''' if torch.cuda.is_available() else '''cpu''' ) lowercase_ : str = torch.cuda.device_count() return device, n_gpu @property def A ( self : Any ) -> str: return is_torch_tpu_available() and self.tpu @property def A ( self : str ) -> int: requires_backends(self , ['''torch'''] ) # TODO(PVP): currently only single GPU is supported return torch.cuda.current_device() @property def A ( self : int ) -> "torch.device": requires_backends(self , ['''torch'''] ) return self._setup_devices[0] @property def A ( self : List[str] ) -> str: requires_backends(self , ['''torch'''] ) return self._setup_devices[1] @property def A ( self : List[str] ) -> Optional[Any]: return self.n_gpu > 0
33
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCAmelCase = { '''configuration_bigbird_pegasus''': [ '''BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BigBirdPegasusConfig''', '''BigBirdPegasusOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BigBirdPegasusForCausalLM''', '''BigBirdPegasusForConditionalGeneration''', '''BigBirdPegasusForQuestionAnswering''', '''BigBirdPegasusForSequenceClassification''', '''BigBirdPegasusModel''', '''BigBirdPegasusPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP, BigBirdPegasusConfig, BigBirdPegasusOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST, BigBirdPegasusForCausalLM, BigBirdPegasusForConditionalGeneration, BigBirdPegasusForQuestionAnswering, BigBirdPegasusForSequenceClassification, BigBirdPegasusModel, BigBirdPegasusPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
89
0
'''simple docstring''' import warnings from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding class _a ( __a ): __a : int = ["""image_processor""", """tokenizer"""] __a : Union[str, Any] = """ChineseCLIPImageProcessor""" __a : List[Any] = ("""BertTokenizer""", """BertTokenizerFast""") def __init__( self : Dict , lowercase : Union[str, Any]=None , lowercase : Dict=None , **lowercase : Optional[Any] ): '''simple docstring''' UpperCAmelCase = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , lowercase , ) UpperCAmelCase = kwargs.pop('''feature_extractor''' ) UpperCAmelCase = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('''You need to specify an `image_processor`.''' ) if tokenizer is None: raise ValueError('''You need to specify a `tokenizer`.''' ) super().__init__(lowercase , lowercase ) UpperCAmelCase = self.image_processor def __call__( self : Tuple , lowercase : Optional[Any]=None , lowercase : Union[str, Any]=None , lowercase : int=None , **lowercase : Dict ): '''simple docstring''' if text is None and images is None: raise ValueError('''You have to specify either text or images. Both cannot be none.''' ) if text is not None: UpperCAmelCase = self.tokenizer(lowercase , return_tensors=lowercase , **lowercase ) if images is not None: UpperCAmelCase = self.image_processor(lowercase , return_tensors=lowercase , **lowercase ) if text is not None and images is not None: UpperCAmelCase = image_features.pixel_values return encoding elif text is not None: return encoding else: return BatchEncoding(data=dict(**lowercase ) , tensor_type=lowercase ) def A ( self : int , *lowercase : Tuple , **lowercase : List[str] ): '''simple docstring''' return self.tokenizer.batch_decode(*lowercase , **lowercase ) def A ( self : Optional[Any] , *lowercase : int , **lowercase : Optional[int] ): '''simple docstring''' return self.tokenizer.decode(*lowercase , **lowercase ) @property def A ( self : Optional[int] ): '''simple docstring''' UpperCAmelCase = self.tokenizer.model_input_names UpperCAmelCase = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) ) @property def A ( self : List[Any] ): '''simple docstring''' warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , lowercase , ) return self.image_processor_class
34
'''simple docstring''' import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=1024 , lowerCAmelCase_=1024 , lowerCAmelCase_=False , **lowerCAmelCase_ ) -> List[Any]: _a : str = AutoTokenizer.from_pretrained(lowerCAmelCase_ ) _a : List[Any] = SeqaSeqDataset(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , type_path='train' , **lowerCAmelCase_ ) _a : List[str] = tok.pad_token_id def get_lens(lowerCAmelCase_ ): _a : Dict = tqdm( DataLoader(lowerCAmelCase_ , batch_size=512 , num_workers=8 , shuffle=lowerCAmelCase_ , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) _a : Union[str, Any] = [] for batch in dl: _a : Optional[Any] = batch['input_ids'].ne(lowerCAmelCase_ ).sum(1 ).tolist() _a : Optional[Any] = batch['labels'].ne(lowerCAmelCase_ ).sum(1 ).tolist() if consider_target: for src, tgt in zip(lowerCAmelCase_ , lowerCAmelCase_ ): max_lens.append(max(lowerCAmelCase_ , lowerCAmelCase_ ) ) else: max_lens.extend(lowerCAmelCase_ ) return max_lens _a : str = get_lens(lowerCAmelCase_ ) _a : Optional[int] = SeqaSeqDataset(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , type_path='val' , **lowerCAmelCase_ ) _a : Dict = get_lens(lowerCAmelCase_ ) pickle_save(lowerCAmelCase_ , train_ds.len_file ) pickle_save(lowerCAmelCase_ , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
89
0
'''simple docstring''' import numpy as np from transformers import Pipeline def __snake_case( _lowerCAmelCase ) -> Optional[int]: snake_case__ : Optional[Any] = np.max(_lowerCAmelCase , axis=-1 , keepdims=_lowerCAmelCase ) snake_case__ : List[str] = np.exp(outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_lowerCAmelCase ) class UpperCAmelCase_ ( _a ): """simple docstring""" def lowerCamelCase ( self : Optional[Any] , **snake_case_ : int ): snake_case__ : Optional[int] = {} if "second_text" in kwargs: snake_case__ : Union[str, Any] = kwargs["""second_text"""] return preprocess_kwargs, {}, {} def lowerCamelCase ( self : str , snake_case_ : Tuple , snake_case_ : Union[str, Any]=None ): return self.tokenizer(snake_case_ , text_pair=snake_case_ , return_tensors=self.framework ) def lowerCamelCase ( self : List[Any] , snake_case_ : Dict ): return self.model(**snake_case_ ) def lowerCamelCase ( self : int , snake_case_ : List[Any] ): snake_case__ : Union[str, Any] = model_outputs.logits[0].numpy() snake_case__ : List[str] = softmax(snake_case_ ) snake_case__ : List[str] = np.argmax(snake_case_ ) snake_case__ : List[str] = self.model.config.idalabel[best_class] snake_case__ : Optional[int] = probabilities[best_class].item() snake_case__ : str = logits.tolist() return {"label": label, "score": score, "logits": logits}
35
'''simple docstring''' from typing import Any class __magic_name__ : def __init__( self : List[Any] ,_UpperCAmelCase : Any ): _a : List[Any] = data _a : Union[str, Any] = None def __repr__( self : Any ): return F"""Node({self.data})""" class __magic_name__ : def __init__( self : int ): _a : Tuple = None def __iter__( self : str ): _a : int = self.head while node: yield node.data _a : Union[str, Any] = node.next def __len__( self : Optional[Any] ): return sum(1 for _ in self ) def __repr__( self : str ): return "->".join([str(_UpperCAmelCase ) for item in self] ) def __getitem__( self : Tuple ,_UpperCAmelCase : int ): if not 0 <= index < len(self ): raise ValueError('list index out of range.' ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self : Union[str, Any] ,_UpperCAmelCase : int ,_UpperCAmelCase : Any ): if not 0 <= index < len(self ): raise ValueError('list index out of range.' ) _a : Any = self.head for _ in range(_UpperCAmelCase ): _a : Optional[Any] = current.next _a : Optional[int] = data def __lowercase ( self : Optional[int] ,_UpperCAmelCase : Any ): self.insert_nth(len(self ) ,_UpperCAmelCase ) def __lowercase ( self : Union[str, Any] ,_UpperCAmelCase : Any ): self.insert_nth(0 ,_UpperCAmelCase ) def __lowercase ( self : str ,_UpperCAmelCase : int ,_UpperCAmelCase : Any ): if not 0 <= index <= len(self ): raise IndexError('list index out of range' ) _a : int = Node(_UpperCAmelCase ) if self.head is None: _a : str = new_node elif index == 0: _a : List[str] = self.head # link new_node to head _a : Union[str, Any] = new_node else: _a : int = self.head for _ in range(index - 1 ): _a : Union[str, Any] = temp.next _a : List[str] = temp.next _a : Optional[int] = new_node def __lowercase ( self : Optional[int] ): # print every node data print(self ) def __lowercase ( self : str ): return self.delete_nth(0 ) def __lowercase ( self : str ): # delete from tail return self.delete_nth(len(self ) - 1 ) def __lowercase ( self : List[str] ,_UpperCAmelCase : int = 0 ): if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError('List index out of range.' ) _a : Optional[Any] = self.head # default first node if index == 0: _a : int = self.head.next else: _a : int = self.head for _ in range(index - 1 ): _a : str = temp.next _a : str = temp.next _a : int = temp.next.next return delete_node.data def __lowercase ( self : List[Any] ): return self.head is None def __lowercase ( self : Tuple ): _a : List[Any] = None _a : Tuple = self.head while current: # Store the current node's next node. _a : Dict = current.next # Make the current node's next point backwards _a : str = prev # Make the previous node be the current node _a : Tuple = current # Make the current node the next node (to progress iteration) _a : Optional[Any] = next_node # Return prev in order to put the head at the end _a : int = prev def __lowerCamelCase ( ) -> None: _a : List[str] = LinkedList() assert linked_list.is_empty() is True assert str(lowerCAmelCase_ ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(10 ): assert len(lowerCAmelCase_ ) == i linked_list.insert_nth(lowerCAmelCase_ , i + 1 ) assert str(lowerCAmelCase_ ) == "->".join(str(lowerCAmelCase_ ) for i in range(1 , 11 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(11 ) assert str(lowerCAmelCase_ ) == "->".join(str(lowerCAmelCase_ ) for i in range(0 , 12 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 10 assert linked_list.delete_tail() == 11 assert len(lowerCAmelCase_ ) == 9 assert str(lowerCAmelCase_ ) == "->".join(str(lowerCAmelCase_ ) for i in range(1 , 10 ) ) assert all(linked_list[i] == i + 1 for i in range(0 , 9 ) ) is True for i in range(0 , 9 ): _a : Union[str, Any] = -i assert all(linked_list[i] == -i for i in range(0 , 9 ) ) is True linked_list.reverse() assert str(lowerCAmelCase_ ) == "->".join(str(lowerCAmelCase_ ) for i in range(-8 , 1 ) ) def __lowerCamelCase ( ) -> None: _a : Dict = [ -9, 100, Node(77345112 ), 'dlrow olleH', 7, 5555, 0, -192.55_555, 'Hello, world!', 77.9, Node(10 ), None, None, 12.20, ] _a : List[Any] = LinkedList() for i in test_input: linked_list.insert_tail(lowerCAmelCase_ ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(lowerCAmelCase_ ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head _a : List[str] = linked_list.delete_head() assert result == -9 assert ( str(lowerCAmelCase_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail _a : Dict = linked_list.delete_tail() assert result == 12.2 assert ( str(lowerCAmelCase_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list _a : Optional[Any] = linked_list.delete_nth(10 ) assert result is None assert ( str(lowerCAmelCase_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node('Hello again, world!' ) ) assert ( str(lowerCAmelCase_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(lowerCAmelCase_ ) assert ( str(lowerCAmelCase_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(lowerCAmelCase_ ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def __lowerCamelCase ( ) -> Union[str, Any]: from doctest import testmod testmod() _a : Optional[int] = LinkedList() linked_list.insert_head(input('Inserting 1st at head ' ).strip() ) linked_list.insert_head(input('Inserting 2nd at head ' ).strip() ) print('\nPrint list:' ) linked_list.print_list() linked_list.insert_tail(input('\nInserting 1st at tail ' ).strip() ) linked_list.insert_tail(input('Inserting 2nd at tail ' ).strip() ) print('\nPrint list:' ) linked_list.print_list() print('\nDelete head' ) linked_list.delete_head() print('Delete tail' ) linked_list.delete_tail() print('\nPrint list:' ) linked_list.print_list() print('\nReverse linked list' ) linked_list.reverse() print('\nPrint list:' ) linked_list.print_list() print('\nString representation of linked list:' ) print(lowerCAmelCase_ ) print('\nReading/changing Node data using indexing:' ) print(f"""Element at Position 1: {linked_list[1]}""" ) _a : Optional[Any] = input('Enter New Value: ' ).strip() print('New list:' ) print(lowerCAmelCase_ ) print(f"""length of linked_list is : {len(lowerCAmelCase_ )}""" ) if __name__ == "__main__": main()
89
0
import re def A ( _lowerCamelCase ): '''simple docstring''' return [char.split() for char in re.split(r"[^ a-z A-Z 0-9 \s]" , str_ )] def A ( _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : Tuple = split_input(str_ ) return "".join( ["".join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def A ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' try: _lowerCAmelCase : Any = split_input(_lowerCamelCase ) if upper: _lowerCAmelCase : Dict = "".join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: _lowerCAmelCase : Dict = "".join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def A ( _lowerCamelCase ): '''simple docstring''' return to_simple_case(_lowerCamelCase ) def A ( _lowerCamelCase ): '''simple docstring''' try: _lowerCAmelCase : Dict = to_simple_case(_lowerCamelCase ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' return to_complex_case(_lowerCamelCase , _lowerCamelCase , "_" ) def A ( _lowerCamelCase , _lowerCamelCase ): '''simple docstring''' return to_complex_case(_lowerCamelCase , _lowerCamelCase , "-" ) if __name__ == "__main__": __import__("doctest").testmod()
36
'''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 __lowerCAmelCase = logging.getLogger() @unittest.skip('Temporarily disable the doc tests.' ) @require_torch @require_tf @slow class __magic_name__ ( unittest.TestCase ): def __lowercase ( self : str ,_UpperCAmelCase : Path ,_UpperCAmelCase : Union[str, None] = None ,_UpperCAmelCase : Union[List[str], None] = None ,_UpperCAmelCase : Union[str, List[str], None] = None ,_UpperCAmelCase : bool = True ,): _a : Dict = [file for file in os.listdir(_UpperCAmelCase ) if os.path.isfile(os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) )] if identifier is not None: _a : str = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): for n_ in n_identifier: _a : int = [file for file in files if n_ not in file] else: _a : Optional[Any] = [file for file in files if n_identifier not in file] _a : Dict = ignore_files or [] ignore_files.append('__init__.py' ) _a : List[str] = [file for file in files if file not in ignore_files] for file in files: # Open all files print('Testing' ,_UpperCAmelCase ) if only_modules: _a : Any = file.split('.' )[0] try: _a : Optional[int] = getattr(_UpperCAmelCase ,_UpperCAmelCase ) _a : Dict = doctest.DocTestSuite(_UpperCAmelCase ) _a : Optional[int] = unittest.TextTestRunner().run(_UpperCAmelCase ) self.assertIs(len(result.failures ) ,0 ) except AttributeError: logger.info(F"""{module_identifier} is not a module.""" ) else: _a : str = doctest.testfile(str('..' / directory / file ) ,optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed ,0 ) def __lowercase ( self : Union[str, Any] ): _a : Optional[Any] = Path('src/transformers' ) _a : Optional[Any] = 'modeling' _a : Union[str, Any] = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(_UpperCAmelCase ,identifier=_UpperCAmelCase ,ignore_files=_UpperCAmelCase ) def __lowercase ( self : int ): _a : str = Path('src/transformers' ) _a : List[str] = 'tokenization' self.analyze_directory(_UpperCAmelCase ,identifier=_UpperCAmelCase ) def __lowercase ( self : int ): _a : Any = Path('src/transformers' ) _a : str = 'configuration' self.analyze_directory(_UpperCAmelCase ,identifier=_UpperCAmelCase ) def __lowercase ( self : Dict ): _a : Tuple = Path('src/transformers' ) _a : Optional[int] = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(_UpperCAmelCase ,n_identifier=_UpperCAmelCase ) def __lowercase ( self : Optional[Any] ): _a : Union[str, Any] = Path('docs/source' ) _a : List[str] = ['favicon.ico'] self.analyze_directory(_UpperCAmelCase ,ignore_files=_UpperCAmelCase ,only_modules=_UpperCAmelCase )
89
0
'''simple docstring''' import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def _SCREAMING_SNAKE_CASE ( UpperCamelCase , UpperCamelCase , UpperCamelCase=1024 , UpperCamelCase=1024 , UpperCamelCase=False , **UpperCamelCase ): """simple docstring""" lowerCAmelCase__ : str = AutoTokenizer.from_pretrained(UpperCamelCase ) lowerCAmelCase__ : Optional[int] = SeqaSeqDataset(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , type_path="""train""" , **UpperCamelCase ) lowerCAmelCase__ : Optional[Any] = tok.pad_token_id def get_lens(UpperCamelCase ): lowerCAmelCase__ : Optional[int] = tqdm( DataLoader(UpperCamelCase , batch_size=512 , num_workers=8 , shuffle=UpperCamelCase , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) lowerCAmelCase__ : List[str] = [] for batch in dl: lowerCAmelCase__ : Dict = batch["""input_ids"""].ne(UpperCamelCase ).sum(1 ).tolist() lowerCAmelCase__ : str = batch["""labels"""].ne(UpperCamelCase ).sum(1 ).tolist() if consider_target: for src, tgt in zip(UpperCamelCase , UpperCamelCase ): max_lens.append(max(UpperCamelCase , UpperCamelCase ) ) else: max_lens.extend(UpperCamelCase ) return max_lens lowerCAmelCase__ : int = get_lens(UpperCamelCase ) lowerCAmelCase__ : int = SeqaSeqDataset(UpperCamelCase , UpperCamelCase , UpperCamelCase , UpperCamelCase , type_path="""val""" , **UpperCamelCase ) lowerCAmelCase__ : str = get_lens(UpperCamelCase ) pickle_save(UpperCamelCase , train_ds.len_file ) pickle_save(UpperCamelCase , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
37
'''simple docstring''' import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_processing_utils import ImageProcessingMixin from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = OrderedDict( [ ('''align''', '''EfficientNetImageProcessor'''), ('''beit''', '''BeitImageProcessor'''), ('''bit''', '''BitImageProcessor'''), ('''blip''', '''BlipImageProcessor'''), ('''blip-2''', '''BlipImageProcessor'''), ('''bridgetower''', '''BridgeTowerImageProcessor'''), ('''chinese_clip''', '''ChineseCLIPImageProcessor'''), ('''clip''', '''CLIPImageProcessor'''), ('''clipseg''', '''ViTImageProcessor'''), ('''conditional_detr''', '''ConditionalDetrImageProcessor'''), ('''convnext''', '''ConvNextImageProcessor'''), ('''convnextv2''', '''ConvNextImageProcessor'''), ('''cvt''', '''ConvNextImageProcessor'''), ('''data2vec-vision''', '''BeitImageProcessor'''), ('''deformable_detr''', '''DeformableDetrImageProcessor'''), ('''deit''', '''DeiTImageProcessor'''), ('''deta''', '''DetaImageProcessor'''), ('''detr''', '''DetrImageProcessor'''), ('''dinat''', '''ViTImageProcessor'''), ('''donut-swin''', '''DonutImageProcessor'''), ('''dpt''', '''DPTImageProcessor'''), ('''efficientformer''', '''EfficientFormerImageProcessor'''), ('''efficientnet''', '''EfficientNetImageProcessor'''), ('''flava''', '''FlavaImageProcessor'''), ('''focalnet''', '''BitImageProcessor'''), ('''git''', '''CLIPImageProcessor'''), ('''glpn''', '''GLPNImageProcessor'''), ('''groupvit''', '''CLIPImageProcessor'''), ('''imagegpt''', '''ImageGPTImageProcessor'''), ('''instructblip''', '''BlipImageProcessor'''), ('''layoutlmv2''', '''LayoutLMv2ImageProcessor'''), ('''layoutlmv3''', '''LayoutLMv3ImageProcessor'''), ('''levit''', '''LevitImageProcessor'''), ('''mask2former''', '''Mask2FormerImageProcessor'''), ('''maskformer''', '''MaskFormerImageProcessor'''), ('''mgp-str''', '''ViTImageProcessor'''), ('''mobilenet_v1''', '''MobileNetV1ImageProcessor'''), ('''mobilenet_v2''', '''MobileNetV2ImageProcessor'''), ('''mobilevit''', '''MobileViTImageProcessor'''), ('''mobilevit''', '''MobileViTImageProcessor'''), ('''mobilevitv2''', '''MobileViTImageProcessor'''), ('''nat''', '''ViTImageProcessor'''), ('''oneformer''', '''OneFormerImageProcessor'''), ('''owlvit''', '''OwlViTImageProcessor'''), ('''perceiver''', '''PerceiverImageProcessor'''), ('''pix2struct''', '''Pix2StructImageProcessor'''), ('''poolformer''', '''PoolFormerImageProcessor'''), ('''regnet''', '''ConvNextImageProcessor'''), ('''resnet''', '''ConvNextImageProcessor'''), ('''sam''', '''SamImageProcessor'''), ('''segformer''', '''SegformerImageProcessor'''), ('''swiftformer''', '''ViTImageProcessor'''), ('''swin''', '''ViTImageProcessor'''), ('''swin2sr''', '''Swin2SRImageProcessor'''), ('''swinv2''', '''ViTImageProcessor'''), ('''table-transformer''', '''DetrImageProcessor'''), ('''timesformer''', '''VideoMAEImageProcessor'''), ('''tvlt''', '''TvltImageProcessor'''), ('''upernet''', '''SegformerImageProcessor'''), ('''van''', '''ConvNextImageProcessor'''), ('''videomae''', '''VideoMAEImageProcessor'''), ('''vilt''', '''ViltImageProcessor'''), ('''vit''', '''ViTImageProcessor'''), ('''vit_hybrid''', '''ViTHybridImageProcessor'''), ('''vit_mae''', '''ViTImageProcessor'''), ('''vit_msn''', '''ViTImageProcessor'''), ('''xclip''', '''CLIPImageProcessor'''), ('''yolos''', '''YolosImageProcessor'''), ] ) __lowerCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def __lowerCamelCase ( lowerCAmelCase_ ) -> Optional[Any]: for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: _a : List[Any] = model_type_to_module_name(lowerCAmelCase_ ) _a : Optional[Any] = importlib.import_module(f""".{module_name}""" , 'transformers.models' ) try: return getattr(lowerCAmelCase_ , lowerCAmelCase_ ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(lowerCAmelCase_ , '__name__' , lowerCAmelCase_ ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. _a : Dict = importlib.import_module('transformers' ) if hasattr(lowerCAmelCase_ , lowerCAmelCase_ ): return getattr(lowerCAmelCase_ , lowerCAmelCase_ ) return None def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = False , lowerCAmelCase_ = False , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = False , **lowerCAmelCase_ , ) -> Tuple: _a : List[str] = get_file_from_repo( lowerCAmelCase_ , lowerCAmelCase_ , cache_dir=lowerCAmelCase_ , force_download=lowerCAmelCase_ , resume_download=lowerCAmelCase_ , proxies=lowerCAmelCase_ , use_auth_token=lowerCAmelCase_ , revision=lowerCAmelCase_ , local_files_only=lowerCAmelCase_ , ) if resolved_config_file is None: logger.info( 'Could not locate the image processor configuration file, will try to use the model config instead.' ) return {} with open(lowerCAmelCase_ , encoding='utf-8' ) as reader: return json.load(lowerCAmelCase_ ) class __magic_name__ : def __init__( self : List[str] ): raise EnvironmentError( 'AutoImageProcessor is designed to be instantiated ' 'using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.' ) @classmethod @replace_list_option_in_docstrings(_UpperCAmelCase ) def __lowercase ( cls : Dict ,_UpperCAmelCase : Union[str, Any] ,**_UpperCAmelCase : Optional[Any] ): _a : Any = kwargs.pop('config' ,_UpperCAmelCase ) _a : Dict = kwargs.pop('trust_remote_code' ,_UpperCAmelCase ) _a : Any = True _a , _a : Tuple = ImageProcessingMixin.get_image_processor_dict(_UpperCAmelCase ,**_UpperCAmelCase ) _a : List[Any] = config_dict.get('image_processor_type' ,_UpperCAmelCase ) _a : int = None if "AutoImageProcessor" in config_dict.get('auto_map' ,{} ): _a : Any = config_dict['auto_map']['AutoImageProcessor'] # If we still don't have the image processor class, check if we're loading from a previous feature extractor config # and if so, infer the image processor class from there. if image_processor_class is None and image_processor_auto_map is None: _a : List[Any] = config_dict.pop('feature_extractor_type' ,_UpperCAmelCase ) if feature_extractor_class is not None: logger.warning( 'Could not find image processor class in the image processor config or the model config. Loading' ' based on pattern matching with the model\'s feature extractor configuration.' ) _a : Optional[int] = feature_extractor_class.replace('FeatureExtractor' ,'ImageProcessor' ) if "AutoFeatureExtractor" in config_dict.get('auto_map' ,{} ): _a : List[Any] = config_dict['auto_map']['AutoFeatureExtractor'] _a : List[str] = feature_extractor_auto_map.replace('FeatureExtractor' ,'ImageProcessor' ) logger.warning( 'Could not find image processor auto map in the image processor config or the model config.' ' Loading based on pattern matching with the model\'s feature extractor configuration.' ) # If we don't find the image processor class in the image processor config, let's try the model config. if image_processor_class is None and image_processor_auto_map is None: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : Dict = AutoConfig.from_pretrained(_UpperCAmelCase ,**_UpperCAmelCase ) # It could be in `config.image_processor_type`` _a : Optional[int] = getattr(_UpperCAmelCase ,'image_processor_type' ,_UpperCAmelCase ) if hasattr(_UpperCAmelCase ,'auto_map' ) and "AutoImageProcessor" in config.auto_map: _a : Union[str, Any] = config.auto_map['AutoImageProcessor'] if image_processor_class is not None: _a : Optional[int] = image_processor_class_from_name(_UpperCAmelCase ) _a : List[str] = image_processor_auto_map is not None _a : Optional[int] = image_processor_class is not None or type(_UpperCAmelCase ) in IMAGE_PROCESSOR_MAPPING _a : Optional[int] = resolve_trust_remote_code( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) if has_remote_code and trust_remote_code: _a : Dict = get_class_from_dynamic_module( _UpperCAmelCase ,_UpperCAmelCase ,**_UpperCAmelCase ) _a : int = kwargs.pop('code_revision' ,_UpperCAmelCase ) if os.path.isdir(_UpperCAmelCase ): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(_UpperCAmelCase ,**_UpperCAmelCase ) elif image_processor_class is not None: return image_processor_class.from_dict(_UpperCAmelCase ,**_UpperCAmelCase ) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(_UpperCAmelCase ) in IMAGE_PROCESSOR_MAPPING: _a : Dict = IMAGE_PROCESSOR_MAPPING[type(_UpperCAmelCase )] return image_processor_class.from_dict(_UpperCAmelCase ,**_UpperCAmelCase ) raise ValueError( F"""Unrecognized image processor in {pretrained_model_name_or_path}. Should have a """ F"""`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following """ F"""`model_type` keys in its {CONFIG_NAME}: {', '.join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}""" ) @staticmethod def __lowercase ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Dict ): IMAGE_PROCESSOR_MAPPING.register(_UpperCAmelCase ,_UpperCAmelCase )
89
0
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import ShapEPipeline else: from .camera import create_pan_cameras from .pipeline_shap_e import ShapEPipeline from .pipeline_shap_e_img2img import ShapEImgaImgPipeline from .renderer import ( BoundingBoxVolume, ImportanceRaySampler, MLPNeRFModelOutput, MLPNeRSTFModel, ShapEParamsProjModel, ShapERenderer, StratifiedRaySampler, VoidNeRFModel, )
38
'''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 __lowerCAmelCase = None __lowerCAmelCase = '''<''' 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 __lowerCAmelCase = [ 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 __magic_name__ : lowerCAmelCase : bool = True lowerCAmelCase : Optional[str] = None # Automatically constructed lowerCAmelCase : ClassVar[str] = "PIL.Image.Image" lowerCAmelCase : ClassVar[Any] = pa.struct({'bytes': pa.binary(), 'path': pa.string()} ) lowerCAmelCase : str = field(default='Image' , init=_UpperCamelCase , repr=_UpperCamelCase ) def __call__( self : Union[str, Any] ): return self.pa_type def __lowercase ( self : Any ,_UpperCAmelCase : Union[str, bytes, dict, np.ndarray, "PIL.Image.Image"] ): if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support encoding images, please install \'Pillow\'.' ) if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : Optional[Any] = np.array(_UpperCAmelCase ) if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): return {"path": value, "bytes": None} elif isinstance(_UpperCAmelCase ,_UpperCAmelCase ): return {"path": None, "bytes": value} elif isinstance(_UpperCAmelCase ,np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(_UpperCAmelCase ) 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 __lowercase ( self : Optional[Any] ,_UpperCAmelCase : dict ,_UpperCAmelCase : Optional[int]=None ): 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 : Dict = {} _a , _a : str = 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(_UpperCAmelCase ): _a : Any = PIL.Image.open(_UpperCAmelCase ) else: _a : List[Any] = path.split('::' )[-1] try: _a : str = string_to_dict(_UpperCAmelCase ,config.HUB_DATASETS_URL )['repo_id'] _a : Optional[Any] = token_per_repo_id.get(_UpperCAmelCase ) except ValueError: _a : int = None with xopen(_UpperCAmelCase ,'rb' ,use_auth_token=_UpperCAmelCase ) as f: _a : Tuple = BytesIO(f.read() ) _a : Union[str, Any] = PIL.Image.open(bytes_ ) else: _a : Optional[int] = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def __lowercase ( self : int ): from .features import Value return ( self if self.decode else { "bytes": Value('binary' ), "path": Value('string' ), } ) def __lowercase ( self : str ,_UpperCAmelCase : Union[pa.StringArray, pa.StructArray, pa.ListArray] ): if pa.types.is_string(storage.type ): _a : Union[str, Any] = pa.array([None] * len(_UpperCAmelCase ) ,type=pa.binary() ) _a : Union[str, 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(_UpperCAmelCase ) ,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 : Tuple = pa.array([None] * len(_UpperCAmelCase ) ,type=pa.binary() ) if storage.type.get_field_index('path' ) >= 0: _a : Union[str, Any] = storage.field('path' ) else: _a : Dict = pa.array([None] * len(_UpperCAmelCase ) ,type=pa.string() ) _a : Optional[Any] = pa.StructArray.from_arrays([bytes_array, path_array] ,['bytes', 'path'] ,mask=storage.is_null() ) elif pa.types.is_list(storage.type ): _a : List[str] = pa.array( [encode_np_array(np.array(_UpperCAmelCase ) )['bytes'] if arr is not None else None for arr in storage.to_pylist()] ,type=pa.binary() ,) _a : int = pa.array([None] * len(_UpperCAmelCase ) ,type=pa.string() ) _a : Optional[Any] = pa.StructArray.from_arrays( [bytes_array, path_array] ,['bytes', 'path'] ,mask=bytes_array.is_null() ) return array_cast(_UpperCAmelCase ,self.pa_type ) def __lowercase ( self : Dict ,_UpperCAmelCase : pa.StructArray ): @no_op_if_value_is_null def path_to_bytes(_UpperCAmelCase : Tuple ): with xopen(_UpperCAmelCase ,'rb' ) as f: _a : int = f.read() return bytes_ _a : Any = 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 : Optional[Any] = pa.array( [os.path.basename(_UpperCAmelCase ) if path is not None else None for path in storage.field('path' ).to_pylist()] ,type=pa.string() ,) _a : Dict = pa.StructArray.from_arrays([bytes_array, path_array] ,['bytes', 'path'] ,mask=bytes_array.is_null() ) return array_cast(_UpperCAmelCase ,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 ( lowerCAmelCase_ ) -> bytes: _a : Optional[int] = BytesIO() if image.format in list_image_compression_formats(): _a : Optional[Any] = image.format else: _a : str = 'PNG' if image.mode in ['1', 'L', 'LA', 'RGB', 'RGBA'] else 'TIFF' image.save(lowerCAmelCase_ , format=lowerCAmelCase_ ) return buffer.getvalue() def __lowerCamelCase ( lowerCAmelCase_ ) -> dict: if hasattr(lowerCAmelCase_ , 'filename' ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(lowerCAmelCase_ )} def __lowerCamelCase ( lowerCAmelCase_ ) -> dict: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support encoding images, please install \'Pillow\'.' ) _a : List[Any] = array.dtype _a : Optional[int] = dtype.byteorder if dtype.byteorder != '=' else _NATIVE_BYTEORDER _a : Union[str, Any] = dtype.kind _a : Union[str, Any] = dtype.itemsize _a : List[Any] = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: _a : Optional[int] = 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 : Union[str, 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 : str = dtype_byteorder + dtype_kind + str(lowerCAmelCase_ ) _a : List[Any] = np.dtype(lowerCAmelCase_ ) 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(lowerCAmelCase_ ) ) return {"path": None, "bytes": image_to_bytes(lowerCAmelCase_ )} def __lowerCamelCase ( lowerCAmelCase_ ) -> List[dict]: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support encoding images, please install \'Pillow\'.' ) if objs: _a , _a : Optional[Any] = first_non_null_value(lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(lowerCAmelCase_ , np.ndarray ): _a : List[str] = no_op_if_value_is_null(lowerCAmelCase_ ) return [obj_to_image_dict_func(lowerCAmelCase_ ) for obj in objs] elif isinstance(lowerCAmelCase_ , PIL.Image.Image ): _a : List[str] = no_op_if_value_is_null(lowerCAmelCase_ ) return [obj_to_image_dict_func(lowerCAmelCase_ ) for obj in objs] else: return objs else: return objs
89
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) _a = { '''configuration_convnext''': ['''CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ConvNextConfig''', '''ConvNextOnnxConfig'''] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a = ['''ConvNextFeatureExtractor'''] _a = ['''ConvNextImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a = [ '''CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''ConvNextForImageClassification''', '''ConvNextModel''', '''ConvNextPreTrainedModel''', '''ConvNextBackbone''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _a = [ '''TFConvNextForImageClassification''', '''TFConvNextModel''', '''TFConvNextPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_convnext import CONVNEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvNextConfig, ConvNextOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_convnext import ConvNextFeatureExtractor from .image_processing_convnext import ConvNextImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_convnext import ( CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST, ConvNextBackbone, ConvNextForImageClassification, ConvNextModel, ConvNextPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_convnext import TFConvNextForImageClassification, TFConvNextModel, TFConvNextPreTrainedModel else: import sys _a = _LazyModule(__name__, globals()['''__file__'''], _import_structure)
39
'''simple docstring''' from __future__ import annotations from collections.abc import Sequence from typing import Literal def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> str | Literal[False]: _a : Optional[int] = list(lowerCAmelCase_ ) _a : Optional[Any] = list(lowerCAmelCase_ ) _a : Union[str, Any] = 0 for i in range(len(lowerCAmelCase_ ) ): if lista[i] != lista[i]: count += 1 _a : Optional[int] = '_' if count > 1: return False else: return "".join(lowerCAmelCase_ ) def __lowerCamelCase ( lowerCAmelCase_ ) -> list[str]: _a : Optional[int] = [] while True: _a : Any = ['$'] * len(lowerCAmelCase_ ) _a : List[str] = [] for i in range(len(lowerCAmelCase_ ) ): for j in range(i + 1 , len(lowerCAmelCase_ ) ): _a : Optional[int] = compare_string(binary[i] , binary[j] ) if k is False: _a : Optional[Any] = '*' _a : Optional[Any] = '*' temp.append('X' ) for i in range(len(lowerCAmelCase_ ) ): if checka[i] == "$": pi.append(binary[i] ) if len(lowerCAmelCase_ ) == 0: return pi _a : Any = list(set(lowerCAmelCase_ ) ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> list[str]: _a : int = [] for minterm in minterms: _a : Optional[int] = '' for _ in range(lowerCAmelCase_ ): _a : Union[str, Any] = str(minterm % 2 ) + string minterm //= 2 temp.append(lowerCAmelCase_ ) return temp def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> bool: _a : int = list(lowerCAmelCase_ ) _a : Union[str, Any] = list(lowerCAmelCase_ ) _a : str = 0 for i in range(len(lowerCAmelCase_ ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> list[str]: _a : List[Any] = [] _a : Optional[Any] = [0] * len(lowerCAmelCase_ ) for i in range(len(chart[0] ) ): _a : Union[str, Any] = 0 _a : int = -1 for j in range(len(lowerCAmelCase_ ) ): if chart[j][i] == 1: count += 1 _a : int = j if count == 1: _a : List[Any] = 1 for i in range(len(lowerCAmelCase_ ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(lowerCAmelCase_ ) ): _a : Any = 0 temp.append(prime_implicants[i] ) while True: _a : Union[str, Any] = 0 _a : List[Any] = -1 _a : str = 0 for i in range(len(lowerCAmelCase_ ) ): _a : Union[str, Any] = chart[i].count(1 ) if count_n > max_n: _a : Any = count_n _a : int = i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(lowerCAmelCase_ ) ): _a : List[str] = 0 def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> list[list[int]]: _a : int = [[0 for x in range(len(lowerCAmelCase_ ) )] for x in range(len(lowerCAmelCase_ ) )] for i in range(len(lowerCAmelCase_ ) ): _a : str = prime_implicants[i].count('_' ) for j in range(len(lowerCAmelCase_ ) ): if is_for_table(prime_implicants[i] , binary[j] , lowerCAmelCase_ ): _a : Optional[Any] = 1 return chart def __lowerCamelCase ( ) -> None: _a : Optional[int] = int(input('Enter the no. of variables\n' ) ) _a : List[Any] = [ float(lowerCAmelCase_ ) for x in input( 'Enter the decimal representation of Minterms \'Spaces Separated\'\n' ).split() ] _a : List[str] = decimal_to_binary(lowerCAmelCase_ , lowerCAmelCase_ ) _a : Dict = check(lowerCAmelCase_ ) print('Prime Implicants are:' ) print(lowerCAmelCase_ ) _a : List[Any] = prime_implicant_chart(lowerCAmelCase_ , lowerCAmelCase_ ) _a : int = selection(lowerCAmelCase_ , lowerCAmelCase_ ) print('Essential Prime Implicants are:' ) print(lowerCAmelCase_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
89
0
"""simple docstring""" from __future__ import annotations from collections import deque class _A : """simple docstring""" def __init__( self : str , __UpperCAmelCase : list[str]): a : list[dict] = [] self.adlist.append( {"value": "", "next_states": [], "fail_state": 0, "output": []}) for keyword in keywords: self.add_keyword(__UpperCAmelCase) self.set_fail_transitions() def __snake_case ( self : Dict , __UpperCAmelCase : int , __UpperCAmelCase : str): for state in self.adlist[current_state]["next_states"]: if char == self.adlist[state]["value"]: return state return None def __snake_case ( self : str , __UpperCAmelCase : str): a : Dict = 0 for character in keyword: a : Any = self.find_next_state(__UpperCAmelCase , __UpperCAmelCase) if next_state is None: self.adlist.append( { "value": character, "next_states": [], "fail_state": 0, "output": [], }) self.adlist[current_state]["next_states"].append(len(self.adlist) - 1) a : Tuple = len(self.adlist) - 1 else: a : Tuple = next_state self.adlist[current_state]["output"].append(__UpperCAmelCase) def __snake_case ( self : Optional[Any]): a : deque = deque() for node in self.adlist[0]["next_states"]: q.append(__UpperCAmelCase) a : Optional[Any] = 0 while q: a : Optional[int] = q.popleft() for child in self.adlist[r]["next_states"]: q.append(__UpperCAmelCase) a : List[str] = self.adlist[r]["fail_state"] while ( self.find_next_state(__UpperCAmelCase , self.adlist[child]["value"]) is None and state != 0 ): a : Optional[int] = self.adlist[state]["fail_state"] a : Dict = self.find_next_state( __UpperCAmelCase , self.adlist[child]["value"]) if self.adlist[child]["fail_state"] is None: a : Optional[int] = 0 a : Union[str, Any] = ( self.adlist[child]["output"] + self.adlist[self.adlist[child]["fail_state"]]["output"] ) def __snake_case ( self : List[Any] , __UpperCAmelCase : str): a : dict = {} # returns a dict with keywords and list of its occurrences a : Any = 0 for i in range(len(__UpperCAmelCase)): while ( self.find_next_state(__UpperCAmelCase , string[i]) is None and current_state != 0 ): a : Any = self.adlist[current_state]["fail_state"] a : str = self.find_next_state(__UpperCAmelCase , string[i]) if next_state is None: a : Dict = 0 else: a : Optional[int] = next_state for key in self.adlist[current_state]["output"]: if key not in result: a : List[str] = [] result[key].append(i - len(__UpperCAmelCase) + 1) return result if __name__ == "__main__": import doctest doctest.testmod()
40
'''simple docstring''' # Copyright 2022 The HuggingFace Team and The OpenBMB Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __lowerCAmelCase = { '''configuration_cpmant''': ['''CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CpmAntConfig'''], '''tokenization_cpmant''': ['''CpmAntTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CpmAntForCausalLM''', '''CpmAntModel''', '''CpmAntPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
89
0
'''simple docstring''' import operator as op _A : Optional[Any] ='''scaler.pt''' _A : Optional[Any] ='''pytorch_model''' _A : int ='''random_states''' _A : List[Any] ='''optimizer''' _A : Dict ='''scheduler''' _A : Dict ='''pytorch_model.bin''' _A : Optional[Any] ='''pytorch_model.bin.index.json''' _A : List[str] ='''model.safetensors''' _A : List[Any] ='''model.safetensors.index.json''' _A : str ='''1.10.2''' _A : List[Any] ='''py38''' _A : int ='''4.17.0''' _A : List[str] =['''ml.p3.16xlarge''', '''ml.p3dn.24xlarge''', '''ml.p4dn.24xlarge'''] _A : Tuple =['''FULL_SHARD''', '''SHARD_GRAD_OP''', '''NO_SHARD''', '''HYBRID_SHARD''', '''HYBRID_SHARD_ZERO2'''] _A : Tuple =['''TRANSFORMER_BASED_WRAP''', '''SIZE_BASED_WRAP''', '''NO_WRAP'''] _A : Optional[int] =['''BACKWARD_PRE''', '''BACKWARD_POST''', '''NO_PREFETCH'''] _A : Optional[int] =['''FULL_STATE_DICT''', '''LOCAL_STATE_DICT''', '''SHARDED_STATE_DICT'''] _A : List[Any] ='''2.0.1''' _A : str =['''pdsh''', '''standard''', '''openmpi''', '''mvapich'''] _A : List[str] =['''default''', '''reduce-overhead''', '''max-autotune'''] _A : str ={'''>''': op.gt, '''>=''': op.ge, '''==''': op.eq, '''!=''': op.ne, '''<=''': op.le, '''<''': op.lt} # These are the args for `torch.distributed.launch` for pytorch < 1.9 _A : Tuple =[ '''nnodes''', '''nproc_per_node''', '''rdzv_backend''', '''rdzv_endpoint''', '''rdzv_id''', '''rdzv_conf''', '''standalone''', '''max_restarts''', '''monitor_interval''', '''start_method''', '''role''', '''module''', '''m''', '''no_python''', '''run_path''', '''log_dir''', '''r''', '''redirects''', '''t''', '''tee''', '''node_rank''', '''master_addr''', '''master_port''', ] _A : Any =['''DEEPSPEED''', '''MULTI_GPU''', '''FSDP''', '''MEGATRON_LM'''] _A : Union[str, Any] =['''DEEPSPEED''', '''MULTI_XPU''', '''FSDP''']
41
'''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 __magic_name__ ( _UpperCamelCase , unittest.TestCase ): lowerCAmelCase : str = LayoutLMTokenizer lowerCAmelCase : Tuple = LayoutLMTokenizerFast lowerCAmelCase : List[Any] = True lowerCAmelCase : int = True def __lowercase ( self : Dict ): super().setUp() _a : int = [ '[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] _a : List[str] = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def __lowercase ( self : Dict ,**_UpperCAmelCase : List[str] ): return LayoutLMTokenizer.from_pretrained(self.tmpdirname ,**_UpperCAmelCase ) def __lowercase ( self : Optional[Any] ,_UpperCAmelCase : Tuple ): _a : Optional[int] = 'UNwant\u00E9d,running' _a : List[Any] = 'unwanted, running' return input_text, output_text def __lowercase ( self : Optional[int] ): _a : Optional[Any] = self.tokenizer_class(self.vocab_file ) _a : Optional[Any] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(_UpperCAmelCase ,['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_UpperCAmelCase ) ,[7, 4, 5, 10, 8, 9] ) def __lowercase ( self : Optional[int] ): pass
89
0
'''simple docstring''' import pytest from datasets.parallel import ParallelBackendConfig, parallel_backend from datasets.utils.py_utils import map_nested from .utils import require_dill_gt_0_3_2, require_joblibspark, require_not_windows def SCREAMING_SNAKE_CASE__ ( __A ) -> Dict: # picklable for multiprocessing return i + 1 @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows def SCREAMING_SNAKE_CASE__ ( ) -> Optional[int]: with parallel_backend('spark' ): assert ParallelBackendConfig.backend_name == "spark" _snake_case = [1, 2, 3] with pytest.raises(__A ): with parallel_backend('unsupported backend' ): map_nested(__A , __A , num_proc=2 ) with pytest.raises(__A ): with parallel_backend('unsupported backend' ): map_nested(__A , __A , num_proc=-1 ) @require_dill_gt_0_3_2 @require_joblibspark @require_not_windows @pytest.mark.parametrize('num_proc' , [2, -1] ) def SCREAMING_SNAKE_CASE__ ( __A ) -> List[str]: _snake_case = [1, 2] _snake_case = {'a': 1, 'b': 2} _snake_case = {'a': [1, 2], 'b': [3, 4]} _snake_case = {'a': {'1': 1}, 'b': 2} _snake_case = {'a': 1, 'b': 2, 'c': 3, 'd': 4} _snake_case = [2, 3] _snake_case = {'a': 2, 'b': 3} _snake_case = {'a': [2, 3], 'b': [4, 5]} _snake_case = {'a': {'1': 2}, 'b': 3} _snake_case = {'a': 2, 'b': 3, 'c': 4, 'd': 5} with parallel_backend('spark' ): assert map_nested(__A , __A , num_proc=__A ) == expected_map_nested_sa assert map_nested(__A , __A , num_proc=__A ) == expected_map_nested_sa assert map_nested(__A , __A , num_proc=__A ) == expected_map_nested_sa assert map_nested(__A , __A , num_proc=__A ) == expected_map_nested_sa assert map_nested(__A , __A , num_proc=__A ) == expected_map_nested_sa
42
'''simple docstring''' import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { '''microsoft/conditional-detr-resnet-50''': ( '''https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json''' ), } class __magic_name__ ( _UpperCamelCase ): lowerCAmelCase : Any = 'conditional_detr' lowerCAmelCase : List[str] = ['past_key_values'] lowerCAmelCase : Optional[int] = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : Optional[int] ,_UpperCAmelCase : Optional[int]=True ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : List[Any]=3 ,_UpperCAmelCase : List[Any]=300 ,_UpperCAmelCase : Dict=6 ,_UpperCAmelCase : List[str]=2048 ,_UpperCAmelCase : Optional[int]=8 ,_UpperCAmelCase : List[Any]=6 ,_UpperCAmelCase : Optional[int]=2048 ,_UpperCAmelCase : Dict=8 ,_UpperCAmelCase : int=0.0 ,_UpperCAmelCase : Optional[Any]=0.0 ,_UpperCAmelCase : Optional[Any]=True ,_UpperCAmelCase : str="relu" ,_UpperCAmelCase : Tuple=256 ,_UpperCAmelCase : Optional[int]=0.1 ,_UpperCAmelCase : str=0.0 ,_UpperCAmelCase : Optional[int]=0.0 ,_UpperCAmelCase : Union[str, Any]=0.02 ,_UpperCAmelCase : List[str]=1.0 ,_UpperCAmelCase : Any=False ,_UpperCAmelCase : int="sine" ,_UpperCAmelCase : List[str]="resnet50" ,_UpperCAmelCase : Optional[int]=True ,_UpperCAmelCase : str=False ,_UpperCAmelCase : str=2 ,_UpperCAmelCase : int=5 ,_UpperCAmelCase : Optional[int]=2 ,_UpperCAmelCase : str=1 ,_UpperCAmelCase : Union[str, Any]=1 ,_UpperCAmelCase : List[str]=2 ,_UpperCAmelCase : Union[str, Any]=5 ,_UpperCAmelCase : List[Any]=2 ,_UpperCAmelCase : Optional[int]=0.25 ,**_UpperCAmelCase : Tuple ,): if backbone_config is not None and use_timm_backbone: raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.' ) if not use_timm_backbone: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) _a : Optional[Any] = CONFIG_MAPPING['resnet'](out_features=['stage4'] ) elif isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : str = backbone_config.get('model_type' ) _a : Union[str, Any] = CONFIG_MAPPING[backbone_model_type] _a : List[Any] = config_class.from_dict(_UpperCAmelCase ) _a : Tuple = use_timm_backbone _a : Union[str, Any] = backbone_config _a : List[Any] = num_channels _a : Union[str, Any] = num_queries _a : Optional[Any] = d_model _a : Tuple = encoder_ffn_dim _a : Dict = encoder_layers _a : List[str] = encoder_attention_heads _a : Union[str, Any] = decoder_ffn_dim _a : Optional[int] = decoder_layers _a : int = decoder_attention_heads _a : Optional[int] = dropout _a : Tuple = attention_dropout _a : List[Any] = activation_dropout _a : str = activation_function _a : Optional[Any] = init_std _a : Union[str, Any] = init_xavier_std _a : List[Any] = encoder_layerdrop _a : List[Any] = decoder_layerdrop _a : Dict = encoder_layers _a : List[Any] = auxiliary_loss _a : Optional[int] = position_embedding_type _a : List[Any] = backbone _a : Optional[int] = use_pretrained_backbone _a : Optional[int] = dilation # Hungarian matcher _a : Tuple = class_cost _a : str = bbox_cost _a : Any = giou_cost # Loss coefficients _a : Tuple = mask_loss_coefficient _a : Dict = dice_loss_coefficient _a : Tuple = cls_loss_coefficient _a : Any = bbox_loss_coefficient _a : Dict = giou_loss_coefficient _a : Union[str, Any] = focal_alpha super().__init__(is_encoder_decoder=_UpperCAmelCase ,**_UpperCAmelCase ) @property def __lowercase ( self : Dict ): return self.encoder_attention_heads @property def __lowercase ( self : str ): return self.d_model def __lowercase ( self : int ): _a : List[str] = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: _a : Dict = self.backbone_config.to_dict() _a : Union[str, Any] = self.__class__.model_type return output class __magic_name__ ( _UpperCamelCase ): lowerCAmelCase : str = version.parse('1.11' ) @property def __lowercase ( self : Dict ): return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('pixel_mask', {0: 'batch'}), ] ) @property def __lowercase ( self : Any ): return 1E-5 @property def __lowercase ( self : List[Any] ): return 12
89
0
import unittest from transformers import AlbertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, ) from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST class lowerCamelCase_ : '''simple docstring''' def __init__( self , __lowercase , __lowercase=13 , __lowercase=7 , __lowercase=True , __lowercase=True , __lowercase=True , __lowercase=True , __lowercase=99 , __lowercase=16 , __lowercase=36 , __lowercase=6 , __lowercase=6 , __lowercase=6 , __lowercase=37 , __lowercase="gelu" , __lowercase=0.1 , __lowercase=0.1 , __lowercase=512 , __lowercase=16 , __lowercase=2 , __lowercase=0.02 , __lowercase=3 , __lowercase=4 , __lowercase=None , ) -> Optional[Any]: __UpperCamelCase :str = parent __UpperCamelCase :List[str] = batch_size __UpperCamelCase :List[Any] = seq_length __UpperCamelCase :Optional[Any] = is_training __UpperCamelCase :List[Any] = use_input_mask __UpperCamelCase :str = use_token_type_ids __UpperCamelCase :Dict = use_labels __UpperCamelCase :List[str] = vocab_size __UpperCamelCase :Any = embedding_size __UpperCamelCase :Union[str, Any] = hidden_size __UpperCamelCase :Tuple = num_hidden_layers __UpperCamelCase :List[Any] = num_hidden_groups __UpperCamelCase :Optional[Any] = num_attention_heads __UpperCamelCase :Tuple = intermediate_size __UpperCamelCase :Any = hidden_act __UpperCamelCase :Optional[Any] = hidden_dropout_prob __UpperCamelCase :Any = attention_probs_dropout_prob __UpperCamelCase :List[Any] = max_position_embeddings __UpperCamelCase :str = type_vocab_size __UpperCamelCase :Any = type_sequence_label_size __UpperCamelCase :int = initializer_range __UpperCamelCase :int = num_labels __UpperCamelCase :Tuple = num_choices __UpperCamelCase :str = scope def UpperCamelCase__ ( self) -> Dict: __UpperCamelCase :Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) __UpperCamelCase :int = None if self.use_input_mask: __UpperCamelCase :str = random_attention_mask([self.batch_size, self.seq_length]) __UpperCamelCase :Dict = None if self.use_token_type_ids: __UpperCamelCase :Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size) __UpperCamelCase :Optional[Any] = None __UpperCamelCase :Dict = None __UpperCamelCase :List[Any] = None if self.use_labels: __UpperCamelCase :str = ids_tensor([self.batch_size] , self.type_sequence_label_size) __UpperCamelCase :Dict = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) __UpperCamelCase :Optional[Any] = ids_tensor([self.batch_size] , self.num_choices) __UpperCamelCase :Tuple = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase__ ( self) -> List[Any]: return AlbertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , num_hidden_groups=self.num_hidden_groups , ) def UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase) -> Union[str, Any]: __UpperCamelCase :Optional[int] = AlbertModel(config=__lowercase) model.to(__lowercase) model.eval() __UpperCamelCase :Optional[Any] = model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase) __UpperCamelCase :List[Any] = model(__lowercase , token_type_ids=__lowercase) __UpperCamelCase :int = model(__lowercase) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size)) def UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase) -> Optional[Any]: __UpperCamelCase :int = AlbertForPreTraining(config=__lowercase) model.to(__lowercase) model.eval() __UpperCamelCase :List[str] = model( __lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase , sentence_order_label=__lowercase , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) self.parent.assertEqual(result.sop_logits.shape , (self.batch_size, config.num_labels)) def UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase) -> Union[str, Any]: __UpperCamelCase :Dict = AlbertForMaskedLM(config=__lowercase) model.to(__lowercase) model.eval() __UpperCamelCase :List[Any] = model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase) -> List[str]: __UpperCamelCase :List[str] = AlbertForQuestionAnswering(config=__lowercase) model.to(__lowercase) model.eval() __UpperCamelCase :List[str] = model( __lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , start_positions=__lowercase , end_positions=__lowercase , ) 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 , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase) -> List[str]: __UpperCamelCase :List[str] = self.num_labels __UpperCamelCase :Optional[Any] = AlbertForSequenceClassification(__lowercase) model.to(__lowercase) model.eval() __UpperCamelCase :List[str] = model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase) -> List[str]: __UpperCamelCase :List[Any] = self.num_labels __UpperCamelCase :Optional[Any] = AlbertForTokenClassification(config=__lowercase) model.to(__lowercase) model.eval() __UpperCamelCase :int = model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase) -> Union[str, Any]: __UpperCamelCase :Optional[int] = self.num_choices __UpperCamelCase :Optional[Any] = AlbertForMultipleChoice(config=__lowercase) model.to(__lowercase) model.eval() __UpperCamelCase :List[Any] = input_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() __UpperCamelCase :List[str] = token_type_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() __UpperCamelCase :str = input_mask.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() __UpperCamelCase :Optional[int] = model( __lowercase , attention_mask=__lowercase , token_type_ids=__lowercase , labels=__lowercase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices)) def UpperCamelCase__ ( self) -> str: __UpperCamelCase :Optional[Any] = self.prepare_config_and_inputs() ( ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ) :Optional[Any] = config_and_inputs __UpperCamelCase :Optional[int] = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class lowerCamelCase_ ( UpperCAmelCase_ , UpperCAmelCase_ , unittest.TestCase ): '''simple docstring''' a__ : Union[str, Any] = ( ( AlbertModel, AlbertForPreTraining, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertForQuestionAnswering, ) if is_torch_available() else () ) a__ : int = ( { """feature-extraction""": AlbertModel, """fill-mask""": AlbertForMaskedLM, """question-answering""": AlbertForQuestionAnswering, """text-classification""": AlbertForSequenceClassification, """token-classification""": AlbertForTokenClassification, """zero-shot""": AlbertForSequenceClassification, } if is_torch_available() else {} ) a__ : List[Any] = True def UpperCamelCase__ ( self , __lowercase , __lowercase , __lowercase=False) -> Any: __UpperCamelCase :List[Any] = super()._prepare_for_class(__lowercase , __lowercase , return_labels=__lowercase) if return_labels: if model_class in get_values(__lowercase): __UpperCamelCase :Union[str, Any] = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=__lowercase) __UpperCamelCase :Union[str, Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__lowercase) return inputs_dict def UpperCamelCase__ ( self) -> Optional[int]: __UpperCamelCase :Dict = AlbertModelTester(self) __UpperCamelCase :Dict = ConfigTester(self , config_class=__lowercase , hidden_size=37) def UpperCamelCase__ ( self) -> Optional[int]: self.config_tester.run_common_tests() def UpperCamelCase__ ( self) -> Any: __UpperCamelCase :Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowercase) def UpperCamelCase__ ( self) -> Union[str, Any]: __UpperCamelCase :Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*__lowercase) def UpperCamelCase__ ( self) -> Union[str, Any]: __UpperCamelCase :Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__lowercase) def UpperCamelCase__ ( self) -> Union[str, Any]: __UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__lowercase) def UpperCamelCase__ ( self) -> Optional[int]: __UpperCamelCase :Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__lowercase) def UpperCamelCase__ ( self) -> Optional[int]: __UpperCamelCase :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__lowercase) def UpperCamelCase__ ( self) -> Optional[Any]: __UpperCamelCase :Any = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __UpperCamelCase :str = type self.model_tester.create_and_check_model(*__lowercase) @slow def UpperCamelCase__ ( self) -> str: for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase :List[Any] = AlbertModel.from_pretrained(__lowercase) self.assertIsNotNone(__lowercase) @require_torch class lowerCamelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase__ ( self) -> Optional[Any]: __UpperCamelCase :int = AlbertModel.from_pretrained('''albert-base-v2''') __UpperCamelCase :Union[str, Any] = torch.tensor([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]]) __UpperCamelCase :str = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]) with torch.no_grad(): __UpperCamelCase :str = model(__lowercase , attention_mask=__lowercase)[0] __UpperCamelCase :Optional[Any] = torch.Size((1, 11, 768)) self.assertEqual(output.shape , __lowercase) __UpperCamelCase :Tuple = torch.tensor( [[[-0.65_13, 1.50_35, -0.27_66], [-0.65_15, 1.50_46, -0.27_80], [-0.65_12, 1.50_49, -0.27_84]]]) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __lowercase , atol=1E-4))
43
'''simple docstring''' import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __magic_name__ : def __init__( self : List[str] ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : List[str]=13 ,_UpperCAmelCase : Any=32 ,_UpperCAmelCase : Union[str, Any]=3 ,_UpperCAmelCase : Optional[int]=4 ,_UpperCAmelCase : Optional[Any]=[10, 20, 30, 40] ,_UpperCAmelCase : Tuple=[2, 2, 3, 2] ,_UpperCAmelCase : Optional[int]=True ,_UpperCAmelCase : Optional[int]=True ,_UpperCAmelCase : Union[str, Any]=37 ,_UpperCAmelCase : Optional[int]="gelu" ,_UpperCAmelCase : Optional[Any]=10 ,_UpperCAmelCase : Tuple=0.02 ,_UpperCAmelCase : Any=["stage2", "stage3", "stage4"] ,_UpperCAmelCase : Any=[2, 3, 4] ,_UpperCAmelCase : Tuple=None ,): _a : Optional[Any] = parent _a : List[Any] = batch_size _a : str = image_size _a : Union[str, Any] = num_channels _a : List[Any] = num_stages _a : Dict = hidden_sizes _a : int = depths _a : Tuple = is_training _a : List[str] = use_labels _a : Dict = intermediate_size _a : int = hidden_act _a : int = num_labels _a : Any = initializer_range _a : Tuple = out_features _a : int = out_indices _a : List[Any] = scope def __lowercase ( self : Dict ): _a : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _a : Union[str, Any] = None if self.use_labels: _a : Tuple = ids_tensor([self.batch_size] ,self.num_labels ) _a : str = self.get_config() return config, pixel_values, labels def __lowercase ( self : Any ): return ConvNextVaConfig( num_channels=self.num_channels ,hidden_sizes=self.hidden_sizes ,depths=self.depths ,num_stages=self.num_stages ,hidden_act=self.hidden_act ,is_decoder=_UpperCAmelCase ,initializer_range=self.initializer_range ,out_features=self.out_features ,out_indices=self.out_indices ,num_labels=self.num_labels ,) def __lowercase ( self : Tuple ,_UpperCAmelCase : Any ,_UpperCAmelCase : Any ,_UpperCAmelCase : Optional[Any] ): _a : Optional[Any] = ConvNextVaModel(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : Any = model(_UpperCAmelCase ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape ,(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) ,) def __lowercase ( self : Tuple ,_UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : int ): _a : List[Any] = ConvNextVaForImageClassification(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : List[str] = model(_UpperCAmelCase ,labels=_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def __lowercase ( self : str ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ): _a : Optional[int] = ConvNextVaBackbone(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : Dict = model(_UpperCAmelCase ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) ,len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) ,[self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) ,len(config.out_features ) ) self.parent.assertListEqual(model.channels ,config.hidden_sizes[1:] ) # verify backbone works with out_features=None _a : Tuple = None _a : List[Any] = ConvNextVaBackbone(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : List[str] = model(_UpperCAmelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) ,1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) ,[self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) ,1 ) self.parent.assertListEqual(model.channels ,[config.hidden_sizes[-1]] ) def __lowercase ( self : Optional[Any] ): _a : Any = self.prepare_config_and_inputs() _a , _a , _a : Union[str, Any] = config_and_inputs _a : Any = {'pixel_values': pixel_values} return config, inputs_dict def __lowercase ( self : str ): _a : Tuple = self.prepare_config_and_inputs() _a , _a , _a : Tuple = config_and_inputs _a : List[Any] = {'pixel_values': pixel_values, 'labels': labels} return config, inputs_dict @require_torch class __magic_name__ ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): lowerCAmelCase : str = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) lowerCAmelCase : str = ( {'feature-extraction': ConvNextVaModel, 'image-classification': ConvNextVaForImageClassification} if is_torch_available() else {} ) lowerCAmelCase : int = False lowerCAmelCase : str = False lowerCAmelCase : Optional[Any] = False lowerCAmelCase : List[str] = False lowerCAmelCase : Optional[int] = False def __lowercase ( self : List[Any] ): _a : str = ConvNextVaModelTester(self ) _a : Tuple = ConfigTester(self ,config_class=_UpperCAmelCase ,has_text_modality=_UpperCAmelCase ,hidden_size=37 ) def __lowercase ( self : Optional[Any] ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __lowercase ( self : str ): return @unittest.skip(reason='ConvNextV2 does not use inputs_embeds' ) def __lowercase ( self : List[Any] ): pass @unittest.skip(reason='ConvNextV2 does not support input and output embeddings' ) def __lowercase ( self : Optional[int] ): pass @unittest.skip(reason='ConvNextV2 does not use feedforward chunking' ) def __lowercase ( self : Any ): pass def __lowercase ( self : List[str] ): if not self.model_tester.is_training: return for model_class in self.all_model_classes: _a , _a : List[Any] = self.model_tester.prepare_config_and_inputs_with_labels() _a : Any = True if model_class.__name__ in [ *get_values(_UpperCAmelCase ), *get_values(_UpperCAmelCase ), ]: continue _a : Optional[Any] = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.train() _a : str = self._prepare_for_class(_UpperCAmelCase ,_UpperCAmelCase ,return_labels=_UpperCAmelCase ) _a : Optional[int] = model(**_UpperCAmelCase ).loss loss.backward() def __lowercase ( self : str ): if not self.model_tester.is_training: return for model_class in self.all_model_classes: _a , _a : Optional[Any] = self.model_tester.prepare_config_and_inputs_with_labels() _a : Optional[int] = False _a : Tuple = True if ( model_class.__name__ in [*get_values(_UpperCAmelCase ), *get_values(_UpperCAmelCase )] or not model_class.supports_gradient_checkpointing ): continue _a : Tuple = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.gradient_checkpointing_enable() model.train() _a : Any = self._prepare_for_class(_UpperCAmelCase ,_UpperCAmelCase ,return_labels=_UpperCAmelCase ) _a : List[Any] = model(**_UpperCAmelCase ).loss loss.backward() def __lowercase ( self : List[Any] ): _a , _a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : int = model_class(_UpperCAmelCase ) _a : Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _a : Dict = [*signature.parameters.keys()] _a : int = ['pixel_values'] self.assertListEqual(arg_names[:1] ,_UpperCAmelCase ) def __lowercase ( self : int ): _a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase ) def __lowercase ( self : Any ): def check_hidden_states_output(_UpperCAmelCase : List[Any] ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Dict ): _a : Union[str, Any] = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() with torch.no_grad(): _a : List[Any] = model(**self._prepare_for_class(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Any = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _a : str = self.model_tester.num_stages self.assertEqual(len(_UpperCAmelCase ) ,expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) ,[self.model_tester.image_size // 4, self.model_tester.image_size // 4] ,) _a , _a : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : int = True check_hidden_states_output(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _a : Optional[Any] = True check_hidden_states_output(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) def __lowercase ( self : List[Any] ): _a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase ) @slow def __lowercase ( self : int ): for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Any = ConvNextVaModel.from_pretrained(_UpperCAmelCase ) self.assertIsNotNone(_UpperCAmelCase ) def __lowerCamelCase ( ) -> List[Any]: _a : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class __magic_name__ ( unittest.TestCase ): @cached_property def __lowercase ( self : Optional[Any] ): return AutoImageProcessor.from_pretrained('facebook/convnextv2-tiny-1k-224' ) if is_vision_available() else None @slow def __lowercase ( self : Any ): _a : List[str] = ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224' ).to(_UpperCAmelCase ) _a : Optional[int] = self.default_image_processor _a : str = prepare_img() _a : str = preprocessor(images=_UpperCAmelCase ,return_tensors='pt' ).to(_UpperCAmelCase ) # forward pass with torch.no_grad(): _a : Dict = model(**_UpperCAmelCase ) # verify the logits _a : Optional[Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape ,_UpperCAmelCase ) _a : Optional[Any] = torch.tensor([0.99_96, 0.19_66, -0.43_86] ).to(_UpperCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,_UpperCAmelCase ,atol=1E-4 ) )
89
0
"""simple docstring""" from typing import Optional import torch import torch.utils.checkpoint from torch import Tensor, nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...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 _a : List[Any] = logging.get_logger(__name__) # General docstring _a : Optional[int] = 'RegNetConfig' # Base docstring _a : Union[str, Any] = 'facebook/regnet-y-040' _a : Tuple = [1, 1_088, 7, 7] # Image classification docstring _a : Tuple = 'facebook/regnet-y-040' _a : Union[str, Any] = 'tabby, tabby cat' _a : Union[str, Any] = [ 'facebook/regnet-y-040', # See all regnet models at https://huggingface.co/models?filter=regnet ] class __A ( nn.Module ): def __init__( self , a__ , a__ , a__ = 3 , a__ = 1 , a__ = 1 , a__ = "relu" , ): super().__init__() _lowerCAmelCase : str = nn.Convad( a__ , a__ , kernel_size=a__ , stride=a__ , padding=kernel_size // 2 , groups=a__ , bias=a__ , ) _lowerCAmelCase : str = nn.BatchNormad(a__ ) _lowerCAmelCase : Optional[int] = ACTaFN[activation] if activation is not None else nn.Identity() def __A ( self , a__ ): _lowerCAmelCase : List[str] = self.convolution(a__ ) _lowerCAmelCase : Union[str, Any] = self.normalization(a__ ) _lowerCAmelCase : List[Any] = self.activation(a__ ) return hidden_state class __A ( nn.Module ): def __init__( self , a__ ): super().__init__() _lowerCAmelCase : Optional[int] = RegNetConvLayer( config.num_channels , config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act ) _lowerCAmelCase : List[Any] = config.num_channels def __A ( self , a__ ): _lowerCAmelCase : Tuple = 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 : List[Any] = self.embedder(a__ ) return hidden_state class __A ( nn.Module ): def __init__( self , a__ , a__ , a__ = 2 ): super().__init__() _lowerCAmelCase : Union[str, Any] = nn.Convad(a__ , a__ , kernel_size=1 , stride=a__ , bias=a__ ) _lowerCAmelCase : Optional[int] = nn.BatchNormad(a__ ) def __A ( self , a__ ): _lowerCAmelCase : str = self.convolution(a__ ) _lowerCAmelCase : Tuple = self.normalization(a__ ) return hidden_state class __A ( nn.Module ): def __init__( self , a__ , a__ ): super().__init__() _lowerCAmelCase : Dict = nn.AdaptiveAvgPoolad((1, 1) ) _lowerCAmelCase : Tuple = nn.Sequential( nn.Convad(a__ , a__ , kernel_size=1 ) , nn.ReLU() , nn.Convad(a__ , a__ , kernel_size=1 ) , nn.Sigmoid() , ) def __A ( self , a__ ): # b c h w -> b c 1 1 _lowerCAmelCase : Tuple = self.pooler(a__ ) _lowerCAmelCase : int = self.attention(a__ ) _lowerCAmelCase : Optional[Any] = hidden_state * attention return hidden_state class __A ( nn.Module ): def __init__( self , a__ , a__ , a__ , a__ = 1 ): super().__init__() _lowerCAmelCase : Optional[Any] = in_channels != out_channels or stride != 1 _lowerCAmelCase : Optional[Any] = max(1 , out_channels // config.groups_width ) _lowerCAmelCase : Tuple = ( RegNetShortCut(a__ , a__ , stride=a__ ) if should_apply_shortcut else nn.Identity() ) _lowerCAmelCase : str = nn.Sequential( RegNetConvLayer(a__ , a__ , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(a__ , a__ , stride=a__ , groups=a__ , activation=config.hidden_act ) , RegNetConvLayer(a__ , a__ , kernel_size=1 , activation=a__ ) , ) _lowerCAmelCase : Union[str, Any] = ACTaFN[config.hidden_act] def __A ( self , a__ ): _lowerCAmelCase : Any = hidden_state _lowerCAmelCase : Any = self.layer(a__ ) _lowerCAmelCase : str = self.shortcut(a__ ) hidden_state += residual _lowerCAmelCase : int = self.activation(a__ ) return hidden_state class __A ( nn.Module ): def __init__( self , a__ , a__ , a__ , a__ = 1 ): super().__init__() _lowerCAmelCase : Dict = in_channels != out_channels or stride != 1 _lowerCAmelCase : List[Any] = max(1 , out_channels // config.groups_width ) _lowerCAmelCase : List[Any] = ( RegNetShortCut(a__ , a__ , stride=a__ ) if should_apply_shortcut else nn.Identity() ) _lowerCAmelCase : Tuple = nn.Sequential( RegNetConvLayer(a__ , a__ , kernel_size=1 , activation=config.hidden_act ) , RegNetConvLayer(a__ , a__ , stride=a__ , groups=a__ , activation=config.hidden_act ) , RegNetSELayer(a__ , reduced_channels=int(round(in_channels / 4 ) ) ) , RegNetConvLayer(a__ , a__ , kernel_size=1 , activation=a__ ) , ) _lowerCAmelCase : Dict = ACTaFN[config.hidden_act] def __A ( self , a__ ): _lowerCAmelCase : List[str] = hidden_state _lowerCAmelCase : Optional[int] = self.layer(a__ ) _lowerCAmelCase : List[Any] = self.shortcut(a__ ) hidden_state += residual _lowerCAmelCase : List[str] = self.activation(a__ ) return hidden_state class __A ( nn.Module ): def __init__( self , a__ , a__ , a__ , a__ = 2 , a__ = 2 , ): super().__init__() _lowerCAmelCase : List[Any] = RegNetXLayer if config.layer_type == """x""" else RegNetYLayer _lowerCAmelCase : str = nn.Sequential( # downsampling is done in the first layer with stride of 2 layer( a__ , a__ , a__ , stride=a__ , ) , *[layer(a__ , a__ , a__ ) for _ in range(depth - 1 )] , ) def __A ( self , a__ ): _lowerCAmelCase : List[Any] = self.layers(a__ ) return hidden_state class __A ( nn.Module ): def __init__( self , a__ ): super().__init__() _lowerCAmelCase : Optional[int] = 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( a__ , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , ) ) _lowerCAmelCase : List[str] = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for (in_channels, out_channels), depth in zip(a__ , config.depths[1:] ): self.stages.append(RegNetStage(a__ , a__ , a__ , depth=a__ ) ) def __A ( self , a__ , a__ = False , a__ = True ): _lowerCAmelCase : Any = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: _lowerCAmelCase : Union[str, Any] = hidden_states + (hidden_state,) _lowerCAmelCase : Union[str, Any] = stage_module(a__ ) if output_hidden_states: _lowerCAmelCase : Union[str, 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=a__ , hidden_states=a__ ) class __A ( SCREAMING_SNAKE_CASE_ ): _UpperCamelCase : Tuple = RegNetConfig _UpperCamelCase : int = "regnet" _UpperCamelCase : List[str] = "pixel_values" _UpperCamelCase : Union[str, Any] = True def __A ( self , a__ ): if isinstance(a__ , nn.Convad ): nn.init.kaiming_normal_(module.weight , mode="""fan_out""" , nonlinearity="""relu""" ) elif isinstance(a__ , (nn.BatchNormad, nn.GroupNorm) ): nn.init.constant_(module.weight , 1 ) nn.init.constant_(module.bias , 0 ) def __A ( self , a__ , a__=False ): if isinstance(a__ , a__ ): _lowerCAmelCase : Optional[int] = value _a : List[Any] = 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' _a : List[Any] = 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." , SCREAMING_SNAKE_CASE_ , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ ): super().__init__(a__ ) _lowerCAmelCase : List[Any] = config _lowerCAmelCase : Any = RegNetEmbeddings(a__ ) _lowerCAmelCase : List[str] = RegNetEncoder(a__ ) _lowerCAmelCase : str = nn.AdaptiveAvgPoolad((1, 1) ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(a__ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=a__ , config_class=_CONFIG_FOR_DOC , modality="""vision""" , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def __A ( self , a__ , a__ = None , a__ = None ): _lowerCAmelCase : Any = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) _lowerCAmelCase : Tuple = return_dict if return_dict is not None else self.config.use_return_dict _lowerCAmelCase : List[Any] = self.embedder(a__ ) _lowerCAmelCase : Optional[Any] = self.encoder( a__ , output_hidden_states=a__ , return_dict=a__ ) _lowerCAmelCase : str = encoder_outputs[0] _lowerCAmelCase : Optional[Any] = self.pooler(a__ ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=a__ , pooler_output=a__ , 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 " , SCREAMING_SNAKE_CASE_ , ) # Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet class __A ( SCREAMING_SNAKE_CASE_ ): def __init__( self , a__ ): super().__init__(a__ ) _lowerCAmelCase : Any = config.num_labels _lowerCAmelCase : Optional[int] = RegNetModel(a__ ) # classification head _lowerCAmelCase : Optional[Any] = 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(a__ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=a__ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def __A ( self , a__ = None , a__ = None , a__ = None , a__ = None , ): _lowerCAmelCase : List[Any] = return_dict if return_dict is not None else self.config.use_return_dict _lowerCAmelCase : Union[str, Any] = self.regnet(a__ , output_hidden_states=a__ , return_dict=a__ ) _lowerCAmelCase : str = outputs.pooler_output if return_dict else outputs[1] _lowerCAmelCase : str = self.classifier(a__ ) _lowerCAmelCase : List[str] = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: _lowerCAmelCase : str = """regression""" elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): _lowerCAmelCase : Optional[int] = """single_label_classification""" else: _lowerCAmelCase : Optional[int] = """multi_label_classification""" if self.config.problem_type == "regression": _lowerCAmelCase : Optional[Any] = MSELoss() if self.num_labels == 1: _lowerCAmelCase : int = loss_fct(logits.squeeze() , labels.squeeze() ) else: _lowerCAmelCase : Dict = loss_fct(a__ , a__ ) elif self.config.problem_type == "single_label_classification": _lowerCAmelCase : Any = CrossEntropyLoss() _lowerCAmelCase : Dict = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": _lowerCAmelCase : Dict = BCEWithLogitsLoss() _lowerCAmelCase : Tuple = loss_fct(a__ , a__ ) if not return_dict: _lowerCAmelCase : Optional[int] = (logits,) + outputs[2:] return (loss,) + output if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=a__ , logits=a__ , hidden_states=outputs.hidden_states )
44
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCAmelCase = { '''configuration_lilt''': ['''LILT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LiltConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''LILT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''LiltForQuestionAnswering''', '''LiltForSequenceClassification''', '''LiltForTokenClassification''', '''LiltModel''', '''LiltPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_lilt import LILT_PRETRAINED_CONFIG_ARCHIVE_MAP, LiltConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lilt import ( LILT_PRETRAINED_MODEL_ARCHIVE_LIST, LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, LiltPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
89
0
"""simple docstring""" import string def lowercase ( lowerCAmelCase__ : str ) -> str: __a = '''''' for i in sequence: __a = ord(lowerCAmelCase__ ) if 65 <= extract <= 90: output += chr(155 - extract ) elif 97 <= extract <= 122: output += chr(219 - extract ) else: output += i return output def lowercase ( lowerCAmelCase__ : str ) -> str: __a = string.ascii_letters __a = string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1] return "".join( letters_reversed[letters.index(lowerCAmelCase__ )] if c in letters else c for c in sequence ) def lowercase ( ) -> None: from timeit import timeit print('''Running performance benchmarks...''' ) __a = '''from string import printable ; from __main__ import atbash, atbash_slow''' print(f'''> atbash_slow(): {timeit('atbash_slow(printable)' , setup=lowerCAmelCase__ )} seconds''' ) print(f'''> atbash(): {timeit('atbash(printable)' , setup=lowerCAmelCase__ )} seconds''' ) if __name__ == "__main__": for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"): print(F'''{example} encrypted in atbash: {atbash(example)}''') benchmark()
45
'''simple docstring''' import math def __lowerCamelCase ( lowerCAmelCase_ ) -> bool: _a : Optional[int] = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(lowerCAmelCase_ ) def __lowerCamelCase ( lowerCAmelCase_ = 1 / 12345 ) -> int: _a : int = 0 _a : Optional[Any] = 0 _a : int = 3 while True: _a : Tuple = (integer**2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(lowerCAmelCase_ ): _a : Union[str, Any] = int(lowerCAmelCase_ ) total_partitions += 1 if check_partition_perfect(lowerCAmelCase_ ): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return int(lowerCAmelCase_ ) integer += 1 if __name__ == "__main__": print(f"""{solution() = }""")
89
0
"""simple docstring""" import torch import torch.nn as nn from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel from ...utils import logging SCREAMING_SNAKE_CASE__ = logging.get_logger(__name__) def UpperCAmelCase__ ( SCREAMING_SNAKE_CASE : Union[str, Any] , SCREAMING_SNAKE_CASE : List[Any] ): '''simple docstring''' lowerCAmelCase = nn.functional.normalize(SCREAMING_SNAKE_CASE ) lowerCAmelCase = nn.functional.normalize(SCREAMING_SNAKE_CASE ) return torch.mm(SCREAMING_SNAKE_CASE , normalized_text_embeds.t() ) class lowercase ( _UpperCAmelCase ): _SCREAMING_SNAKE_CASE = CLIPConfig _SCREAMING_SNAKE_CASE = ['CLIPEncoderLayer'] def __init__( self , lowercase ) -> Optional[int]: super().__init__(lowercase ) lowerCAmelCase = CLIPVisionModel(config.vision_config ) lowerCAmelCase = nn.Linear(config.vision_config.hidden_size , config.projection_dim , bias=lowercase ) lowerCAmelCase = nn.Parameter(torch.ones(17 , config.projection_dim ) , requires_grad=lowercase ) lowerCAmelCase = nn.Parameter(torch.ones(3 , config.projection_dim ) , requires_grad=lowercase ) lowerCAmelCase = nn.Parameter(torch.ones(17 ) , requires_grad=lowercase ) lowerCAmelCase = nn.Parameter(torch.ones(3 ) , requires_grad=lowercase ) @torch.no_grad() def _snake_case ( self , lowercase , lowercase ) -> Optional[Any]: lowerCAmelCase = self.vision_model(lowercase )[1] # pooled_output lowerCAmelCase = self.visual_projection(lowercase ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 lowerCAmelCase = cosine_distance(lowercase , self.special_care_embeds ).cpu().float().numpy() lowerCAmelCase = cosine_distance(lowercase , self.concept_embeds ).cpu().float().numpy() lowerCAmelCase = [] lowerCAmelCase = image_embeds.shape[0] for i in range(lowercase ): lowerCAmelCase = {"""special_scores""": {}, """special_care""": [], """concept_scores""": {}, """bad_concepts""": []} # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign images lowerCAmelCase = 0.0 for concept_idx in range(len(special_cos_dist[0] ) ): lowerCAmelCase = special_cos_dist[i][concept_idx] lowerCAmelCase = self.special_care_embeds_weights[concept_idx].item() lowerCAmelCase = round(concept_cos - concept_threshold + adjustment , 3 ) if result_img["special_scores"][concept_idx] > 0: result_img["special_care"].append({concept_idx, result_img["""special_scores"""][concept_idx]} ) lowerCAmelCase = 0.01 for concept_idx in range(len(cos_dist[0] ) ): lowerCAmelCase = cos_dist[i][concept_idx] lowerCAmelCase = self.concept_embeds_weights[concept_idx].item() lowerCAmelCase = round(concept_cos - concept_threshold + adjustment , 3 ) if result_img["concept_scores"][concept_idx] > 0: result_img["bad_concepts"].append(lowercase ) result.append(lowercase ) lowerCAmelCase = [len(res["""bad_concepts"""] ) > 0 for res in result] return images, has_nsfw_concepts @torch.no_grad() def _snake_case ( self , lowercase , lowercase ) -> Union[str, Any]: lowerCAmelCase = self.vision_model(lowercase )[1] # pooled_output lowerCAmelCase = self.visual_projection(lowercase ) lowerCAmelCase = cosine_distance(lowercase , self.special_care_embeds ) lowerCAmelCase = cosine_distance(lowercase , self.concept_embeds ) # increase this value to create a stronger `nsfw` filter # at the cost of increasing the possibility of filtering benign images lowerCAmelCase = 0.0 lowerCAmelCase = special_cos_dist - self.special_care_embeds_weights + adjustment # special_scores = special_scores.round(decimals=3) lowerCAmelCase = torch.any(special_scores > 0 , dim=1 ) lowerCAmelCase = special_care * 0.01 lowerCAmelCase = special_adjustment.unsqueeze(1 ).expand(-1 , cos_dist.shape[1] ) lowerCAmelCase = (cos_dist - self.concept_embeds_weights) + special_adjustment # concept_scores = concept_scores.round(decimals=3) lowerCAmelCase = torch.any(concept_scores > 0 , dim=1 ) return images, has_nsfw_concepts
46
'''simple docstring''' import argparse import json import torch from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=1 ) -> Dict: if n_shave_prefix_segments >= 0: return ".".join(path.split('.' )[n_shave_prefix_segments:] ) else: return ".".join(path.split('.' )[:n_shave_prefix_segments] ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=0 ) -> Tuple: _a : Any = [] for old_item in old_list: _a : Union[str, Any] = old_item.replace('in_layers.0' , 'norm1' ) _a : Optional[int] = new_item.replace('in_layers.2' , 'conv1' ) _a : str = new_item.replace('out_layers.0' , 'norm2' ) _a : List[str] = new_item.replace('out_layers.3' , 'conv2' ) _a : str = new_item.replace('emb_layers.1' , 'time_emb_proj' ) _a : Tuple = new_item.replace('skip_connection' , 'conv_shortcut' ) _a : Any = shave_segments(lowerCAmelCase_ , n_shave_prefix_segments=lowerCAmelCase_ ) mapping.append({'old': old_item, 'new': new_item} ) return mapping def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=0 ) -> Any: _a : List[str] = [] for old_item in old_list: _a : List[Any] = old_item _a : Optional[int] = new_item.replace('norm.weight' , 'group_norm.weight' ) _a : Optional[Any] = new_item.replace('norm.bias' , 'group_norm.bias' ) _a : Any = new_item.replace('proj_out.weight' , 'proj_attn.weight' ) _a : Optional[Any] = new_item.replace('proj_out.bias' , 'proj_attn.bias' ) _a : Optional[int] = shave_segments(lowerCAmelCase_ , n_shave_prefix_segments=lowerCAmelCase_ ) mapping.append({'old': old_item, 'new': new_item} ) return mapping def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None , lowerCAmelCase_=None , lowerCAmelCase_=None ) -> Any: assert isinstance(lowerCAmelCase_ , lowerCAmelCase_ ), "Paths should be a list of dicts containing 'old' and 'new' keys." # Splits the attention layers into three variables. if attention_paths_to_split is not None: for path, path_map in attention_paths_to_split.items(): _a : Optional[Any] = old_checkpoint[path] _a : Optional[Any] = old_tensor.shape[0] // 3 _a : Any = (-1, channels) if len(old_tensor.shape ) == 3 else (-1) _a : int = old_tensor.shape[0] // config['num_head_channels'] // 3 _a : str = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:] ) _a , _a , _a : Tuple = old_tensor.split(channels // num_heads , dim=1 ) _a : Dict = query.reshape(lowerCAmelCase_ ) _a : str = key.reshape(lowerCAmelCase_ ) _a : Optional[int] = value.reshape(lowerCAmelCase_ ) for path in paths: _a : Dict = path['new'] # These have already been assigned if attention_paths_to_split is not None and new_path in attention_paths_to_split: continue # Global renaming happens here _a : Any = new_path.replace('middle_block.0' , 'mid_block.resnets.0' ) _a : str = new_path.replace('middle_block.1' , 'mid_block.attentions.0' ) _a : Union[str, Any] = new_path.replace('middle_block.2' , 'mid_block.resnets.1' ) if additional_replacements is not None: for replacement in additional_replacements: _a : int = new_path.replace(replacement['old'] , replacement['new'] ) # proj_attn.weight has to be converted from conv 1D to linear if "proj_attn.weight" in new_path: _a : List[str] = old_checkpoint[path['old']][:, :, 0] else: _a : Dict = old_checkpoint[path['old']] def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> List[Any]: _a : Optional[int] = {} _a : Dict = checkpoint['time_embed.0.weight'] _a : Tuple = checkpoint['time_embed.0.bias'] _a : Union[str, Any] = checkpoint['time_embed.2.weight'] _a : List[str] = checkpoint['time_embed.2.bias'] _a : List[str] = checkpoint['input_blocks.0.0.weight'] _a : Union[str, Any] = checkpoint['input_blocks.0.0.bias'] _a : Optional[int] = checkpoint['out.0.weight'] _a : int = checkpoint['out.0.bias'] _a : List[str] = checkpoint['out.2.weight'] _a : Optional[int] = checkpoint['out.2.bias'] # Retrieves the keys for the input blocks only _a : Optional[int] = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'input_blocks' in layer} ) _a : Dict = { layer_id: [key for key in checkpoint if f"""input_blocks.{layer_id}""" in key] for layer_id in range(lowerCAmelCase_ ) } # Retrieves the keys for the middle blocks only _a : List[Any] = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'middle_block' in layer} ) _a : Union[str, Any] = { layer_id: [key for key in checkpoint if f"""middle_block.{layer_id}""" in key] for layer_id in range(lowerCAmelCase_ ) } # Retrieves the keys for the output blocks only _a : Optional[int] = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'output_blocks' in layer} ) _a : str = { layer_id: [key for key in checkpoint if f"""output_blocks.{layer_id}""" in key] for layer_id in range(lowerCAmelCase_ ) } for i in range(1 , lowerCAmelCase_ ): _a : List[Any] = (i - 1) // (config['num_res_blocks'] + 1) _a : Optional[int] = (i - 1) % (config['num_res_blocks'] + 1) _a : Optional[int] = [key for key in input_blocks[i] if f"""input_blocks.{i}.0""" in key] _a : Optional[Any] = [key for key in input_blocks[i] if f"""input_blocks.{i}.1""" in key] if f"""input_blocks.{i}.0.op.weight""" in checkpoint: _a : List[Any] = checkpoint[ f"""input_blocks.{i}.0.op.weight""" ] _a : Union[str, Any] = checkpoint[ f"""input_blocks.{i}.0.op.bias""" ] continue _a : Any = renew_resnet_paths(lowerCAmelCase_ ) _a : List[str] = {'old': f"""input_blocks.{i}.0""", 'new': f"""down_blocks.{block_id}.resnets.{layer_in_block_id}"""} _a : Optional[Any] = {'old': 'resnets.2.op', 'new': 'downsamplers.0.op'} assign_to_checkpoint( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , additional_replacements=[meta_path, resnet_op] , config=lowerCAmelCase_ ) if len(lowerCAmelCase_ ): _a : List[str] = renew_attention_paths(lowerCAmelCase_ ) _a : List[Any] = { 'old': f"""input_blocks.{i}.1""", 'new': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}""", } _a : Optional[Any] = { f"""input_blocks.{i}.1.qkv.bias""": { 'key': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias""", 'query': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias""", 'value': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias""", }, f"""input_blocks.{i}.1.qkv.weight""": { 'key': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight""", 'query': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight""", 'value': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight""", }, } assign_to_checkpoint( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , additional_replacements=[meta_path] , attention_paths_to_split=lowerCAmelCase_ , config=lowerCAmelCase_ , ) _a : str = middle_blocks[0] _a : Tuple = middle_blocks[1] _a : Any = middle_blocks[2] _a : List[Any] = renew_resnet_paths(lowerCAmelCase_ ) assign_to_checkpoint(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , config=lowerCAmelCase_ ) _a : Any = renew_resnet_paths(lowerCAmelCase_ ) assign_to_checkpoint(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , config=lowerCAmelCase_ ) _a : int = renew_attention_paths(lowerCAmelCase_ ) _a : int = { 'middle_block.1.qkv.bias': { 'key': 'mid_block.attentions.0.key.bias', 'query': 'mid_block.attentions.0.query.bias', 'value': 'mid_block.attentions.0.value.bias', }, 'middle_block.1.qkv.weight': { 'key': 'mid_block.attentions.0.key.weight', 'query': 'mid_block.attentions.0.query.weight', 'value': 'mid_block.attentions.0.value.weight', }, } assign_to_checkpoint( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , attention_paths_to_split=lowerCAmelCase_ , config=lowerCAmelCase_ ) for i in range(lowerCAmelCase_ ): _a : List[str] = i // (config['num_res_blocks'] + 1) _a : Any = i % (config['num_res_blocks'] + 1) _a : Union[str, Any] = [shave_segments(lowerCAmelCase_ , 2 ) for name in output_blocks[i]] _a : Optional[Any] = {} for layer in output_block_layers: _a , _a : str = layer.split('.' )[0], shave_segments(lowerCAmelCase_ , 1 ) if layer_id in output_block_list: output_block_list[layer_id].append(lowerCAmelCase_ ) else: _a : str = [layer_name] if len(lowerCAmelCase_ ) > 1: _a : str = [key for key in output_blocks[i] if f"""output_blocks.{i}.0""" in key] _a : Optional[Any] = [key for key in output_blocks[i] if f"""output_blocks.{i}.1""" in key] _a : Dict = renew_resnet_paths(lowerCAmelCase_ ) _a : str = renew_resnet_paths(lowerCAmelCase_ ) _a : Optional[int] = {'old': f"""output_blocks.{i}.0""", 'new': f"""up_blocks.{block_id}.resnets.{layer_in_block_id}"""} assign_to_checkpoint(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , additional_replacements=[meta_path] , config=lowerCAmelCase_ ) if ["conv.weight", "conv.bias"] in output_block_list.values(): _a : List[Any] = list(output_block_list.values() ).index(['conv.weight', 'conv.bias'] ) _a : Tuple = checkpoint[ f"""output_blocks.{i}.{index}.conv.weight""" ] _a : List[str] = checkpoint[ f"""output_blocks.{i}.{index}.conv.bias""" ] # Clear attentions as they have been attributed above. if len(lowerCAmelCase_ ) == 2: _a : Union[str, Any] = [] if len(lowerCAmelCase_ ): _a : Tuple = renew_attention_paths(lowerCAmelCase_ ) _a : str = { 'old': f"""output_blocks.{i}.1""", 'new': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}""", } _a : List[Any] = { f"""output_blocks.{i}.1.qkv.bias""": { 'key': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias""", 'query': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias""", 'value': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias""", }, f"""output_blocks.{i}.1.qkv.weight""": { 'key': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight""", 'query': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight""", 'value': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight""", }, } assign_to_checkpoint( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , additional_replacements=[meta_path] , attention_paths_to_split=to_split if any('qkv' in key for key in attentions ) else None , config=lowerCAmelCase_ , ) else: _a : List[Any] = renew_resnet_paths(lowerCAmelCase_ , n_shave_prefix_segments=1 ) for path in resnet_0_paths: _a : int = '.'.join(['output_blocks', str(lowerCAmelCase_ ), path['old']] ) _a : Union[str, Any] = '.'.join(['up_blocks', str(lowerCAmelCase_ ), 'resnets', str(lowerCAmelCase_ ), path['new']] ) _a : Union[str, Any] = checkpoint[old_path] return new_checkpoint if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the architecture.''', ) parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') __lowerCAmelCase = parser.parse_args() __lowerCAmelCase = torch.load(args.checkpoint_path) with open(args.config_file) as f: __lowerCAmelCase = json.loads(f.read()) __lowerCAmelCase = convert_ldm_checkpoint(checkpoint, config) if "ldm" in config: del config["ldm"] __lowerCAmelCase = UNetaDModel(**config) model.load_state_dict(converted_checkpoint) try: __lowerCAmelCase = DDPMScheduler.from_config('''/'''.join(args.checkpoint_path.split('''/''')[:-1])) __lowerCAmelCase = VQModel.from_pretrained('''/'''.join(args.checkpoint_path.split('''/''')[:-1])) __lowerCAmelCase = LDMPipeline(unet=model, scheduler=scheduler, vae=vqvae) pipe.save_pretrained(args.dump_path) except: # noqa: E722 model.save_pretrained(args.dump_path)
89
0
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class A__ ( A__ ): A__ = ( 'This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.' 'It takes two arguments named `image` which should be the original image, and `label` which should be a text ' 'describing the elements what should be identified in the segmentation mask. The tool returns the mask.' ) A__ = 'CIDAS/clipseg-rd64-refined' A__ = 'image_segmenter' A__ = CLIPSegForImageSegmentation A__ = ['image', 'text'] A__ = ['image'] def __init__( self : Any , *_a : Dict , **_a : str ) -> Any: '''simple docstring''' requires_backends(self , ['vision'] ) super().__init__(*_a , **_a ) def A ( self : int , _a : "Image" , _a : str ) -> Optional[Any]: '''simple docstring''' return self.pre_processor(text=[label] , images=[image] , padding=_a , return_tensors='pt' ) def A ( self : Dict , _a : Dict ) -> str: '''simple docstring''' with torch.no_grad(): _SCREAMING_SNAKE_CASE =self.model(**_a ).logits return logits def A ( self : Any , _a : str ) -> Union[str, Any]: '''simple docstring''' _SCREAMING_SNAKE_CASE =outputs.cpu().detach().numpy() _SCREAMING_SNAKE_CASE =0 _SCREAMING_SNAKE_CASE =1 return Image.fromarray((array * 255).astype(np.uinta ) )
47
'''simple docstring''' import datetime import platform import subprocess from typing import Optional, Tuple, Union import numpy as np def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> np.array: _a : Optional[int] = f"""{sampling_rate}""" _a : Any = '1' _a : Optional[int] = 'f32le' _a : Any = [ 'ffmpeg', '-i', 'pipe:0', '-ac', ac, '-ar', ar, '-f', format_for_conversion, '-hide_banner', '-loglevel', 'quiet', 'pipe:1', ] try: with subprocess.Popen(lowerCAmelCase_ , stdin=subprocess.PIPE , stdout=subprocess.PIPE ) as ffmpeg_process: _a : int = ffmpeg_process.communicate(lowerCAmelCase_ ) except FileNotFoundError as error: raise ValueError('ffmpeg was not found but is required to load audio files from filename' ) from error _a : int = output_stream[0] _a : List[str] = np.frombuffer(lowerCAmelCase_ , np.floataa ) if audio.shape[0] == 0: raise ValueError('Malformed soundfile' ) return audio def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = "f32le" , ) -> Union[str, Any]: _a : List[str] = f"""{sampling_rate}""" _a : List[str] = '1' if format_for_conversion == "s16le": _a : List[Any] = 2 elif format_for_conversion == "f32le": _a : Dict = 4 else: raise ValueError(f"""Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`""" ) _a : Any = platform.system() if system == "Linux": _a : Union[str, Any] = 'alsa' _a : Union[str, Any] = 'default' elif system == "Darwin": _a : Any = 'avfoundation' _a : Optional[int] = ':0' elif system == "Windows": _a : str = 'dshow' _a : Tuple = 'default' _a : str = [ 'ffmpeg', '-f', format_, '-i', input_, '-ac', ac, '-ar', ar, '-f', format_for_conversion, '-fflags', 'nobuffer', '-hide_banner', '-loglevel', 'quiet', 'pipe:1', ] _a : Any = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample _a : Union[str, Any] = _ffmpeg_stream(lowerCAmelCase_ , lowerCAmelCase_ ) for item in iterator: yield item def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = "f32le" , ) -> str: if stream_chunk_s is not None: _a : str = stream_chunk_s else: _a : List[str] = chunk_length_s _a : int = ffmpeg_microphone(lowerCAmelCase_ , lowerCAmelCase_ , format_for_conversion=lowerCAmelCase_ ) if format_for_conversion == "s16le": _a : Optional[Any] = np.intaa _a : List[Any] = 2 elif format_for_conversion == "f32le": _a : Tuple = np.floataa _a : Any = 4 else: raise ValueError(f"""Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`""" ) if stride_length_s is None: _a : str = chunk_length_s / 6 _a : Any = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample if isinstance(lowerCAmelCase_ , (int, float) ): _a : List[str] = [stride_length_s, stride_length_s] _a : str = int(round(sampling_rate * stride_length_s[0] ) ) * size_of_sample _a : List[str] = int(round(sampling_rate * stride_length_s[1] ) ) * size_of_sample _a : Any = datetime.datetime.now() _a : Dict = datetime.timedelta(seconds=lowerCAmelCase_ ) for item in chunk_bytes_iter(lowerCAmelCase_ , lowerCAmelCase_ , stride=(stride_left, stride_right) , stream=lowerCAmelCase_ ): # Put everything back in numpy scale _a : List[Any] = np.frombuffer(item['raw'] , dtype=lowerCAmelCase_ ) _a : List[str] = ( item['stride'][0] // size_of_sample, item['stride'][1] // size_of_sample, ) _a : Union[str, Any] = sampling_rate audio_time += delta if datetime.datetime.now() > audio_time + 10 * delta: # We're late !! SKIP continue yield item def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = False ) -> List[Any]: _a : Tuple = B'' _a , _a : str = stride if stride_left + stride_right >= chunk_len: raise ValueError( f"""Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}""" ) _a : Optional[int] = 0 for raw in iterator: acc += raw if stream and len(lowerCAmelCase_ ) < chunk_len: _a : str = (_stride_left, 0) yield {"raw": acc[:chunk_len], "stride": stride, "partial": True} else: while len(lowerCAmelCase_ ) >= chunk_len: # We are flushing the accumulator _a : Union[str, Any] = (_stride_left, stride_right) _a : Dict = {'raw': acc[:chunk_len], 'stride': stride} if stream: _a : List[str] = False yield item _a : int = stride_left _a : List[Any] = acc[chunk_len - stride_left - stride_right :] # Last chunk if len(lowerCAmelCase_ ) > stride_left: _a : str = {'raw': acc, 'stride': (_stride_left, 0)} if stream: _a : str = False yield item def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> Tuple: _a : Optional[Any] = 2**24 # 16Mo try: with subprocess.Popen(lowerCAmelCase_ , stdout=subprocess.PIPE , bufsize=lowerCAmelCase_ ) as ffmpeg_process: while True: _a : Any = ffmpeg_process.stdout.read(lowerCAmelCase_ ) if raw == b"": break yield raw except FileNotFoundError as error: raise ValueError('ffmpeg was not found but is required to stream audio files from filename' ) from error
89
0
import argparse import os import re SCREAMING_SNAKE_CASE__ : Any = 'src/transformers' # Pattern that looks at the indentation in a line. SCREAMING_SNAKE_CASE__ : Any = re.compile(r'^(\s*)\S') # Pattern that matches `"key":" and puts `key` in group 0. SCREAMING_SNAKE_CASE__ : Optional[int] = re.compile(r'^\s*"([^"]+)":') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. SCREAMING_SNAKE_CASE__ : List[str] = re.compile(r'^\s*_import_structure\["([^"]+)"\]') # Pattern that matches `"key",` and puts `key` in group 0. SCREAMING_SNAKE_CASE__ : str = re.compile(r'^\s*"([^"]+)",\s*$') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. SCREAMING_SNAKE_CASE__ : int = re.compile(r'\[([^\]]+)\]') def A ( _SCREAMING_SNAKE_CASE ) -> Optional[int]: lowerCamelCase : List[str] = _re_indent.search(_SCREAMING_SNAKE_CASE ) return "" if search is None else search.groups()[0] def A ( _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE="" ,_SCREAMING_SNAKE_CASE=None ,_SCREAMING_SNAKE_CASE=None ) -> Tuple: lowerCamelCase : Optional[Any] = 0 lowerCamelCase : Any = code.split("\n" ) if start_prompt is not None: while not lines[index].startswith(_SCREAMING_SNAKE_CASE ): index += 1 lowerCamelCase : List[Any] = ["\n".join(lines[:index] )] else: lowerCamelCase : str = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). lowerCamelCase : Union[str, Any] = [lines[index]] index += 1 while index < len(_SCREAMING_SNAKE_CASE ) and (end_prompt is None or not lines[index].startswith(_SCREAMING_SNAKE_CASE )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(_SCREAMING_SNAKE_CASE ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + " " ): current_block.append(lines[index] ) blocks.append("\n".join(_SCREAMING_SNAKE_CASE ) ) if index < len(_SCREAMING_SNAKE_CASE ) - 1: lowerCamelCase : Any = [lines[index + 1]] index += 1 else: lowerCamelCase : Any = [] else: blocks.append("\n".join(_SCREAMING_SNAKE_CASE ) ) lowerCamelCase : Tuple = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(_SCREAMING_SNAKE_CASE ) > 0: blocks.append("\n".join(_SCREAMING_SNAKE_CASE ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(_SCREAMING_SNAKE_CASE ): blocks.append("\n".join(lines[index:] ) ) return blocks def A ( _SCREAMING_SNAKE_CASE ) -> Optional[Any]: def _inner(_SCREAMING_SNAKE_CASE ): return key(_SCREAMING_SNAKE_CASE ).lower().replace("_" ,"" ) return _inner def A ( _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE=None ) -> Union[str, Any]: # If no key is provided, we use a noop. def noop(_SCREAMING_SNAKE_CASE ): return x if key is None: lowerCamelCase : List[str] = noop # Constants are all uppercase, they go first. lowerCamelCase : int = [obj for obj in objects if key(_SCREAMING_SNAKE_CASE ).isupper()] # Classes are not all uppercase but start with a capital, they go second. lowerCamelCase : Union[str, Any] = [obj for obj in objects if key(_SCREAMING_SNAKE_CASE )[0].isupper() and not key(_SCREAMING_SNAKE_CASE ).isupper()] # Functions begin with a lowercase, they go last. lowerCamelCase : Optional[int] = [obj for obj in objects if not key(_SCREAMING_SNAKE_CASE )[0].isupper()] lowerCamelCase : Union[str, Any] = ignore_underscore(_SCREAMING_SNAKE_CASE ) return sorted(_SCREAMING_SNAKE_CASE ,key=_SCREAMING_SNAKE_CASE ) + sorted(_SCREAMING_SNAKE_CASE ,key=_SCREAMING_SNAKE_CASE ) + sorted(_SCREAMING_SNAKE_CASE ,key=_SCREAMING_SNAKE_CASE ) def A ( _SCREAMING_SNAKE_CASE ) -> List[Any]: # This inner function sort imports between [ ]. def _replace(_SCREAMING_SNAKE_CASE ): lowerCamelCase : Optional[Any] = match.groups()[0] if "," not in imports: return f'''[{imports}]''' lowerCamelCase : int = [part.strip().replace("\"" ,"" ) for part in imports.split("," )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowerCamelCase : Optional[int] = keys[:-1] return "[" + ", ".join([f'''"{k}"''' for k in sort_objects(_SCREAMING_SNAKE_CASE )] ) + "]" lowerCamelCase : List[str] = import_statement.split("\n" ) if len(_SCREAMING_SNAKE_CASE ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. lowerCamelCase : List[str] = 2 if lines[1].strip() == "[" else 1 lowerCamelCase : Union[str, Any] = [(i, _re_strip_line.search(_SCREAMING_SNAKE_CASE ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] lowerCamelCase : str = sort_objects(_SCREAMING_SNAKE_CASE ,key=lambda _SCREAMING_SNAKE_CASE : x[1] ) lowerCamelCase : str = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(_SCREAMING_SNAKE_CASE ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: lowerCamelCase : Optional[int] = _re_bracket_content.sub(_replace ,lines[1] ) else: lowerCamelCase : List[str] = [part.strip().replace("\"" ,"" ) for part in lines[1].split("," )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: lowerCamelCase : Any = keys[:-1] lowerCamelCase : Any = get_indent(lines[1] ) + ", ".join([f'''"{k}"''' for k in sort_objects(_SCREAMING_SNAKE_CASE )] ) return "\n".join(_SCREAMING_SNAKE_CASE ) else: # Finally we have to deal with imports fitting on one line lowerCamelCase : Dict = _re_bracket_content.sub(_replace ,_SCREAMING_SNAKE_CASE ) return import_statement def A ( _SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE=True ) -> Optional[Any]: with open(_SCREAMING_SNAKE_CASE ,encoding="utf-8" ) as f: lowerCamelCase : Union[str, Any] = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 lowerCamelCase : Optional[int] = split_code_in_indented_blocks( _SCREAMING_SNAKE_CASE ,start_prompt="_import_structure = {" ,end_prompt="if TYPE_CHECKING:" ) # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 ,len(_SCREAMING_SNAKE_CASE ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. lowerCamelCase : int = main_blocks[block_idx] lowerCamelCase : Union[str, Any] = block.split("\n" ) # Get to the start of the imports. lowerCamelCase : List[str] = 0 while line_idx < len(_SCREAMING_SNAKE_CASE ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: lowerCamelCase : int = len(_SCREAMING_SNAKE_CASE ) else: line_idx += 1 if line_idx >= len(_SCREAMING_SNAKE_CASE ): continue # Ignore beginning and last line: they don't contain anything. lowerCamelCase : Optional[int] = "\n".join(block_lines[line_idx:-1] ) lowerCamelCase : Optional[int] = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. lowerCamelCase : Dict = split_code_in_indented_blocks(_SCREAMING_SNAKE_CASE ,indent_level=_SCREAMING_SNAKE_CASE ) # We have two categories of import key: list or _import_structure[key].append/extend lowerCamelCase : Union[str, Any] = _re_direct_key if "_import_structure = {" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. lowerCamelCase : Optional[Any] = [(pattern.search(_SCREAMING_SNAKE_CASE ).groups()[0] if pattern.search(_SCREAMING_SNAKE_CASE ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. lowerCamelCase : Optional[Any] = [(i, key) for i, key in enumerate(_SCREAMING_SNAKE_CASE ) if key is not None] lowerCamelCase : str = [x[0] for x in sorted(_SCREAMING_SNAKE_CASE ,key=lambda _SCREAMING_SNAKE_CASE : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. lowerCamelCase : List[Any] = 0 lowerCamelCase : Optional[Any] = [] for i in range(len(_SCREAMING_SNAKE_CASE ) ): if keys[i] is None: reorderded_blocks.append(internal_blocks[i] ) else: lowerCamelCase : Union[str, Any] = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reorderded_blocks.append(_SCREAMING_SNAKE_CASE ) count += 1 # And we put our main block back together with its first and last line. lowerCamelCase : Dict = "\n".join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]] ) if code != "\n".join(_SCREAMING_SNAKE_CASE ): if check_only: return True else: print(f'''Overwriting {file}.''' ) with open(_SCREAMING_SNAKE_CASE ,"w" ,encoding="utf-8" ) as f: f.write("\n".join(_SCREAMING_SNAKE_CASE ) ) def A ( _SCREAMING_SNAKE_CASE=True ) -> Any: lowerCamelCase : Optional[Any] = [] for root, _, files in os.walk(_SCREAMING_SNAKE_CASE ): if "__init__.py" in files: lowerCamelCase : Any = sort_imports(os.path.join(_SCREAMING_SNAKE_CASE ,"__init__.py" ) ,check_only=_SCREAMING_SNAKE_CASE ) if result: lowerCamelCase : Optional[Any] = [os.path.join(_SCREAMING_SNAKE_CASE ,"__init__.py" )] if len(_SCREAMING_SNAKE_CASE ) > 0: raise ValueError(f'''Would overwrite {len(_SCREAMING_SNAKE_CASE )} files, run `make style`.''' ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Tuple = argparse.ArgumentParser() parser.add_argument('--check_only', action='store_true', help='Whether to only check or fix style.') SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
48
'''simple docstring''' __lowerCAmelCase = { '''A''': ['''B''', '''C''', '''E'''], '''B''': ['''A''', '''D''', '''E'''], '''C''': ['''A''', '''F''', '''G'''], '''D''': ['''B'''], '''E''': ['''A''', '''B''', '''D'''], '''F''': ['''C'''], '''G''': ['''C'''], } def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> list[str]: _a : List[Any] = set() # keep track of all the paths to be checked _a : Any = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue _a : Tuple = queue.pop(0 ) # get the last node from the path _a : Tuple = path[-1] if node not in explored: _a : Optional[Any] = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: _a : Any = list(lowerCAmelCase_ ) new_path.append(lowerCAmelCase_ ) queue.append(lowerCAmelCase_ ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(lowerCAmelCase_ ) # in case there's no path between the 2 nodes return [] def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> int: if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 _a : Optional[int] = [start] _a : Dict = set(lowerCAmelCase_ ) # Keep tab on distances from `start` node. _a : Dict = {start: 0, target: -1} while queue: _a : List[str] = queue.pop(0 ) if node == target: _a : Any = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(lowerCAmelCase_ ) queue.append(lowerCAmelCase_ ) _a : Any = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, '''G''', '''D''')) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, '''G''', '''D''')) # returns 4
89
0
from collections import UserDict from typing import Union import numpy as np import requests from ..utils import ( add_end_docstrings, logging, ) from .audio_classification import ffmpeg_read from .base import PIPELINE_INIT_ARGS, Pipeline __snake_case :List[Any] = logging.get_logger(__name__) @add_end_docstrings(__UpperCAmelCase ) class _A ( __UpperCAmelCase ): def __init__( self : Any , **__SCREAMING_SNAKE_CASE : Union[str, Any]): '''simple docstring''' super().__init__(**__SCREAMING_SNAKE_CASE) if self.framework != "pt": raise ValueError(F'The {self.__class__} is only available in PyTorch.') # No specific FOR_XXX available yet def __call__( self : Tuple , __SCREAMING_SNAKE_CASE : Union[np.ndarray, bytes, str] , **__SCREAMING_SNAKE_CASE : int): '''simple docstring''' return super().__call__(__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE) def _lowerCamelCase ( self : Tuple , **__SCREAMING_SNAKE_CASE : Any): '''simple docstring''' __a = {} if "candidate_labels" in kwargs: __a = kwargs['''candidate_labels'''] if "hypothesis_template" in kwargs: __a = kwargs['''hypothesis_template'''] return preprocess_params, {}, {} def _lowerCamelCase ( self : List[Any] , __SCREAMING_SNAKE_CASE : Tuple , __SCREAMING_SNAKE_CASE : List[str]=None , __SCREAMING_SNAKE_CASE : Tuple="This is a sound of {}."): '''simple docstring''' if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE): if audio.startswith('''http://''') or audio.startswith('''https://'''): # We need to actually check for a real protocol, otherwise it's impossible to use a local file # like http_huggingface_co.png __a = requests.get(__SCREAMING_SNAKE_CASE).content else: with open(__SCREAMING_SNAKE_CASE , '''rb''') as f: __a = f.read() if isinstance(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE): __a = ffmpeg_read(__SCREAMING_SNAKE_CASE , self.feature_extractor.sampling_rate) if not isinstance(__SCREAMING_SNAKE_CASE , np.ndarray): raise ValueError('''We expect a numpy ndarray as input''') if len(audio.shape) != 1: raise ValueError('''We expect a single channel audio input for ZeroShotAudioClassificationPipeline''') __a = self.feature_extractor( [audio] , sampling_rate=self.feature_extractor.sampling_rate , return_tensors='''pt''') __a = candidate_labels __a = [hypothesis_template.format(__SCREAMING_SNAKE_CASE) for x in candidate_labels] __a = self.tokenizer(__SCREAMING_SNAKE_CASE , return_tensors=self.framework , padding=__SCREAMING_SNAKE_CASE) __a = [text_inputs] return inputs def _lowerCamelCase ( self : List[Any] , __SCREAMING_SNAKE_CASE : Optional[int]): '''simple docstring''' __a = model_inputs.pop('''candidate_labels''') __a = model_inputs.pop('''text_inputs''') if isinstance(text_inputs[0] , __SCREAMING_SNAKE_CASE): __a = text_inputs[0] else: # Batching case. __a = text_inputs[0][0] __a = self.model(**__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE) __a = { '''candidate_labels''': candidate_labels, '''logits''': outputs.logits_per_audio, } return model_outputs def _lowerCamelCase ( self : Optional[int] , __SCREAMING_SNAKE_CASE : Optional[int]): '''simple docstring''' __a = model_outputs.pop('''candidate_labels''') __a = model_outputs['''logits'''][0] if self.framework == "pt": __a = logits.softmax(dim=0) __a = probs.tolist() else: raise ValueError('''`tf` framework not supported.''') __a = [ {'''score''': score, '''label''': candidate_label} for score, candidate_label in sorted(zip(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE) , key=lambda __SCREAMING_SNAKE_CASE: -x[0]) ] return result
49
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __lowerCAmelCase = {'''configuration_swin''': ['''SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SwinConfig''', '''SwinOnnxConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''SWIN_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SwinForImageClassification''', '''SwinForMaskedImageModeling''', '''SwinModel''', '''SwinPreTrainedModel''', '''SwinBackbone''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFSwinForImageClassification''', '''TFSwinForMaskedImageModeling''', '''TFSwinModel''', '''TFSwinPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_swin import SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinConfig, SwinOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swin import ( SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, SwinBackbone, SwinForImageClassification, SwinForMaskedImageModeling, SwinModel, SwinPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_swin import ( TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, TFSwinForImageClassification, TFSwinForMaskedImageModeling, TFSwinModel, TFSwinPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
89
0
import argparse from tax import checkpoints from transformers import AutoConfig, FlaxAutoModelForSeqaSeqLM def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) -> Union[str, Any]: lowerCamelCase__ : List[str] = AutoConfig.from_pretrained(_UpperCAmelCase ) lowerCamelCase__ : Any = FlaxAutoModelForSeqaSeqLM.from_config(config=_UpperCAmelCase ) lowerCamelCase__ : Optional[int] = checkpoints.load_tax_checkpoint(_UpperCAmelCase ) lowerCamelCase__ : Dict = 'wi_0' in tax_model['target']['encoder']['layers_0']['mlp'] if config.model_type == "t5": lowerCamelCase__ : Optional[Any] = 'SelfAttention' if config.model_type == "longt5" and config.encoder_attention_type == "local": lowerCamelCase__ : Union[str, Any] = 'LocalSelfAttention' elif config.model_type == "longt5" and config.encoder_attention_type == "transient-global": lowerCamelCase__ : Tuple = 'TransientGlobalSelfAttention' else: raise ValueError( 'Given config is expected to have `model_type=\'t5\'`, or `model_type=\'longt5` with `encoder_attention_type`' ' attribute with a value from [\'local\', \'transient-global].' ) # Encoder for layer_index in range(config.num_layers ): lowerCamelCase__ : Union[str, Any] = F"""layers_{str(_UpperCAmelCase )}""" # Self-Attention lowerCamelCase__ : Any = tax_model['target']['encoder'][layer_name]['attention']['key']['kernel'] lowerCamelCase__ : List[str] = tax_model['target']['encoder'][layer_name]['attention']['out']['kernel'] lowerCamelCase__ : Union[str, Any] = tax_model['target']['encoder'][layer_name]['attention']['query']['kernel'] lowerCamelCase__ : Tuple = tax_model['target']['encoder'][layer_name]['attention']['value']['kernel'] # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": lowerCamelCase__ : Optional[Any] = tax_model['target']['encoder'][layer_name]['attention']['T5LayerNorm_0']['scale'] # Layer Normalization lowerCamelCase__ : int = tax_model['target']['encoder'][layer_name]['pre_attention_layer_norm']['scale'] if split_mlp_wi: lowerCamelCase__ : Tuple = tax_model['target']['encoder'][layer_name]['mlp']['wi_0']['kernel'] lowerCamelCase__ : Optional[int] = tax_model['target']['encoder'][layer_name]['mlp']['wi_1']['kernel'] else: lowerCamelCase__ : List[str] = tax_model['target']['encoder'][layer_name]['mlp']['wi']['kernel'] lowerCamelCase__ : int = tax_model['target']['encoder'][layer_name]['mlp']['wo']['kernel'] # Layer Normalization lowerCamelCase__ : Optional[Any] = tax_model['target']['encoder'][layer_name]['pre_mlp_layer_norm']['scale'] # Assigning lowerCamelCase__ : Optional[int] = flax_model.params['encoder']['block'][str(_UpperCAmelCase )]['layer'] lowerCamelCase__ : int = tax_attention_key lowerCamelCase__ : str = tax_attention_out lowerCamelCase__ : Optional[Any] = tax_attention_query lowerCamelCase__ : Dict = tax_attention_value lowerCamelCase__ : List[str] = tax_attention_layer_norm # Global input layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": lowerCamelCase__ : List[Any] = tax_global_layer_norm if split_mlp_wi: lowerCamelCase__ : List[str] = tax_mlp_wi_a lowerCamelCase__ : Union[str, Any] = tax_mlp_wi_a else: lowerCamelCase__ : List[Any] = tax_mlp_wi lowerCamelCase__ : List[str] = tax_mlp_wo lowerCamelCase__ : Optional[int] = tax_mlp_layer_norm lowerCamelCase__ : Any = flax_model_encoder_layer_block # Only for layer 0: lowerCamelCase__ : List[Any] = tax_model['target']['encoder']['relpos_bias']['rel_embedding'].T lowerCamelCase__ : List[str] = tax_encoder_rel_embedding # Side/global relative position_bias + layer norm if config.model_type == "longt5" and config.encoder_attention_type == "transient-global": lowerCamelCase__ : Optional[Any] = tax_model['target']['encoder']['side_relpos_bias']['rel_embedding'].T lowerCamelCase__ : str = tax_encoder_global_rel_embedding # Assigning lowerCamelCase__ : Union[str, Any] = tax_model['target']['encoder']['encoder_norm']['scale'] lowerCamelCase__ : str = tax_encoder_norm # Decoder for layer_index in range(config.num_layers ): lowerCamelCase__ : str = F"""layers_{str(_UpperCAmelCase )}""" # Self-Attention lowerCamelCase__ : Optional[int] = tax_model['target']['decoder'][layer_name]['self_attention']['key']['kernel'] lowerCamelCase__ : List[Any] = tax_model['target']['decoder'][layer_name]['self_attention']['out']['kernel'] lowerCamelCase__ : str = tax_model['target']['decoder'][layer_name]['self_attention']['query']['kernel'] lowerCamelCase__ : Tuple = tax_model['target']['decoder'][layer_name]['self_attention']['value']['kernel'] # Layer Normalization lowerCamelCase__ : Union[str, Any] = tax_model['target']['decoder'][layer_name]['pre_self_attention_layer_norm'][ 'scale' ] # Encoder-Decoder-Attention lowerCamelCase__ : Optional[Any] = tax_model['target']['decoder'][layer_name]['encoder_decoder_attention'] lowerCamelCase__ : str = tax_enc_dec_attention_module['key']['kernel'] lowerCamelCase__ : str = tax_enc_dec_attention_module['out']['kernel'] lowerCamelCase__ : int = tax_enc_dec_attention_module['query']['kernel'] lowerCamelCase__ : str = tax_enc_dec_attention_module['value']['kernel'] # Layer Normalization lowerCamelCase__ : Dict = tax_model['target']['decoder'][layer_name]['pre_cross_attention_layer_norm']['scale'] # MLP if split_mlp_wi: lowerCamelCase__ : Optional[Any] = tax_model['target']['decoder'][layer_name]['mlp']['wi_0']['kernel'] lowerCamelCase__ : str = tax_model['target']['decoder'][layer_name]['mlp']['wi_1']['kernel'] else: lowerCamelCase__ : List[str] = tax_model['target']['decoder'][layer_name]['mlp']['wi']['kernel'] lowerCamelCase__ : Union[str, Any] = tax_model['target']['decoder'][layer_name]['mlp']['wo']['kernel'] # Layer Normalization lowerCamelCase__ : List[str] = tax_model['target']['decoder'][layer_name]['pre_mlp_layer_norm']['scale'] # Assigning lowerCamelCase__ : Tuple = flax_model.params['decoder']['block'][str(_UpperCAmelCase )]['layer'] lowerCamelCase__ : Optional[Any] = tax_attention_key lowerCamelCase__ : str = tax_attention_out lowerCamelCase__ : int = tax_attention_query lowerCamelCase__ : Optional[Any] = tax_attention_value lowerCamelCase__ : Optional[Any] = tax_pre_attention_layer_norm lowerCamelCase__ : str = tax_enc_dec_attention_key lowerCamelCase__ : Dict = tax_enc_dec_attention_out lowerCamelCase__ : Optional[Any] = tax_enc_dec_attention_query lowerCamelCase__ : Optional[int] = tax_enc_dec_attention_value lowerCamelCase__ : Tuple = tax_cross_layer_norm if split_mlp_wi: lowerCamelCase__ : List[Any] = tax_mlp_wi_a lowerCamelCase__ : Union[str, Any] = tax_mlp_wi_a else: lowerCamelCase__ : str = tax_mlp_wi lowerCamelCase__ : Optional[int] = tax_mlp_wo lowerCamelCase__ : Dict = txa_mlp_layer_norm lowerCamelCase__ : List[Any] = flax_model_decoder_layer_block # Decoder Normalization lowerCamelCase__ : str = tax_model['target']['decoder']['decoder_norm']['scale'] lowerCamelCase__ : List[Any] = txa_decoder_norm # Only for layer 0: lowerCamelCase__ : Any = tax_model['target']['decoder']['relpos_bias']['rel_embedding'].T lowerCamelCase__ : List[str] = tax_decoder_rel_embedding # Token Embeddings lowerCamelCase__ : Union[str, Any] = tax_model['target']['token_embedder']['embedding'] lowerCamelCase__ : Optional[Any] = txa_token_embeddings # LM Head (only in v1.1 and LongT5 checkpoints) if "logits_dense" in tax_model["target"]["decoder"]: lowerCamelCase__ : List[str] = tax_model['target']['decoder']['logits_dense']['kernel'] flax_model.save_pretrained(_UpperCAmelCase ) print('T5X Model was sucessfully converted!' ) if __name__ == "__main__": _UpperCAmelCase : int = argparse.ArgumentParser() # Required parameters parser.add_argument( """--t5x_checkpoint_path""", default=None, type=str, required=True, help="""Path the T5X checkpoint.""" ) parser.add_argument("""--config_name""", default=None, type=str, required=True, help="""Config name of LongT5/T5 model.""") parser.add_argument( """--flax_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output FLAX model.""" ) _UpperCAmelCase : Tuple = parser.parse_args() convert_tax_checkpoint_to_flax(args.tax_checkpoint_path, args.config_name, args.flax_dump_folder_path)
50
'''simple docstring''' import unittest from transformers import BarthezTokenizer, BarthezTokenizerFast, BatchEncoding from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers @require_sentencepiece @slow # see https://github.com/huggingface/transformers/issues/11457 class __magic_name__ ( _UpperCamelCase , unittest.TestCase ): lowerCAmelCase : Optional[int] = BarthezTokenizer lowerCAmelCase : int = BarthezTokenizerFast lowerCAmelCase : Dict = True lowerCAmelCase : str = True def __lowercase ( self : List[Any] ): super().setUp() _a : List[Any] = BarthezTokenizerFast.from_pretrained('moussaKam/mbarthez' ) tokenizer.save_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ,legacy_format=_UpperCAmelCase ) _a : Union[str, Any] = tokenizer def __lowercase ( self : Tuple ): _a : Optional[Any] = '<pad>' _a : List[Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_UpperCAmelCase ) ,_UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_UpperCAmelCase ) ,_UpperCAmelCase ) def __lowercase ( self : str ): _a : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] ,'<s>' ) self.assertEqual(vocab_keys[1] ,'<pad>' ) self.assertEqual(vocab_keys[-1] ,'<mask>' ) self.assertEqual(len(_UpperCAmelCase ) ,101122 ) def __lowercase ( self : Dict ): self.assertEqual(self.get_tokenizer().vocab_size ,101122 ) @require_torch def __lowercase ( self : Dict ): _a : Any = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] _a : Dict = [0, 57, 3018, 70307, 91, 2] _a : Dict = self.tokenizer( _UpperCAmelCase ,max_length=len(_UpperCAmelCase ) ,padding=_UpperCAmelCase ,truncation=_UpperCAmelCase ,return_tensors='pt' ) self.assertIsInstance(_UpperCAmelCase ,_UpperCAmelCase ) self.assertEqual((2, 6) ,batch.input_ids.shape ) self.assertEqual((2, 6) ,batch.attention_mask.shape ) _a : Tuple = batch.input_ids.tolist()[0] self.assertListEqual(_UpperCAmelCase ,_UpperCAmelCase ) def __lowercase ( self : Optional[Any] ): if not self.test_rust_tokenizer: return _a : str = self.get_tokenizer() _a : List[str] = self.get_rust_tokenizer() _a : Dict = 'I was born in 92000, and this is falsé.' _a : List[Any] = tokenizer.tokenize(_UpperCAmelCase ) _a : Tuple = rust_tokenizer.tokenize(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase ,_UpperCAmelCase ) _a : Optional[Any] = tokenizer.encode(_UpperCAmelCase ,add_special_tokens=_UpperCAmelCase ) _a : Optional[int] = rust_tokenizer.encode(_UpperCAmelCase ,add_special_tokens=_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase ,_UpperCAmelCase ) _a : Union[str, Any] = self.get_rust_tokenizer() _a : Any = tokenizer.encode(_UpperCAmelCase ) _a : Optional[int] = rust_tokenizer.encode(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase ,_UpperCAmelCase ) @slow def __lowercase ( self : Optional[int] ): # fmt: off _a : Optional[int] = {'input_ids': [[0, 490, 14328, 4507, 354, 47, 43669, 95, 25, 78117, 20215, 19779, 190, 22, 400, 4, 35343, 80310, 603, 86, 24937, 105, 33438, 94762, 196, 39642, 7, 15, 15933, 173, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 10534, 87, 25, 66, 3358, 196, 55289, 8, 82961, 81, 2204, 75203, 7, 15, 763, 12956, 216, 178, 14328, 9595, 1377, 69693, 7, 448, 71021, 196, 18106, 1437, 13974, 108, 9083, 4, 49315, 7, 39, 86, 1326, 2793, 46333, 4, 448, 196, 74588, 7, 49315, 7, 39, 21, 822, 38470, 74, 21, 66723, 62480, 8, 22050, 5, 2]], '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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # moussaKam/mbarthez is a french model. So we also use french texts. _a : Optional[Any] = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=_UpperCAmelCase ,model_name='moussaKam/mbarthez' ,revision='c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6' ,sequences=_UpperCAmelCase ,)
89
0
import os import tempfile import unittest from transformers.models.marian.convert_marian_tatoeba_to_pytorch import DEFAULT_REPO, TatoebaConverter from transformers.testing_utils import slow from transformers.utils import cached_property @unittest.skipUnless(os.path.exists(a ) , '''Tatoeba directory does not exist.''' ) class __snake_case ( unittest.TestCase ): @cached_property def lowerCamelCase ( self : Optional[int]): """simple docstring""" UpperCAmelCase_ = tempfile.mkdtemp() return TatoebaConverter(save_dir=_snake_case) @slow def lowerCamelCase ( self : str): """simple docstring""" self.resolver.convert_models(['''heb-eng''']) @slow def lowerCamelCase ( self : str): """simple docstring""" UpperCAmelCase_ , UpperCAmelCase_ = self.resolver.write_model_card('''opus-mt-he-en''' , dry_run=_snake_case) assert mmeta["long_pair"] == "heb-eng"
51
'''simple docstring''' import subprocess import sys from transformers import BertConfig, BertModel, BertTokenizer, pipeline from transformers.testing_utils import TestCasePlus, require_torch class __magic_name__ ( _UpperCamelCase ): @require_torch def __lowercase ( self : Tuple ): # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched _a : Optional[int] = '\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n ' _a : List[str] = '\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n ' _a : Tuple = '\nimport socket\ndef offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn\'t access internet")\nsocket.socket = offline_socket\n ' # Force fetching the files so that we can use the cache _a : List[Any] = 'hf-internal-testing/tiny-random-bert' BertConfig.from_pretrained(_UpperCAmelCase ) BertModel.from_pretrained(_UpperCAmelCase ) BertTokenizer.from_pretrained(_UpperCAmelCase ) pipeline(task='fill-mask' ,model=_UpperCAmelCase ) # baseline - just load from_pretrained with normal network _a : Optional[int] = [sys.executable, '-c', '\n'.join([load, run, mock] )] # should succeed _a : Tuple = self.get_env() # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files _a : int = '1' _a : List[Any] = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) @require_torch def __lowercase ( self : Any ): # python one-liner segments # this must be loaded before socket.socket is monkey-patched _a : Dict = '\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n ' _a : Optional[int] = '\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n ' _a : Optional[Any] = '\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet")\nsocket.socket = offline_socket\n ' # Force fetching the files so that we can use the cache _a : int = 'hf-internal-testing/tiny-random-bert' BertConfig.from_pretrained(_UpperCAmelCase ) BertModel.from_pretrained(_UpperCAmelCase ) BertTokenizer.from_pretrained(_UpperCAmelCase ) pipeline(task='fill-mask' ,model=_UpperCAmelCase ) # baseline - just load from_pretrained with normal network _a : Optional[int] = [sys.executable, '-c', '\n'.join([load, run, mock] )] # should succeed _a : str = self.get_env() _a : Optional[Any] = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) @require_torch def __lowercase ( self : List[str] ): # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched _a : Union[str, Any] = '\nfrom transformers import BertConfig, BertModel, BertTokenizer\n ' _a : Optional[Any] = '\nmname = "hf-internal-testing/tiny-random-bert-sharded"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nprint("success")\n ' _a : str = '\nimport socket\ndef offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled")\nsocket.socket = offline_socket\n ' # baseline - just load from_pretrained with normal network _a : Optional[Any] = [sys.executable, '-c', '\n'.join([load, run] )] # should succeed _a : Dict = self.get_env() _a : int = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) # next emulate no network _a : List[Any] = [sys.executable, '-c', '\n'.join([load, mock, run] )] # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this. # env["TRANSFORMERS_OFFLINE"] = "0" # result = subprocess.run(cmd, env=env, check=False, capture_output=True) # self.assertEqual(result.returncode, 1, result.stderr) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files _a : int = '1' _a : Any = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) @require_torch def __lowercase ( self : int ): _a : Optional[Any] = '\nfrom transformers import pipeline\n ' _a : str = '\nmname = "hf-internal-testing/tiny-random-bert"\npipe = pipeline(model=mname)\n ' _a : List[str] = '\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled")\nsocket.socket = offline_socket\n ' _a : List[Any] = self.get_env() _a : Dict = '1' _a : Dict = [sys.executable, '-c', '\n'.join([load, mock, run] )] _a : str = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,1 ,result.stderr ) self.assertIn( 'You cannot infer task automatically within `pipeline` when using offline mode' ,result.stderr.decode().replace('\n' ,'' ) ,) @require_torch def __lowercase ( self : int ): _a : Optional[int] = '\nfrom transformers import AutoModel\n ' _a : List[Any] = '\nmname = "hf-internal-testing/test_dynamic_model"\nAutoModel.from_pretrained(mname, trust_remote_code=True)\nprint("success")\n ' # baseline - just load from_pretrained with normal network _a : Union[str, Any] = [sys.executable, '-c', '\n'.join([load, run] )] # should succeed _a : Tuple = self.get_env() _a : List[str] = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files _a : Optional[Any] = '1' _a : Any = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() )
89
0
import inspect import unittest from huggingface_hub import hf_hub_download from transformers import ConvNextConfig, UperNetConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import UperNetForSemanticSegmentation from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class A__ : def __init__( self , A_ , A_=13 , A_=32 , A_=3 , A_=4 , A_=[10, 20, 30, 40] , A_=[2, 2, 3, 2] , A_=True , A_=True , A_=37 , A_="gelu" , A_=10 , A_=0.02 , A_=["stage2", "stage3", "stage4"] , A_=3 , A_=None , ): '''simple docstring''' UpperCamelCase : Optional[Any] = parent UpperCamelCase : Tuple = batch_size UpperCamelCase : Union[str, Any] = image_size UpperCamelCase : Dict = num_channels UpperCamelCase : str = num_stages UpperCamelCase : Any = hidden_sizes UpperCamelCase : Tuple = depths UpperCamelCase : int = is_training UpperCamelCase : Dict = use_labels UpperCamelCase : Optional[int] = intermediate_size UpperCamelCase : Any = hidden_act UpperCamelCase : List[str] = type_sequence_label_size UpperCamelCase : str = initializer_range UpperCamelCase : Optional[int] = out_features UpperCamelCase : List[str] = num_labels UpperCamelCase : Tuple = scope UpperCamelCase : Optional[Any] = num_stages def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Any = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase : Optional[int] = None if self.use_labels: UpperCamelCase : Optional[Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCamelCase : Optional[int] = self.get_config() return config, pixel_values, labels def __UpperCamelCase( self ): '''simple docstring''' return ConvNextConfig( num_channels=self.num_channels , num_stages=self.num_stages , hidden_sizes=self.hidden_sizes , depths=self.depths , is_training=self.is_training , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , out_features=self.out_features , ) def __UpperCamelCase( self ): '''simple docstring''' return UperNetConfig( backbone_config=self.get_backbone_config() , hidden_size=512 , pool_scales=[1, 2, 3, 6] , use_auxiliary_head=A_ , auxiliary_loss_weight=0.4 , auxiliary_in_channels=40 , auxiliary_channels=256 , auxiliary_num_convs=1 , auxiliary_concat_input=A_ , loss_ignore_index=255 , num_labels=self.num_labels , ) def __UpperCamelCase( self , A_ , A_ , A_ ): '''simple docstring''' UpperCamelCase : List[str] = UperNetForSemanticSegmentation(config=A_ ) model.to(A_ ) model.eval() UpperCamelCase : List[Any] = model(A_ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size, self.image_size) ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[Any] = self.prepare_config_and_inputs() ( ( UpperCamelCase ) , ( UpperCamelCase ) , ( UpperCamelCase ) , ) : Optional[int] = config_and_inputs UpperCamelCase : str = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class A__ ( __snake_case , __snake_case , unittest.TestCase ): _UpperCAmelCase :Optional[Any] = (UperNetForSemanticSegmentation,) if is_torch_available() else () _UpperCAmelCase :List[str] = {'image-segmentation': UperNetForSemanticSegmentation} if is_torch_available() else {} _UpperCAmelCase :Dict = False _UpperCAmelCase :Dict = False _UpperCAmelCase :Optional[int] = False _UpperCAmelCase :Dict = False _UpperCAmelCase :Optional[Any] = False _UpperCAmelCase :Dict = False def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Union[str, Any] = UperNetModelTester(self ) UpperCamelCase : Dict = ConfigTester(self , config_class=A_ , has_text_modality=A_ , hidden_size=37 ) def __UpperCamelCase( self ): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __UpperCamelCase( self ): '''simple docstring''' return def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase , UpperCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase : Dict = model_class(A_ ) UpperCamelCase : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase : Optional[int] = [*signature.parameters.keys()] UpperCamelCase : List[Any] = ["pixel_values"] self.assertListEqual(arg_names[:1] , A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*A_ ) @unittest.skip(reason="UperNet does not use inputs_embeds" ) def __UpperCamelCase( self ): '''simple docstring''' pass @unittest.skip(reason="UperNet does not support input and output embeddings" ) def __UpperCamelCase( self ): '''simple docstring''' pass @unittest.skip(reason="UperNet does not have a base model" ) def __UpperCamelCase( self ): '''simple docstring''' pass @unittest.skip(reason="UperNet does not have a base model" ) def __UpperCamelCase( self ): '''simple docstring''' pass @require_torch_multi_gpu @unittest.skip(reason="UperNet has some layers using `add_module` which doesn't work well with `nn.DataParallel`" ) def __UpperCamelCase( self ): '''simple docstring''' pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def __UpperCamelCase( self ): '''simple docstring''' pass def __UpperCamelCase( self ): '''simple docstring''' def check_hidden_states_output(A_ , A_ , A_ ): UpperCamelCase : Any = model_class(A_ ) model.to(A_ ) model.eval() with torch.no_grad(): UpperCamelCase : Dict = model(**self._prepare_for_class(A_ , A_ ) ) UpperCamelCase : Optional[Any] = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states UpperCamelCase : Optional[Any] = self.model_tester.num_stages self.assertEqual(len(A_ ) , expected_num_stages + 1 ) # ConvNext's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) UpperCamelCase , UpperCamelCase : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase : Tuple = True check_hidden_states_output(A_ , A_ , A_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase : Dict = True check_hidden_states_output(A_ , A_ , A_ ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase , UpperCamelCase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() UpperCamelCase : Tuple = _config_zero_init(A_ ) UpperCamelCase : Optional[int] = _config_zero_init(configs_no_init.backbone_config ) for model_class in self.all_model_classes: UpperCamelCase : Dict = model_class(config=A_ ) for name, param in model.named_parameters(): if param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F"""Parameter {name} of model {model_class} seems not properly initialized""" , ) @unittest.skip(reason="UperNet does not have tied weights" ) def __UpperCamelCase( self ): '''simple docstring''' pass @slow def __UpperCamelCase( self ): '''simple docstring''' for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase : int = UperNetForSemanticSegmentation.from_pretrained(A_ ) self.assertIsNotNone(A_ ) def A_ ( ) -> Optional[Any]: UpperCamelCase : Optional[int] = hf_hub_download( repo_id="hf-internal-testing/fixtures_ade20k" , repo_type="dataset" , filename="ADE_val_00000001.jpg" ) UpperCamelCase : Dict = Image.open(_lowerCAmelCase ).convert("RGB" ) return image @require_torch @require_vision @slow class A__ ( unittest.TestCase ): def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : str = AutoImageProcessor.from_pretrained("openmmlab/upernet-swin-tiny" ) UpperCamelCase : Dict = UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-swin-tiny" ).to(A_ ) UpperCamelCase : Tuple = prepare_img() UpperCamelCase : Union[str, Any] = processor(images=A_ , return_tensors="pt" ).to(A_ ) with torch.no_grad(): UpperCamelCase : Union[str, Any] = model(**A_ ) UpperCamelCase : str = torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , A_ ) UpperCamelCase : Optional[Any] = torch.tensor( [[-7.59_58, -7.59_58, -7.43_02], [-7.59_58, -7.59_58, -7.43_02], [-7.47_97, -7.47_97, -7.30_68]] ).to(A_ ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , A_ , atol=1e-4 ) ) def __UpperCamelCase( self ): '''simple docstring''' UpperCamelCase : Optional[int] = AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-tiny" ) UpperCamelCase : str = UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-tiny" ).to(A_ ) UpperCamelCase : Any = prepare_img() UpperCamelCase : str = processor(images=A_ , return_tensors="pt" ).to(A_ ) with torch.no_grad(): UpperCamelCase : List[str] = model(**A_ ) UpperCamelCase : List[str] = torch.Size((1, model.config.num_labels, 512, 512) ) self.assertEqual(outputs.logits.shape , A_ ) UpperCamelCase : int = torch.tensor( [[-8.81_10, -8.81_10, -8.65_21], [-8.81_10, -8.81_10, -8.65_21], [-8.77_46, -8.77_46, -8.61_30]] ).to(A_ ) self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3] , A_ , atol=1e-4 ) )
52
'''simple docstring''' def __lowerCamelCase ( ) -> Tuple: for n in range(1 , 1000000 ): yield n * (n + 1) // 2 def __lowerCamelCase ( lowerCAmelCase_ ) -> List[Any]: _a : Any = 1 _a : Tuple = 2 while i * i <= n: _a : Tuple = 0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def __lowerCamelCase ( ) -> str: return next(i for i in triangle_number_generator() if count_divisors(lowerCAmelCase_ ) > 500 ) if __name__ == "__main__": print(solution())
89
0
'''simple docstring''' 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 a__ : Tuple =logging.get_logger(__name__) @add_end_docstrings(__lowerCamelCase ) class snake_case ( __lowerCamelCase ): """simple docstring""" def __init__( self : Optional[Any] , **__A : Dict ): super().__init__(**__A ) 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(__A ) def _lowerCamelCase ( self : int , **__A : Dict ): __UpperCamelCase = {} __UpperCamelCase = {} __UpperCamelCase = {} # preprocess args if "points_per_batch" in kwargs: __UpperCamelCase = kwargs['points_per_batch'] if "points_per_crop" in kwargs: __UpperCamelCase = kwargs['points_per_crop'] if "crops_n_layers" in kwargs: __UpperCamelCase = kwargs['crops_n_layers'] if "crop_overlap_ratio" in kwargs: __UpperCamelCase = kwargs['crop_overlap_ratio'] if "crop_n_points_downscale_factor" in kwargs: __UpperCamelCase = kwargs['crop_n_points_downscale_factor'] # postprocess args if "pred_iou_thresh" in kwargs: __UpperCamelCase = kwargs['pred_iou_thresh'] if "stability_score_offset" in kwargs: __UpperCamelCase = kwargs['stability_score_offset'] if "mask_threshold" in kwargs: __UpperCamelCase = kwargs['mask_threshold'] if "stability_score_thresh" in kwargs: __UpperCamelCase = kwargs['stability_score_thresh'] if "crops_nms_thresh" in kwargs: __UpperCamelCase = kwargs['crops_nms_thresh'] if "output_rle_mask" in kwargs: __UpperCamelCase = kwargs['output_rle_mask'] if "output_bboxes_mask" in kwargs: __UpperCamelCase = kwargs['output_bboxes_mask'] return preprocess_kwargs, forward_params, postprocess_kwargs def __call__( self : Union[str, Any] , __A : List[str] , *__A : List[Any] , __A : int=None , __A : Optional[int]=None , **__A : Any ): return super().__call__(__A , *__A , num_workers=__A , batch_size=__A , **__A ) def _lowerCamelCase ( self : Optional[int] , __A : Optional[int] , __A : Union[str, Any]=6_4 , __A : int = 0 , __A : float = 5_1_2 / 1_5_0_0 , __A : Optional[int] = 3_2 , __A : Optional[int] = 1 , ): __UpperCamelCase = load_image(__A ) __UpperCamelCase = self.image_processor.size['longest_edge'] __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = self.image_processor.generate_crop_boxes( __A , __A , __A , __A , __A , __A ) __UpperCamelCase = self.image_processor(images=__A , return_tensors='pt' ) with self.device_placement(): if self.framework == "pt": __UpperCamelCase = self.get_inference_context() with inference_context(): __UpperCamelCase = self._ensure_tensor_on_device(__A , device=self.device ) __UpperCamelCase = self.model.get_image_embeddings(model_inputs.pop('pixel_values' ) ) __UpperCamelCase = image_embeddings __UpperCamelCase = grid_points.shape[1] __UpperCamelCase = 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 , __A , __A ): __UpperCamelCase = grid_points[:, i : i + points_per_batch, :, :] __UpperCamelCase = input_labels[:, i : i + points_per_batch] __UpperCamelCase = 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 : Dict , __A : Union[str, Any] , __A : Any=0.88 , __A : Any=0.95 , __A : Tuple=0 , __A : str=1 , ): __UpperCamelCase = model_inputs.pop('input_boxes' ) __UpperCamelCase = model_inputs.pop('is_last' ) __UpperCamelCase = model_inputs.pop('original_sizes' ).tolist() __UpperCamelCase = model_inputs.pop('reshaped_input_sizes' ).tolist() __UpperCamelCase = self.model(**__A ) # post processing happens here in order to avoid CPU GPU copies of ALL the masks __UpperCamelCase = model_outputs['pred_masks'] __UpperCamelCase = self.image_processor.post_process_masks( __A , __A , __A , __A , binarize=__A ) __UpperCamelCase = model_outputs['iou_scores'] __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = self.image_processor.filter_masks( masks[0] , iou_scores[0] , original_sizes[0] , input_boxes[0] , __A , __A , __A , __A , ) return { "masks": masks, "is_last": is_last, "boxes": boxes, "iou_scores": iou_scores, } def _lowerCamelCase ( self : Union[str, Any] , __A : Dict , __A : Dict=False , __A : Optional[Any]=False , __A : Union[str, Any]=0.7 , ): __UpperCamelCase = [] __UpperCamelCase = [] __UpperCamelCase = [] 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' ) ) __UpperCamelCase = torch.cat(__A ) __UpperCamelCase = torch.cat(__A ) __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = self.image_processor.post_process_for_mask_generation( __A , __A , __A , __A ) __UpperCamelCase = defaultdict(__A ) for output in model_outputs: for k, v in output.items(): extra[k].append(__A ) __UpperCamelCase = {} if output_rle_mask: __UpperCamelCase = rle_mask if output_bboxes_mask: __UpperCamelCase = bounding_boxes return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
53
'''simple docstring''' import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class __magic_name__ ( _UpperCamelCase ): def __init__( self : Optional[int] ,_UpperCAmelCase : Union[str, "sqlalchemy.sql.Selectable"] ,_UpperCAmelCase : Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] ,_UpperCAmelCase : Optional[Features] = None ,_UpperCAmelCase : str = None ,_UpperCAmelCase : bool = False ,**_UpperCAmelCase : Dict ,): super().__init__(features=_UpperCAmelCase ,cache_dir=_UpperCAmelCase ,keep_in_memory=_UpperCAmelCase ,**_UpperCAmelCase ) _a : Tuple = Sql( cache_dir=_UpperCAmelCase ,features=_UpperCAmelCase ,sql=_UpperCAmelCase ,con=_UpperCAmelCase ,**_UpperCAmelCase ,) def __lowercase ( self : Dict ): _a : Optional[Any] = None _a : Dict = None _a : Dict = None _a : Optional[int] = None self.builder.download_and_prepare( download_config=_UpperCAmelCase ,download_mode=_UpperCAmelCase ,verification_mode=_UpperCAmelCase ,base_path=_UpperCAmelCase ,) # Build dataset for splits _a : List[str] = self.builder.as_dataset( split='train' ,verification_mode=_UpperCAmelCase ,in_memory=self.keep_in_memory ) return dataset class __magic_name__ : def __init__( self : Optional[int] ,_UpperCAmelCase : Dataset ,_UpperCAmelCase : str ,_UpperCAmelCase : Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] ,_UpperCAmelCase : Optional[int] = None ,_UpperCAmelCase : Optional[int] = None ,**_UpperCAmelCase : Dict ,): if num_proc is not None and num_proc <= 0: raise ValueError(F"""num_proc {num_proc} must be an integer > 0.""" ) _a : Dict = dataset _a : List[Any] = name _a : Tuple = con _a : Union[str, Any] = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE _a : List[Any] = num_proc _a : Tuple = to_sql_kwargs def __lowercase ( self : List[Any] ): _a : Tuple = self.to_sql_kwargs.pop('sql' ,_UpperCAmelCase ) _a : str = self.to_sql_kwargs.pop('con' ,_UpperCAmelCase ) _a : Optional[Any] = self.to_sql_kwargs.pop('index' ,_UpperCAmelCase ) _a : Any = self._write(index=_UpperCAmelCase ,**self.to_sql_kwargs ) return written def __lowercase ( self : Optional[int] ,_UpperCAmelCase : Dict ): _a , _a , _a : Any = args _a : Tuple = {**to_sql_kwargs, 'if_exists': 'append'} if offset > 0 else to_sql_kwargs _a : Dict = query_table( table=self.dataset.data ,key=slice(_UpperCAmelCase ,offset + self.batch_size ) ,indices=self.dataset._indices ,) _a : Tuple = batch.to_pandas() _a : Dict = df.to_sql(self.name ,self.con ,index=_UpperCAmelCase ,**_UpperCAmelCase ) return num_rows or len(_UpperCAmelCase ) def __lowercase ( self : int ,_UpperCAmelCase : Optional[int] ,**_UpperCAmelCase : List[Any] ): _a : Union[str, Any] = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 ,len(self.dataset ) ,self.batch_size ) ,unit='ba' ,disable=not logging.is_progress_bar_enabled() ,desc='Creating SQL from Arrow format' ,): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: _a , _a : List[Any] = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql ,[(offset, index, to_sql_kwargs) for offset in range(0 ,_UpperCAmelCase ,_UpperCAmelCase )] ,) ,total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size ,unit='ba' ,disable=not logging.is_progress_bar_enabled() ,desc='Creating SQL from Arrow format' ,): written += num_rows return written
89
0
"""simple docstring""" import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation a__ : Union[str, Any] = logging.get_logger(__name__) a__ : str = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} a__ : Dict = { '''tokenizer_file''': { '''EleutherAI/gpt-neox-20b''': '''https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/tokenizer.json''', }, } a__ : Dict = { '''gpt-neox-20b''': 2_0_4_8, } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : List[Any] = VOCAB_FILES_NAMES snake_case__ : Dict = PRETRAINED_VOCAB_FILES_MAP snake_case__ : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case__ : Union[str, Any] = ["input_ids", "attention_mask"] def __init__( self : Union[str, Any] , UpperCAmelCase__ : int=None , UpperCAmelCase__ : List[str]=None , UpperCAmelCase__ : str=None , UpperCAmelCase__ : Union[str, Any]="<|endoftext|>" , UpperCAmelCase__ : Optional[Any]="<|endoftext|>" , UpperCAmelCase__ : List[str]="<|endoftext|>" , UpperCAmelCase__ : List[Any]=False , **UpperCAmelCase__ : Optional[int] , ) -> Optional[Any]: super().__init__( UpperCAmelCase__ , UpperCAmelCase__ , tokenizer_file=UpperCAmelCase__ , unk_token=UpperCAmelCase__ , bos_token=UpperCAmelCase__ , eos_token=UpperCAmelCase__ , add_prefix_space=UpperCAmelCase__ , **UpperCAmelCase__ , ) __SCREAMING_SNAKE_CASE = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , UpperCAmelCase__ ) != add_prefix_space: __SCREAMING_SNAKE_CASE = getattr(UpperCAmelCase__ , pre_tok_state.pop("type" ) ) __SCREAMING_SNAKE_CASE = add_prefix_space __SCREAMING_SNAKE_CASE = pre_tok_class(**UpperCAmelCase__ ) __SCREAMING_SNAKE_CASE = add_prefix_space def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : str , UpperCAmelCase__ : Optional[str] = None ) -> Tuple[str]: __SCREAMING_SNAKE_CASE = self._tokenizer.model.save(UpperCAmelCase__ , name=UpperCAmelCase__ ) return tuple(UpperCAmelCase__ ) def UpperCAmelCase_ ( self : Optional[int] , UpperCAmelCase__ : "Conversation" ) -> List[int]: __SCREAMING_SNAKE_CASE = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(UpperCAmelCase__ , add_special_tokens=UpperCAmelCase__ ) + [self.eos_token_id] ) if len(UpperCAmelCase__ ) > self.model_max_length: __SCREAMING_SNAKE_CASE = input_ids[-self.model_max_length :] return input_ids
54
'''simple docstring''' from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> np.ndarray: _a : Union[str, Any] = cva.getAffineTransform(lowerCAmelCase_ , lowerCAmelCase_ ) return cva.warpAffine(lowerCAmelCase_ , lowerCAmelCase_ , (rows, cols) ) if __name__ == "__main__": # read original image __lowerCAmelCase = cva.imread( str(Path(__file__).resolve().parent.parent / '''image_data''' / '''lena.jpg''') ) # turn image in gray scale value __lowerCAmelCase = cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape __lowerCAmelCase , __lowerCAmelCase = gray_img.shape # set different points to rotate image __lowerCAmelCase = np.array([[50, 50], [200, 50], [50, 200]], np.floataa) __lowerCAmelCase = np.array([[10, 100], [200, 50], [100, 250]], np.floataa) __lowerCAmelCase = np.array([[50, 50], [150, 50], [120, 200]], np.floataa) __lowerCAmelCase = np.array([[10, 100], [80, 50], [180, 250]], np.floataa) # add all rotated images in a list __lowerCAmelCase = [ gray_img, get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), ] # plot different image rotations __lowerCAmelCase = plt.figure(1) __lowerCAmelCase = ['''Original''', '''Rotation 1''', '''Rotation 2''', '''Rotation 3'''] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, '''gray''') plt.title(titles[i]) plt.axis('''off''') plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
89
0
'''simple docstring''' import math def __snake_case ( UpperCAmelCase_ : int ): lowerCamelCase_ = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(UpperCAmelCase_ ) def __snake_case ( UpperCAmelCase_ : float = 1 / 12345 ): lowerCamelCase_ = 0 lowerCamelCase_ = 0 lowerCamelCase_ = 3 while True: lowerCamelCase_ = (integer**2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(UpperCAmelCase_ ): lowerCamelCase_ = int(UpperCAmelCase_ ) total_partitions += 1 if check_partition_perfect(UpperCAmelCase_ ): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return int(UpperCAmelCase_ ) integer += 1 if __name__ == "__main__": print(f'''{solution() = }''')
55
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCAmelCase = { '''configuration_bigbird_pegasus''': [ '''BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BigBirdPegasusConfig''', '''BigBirdPegasusOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BigBirdPegasusForCausalLM''', '''BigBirdPegasusForConditionalGeneration''', '''BigBirdPegasusForQuestionAnswering''', '''BigBirdPegasusForSequenceClassification''', '''BigBirdPegasusModel''', '''BigBirdPegasusPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP, BigBirdPegasusConfig, BigBirdPegasusOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST, BigBirdPegasusForCausalLM, BigBirdPegasusForConditionalGeneration, BigBirdPegasusForQuestionAnswering, BigBirdPegasusForSequenceClassification, BigBirdPegasusModel, BigBirdPegasusPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
89
0
'''simple docstring''' def __magic_name__ ( __UpperCAmelCase ) -> set: '''simple docstring''' snake_case_ = set() # edges = list of graph's edges snake_case_ = get_edges(__UpperCAmelCase ) # 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: snake_case_ ,snake_case_ = edges.pop() chosen_vertices.add(__UpperCAmelCase ) chosen_vertices.add(__UpperCAmelCase ) for edge in edges.copy(): if from_node in edge or to_node in edge: edges.discard(__UpperCAmelCase ) return chosen_vertices def __magic_name__ ( __UpperCAmelCase ) -> set: '''simple docstring''' snake_case_ = 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)}")
56
'''simple docstring''' import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=1024 , lowerCAmelCase_=1024 , lowerCAmelCase_=False , **lowerCAmelCase_ ) -> List[Any]: _a : str = AutoTokenizer.from_pretrained(lowerCAmelCase_ ) _a : List[Any] = SeqaSeqDataset(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , type_path='train' , **lowerCAmelCase_ ) _a : List[str] = tok.pad_token_id def get_lens(lowerCAmelCase_ ): _a : Dict = tqdm( DataLoader(lowerCAmelCase_ , batch_size=512 , num_workers=8 , shuffle=lowerCAmelCase_ , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) _a : Union[str, Any] = [] for batch in dl: _a : Optional[Any] = batch['input_ids'].ne(lowerCAmelCase_ ).sum(1 ).tolist() _a : Optional[Any] = batch['labels'].ne(lowerCAmelCase_ ).sum(1 ).tolist() if consider_target: for src, tgt in zip(lowerCAmelCase_ , lowerCAmelCase_ ): max_lens.append(max(lowerCAmelCase_ , lowerCAmelCase_ ) ) else: max_lens.extend(lowerCAmelCase_ ) return max_lens _a : str = get_lens(lowerCAmelCase_ ) _a : Optional[int] = SeqaSeqDataset(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , type_path='val' , **lowerCAmelCase_ ) _a : Dict = get_lens(lowerCAmelCase_ ) pickle_save(lowerCAmelCase_ , train_ds.len_file ) pickle_save(lowerCAmelCase_ , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
89
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, ) A : Optional[int] = { "configuration_blenderbot_small": [ "BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlenderbotSmallConfig", "BlenderbotSmallOnnxConfig", ], "tokenization_blenderbot_small": ["BlenderbotSmallTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Optional[int] = ["BlenderbotSmallTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Optional[Any] = [ "BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST", "BlenderbotSmallForCausalLM", "BlenderbotSmallForConditionalGeneration", "BlenderbotSmallModel", "BlenderbotSmallPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Optional[Any] = [ "TFBlenderbotSmallForConditionalGeneration", "TFBlenderbotSmallModel", "TFBlenderbotSmallPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : int = [ "FlaxBlenderbotSmallForConditionalGeneration", "FlaxBlenderbotSmallModel", "FlaxBlenderbotSmallPreTrainedModel", ] if TYPE_CHECKING: from .configuration_blenderbot_small import ( BLENDERBOT_SMALL_PRETRAINED_CONFIG_ARCHIVE_MAP, BlenderbotSmallConfig, BlenderbotSmallOnnxConfig, ) from .tokenization_blenderbot_small import BlenderbotSmallTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_blenderbot_small_fast import BlenderbotSmallTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blenderbot_small import ( BLENDERBOT_SMALL_PRETRAINED_MODEL_ARCHIVE_LIST, BlenderbotSmallForCausalLM, BlenderbotSmallForConditionalGeneration, BlenderbotSmallModel, BlenderbotSmallPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blenderbot_small import ( TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel, TFBlenderbotSmallPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_blenderbot_small import ( FlaxBlenderbotSmallForConditionalGeneration, FlaxBlenderbotSmallModel, FlaxBlenderbotSmallPreTrainedModel, ) else: import sys A : Dict = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
57
'''simple docstring''' from typing import Any class __magic_name__ : def __init__( self : List[Any] ,_UpperCAmelCase : Any ): _a : List[Any] = data _a : Union[str, Any] = None def __repr__( self : Any ): return F"""Node({self.data})""" class __magic_name__ : def __init__( self : int ): _a : Tuple = None def __iter__( self : str ): _a : int = self.head while node: yield node.data _a : Union[str, Any] = node.next def __len__( self : Optional[Any] ): return sum(1 for _ in self ) def __repr__( self : str ): return "->".join([str(_UpperCAmelCase ) for item in self] ) def __getitem__( self : Tuple ,_UpperCAmelCase : int ): if not 0 <= index < len(self ): raise ValueError('list index out of range.' ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self : Union[str, Any] ,_UpperCAmelCase : int ,_UpperCAmelCase : Any ): if not 0 <= index < len(self ): raise ValueError('list index out of range.' ) _a : Any = self.head for _ in range(_UpperCAmelCase ): _a : Optional[Any] = current.next _a : Optional[int] = data def __lowercase ( self : Optional[int] ,_UpperCAmelCase : Any ): self.insert_nth(len(self ) ,_UpperCAmelCase ) def __lowercase ( self : Union[str, Any] ,_UpperCAmelCase : Any ): self.insert_nth(0 ,_UpperCAmelCase ) def __lowercase ( self : str ,_UpperCAmelCase : int ,_UpperCAmelCase : Any ): if not 0 <= index <= len(self ): raise IndexError('list index out of range' ) _a : int = Node(_UpperCAmelCase ) if self.head is None: _a : str = new_node elif index == 0: _a : List[str] = self.head # link new_node to head _a : Union[str, Any] = new_node else: _a : int = self.head for _ in range(index - 1 ): _a : Union[str, Any] = temp.next _a : List[str] = temp.next _a : Optional[int] = new_node def __lowercase ( self : Optional[int] ): # print every node data print(self ) def __lowercase ( self : str ): return self.delete_nth(0 ) def __lowercase ( self : str ): # delete from tail return self.delete_nth(len(self ) - 1 ) def __lowercase ( self : List[str] ,_UpperCAmelCase : int = 0 ): if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError('List index out of range.' ) _a : Optional[Any] = self.head # default first node if index == 0: _a : int = self.head.next else: _a : int = self.head for _ in range(index - 1 ): _a : str = temp.next _a : str = temp.next _a : int = temp.next.next return delete_node.data def __lowercase ( self : List[Any] ): return self.head is None def __lowercase ( self : Tuple ): _a : List[Any] = None _a : Tuple = self.head while current: # Store the current node's next node. _a : Dict = current.next # Make the current node's next point backwards _a : str = prev # Make the previous node be the current node _a : Tuple = current # Make the current node the next node (to progress iteration) _a : Optional[Any] = next_node # Return prev in order to put the head at the end _a : int = prev def __lowerCamelCase ( ) -> None: _a : List[str] = LinkedList() assert linked_list.is_empty() is True assert str(lowerCAmelCase_ ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(10 ): assert len(lowerCAmelCase_ ) == i linked_list.insert_nth(lowerCAmelCase_ , i + 1 ) assert str(lowerCAmelCase_ ) == "->".join(str(lowerCAmelCase_ ) for i in range(1 , 11 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(11 ) assert str(lowerCAmelCase_ ) == "->".join(str(lowerCAmelCase_ ) for i in range(0 , 12 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 10 assert linked_list.delete_tail() == 11 assert len(lowerCAmelCase_ ) == 9 assert str(lowerCAmelCase_ ) == "->".join(str(lowerCAmelCase_ ) for i in range(1 , 10 ) ) assert all(linked_list[i] == i + 1 for i in range(0 , 9 ) ) is True for i in range(0 , 9 ): _a : Union[str, Any] = -i assert all(linked_list[i] == -i for i in range(0 , 9 ) ) is True linked_list.reverse() assert str(lowerCAmelCase_ ) == "->".join(str(lowerCAmelCase_ ) for i in range(-8 , 1 ) ) def __lowerCamelCase ( ) -> None: _a : Dict = [ -9, 100, Node(77345112 ), 'dlrow olleH', 7, 5555, 0, -192.55_555, 'Hello, world!', 77.9, Node(10 ), None, None, 12.20, ] _a : List[Any] = LinkedList() for i in test_input: linked_list.insert_tail(lowerCAmelCase_ ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(lowerCAmelCase_ ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head _a : List[str] = linked_list.delete_head() assert result == -9 assert ( str(lowerCAmelCase_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail _a : Dict = linked_list.delete_tail() assert result == 12.2 assert ( str(lowerCAmelCase_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list _a : Optional[Any] = linked_list.delete_nth(10 ) assert result is None assert ( str(lowerCAmelCase_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node('Hello again, world!' ) ) assert ( str(lowerCAmelCase_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(lowerCAmelCase_ ) assert ( str(lowerCAmelCase_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(lowerCAmelCase_ ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def __lowerCamelCase ( ) -> Union[str, Any]: from doctest import testmod testmod() _a : Optional[int] = LinkedList() linked_list.insert_head(input('Inserting 1st at head ' ).strip() ) linked_list.insert_head(input('Inserting 2nd at head ' ).strip() ) print('\nPrint list:' ) linked_list.print_list() linked_list.insert_tail(input('\nInserting 1st at tail ' ).strip() ) linked_list.insert_tail(input('Inserting 2nd at tail ' ).strip() ) print('\nPrint list:' ) linked_list.print_list() print('\nDelete head' ) linked_list.delete_head() print('Delete tail' ) linked_list.delete_tail() print('\nPrint list:' ) linked_list.print_list() print('\nReverse linked list' ) linked_list.reverse() print('\nPrint list:' ) linked_list.print_list() print('\nString representation of linked list:' ) print(lowerCAmelCase_ ) print('\nReading/changing Node data using indexing:' ) print(f"""Element at Position 1: {linked_list[1]}""" ) _a : Optional[Any] = input('Enter New Value: ' ).strip() print('New list:' ) print(lowerCAmelCase_ ) print(f"""length of linked_list is : {len(lowerCAmelCase_ )}""" ) if __name__ == "__main__": main()
89
0
'''simple docstring''' import json import logging import math import os import sys from dataclasses import dataclass, field from typing import Optional from datasets import Dataset, load_dataset import transformers from transformers import ( CONFIG_MAPPING, MODEL_FOR_MASKED_LM_MAPPING, AutoConfig, AutoModelForMaskedLM, AutoTokenizer, DataCollatorForWholeWordMask, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import get_last_checkpoint, is_main_process lowercase_ = logging.getLogger(__name__) lowercase_ = list(MODEL_FOR_MASKED_LM_MAPPING.keys()) lowercase_ = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class a_ : '''simple docstring''' UpperCamelCase = field( default=snake_case_ , metadata={ '''help''': ( '''The model checkpoint for weights initialization.Don\'t set if you want to train a model from scratch.''' ) } , ) UpperCamelCase = field( default=snake_case_ , metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(snake_case_ )} , ) UpperCamelCase = field( default=snake_case_ , metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) } , ) UpperCamelCase = field( default=snake_case_ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) UpperCamelCase = field( default=snake_case_ , metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} ) UpperCamelCase = field( default=snake_case_ , metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''} , ) UpperCamelCase = field( default=snake_case_ , metadata={'''help''': '''Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'''} , ) UpperCamelCase = field( default='''main''' , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} , ) UpperCamelCase = field( default=snake_case_ , metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } , ) def snake_case_( self ) -> str: if self.config_overrides is not None and (self.config_name is not None or self.model_name_or_path is not None): raise ValueError( """--config_overrides can't be used in combination with --config_name or --model_name_or_path""" ) @dataclass class a_ : '''simple docstring''' UpperCamelCase = field( default=snake_case_ , metadata={'''help''': '''The name of the dataset to use (via the datasets library).'''} ) UpperCamelCase = field( default=snake_case_ , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) UpperCamelCase = field(default=snake_case_ , metadata={'''help''': '''The input training data file (a text file).'''} ) UpperCamelCase = field( default=snake_case_ , metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''} , ) UpperCamelCase = field( default=snake_case_ , metadata={'''help''': '''An optional input train ref data file for whole word masking in Chinese.'''} , ) UpperCamelCase = field( default=snake_case_ , metadata={'''help''': '''An optional input validation ref data file for whole word masking in Chinese.'''} , ) UpperCamelCase = field( default=snake_case_ , metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} ) UpperCamelCase = field( default=5 , metadata={ '''help''': '''The percentage of the train set used as validation set in case there\'s no validation split''' } , ) UpperCamelCase = field( default=snake_case_ , metadata={ '''help''': ( '''The maximum total input sequence length after tokenization. Sequences longer ''' '''than this will be truncated. Default to the max input length of the model.''' ) } , ) UpperCamelCase = field( default=snake_case_ , metadata={'''help''': '''The number of processes to use for the preprocessing.'''} , ) UpperCamelCase = field( default=0.15 , metadata={'''help''': '''Ratio of tokens to mask for masked language modeling loss'''} ) UpperCamelCase = field( default=snake_case_ , metadata={ '''help''': ( '''Whether to pad all samples to `max_seq_length`. ''' '''If False, will pad the samples dynamically when batching to the maximum length in the batch.''' ) } , ) def snake_case_( self ) -> Optional[int]: if self.train_file is not None: _SCREAMING_SNAKE_CASE = self.train_file.split(""".""" )[-1] assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, a json or a txt file." if self.validation_file is not None: _SCREAMING_SNAKE_CASE = self.validation_file.split(""".""" )[-1] assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, a json or a txt file." def lowerCamelCase ( __lowerCamelCase : Dict , __lowerCamelCase : Optional[Any] ) ->Tuple: with open(__lowerCamelCase , """r""" , encoding="""utf-8""" ) as f: _SCREAMING_SNAKE_CASE = [json.loads(__lowerCamelCase ) for line in f.read().splitlines() if (len(__lowerCamelCase ) > 0 and not line.isspace())] assert len(__lowerCamelCase ) == len(__lowerCamelCase ) _SCREAMING_SNAKE_CASE = {c: dataset[c] for c in dataset.column_names} _SCREAMING_SNAKE_CASE = refs return Dataset.from_dict(__lowerCamelCase ) def lowerCamelCase ( ) ->Union[str, Any]: # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. _SCREAMING_SNAKE_CASE = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(""".json""" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = parser.parse_args_into_dataclasses() # Detecting last checkpoint. _SCREAMING_SNAKE_CASE = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _SCREAMING_SNAKE_CASE = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'Output directory ({training_args.output_dir}) already exists and is not empty. ' """Use --overwrite_output_dir to overcome.""" ) elif last_checkpoint is not None: logger.info( F'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ' """the `--output_dir` or add `--overwrite_output_dir` to train from scratch.""" ) # Setup logging logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""" , datefmt="""%m/%d/%Y %H:%M:%S""" , handlers=[logging.StreamHandler(sys.stdout )] , ) logger.setLevel(logging.INFO if is_main_process(training_args.local_rank ) else logging.WARN ) # Log on each process the small summary: logger.warning( F'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}' + F'distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}' ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info("""Training/evaluation parameters %s""" , __lowerCamelCase ) # Set seed before initializing model. set_seed(training_args.seed ) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.dataset_name is not None: # Downloading and loading a dataset from the hub. _SCREAMING_SNAKE_CASE = load_dataset(data_args.dataset_name , data_args.dataset_config_name ) if "validation" not in datasets.keys(): _SCREAMING_SNAKE_CASE = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F'train[:{data_args.validation_split_percentage}%]' , ) _SCREAMING_SNAKE_CASE = load_dataset( data_args.dataset_name , data_args.dataset_config_name , split=F'train[{data_args.validation_split_percentage}%:]' , ) else: _SCREAMING_SNAKE_CASE = {} if data_args.train_file is not None: _SCREAMING_SNAKE_CASE = data_args.train_file if data_args.validation_file is not None: _SCREAMING_SNAKE_CASE = data_args.validation_file _SCREAMING_SNAKE_CASE = data_args.train_file.split(""".""" )[-1] if extension == "txt": _SCREAMING_SNAKE_CASE = """text""" _SCREAMING_SNAKE_CASE = load_dataset(__lowerCamelCase , data_files=__lowerCamelCase ) # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _SCREAMING_SNAKE_CASE = { """cache_dir""": model_args.cache_dir, """revision""": model_args.model_revision, """use_auth_token""": True if model_args.use_auth_token else None, } if model_args.config_name: _SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(model_args.config_name , **__lowerCamelCase ) elif model_args.model_name_or_path: _SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(model_args.model_name_or_path , **__lowerCamelCase ) else: _SCREAMING_SNAKE_CASE = CONFIG_MAPPING[model_args.model_type]() logger.warning("""You are instantiating a new config instance from scratch.""" ) if model_args.config_overrides is not None: logger.info(F'Overriding config: {model_args.config_overrides}' ) config.update_from_string(model_args.config_overrides ) logger.info(F'New config: {config}' ) _SCREAMING_SNAKE_CASE = { """cache_dir""": model_args.cache_dir, """use_fast""": model_args.use_fast_tokenizer, """revision""": model_args.model_revision, """use_auth_token""": True if model_args.use_auth_token else None, } if model_args.tokenizer_name: _SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(model_args.tokenizer_name , **__lowerCamelCase ) elif model_args.model_name_or_path: _SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(model_args.model_name_or_path , **__lowerCamelCase ) else: raise ValueError( """You are instantiating a new tokenizer from scratch. This is not supported by this script.""" """You can do it from another script, save it, and load it from here, using --tokenizer_name.""" ) if model_args.model_name_or_path: _SCREAMING_SNAKE_CASE = AutoModelForMaskedLM.from_pretrained( model_args.model_name_or_path , from_tf=bool(""".ckpt""" in model_args.model_name_or_path ) , config=__lowerCamelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("""Training new model from scratch""" ) _SCREAMING_SNAKE_CASE = AutoModelForMaskedLM.from_config(__lowerCamelCase ) model.resize_token_embeddings(len(__lowerCamelCase ) ) # Preprocessing the datasets. # First we tokenize all the texts. if training_args.do_train: _SCREAMING_SNAKE_CASE = datasets["""train"""].column_names else: _SCREAMING_SNAKE_CASE = datasets["""validation"""].column_names _SCREAMING_SNAKE_CASE = """text""" if """text""" in column_names else column_names[0] _SCREAMING_SNAKE_CASE = """max_length""" if data_args.pad_to_max_length else False def tokenize_function(__lowerCamelCase : List[str] ): # Remove empty lines _SCREAMING_SNAKE_CASE = [line for line in examples["""text"""] if len(__lowerCamelCase ) > 0 and not line.isspace()] return tokenizer(examples["""text"""] , padding=__lowerCamelCase , truncation=__lowerCamelCase , max_length=data_args.max_seq_length ) _SCREAMING_SNAKE_CASE = datasets.map( __lowerCamelCase , batched=__lowerCamelCase , num_proc=data_args.preprocessing_num_workers , remove_columns=[text_column_name] , load_from_cache_file=not data_args.overwrite_cache , ) # Add the chinese references if provided if data_args.train_ref_file is not None: _SCREAMING_SNAKE_CASE = add_chinese_references(tokenized_datasets["""train"""] , data_args.train_ref_file ) if data_args.validation_ref_file is not None: _SCREAMING_SNAKE_CASE = add_chinese_references( tokenized_datasets["""validation"""] , data_args.validation_ref_file ) # If we have ref files, need to avoid it removed by trainer _SCREAMING_SNAKE_CASE = data_args.train_ref_file or data_args.validation_ref_file if has_ref: _SCREAMING_SNAKE_CASE = False # Data collator # This one will take care of randomly masking the tokens. _SCREAMING_SNAKE_CASE = DataCollatorForWholeWordMask(tokenizer=__lowerCamelCase , mlm_probability=data_args.mlm_probability ) # Initialize our Trainer _SCREAMING_SNAKE_CASE = Trainer( model=__lowerCamelCase , args=__lowerCamelCase , train_dataset=tokenized_datasets["""train"""] if training_args.do_train else None , eval_dataset=tokenized_datasets["""validation"""] if training_args.do_eval else None , tokenizer=__lowerCamelCase , data_collator=__lowerCamelCase , ) # Training if training_args.do_train: if last_checkpoint is not None: _SCREAMING_SNAKE_CASE = last_checkpoint elif model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path ): _SCREAMING_SNAKE_CASE = model_args.model_name_or_path else: _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = trainer.train(resume_from_checkpoint=__lowerCamelCase ) trainer.save_model() # Saves the tokenizer too for easy upload _SCREAMING_SNAKE_CASE = os.path.join(training_args.output_dir , """train_results.txt""" ) if trainer.is_world_process_zero(): with open(__lowerCamelCase , """w""" ) as writer: logger.info("""***** Train results *****""" ) for key, value in sorted(train_result.metrics.items() ): logger.info(F' {key} = {value}' ) writer.write(F'{key} = {value}\n' ) # Need to save the state, since Trainer.save_model saves only the tokenizer with the model trainer.state.save_to_json(os.path.join(training_args.output_dir , """trainer_state.json""" ) ) # Evaluation _SCREAMING_SNAKE_CASE = {} if training_args.do_eval: logger.info("""*** Evaluate ***""" ) _SCREAMING_SNAKE_CASE = trainer.evaluate() _SCREAMING_SNAKE_CASE = math.exp(eval_output["""eval_loss"""] ) _SCREAMING_SNAKE_CASE = perplexity _SCREAMING_SNAKE_CASE = os.path.join(training_args.output_dir , """eval_results_mlm_wwm.txt""" ) if trainer.is_world_process_zero(): with open(__lowerCamelCase , """w""" ) as writer: logger.info("""***** Eval results *****""" ) for key, value in sorted(results.items() ): logger.info(F' {key} = {value}' ) writer.write(F'{key} = {value}\n' ) return results def lowerCamelCase ( __lowerCamelCase : List[str] ) ->Union[str, Any]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
58
'''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 __lowerCAmelCase = logging.getLogger() @unittest.skip('Temporarily disable the doc tests.' ) @require_torch @require_tf @slow class __magic_name__ ( unittest.TestCase ): def __lowercase ( self : str ,_UpperCAmelCase : Path ,_UpperCAmelCase : Union[str, None] = None ,_UpperCAmelCase : Union[List[str], None] = None ,_UpperCAmelCase : Union[str, List[str], None] = None ,_UpperCAmelCase : bool = True ,): _a : Dict = [file for file in os.listdir(_UpperCAmelCase ) if os.path.isfile(os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) )] if identifier is not None: _a : str = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): for n_ in n_identifier: _a : int = [file for file in files if n_ not in file] else: _a : Optional[Any] = [file for file in files if n_identifier not in file] _a : Dict = ignore_files or [] ignore_files.append('__init__.py' ) _a : List[str] = [file for file in files if file not in ignore_files] for file in files: # Open all files print('Testing' ,_UpperCAmelCase ) if only_modules: _a : Any = file.split('.' )[0] try: _a : Optional[int] = getattr(_UpperCAmelCase ,_UpperCAmelCase ) _a : Dict = doctest.DocTestSuite(_UpperCAmelCase ) _a : Optional[int] = unittest.TextTestRunner().run(_UpperCAmelCase ) self.assertIs(len(result.failures ) ,0 ) except AttributeError: logger.info(F"""{module_identifier} is not a module.""" ) else: _a : str = doctest.testfile(str('..' / directory / file ) ,optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed ,0 ) def __lowercase ( self : Union[str, Any] ): _a : Optional[Any] = Path('src/transformers' ) _a : Optional[Any] = 'modeling' _a : Union[str, Any] = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(_UpperCAmelCase ,identifier=_UpperCAmelCase ,ignore_files=_UpperCAmelCase ) def __lowercase ( self : int ): _a : str = Path('src/transformers' ) _a : List[str] = 'tokenization' self.analyze_directory(_UpperCAmelCase ,identifier=_UpperCAmelCase ) def __lowercase ( self : int ): _a : Any = Path('src/transformers' ) _a : str = 'configuration' self.analyze_directory(_UpperCAmelCase ,identifier=_UpperCAmelCase ) def __lowercase ( self : Dict ): _a : Tuple = Path('src/transformers' ) _a : Optional[int] = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(_UpperCAmelCase ,n_identifier=_UpperCAmelCase ) def __lowercase ( self : Optional[Any] ): _a : Union[str, Any] = Path('docs/source' ) _a : List[str] = ['favicon.ico'] self.analyze_directory(_UpperCAmelCase ,ignore_files=_UpperCAmelCase ,only_modules=_UpperCAmelCase )
89
0
import argparse import logging import os import datasets import tensorflow as tf from transformers import AutoTokenizer __lowerCamelCase = logging.getLogger(__name__) def UpperCamelCase ( ): snake_case : Tuple = argparse.ArgumentParser( description="Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset." ) parser.add_argument( "--dataset_name" , type=__lowerCamelCase , default="wikitext" , help="Name of the training. Explore datasets at: hf.co/datasets." , ) parser.add_argument( "--dataset_config" , type=__lowerCamelCase , default="wikitext-103-raw-v1" , help="Configuration name of the dataset." ) parser.add_argument( "--tokenizer_name_or_path" , type=__lowerCamelCase , default="sayakpaul/unigram-tokenizer-wikitext" , help="Tokenizer identifier. Can be a local filepath or a Hub identifier." , ) parser.add_argument( "--shard_size" , type=__lowerCamelCase , default=1000 , help="Number of entries to go in a single shard." , ) parser.add_argument("--split" , type=__lowerCamelCase , default="train" , choices=["train", "test", "validation"] ) parser.add_argument( "--limit" , default=__lowerCamelCase , type=__lowerCamelCase , help="Limit the number of shards (used for debugging)." , ) parser.add_argument( "--max_length" , type=__lowerCamelCase , default=512 , 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=__lowerCamelCase , 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." , ) snake_case : Dict = parser.parse_args() return args def UpperCamelCase ( __lowerCamelCase : Union[str, Any] ): def fn(__lowerCamelCase : Union[str, Any] ): return tokenizer(examples["text"] ) return fn def UpperCamelCase ( __lowerCamelCase : Optional[int] ): snake_case : Optional[int] = [] for i in range(len(tokenized_data["input_ids"] ) ): snake_case : str = { "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] ) ), } snake_case : Optional[int] = tf.train.Features(feature=__lowerCamelCase ) snake_case : List[str] = tf.train.Example(features=__lowerCamelCase ) snake_case : Union[str, Any] = example.SerializeToString() records.append(__lowerCamelCase ) return records def UpperCamelCase ( __lowerCamelCase : List[Any] ): snake_case : Any = datasets.load_dataset(args.dataset_name , args.dataset_config , split=args.split ) if args.limit is not None: snake_case : Optional[Any] = min(len(__lowerCamelCase ) , args.limit ) snake_case : Tuple = dataset.select(range(__lowerCamelCase ) ) print(f"""Limiting the dataset to {args.limit} entries.""" ) snake_case : Tuple = 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 ) snake_case : List[Any] = os.path.join(args.output_dir , args.split ) if not os.path.exists(__lowerCamelCase ): os.makedirs(__lowerCamelCase ) else: snake_case : Tuple = os.path.join(args.output_dir , args.split ) # Tokenize the whole dataset at once. snake_case : Any = tokenize_function(__lowerCamelCase ) snake_case : Optional[Any] = dataset.map(__lowerCamelCase , batched=__lowerCamelCase , 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(__lowerCamelCase : List[str] ): # Concatenate all texts. snake_case : Optional[Any] = {k: sum(examples[k] , [] ) for k in examples.keys()} snake_case : str = 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 🫀 snake_case : Any = (total_length // args.max_length) * args.max_length # Split by chunks of max_len. snake_case : Union[str, Any] = { k: [t[i : i + args.max_length] for i in range(0 , __lowerCamelCase , args.max_length )] for k, t in concatenated_examples.items() } return result snake_case : Any = dataset_tokenized.map(__lowerCamelCase , batched=__lowerCamelCase , batch_size=1000 , num_proc=4 ) snake_case : Dict = 0 snake_case : Optional[int] = 0 for shard in range(0 , len(__lowerCamelCase ) , args.shard_size ): snake_case : int = grouped_dataset[shard : shard + args.shard_size] snake_case : Any = len(dataset_snapshot["input_ids"] ) snake_case : List[Any] = os.path.join(__lowerCamelCase , f"""dataset-{shard_count}-{records_containing}.tfrecord""" ) snake_case : Tuple = get_serialized_examples(__lowerCamelCase ) with tf.io.TFRecordWriter(__lowerCamelCase ) as out_file: for i in range(len(__lowerCamelCase ) ): snake_case : Dict = serialized_examples[i] out_file.write(__lowerCamelCase ) print("Wrote file {} containing {} records".format(__lowerCamelCase , __lowerCamelCase ) ) 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=__lowerCamelCase ) if __name__ == "__main__": __lowerCamelCase = parse_args() main(args)
59
'''simple docstring''' import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_processing_utils import ImageProcessingMixin from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = OrderedDict( [ ('''align''', '''EfficientNetImageProcessor'''), ('''beit''', '''BeitImageProcessor'''), ('''bit''', '''BitImageProcessor'''), ('''blip''', '''BlipImageProcessor'''), ('''blip-2''', '''BlipImageProcessor'''), ('''bridgetower''', '''BridgeTowerImageProcessor'''), ('''chinese_clip''', '''ChineseCLIPImageProcessor'''), ('''clip''', '''CLIPImageProcessor'''), ('''clipseg''', '''ViTImageProcessor'''), ('''conditional_detr''', '''ConditionalDetrImageProcessor'''), ('''convnext''', '''ConvNextImageProcessor'''), ('''convnextv2''', '''ConvNextImageProcessor'''), ('''cvt''', '''ConvNextImageProcessor'''), ('''data2vec-vision''', '''BeitImageProcessor'''), ('''deformable_detr''', '''DeformableDetrImageProcessor'''), ('''deit''', '''DeiTImageProcessor'''), ('''deta''', '''DetaImageProcessor'''), ('''detr''', '''DetrImageProcessor'''), ('''dinat''', '''ViTImageProcessor'''), ('''donut-swin''', '''DonutImageProcessor'''), ('''dpt''', '''DPTImageProcessor'''), ('''efficientformer''', '''EfficientFormerImageProcessor'''), ('''efficientnet''', '''EfficientNetImageProcessor'''), ('''flava''', '''FlavaImageProcessor'''), ('''focalnet''', '''BitImageProcessor'''), ('''git''', '''CLIPImageProcessor'''), ('''glpn''', '''GLPNImageProcessor'''), ('''groupvit''', '''CLIPImageProcessor'''), ('''imagegpt''', '''ImageGPTImageProcessor'''), ('''instructblip''', '''BlipImageProcessor'''), ('''layoutlmv2''', '''LayoutLMv2ImageProcessor'''), ('''layoutlmv3''', '''LayoutLMv3ImageProcessor'''), ('''levit''', '''LevitImageProcessor'''), ('''mask2former''', '''Mask2FormerImageProcessor'''), ('''maskformer''', '''MaskFormerImageProcessor'''), ('''mgp-str''', '''ViTImageProcessor'''), ('''mobilenet_v1''', '''MobileNetV1ImageProcessor'''), ('''mobilenet_v2''', '''MobileNetV2ImageProcessor'''), ('''mobilevit''', '''MobileViTImageProcessor'''), ('''mobilevit''', '''MobileViTImageProcessor'''), ('''mobilevitv2''', '''MobileViTImageProcessor'''), ('''nat''', '''ViTImageProcessor'''), ('''oneformer''', '''OneFormerImageProcessor'''), ('''owlvit''', '''OwlViTImageProcessor'''), ('''perceiver''', '''PerceiverImageProcessor'''), ('''pix2struct''', '''Pix2StructImageProcessor'''), ('''poolformer''', '''PoolFormerImageProcessor'''), ('''regnet''', '''ConvNextImageProcessor'''), ('''resnet''', '''ConvNextImageProcessor'''), ('''sam''', '''SamImageProcessor'''), ('''segformer''', '''SegformerImageProcessor'''), ('''swiftformer''', '''ViTImageProcessor'''), ('''swin''', '''ViTImageProcessor'''), ('''swin2sr''', '''Swin2SRImageProcessor'''), ('''swinv2''', '''ViTImageProcessor'''), ('''table-transformer''', '''DetrImageProcessor'''), ('''timesformer''', '''VideoMAEImageProcessor'''), ('''tvlt''', '''TvltImageProcessor'''), ('''upernet''', '''SegformerImageProcessor'''), ('''van''', '''ConvNextImageProcessor'''), ('''videomae''', '''VideoMAEImageProcessor'''), ('''vilt''', '''ViltImageProcessor'''), ('''vit''', '''ViTImageProcessor'''), ('''vit_hybrid''', '''ViTHybridImageProcessor'''), ('''vit_mae''', '''ViTImageProcessor'''), ('''vit_msn''', '''ViTImageProcessor'''), ('''xclip''', '''CLIPImageProcessor'''), ('''yolos''', '''YolosImageProcessor'''), ] ) __lowerCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def __lowerCamelCase ( lowerCAmelCase_ ) -> Optional[Any]: for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: _a : List[Any] = model_type_to_module_name(lowerCAmelCase_ ) _a : Optional[Any] = importlib.import_module(f""".{module_name}""" , 'transformers.models' ) try: return getattr(lowerCAmelCase_ , lowerCAmelCase_ ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(lowerCAmelCase_ , '__name__' , lowerCAmelCase_ ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. _a : Dict = importlib.import_module('transformers' ) if hasattr(lowerCAmelCase_ , lowerCAmelCase_ ): return getattr(lowerCAmelCase_ , lowerCAmelCase_ ) return None def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = False , lowerCAmelCase_ = False , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = False , **lowerCAmelCase_ , ) -> Tuple: _a : List[str] = get_file_from_repo( lowerCAmelCase_ , lowerCAmelCase_ , cache_dir=lowerCAmelCase_ , force_download=lowerCAmelCase_ , resume_download=lowerCAmelCase_ , proxies=lowerCAmelCase_ , use_auth_token=lowerCAmelCase_ , revision=lowerCAmelCase_ , local_files_only=lowerCAmelCase_ , ) if resolved_config_file is None: logger.info( 'Could not locate the image processor configuration file, will try to use the model config instead.' ) return {} with open(lowerCAmelCase_ , encoding='utf-8' ) as reader: return json.load(lowerCAmelCase_ ) class __magic_name__ : def __init__( self : List[str] ): raise EnvironmentError( 'AutoImageProcessor is designed to be instantiated ' 'using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.' ) @classmethod @replace_list_option_in_docstrings(_UpperCAmelCase ) def __lowercase ( cls : Dict ,_UpperCAmelCase : Union[str, Any] ,**_UpperCAmelCase : Optional[Any] ): _a : Any = kwargs.pop('config' ,_UpperCAmelCase ) _a : Dict = kwargs.pop('trust_remote_code' ,_UpperCAmelCase ) _a : Any = True _a , _a : Tuple = ImageProcessingMixin.get_image_processor_dict(_UpperCAmelCase ,**_UpperCAmelCase ) _a : List[Any] = config_dict.get('image_processor_type' ,_UpperCAmelCase ) _a : int = None if "AutoImageProcessor" in config_dict.get('auto_map' ,{} ): _a : Any = config_dict['auto_map']['AutoImageProcessor'] # If we still don't have the image processor class, check if we're loading from a previous feature extractor config # and if so, infer the image processor class from there. if image_processor_class is None and image_processor_auto_map is None: _a : List[Any] = config_dict.pop('feature_extractor_type' ,_UpperCAmelCase ) if feature_extractor_class is not None: logger.warning( 'Could not find image processor class in the image processor config or the model config. Loading' ' based on pattern matching with the model\'s feature extractor configuration.' ) _a : Optional[int] = feature_extractor_class.replace('FeatureExtractor' ,'ImageProcessor' ) if "AutoFeatureExtractor" in config_dict.get('auto_map' ,{} ): _a : List[Any] = config_dict['auto_map']['AutoFeatureExtractor'] _a : List[str] = feature_extractor_auto_map.replace('FeatureExtractor' ,'ImageProcessor' ) logger.warning( 'Could not find image processor auto map in the image processor config or the model config.' ' Loading based on pattern matching with the model\'s feature extractor configuration.' ) # If we don't find the image processor class in the image processor config, let's try the model config. if image_processor_class is None and image_processor_auto_map is None: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : Dict = AutoConfig.from_pretrained(_UpperCAmelCase ,**_UpperCAmelCase ) # It could be in `config.image_processor_type`` _a : Optional[int] = getattr(_UpperCAmelCase ,'image_processor_type' ,_UpperCAmelCase ) if hasattr(_UpperCAmelCase ,'auto_map' ) and "AutoImageProcessor" in config.auto_map: _a : Union[str, Any] = config.auto_map['AutoImageProcessor'] if image_processor_class is not None: _a : Optional[int] = image_processor_class_from_name(_UpperCAmelCase ) _a : List[str] = image_processor_auto_map is not None _a : Optional[int] = image_processor_class is not None or type(_UpperCAmelCase ) in IMAGE_PROCESSOR_MAPPING _a : Optional[int] = resolve_trust_remote_code( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) if has_remote_code and trust_remote_code: _a : Dict = get_class_from_dynamic_module( _UpperCAmelCase ,_UpperCAmelCase ,**_UpperCAmelCase ) _a : int = kwargs.pop('code_revision' ,_UpperCAmelCase ) if os.path.isdir(_UpperCAmelCase ): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(_UpperCAmelCase ,**_UpperCAmelCase ) elif image_processor_class is not None: return image_processor_class.from_dict(_UpperCAmelCase ,**_UpperCAmelCase ) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(_UpperCAmelCase ) in IMAGE_PROCESSOR_MAPPING: _a : Dict = IMAGE_PROCESSOR_MAPPING[type(_UpperCAmelCase )] return image_processor_class.from_dict(_UpperCAmelCase ,**_UpperCAmelCase ) raise ValueError( F"""Unrecognized image processor in {pretrained_model_name_or_path}. Should have a """ F"""`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following """ F"""`model_type` keys in its {CONFIG_NAME}: {', '.join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}""" ) @staticmethod def __lowercase ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Dict ): IMAGE_PROCESSOR_MAPPING.register(_UpperCAmelCase ,_UpperCAmelCase )
89
0
"""simple docstring""" from string import ascii_uppercase snake_case__ : List[Any] = {char: i for i, char in enumerate(ascii_uppercase)} snake_case__ : Optional[Any] = dict(enumerate(ascii_uppercase)) def _snake_case ( _snake_case : str , _snake_case : str ): lowerCAmelCase : Optional[Any] = len(_snake_case ) lowerCAmelCase : List[str] = 0 while True: if x == i: lowerCAmelCase : Dict = 0 if len(_snake_case ) == len(_snake_case ): break key += key[i] i += 1 return key def _snake_case ( _snake_case : str , _snake_case : str ): lowerCAmelCase : Union[str, Any] = '''''' lowerCAmelCase : List[str] = 0 for letter in message: if letter == " ": cipher_text += " " else: lowerCAmelCase : int = (dicta[letter] - dicta[key_new[i]]) % 26 i += 1 cipher_text += dicta[x] return cipher_text def _snake_case ( _snake_case : str , _snake_case : str ): lowerCAmelCase : Optional[int] = '''''' lowerCAmelCase : str = 0 for letter in cipher_text: if letter == " ": or_txt += " " else: lowerCAmelCase : Optional[Any] = (dicta[letter] + dicta[key_new[i]] + 26) % 26 i += 1 or_txt += dicta[x] return or_txt def _snake_case ( ): lowerCAmelCase : List[Any] = '''THE GERMAN ATTACK''' lowerCAmelCase : Any = '''SECRET''' lowerCAmelCase : Union[str, Any] = generate_key(_snake_case , _snake_case ) lowerCAmelCase : str = cipher_text(_snake_case , _snake_case ) print(f'''Encrypted Text = {s}''' ) print(f'''Original Text = {original_text(_snake_case , _snake_case )}''' ) if __name__ == "__main__": import doctest doctest.testmod() main()
60
'''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 __lowerCAmelCase = None __lowerCAmelCase = '''<''' 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 __lowerCAmelCase = [ 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 __magic_name__ : lowerCAmelCase : bool = True lowerCAmelCase : Optional[str] = None # Automatically constructed lowerCAmelCase : ClassVar[str] = "PIL.Image.Image" lowerCAmelCase : ClassVar[Any] = pa.struct({'bytes': pa.binary(), 'path': pa.string()} ) lowerCAmelCase : str = field(default='Image' , init=_UpperCamelCase , repr=_UpperCamelCase ) def __call__( self : Union[str, Any] ): return self.pa_type def __lowercase ( self : Any ,_UpperCAmelCase : Union[str, bytes, dict, np.ndarray, "PIL.Image.Image"] ): if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support encoding images, please install \'Pillow\'.' ) if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : Optional[Any] = np.array(_UpperCAmelCase ) if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): return {"path": value, "bytes": None} elif isinstance(_UpperCAmelCase ,_UpperCAmelCase ): return {"path": None, "bytes": value} elif isinstance(_UpperCAmelCase ,np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(_UpperCAmelCase ) 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 __lowercase ( self : Optional[Any] ,_UpperCAmelCase : dict ,_UpperCAmelCase : Optional[int]=None ): 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 : Dict = {} _a , _a : str = 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(_UpperCAmelCase ): _a : Any = PIL.Image.open(_UpperCAmelCase ) else: _a : List[Any] = path.split('::' )[-1] try: _a : str = string_to_dict(_UpperCAmelCase ,config.HUB_DATASETS_URL )['repo_id'] _a : Optional[Any] = token_per_repo_id.get(_UpperCAmelCase ) except ValueError: _a : int = None with xopen(_UpperCAmelCase ,'rb' ,use_auth_token=_UpperCAmelCase ) as f: _a : Tuple = BytesIO(f.read() ) _a : Union[str, Any] = PIL.Image.open(bytes_ ) else: _a : Optional[int] = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def __lowercase ( self : int ): from .features import Value return ( self if self.decode else { "bytes": Value('binary' ), "path": Value('string' ), } ) def __lowercase ( self : str ,_UpperCAmelCase : Union[pa.StringArray, pa.StructArray, pa.ListArray] ): if pa.types.is_string(storage.type ): _a : Union[str, Any] = pa.array([None] * len(_UpperCAmelCase ) ,type=pa.binary() ) _a : Union[str, 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(_UpperCAmelCase ) ,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 : Tuple = pa.array([None] * len(_UpperCAmelCase ) ,type=pa.binary() ) if storage.type.get_field_index('path' ) >= 0: _a : Union[str, Any] = storage.field('path' ) else: _a : Dict = pa.array([None] * len(_UpperCAmelCase ) ,type=pa.string() ) _a : Optional[Any] = pa.StructArray.from_arrays([bytes_array, path_array] ,['bytes', 'path'] ,mask=storage.is_null() ) elif pa.types.is_list(storage.type ): _a : List[str] = pa.array( [encode_np_array(np.array(_UpperCAmelCase ) )['bytes'] if arr is not None else None for arr in storage.to_pylist()] ,type=pa.binary() ,) _a : int = pa.array([None] * len(_UpperCAmelCase ) ,type=pa.string() ) _a : Optional[Any] = pa.StructArray.from_arrays( [bytes_array, path_array] ,['bytes', 'path'] ,mask=bytes_array.is_null() ) return array_cast(_UpperCAmelCase ,self.pa_type ) def __lowercase ( self : Dict ,_UpperCAmelCase : pa.StructArray ): @no_op_if_value_is_null def path_to_bytes(_UpperCAmelCase : Tuple ): with xopen(_UpperCAmelCase ,'rb' ) as f: _a : int = f.read() return bytes_ _a : Any = 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 : Optional[Any] = pa.array( [os.path.basename(_UpperCAmelCase ) if path is not None else None for path in storage.field('path' ).to_pylist()] ,type=pa.string() ,) _a : Dict = pa.StructArray.from_arrays([bytes_array, path_array] ,['bytes', 'path'] ,mask=bytes_array.is_null() ) return array_cast(_UpperCAmelCase ,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 ( lowerCAmelCase_ ) -> bytes: _a : Optional[int] = BytesIO() if image.format in list_image_compression_formats(): _a : Optional[Any] = image.format else: _a : str = 'PNG' if image.mode in ['1', 'L', 'LA', 'RGB', 'RGBA'] else 'TIFF' image.save(lowerCAmelCase_ , format=lowerCAmelCase_ ) return buffer.getvalue() def __lowerCamelCase ( lowerCAmelCase_ ) -> dict: if hasattr(lowerCAmelCase_ , 'filename' ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(lowerCAmelCase_ )} def __lowerCamelCase ( lowerCAmelCase_ ) -> dict: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support encoding images, please install \'Pillow\'.' ) _a : List[Any] = array.dtype _a : Optional[int] = dtype.byteorder if dtype.byteorder != '=' else _NATIVE_BYTEORDER _a : Union[str, Any] = dtype.kind _a : Union[str, Any] = dtype.itemsize _a : List[Any] = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: _a : Optional[int] = 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 : Union[str, 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 : str = dtype_byteorder + dtype_kind + str(lowerCAmelCase_ ) _a : List[Any] = np.dtype(lowerCAmelCase_ ) 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(lowerCAmelCase_ ) ) return {"path": None, "bytes": image_to_bytes(lowerCAmelCase_ )} def __lowerCamelCase ( lowerCAmelCase_ ) -> List[dict]: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support encoding images, please install \'Pillow\'.' ) if objs: _a , _a : Optional[Any] = first_non_null_value(lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(lowerCAmelCase_ , np.ndarray ): _a : List[str] = no_op_if_value_is_null(lowerCAmelCase_ ) return [obj_to_image_dict_func(lowerCAmelCase_ ) for obj in objs] elif isinstance(lowerCAmelCase_ , PIL.Image.Image ): _a : List[str] = no_op_if_value_is_null(lowerCAmelCase_ ) return [obj_to_image_dict_func(lowerCAmelCase_ ) for obj in objs] else: return objs else: return objs
89
0
"""simple docstring""" import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def __a ( __lowerCamelCase ): UpperCAmelCase_ : Union[str, Any] = args.pruning_method UpperCAmelCase_ : int = args.threshold UpperCAmelCase_ : Optional[int] = args.model_name_or_path.rstrip("/" ) UpperCAmelCase_ : List[str] = args.target_model_path print(f"""Load fine-pruned model from {model_name_or_path}""" ) UpperCAmelCase_ : Tuple = torch.load(os.path.join(__lowerCamelCase, "pytorch_model.bin" ) ) UpperCAmelCase_ : Tuple = {} for name, tensor in model.items(): if "embeddings" in name or "LayerNorm" in name or "pooler" in name: UpperCAmelCase_ : Optional[Any] = tensor print(f"""Copied layer {name}""" ) elif "classifier" in name or "qa_output" in name: UpperCAmelCase_ : Optional[Any] = tensor print(f"""Copied layer {name}""" ) elif "bias" in name: UpperCAmelCase_ : Optional[int] = tensor print(f"""Copied layer {name}""" ) else: if pruning_method == "magnitude": UpperCAmelCase_ : str = MagnitudeBinarizer.apply(inputs=__lowerCamelCase, threshold=__lowerCamelCase ) UpperCAmelCase_ : Optional[int] = tensor * mask print(f"""Pruned layer {name}""" ) elif pruning_method == "topK": if "mask_scores" in name: continue UpperCAmelCase_ : Optional[Any] = name[:-6] UpperCAmelCase_ : int = model[f"""{prefix_}mask_scores"""] UpperCAmelCase_ : List[Any] = TopKBinarizer.apply(__lowerCamelCase, __lowerCamelCase ) UpperCAmelCase_ : int = tensor * mask print(f"""Pruned layer {name}""" ) elif pruning_method == "sigmoied_threshold": if "mask_scores" in name: continue UpperCAmelCase_ : Tuple = name[:-6] UpperCAmelCase_ : Optional[Any] = model[f"""{prefix_}mask_scores"""] UpperCAmelCase_ : Any = ThresholdBinarizer.apply(__lowerCamelCase, __lowerCamelCase, __lowerCamelCase ) UpperCAmelCase_ : Tuple = tensor * mask print(f"""Pruned layer {name}""" ) elif pruning_method == "l0": if "mask_scores" in name: continue UpperCAmelCase_ : Optional[int] = name[:-6] UpperCAmelCase_ : List[str] = model[f"""{prefix_}mask_scores"""] UpperCAmelCase_ , UpperCAmelCase_ : int = -0.1, 1.1 UpperCAmelCase_ : str = torch.sigmoid(__lowerCamelCase ) UpperCAmelCase_ : Optional[Any] = s * (r - l) + l UpperCAmelCase_ : Any = s_bar.clamp(min=0.0, max=1.0 ) UpperCAmelCase_ : Optional[Any] = tensor * mask print(f"""Pruned layer {name}""" ) else: raise ValueError("Unknown pruning method" ) if target_model_path is None: UpperCAmelCase_ : int = os.path.join( os.path.dirname(__lowerCamelCase ), f"""bertarized_{os.path.basename(__lowerCamelCase )}""" ) if not os.path.isdir(__lowerCamelCase ): shutil.copytree(__lowerCamelCase, __lowerCamelCase ) print(f"""\nCreated folder {target_model_path}""" ) torch.save(__lowerCamelCase, os.path.join(__lowerCamelCase, "pytorch_model.bin" ) ) print("\nPruned model saved! See you later!" ) if __name__ == "__main__": _a = argparse.ArgumentParser() parser.add_argument( '--pruning_method', choices=['l0', 'magnitude', 'topK', 'sigmoied_threshold'], type=str, required=True, help=( 'Pruning Method (l0 = L0 regularization, magnitude = Magnitude pruning, topK = Movement pruning,' ' sigmoied_threshold = Soft movement pruning)' ), ) parser.add_argument( '--threshold', type=float, required=False, help=( 'For `magnitude` and `topK`, it is the level of remaining weights (in %) in the fine-pruned model.' 'For `sigmoied_threshold`, it is the threshold \tau against which the (sigmoied) scores are compared.' 'Not needed for `l0`' ), ) parser.add_argument( '--model_name_or_path', type=str, required=True, help='Folder containing the model that was previously fine-pruned', ) parser.add_argument( '--target_model_path', default=None, type=str, required=False, help='Folder containing the model that was previously fine-pruned', ) _a = parser.parse_args() main(args)
61
'''simple docstring''' from __future__ import annotations from collections.abc import Sequence from typing import Literal def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> str | Literal[False]: _a : Optional[int] = list(lowerCAmelCase_ ) _a : Optional[Any] = list(lowerCAmelCase_ ) _a : Union[str, Any] = 0 for i in range(len(lowerCAmelCase_ ) ): if lista[i] != lista[i]: count += 1 _a : Optional[int] = '_' if count > 1: return False else: return "".join(lowerCAmelCase_ ) def __lowerCamelCase ( lowerCAmelCase_ ) -> list[str]: _a : Optional[int] = [] while True: _a : Any = ['$'] * len(lowerCAmelCase_ ) _a : List[str] = [] for i in range(len(lowerCAmelCase_ ) ): for j in range(i + 1 , len(lowerCAmelCase_ ) ): _a : Optional[int] = compare_string(binary[i] , binary[j] ) if k is False: _a : Optional[Any] = '*' _a : Optional[Any] = '*' temp.append('X' ) for i in range(len(lowerCAmelCase_ ) ): if checka[i] == "$": pi.append(binary[i] ) if len(lowerCAmelCase_ ) == 0: return pi _a : Any = list(set(lowerCAmelCase_ ) ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> list[str]: _a : int = [] for minterm in minterms: _a : Optional[int] = '' for _ in range(lowerCAmelCase_ ): _a : Union[str, Any] = str(minterm % 2 ) + string minterm //= 2 temp.append(lowerCAmelCase_ ) return temp def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> bool: _a : int = list(lowerCAmelCase_ ) _a : Union[str, Any] = list(lowerCAmelCase_ ) _a : str = 0 for i in range(len(lowerCAmelCase_ ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> list[str]: _a : List[Any] = [] _a : Optional[Any] = [0] * len(lowerCAmelCase_ ) for i in range(len(chart[0] ) ): _a : Union[str, Any] = 0 _a : int = -1 for j in range(len(lowerCAmelCase_ ) ): if chart[j][i] == 1: count += 1 _a : int = j if count == 1: _a : List[Any] = 1 for i in range(len(lowerCAmelCase_ ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(lowerCAmelCase_ ) ): _a : Any = 0 temp.append(prime_implicants[i] ) while True: _a : Union[str, Any] = 0 _a : List[Any] = -1 _a : str = 0 for i in range(len(lowerCAmelCase_ ) ): _a : Union[str, Any] = chart[i].count(1 ) if count_n > max_n: _a : Any = count_n _a : int = i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(lowerCAmelCase_ ) ): _a : List[str] = 0 def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> list[list[int]]: _a : int = [[0 for x in range(len(lowerCAmelCase_ ) )] for x in range(len(lowerCAmelCase_ ) )] for i in range(len(lowerCAmelCase_ ) ): _a : str = prime_implicants[i].count('_' ) for j in range(len(lowerCAmelCase_ ) ): if is_for_table(prime_implicants[i] , binary[j] , lowerCAmelCase_ ): _a : Optional[Any] = 1 return chart def __lowerCamelCase ( ) -> None: _a : Optional[int] = int(input('Enter the no. of variables\n' ) ) _a : List[Any] = [ float(lowerCAmelCase_ ) for x in input( 'Enter the decimal representation of Minterms \'Spaces Separated\'\n' ).split() ] _a : List[str] = decimal_to_binary(lowerCAmelCase_ , lowerCAmelCase_ ) _a : Dict = check(lowerCAmelCase_ ) print('Prime Implicants are:' ) print(lowerCAmelCase_ ) _a : List[Any] = prime_implicant_chart(lowerCAmelCase_ , lowerCAmelCase_ ) _a : int = selection(lowerCAmelCase_ , lowerCAmelCase_ ) print('Essential Prime Implicants are:' ) print(lowerCAmelCase_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
89
0
import json import os import tempfile import datasets from utils import generate_example_dataset, get_duration _A = 5_0000 _A = 5000 _A , _A = os.path.split(__file__) _A = os.path.join(RESULTS_BASEPATH, 'results', RESULTS_FILENAME.replace('.py', '.json')) @get_duration def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : datasets.Dataset , SCREAMING_SNAKE_CASE__ : Any ): for i in range(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =dataset[i] @get_duration def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : datasets.Dataset , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : List[str] ): for i in range(0 , len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =dataset[i : i + batch_size] @get_duration def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : datasets.Dataset , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any ): with dataset.formatted_as(type=SCREAMING_SNAKE_CASE__ ): for i in range(SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =dataset[i] @get_duration def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : datasets.Dataset , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Dict ): with dataset.formatted_as(type=SCREAMING_SNAKE_CASE__ ): for i in range(0 , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __UpperCamelCase =dataset[i : i + batch_size] def _UpperCAmelCase ( ): __UpperCamelCase ={'num examples': SPEED_TEST_N_EXAMPLES} __UpperCamelCase =[ (read, {'length': SMALL_TEST}), (read, {'length': SPEED_TEST_N_EXAMPLES}), (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 10}), (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 1_00}), (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 10_00}), (read_formatted, {'type': 'numpy', 'length': SMALL_TEST}), (read_formatted, {'type': 'pandas', 'length': SMALL_TEST}), (read_formatted, {'type': 'torch', 'length': SMALL_TEST}), (read_formatted, {'type': 'tensorflow', 'length': SMALL_TEST}), (read_formatted_batch, {'type': 'numpy', 'length': SMALL_TEST, 'batch_size': 10}), (read_formatted_batch, {'type': 'numpy', 'length': SMALL_TEST, 'batch_size': 10_00}), ] __UpperCamelCase =[ (read, {'length': SMALL_TEST}), (read, {'length': SPEED_TEST_N_EXAMPLES}), (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 10}), (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 1_00}), (read_batch, {'length': SPEED_TEST_N_EXAMPLES, 'batch_size': 10_00}), (read_formatted, {'type': 'numpy', 'length': SMALL_TEST}), (read_formatted_batch, {'type': 'numpy', 'length': SMALL_TEST, 'batch_size': 10}), (read_formatted_batch, {'type': 'numpy', 'length': SMALL_TEST, 'batch_size': 10_00}), ] with tempfile.TemporaryDirectory() as tmp_dir: print('generating dataset' ) __UpperCamelCase =datasets.Features( {'list': datasets.Sequence(datasets.Value('float32' ) ), 'numbers': datasets.Value('float32' )} ) __UpperCamelCase =generate_example_dataset( os.path.join(SCREAMING_SNAKE_CASE__ , 'dataset.arrow' ) , SCREAMING_SNAKE_CASE__ , num_examples=SCREAMING_SNAKE_CASE__ , seq_shapes={'list': (1_00,)} , ) print('first set of iterations' ) for func, kwargs in functions: print(func.__name__ , str(SCREAMING_SNAKE_CASE__ ) ) __UpperCamelCase =func(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) print('shuffling dataset' ) __UpperCamelCase =dataset.shuffle() print('Second set of iterations (after shuffling' ) for func, kwargs in functions_shuffled: print('shuffled ' , func.__name__ , str(SCREAMING_SNAKE_CASE__ ) ) __UpperCamelCase =func( SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) with open(SCREAMING_SNAKE_CASE__ , 'wb' ) as f: f.write(json.dumps(SCREAMING_SNAKE_CASE__ ).encode('utf-8' ) ) if __name__ == "__main__": # useful to run the profiler benchmark_iterating()
62
'''simple docstring''' # Copyright 2022 The HuggingFace Team and The OpenBMB Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __lowerCAmelCase = { '''configuration_cpmant''': ['''CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CpmAntConfig'''], '''tokenization_cpmant''': ['''CpmAntTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CpmAntForCausalLM''', '''CpmAntModel''', '''CpmAntPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
89
0
'''simple docstring''' import argparse from transformers import TaConfig, TaForConditionalGeneration, load_tf_weights_in_ta from transformers.utils import logging logging.set_verbosity_info() def _lowerCamelCase ( lowercase : Any , lowercase : Tuple , lowercase : Optional[Any] ) -> Optional[Any]: # Initialise PyTorch model _a = TaConfig.from_json_file(lowercase ) print(F'Building PyTorch model from configuration: {config}' ) _a = TaForConditionalGeneration(lowercase ) # Load weights from tf checkpoint load_tf_weights_in_ta(lowercase , lowercase , lowercase ) # Save pytorch-model print(F'Save PyTorch model to {pytorch_dump_path}' ) model.save_pretrained(lowercase ) if __name__ == "__main__": lowerCAmelCase_ : Dict = 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( '--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.' ) lowerCAmelCase_ : str = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path)
63
'''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 __magic_name__ ( _UpperCamelCase , unittest.TestCase ): lowerCAmelCase : str = LayoutLMTokenizer lowerCAmelCase : Tuple = LayoutLMTokenizerFast lowerCAmelCase : List[Any] = True lowerCAmelCase : int = True def __lowercase ( self : Dict ): super().setUp() _a : int = [ '[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] _a : List[str] = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def __lowercase ( self : Dict ,**_UpperCAmelCase : List[str] ): return LayoutLMTokenizer.from_pretrained(self.tmpdirname ,**_UpperCAmelCase ) def __lowercase ( self : Optional[Any] ,_UpperCAmelCase : Tuple ): _a : Optional[int] = 'UNwant\u00E9d,running' _a : List[Any] = 'unwanted, running' return input_text, output_text def __lowercase ( self : Optional[int] ): _a : Optional[Any] = self.tokenizer_class(self.vocab_file ) _a : Optional[Any] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(_UpperCAmelCase ,['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_UpperCAmelCase ) ,[7, 4, 5, 10, 8, 9] ) def __lowercase ( self : Optional[int] ): pass
89
0
"""simple docstring""" import unittest from parameterized import parameterized from transformers import AutoTokenizer, GPTNeoXConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, GPTNeoXModel, ) class lowercase: '''simple docstring''' def __init__( self: Optional[Any], a_: Tuple, a_: Any=13, a_: Any=7, a_: Tuple=True, a_: int=True, a_: Union[str, Any]=True, a_: Optional[int]=True, a_: int=99, a_: Tuple=64, a_: Union[str, Any]=5, a_: Optional[int]=4, a_: int=37, a_: str="gelu", a_: Tuple=0.1, a_: Any=0.1, a_: Tuple=512, a_: Optional[Any]=16, a_: Union[str, Any]=2, a_: int=0.02, a_: List[Any]=3, a_: List[Any]=4, a_: Tuple=None, ): '''simple docstring''' _snake_case : Optional[int] = parent _snake_case : Tuple = batch_size _snake_case : List[Any] = seq_length _snake_case : Union[str, Any] = is_training _snake_case : Union[str, Any] = use_input_mask _snake_case : List[str] = use_token_type_ids _snake_case : Optional[int] = use_labels _snake_case : Optional[Any] = vocab_size _snake_case : str = hidden_size _snake_case : Tuple = num_hidden_layers _snake_case : Optional[Any] = num_attention_heads _snake_case : Optional[Any] = intermediate_size _snake_case : Union[str, Any] = hidden_act _snake_case : Optional[Any] = hidden_dropout_prob _snake_case : Optional[int] = attention_probs_dropout_prob _snake_case : Any = max_position_embeddings _snake_case : Optional[Any] = type_vocab_size _snake_case : Tuple = type_sequence_label_size _snake_case : Optional[int] = initializer_range _snake_case : int = num_labels _snake_case : Dict = num_choices _snake_case : str = scope _snake_case : Optional[int] = vocab_size - 1 def UpperCamelCase_ ( self: Union[str, Any] ): '''simple docstring''' _snake_case : Optional[Any] = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) _snake_case : int = None if self.use_input_mask: _snake_case : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) _snake_case : Optional[int] = None if self.use_labels: _snake_case : Dict = ids_tensor([self.batch_size, self.seq_length], self.num_labels ) _snake_case : Optional[int] = self.get_config() return config, input_ids, input_mask, token_labels def UpperCamelCase_ ( self: str ): '''simple docstring''' return GPTNeoXConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, is_decoder=a_, initializer_range=self.initializer_range, pad_token_id=self.pad_token_id, ) def UpperCamelCase_ ( self: str ): '''simple docstring''' _snake_case , _snake_case , _snake_case , _snake_case : Dict = self.prepare_config_and_inputs() _snake_case : Optional[Any] = True return config, input_ids, input_mask, token_labels def UpperCamelCase_ ( self: Tuple, a_: int, a_: List[Any], a_: Dict ): '''simple docstring''' _snake_case : Optional[Any] = GPTNeoXModel(config=a_ ) model.to(a_ ) model.eval() _snake_case : Union[str, Any] = model(a_, attention_mask=a_ ) _snake_case : List[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self: Union[str, Any], a_: Union[str, Any], a_: Optional[int], a_: List[Any] ): '''simple docstring''' _snake_case : List[str] = True _snake_case : Any = GPTNeoXModel(a_ ) model.to(a_ ) model.eval() _snake_case : Optional[Any] = model(a_, attention_mask=a_ ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self: Optional[Any], a_: Optional[int], a_: int, a_: Union[str, Any], a_: Any ): '''simple docstring''' _snake_case : Optional[Any] = GPTNeoXForCausalLM(config=a_ ) model.to(a_ ) model.eval() _snake_case : str = model(a_, attention_mask=a_, labels=a_ ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self: Union[str, Any], a_: int, a_: List[Any], a_: Union[str, Any], a_: str ): '''simple docstring''' _snake_case : int = self.num_labels _snake_case : Optional[int] = GPTNeoXForQuestionAnswering(a_ ) model.to(a_ ) model.eval() _snake_case : Tuple = model(a_, attention_mask=a_ ) self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length) ) def UpperCamelCase_ ( self: Dict, a_: Dict, a_: Optional[int], a_: str, a_: str ): '''simple docstring''' _snake_case : Optional[int] = self.num_labels _snake_case : Union[str, Any] = GPTNeoXForSequenceClassification(a_ ) model.to(a_ ) model.eval() _snake_case : List[str] = ids_tensor([self.batch_size], self.type_sequence_label_size ) _snake_case : List[Any] = model(a_, attention_mask=a_, labels=a_ ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self: str, a_: Optional[Any], a_: Tuple, a_: List[Any], a_: List[str] ): '''simple docstring''' _snake_case : Optional[Any] = self.num_labels _snake_case : List[str] = GPTNeoXForTokenClassification(a_ ) model.to(a_ ) model.eval() _snake_case : str = model(a_, attention_mask=a_, labels=a_ ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase_ ( self: List[str], a_: Dict, a_: str, a_: Optional[Any] ): '''simple docstring''' _snake_case : Any = True _snake_case : Optional[int] = GPTNeoXForCausalLM(config=a_ ) model.to(a_ ) model.eval() # first forward pass _snake_case : Optional[Any] = model(a_, attention_mask=a_, use_cache=a_ ) _snake_case : Union[str, Any] = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids _snake_case : Dict = ids_tensor((self.batch_size, 3), config.vocab_size ) _snake_case : Optional[Any] = ids_tensor((self.batch_size, 3), vocab_size=2 ) # append to next input_ids and _snake_case : Optional[Any] = torch.cat([input_ids, next_tokens], dim=-1 ) _snake_case : List[Any] = torch.cat([input_mask, next_mask], dim=-1 ) _snake_case : int = model(a_, attention_mask=a_, output_hidden_states=a_ ) _snake_case : str = output_from_no_past["""hidden_states"""][0] _snake_case : Union[str, Any] = model( a_, attention_mask=a_, past_key_values=a_, output_hidden_states=a_, )["""hidden_states"""][0] # select random slice _snake_case : Any = ids_tensor((1,), output_from_past.shape[-1] ).item() _snake_case : str = output_from_no_past[:, -3:, random_slice_idx].detach() _snake_case : int = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_, a_, atol=1E-3 ) ) def UpperCamelCase_ ( self: List[str] ): '''simple docstring''' _snake_case : Any = self.prepare_config_and_inputs() _snake_case , _snake_case , _snake_case , _snake_case : Dict = config_and_inputs _snake_case : Union[str, Any] = {"""input_ids""": input_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class lowercase( __a , __a , __a , unittest.TestCase ): '''simple docstring''' lowercase__ = ( ( GPTNeoXModel, GPTNeoXForCausalLM, GPTNeoXForQuestionAnswering, GPTNeoXForSequenceClassification, GPTNeoXForTokenClassification, ) if is_torch_available() else () ) lowercase__ = (GPTNeoXForCausalLM,) if is_torch_available() else () lowercase__ = ( { "feature-extraction": GPTNeoXModel, "question-answering": GPTNeoXForQuestionAnswering, "text-classification": GPTNeoXForSequenceClassification, "text-generation": GPTNeoXForCausalLM, "token-classification": GPTNeoXForTokenClassification, "zero-shot": GPTNeoXForSequenceClassification, } if is_torch_available() else {} ) lowercase__ = False lowercase__ = False lowercase__ = False lowercase__ = False def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' _snake_case : Union[str, Any] = GPTNeoXModelTester(self ) _snake_case : List[str] = ConfigTester(self, config_class=a_, hidden_size=64, num_attention_heads=8 ) def UpperCamelCase_ ( self: List[str] ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase_ ( self: Optional[int] ): '''simple docstring''' _snake_case , _snake_case , _snake_case , _snake_case : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(a_, a_, a_ ) def UpperCamelCase_ ( self: Any ): '''simple docstring''' _snake_case , _snake_case , _snake_case , _snake_case : List[str] = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(a_, a_, a_ ) def UpperCamelCase_ ( self: Any ): '''simple docstring''' _snake_case , _snake_case , _snake_case , _snake_case : Dict = self.model_tester.prepare_config_and_inputs_for_decoder() _snake_case : str = None self.model_tester.create_and_check_model_as_decoder(a_, a_, a_ ) def UpperCamelCase_ ( self: List[Any] ): '''simple docstring''' _snake_case , _snake_case , _snake_case , _snake_case : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(a_, a_, a_ ) def UpperCamelCase_ ( self: int ): '''simple docstring''' _snake_case : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_causal_lm(*a_ ) def UpperCamelCase_ ( self: str ): '''simple docstring''' _snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*a_ ) def UpperCamelCase_ ( self: Optional[int] ): '''simple docstring''' _snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*a_ ) def UpperCamelCase_ ( self: Any ): '''simple docstring''' _snake_case : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*a_ ) @unittest.skip(reason="""Feed forward chunking is not implemented""" ) def UpperCamelCase_ ( self: Optional[Any] ): '''simple docstring''' pass @parameterized.expand([("""linear""",), ("""dynamic""",)] ) def UpperCamelCase_ ( self: Optional[int], a_: List[Any] ): '''simple docstring''' _snake_case , _snake_case : Tuple = self.model_tester.prepare_config_and_inputs_for_common() _snake_case : Optional[Any] = ids_tensor([1, 10], config.vocab_size ) _snake_case : Any = ids_tensor([1, int(config.max_position_embeddings * 1.5 )], config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights _snake_case : List[str] = GPTNeoXModel(a_ ) original_model.to(a_ ) original_model.eval() _snake_case : Dict = original_model(a_ ).last_hidden_state _snake_case : List[Any] = original_model(a_ ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights _snake_case : Optional[int] = {"""type""": scaling_type, """factor""": 10.0} _snake_case : Union[str, Any] = GPTNeoXModel(a_ ) scaled_model.to(a_ ) scaled_model.eval() _snake_case : Optional[int] = scaled_model(a_ ).last_hidden_state _snake_case : Dict = scaled_model(a_ ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(a_, a_, atol=1E-5 ) ) else: self.assertFalse(torch.allclose(a_, a_, atol=1E-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(a_, a_, atol=1E-5 ) ) @require_torch class lowercase( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase_ ( self: Tuple ): '''simple docstring''' _snake_case : List[str] = AutoTokenizer.from_pretrained("""EleutherAI/pythia-410m-deduped""" ) for checkpointing in [True, False]: _snake_case : Dict = GPTNeoXForCausalLM.from_pretrained("""EleutherAI/pythia-410m-deduped""" ) if checkpointing: model.gradient_checkpointing_enable() else: model.gradient_checkpointing_disable() model.to(a_ ) _snake_case : Optional[int] = tokenizer("""My favorite food is""", return_tensors="""pt""" ).to(a_ ) # The hub repo. is updated on 2023-04-04, resulting in poor outputs. # See: https://github.com/huggingface/transformers/pull/24193 _snake_case : Tuple = """My favorite food is a good old-fashioned, old-fashioned, old-fashioned.\n\nI'm not sure""" _snake_case : str = model.generate(**a_, do_sample=a_, max_new_tokens=20 ) _snake_case : List[Any] = tokenizer.batch_decode(a_ )[0] self.assertEqual(a_, a_ )
64
'''simple docstring''' import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { '''microsoft/conditional-detr-resnet-50''': ( '''https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json''' ), } class __magic_name__ ( _UpperCamelCase ): lowerCAmelCase : Any = 'conditional_detr' lowerCAmelCase : List[str] = ['past_key_values'] lowerCAmelCase : Optional[int] = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : Optional[int] ,_UpperCAmelCase : Optional[int]=True ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : List[Any]=3 ,_UpperCAmelCase : List[Any]=300 ,_UpperCAmelCase : Dict=6 ,_UpperCAmelCase : List[str]=2048 ,_UpperCAmelCase : Optional[int]=8 ,_UpperCAmelCase : List[Any]=6 ,_UpperCAmelCase : Optional[int]=2048 ,_UpperCAmelCase : Dict=8 ,_UpperCAmelCase : int=0.0 ,_UpperCAmelCase : Optional[Any]=0.0 ,_UpperCAmelCase : Optional[Any]=True ,_UpperCAmelCase : str="relu" ,_UpperCAmelCase : Tuple=256 ,_UpperCAmelCase : Optional[int]=0.1 ,_UpperCAmelCase : str=0.0 ,_UpperCAmelCase : Optional[int]=0.0 ,_UpperCAmelCase : Union[str, Any]=0.02 ,_UpperCAmelCase : List[str]=1.0 ,_UpperCAmelCase : Any=False ,_UpperCAmelCase : int="sine" ,_UpperCAmelCase : List[str]="resnet50" ,_UpperCAmelCase : Optional[int]=True ,_UpperCAmelCase : str=False ,_UpperCAmelCase : str=2 ,_UpperCAmelCase : int=5 ,_UpperCAmelCase : Optional[int]=2 ,_UpperCAmelCase : str=1 ,_UpperCAmelCase : Union[str, Any]=1 ,_UpperCAmelCase : List[str]=2 ,_UpperCAmelCase : Union[str, Any]=5 ,_UpperCAmelCase : List[Any]=2 ,_UpperCAmelCase : Optional[int]=0.25 ,**_UpperCAmelCase : Tuple ,): if backbone_config is not None and use_timm_backbone: raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.' ) if not use_timm_backbone: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) _a : Optional[Any] = CONFIG_MAPPING['resnet'](out_features=['stage4'] ) elif isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : str = backbone_config.get('model_type' ) _a : Union[str, Any] = CONFIG_MAPPING[backbone_model_type] _a : List[Any] = config_class.from_dict(_UpperCAmelCase ) _a : Tuple = use_timm_backbone _a : Union[str, Any] = backbone_config _a : List[Any] = num_channels _a : Union[str, Any] = num_queries _a : Optional[Any] = d_model _a : Tuple = encoder_ffn_dim _a : Dict = encoder_layers _a : List[str] = encoder_attention_heads _a : Union[str, Any] = decoder_ffn_dim _a : Optional[int] = decoder_layers _a : int = decoder_attention_heads _a : Optional[int] = dropout _a : Tuple = attention_dropout _a : List[Any] = activation_dropout _a : str = activation_function _a : Optional[Any] = init_std _a : Union[str, Any] = init_xavier_std _a : List[Any] = encoder_layerdrop _a : List[Any] = decoder_layerdrop _a : Dict = encoder_layers _a : List[Any] = auxiliary_loss _a : Optional[int] = position_embedding_type _a : List[Any] = backbone _a : Optional[int] = use_pretrained_backbone _a : Optional[int] = dilation # Hungarian matcher _a : Tuple = class_cost _a : str = bbox_cost _a : Any = giou_cost # Loss coefficients _a : Tuple = mask_loss_coefficient _a : Dict = dice_loss_coefficient _a : Tuple = cls_loss_coefficient _a : Any = bbox_loss_coefficient _a : Dict = giou_loss_coefficient _a : Union[str, Any] = focal_alpha super().__init__(is_encoder_decoder=_UpperCAmelCase ,**_UpperCAmelCase ) @property def __lowercase ( self : Dict ): return self.encoder_attention_heads @property def __lowercase ( self : str ): return self.d_model def __lowercase ( self : int ): _a : List[str] = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: _a : Dict = self.backbone_config.to_dict() _a : Union[str, Any] = self.__class__.model_type return output class __magic_name__ ( _UpperCamelCase ): lowerCAmelCase : str = version.parse('1.11' ) @property def __lowercase ( self : Dict ): return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('pixel_mask', {0: 'batch'}), ] ) @property def __lowercase ( self : Any ): return 1E-5 @property def __lowercase ( self : List[Any] ): return 12
89
0
import random def lowerCAmelCase_ ( __A, __A, __A ) -> Dict: '''simple docstring''' UpperCAmelCase__ = a[left_index] UpperCAmelCase__ = left_index + 1 for j in range(left_index + 1, __A ): if a[j] < pivot: UpperCAmelCase__ , UpperCAmelCase__ = a[i], a[j] i += 1 UpperCAmelCase__ , UpperCAmelCase__ = a[i - 1], a[left_index] return i - 1 def lowerCAmelCase_ ( __A, __A, __A ) -> Tuple: '''simple docstring''' if left < right: UpperCAmelCase__ = random.randint(__A, right - 1 ) UpperCAmelCase__ , UpperCAmelCase__ = ( a[left], a[pivot], ) # switches the pivot with the left most bound UpperCAmelCase__ = partition(__A, __A, __A ) quick_sort_random( __A, __A, __A ) # recursive quicksort to the left of the pivot point quick_sort_random( __A, pivot_index + 1, __A ) # recursive quicksort to the right of the pivot point def lowerCAmelCase_ ( ) -> Any: '''simple docstring''' UpperCAmelCase__ = input("Enter numbers separated by a comma:\n" ).strip() UpperCAmelCase__ = [int(__A ) for item in user_input.split("," )] quick_sort_random(__A, 0, len(__A ) ) print(__A ) if __name__ == "__main__": main()
65
'''simple docstring''' import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __magic_name__ : def __init__( self : List[str] ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : List[str]=13 ,_UpperCAmelCase : Any=32 ,_UpperCAmelCase : Union[str, Any]=3 ,_UpperCAmelCase : Optional[int]=4 ,_UpperCAmelCase : Optional[Any]=[10, 20, 30, 40] ,_UpperCAmelCase : Tuple=[2, 2, 3, 2] ,_UpperCAmelCase : Optional[int]=True ,_UpperCAmelCase : Optional[int]=True ,_UpperCAmelCase : Union[str, Any]=37 ,_UpperCAmelCase : Optional[int]="gelu" ,_UpperCAmelCase : Optional[Any]=10 ,_UpperCAmelCase : Tuple=0.02 ,_UpperCAmelCase : Any=["stage2", "stage3", "stage4"] ,_UpperCAmelCase : Any=[2, 3, 4] ,_UpperCAmelCase : Tuple=None ,): _a : Optional[Any] = parent _a : List[Any] = batch_size _a : str = image_size _a : Union[str, Any] = num_channels _a : List[Any] = num_stages _a : Dict = hidden_sizes _a : int = depths _a : Tuple = is_training _a : List[str] = use_labels _a : Dict = intermediate_size _a : int = hidden_act _a : int = num_labels _a : Any = initializer_range _a : Tuple = out_features _a : int = out_indices _a : List[Any] = scope def __lowercase ( self : Dict ): _a : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _a : Union[str, Any] = None if self.use_labels: _a : Tuple = ids_tensor([self.batch_size] ,self.num_labels ) _a : str = self.get_config() return config, pixel_values, labels def __lowercase ( self : Any ): return ConvNextVaConfig( num_channels=self.num_channels ,hidden_sizes=self.hidden_sizes ,depths=self.depths ,num_stages=self.num_stages ,hidden_act=self.hidden_act ,is_decoder=_UpperCAmelCase ,initializer_range=self.initializer_range ,out_features=self.out_features ,out_indices=self.out_indices ,num_labels=self.num_labels ,) def __lowercase ( self : Tuple ,_UpperCAmelCase : Any ,_UpperCAmelCase : Any ,_UpperCAmelCase : Optional[Any] ): _a : Optional[Any] = ConvNextVaModel(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : Any = model(_UpperCAmelCase ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape ,(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) ,) def __lowercase ( self : Tuple ,_UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : int ): _a : List[Any] = ConvNextVaForImageClassification(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : List[str] = model(_UpperCAmelCase ,labels=_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def __lowercase ( self : str ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ): _a : Optional[int] = ConvNextVaBackbone(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : Dict = model(_UpperCAmelCase ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) ,len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) ,[self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) ,len(config.out_features ) ) self.parent.assertListEqual(model.channels ,config.hidden_sizes[1:] ) # verify backbone works with out_features=None _a : Tuple = None _a : List[Any] = ConvNextVaBackbone(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : List[str] = model(_UpperCAmelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) ,1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) ,[self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) ,1 ) self.parent.assertListEqual(model.channels ,[config.hidden_sizes[-1]] ) def __lowercase ( self : Optional[Any] ): _a : Any = self.prepare_config_and_inputs() _a , _a , _a : Union[str, Any] = config_and_inputs _a : Any = {'pixel_values': pixel_values} return config, inputs_dict def __lowercase ( self : str ): _a : Tuple = self.prepare_config_and_inputs() _a , _a , _a : Tuple = config_and_inputs _a : List[Any] = {'pixel_values': pixel_values, 'labels': labels} return config, inputs_dict @require_torch class __magic_name__ ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): lowerCAmelCase : str = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) lowerCAmelCase : str = ( {'feature-extraction': ConvNextVaModel, 'image-classification': ConvNextVaForImageClassification} if is_torch_available() else {} ) lowerCAmelCase : int = False lowerCAmelCase : str = False lowerCAmelCase : Optional[Any] = False lowerCAmelCase : List[str] = False lowerCAmelCase : Optional[int] = False def __lowercase ( self : List[Any] ): _a : str = ConvNextVaModelTester(self ) _a : Tuple = ConfigTester(self ,config_class=_UpperCAmelCase ,has_text_modality=_UpperCAmelCase ,hidden_size=37 ) def __lowercase ( self : Optional[Any] ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __lowercase ( self : str ): return @unittest.skip(reason='ConvNextV2 does not use inputs_embeds' ) def __lowercase ( self : List[Any] ): pass @unittest.skip(reason='ConvNextV2 does not support input and output embeddings' ) def __lowercase ( self : Optional[int] ): pass @unittest.skip(reason='ConvNextV2 does not use feedforward chunking' ) def __lowercase ( self : Any ): pass def __lowercase ( self : List[str] ): if not self.model_tester.is_training: return for model_class in self.all_model_classes: _a , _a : List[Any] = self.model_tester.prepare_config_and_inputs_with_labels() _a : Any = True if model_class.__name__ in [ *get_values(_UpperCAmelCase ), *get_values(_UpperCAmelCase ), ]: continue _a : Optional[Any] = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.train() _a : str = self._prepare_for_class(_UpperCAmelCase ,_UpperCAmelCase ,return_labels=_UpperCAmelCase ) _a : Optional[int] = model(**_UpperCAmelCase ).loss loss.backward() def __lowercase ( self : str ): if not self.model_tester.is_training: return for model_class in self.all_model_classes: _a , _a : Optional[Any] = self.model_tester.prepare_config_and_inputs_with_labels() _a : Optional[int] = False _a : Tuple = True if ( model_class.__name__ in [*get_values(_UpperCAmelCase ), *get_values(_UpperCAmelCase )] or not model_class.supports_gradient_checkpointing ): continue _a : Tuple = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.gradient_checkpointing_enable() model.train() _a : Any = self._prepare_for_class(_UpperCAmelCase ,_UpperCAmelCase ,return_labels=_UpperCAmelCase ) _a : List[Any] = model(**_UpperCAmelCase ).loss loss.backward() def __lowercase ( self : List[Any] ): _a , _a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : int = model_class(_UpperCAmelCase ) _a : Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _a : Dict = [*signature.parameters.keys()] _a : int = ['pixel_values'] self.assertListEqual(arg_names[:1] ,_UpperCAmelCase ) def __lowercase ( self : int ): _a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase ) def __lowercase ( self : Any ): def check_hidden_states_output(_UpperCAmelCase : List[Any] ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Dict ): _a : Union[str, Any] = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() with torch.no_grad(): _a : List[Any] = model(**self._prepare_for_class(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Any = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _a : str = self.model_tester.num_stages self.assertEqual(len(_UpperCAmelCase ) ,expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) ,[self.model_tester.image_size // 4, self.model_tester.image_size // 4] ,) _a , _a : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : int = True check_hidden_states_output(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _a : Optional[Any] = True check_hidden_states_output(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) def __lowercase ( self : List[Any] ): _a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase ) @slow def __lowercase ( self : int ): for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Any = ConvNextVaModel.from_pretrained(_UpperCAmelCase ) self.assertIsNotNone(_UpperCAmelCase ) def __lowerCamelCase ( ) -> List[Any]: _a : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class __magic_name__ ( unittest.TestCase ): @cached_property def __lowercase ( self : Optional[Any] ): return AutoImageProcessor.from_pretrained('facebook/convnextv2-tiny-1k-224' ) if is_vision_available() else None @slow def __lowercase ( self : Any ): _a : List[str] = ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224' ).to(_UpperCAmelCase ) _a : Optional[int] = self.default_image_processor _a : str = prepare_img() _a : str = preprocessor(images=_UpperCAmelCase ,return_tensors='pt' ).to(_UpperCAmelCase ) # forward pass with torch.no_grad(): _a : Dict = model(**_UpperCAmelCase ) # verify the logits _a : Optional[Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape ,_UpperCAmelCase ) _a : Optional[Any] = torch.tensor([0.99_96, 0.19_66, -0.43_86] ).to(_UpperCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,_UpperCAmelCase ,atol=1E-4 ) )
89
0
"""simple docstring""" import math class lowerCamelCase : '''simple docstring''' def lowerCAmelCase_ ( self: Tuple , snake_case: list[list[float]] , snake_case: list[int] ) -> int: snake_case_ :Any = 0.0 snake_case_ :Tuple = 0.0 for i in range(len(snake_case ) ): da += math.pow((sample[i] - weights[0][i]) , 2 ) da += math.pow((sample[i] - weights[1][i]) , 2 ) return 0 if da > da else 1 return 0 def lowerCAmelCase_ ( self: Optional[int] , snake_case: list[list[int | float]] , snake_case: list[int] , snake_case: int , snake_case: float ) -> list[list[int | float]]: for i in range(len(snake_case ) ): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights def A_ ( ): '''simple docstring''' snake_case_ :Dict = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) snake_case_ :List[Any] = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training snake_case_ :Optional[Any] = SelfOrganizingMap() snake_case_ :Dict = 3 snake_case_ :Dict = 0.5 for _ in range(_lowercase ): for j in range(len(_lowercase ) ): # training sample snake_case_ :List[Any] = training_samples[j] # Compute the winning vector snake_case_ :Optional[int] = self_organizing_map.get_winner(_lowercase, _lowercase ) # Update the winning vector snake_case_ :List[str] = self_organizing_map.update(_lowercase, _lowercase, _lowercase, _lowercase ) # classify test sample snake_case_ :str = [0, 0, 0, 1] snake_case_ :List[Any] = self_organizing_map.get_winner(_lowercase, _lowercase ) # results print(f"""Clusters that the test sample belongs to : {winner}""" ) print(f"""Weights that have been trained : {weights}""" ) # running the main() function if __name__ == "__main__": main()
66
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCAmelCase = { '''configuration_lilt''': ['''LILT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LiltConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''LILT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''LiltForQuestionAnswering''', '''LiltForSequenceClassification''', '''LiltForTokenClassification''', '''LiltModel''', '''LiltPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_lilt import LILT_PRETRAINED_CONFIG_ARCHIVE_MAP, LiltConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lilt import ( LILT_PRETRAINED_MODEL_ARCHIVE_LIST, LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, LiltPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
89
0
'''simple docstring''' import os import unittest from transformers.models.phobert.tokenization_phobert import VOCAB_FILES_NAMES, PhobertTokenizer from ...test_tokenization_common import TokenizerTesterMixin class a__ ( UpperCAmelCase__ , unittest.TestCase ): lowerCamelCase : Optional[int] =PhobertTokenizer lowerCamelCase : Any =False def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt __lowerCamelCase = ['''T@@''', '''i''', '''I''', '''R@@''', '''r''', '''e@@'''] __lowerCamelCase = dict(zip(a , range(len(a ) ) ) ) __lowerCamelCase = ['''#version: 0.2''', '''l à</w>'''] __lowerCamelCase = {'''unk_token''': '''<unk>'''} __lowerCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) __lowerCamelCase = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: for token in vocab_tokens: fp.write(f"""{token} {vocab_tokens[token]}\n""" ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(a ) ) def SCREAMING_SNAKE_CASE__ ( self : int , **a : List[str] ): """simple docstring""" kwargs.update(self.special_tokens_map ) return PhobertTokenizer.from_pretrained(self.tmpdirname , **a ) def SCREAMING_SNAKE_CASE__ ( self : str , a : Tuple ): """simple docstring""" __lowerCamelCase = '''Tôi là VinAI Research''' __lowerCamelCase = '''T<unk> i <unk> <unk> <unk> <unk> <unk> <unk> I Re<unk> e<unk> <unk> <unk> <unk>''' return input_text, output_text def SCREAMING_SNAKE_CASE__ ( self : int ): """simple docstring""" __lowerCamelCase = PhobertTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) __lowerCamelCase = '''Tôi là VinAI Research''' __lowerCamelCase = '''T@@ ô@@ i l@@ à V@@ i@@ n@@ A@@ I R@@ e@@ s@@ e@@ a@@ r@@ c@@ h'''.split() __lowerCamelCase = tokenizer.tokenize(a ) print(a ) self.assertListEqual(a , a ) __lowerCamelCase = tokens + [tokenizer.unk_token] __lowerCamelCase = [4, 3, 5, 3, 3, 3, 3, 3, 3, 6, 7, 9, 3, 9, 3, 3, 3, 3, 3] self.assertListEqual(tokenizer.convert_tokens_to_ids(a ) , a )
67
'''simple docstring''' import math def __lowerCamelCase ( lowerCAmelCase_ ) -> bool: _a : Optional[int] = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(lowerCAmelCase_ ) def __lowerCamelCase ( lowerCAmelCase_ = 1 / 12345 ) -> int: _a : int = 0 _a : Optional[Any] = 0 _a : int = 3 while True: _a : Tuple = (integer**2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(lowerCAmelCase_ ): _a : Union[str, Any] = int(lowerCAmelCase_ ) total_partitions += 1 if check_partition_perfect(lowerCAmelCase_ ): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return int(lowerCAmelCase_ ) integer += 1 if __name__ == "__main__": print(f"""{solution() = }""")
89
0
import argparse import shlex import runhouse as rh if __name__ == "__main__": # Refer to https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup for cloud access # setup instructions, if using on-demand hardware # If user passes --user <user> --host <host> --key_path <key_path> <example> <args>, fill them in as BYO cluster # If user passes --instance <instance> --provider <provider> <example> <args>, fill them in as on-demand cluster # Throw an error if user passes both BYO and on-demand cluster args # Otherwise, use default values lowerCAmelCase__ = argparse.ArgumentParser() parser.add_argument("""--user""", type=str, default="""ubuntu""") parser.add_argument("""--host""", type=str, default="""localhost""") parser.add_argument("""--key_path""", type=str, default=None) parser.add_argument("""--instance""", type=str, default="""V100:1""") parser.add_argument("""--provider""", type=str, default="""cheapest""") parser.add_argument("""--use_spot""", type=bool, default=False) parser.add_argument("""--example""", type=str, default="""pytorch/text-generation/run_generation.py""") lowerCAmelCase__ , lowerCAmelCase__ = parser.parse_known_args() if args.host != "localhost": if args.instance != "V100:1" or args.provider != "cheapest": raise ValueError("""Cannot specify both BYO and on-demand cluster args""") lowerCAmelCase__ = rh.cluster( name="""rh-cluster""", ips=[args.host], ssh_creds={"""ssh_user""": args.user, """ssh_private_key""": args.key_path} ) else: lowerCAmelCase__ = rh.cluster( name="""rh-cluster""", instance_type=args.instance, provider=args.provider, use_spot=args.use_spot ) lowerCAmelCase__ = args.example.rsplit("""/""", 1)[0] # Set up remote environment cluster.install_packages(["""pip:./"""]) # Installs transformers from local source # Note transformers is copied into the home directory on the remote machine, so we can install from there cluster.run([f"""pip install -r transformers/examples/{example_dir}/requirements.txt"""]) cluster.run(["""pip install torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117"""]) # Run example. You can bypass the CLI wrapper and paste your own code here. cluster.run([f"""python transformers/examples/{args.example} {' '.join(shlex.quote(arg) for arg in unknown)}"""]) # Alternatively, we can just import and run a training function (especially if there's no wrapper CLI): # from my_script... import train # reqs = ['pip:./', 'torch', 'datasets', 'accelerate', 'evaluate', 'tqdm', 'scipy', 'scikit-learn', 'tensorboard'] # launch_train_gpu = rh.function(fn=train, # system=gpu, # reqs=reqs, # name='train_bert_glue') # # We can pass in arguments just like we would to a function: # launch_train_gpu(num_epochs = 3, lr = 2e-5, seed = 42, batch_size = 16 # stream_logs=True)
68
'''simple docstring''' import argparse import json import torch from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=1 ) -> Dict: if n_shave_prefix_segments >= 0: return ".".join(path.split('.' )[n_shave_prefix_segments:] ) else: return ".".join(path.split('.' )[:n_shave_prefix_segments] ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=0 ) -> Tuple: _a : Any = [] for old_item in old_list: _a : Union[str, Any] = old_item.replace('in_layers.0' , 'norm1' ) _a : Optional[int] = new_item.replace('in_layers.2' , 'conv1' ) _a : str = new_item.replace('out_layers.0' , 'norm2' ) _a : List[str] = new_item.replace('out_layers.3' , 'conv2' ) _a : str = new_item.replace('emb_layers.1' , 'time_emb_proj' ) _a : Tuple = new_item.replace('skip_connection' , 'conv_shortcut' ) _a : Any = shave_segments(lowerCAmelCase_ , n_shave_prefix_segments=lowerCAmelCase_ ) mapping.append({'old': old_item, 'new': new_item} ) return mapping def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=0 ) -> Any: _a : List[str] = [] for old_item in old_list: _a : List[Any] = old_item _a : Optional[int] = new_item.replace('norm.weight' , 'group_norm.weight' ) _a : Optional[Any] = new_item.replace('norm.bias' , 'group_norm.bias' ) _a : Any = new_item.replace('proj_out.weight' , 'proj_attn.weight' ) _a : Optional[Any] = new_item.replace('proj_out.bias' , 'proj_attn.bias' ) _a : Optional[int] = shave_segments(lowerCAmelCase_ , n_shave_prefix_segments=lowerCAmelCase_ ) mapping.append({'old': old_item, 'new': new_item} ) return mapping def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None , lowerCAmelCase_=None , lowerCAmelCase_=None ) -> Any: assert isinstance(lowerCAmelCase_ , lowerCAmelCase_ ), "Paths should be a list of dicts containing 'old' and 'new' keys." # Splits the attention layers into three variables. if attention_paths_to_split is not None: for path, path_map in attention_paths_to_split.items(): _a : Optional[Any] = old_checkpoint[path] _a : Optional[Any] = old_tensor.shape[0] // 3 _a : Any = (-1, channels) if len(old_tensor.shape ) == 3 else (-1) _a : int = old_tensor.shape[0] // config['num_head_channels'] // 3 _a : str = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:] ) _a , _a , _a : Tuple = old_tensor.split(channels // num_heads , dim=1 ) _a : Dict = query.reshape(lowerCAmelCase_ ) _a : str = key.reshape(lowerCAmelCase_ ) _a : Optional[int] = value.reshape(lowerCAmelCase_ ) for path in paths: _a : Dict = path['new'] # These have already been assigned if attention_paths_to_split is not None and new_path in attention_paths_to_split: continue # Global renaming happens here _a : Any = new_path.replace('middle_block.0' , 'mid_block.resnets.0' ) _a : str = new_path.replace('middle_block.1' , 'mid_block.attentions.0' ) _a : Union[str, Any] = new_path.replace('middle_block.2' , 'mid_block.resnets.1' ) if additional_replacements is not None: for replacement in additional_replacements: _a : int = new_path.replace(replacement['old'] , replacement['new'] ) # proj_attn.weight has to be converted from conv 1D to linear if "proj_attn.weight" in new_path: _a : List[str] = old_checkpoint[path['old']][:, :, 0] else: _a : Dict = old_checkpoint[path['old']] def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> List[Any]: _a : Optional[int] = {} _a : Dict = checkpoint['time_embed.0.weight'] _a : Tuple = checkpoint['time_embed.0.bias'] _a : Union[str, Any] = checkpoint['time_embed.2.weight'] _a : List[str] = checkpoint['time_embed.2.bias'] _a : List[str] = checkpoint['input_blocks.0.0.weight'] _a : Union[str, Any] = checkpoint['input_blocks.0.0.bias'] _a : Optional[int] = checkpoint['out.0.weight'] _a : int = checkpoint['out.0.bias'] _a : List[str] = checkpoint['out.2.weight'] _a : Optional[int] = checkpoint['out.2.bias'] # Retrieves the keys for the input blocks only _a : Optional[int] = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'input_blocks' in layer} ) _a : Dict = { layer_id: [key for key in checkpoint if f"""input_blocks.{layer_id}""" in key] for layer_id in range(lowerCAmelCase_ ) } # Retrieves the keys for the middle blocks only _a : List[Any] = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'middle_block' in layer} ) _a : Union[str, Any] = { layer_id: [key for key in checkpoint if f"""middle_block.{layer_id}""" in key] for layer_id in range(lowerCAmelCase_ ) } # Retrieves the keys for the output blocks only _a : Optional[int] = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'output_blocks' in layer} ) _a : str = { layer_id: [key for key in checkpoint if f"""output_blocks.{layer_id}""" in key] for layer_id in range(lowerCAmelCase_ ) } for i in range(1 , lowerCAmelCase_ ): _a : List[Any] = (i - 1) // (config['num_res_blocks'] + 1) _a : Optional[int] = (i - 1) % (config['num_res_blocks'] + 1) _a : Optional[int] = [key for key in input_blocks[i] if f"""input_blocks.{i}.0""" in key] _a : Optional[Any] = [key for key in input_blocks[i] if f"""input_blocks.{i}.1""" in key] if f"""input_blocks.{i}.0.op.weight""" in checkpoint: _a : List[Any] = checkpoint[ f"""input_blocks.{i}.0.op.weight""" ] _a : Union[str, Any] = checkpoint[ f"""input_blocks.{i}.0.op.bias""" ] continue _a : Any = renew_resnet_paths(lowerCAmelCase_ ) _a : List[str] = {'old': f"""input_blocks.{i}.0""", 'new': f"""down_blocks.{block_id}.resnets.{layer_in_block_id}"""} _a : Optional[Any] = {'old': 'resnets.2.op', 'new': 'downsamplers.0.op'} assign_to_checkpoint( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , additional_replacements=[meta_path, resnet_op] , config=lowerCAmelCase_ ) if len(lowerCAmelCase_ ): _a : List[str] = renew_attention_paths(lowerCAmelCase_ ) _a : List[Any] = { 'old': f"""input_blocks.{i}.1""", 'new': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}""", } _a : Optional[Any] = { f"""input_blocks.{i}.1.qkv.bias""": { 'key': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias""", 'query': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias""", 'value': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias""", }, f"""input_blocks.{i}.1.qkv.weight""": { 'key': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight""", 'query': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight""", 'value': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight""", }, } assign_to_checkpoint( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , additional_replacements=[meta_path] , attention_paths_to_split=lowerCAmelCase_ , config=lowerCAmelCase_ , ) _a : str = middle_blocks[0] _a : Tuple = middle_blocks[1] _a : Any = middle_blocks[2] _a : List[Any] = renew_resnet_paths(lowerCAmelCase_ ) assign_to_checkpoint(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , config=lowerCAmelCase_ ) _a : Any = renew_resnet_paths(lowerCAmelCase_ ) assign_to_checkpoint(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , config=lowerCAmelCase_ ) _a : int = renew_attention_paths(lowerCAmelCase_ ) _a : int = { 'middle_block.1.qkv.bias': { 'key': 'mid_block.attentions.0.key.bias', 'query': 'mid_block.attentions.0.query.bias', 'value': 'mid_block.attentions.0.value.bias', }, 'middle_block.1.qkv.weight': { 'key': 'mid_block.attentions.0.key.weight', 'query': 'mid_block.attentions.0.query.weight', 'value': 'mid_block.attentions.0.value.weight', }, } assign_to_checkpoint( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , attention_paths_to_split=lowerCAmelCase_ , config=lowerCAmelCase_ ) for i in range(lowerCAmelCase_ ): _a : List[str] = i // (config['num_res_blocks'] + 1) _a : Any = i % (config['num_res_blocks'] + 1) _a : Union[str, Any] = [shave_segments(lowerCAmelCase_ , 2 ) for name in output_blocks[i]] _a : Optional[Any] = {} for layer in output_block_layers: _a , _a : str = layer.split('.' )[0], shave_segments(lowerCAmelCase_ , 1 ) if layer_id in output_block_list: output_block_list[layer_id].append(lowerCAmelCase_ ) else: _a : str = [layer_name] if len(lowerCAmelCase_ ) > 1: _a : str = [key for key in output_blocks[i] if f"""output_blocks.{i}.0""" in key] _a : Optional[Any] = [key for key in output_blocks[i] if f"""output_blocks.{i}.1""" in key] _a : Dict = renew_resnet_paths(lowerCAmelCase_ ) _a : str = renew_resnet_paths(lowerCAmelCase_ ) _a : Optional[int] = {'old': f"""output_blocks.{i}.0""", 'new': f"""up_blocks.{block_id}.resnets.{layer_in_block_id}"""} assign_to_checkpoint(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , additional_replacements=[meta_path] , config=lowerCAmelCase_ ) if ["conv.weight", "conv.bias"] in output_block_list.values(): _a : List[Any] = list(output_block_list.values() ).index(['conv.weight', 'conv.bias'] ) _a : Tuple = checkpoint[ f"""output_blocks.{i}.{index}.conv.weight""" ] _a : List[str] = checkpoint[ f"""output_blocks.{i}.{index}.conv.bias""" ] # Clear attentions as they have been attributed above. if len(lowerCAmelCase_ ) == 2: _a : Union[str, Any] = [] if len(lowerCAmelCase_ ): _a : Tuple = renew_attention_paths(lowerCAmelCase_ ) _a : str = { 'old': f"""output_blocks.{i}.1""", 'new': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}""", } _a : List[Any] = { f"""output_blocks.{i}.1.qkv.bias""": { 'key': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias""", 'query': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias""", 'value': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias""", }, f"""output_blocks.{i}.1.qkv.weight""": { 'key': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight""", 'query': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight""", 'value': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight""", }, } assign_to_checkpoint( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , additional_replacements=[meta_path] , attention_paths_to_split=to_split if any('qkv' in key for key in attentions ) else None , config=lowerCAmelCase_ , ) else: _a : List[Any] = renew_resnet_paths(lowerCAmelCase_ , n_shave_prefix_segments=1 ) for path in resnet_0_paths: _a : int = '.'.join(['output_blocks', str(lowerCAmelCase_ ), path['old']] ) _a : Union[str, Any] = '.'.join(['up_blocks', str(lowerCAmelCase_ ), 'resnets', str(lowerCAmelCase_ ), path['new']] ) _a : Union[str, Any] = checkpoint[old_path] return new_checkpoint if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the architecture.''', ) parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') __lowerCAmelCase = parser.parse_args() __lowerCAmelCase = torch.load(args.checkpoint_path) with open(args.config_file) as f: __lowerCAmelCase = json.loads(f.read()) __lowerCAmelCase = convert_ldm_checkpoint(checkpoint, config) if "ldm" in config: del config["ldm"] __lowerCAmelCase = UNetaDModel(**config) model.load_state_dict(converted_checkpoint) try: __lowerCAmelCase = DDPMScheduler.from_config('''/'''.join(args.checkpoint_path.split('''/''')[:-1])) __lowerCAmelCase = VQModel.from_pretrained('''/'''.join(args.checkpoint_path.split('''/''')[:-1])) __lowerCAmelCase = LDMPipeline(unet=model, scheduler=scheduler, vae=vqvae) pipe.save_pretrained(args.dump_path) except: # noqa: E722 model.save_pretrained(args.dump_path)
89
0
"""simple docstring""" import torch from torch import nn from transformers import CLIPPreTrainedModel, CLIPVisionModel from ...models.attention import BasicTransformerBlock from ...utils import logging __UpperCamelCase = logging.get_logger(__name__) # pylint: disable=invalid-name class UpperCamelCase ( lowerCAmelCase__ ): def __init__( self, lowerCAmelCase__, lowerCAmelCase__=768) -> Any: super().__init__(lowerCAmelCase__) snake_case_ = proj_size snake_case_ = CLIPVisionModel(lowerCAmelCase__) snake_case_ = PaintByExampleMapper(lowerCAmelCase__) snake_case_ = nn.LayerNorm(config.hidden_size) snake_case_ = nn.Linear(config.hidden_size, self.proj_size) # uncondition for scaling snake_case_ = nn.Parameter(torch.randn((1, 1, self.proj_size))) def a_ ( self, lowerCAmelCase__, lowerCAmelCase__=False) -> int: snake_case_ = self.model(pixel_values=lowerCAmelCase__) snake_case_ = clip_output.pooler_output snake_case_ = self.mapper(latent_states[:, None]) snake_case_ = self.final_layer_norm(lowerCAmelCase__) snake_case_ = self.proj_out(lowerCAmelCase__) if return_uncond_vector: return latent_states, self.uncond_vector return latent_states class UpperCamelCase ( nn.Module ): def __init__( self, lowerCAmelCase__) -> List[str]: super().__init__() snake_case_ = (config.num_hidden_layers + 1) // 5 snake_case_ = config.hidden_size snake_case_ = 1 snake_case_ = nn.ModuleList( [ BasicTransformerBlock(lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__, activation_fn='gelu', attention_bias=lowerCAmelCase__) for _ in range(lowerCAmelCase__) ]) def a_ ( self, lowerCAmelCase__) -> List[Any]: for block in self.blocks: snake_case_ = block(lowerCAmelCase__) return hidden_states
69
'''simple docstring''' import datetime import platform import subprocess from typing import Optional, Tuple, Union import numpy as np def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> np.array: _a : Optional[int] = f"""{sampling_rate}""" _a : Any = '1' _a : Optional[int] = 'f32le' _a : Any = [ 'ffmpeg', '-i', 'pipe:0', '-ac', ac, '-ar', ar, '-f', format_for_conversion, '-hide_banner', '-loglevel', 'quiet', 'pipe:1', ] try: with subprocess.Popen(lowerCAmelCase_ , stdin=subprocess.PIPE , stdout=subprocess.PIPE ) as ffmpeg_process: _a : int = ffmpeg_process.communicate(lowerCAmelCase_ ) except FileNotFoundError as error: raise ValueError('ffmpeg was not found but is required to load audio files from filename' ) from error _a : int = output_stream[0] _a : List[str] = np.frombuffer(lowerCAmelCase_ , np.floataa ) if audio.shape[0] == 0: raise ValueError('Malformed soundfile' ) return audio def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = "f32le" , ) -> Union[str, Any]: _a : List[str] = f"""{sampling_rate}""" _a : List[str] = '1' if format_for_conversion == "s16le": _a : List[Any] = 2 elif format_for_conversion == "f32le": _a : Dict = 4 else: raise ValueError(f"""Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`""" ) _a : Any = platform.system() if system == "Linux": _a : Union[str, Any] = 'alsa' _a : Union[str, Any] = 'default' elif system == "Darwin": _a : Any = 'avfoundation' _a : Optional[int] = ':0' elif system == "Windows": _a : str = 'dshow' _a : Tuple = 'default' _a : str = [ 'ffmpeg', '-f', format_, '-i', input_, '-ac', ac, '-ar', ar, '-f', format_for_conversion, '-fflags', 'nobuffer', '-hide_banner', '-loglevel', 'quiet', 'pipe:1', ] _a : Any = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample _a : Union[str, Any] = _ffmpeg_stream(lowerCAmelCase_ , lowerCAmelCase_ ) for item in iterator: yield item def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = "f32le" , ) -> str: if stream_chunk_s is not None: _a : str = stream_chunk_s else: _a : List[str] = chunk_length_s _a : int = ffmpeg_microphone(lowerCAmelCase_ , lowerCAmelCase_ , format_for_conversion=lowerCAmelCase_ ) if format_for_conversion == "s16le": _a : Optional[Any] = np.intaa _a : List[Any] = 2 elif format_for_conversion == "f32le": _a : Tuple = np.floataa _a : Any = 4 else: raise ValueError(f"""Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`""" ) if stride_length_s is None: _a : str = chunk_length_s / 6 _a : Any = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample if isinstance(lowerCAmelCase_ , (int, float) ): _a : List[str] = [stride_length_s, stride_length_s] _a : str = int(round(sampling_rate * stride_length_s[0] ) ) * size_of_sample _a : List[str] = int(round(sampling_rate * stride_length_s[1] ) ) * size_of_sample _a : Any = datetime.datetime.now() _a : Dict = datetime.timedelta(seconds=lowerCAmelCase_ ) for item in chunk_bytes_iter(lowerCAmelCase_ , lowerCAmelCase_ , stride=(stride_left, stride_right) , stream=lowerCAmelCase_ ): # Put everything back in numpy scale _a : List[Any] = np.frombuffer(item['raw'] , dtype=lowerCAmelCase_ ) _a : List[str] = ( item['stride'][0] // size_of_sample, item['stride'][1] // size_of_sample, ) _a : Union[str, Any] = sampling_rate audio_time += delta if datetime.datetime.now() > audio_time + 10 * delta: # We're late !! SKIP continue yield item def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = False ) -> List[Any]: _a : Tuple = B'' _a , _a : str = stride if stride_left + stride_right >= chunk_len: raise ValueError( f"""Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}""" ) _a : Optional[int] = 0 for raw in iterator: acc += raw if stream and len(lowerCAmelCase_ ) < chunk_len: _a : str = (_stride_left, 0) yield {"raw": acc[:chunk_len], "stride": stride, "partial": True} else: while len(lowerCAmelCase_ ) >= chunk_len: # We are flushing the accumulator _a : Union[str, Any] = (_stride_left, stride_right) _a : Dict = {'raw': acc[:chunk_len], 'stride': stride} if stream: _a : List[str] = False yield item _a : int = stride_left _a : List[Any] = acc[chunk_len - stride_left - stride_right :] # Last chunk if len(lowerCAmelCase_ ) > stride_left: _a : str = {'raw': acc, 'stride': (_stride_left, 0)} if stream: _a : str = False yield item def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> Tuple: _a : Optional[Any] = 2**24 # 16Mo try: with subprocess.Popen(lowerCAmelCase_ , stdout=subprocess.PIPE , bufsize=lowerCAmelCase_ ) as ffmpeg_process: while True: _a : Any = ffmpeg_process.stdout.read(lowerCAmelCase_ ) if raw == b"": break yield raw except FileNotFoundError as error: raise ValueError('ffmpeg was not found but is required to stream audio files from filename' ) from error
89
0
'''simple docstring''' from __future__ import annotations def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase ): """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!""" ) _lowerCAmelCase = number_of_bytes // partitions _lowerCAmelCase = [] for i in range(lowerCAmelCase ): _lowerCAmelCase = i * bytes_per_partition + 1 _lowerCAmelCase = ( 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()
70
'''simple docstring''' __lowerCAmelCase = { '''A''': ['''B''', '''C''', '''E'''], '''B''': ['''A''', '''D''', '''E'''], '''C''': ['''A''', '''F''', '''G'''], '''D''': ['''B'''], '''E''': ['''A''', '''B''', '''D'''], '''F''': ['''C'''], '''G''': ['''C'''], } def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> list[str]: _a : List[Any] = set() # keep track of all the paths to be checked _a : Any = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue _a : Tuple = queue.pop(0 ) # get the last node from the path _a : Tuple = path[-1] if node not in explored: _a : Optional[Any] = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: _a : Any = list(lowerCAmelCase_ ) new_path.append(lowerCAmelCase_ ) queue.append(lowerCAmelCase_ ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(lowerCAmelCase_ ) # in case there's no path between the 2 nodes return [] def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> int: if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 _a : Optional[int] = [start] _a : Dict = set(lowerCAmelCase_ ) # Keep tab on distances from `start` node. _a : Dict = {start: 0, target: -1} while queue: _a : List[str] = queue.pop(0 ) if node == target: _a : Any = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(lowerCAmelCase_ ) queue.append(lowerCAmelCase_ ) _a : Any = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, '''G''', '''D''')) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, '''G''', '''D''')) # returns 4
89
0
import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImgaImgPipeline, UNetaDConditionModel from diffusers.pipelines.pipeline_utils import DiffusionPipeline from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import ( enable_full_determinism, floats_tensor, load_image, load_numpy, require_torch_gpu, skip_mps, slow, torch_device, ) from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class __A ( a , a , a , unittest.TestCase ): """simple docstring""" UpperCamelCase__ : Dict =StableUnCLIPImgaImgPipeline UpperCamelCase__ : Optional[int] =TEXT_GUIDED_IMAGE_VARIATION_PARAMS UpperCamelCase__ : int =TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS UpperCamelCase__ : Tuple =frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess UpperCamelCase__ : Optional[Any] =frozenset([] ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Optional[int] =32 __UpperCamelCase : Optional[int] =embedder_hidden_size # image encoding components __UpperCamelCase : Optional[int] =CLIPImageProcessor(crop_size=32 , size=32 ) torch.manual_seed(0 ) __UpperCamelCase : List[str] =CLIPVisionModelWithProjection( CLIPVisionConfig( hidden_size=lowerCamelCase__ , projection_dim=lowerCamelCase__ , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) ) # regular denoising components torch.manual_seed(0 ) __UpperCamelCase : Any =StableUnCLIPImageNormalizer(embedding_dim=lowerCamelCase__ ) __UpperCamelCase : Any =DDPMScheduler(beta_schedule='squaredcos_cap_v2' ) torch.manual_seed(0 ) __UpperCamelCase : Optional[Any] =CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) torch.manual_seed(0 ) __UpperCamelCase : Union[str, Any] =CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=lowerCamelCase__ , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) ) torch.manual_seed(0 ) __UpperCamelCase : int =UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type='projection' , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=lowerCamelCase__ , layers_per_block=1 , upcast_attention=lowerCamelCase__ , use_linear_projection=lowerCamelCase__ , ) torch.manual_seed(0 ) __UpperCamelCase : int =DDIMScheduler( beta_schedule='scaled_linear' , beta_start=0.00_085 , beta_end=0.012 , prediction_type='v_prediction' , set_alpha_to_one=lowerCamelCase__ , steps_offset=1 , ) torch.manual_seed(0 ) __UpperCamelCase : int =AutoencoderKL() __UpperCamelCase : int ={ # image encoding components 'feature_extractor': feature_extractor, 'image_encoder': image_encoder.eval(), # image noising components 'image_normalizer': image_normalizer.eval(), 'image_noising_scheduler': image_noising_scheduler, # regular denoising components 'tokenizer': tokenizer, 'text_encoder': text_encoder.eval(), 'unet': unet.eval(), 'scheduler': scheduler, 'vae': vae.eval(), } return components def __lowercase ( self , lowerCamelCase__ , lowerCamelCase__=0 , lowerCamelCase__=True ): """simple docstring""" if str(lowerCamelCase__ ).startswith('mps' ): __UpperCamelCase : Union[str, Any] =torch.manual_seed(lowerCamelCase__ ) else: __UpperCamelCase : Optional[Any] =torch.Generator(device=lowerCamelCase__ ).manual_seed(lowerCamelCase__ ) __UpperCamelCase : int =floats_tensor((1, 3, 32, 32) , rng=random.Random(lowerCamelCase__ ) ).to(lowerCamelCase__ ) if pil_image: __UpperCamelCase : Union[str, Any] =input_image * 0.5 + 0.5 __UpperCamelCase : List[Any] =input_image.clamp(0 , 1 ) __UpperCamelCase : Optional[int] =input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() __UpperCamelCase : Dict =DiffusionPipeline.numpy_to_pil(lowerCamelCase__ )[0] return { "prompt": "An anime racoon running a marathon", "image": input_image, "generator": generator, "num_inference_steps": 2, "output_type": "np", } @skip_mps def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Optional[int] ='cpu' # ensure determinism for the device-dependent torch.Generator __UpperCamelCase : List[str] =self.get_dummy_components() __UpperCamelCase : Union[str, Any] =StableUnCLIPImgaImgPipeline(**lowerCamelCase__ ) __UpperCamelCase : Tuple =sd_pipe.to(lowerCamelCase__ ) sd_pipe.set_progress_bar_config(disable=lowerCamelCase__ ) __UpperCamelCase : Tuple =self.get_dummy_inputs(lowerCamelCase__ ) inputs.update({'image_embeds': None} ) __UpperCamelCase : Optional[int] =sd_pipe(**lowerCamelCase__ ).images __UpperCamelCase : int =image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __UpperCamelCase : Union[str, Any] =np.array([0.3_872, 0.7_224, 0.5_601, 0.4_741, 0.6_872, 0.5_814, 0.4_636, 0.3_867, 0.5_078] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3 def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Optional[Any] =torch_device in ['cpu', 'mps'] self._test_attention_slicing_forward_pass(test_max_difference=lowerCamelCase__ ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Tuple =torch_device in ['cpu', 'mps'] self._test_inference_batch_single_identical(test_max_difference=lowerCamelCase__ ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def __lowercase ( self ): """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(test_max_difference=lowerCamelCase__ ) @slow @require_torch_gpu class __A ( unittest.TestCase ): """simple docstring""" def __lowercase ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Union[str, Any] =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) __UpperCamelCase : List[str] =load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy' ) __UpperCamelCase : str =StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-l-img2img' , torch_dtype=torch.floataa ) pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __UpperCamelCase : Optional[Any] =torch.Generator(device='cpu' ).manual_seed(0 ) __UpperCamelCase : Union[str, Any] =pipe(lowerCamelCase__ , 'anime turle' , generator=lowerCamelCase__ , output_type='np' ) __UpperCamelCase : Union[str, Any] =output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(lowerCamelCase__ , lowerCamelCase__ ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Union[str, Any] =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) __UpperCamelCase : int =load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy' ) __UpperCamelCase : Union[str, Any] =StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-h-img2img' , torch_dtype=torch.floataa ) pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __UpperCamelCase : int =torch.Generator(device='cpu' ).manual_seed(0 ) __UpperCamelCase : Union[str, Any] =pipe(lowerCamelCase__ , 'anime turle' , generator=lowerCamelCase__ , output_type='np' ) __UpperCamelCase : Dict =output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(lowerCamelCase__ , lowerCamelCase__ ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Optional[int] =load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() __UpperCamelCase : int =StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-h-img2img' , torch_dtype=torch.floataa ) __UpperCamelCase : Dict =pipe.to(lowerCamelCase__ ) pipe.set_progress_bar_config(disable=lowerCamelCase__ ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() __UpperCamelCase : Tuple =pipe( lowerCamelCase__ , 'anime turtle' , num_inference_steps=2 , output_type='np' , ) __UpperCamelCase : List[Any] =torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
71
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __lowerCAmelCase = {'''configuration_swin''': ['''SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SwinConfig''', '''SwinOnnxConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''SWIN_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SwinForImageClassification''', '''SwinForMaskedImageModeling''', '''SwinModel''', '''SwinPreTrainedModel''', '''SwinBackbone''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFSwinForImageClassification''', '''TFSwinForMaskedImageModeling''', '''TFSwinModel''', '''TFSwinPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_swin import SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinConfig, SwinOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swin import ( SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, SwinBackbone, SwinForImageClassification, SwinForMaskedImageModeling, SwinModel, SwinPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_swin import ( TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, TFSwinForImageClassification, TFSwinForMaskedImageModeling, TFSwinModel, TFSwinPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
89
0
"""simple docstring""" import collections import importlib.util import os import re from pathlib import Path lowerCAmelCase__ = '''src/transformers''' # Matches is_xxx_available() lowerCAmelCase__ = re.compile(R'''is\_([a-z_]*)_available()''') # Catches a one-line _import_struct = {xxx} lowerCAmelCase__ = re.compile(R'''^_import_structure\s+=\s+\{([^\}]+)\}''') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] lowerCAmelCase__ = re.compile(R'''\s+"\S*":\s+\[([^\]]*)\]''') # Catches a line if not is_foo_available lowerCAmelCase__ = re.compile(R'''^\s*if\s+not\s+is\_[a-z_]*\_available\(\)''') # Catches a line _import_struct["bla"].append("foo") lowerCAmelCase__ = re.compile(R'''^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)''') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] lowerCAmelCase__ = re.compile(R'''^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]''') # Catches a line with an object between quotes and a comma: "MyModel", lowerCAmelCase__ = re.compile('''^\s+"([^"]+)",''') # Catches a line with objects between brackets only: ["foo", "bar"], lowerCAmelCase__ = re.compile('''^\s+\[([^\]]+)\]''') # Catches a line with from foo import bar, bla, boo lowerCAmelCase__ = re.compile(R'''\s+from\s+\S*\s+import\s+([^\(\s].*)\n''') # Catches a line with try: lowerCAmelCase__ = re.compile(R'''^\s*try:''') # Catches a line with else: lowerCAmelCase__ = re.compile(R'''^\s*else:''') def snake_case_ ( A_ : Union[str, Any] ): '''simple docstring''' if _re_test_backend.search(A_ ) is None: return None _lowerCamelCase : List[Any] = [b[0] for b in _re_backend.findall(A_ )] backends.sort() return "_and_".join(A_ ) def snake_case_ ( A_ : Union[str, Any] ): '''simple docstring''' with open(A_, '''r''', encoding='''utf-8''', newline='''\n''' ) as f: _lowerCamelCase : Any = f.readlines() _lowerCamelCase : Tuple = 0 while line_index < len(A_ ) and not lines[line_index].startswith('''_import_structure = {''' ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(A_ ): return None # First grab the objects without a specific backend in _import_structure _lowerCamelCase : int = [] while not lines[line_index].startswith('''if TYPE_CHECKING''' ) and find_backend(lines[line_index] ) is None: _lowerCamelCase : Any = lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(A_ ): _lowerCamelCase : Optional[int] = _re_one_line_import_struct.search(A_ ).groups()[0] _lowerCamelCase : Optional[Any] = re.findall('''\[([^\]]+)\]''', A_ ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(''', ''' )] ) line_index += 1 continue _lowerCamelCase : Union[str, Any] = _re_import_struct_key_value.search(A_ ) if single_line_import_search is not None: _lowerCamelCase : Tuple = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(''', ''' ) if len(A_ ) > 0] objects.extend(A_ ) elif line.startswith(''' ''' * 8 + '''"''' ): objects.append(line[9:-3] ) line_index += 1 _lowerCamelCase : Dict = {'''none''': objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith('''if TYPE_CHECKING''' ): # If the line is an if not is_backend_available, we grab all objects associated. _lowerCamelCase : Optional[Any] = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: _lowerCamelCase : Optional[int] = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 _lowerCamelCase : Union[str, Any] = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(''' ''' * 4 ): _lowerCamelCase : int = lines[line_index] if _re_import_struct_add_one.search(A_ ) is not None: objects.append(_re_import_struct_add_one.search(A_ ).groups()[0] ) elif _re_import_struct_add_many.search(A_ ) is not None: _lowerCamelCase : Optional[Any] = _re_import_struct_add_many.search(A_ ).groups()[0].split(''', ''' ) _lowerCamelCase : int = [obj[1:-1] for obj in imports if len(A_ ) > 0] objects.extend(A_ ) elif _re_between_brackets.search(A_ ) is not None: _lowerCamelCase : Tuple = _re_between_brackets.search(A_ ).groups()[0].split(''', ''' ) _lowerCamelCase : List[Any] = [obj[1:-1] for obj in imports if len(A_ ) > 0] objects.extend(A_ ) elif _re_quote_object.search(A_ ) is not None: objects.append(_re_quote_object.search(A_ ).groups()[0] ) elif line.startswith(''' ''' * 8 + '''"''' ): objects.append(line[9:-3] ) elif line.startswith(''' ''' * 12 + '''"''' ): objects.append(line[13:-3] ) line_index += 1 _lowerCamelCase : List[str] = objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend _lowerCamelCase : Dict = [] while ( line_index < len(A_ ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith('''else''' ) ): _lowerCamelCase : int = lines[line_index] _lowerCamelCase : Dict = _re_import.search(A_ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(''', ''' ) ) elif line.startswith(''' ''' * 8 ): objects.append(line[8:-2] ) line_index += 1 _lowerCamelCase : Any = {'''none''': objects} # Let's continue with backend-specific objects while line_index < len(A_ ): # If the line is an if is_backend_available, we grab all objects associated. _lowerCamelCase : Any = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: _lowerCamelCase : str = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 _lowerCamelCase : Optional[int] = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(''' ''' * 8 ): _lowerCamelCase : Optional[Any] = lines[line_index] _lowerCamelCase : Optional[int] = _re_import.search(A_ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(''', ''' ) ) elif line.startswith(''' ''' * 12 ): objects.append(line[12:-2] ) line_index += 1 _lowerCamelCase : List[Any] = objects else: line_index += 1 return import_dict_objects, type_hint_objects def snake_case_ ( A_ : Tuple, A_ : List[str] ): '''simple docstring''' def find_duplicates(A_ : List[str] ): return [k for k, v in collections.Counter(A_ ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] _lowerCamelCase : Tuple = [] for key in import_dict_objects.keys(): _lowerCamelCase : Optional[Any] = find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(F'''Duplicate _import_structure definitions for: {duplicate_imports}''' ) _lowerCamelCase : Optional[Any] = find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(F'''Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}''' ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): _lowerCamelCase : Dict = '''base imports''' if key == '''none''' else F'''{key} backend''' errors.append(F'''Differences for {name}:''' ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(F''' {a} in TYPE_HINT but not in _import_structure.''' ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(F''' {a} in _import_structure but not in TYPE_HINT.''' ) return errors def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : Optional[int] = [] for root, _, files in os.walk(A_ ): if "__init__.py" in files: _lowerCamelCase : Optional[Any] = os.path.join(A_, '''__init__.py''' ) _lowerCamelCase : Optional[Any] = parse_init(A_ ) if objects is not None: _lowerCamelCase : List[Any] = analyze_results(*A_ ) if len(A_ ) > 0: _lowerCamelCase : List[str] = F'''Problem in {fname}, both halves do not define the same objects.\n{errors[0]}''' failures.append('''\n'''.join(A_ ) ) if len(A_ ) > 0: raise ValueError('''\n\n'''.join(A_ ) ) def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : Tuple = [] for path, directories, files in os.walk(A_ ): for folder in directories: # Ignore private modules if folder.startswith('''_''' ): directories.remove(A_ ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(A_ ) / folder).glob('''*.py''' ) ) ) == 0: continue _lowerCamelCase : Tuple = str((Path(A_ ) / folder).relative_to(A_ ) ) _lowerCamelCase : List[str] = short_path.replace(os.path.sep, '''.''' ) submodules.append(A_ ) for fname in files: if fname == "__init__.py": continue _lowerCamelCase : Dict = str((Path(A_ ) / fname).relative_to(A_ ) ) _lowerCamelCase : Union[str, Any] = short_path.replace('''.py''', '''''' ).replace(os.path.sep, '''.''' ) if len(submodule.split('''.''' ) ) == 1: submodules.append(A_ ) return submodules lowerCAmelCase__ = [ '''convert_pytorch_checkpoint_to_tf2''', '''modeling_flax_pytorch_utils''', ] def snake_case_ ( ): '''simple docstring''' _lowerCamelCase : Any = importlib.util.spec_from_file_location( '''transformers''', os.path.join(A_, '''__init__.py''' ), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) _lowerCamelCase : Any = spec.loader.load_module() _lowerCamelCase : Any = [ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(A_ ) > 0: _lowerCamelCase : Dict = '''\n'''.join(F'''- {module}''' for module in module_not_registered ) raise ValueError( '''The following submodules are not properly registered in the main init of Transformers:\n''' F'''{list_of_modules}\n''' '''Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value.''' ) if __name__ == "__main__": check_all_inits() check_submodules()
72
'''simple docstring''' import unittest from transformers import BarthezTokenizer, BarthezTokenizerFast, BatchEncoding from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers @require_sentencepiece @slow # see https://github.com/huggingface/transformers/issues/11457 class __magic_name__ ( _UpperCamelCase , unittest.TestCase ): lowerCAmelCase : Optional[int] = BarthezTokenizer lowerCAmelCase : int = BarthezTokenizerFast lowerCAmelCase : Dict = True lowerCAmelCase : str = True def __lowercase ( self : List[Any] ): super().setUp() _a : List[Any] = BarthezTokenizerFast.from_pretrained('moussaKam/mbarthez' ) tokenizer.save_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ,legacy_format=_UpperCAmelCase ) _a : Union[str, Any] = tokenizer def __lowercase ( self : Tuple ): _a : Optional[Any] = '<pad>' _a : List[Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_UpperCAmelCase ) ,_UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_UpperCAmelCase ) ,_UpperCAmelCase ) def __lowercase ( self : str ): _a : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] ,'<s>' ) self.assertEqual(vocab_keys[1] ,'<pad>' ) self.assertEqual(vocab_keys[-1] ,'<mask>' ) self.assertEqual(len(_UpperCAmelCase ) ,101122 ) def __lowercase ( self : Dict ): self.assertEqual(self.get_tokenizer().vocab_size ,101122 ) @require_torch def __lowercase ( self : Dict ): _a : Any = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] _a : Dict = [0, 57, 3018, 70307, 91, 2] _a : Dict = self.tokenizer( _UpperCAmelCase ,max_length=len(_UpperCAmelCase ) ,padding=_UpperCAmelCase ,truncation=_UpperCAmelCase ,return_tensors='pt' ) self.assertIsInstance(_UpperCAmelCase ,_UpperCAmelCase ) self.assertEqual((2, 6) ,batch.input_ids.shape ) self.assertEqual((2, 6) ,batch.attention_mask.shape ) _a : Tuple = batch.input_ids.tolist()[0] self.assertListEqual(_UpperCAmelCase ,_UpperCAmelCase ) def __lowercase ( self : Optional[Any] ): if not self.test_rust_tokenizer: return _a : str = self.get_tokenizer() _a : List[str] = self.get_rust_tokenizer() _a : Dict = 'I was born in 92000, and this is falsé.' _a : List[Any] = tokenizer.tokenize(_UpperCAmelCase ) _a : Tuple = rust_tokenizer.tokenize(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase ,_UpperCAmelCase ) _a : Optional[Any] = tokenizer.encode(_UpperCAmelCase ,add_special_tokens=_UpperCAmelCase ) _a : Optional[int] = rust_tokenizer.encode(_UpperCAmelCase ,add_special_tokens=_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase ,_UpperCAmelCase ) _a : Union[str, Any] = self.get_rust_tokenizer() _a : Any = tokenizer.encode(_UpperCAmelCase ) _a : Optional[int] = rust_tokenizer.encode(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase ,_UpperCAmelCase ) @slow def __lowercase ( self : Optional[int] ): # fmt: off _a : Optional[int] = {'input_ids': [[0, 490, 14328, 4507, 354, 47, 43669, 95, 25, 78117, 20215, 19779, 190, 22, 400, 4, 35343, 80310, 603, 86, 24937, 105, 33438, 94762, 196, 39642, 7, 15, 15933, 173, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 10534, 87, 25, 66, 3358, 196, 55289, 8, 82961, 81, 2204, 75203, 7, 15, 763, 12956, 216, 178, 14328, 9595, 1377, 69693, 7, 448, 71021, 196, 18106, 1437, 13974, 108, 9083, 4, 49315, 7, 39, 86, 1326, 2793, 46333, 4, 448, 196, 74588, 7, 49315, 7, 39, 21, 822, 38470, 74, 21, 66723, 62480, 8, 22050, 5, 2]], '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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # moussaKam/mbarthez is a french model. So we also use french texts. _a : Optional[Any] = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=_UpperCAmelCase ,model_name='moussaKam/mbarthez' ,revision='c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6' ,sequences=_UpperCAmelCase ,)
89
0
from math import isclose, sqrt def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> tuple[float, float, float]: __lowerCamelCase : Tuple = point_y / 4 / point_x __lowerCamelCase : Tuple = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) __lowerCamelCase : List[Any] = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) __lowerCamelCase : int = (sa - ca * incoming_gradient) / (ca + sa * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 __lowerCamelCase : Any = outgoing_gradient**2 + 4 __lowerCamelCase : Optional[int] = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) __lowerCamelCase : str = (point_y - outgoing_gradient * point_x) ** 2 - 1_0_0 __lowerCamelCase : str = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) __lowerCamelCase : Optional[Any] = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term ) ) / (2 * quadratic_term) # two solutions, one of which is our input point __lowerCamelCase : Optional[Any] = x_minus if isclose(lowerCamelCase__ , lowerCamelCase__ ) else x_plus __lowerCamelCase : Tuple = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ = 1.4 , lowerCamelCase__ = -9.6 ) -> int: __lowerCamelCase : int = 0 __lowerCamelCase : float = first_x_coord __lowerCamelCase : float = first_y_coord __lowerCamelCase : float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): __lowerCamelCase , __lowerCamelCase , __lowerCamelCase : Any = next_point(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) num_reflections += 1 return num_reflections if __name__ == "__main__": print(F"""{solution() = }""")
73
'''simple docstring''' import subprocess import sys from transformers import BertConfig, BertModel, BertTokenizer, pipeline from transformers.testing_utils import TestCasePlus, require_torch class __magic_name__ ( _UpperCamelCase ): @require_torch def __lowercase ( self : Tuple ): # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched _a : Optional[int] = '\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n ' _a : List[str] = '\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n ' _a : Tuple = '\nimport socket\ndef offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn\'t access internet")\nsocket.socket = offline_socket\n ' # Force fetching the files so that we can use the cache _a : List[Any] = 'hf-internal-testing/tiny-random-bert' BertConfig.from_pretrained(_UpperCAmelCase ) BertModel.from_pretrained(_UpperCAmelCase ) BertTokenizer.from_pretrained(_UpperCAmelCase ) pipeline(task='fill-mask' ,model=_UpperCAmelCase ) # baseline - just load from_pretrained with normal network _a : Optional[int] = [sys.executable, '-c', '\n'.join([load, run, mock] )] # should succeed _a : Tuple = self.get_env() # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files _a : int = '1' _a : List[Any] = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) @require_torch def __lowercase ( self : Any ): # python one-liner segments # this must be loaded before socket.socket is monkey-patched _a : Dict = '\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n ' _a : Optional[int] = '\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n ' _a : Optional[Any] = '\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet")\nsocket.socket = offline_socket\n ' # Force fetching the files so that we can use the cache _a : int = 'hf-internal-testing/tiny-random-bert' BertConfig.from_pretrained(_UpperCAmelCase ) BertModel.from_pretrained(_UpperCAmelCase ) BertTokenizer.from_pretrained(_UpperCAmelCase ) pipeline(task='fill-mask' ,model=_UpperCAmelCase ) # baseline - just load from_pretrained with normal network _a : Optional[int] = [sys.executable, '-c', '\n'.join([load, run, mock] )] # should succeed _a : str = self.get_env() _a : Optional[Any] = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) @require_torch def __lowercase ( self : List[str] ): # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched _a : Union[str, Any] = '\nfrom transformers import BertConfig, BertModel, BertTokenizer\n ' _a : Optional[Any] = '\nmname = "hf-internal-testing/tiny-random-bert-sharded"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nprint("success")\n ' _a : str = '\nimport socket\ndef offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled")\nsocket.socket = offline_socket\n ' # baseline - just load from_pretrained with normal network _a : Optional[Any] = [sys.executable, '-c', '\n'.join([load, run] )] # should succeed _a : Dict = self.get_env() _a : int = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) # next emulate no network _a : List[Any] = [sys.executable, '-c', '\n'.join([load, mock, run] )] # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this. # env["TRANSFORMERS_OFFLINE"] = "0" # result = subprocess.run(cmd, env=env, check=False, capture_output=True) # self.assertEqual(result.returncode, 1, result.stderr) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files _a : int = '1' _a : Any = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) @require_torch def __lowercase ( self : int ): _a : Optional[Any] = '\nfrom transformers import pipeline\n ' _a : str = '\nmname = "hf-internal-testing/tiny-random-bert"\npipe = pipeline(model=mname)\n ' _a : List[str] = '\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled")\nsocket.socket = offline_socket\n ' _a : List[Any] = self.get_env() _a : Dict = '1' _a : Dict = [sys.executable, '-c', '\n'.join([load, mock, run] )] _a : str = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,1 ,result.stderr ) self.assertIn( 'You cannot infer task automatically within `pipeline` when using offline mode' ,result.stderr.decode().replace('\n' ,'' ) ,) @require_torch def __lowercase ( self : int ): _a : Optional[int] = '\nfrom transformers import AutoModel\n ' _a : List[Any] = '\nmname = "hf-internal-testing/test_dynamic_model"\nAutoModel.from_pretrained(mname, trust_remote_code=True)\nprint("success")\n ' # baseline - just load from_pretrained with normal network _a : Union[str, Any] = [sys.executable, '-c', '\n'.join([load, run] )] # should succeed _a : Tuple = self.get_env() _a : List[str] = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files _a : Optional[Any] = '1' _a : Any = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() )
89
0
"""simple docstring""" 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 = '''▁''' _lowercase = {'''vocab_file''': '''spiece.model'''} _lowercase = { '''vocab_file''': {'''google/pegasus-xsum''': '''https://huggingface.co/google/pegasus-xsum/resolve/main/spiece.model'''} } _lowercase = { '''google/pegasus-xsum''': 5_12, } _lowercase = logging.get_logger(__name__) class lowerCAmelCase_ ( _lowercase ): '''simple docstring''' _lowerCamelCase: List[str] = VOCAB_FILES_NAMES _lowerCamelCase: Optional[Any] = VOCAB_FILES_NAMES _lowerCamelCase: Union[str, Any] = PRETRAINED_VOCAB_FILES_MAP _lowerCamelCase: Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _lowerCamelCase: str = ['''input_ids''', '''attention_mask'''] def __init__( self : Union[str, Any] ,A_ : int ,A_ : List[Any]="<pad>" ,A_ : List[str]="</s>" ,A_ : Any="<unk>" ,A_ : Union[str, Any]="<mask_2>" ,A_ : int="<mask_1>" ,A_ : str=None ,A_ : List[Any]=103 ,A_ : Optional[Dict[str, Any]] = None ,**A_ : List[Any] ,) -> None: A = offset if additional_special_tokens is not None: if not isinstance(A_ ,A_ ): raise TypeError( F'additional_special_tokens should be of type {type(A_ )}, but is' F' {type(A_ )}' ) A = ( ([mask_token_sent] + additional_special_tokens) if mask_token_sent not in additional_special_tokens and mask_token_sent is not None else additional_special_tokens ) # fill additional tokens with ..., <unk_token_102> in case not all additional tokens are already taken additional_special_tokens_extended += [ F'<unk_{i}>' for i in range(len(A_ ) ,self.offset - 1 ) ] if len(set(A_ ) ) != len(A_ ): raise ValueError( 'Please make sure that the provided additional_special_tokens do not contain an incorrectly' F' shifted list of <unk_x> tokens. Found {additional_special_tokens_extended}.' ) A = additional_special_tokens_extended else: A = [mask_token_sent] if mask_token_sent is not None else [] additional_special_tokens += [F'<unk_{i}>' for i in range(2 ,self.offset )] A = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=A_ ,unk_token=A_ ,mask_token=A_ ,pad_token=A_ ,mask_token_sent=A_ ,offset=A_ ,additional_special_tokens=A_ ,sp_model_kwargs=self.sp_model_kwargs ,**A_ ,) A = mask_token_sent A = vocab_file A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(A_ ) # add special tokens to encoder dict A = { 0: self.pad_token, 1: self.eos_token, } if self.mask_token_sent is not None: self.encoder.update( { 2: self.mask_token_sent, 3: self.mask_token, } ) if self.offset > 0: # entries 2-104 are only used for pretraining and called <mask_1>, <mask_2>, unk_2, ...unk_102 # mask_token_sent is already added to list -> so start at 1 self.encoder.update({i + 3: additional_special_tokens[i] for i in range(1 ,self.offset - 1 )} ) A = {v: k for k, v in self.encoder.items()} @property def _SCREAMING_SNAKE_CASE ( self : str ) -> int: return len(self.sp_model ) + self.offset def _SCREAMING_SNAKE_CASE ( self : List[str] ) -> Dict[str, int]: A = {self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ) -> Optional[int]: A = self.__dict__.copy() A = None return state def __setstate__( self : str ,A_ : Tuple ) -> List[str]: A = d # for backward compatibility if not hasattr(self ,'sp_model_kwargs' ): A = {} A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def _SCREAMING_SNAKE_CASE ( self : str ,A_ : str ) -> List[str]: return self.sp_model.encode(A_ ,out_type=A_ ) def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : str ) -> int: if token in self.decoder: return self.decoder[token] elif token in self.added_tokens_decoder: return self.added_tokens_decoder[token] A = self.sp_model.piece_to_id(A_ ) return sp_id + self.offset def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : int ) -> str: if index in self.encoder: return self.encoder[index] elif index in self.added_tokens_encoder: return self.added_tokens_encoder[index] else: A = self.sp_model.IdToPiece(index - self.offset ) return token def _SCREAMING_SNAKE_CASE ( self : int ,A_ : int ) -> Any: A = [] A = '' 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(A_ ) + token A = [] else: current_sub_tokens.append(A_ ) out_string += self.sp_model.decode(A_ ) return out_string.strip() def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : List[str]=False ) -> Optional[Any]: return 1 def _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : Dict ) -> Optional[int]: A = set(self.all_special_ids ) # call it once instead of inside list comp all_special_ids.remove(self.unk_token_id ) # <unk> is only sometimes special return [1 if x in all_special_ids else 0 for x in seq] def _SCREAMING_SNAKE_CASE ( self : Any ,A_ : List ,A_ : Optional[List] = None ,A_ : bool = False ) -> List[int]: if already_has_special_tokens: return self._special_token_mask(A_ ) elif token_ids_a is None: return self._special_token_mask(A_ ) + [1] else: return self._special_token_mask(token_ids_a + token_ids_a ) + [1] def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] ,A_ : Any ,A_ : Optional[int]=None ) -> List[int]: 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 _SCREAMING_SNAKE_CASE ( self : List[Any] ,A_ : str ,A_ : Optional[str] = None ) -> Tuple[str]: if not os.path.isdir(A_ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return A = 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_ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,A_ ) elif not os.path.isfile(self.vocab_file ): with open(A_ ,'wb' ) as fi: A = self.sp_model.serialized_model_proto() fi.write(A_ ) return (out_vocab_file,)
74
'''simple docstring''' def __lowerCamelCase ( ) -> Tuple: for n in range(1 , 1000000 ): yield n * (n + 1) // 2 def __lowerCamelCase ( lowerCAmelCase_ ) -> List[Any]: _a : Any = 1 _a : Tuple = 2 while i * i <= n: _a : Tuple = 0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def __lowerCamelCase ( ) -> str: return next(i for i in triangle_number_generator() if count_divisors(lowerCAmelCase_ ) > 500 ) if __name__ == "__main__": print(solution())
89
0
'''simple docstring''' import fire from utils import calculate_rouge, save_json def a_ ( __snake_case : int , __snake_case : Optional[int] , __snake_case : Optional[Any]=None , **__snake_case : Union[str, Any] ) -> Dict: """simple docstring""" lowerCamelCase_ =[x.strip() for x in open(__snake_case ).readlines()] lowerCamelCase_ =[x.strip() for x in open(__snake_case ).readlines()][: len(__snake_case )] lowerCamelCase_ =calculate_rouge(__snake_case , __snake_case , **__snake_case ) if save_path is not None: save_json(__snake_case , __snake_case , indent=__snake_case ) return metrics # these print nicely if __name__ == "__main__": fire.Fire(calculate_rouge_path)
75
'''simple docstring''' import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class __magic_name__ ( _UpperCamelCase ): def __init__( self : Optional[int] ,_UpperCAmelCase : Union[str, "sqlalchemy.sql.Selectable"] ,_UpperCAmelCase : Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] ,_UpperCAmelCase : Optional[Features] = None ,_UpperCAmelCase : str = None ,_UpperCAmelCase : bool = False ,**_UpperCAmelCase : Dict ,): super().__init__(features=_UpperCAmelCase ,cache_dir=_UpperCAmelCase ,keep_in_memory=_UpperCAmelCase ,**_UpperCAmelCase ) _a : Tuple = Sql( cache_dir=_UpperCAmelCase ,features=_UpperCAmelCase ,sql=_UpperCAmelCase ,con=_UpperCAmelCase ,**_UpperCAmelCase ,) def __lowercase ( self : Dict ): _a : Optional[Any] = None _a : Dict = None _a : Dict = None _a : Optional[int] = None self.builder.download_and_prepare( download_config=_UpperCAmelCase ,download_mode=_UpperCAmelCase ,verification_mode=_UpperCAmelCase ,base_path=_UpperCAmelCase ,) # Build dataset for splits _a : List[str] = self.builder.as_dataset( split='train' ,verification_mode=_UpperCAmelCase ,in_memory=self.keep_in_memory ) return dataset class __magic_name__ : def __init__( self : Optional[int] ,_UpperCAmelCase : Dataset ,_UpperCAmelCase : str ,_UpperCAmelCase : Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] ,_UpperCAmelCase : Optional[int] = None ,_UpperCAmelCase : Optional[int] = None ,**_UpperCAmelCase : Dict ,): if num_proc is not None and num_proc <= 0: raise ValueError(F"""num_proc {num_proc} must be an integer > 0.""" ) _a : Dict = dataset _a : List[Any] = name _a : Tuple = con _a : Union[str, Any] = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE _a : List[Any] = num_proc _a : Tuple = to_sql_kwargs def __lowercase ( self : List[Any] ): _a : Tuple = self.to_sql_kwargs.pop('sql' ,_UpperCAmelCase ) _a : str = self.to_sql_kwargs.pop('con' ,_UpperCAmelCase ) _a : Optional[Any] = self.to_sql_kwargs.pop('index' ,_UpperCAmelCase ) _a : Any = self._write(index=_UpperCAmelCase ,**self.to_sql_kwargs ) return written def __lowercase ( self : Optional[int] ,_UpperCAmelCase : Dict ): _a , _a , _a : Any = args _a : Tuple = {**to_sql_kwargs, 'if_exists': 'append'} if offset > 0 else to_sql_kwargs _a : Dict = query_table( table=self.dataset.data ,key=slice(_UpperCAmelCase ,offset + self.batch_size ) ,indices=self.dataset._indices ,) _a : Tuple = batch.to_pandas() _a : Dict = df.to_sql(self.name ,self.con ,index=_UpperCAmelCase ,**_UpperCAmelCase ) return num_rows or len(_UpperCAmelCase ) def __lowercase ( self : int ,_UpperCAmelCase : Optional[int] ,**_UpperCAmelCase : List[Any] ): _a : Union[str, Any] = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 ,len(self.dataset ) ,self.batch_size ) ,unit='ba' ,disable=not logging.is_progress_bar_enabled() ,desc='Creating SQL from Arrow format' ,): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: _a , _a : List[Any] = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql ,[(offset, index, to_sql_kwargs) for offset in range(0 ,_UpperCAmelCase ,_UpperCAmelCase )] ,) ,total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size ,unit='ba' ,disable=not logging.is_progress_bar_enabled() ,desc='Creating SQL from Arrow format' ,): written += num_rows return written
89
0
from ..utils import DummyObject, requires_backends class _UpperCamelCase ( metaclass=__A ): '''simple docstring''' lowerCamelCase__ =['speech'] def __init__( self : List[Any] , *a : Tuple , **a : Union[str, Any] ) -> Tuple: """simple docstring""" requires_backends(self , ["speech"] ) class _UpperCamelCase ( metaclass=__A ): '''simple docstring''' lowerCamelCase__ =['speech'] def __init__( self : Optional[int] , *a : int , **a : List[str] ) -> Union[str, Any]: """simple docstring""" requires_backends(self , ["speech"] )
76
'''simple docstring''' from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> np.ndarray: _a : Union[str, Any] = cva.getAffineTransform(lowerCAmelCase_ , lowerCAmelCase_ ) return cva.warpAffine(lowerCAmelCase_ , lowerCAmelCase_ , (rows, cols) ) if __name__ == "__main__": # read original image __lowerCAmelCase = cva.imread( str(Path(__file__).resolve().parent.parent / '''image_data''' / '''lena.jpg''') ) # turn image in gray scale value __lowerCAmelCase = cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape __lowerCAmelCase , __lowerCAmelCase = gray_img.shape # set different points to rotate image __lowerCAmelCase = np.array([[50, 50], [200, 50], [50, 200]], np.floataa) __lowerCAmelCase = np.array([[10, 100], [200, 50], [100, 250]], np.floataa) __lowerCAmelCase = np.array([[50, 50], [150, 50], [120, 200]], np.floataa) __lowerCAmelCase = np.array([[10, 100], [80, 50], [180, 250]], np.floataa) # add all rotated images in a list __lowerCAmelCase = [ gray_img, get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), ] # plot different image rotations __lowerCAmelCase = plt.figure(1) __lowerCAmelCase = ['''Original''', '''Rotation 1''', '''Rotation 2''', '''Rotation 3'''] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, '''gray''') plt.title(titles[i]) plt.axis('''off''') plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
89
0
"""simple docstring""" import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class UpperCAmelCase_ ( ctypes.Structure): # _fields is a specific attr expected by ctypes lowerCamelCase__ : Any = [("size", ctypes.c_int), ("visible", ctypes.c_byte)] def a_ ( ): '''simple docstring''' if os.name == "nt": lowercase__ : Any = CursorInfo() lowercase__ : Tuple = ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(_lowerCAmelCase , ctypes.byref(_lowerCAmelCase ) ) lowercase__ : List[Any] = False ctypes.windll.kernelaa.SetConsoleCursorInfo(_lowerCAmelCase , ctypes.byref(_lowerCAmelCase ) ) elif os.name == "posix": sys.stdout.write('\033[?25l' ) sys.stdout.flush() def a_ ( ): '''simple docstring''' if os.name == "nt": lowercase__ : Dict = CursorInfo() lowercase__ : List[str] = ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(_lowerCAmelCase , ctypes.byref(_lowerCAmelCase ) ) lowercase__ : int = True ctypes.windll.kernelaa.SetConsoleCursorInfo(_lowerCAmelCase , ctypes.byref(_lowerCAmelCase ) ) elif os.name == "posix": sys.stdout.write('\033[?25h' ) sys.stdout.flush() @contextmanager def a_ ( ): '''simple docstring''' try: hide_cursor() yield finally: show_cursor()
77
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCAmelCase = { '''configuration_bigbird_pegasus''': [ '''BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BigBirdPegasusConfig''', '''BigBirdPegasusOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BigBirdPegasusForCausalLM''', '''BigBirdPegasusForConditionalGeneration''', '''BigBirdPegasusForQuestionAnswering''', '''BigBirdPegasusForSequenceClassification''', '''BigBirdPegasusModel''', '''BigBirdPegasusPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP, BigBirdPegasusConfig, BigBirdPegasusOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST, BigBirdPegasusForCausalLM, BigBirdPegasusForConditionalGeneration, BigBirdPegasusForQuestionAnswering, BigBirdPegasusForSequenceClassification, BigBirdPegasusModel, BigBirdPegasusPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
89
0
"""simple docstring""" import os import numpy import onnx def _lowerCAmelCase ( lowercase_ , lowercase_ ): UpperCAmelCase = a.name UpperCAmelCase = b.name UpperCAmelCase = '' UpperCAmelCase = '' UpperCAmelCase = a == b UpperCAmelCase = name_a UpperCAmelCase = name_b return res def _lowerCAmelCase ( lowercase_ , lowercase_ , lowercase_ ): for i, input_name in enumerate(node_proto.input ): if input_name == name: node_proto.input.insert(lowercase_ , lowercase_ ) node_proto.input.pop(i + 1 ) if node_proto.op_type == "If": _graph_replace_input_with(node_proto.attribute[0].g , lowercase_ , lowercase_ ) _graph_replace_input_with(node_proto.attribute[1].g , lowercase_ , lowercase_ ) if node_proto.op_type == "Loop": _graph_replace_input_with(node_proto.attribute[0].g , lowercase_ , lowercase_ ) def _lowerCAmelCase ( lowercase_ , lowercase_ , lowercase_ ): for n in graph_proto.node: _node_replace_input_with(lowercase_ , lowercase_ , lowercase_ ) def _lowerCAmelCase ( lowercase_ , lowercase_ , lowercase_ ): UpperCAmelCase = list(model.graph.initializer ) UpperCAmelCase = list(model_without_ext.graph.initializer ) for i, ref_i in ind_to_replace: assert inits_with_data[i].name == inits[i].name assert inits_with_data[ref_i].name == inits[ref_i].name assert i > ref_i UpperCAmelCase = inits[i].name UpperCAmelCase = inits[ref_i].name model_without_ext.graph.initializer.remove(inits[i] ) # for n in model.graph.node: _graph_replace_input_with(model_without_ext.graph , lowercase_ , lowercase_ ) def _lowerCAmelCase ( lowercase_ ): UpperCAmelCase = os.path.dirname(lowercase_ ) UpperCAmelCase = os.path.basename(lowercase_ ) UpperCAmelCase = onnx.load(os.path.join(lowercase_ , lowercase_ ) ) UpperCAmelCase = list(model.graph.initializer ) UpperCAmelCase = set() UpperCAmelCase = {} UpperCAmelCase = [] UpperCAmelCase = 0 for i in range(len(lowercase_ ) ): if i in dup_set: continue for j in range(i + 1 , len(lowercase_ ) ): if j in dup_set: continue if _is_equal_tensor_proto(inits[i] , inits[j] ): dup_set.add(lowercase_ ) dup_set.add(lowercase_ ) UpperCAmelCase = inits[j].data_type UpperCAmelCase = numpy.prod(inits[j].dims ) if dtype == 1: mem_size *= 4 elif dtype == 6: mem_size *= 4 elif dtype == 7 or dtype == 11: mem_size *= 8 else: print('unexpected data type: ' , lowercase_ ) total_reduced_size += mem_size UpperCAmelCase = inits[i].name UpperCAmelCase = inits[j].name if name_i in dup_map: dup_map[name_i].append(lowercase_ ) else: UpperCAmelCase = [name_j] ind_to_replace.append((j, i) ) print('total reduced size: ' , total_reduced_size / 1024 / 1024 / 1024 , 'GB' ) UpperCAmelCase = sorted(lowercase_ ) _remove_dup_initializers_from_model(lowercase_ , lowercase_ , lowercase_ ) UpperCAmelCase = 'optimized_' + model_file_name UpperCAmelCase = os.path.join(lowercase_ , lowercase_ ) onnx.save(lowercase_ , lowercase_ ) return new_model
78
'''simple docstring''' import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=1024 , lowerCAmelCase_=1024 , lowerCAmelCase_=False , **lowerCAmelCase_ ) -> List[Any]: _a : str = AutoTokenizer.from_pretrained(lowerCAmelCase_ ) _a : List[Any] = SeqaSeqDataset(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , type_path='train' , **lowerCAmelCase_ ) _a : List[str] = tok.pad_token_id def get_lens(lowerCAmelCase_ ): _a : Dict = tqdm( DataLoader(lowerCAmelCase_ , batch_size=512 , num_workers=8 , shuffle=lowerCAmelCase_ , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) _a : Union[str, Any] = [] for batch in dl: _a : Optional[Any] = batch['input_ids'].ne(lowerCAmelCase_ ).sum(1 ).tolist() _a : Optional[Any] = batch['labels'].ne(lowerCAmelCase_ ).sum(1 ).tolist() if consider_target: for src, tgt in zip(lowerCAmelCase_ , lowerCAmelCase_ ): max_lens.append(max(lowerCAmelCase_ , lowerCAmelCase_ ) ) else: max_lens.extend(lowerCAmelCase_ ) return max_lens _a : str = get_lens(lowerCAmelCase_ ) _a : Optional[int] = SeqaSeqDataset(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , type_path='val' , **lowerCAmelCase_ ) _a : Dict = get_lens(lowerCAmelCase_ ) pickle_save(lowerCAmelCase_ , train_ds.len_file ) pickle_save(lowerCAmelCase_ , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
89
0
'''simple docstring''' from collections import deque class _UpperCAmelCase : """simple docstring""" def __init__( self : List[Any] , __UpperCAmelCase : str , __UpperCAmelCase : int , __UpperCAmelCase : int ): '''simple docstring''' _A = process_name # process name _A = arrival_time # arrival time of the process # completion time of finished process or last interrupted time _A = arrival_time _A = burst_time # remaining burst time _A = 0 # total time of the process wait in ready queue _A = 0 # time from arrival time to completion time class _UpperCAmelCase : """simple docstring""" def __init__( self : str , __UpperCAmelCase : int , __UpperCAmelCase : list[int] , __UpperCAmelCase : deque[Process] , __UpperCAmelCase : int , ): '''simple docstring''' _A = number_of_queues # time slice of queues that round robin algorithm applied _A = time_slices # unfinished process is in this ready_queue _A = queue # current time _A = current_time # finished process is in this sequence queue _A = deque() def lowerCAmelCase ( self : Any ): '''simple docstring''' _A = [] for i in range(len(self.finish_queue ) ): sequence.append(self.finish_queue[i].process_name ) return sequence def lowerCAmelCase ( self : Any , __UpperCAmelCase : list[Process] ): '''simple docstring''' _A = [] for i in range(len(__UpperCAmelCase ) ): waiting_times.append(queue[i].waiting_time ) return waiting_times def lowerCAmelCase ( self : List[str] , __UpperCAmelCase : list[Process] ): '''simple docstring''' _A = [] for i in range(len(__UpperCAmelCase ) ): turnaround_times.append(queue[i].turnaround_time ) return turnaround_times def lowerCAmelCase ( self : Dict , __UpperCAmelCase : list[Process] ): '''simple docstring''' _A = [] for i in range(len(__UpperCAmelCase ) ): completion_times.append(queue[i].stop_time ) return completion_times def lowerCAmelCase ( self : Any , __UpperCAmelCase : deque[Process] ): '''simple docstring''' return [q.burst_time for q in queue] def lowerCAmelCase ( self : Optional[Any] , __UpperCAmelCase : Process ): '''simple docstring''' process.waiting_time += self.current_time - process.stop_time return process.waiting_time def lowerCAmelCase ( self : Tuple , __UpperCAmelCase : deque[Process] ): '''simple docstring''' _A = deque() # sequence deque of finished process while len(__UpperCAmelCase ) != 0: _A = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of current process self.update_waiting_time(__UpperCAmelCase ) # update current time self.current_time += cp.burst_time # finish the process and set the process's burst-time 0 _A = 0 # set the process's turnaround time because it is finished _A = self.current_time - cp.arrival_time # set the completion time _A = self.current_time # add the process to queue that has finished queue finished.append(__UpperCAmelCase ) self.finish_queue.extend(__UpperCAmelCase ) # add finished process to finish queue # FCFS will finish all remaining processes return finished def lowerCAmelCase ( self : Tuple , __UpperCAmelCase : deque[Process] , __UpperCAmelCase : int ): '''simple docstring''' _A = deque() # sequence deque of terminated process # just for 1 cycle and unfinished processes will go back to queue for _ in range(len(__UpperCAmelCase ) ): _A = ready_queue.popleft() # current process # if process's arrival time is later than current time, update current time if self.current_time < cp.arrival_time: self.current_time += cp.arrival_time # update waiting time of unfinished processes self.update_waiting_time(__UpperCAmelCase ) # if the burst time of process is bigger than time-slice if cp.burst_time > time_slice: # use CPU for only time-slice self.current_time += time_slice # update remaining burst time cp.burst_time -= time_slice # update end point time _A = self.current_time # locate the process behind the queue because it is not finished ready_queue.append(__UpperCAmelCase ) else: # use CPU for remaining burst time self.current_time += cp.burst_time # set burst time 0 because the process is finished _A = 0 # set the finish time _A = self.current_time # update the process' turnaround time because it is finished _A = self.current_time - cp.arrival_time # add the process to queue that has finished queue finished.append(__UpperCAmelCase ) self.finish_queue.extend(__UpperCAmelCase ) # add finished process to finish queue # return finished processes queue and remaining processes queue return finished, ready_queue def lowerCAmelCase ( self : str ): '''simple docstring''' for i in range(self.number_of_queues - 1 ): _A , _A = self.round_robin( self.ready_queue , self.time_slices[i] ) # the last queue has first_come_first_served algorithm self.first_come_first_served(self.ready_queue ) return self.finish_queue if __name__ == "__main__": import doctest lowerCamelCase_ = Process('''P1''', 0, 53) lowerCamelCase_ = Process('''P2''', 0, 17) lowerCamelCase_ = Process('''P3''', 0, 68) lowerCamelCase_ = Process('''P4''', 0, 24) lowerCamelCase_ = 3 lowerCamelCase_ = [17, 25] lowerCamelCase_ = deque([Pa, Pa, Pa, Pa]) if len(time_slices) != number_of_queues - 1: raise SystemExit(0) doctest.testmod(extraglobs={'''queue''': deque([Pa, Pa, Pa, Pa])}) lowerCamelCase_ = Process('''P1''', 0, 53) lowerCamelCase_ = Process('''P2''', 0, 17) lowerCamelCase_ = Process('''P3''', 0, 68) lowerCamelCase_ = Process('''P4''', 0, 24) lowerCamelCase_ = 3 lowerCamelCase_ = [17, 25] lowerCamelCase_ = deque([Pa, Pa, Pa, Pa]) lowerCamelCase_ = MLFQ(number_of_queues, time_slices, queue, 0) lowerCamelCase_ = mlfq.multi_level_feedback_queue() # print total waiting times of processes(P1, P2, P3, P4) print( F"""waiting time:\ \t\t\t{MLFQ.calculate_waiting_time(mlfq, [Pa, Pa, Pa, Pa])}""" ) # print completion times of processes(P1, P2, P3, P4) print( F"""completion time:\ \t\t{MLFQ.calculate_completion_time(mlfq, [Pa, Pa, Pa, Pa])}""" ) # print total turnaround times of processes(P1, P2, P3, P4) print( F"""turnaround time:\ \t\t{MLFQ.calculate_turnaround_time(mlfq, [Pa, Pa, Pa, Pa])}""" ) # print sequence of finished processes print( F"""sequence of finished processes:\ {mlfq.calculate_sequence_of_finish_queue()}""" )
79
'''simple docstring''' from typing import Any class __magic_name__ : def __init__( self : List[Any] ,_UpperCAmelCase : Any ): _a : List[Any] = data _a : Union[str, Any] = None def __repr__( self : Any ): return F"""Node({self.data})""" class __magic_name__ : def __init__( self : int ): _a : Tuple = None def __iter__( self : str ): _a : int = self.head while node: yield node.data _a : Union[str, Any] = node.next def __len__( self : Optional[Any] ): return sum(1 for _ in self ) def __repr__( self : str ): return "->".join([str(_UpperCAmelCase ) for item in self] ) def __getitem__( self : Tuple ,_UpperCAmelCase : int ): if not 0 <= index < len(self ): raise ValueError('list index out of range.' ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self : Union[str, Any] ,_UpperCAmelCase : int ,_UpperCAmelCase : Any ): if not 0 <= index < len(self ): raise ValueError('list index out of range.' ) _a : Any = self.head for _ in range(_UpperCAmelCase ): _a : Optional[Any] = current.next _a : Optional[int] = data def __lowercase ( self : Optional[int] ,_UpperCAmelCase : Any ): self.insert_nth(len(self ) ,_UpperCAmelCase ) def __lowercase ( self : Union[str, Any] ,_UpperCAmelCase : Any ): self.insert_nth(0 ,_UpperCAmelCase ) def __lowercase ( self : str ,_UpperCAmelCase : int ,_UpperCAmelCase : Any ): if not 0 <= index <= len(self ): raise IndexError('list index out of range' ) _a : int = Node(_UpperCAmelCase ) if self.head is None: _a : str = new_node elif index == 0: _a : List[str] = self.head # link new_node to head _a : Union[str, Any] = new_node else: _a : int = self.head for _ in range(index - 1 ): _a : Union[str, Any] = temp.next _a : List[str] = temp.next _a : Optional[int] = new_node def __lowercase ( self : Optional[int] ): # print every node data print(self ) def __lowercase ( self : str ): return self.delete_nth(0 ) def __lowercase ( self : str ): # delete from tail return self.delete_nth(len(self ) - 1 ) def __lowercase ( self : List[str] ,_UpperCAmelCase : int = 0 ): if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError('List index out of range.' ) _a : Optional[Any] = self.head # default first node if index == 0: _a : int = self.head.next else: _a : int = self.head for _ in range(index - 1 ): _a : str = temp.next _a : str = temp.next _a : int = temp.next.next return delete_node.data def __lowercase ( self : List[Any] ): return self.head is None def __lowercase ( self : Tuple ): _a : List[Any] = None _a : Tuple = self.head while current: # Store the current node's next node. _a : Dict = current.next # Make the current node's next point backwards _a : str = prev # Make the previous node be the current node _a : Tuple = current # Make the current node the next node (to progress iteration) _a : Optional[Any] = next_node # Return prev in order to put the head at the end _a : int = prev def __lowerCamelCase ( ) -> None: _a : List[str] = LinkedList() assert linked_list.is_empty() is True assert str(lowerCAmelCase_ ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(10 ): assert len(lowerCAmelCase_ ) == i linked_list.insert_nth(lowerCAmelCase_ , i + 1 ) assert str(lowerCAmelCase_ ) == "->".join(str(lowerCAmelCase_ ) for i in range(1 , 11 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(11 ) assert str(lowerCAmelCase_ ) == "->".join(str(lowerCAmelCase_ ) for i in range(0 , 12 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 10 assert linked_list.delete_tail() == 11 assert len(lowerCAmelCase_ ) == 9 assert str(lowerCAmelCase_ ) == "->".join(str(lowerCAmelCase_ ) for i in range(1 , 10 ) ) assert all(linked_list[i] == i + 1 for i in range(0 , 9 ) ) is True for i in range(0 , 9 ): _a : Union[str, Any] = -i assert all(linked_list[i] == -i for i in range(0 , 9 ) ) is True linked_list.reverse() assert str(lowerCAmelCase_ ) == "->".join(str(lowerCAmelCase_ ) for i in range(-8 , 1 ) ) def __lowerCamelCase ( ) -> None: _a : Dict = [ -9, 100, Node(77345112 ), 'dlrow olleH', 7, 5555, 0, -192.55_555, 'Hello, world!', 77.9, Node(10 ), None, None, 12.20, ] _a : List[Any] = LinkedList() for i in test_input: linked_list.insert_tail(lowerCAmelCase_ ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(lowerCAmelCase_ ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head _a : List[str] = linked_list.delete_head() assert result == -9 assert ( str(lowerCAmelCase_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail _a : Dict = linked_list.delete_tail() assert result == 12.2 assert ( str(lowerCAmelCase_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list _a : Optional[Any] = linked_list.delete_nth(10 ) assert result is None assert ( str(lowerCAmelCase_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node('Hello again, world!' ) ) assert ( str(lowerCAmelCase_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(lowerCAmelCase_ ) assert ( str(lowerCAmelCase_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(lowerCAmelCase_ ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def __lowerCamelCase ( ) -> Union[str, Any]: from doctest import testmod testmod() _a : Optional[int] = LinkedList() linked_list.insert_head(input('Inserting 1st at head ' ).strip() ) linked_list.insert_head(input('Inserting 2nd at head ' ).strip() ) print('\nPrint list:' ) linked_list.print_list() linked_list.insert_tail(input('\nInserting 1st at tail ' ).strip() ) linked_list.insert_tail(input('Inserting 2nd at tail ' ).strip() ) print('\nPrint list:' ) linked_list.print_list() print('\nDelete head' ) linked_list.delete_head() print('Delete tail' ) linked_list.delete_tail() print('\nPrint list:' ) linked_list.print_list() print('\nReverse linked list' ) linked_list.reverse() print('\nPrint list:' ) linked_list.print_list() print('\nString representation of linked list:' ) print(lowerCAmelCase_ ) print('\nReading/changing Node data using indexing:' ) print(f"""Element at Position 1: {linked_list[1]}""" ) _a : Optional[Any] = input('Enter New Value: ' ).strip() print('New list:' ) print(lowerCAmelCase_ ) print(f"""length of linked_list is : {len(lowerCAmelCase_ )}""" ) if __name__ == "__main__": main()
89
0
'''simple docstring''' from __future__ import annotations import inspect import unittest from math import floor import numpy as np from transformers import CvtConfig from transformers.testing_utils import require_tf, require_vision, slow from transformers.utils import cached_property, is_tf_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFCvtForImageClassification, TFCvtModel from transformers.models.cvt.modeling_tf_cvt import TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowercase_ ( a__ ): def __a ( self ): UpperCamelCase__ = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(a , "embed_dim" ) ) self.parent.assertTrue(hasattr(a , "num_heads" ) ) class lowercase_ : def __init__( self , a , a=13 , a=64 , a=3 , a=[16, 48, 96] , a=[1, 3, 6] , a=[1, 2, 10] , a=[7, 3, 3] , a=[4, 2, 2] , a=[2, 1, 1] , a=[2, 2, 2] , a=[False, False, True] , a=[0.0, 0.0, 0.0] , a=0.02 , a=1e-12 , a=True , a=True , a=2 , ): UpperCamelCase__ = parent UpperCamelCase__ = batch_size UpperCamelCase__ = image_size UpperCamelCase__ = patch_sizes UpperCamelCase__ = patch_stride UpperCamelCase__ = patch_padding UpperCamelCase__ = is_training UpperCamelCase__ = use_labels UpperCamelCase__ = num_labels UpperCamelCase__ = num_channels UpperCamelCase__ = embed_dim UpperCamelCase__ = num_heads UpperCamelCase__ = stride_kv UpperCamelCase__ = depth UpperCamelCase__ = cls_token UpperCamelCase__ = attention_drop_rate UpperCamelCase__ = initializer_range UpperCamelCase__ = layer_norm_eps def __a ( self ): UpperCamelCase__ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCamelCase__ = None if self.use_labels: # create a random int32 tensor of given shape UpperCamelCase__ = ids_tensor([self.batch_size] , self.num_labels ) UpperCamelCase__ = self.get_config() return config, pixel_values, labels def __a ( self ): return CvtConfig( image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , ) def __a ( self , a , a , a ): UpperCamelCase__ = TFCvtModel(config=a ) UpperCamelCase__ = model(a , training=a ) UpperCamelCase__ = (self.image_size, self.image_size) UpperCamelCase__ , UpperCamelCase__ = image_size[0], image_size[1] for i in range(len(self.depth ) ): UpperCamelCase__ = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) UpperCamelCase__ = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) ) def __a ( self , a , a , a ): UpperCamelCase__ = self.num_labels UpperCamelCase__ = TFCvtForImageClassification(a ) UpperCamelCase__ = model(a , labels=a , training=a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __a ( self ): UpperCamelCase__ = self.prepare_config_and_inputs() UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ = config_and_inputs UpperCamelCase__ = {"pixel_values": pixel_values} return config, inputs_dict @require_tf class lowercase_ ( a__ , a__ , unittest.TestCase ): __UpperCAmelCase = (TFCvtModel, TFCvtForImageClassification) if is_tf_available() else () __UpperCAmelCase = ( {'feature-extraction': TFCvtModel, 'image-classification': TFCvtForImageClassification} if is_tf_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def __a ( self ): UpperCamelCase__ = TFCvtModelTester(self ) UpperCamelCase__ = TFCvtConfigTester(self , config_class=a , has_text_modality=a , hidden_size=37 ) def __a ( self ): self.config_tester.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() @unittest.skip(reason="Cvt does not output attentions" ) def __a ( self ): pass @unittest.skip(reason="Cvt does not use inputs_embeds" ) def __a ( self ): pass @unittest.skip(reason="Cvt does not support input and output embeddings" ) def __a ( self ): pass @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("GPU" ) ) == 0 , reason="TF does not support backprop for grouped convolutions on CPU." , ) def __a ( self ): super().test_dataset_conversion() @unittest.skipIf( not is_tf_available() or len(tf.config.list_physical_devices("GPU" ) ) == 0 , reason="TF does not support backprop for grouped convolutions on CPU." , ) @slow def __a ( self ): super().test_keras_fit() @unittest.skip(reason="Get `Failed to determine best cudnn convolution algo.` error after using TF 2.12+cuda 11.8" ) def __a ( self ): UpperCamelCase__ = tf.keras.mixed_precision.Policy("mixed_float16" ) tf.keras.mixed_precision.set_global_policy(a ) super().test_keras_fit() tf.keras.mixed_precision.set_global_policy("float32" ) def __a ( self ): UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ = model_class(a ) UpperCamelCase__ = inspect.signature(model.call ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCamelCase__ = [*signature.parameters.keys()] UpperCamelCase__ = ["pixel_values"] self.assertListEqual(arg_names[:1] , a ) def __a ( self ): def check_hidden_states_output(a , a , a ): UpperCamelCase__ = model_class(a ) UpperCamelCase__ = model(**self._prepare_for_class(a , a ) ) UpperCamelCase__ = outputs.hidden_states UpperCamelCase__ = len(self.model_tester.depth ) self.assertEqual(len(a ) , a ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) UpperCamelCase__ , UpperCamelCase__ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCamelCase__ = True check_hidden_states_output(a , a , a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCamelCase__ = True check_hidden_states_output(a , a , a ) def __a ( self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a ) def __a ( self ): UpperCamelCase__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a ) @slow def __a ( self ): for model_name in TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCamelCase__ = TFCvtModel.from_pretrained(a ) self.assertIsNotNone(a ) def _UpperCamelCase ( ) -> Optional[int]: '''simple docstring''' UpperCamelCase__ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_tf @require_vision class lowercase_ ( unittest.TestCase ): @cached_property def __a ( self ): return AutoImageProcessor.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def __a ( self ): UpperCamelCase__ = TFCvtForImageClassification.from_pretrained(TF_CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) UpperCamelCase__ = self.default_image_processor UpperCamelCase__ = prepare_img() UpperCamelCase__ = image_processor(images=a , return_tensors="tf" ) # forward pass UpperCamelCase__ = model(**a ) # verify the logits UpperCamelCase__ = tf.TensorShape((1, 10_00) ) self.assertEqual(outputs.logits.shape , a ) UpperCamelCase__ = tf.constant([0.9285, 0.9015, -0.3150] ) self.assertTrue(np.allclose(outputs.logits[0, :3].numpy() , a , atol=1e-4 ) )
80
'''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 __lowerCAmelCase = logging.getLogger() @unittest.skip('Temporarily disable the doc tests.' ) @require_torch @require_tf @slow class __magic_name__ ( unittest.TestCase ): def __lowercase ( self : str ,_UpperCAmelCase : Path ,_UpperCAmelCase : Union[str, None] = None ,_UpperCAmelCase : Union[List[str], None] = None ,_UpperCAmelCase : Union[str, List[str], None] = None ,_UpperCAmelCase : bool = True ,): _a : Dict = [file for file in os.listdir(_UpperCAmelCase ) if os.path.isfile(os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) )] if identifier is not None: _a : str = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): for n_ in n_identifier: _a : int = [file for file in files if n_ not in file] else: _a : Optional[Any] = [file for file in files if n_identifier not in file] _a : Dict = ignore_files or [] ignore_files.append('__init__.py' ) _a : List[str] = [file for file in files if file not in ignore_files] for file in files: # Open all files print('Testing' ,_UpperCAmelCase ) if only_modules: _a : Any = file.split('.' )[0] try: _a : Optional[int] = getattr(_UpperCAmelCase ,_UpperCAmelCase ) _a : Dict = doctest.DocTestSuite(_UpperCAmelCase ) _a : Optional[int] = unittest.TextTestRunner().run(_UpperCAmelCase ) self.assertIs(len(result.failures ) ,0 ) except AttributeError: logger.info(F"""{module_identifier} is not a module.""" ) else: _a : str = doctest.testfile(str('..' / directory / file ) ,optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed ,0 ) def __lowercase ( self : Union[str, Any] ): _a : Optional[Any] = Path('src/transformers' ) _a : Optional[Any] = 'modeling' _a : Union[str, Any] = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(_UpperCAmelCase ,identifier=_UpperCAmelCase ,ignore_files=_UpperCAmelCase ) def __lowercase ( self : int ): _a : str = Path('src/transformers' ) _a : List[str] = 'tokenization' self.analyze_directory(_UpperCAmelCase ,identifier=_UpperCAmelCase ) def __lowercase ( self : int ): _a : Any = Path('src/transformers' ) _a : str = 'configuration' self.analyze_directory(_UpperCAmelCase ,identifier=_UpperCAmelCase ) def __lowercase ( self : Dict ): _a : Tuple = Path('src/transformers' ) _a : Optional[int] = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(_UpperCAmelCase ,n_identifier=_UpperCAmelCase ) def __lowercase ( self : Optional[Any] ): _a : Union[str, Any] = Path('docs/source' ) _a : List[str] = ['favicon.ico'] self.analyze_directory(_UpperCAmelCase ,ignore_files=_UpperCAmelCase ,only_modules=_UpperCAmelCase )
89
0
"""simple docstring""" from typing import Dict, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import flip_channel_order, resize, to_channel_dimension_format, to_pil_image from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_pytesseract_available, is_vision_available, logging, requires_backends if is_vision_available(): import PIL # soft dependency if is_pytesseract_available(): import pytesseract lowerCamelCase_ : List[Any] = logging.get_logger(__name__) def _A ( lowercase , lowercase , lowercase ): """simple docstring""" return [ int(10_00 * (box[0] / width) ), int(10_00 * (box[1] / height) ), int(10_00 * (box[2] / width) ), int(10_00 * (box[3] / height) ), ] def _A ( lowercase , lowercase , lowercase = None ): """simple docstring""" a =tesseract_config if tesseract_config is not None else '''''' # apply OCR a =to_pil_image(lowercase ) a , a =pil_image.size a =pytesseract.image_to_data(lowercase , lang=lowercase , output_type='''dict''' , config=lowercase ) a , a , a , a , a =data['''text'''], data['''left'''], data['''top'''], data['''width'''], data['''height'''] # filter empty words and corresponding coordinates a =[idx for idx, word in enumerate(lowercase ) if not word.strip()] a =[word for idx, word in enumerate(lowercase ) if idx not in irrelevant_indices] a =[coord for idx, coord in enumerate(lowercase ) if idx not in irrelevant_indices] a =[coord for idx, coord in enumerate(lowercase ) if idx not in irrelevant_indices] a =[coord for idx, coord in enumerate(lowercase ) if idx not in irrelevant_indices] a =[coord for idx, coord in enumerate(lowercase ) if idx not in irrelevant_indices] # turn coordinates into (left, top, left+width, top+height) format a =[] for x, y, w, h in zip(lowercase , lowercase , lowercase , lowercase ): a =[x, y, x + w, y + h] actual_boxes.append(lowercase ) # finally, normalize the bounding boxes a =[] for box in actual_boxes: normalized_boxes.append(normalize_box(lowercase , lowercase , lowercase ) ) assert len(lowercase ) == len(lowercase ), "Not as many words as there are bounding boxes" return words, normalized_boxes class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = ["pixel_values"] def __init__( self , __A = True , __A = None , __A = PILImageResampling.BILINEAR , __A = True , __A = None , __A = "" , **__A , ) -> None: super().__init__(**__A ) a =size if size is not None else {'''height''': 224, '''width''': 224} a =get_size_dict(__A ) a =do_resize a =size a =resample a =apply_ocr a =ocr_lang a =tesseract_config def SCREAMING_SNAKE_CASE ( self , __A , __A , __A = PILImageResampling.BILINEAR , __A = None , **__A , ) -> np.ndarray: a =get_size_dict(__A ) if "height" not in size or "width" not in size: raise ValueError(f'''The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}''' ) a =(size['''height'''], size['''width''']) return resize(__A , size=__A , resample=__A , data_format=__A , **__A ) def SCREAMING_SNAKE_CASE ( self , __A , __A = None , __A = None , __A = None , __A = None , __A = None , __A = None , __A = None , __A = ChannelDimension.FIRST , **__A , ) -> PIL.Image.Image: 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(__A ) a =resample if resample is not None else self.resample a =apply_ocr if apply_ocr is not None else self.apply_ocr a =ocr_lang if ocr_lang is not None else self.ocr_lang a =tesseract_config if tesseract_config is not None else self.tesseract_config a =make_list_of_images(__A ) if not valid_images(__A ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) # All transformations expect numpy arrays. a =[to_numpy_array(__A ) for image in images] if apply_ocr: requires_backends(self , '''pytesseract''' ) a =[] a =[] for image in images: a , a =apply_tesseract(__A , __A , __A ) words_batch.append(__A ) boxes_batch.append(__A ) if do_resize: a =[self.resize(image=__A , size=__A , resample=__A ) for image in images] # flip color channels from RGB to BGR (as Detectron2 requires this) a =[flip_channel_order(__A ) for image in images] a =[to_channel_dimension_format(__A , __A ) for image in images] a =BatchFeature(data={'''pixel_values''': images} , tensor_type=__A ) if apply_ocr: a =words_batch a =boxes_batch return data
81
'''simple docstring''' import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_processing_utils import ImageProcessingMixin from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = OrderedDict( [ ('''align''', '''EfficientNetImageProcessor'''), ('''beit''', '''BeitImageProcessor'''), ('''bit''', '''BitImageProcessor'''), ('''blip''', '''BlipImageProcessor'''), ('''blip-2''', '''BlipImageProcessor'''), ('''bridgetower''', '''BridgeTowerImageProcessor'''), ('''chinese_clip''', '''ChineseCLIPImageProcessor'''), ('''clip''', '''CLIPImageProcessor'''), ('''clipseg''', '''ViTImageProcessor'''), ('''conditional_detr''', '''ConditionalDetrImageProcessor'''), ('''convnext''', '''ConvNextImageProcessor'''), ('''convnextv2''', '''ConvNextImageProcessor'''), ('''cvt''', '''ConvNextImageProcessor'''), ('''data2vec-vision''', '''BeitImageProcessor'''), ('''deformable_detr''', '''DeformableDetrImageProcessor'''), ('''deit''', '''DeiTImageProcessor'''), ('''deta''', '''DetaImageProcessor'''), ('''detr''', '''DetrImageProcessor'''), ('''dinat''', '''ViTImageProcessor'''), ('''donut-swin''', '''DonutImageProcessor'''), ('''dpt''', '''DPTImageProcessor'''), ('''efficientformer''', '''EfficientFormerImageProcessor'''), ('''efficientnet''', '''EfficientNetImageProcessor'''), ('''flava''', '''FlavaImageProcessor'''), ('''focalnet''', '''BitImageProcessor'''), ('''git''', '''CLIPImageProcessor'''), ('''glpn''', '''GLPNImageProcessor'''), ('''groupvit''', '''CLIPImageProcessor'''), ('''imagegpt''', '''ImageGPTImageProcessor'''), ('''instructblip''', '''BlipImageProcessor'''), ('''layoutlmv2''', '''LayoutLMv2ImageProcessor'''), ('''layoutlmv3''', '''LayoutLMv3ImageProcessor'''), ('''levit''', '''LevitImageProcessor'''), ('''mask2former''', '''Mask2FormerImageProcessor'''), ('''maskformer''', '''MaskFormerImageProcessor'''), ('''mgp-str''', '''ViTImageProcessor'''), ('''mobilenet_v1''', '''MobileNetV1ImageProcessor'''), ('''mobilenet_v2''', '''MobileNetV2ImageProcessor'''), ('''mobilevit''', '''MobileViTImageProcessor'''), ('''mobilevit''', '''MobileViTImageProcessor'''), ('''mobilevitv2''', '''MobileViTImageProcessor'''), ('''nat''', '''ViTImageProcessor'''), ('''oneformer''', '''OneFormerImageProcessor'''), ('''owlvit''', '''OwlViTImageProcessor'''), ('''perceiver''', '''PerceiverImageProcessor'''), ('''pix2struct''', '''Pix2StructImageProcessor'''), ('''poolformer''', '''PoolFormerImageProcessor'''), ('''regnet''', '''ConvNextImageProcessor'''), ('''resnet''', '''ConvNextImageProcessor'''), ('''sam''', '''SamImageProcessor'''), ('''segformer''', '''SegformerImageProcessor'''), ('''swiftformer''', '''ViTImageProcessor'''), ('''swin''', '''ViTImageProcessor'''), ('''swin2sr''', '''Swin2SRImageProcessor'''), ('''swinv2''', '''ViTImageProcessor'''), ('''table-transformer''', '''DetrImageProcessor'''), ('''timesformer''', '''VideoMAEImageProcessor'''), ('''tvlt''', '''TvltImageProcessor'''), ('''upernet''', '''SegformerImageProcessor'''), ('''van''', '''ConvNextImageProcessor'''), ('''videomae''', '''VideoMAEImageProcessor'''), ('''vilt''', '''ViltImageProcessor'''), ('''vit''', '''ViTImageProcessor'''), ('''vit_hybrid''', '''ViTHybridImageProcessor'''), ('''vit_mae''', '''ViTImageProcessor'''), ('''vit_msn''', '''ViTImageProcessor'''), ('''xclip''', '''CLIPImageProcessor'''), ('''yolos''', '''YolosImageProcessor'''), ] ) __lowerCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def __lowerCamelCase ( lowerCAmelCase_ ) -> Optional[Any]: for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: _a : List[Any] = model_type_to_module_name(lowerCAmelCase_ ) _a : Optional[Any] = importlib.import_module(f""".{module_name}""" , 'transformers.models' ) try: return getattr(lowerCAmelCase_ , lowerCAmelCase_ ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(lowerCAmelCase_ , '__name__' , lowerCAmelCase_ ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. _a : Dict = importlib.import_module('transformers' ) if hasattr(lowerCAmelCase_ , lowerCAmelCase_ ): return getattr(lowerCAmelCase_ , lowerCAmelCase_ ) return None def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = False , lowerCAmelCase_ = False , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = False , **lowerCAmelCase_ , ) -> Tuple: _a : List[str] = get_file_from_repo( lowerCAmelCase_ , lowerCAmelCase_ , cache_dir=lowerCAmelCase_ , force_download=lowerCAmelCase_ , resume_download=lowerCAmelCase_ , proxies=lowerCAmelCase_ , use_auth_token=lowerCAmelCase_ , revision=lowerCAmelCase_ , local_files_only=lowerCAmelCase_ , ) if resolved_config_file is None: logger.info( 'Could not locate the image processor configuration file, will try to use the model config instead.' ) return {} with open(lowerCAmelCase_ , encoding='utf-8' ) as reader: return json.load(lowerCAmelCase_ ) class __magic_name__ : def __init__( self : List[str] ): raise EnvironmentError( 'AutoImageProcessor is designed to be instantiated ' 'using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.' ) @classmethod @replace_list_option_in_docstrings(_UpperCAmelCase ) def __lowercase ( cls : Dict ,_UpperCAmelCase : Union[str, Any] ,**_UpperCAmelCase : Optional[Any] ): _a : Any = kwargs.pop('config' ,_UpperCAmelCase ) _a : Dict = kwargs.pop('trust_remote_code' ,_UpperCAmelCase ) _a : Any = True _a , _a : Tuple = ImageProcessingMixin.get_image_processor_dict(_UpperCAmelCase ,**_UpperCAmelCase ) _a : List[Any] = config_dict.get('image_processor_type' ,_UpperCAmelCase ) _a : int = None if "AutoImageProcessor" in config_dict.get('auto_map' ,{} ): _a : Any = config_dict['auto_map']['AutoImageProcessor'] # If we still don't have the image processor class, check if we're loading from a previous feature extractor config # and if so, infer the image processor class from there. if image_processor_class is None and image_processor_auto_map is None: _a : List[Any] = config_dict.pop('feature_extractor_type' ,_UpperCAmelCase ) if feature_extractor_class is not None: logger.warning( 'Could not find image processor class in the image processor config or the model config. Loading' ' based on pattern matching with the model\'s feature extractor configuration.' ) _a : Optional[int] = feature_extractor_class.replace('FeatureExtractor' ,'ImageProcessor' ) if "AutoFeatureExtractor" in config_dict.get('auto_map' ,{} ): _a : List[Any] = config_dict['auto_map']['AutoFeatureExtractor'] _a : List[str] = feature_extractor_auto_map.replace('FeatureExtractor' ,'ImageProcessor' ) logger.warning( 'Could not find image processor auto map in the image processor config or the model config.' ' Loading based on pattern matching with the model\'s feature extractor configuration.' ) # If we don't find the image processor class in the image processor config, let's try the model config. if image_processor_class is None and image_processor_auto_map is None: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : Dict = AutoConfig.from_pretrained(_UpperCAmelCase ,**_UpperCAmelCase ) # It could be in `config.image_processor_type`` _a : Optional[int] = getattr(_UpperCAmelCase ,'image_processor_type' ,_UpperCAmelCase ) if hasattr(_UpperCAmelCase ,'auto_map' ) and "AutoImageProcessor" in config.auto_map: _a : Union[str, Any] = config.auto_map['AutoImageProcessor'] if image_processor_class is not None: _a : Optional[int] = image_processor_class_from_name(_UpperCAmelCase ) _a : List[str] = image_processor_auto_map is not None _a : Optional[int] = image_processor_class is not None or type(_UpperCAmelCase ) in IMAGE_PROCESSOR_MAPPING _a : Optional[int] = resolve_trust_remote_code( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) if has_remote_code and trust_remote_code: _a : Dict = get_class_from_dynamic_module( _UpperCAmelCase ,_UpperCAmelCase ,**_UpperCAmelCase ) _a : int = kwargs.pop('code_revision' ,_UpperCAmelCase ) if os.path.isdir(_UpperCAmelCase ): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(_UpperCAmelCase ,**_UpperCAmelCase ) elif image_processor_class is not None: return image_processor_class.from_dict(_UpperCAmelCase ,**_UpperCAmelCase ) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(_UpperCAmelCase ) in IMAGE_PROCESSOR_MAPPING: _a : Dict = IMAGE_PROCESSOR_MAPPING[type(_UpperCAmelCase )] return image_processor_class.from_dict(_UpperCAmelCase ,**_UpperCAmelCase ) raise ValueError( F"""Unrecognized image processor in {pretrained_model_name_or_path}. Should have a """ F"""`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following """ F"""`model_type` keys in its {CONFIG_NAME}: {', '.join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}""" ) @staticmethod def __lowercase ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Dict ): IMAGE_PROCESSOR_MAPPING.register(_UpperCAmelCase ,_UpperCAmelCase )
89
0
import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS, CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class __lowerCAmelCase ( lowerCamelCase__ , unittest.TestCase ): __lowerCamelCase = DiTPipeline __lowerCamelCase = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS __lowerCamelCase = PipelineTesterMixin.required_optional_params - { '''latents''', '''num_images_per_prompt''', '''callback''', '''callback_steps''', } __lowerCamelCase = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS __lowerCamelCase = False def snake_case ( self ): """simple docstring""" torch.manual_seed(0 ) _lowerCAmelCase = TransformeraDModel( sample_size=16 , num_layers=2 , patch_size=4 , attention_head_dim=8 , num_attention_heads=2 , in_channels=4 , out_channels=8 , attention_bias=_snake_case , activation_fn="""gelu-approximate""" , num_embeds_ada_norm=1000 , norm_type="""ada_norm_zero""" , norm_elementwise_affine=_snake_case , ) _lowerCAmelCase = AutoencoderKL() _lowerCAmelCase = DDIMScheduler() _lowerCAmelCase = {"""transformer""": transformer.eval(), """vae""": vae.eval(), """scheduler""": scheduler} return components def snake_case ( self , _snake_case , _snake_case=0 ): """simple docstring""" if str(_snake_case ).startswith("""mps""" ): _lowerCAmelCase = torch.manual_seed(_snake_case ) else: _lowerCAmelCase = torch.Generator(device=_snake_case ).manual_seed(_snake_case ) _lowerCAmelCase = { """class_labels""": [1], """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs def snake_case ( self ): """simple docstring""" _lowerCAmelCase = """cpu""" _lowerCAmelCase = self.get_dummy_components() _lowerCAmelCase = self.pipeline_class(**_snake_case ) pipe.to(_snake_case ) pipe.set_progress_bar_config(disable=_snake_case ) _lowerCAmelCase = self.get_dummy_inputs(_snake_case ) _lowerCAmelCase = pipe(**_snake_case ).images _lowerCAmelCase = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 16, 16, 3) ) _lowerCAmelCase = np.array([0.2946, 0.6601, 0.4329, 0.3296, 0.4144, 0.5319, 0.7273, 0.5013, 0.4457] ) _lowerCAmelCase = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_snake_case , 1e-3 ) def snake_case ( self ): """simple docstring""" self._test_inference_batch_single_identical(relax_max_difference=_snake_case , expected_max_diff=1e-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available() , reason="""XFormers attention is only available with CUDA and `xformers` installed""" , ) def snake_case ( self ): """simple docstring""" self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3 ) @require_torch_gpu @slow class __lowerCAmelCase ( unittest.TestCase ): def snake_case ( self ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def snake_case ( self ): """simple docstring""" _lowerCAmelCase = torch.manual_seed(0 ) _lowerCAmelCase = DiTPipeline.from_pretrained("""facebook/DiT-XL-2-256""" ) pipe.to("""cuda""" ) _lowerCAmelCase = ["""vase""", """umbrella""", """white shark""", """white wolf"""] _lowerCAmelCase = pipe.get_label_ids(_snake_case ) _lowerCAmelCase = pipe(_snake_case , generator=_snake_case , num_inference_steps=40 , output_type="""np""" ).images for word, image in zip(_snake_case , _snake_case ): _lowerCAmelCase = load_numpy( F'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy' ) assert np.abs((expected_image - image).max() ) < 1e-2 def snake_case ( self ): """simple docstring""" _lowerCAmelCase = DiTPipeline.from_pretrained("""facebook/DiT-XL-2-512""" ) _lowerCAmelCase = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.to("""cuda""" ) _lowerCAmelCase = ["""vase""", """umbrella"""] _lowerCAmelCase = pipe.get_label_ids(_snake_case ) _lowerCAmelCase = torch.manual_seed(0 ) _lowerCAmelCase = pipe(_snake_case , generator=_snake_case , num_inference_steps=25 , output_type="""np""" ).images for word, image in zip(_snake_case , _snake_case ): _lowerCAmelCase = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" F'/dit/{word}_512.npy' ) assert np.abs((expected_image - image).max() ) < 1e-1
82
'''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 __lowerCAmelCase = None __lowerCAmelCase = '''<''' 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 __lowerCAmelCase = [ 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 __magic_name__ : lowerCAmelCase : bool = True lowerCAmelCase : Optional[str] = None # Automatically constructed lowerCAmelCase : ClassVar[str] = "PIL.Image.Image" lowerCAmelCase : ClassVar[Any] = pa.struct({'bytes': pa.binary(), 'path': pa.string()} ) lowerCAmelCase : str = field(default='Image' , init=_UpperCamelCase , repr=_UpperCamelCase ) def __call__( self : Union[str, Any] ): return self.pa_type def __lowercase ( self : Any ,_UpperCAmelCase : Union[str, bytes, dict, np.ndarray, "PIL.Image.Image"] ): if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support encoding images, please install \'Pillow\'.' ) if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : Optional[Any] = np.array(_UpperCAmelCase ) if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): return {"path": value, "bytes": None} elif isinstance(_UpperCAmelCase ,_UpperCAmelCase ): return {"path": None, "bytes": value} elif isinstance(_UpperCAmelCase ,np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(_UpperCAmelCase ) 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 __lowercase ( self : Optional[Any] ,_UpperCAmelCase : dict ,_UpperCAmelCase : Optional[int]=None ): 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 : Dict = {} _a , _a : str = 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(_UpperCAmelCase ): _a : Any = PIL.Image.open(_UpperCAmelCase ) else: _a : List[Any] = path.split('::' )[-1] try: _a : str = string_to_dict(_UpperCAmelCase ,config.HUB_DATASETS_URL )['repo_id'] _a : Optional[Any] = token_per_repo_id.get(_UpperCAmelCase ) except ValueError: _a : int = None with xopen(_UpperCAmelCase ,'rb' ,use_auth_token=_UpperCAmelCase ) as f: _a : Tuple = BytesIO(f.read() ) _a : Union[str, Any] = PIL.Image.open(bytes_ ) else: _a : Optional[int] = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def __lowercase ( self : int ): from .features import Value return ( self if self.decode else { "bytes": Value('binary' ), "path": Value('string' ), } ) def __lowercase ( self : str ,_UpperCAmelCase : Union[pa.StringArray, pa.StructArray, pa.ListArray] ): if pa.types.is_string(storage.type ): _a : Union[str, Any] = pa.array([None] * len(_UpperCAmelCase ) ,type=pa.binary() ) _a : Union[str, 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(_UpperCAmelCase ) ,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 : Tuple = pa.array([None] * len(_UpperCAmelCase ) ,type=pa.binary() ) if storage.type.get_field_index('path' ) >= 0: _a : Union[str, Any] = storage.field('path' ) else: _a : Dict = pa.array([None] * len(_UpperCAmelCase ) ,type=pa.string() ) _a : Optional[Any] = pa.StructArray.from_arrays([bytes_array, path_array] ,['bytes', 'path'] ,mask=storage.is_null() ) elif pa.types.is_list(storage.type ): _a : List[str] = pa.array( [encode_np_array(np.array(_UpperCAmelCase ) )['bytes'] if arr is not None else None for arr in storage.to_pylist()] ,type=pa.binary() ,) _a : int = pa.array([None] * len(_UpperCAmelCase ) ,type=pa.string() ) _a : Optional[Any] = pa.StructArray.from_arrays( [bytes_array, path_array] ,['bytes', 'path'] ,mask=bytes_array.is_null() ) return array_cast(_UpperCAmelCase ,self.pa_type ) def __lowercase ( self : Dict ,_UpperCAmelCase : pa.StructArray ): @no_op_if_value_is_null def path_to_bytes(_UpperCAmelCase : Tuple ): with xopen(_UpperCAmelCase ,'rb' ) as f: _a : int = f.read() return bytes_ _a : Any = 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 : Optional[Any] = pa.array( [os.path.basename(_UpperCAmelCase ) if path is not None else None for path in storage.field('path' ).to_pylist()] ,type=pa.string() ,) _a : Dict = pa.StructArray.from_arrays([bytes_array, path_array] ,['bytes', 'path'] ,mask=bytes_array.is_null() ) return array_cast(_UpperCAmelCase ,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 ( lowerCAmelCase_ ) -> bytes: _a : Optional[int] = BytesIO() if image.format in list_image_compression_formats(): _a : Optional[Any] = image.format else: _a : str = 'PNG' if image.mode in ['1', 'L', 'LA', 'RGB', 'RGBA'] else 'TIFF' image.save(lowerCAmelCase_ , format=lowerCAmelCase_ ) return buffer.getvalue() def __lowerCamelCase ( lowerCAmelCase_ ) -> dict: if hasattr(lowerCAmelCase_ , 'filename' ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(lowerCAmelCase_ )} def __lowerCamelCase ( lowerCAmelCase_ ) -> dict: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support encoding images, please install \'Pillow\'.' ) _a : List[Any] = array.dtype _a : Optional[int] = dtype.byteorder if dtype.byteorder != '=' else _NATIVE_BYTEORDER _a : Union[str, Any] = dtype.kind _a : Union[str, Any] = dtype.itemsize _a : List[Any] = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: _a : Optional[int] = 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 : Union[str, 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 : str = dtype_byteorder + dtype_kind + str(lowerCAmelCase_ ) _a : List[Any] = np.dtype(lowerCAmelCase_ ) 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(lowerCAmelCase_ ) ) return {"path": None, "bytes": image_to_bytes(lowerCAmelCase_ )} def __lowerCamelCase ( lowerCAmelCase_ ) -> List[dict]: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support encoding images, please install \'Pillow\'.' ) if objs: _a , _a : Optional[Any] = first_non_null_value(lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(lowerCAmelCase_ , np.ndarray ): _a : List[str] = no_op_if_value_is_null(lowerCAmelCase_ ) return [obj_to_image_dict_func(lowerCAmelCase_ ) for obj in objs] elif isinstance(lowerCAmelCase_ , PIL.Image.Image ): _a : List[str] = no_op_if_value_is_null(lowerCAmelCase_ ) return [obj_to_image_dict_func(lowerCAmelCase_ ) for obj in objs] else: return objs else: return objs
89
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ : Optional[Any] = logging.get_logger(__name__) snake_case_ : Any = { 'andreasmadsen/efficient_mlm_m0.40': ( 'https://huggingface.co/andreasmadsen/efficient_mlm_m0.40/resolve/main/config.json' ), } class lowercase__ ( lowercase ): lowercase__ = """roberta-prelayernorm""" def __init__( self : List[Any] ,lowerCamelCase__ : Tuple=50265 ,lowerCamelCase__ : Optional[int]=768 ,lowerCamelCase__ : Optional[int]=12 ,lowerCamelCase__ : str=12 ,lowerCamelCase__ : List[str]=3072 ,lowerCamelCase__ : str="gelu" ,lowerCamelCase__ : List[Any]=0.1 ,lowerCamelCase__ : Dict=0.1 ,lowerCamelCase__ : Any=512 ,lowerCamelCase__ : Union[str, Any]=2 ,lowerCamelCase__ : List[str]=0.0_2 ,lowerCamelCase__ : List[Any]=1E-12 ,lowerCamelCase__ : List[Any]=1 ,lowerCamelCase__ : str=0 ,lowerCamelCase__ : Optional[Any]=2 ,lowerCamelCase__ : Optional[Any]="absolute" ,lowerCamelCase__ : List[str]=True ,lowerCamelCase__ : str=None ,**lowerCamelCase__ : List[Any] ,): '''simple docstring''' super().__init__(pad_token_id=lowerCamelCase__ ,bos_token_id=lowerCamelCase__ ,eos_token_id=lowerCamelCase__ ,**lowerCamelCase__ ) _UpperCamelCase : Union[str, Any] = vocab_size _UpperCamelCase : Dict = hidden_size _UpperCamelCase : str = num_hidden_layers _UpperCamelCase : Tuple = num_attention_heads _UpperCamelCase : Dict = hidden_act _UpperCamelCase : List[str] = intermediate_size _UpperCamelCase : Optional[int] = hidden_dropout_prob _UpperCamelCase : int = attention_probs_dropout_prob _UpperCamelCase : str = max_position_embeddings _UpperCamelCase : List[Any] = type_vocab_size _UpperCamelCase : Optional[Any] = initializer_range _UpperCamelCase : Optional[Any] = layer_norm_eps _UpperCamelCase : Any = position_embedding_type _UpperCamelCase : int = use_cache _UpperCamelCase : Optional[int] = classifier_dropout class lowercase__ ( lowercase ): @property def UpperCamelCase_ ( self : Dict ): '''simple docstring''' if self.task == "multiple-choice": _UpperCamelCase : Optional[Any] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: _UpperCamelCase : str = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
83
'''simple docstring''' from __future__ import annotations from collections.abc import Sequence from typing import Literal def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> str | Literal[False]: _a : Optional[int] = list(lowerCAmelCase_ ) _a : Optional[Any] = list(lowerCAmelCase_ ) _a : Union[str, Any] = 0 for i in range(len(lowerCAmelCase_ ) ): if lista[i] != lista[i]: count += 1 _a : Optional[int] = '_' if count > 1: return False else: return "".join(lowerCAmelCase_ ) def __lowerCamelCase ( lowerCAmelCase_ ) -> list[str]: _a : Optional[int] = [] while True: _a : Any = ['$'] * len(lowerCAmelCase_ ) _a : List[str] = [] for i in range(len(lowerCAmelCase_ ) ): for j in range(i + 1 , len(lowerCAmelCase_ ) ): _a : Optional[int] = compare_string(binary[i] , binary[j] ) if k is False: _a : Optional[Any] = '*' _a : Optional[Any] = '*' temp.append('X' ) for i in range(len(lowerCAmelCase_ ) ): if checka[i] == "$": pi.append(binary[i] ) if len(lowerCAmelCase_ ) == 0: return pi _a : Any = list(set(lowerCAmelCase_ ) ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> list[str]: _a : int = [] for minterm in minterms: _a : Optional[int] = '' for _ in range(lowerCAmelCase_ ): _a : Union[str, Any] = str(minterm % 2 ) + string minterm //= 2 temp.append(lowerCAmelCase_ ) return temp def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> bool: _a : int = list(lowerCAmelCase_ ) _a : Union[str, Any] = list(lowerCAmelCase_ ) _a : str = 0 for i in range(len(lowerCAmelCase_ ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> list[str]: _a : List[Any] = [] _a : Optional[Any] = [0] * len(lowerCAmelCase_ ) for i in range(len(chart[0] ) ): _a : Union[str, Any] = 0 _a : int = -1 for j in range(len(lowerCAmelCase_ ) ): if chart[j][i] == 1: count += 1 _a : int = j if count == 1: _a : List[Any] = 1 for i in range(len(lowerCAmelCase_ ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(lowerCAmelCase_ ) ): _a : Any = 0 temp.append(prime_implicants[i] ) while True: _a : Union[str, Any] = 0 _a : List[Any] = -1 _a : str = 0 for i in range(len(lowerCAmelCase_ ) ): _a : Union[str, Any] = chart[i].count(1 ) if count_n > max_n: _a : Any = count_n _a : int = i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(lowerCAmelCase_ ) ): _a : List[str] = 0 def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> list[list[int]]: _a : int = [[0 for x in range(len(lowerCAmelCase_ ) )] for x in range(len(lowerCAmelCase_ ) )] for i in range(len(lowerCAmelCase_ ) ): _a : str = prime_implicants[i].count('_' ) for j in range(len(lowerCAmelCase_ ) ): if is_for_table(prime_implicants[i] , binary[j] , lowerCAmelCase_ ): _a : Optional[Any] = 1 return chart def __lowerCamelCase ( ) -> None: _a : Optional[int] = int(input('Enter the no. of variables\n' ) ) _a : List[Any] = [ float(lowerCAmelCase_ ) for x in input( 'Enter the decimal representation of Minterms \'Spaces Separated\'\n' ).split() ] _a : List[str] = decimal_to_binary(lowerCAmelCase_ , lowerCAmelCase_ ) _a : Dict = check(lowerCAmelCase_ ) print('Prime Implicants are:' ) print(lowerCAmelCase_ ) _a : List[Any] = prime_implicant_chart(lowerCAmelCase_ , lowerCAmelCase_ ) _a : int = selection(lowerCAmelCase_ , lowerCAmelCase_ ) print('Essential Prime Implicants are:' ) print(lowerCAmelCase_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
89
0
"""simple docstring""" from collections import defaultdict def _snake_case ( lowercase__ : int ) -> int: '''simple docstring''' lowerCAmelCase_ :List[Any] = 1 lowerCAmelCase_ :str = True for v in tree[start]: if v not in visited: ret += dfs(lowercase__ ) if ret % 2 == 0: cuts.append(lowercase__ ) return ret def _snake_case ( ) -> int: '''simple docstring''' dfs(1 ) if __name__ == "__main__": __UpperCAmelCase , __UpperCAmelCase = 10, 9 __UpperCAmelCase = defaultdict(list) __UpperCAmelCase = {} __UpperCAmelCase = [] __UpperCAmelCase = 0 __UpperCAmelCase = [(2, 1), (3, 1), (4, 3), (5, 2), (6, 1), (7, 2), (8, 6), (9, 8), (10, 8)] for u, v in edges: tree[u].append(v) tree[v].append(u) even_tree() print(len(cuts) - 1)
84
'''simple docstring''' # Copyright 2022 The HuggingFace Team and The OpenBMB Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __lowerCAmelCase = { '''configuration_cpmant''': ['''CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CpmAntConfig'''], '''tokenization_cpmant''': ['''CpmAntTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CpmAntForCausalLM''', '''CpmAntModel''', '''CpmAntPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
89
0
'''simple docstring''' import shutil import tempfile import unittest import numpy as np import pytest from transformers import is_speech_available, is_vision_available from transformers.testing_utils import require_torch if is_vision_available(): from transformers import TvltImageProcessor if is_speech_available(): from transformers import TvltFeatureExtractor from transformers import TvltProcessor @require_torch class _snake_case ( unittest.TestCase ): def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ = "ZinengTang/tvlt-base" snake_case_ = tempfile.mkdtemp() def lowerCAmelCase__ ( self , **a__ ) -> Any: '''simple docstring''' return TvltImageProcessor.from_pretrained(self.checkpoint , **a__ ) def lowerCAmelCase__ ( self , **a__ ) -> Union[str, Any]: '''simple docstring''' return TvltFeatureExtractor.from_pretrained(self.checkpoint , **a__ ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' shutil.rmtree(self.tmpdirname ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ = self.get_image_processor() snake_case_ = self.get_feature_extractor() snake_case_ = TvltProcessor(image_processor=a__ , feature_extractor=a__ ) processor.save_pretrained(self.tmpdirname ) snake_case_ = TvltProcessor.from_pretrained(self.tmpdirname ) self.assertIsInstance(processor.feature_extractor , a__ ) self.assertIsInstance(processor.image_processor , a__ ) def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ = self.get_image_processor() snake_case_ = self.get_feature_extractor() snake_case_ = TvltProcessor(image_processor=a__ , feature_extractor=a__ ) snake_case_ = np.ones([12_000] ) snake_case_ = feature_extractor(a__ , return_tensors="np" ) snake_case_ = processor(audio=a__ , return_tensors="np" ) for key in audio_dict.keys(): self.assertAlmostEqual(audio_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def lowerCAmelCase__ ( self ) -> Optional[int]: '''simple docstring''' snake_case_ = self.get_image_processor() snake_case_ = self.get_feature_extractor() snake_case_ = TvltProcessor(image_processor=a__ , feature_extractor=a__ ) snake_case_ = np.ones([3, 224, 224] ) snake_case_ = image_processor(a__ , return_tensors="np" ) snake_case_ = processor(images=a__ , return_tensors="np" ) for key in image_dict.keys(): self.assertAlmostEqual(image_dict[key].sum() , input_processor[key].sum() , delta=1e-2 ) def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' snake_case_ = self.get_image_processor() snake_case_ = self.get_feature_extractor() snake_case_ = TvltProcessor(image_processor=a__ , feature_extractor=a__ ) snake_case_ = np.ones([12_000] ) snake_case_ = np.ones([3, 224, 224] ) snake_case_ = processor(audio=a__ , images=a__ ) self.assertListEqual(list(inputs.keys() ) , ["audio_values", "audio_mask", "pixel_values", "pixel_mask"] ) # test if it raises when no input is passed with pytest.raises(a__ ): processor() def lowerCAmelCase__ ( self ) -> Union[str, Any]: '''simple docstring''' snake_case_ = self.get_image_processor() snake_case_ = self.get_feature_extractor() snake_case_ = TvltProcessor(image_processor=a__ , feature_extractor=a__ ) self.assertListEqual( processor.model_input_names , image_processor.model_input_names + feature_extractor.model_input_names , msg="`processor` and `image_processor`+`feature_extractor` model input names do not match" , )
85
'''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 __magic_name__ ( _UpperCamelCase , unittest.TestCase ): lowerCAmelCase : str = LayoutLMTokenizer lowerCAmelCase : Tuple = LayoutLMTokenizerFast lowerCAmelCase : List[Any] = True lowerCAmelCase : int = True def __lowercase ( self : Dict ): super().setUp() _a : int = [ '[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] _a : List[str] = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def __lowercase ( self : Dict ,**_UpperCAmelCase : List[str] ): return LayoutLMTokenizer.from_pretrained(self.tmpdirname ,**_UpperCAmelCase ) def __lowercase ( self : Optional[Any] ,_UpperCAmelCase : Tuple ): _a : Optional[int] = 'UNwant\u00E9d,running' _a : List[Any] = 'unwanted, running' return input_text, output_text def __lowercase ( self : Optional[int] ): _a : Optional[Any] = self.tokenizer_class(self.vocab_file ) _a : Optional[Any] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(_UpperCAmelCase ,['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_UpperCAmelCase ) ,[7, 4, 5, 10, 8, 9] ) def __lowercase ( self : Optional[int] ): pass
89
0
"""simple docstring""" 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 lowerCamelCase__ = logging.getLogger(__name__) def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase ): # 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 __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase=False ): __lowerCAmelCase : Optional[Any] = 2 if unlogit: __lowerCAmelCase : str = torch.pow(_UpperCamelCase , _UpperCamelCase ) __lowerCAmelCase : Tuple = p * torch.log(_UpperCamelCase ) __lowerCAmelCase : Any = 0 return -plogp.sum(dim=-1 ) def __lowerCAmelCase (_UpperCamelCase ): 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 __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase=True , _UpperCamelCase=True , _UpperCamelCase=None , _UpperCamelCase=False ): __lowerCAmelCase , __lowerCAmelCase : int = model.config.num_hidden_layers, model.config.num_attention_heads __lowerCAmelCase : List[Any] = torch.zeros(_UpperCamelCase , _UpperCamelCase ).to(args.device ) __lowerCAmelCase : Any = torch.zeros(_UpperCamelCase , _UpperCamelCase ).to(args.device ) if head_mask is None: __lowerCAmelCase : int = 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: __lowerCAmelCase : int = None __lowerCAmelCase : Tuple = 0.0 __lowerCAmelCase : Tuple = 0.0 for step, inputs in enumerate(tqdm(_UpperCamelCase , desc='Iteration' , disable=args.local_rank not in [-1, 0] ) ): __lowerCAmelCase : List[str] = tuple(t.to(args.device ) for t in inputs ) ((__lowerCAmelCase) , ) : Tuple = inputs # Do a forward pass (not with torch.no_grad() since we need gradients for importance score - see below) __lowerCAmelCase : Union[str, Any] = model(_UpperCamelCase , labels=_UpperCamelCase , head_mask=_UpperCamelCase ) # (loss), lm_logits, presents, (all hidden_states), (attentions) __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Optional[Any] = ( 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 ): __lowerCAmelCase : int = 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: __lowerCAmelCase : List[str] = 2 __lowerCAmelCase : Tuple = torch.pow(torch.pow(_UpperCamelCase , _UpperCamelCase ).sum(-1 ) , 1 / exponent ) head_importance /= norm_by_layer.unsqueeze(-1 ) + 1e-2_0 if not args.dont_normalize_global_importance: __lowerCAmelCase : Dict = (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' ) __lowerCAmelCase : int = torch.zeros(head_importance.numel() , dtype=torch.long , device=args.device ) __lowerCAmelCase : Dict = torch.arange( head_importance.numel() , device=args.device ) __lowerCAmelCase : Any = head_ranks.view_as(_UpperCamelCase ) print_ad_tensor(_UpperCamelCase ) return attn_entropy, head_importance, total_loss def __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : int = compute_heads_importance(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , compute_entropy=_UpperCamelCase ) __lowerCAmelCase : List[str] = 1 / loss # instead of downsteam score use the LM loss logger.info('Pruning: original score: %f, threshold: %f' , _UpperCamelCase , original_score * args.masking_threshold ) __lowerCAmelCase : Optional[int] = torch.ones_like(_UpperCamelCase ) __lowerCAmelCase : Any = max(1 , int(new_head_mask.numel() * args.masking_amount ) ) __lowerCAmelCase : Tuple = original_score while current_score >= original_score * args.masking_threshold: __lowerCAmelCase : Union[str, Any] = new_head_mask.clone().detach() # save current head mask # heads from least important to most - keep only not-masked heads __lowerCAmelCase : Optional[Any] = float('Inf' ) __lowerCAmelCase : Tuple = head_importance.view(-1 ).sort()[1] if len(_UpperCamelCase ) <= num_to_mask: print('BREAK BY num_to_mask' ) break # mask heads __lowerCAmelCase : List[str] = current_heads_to_mask[:num_to_mask] logger.info('Heads to mask: %s' , str(current_heads_to_mask.tolist() ) ) __lowerCAmelCase : Optional[int] = new_head_mask.view(-1 ) __lowerCAmelCase : Optional[int] = 0.0 __lowerCAmelCase : Optional[Any] = new_head_mask.view_as(_UpperCamelCase ) __lowerCAmelCase : Any = new_head_mask.clone().detach() print_ad_tensor(_UpperCamelCase ) # Compute metric and head importance again __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : List[str] = compute_heads_importance( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , compute_entropy=_UpperCamelCase , head_mask=_UpperCamelCase ) __lowerCAmelCase : Tuple = 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() * 100 , ) 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 __lowerCAmelCase (_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): __lowerCAmelCase : Union[str, Any] = datetime.now() __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Tuple = compute_heads_importance( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , compute_entropy=_UpperCamelCase , compute_importance=_UpperCamelCase , head_mask=_UpperCamelCase ) __lowerCAmelCase : Union[str, Any] = 1 / loss __lowerCAmelCase : Dict = datetime.now() - before_time __lowerCAmelCase : str = sum(p.numel() for p in model.parameters() ) __lowerCAmelCase : Tuple = { 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 ): __lowerCAmelCase : Tuple = [ v, ] assert sum(len(_UpperCamelCase ) for h in heads_to_prune.values() ) == (1 - head_mask.long()).sum().item() model.prune_heads(_UpperCamelCase ) __lowerCAmelCase : Optional[int] = sum(p.numel() for p in model.parameters() ) __lowerCAmelCase : str = datetime.now() __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase : Tuple = compute_heads_importance( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , compute_entropy=_UpperCamelCase , compute_importance=_UpperCamelCase , head_mask=_UpperCamelCase , actually_pruned=_UpperCamelCase , ) __lowerCAmelCase : Optional[Any] = 1 / loss __lowerCAmelCase : Optional[Any] = 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 * 100 , ) 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 * 100 ) save_model(_UpperCamelCase , args.output_dir ) def __lowerCAmelCase (): __lowerCAmelCase : List[str] = 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=128 , 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.' ) __lowerCAmelCase : List[str] = 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: __lowerCAmelCase : List[Any] = torch.device('cuda' if torch.cuda.is_available() and not args.no_cuda else 'cpu' ) __lowerCAmelCase : Optional[Any] = 0 if args.no_cuda else torch.cuda.device_count() else: torch.cuda.set_device(args.local_rank ) __lowerCAmelCase : Dict = torch.device('cuda' , args.local_rank ) __lowerCAmelCase : Union[str, Any] = 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 ) ) ) __lowerCAmelCase : Any = GPTaLMHeadModel.from_pretrained(args.model_name_or_path ) # Distributed and parallel training model.to(args.device ) if args.local_rank != -1: __lowerCAmelCase : int = nn.parallel.DistributedDataParallel( _UpperCamelCase , device_ids=[args.local_rank] , output_device=args.local_rank , find_unused_parameters=_UpperCamelCase ) elif args.n_gpu > 1: __lowerCAmelCase : Tuple = 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 __lowerCAmelCase : List[str] = np.concatenate( [ np.loadtxt(args.data_dir , dtype=np.intaa ), ] ) __lowerCAmelCase : List[Any] = (torch.from_numpy(_UpperCamelCase ),) __lowerCAmelCase : Optional[int] = TensorDataset(*_UpperCamelCase ) __lowerCAmelCase : Tuple = RandomSampler(_UpperCamelCase ) __lowerCAmelCase : Optional[Any] = 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: __lowerCAmelCase : List[str] = mask_heads(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) prune_heads(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) if __name__ == "__main__": main()
86
'''simple docstring''' import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { '''microsoft/conditional-detr-resnet-50''': ( '''https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json''' ), } class __magic_name__ ( _UpperCamelCase ): lowerCAmelCase : Any = 'conditional_detr' lowerCAmelCase : List[str] = ['past_key_values'] lowerCAmelCase : Optional[int] = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : Optional[int] ,_UpperCAmelCase : Optional[int]=True ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : List[Any]=3 ,_UpperCAmelCase : List[Any]=300 ,_UpperCAmelCase : Dict=6 ,_UpperCAmelCase : List[str]=2048 ,_UpperCAmelCase : Optional[int]=8 ,_UpperCAmelCase : List[Any]=6 ,_UpperCAmelCase : Optional[int]=2048 ,_UpperCAmelCase : Dict=8 ,_UpperCAmelCase : int=0.0 ,_UpperCAmelCase : Optional[Any]=0.0 ,_UpperCAmelCase : Optional[Any]=True ,_UpperCAmelCase : str="relu" ,_UpperCAmelCase : Tuple=256 ,_UpperCAmelCase : Optional[int]=0.1 ,_UpperCAmelCase : str=0.0 ,_UpperCAmelCase : Optional[int]=0.0 ,_UpperCAmelCase : Union[str, Any]=0.02 ,_UpperCAmelCase : List[str]=1.0 ,_UpperCAmelCase : Any=False ,_UpperCAmelCase : int="sine" ,_UpperCAmelCase : List[str]="resnet50" ,_UpperCAmelCase : Optional[int]=True ,_UpperCAmelCase : str=False ,_UpperCAmelCase : str=2 ,_UpperCAmelCase : int=5 ,_UpperCAmelCase : Optional[int]=2 ,_UpperCAmelCase : str=1 ,_UpperCAmelCase : Union[str, Any]=1 ,_UpperCAmelCase : List[str]=2 ,_UpperCAmelCase : Union[str, Any]=5 ,_UpperCAmelCase : List[Any]=2 ,_UpperCAmelCase : Optional[int]=0.25 ,**_UpperCAmelCase : Tuple ,): if backbone_config is not None and use_timm_backbone: raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.' ) if not use_timm_backbone: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) _a : Optional[Any] = CONFIG_MAPPING['resnet'](out_features=['stage4'] ) elif isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : str = backbone_config.get('model_type' ) _a : Union[str, Any] = CONFIG_MAPPING[backbone_model_type] _a : List[Any] = config_class.from_dict(_UpperCAmelCase ) _a : Tuple = use_timm_backbone _a : Union[str, Any] = backbone_config _a : List[Any] = num_channels _a : Union[str, Any] = num_queries _a : Optional[Any] = d_model _a : Tuple = encoder_ffn_dim _a : Dict = encoder_layers _a : List[str] = encoder_attention_heads _a : Union[str, Any] = decoder_ffn_dim _a : Optional[int] = decoder_layers _a : int = decoder_attention_heads _a : Optional[int] = dropout _a : Tuple = attention_dropout _a : List[Any] = activation_dropout _a : str = activation_function _a : Optional[Any] = init_std _a : Union[str, Any] = init_xavier_std _a : List[Any] = encoder_layerdrop _a : List[Any] = decoder_layerdrop _a : Dict = encoder_layers _a : List[Any] = auxiliary_loss _a : Optional[int] = position_embedding_type _a : List[Any] = backbone _a : Optional[int] = use_pretrained_backbone _a : Optional[int] = dilation # Hungarian matcher _a : Tuple = class_cost _a : str = bbox_cost _a : Any = giou_cost # Loss coefficients _a : Tuple = mask_loss_coefficient _a : Dict = dice_loss_coefficient _a : Tuple = cls_loss_coefficient _a : Any = bbox_loss_coefficient _a : Dict = giou_loss_coefficient _a : Union[str, Any] = focal_alpha super().__init__(is_encoder_decoder=_UpperCAmelCase ,**_UpperCAmelCase ) @property def __lowercase ( self : Dict ): return self.encoder_attention_heads @property def __lowercase ( self : str ): return self.d_model def __lowercase ( self : int ): _a : List[str] = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: _a : Dict = self.backbone_config.to_dict() _a : Union[str, Any] = self.__class__.model_type return output class __magic_name__ ( _UpperCamelCase ): lowerCAmelCase : str = version.parse('1.11' ) @property def __lowercase ( self : Dict ): return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('pixel_mask', {0: 'batch'}), ] ) @property def __lowercase ( self : Any ): return 1E-5 @property def __lowercase ( self : List[Any] ): return 12
89
0
import multiprocessing import time from arguments import PretokenizationArguments from datasets import load_dataset from transformers import AutoTokenizer, HfArgumentParser def lowercase_ ( _lowerCamelCase : str): lowercase__ : Tuple = {} lowercase__ : Any = tokenizer(example["content"] , truncation=_lowerCamelCase)["input_ids"] lowercase__ : int = len(example["content"]) / len(output["input_ids"]) return output UpperCamelCase = HfArgumentParser(PretokenizationArguments) UpperCamelCase = parser.parse_args() if args.num_workers is None: UpperCamelCase = multiprocessing.cpu_count() UpperCamelCase = AutoTokenizer.from_pretrained(args.tokenizer_dir) UpperCamelCase = time.time() UpperCamelCase = load_dataset(args.dataset_name, split='''train''') print(f"Dataset loaded in {time.time()-t_start:.2f}s") UpperCamelCase = time.time() UpperCamelCase = ds.map( tokenize, num_proc=args.num_workers, remove_columns=[ '''repo_name''', '''path''', '''copies''', '''size''', '''content''', '''license''', '''hash''', '''line_mean''', '''line_max''', '''alpha_frac''', '''autogenerated''', ], ) print(f"Dataset tokenized in {time.time()-t_start:.2f}s") UpperCamelCase = time.time() ds.push_to_hub(args.tokenized_data_repo) print(f"Data pushed to the hub in {time.time()-t_start:.2f}s")
87
'''simple docstring''' import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __magic_name__ : def __init__( self : List[str] ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : List[str]=13 ,_UpperCAmelCase : Any=32 ,_UpperCAmelCase : Union[str, Any]=3 ,_UpperCAmelCase : Optional[int]=4 ,_UpperCAmelCase : Optional[Any]=[10, 20, 30, 40] ,_UpperCAmelCase : Tuple=[2, 2, 3, 2] ,_UpperCAmelCase : Optional[int]=True ,_UpperCAmelCase : Optional[int]=True ,_UpperCAmelCase : Union[str, Any]=37 ,_UpperCAmelCase : Optional[int]="gelu" ,_UpperCAmelCase : Optional[Any]=10 ,_UpperCAmelCase : Tuple=0.02 ,_UpperCAmelCase : Any=["stage2", "stage3", "stage4"] ,_UpperCAmelCase : Any=[2, 3, 4] ,_UpperCAmelCase : Tuple=None ,): _a : Optional[Any] = parent _a : List[Any] = batch_size _a : str = image_size _a : Union[str, Any] = num_channels _a : List[Any] = num_stages _a : Dict = hidden_sizes _a : int = depths _a : Tuple = is_training _a : List[str] = use_labels _a : Dict = intermediate_size _a : int = hidden_act _a : int = num_labels _a : Any = initializer_range _a : Tuple = out_features _a : int = out_indices _a : List[Any] = scope def __lowercase ( self : Dict ): _a : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _a : Union[str, Any] = None if self.use_labels: _a : Tuple = ids_tensor([self.batch_size] ,self.num_labels ) _a : str = self.get_config() return config, pixel_values, labels def __lowercase ( self : Any ): return ConvNextVaConfig( num_channels=self.num_channels ,hidden_sizes=self.hidden_sizes ,depths=self.depths ,num_stages=self.num_stages ,hidden_act=self.hidden_act ,is_decoder=_UpperCAmelCase ,initializer_range=self.initializer_range ,out_features=self.out_features ,out_indices=self.out_indices ,num_labels=self.num_labels ,) def __lowercase ( self : Tuple ,_UpperCAmelCase : Any ,_UpperCAmelCase : Any ,_UpperCAmelCase : Optional[Any] ): _a : Optional[Any] = ConvNextVaModel(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : Any = model(_UpperCAmelCase ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape ,(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) ,) def __lowercase ( self : Tuple ,_UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : int ): _a : List[Any] = ConvNextVaForImageClassification(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : List[str] = model(_UpperCAmelCase ,labels=_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def __lowercase ( self : str ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ): _a : Optional[int] = ConvNextVaBackbone(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : Dict = model(_UpperCAmelCase ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) ,len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) ,[self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) ,len(config.out_features ) ) self.parent.assertListEqual(model.channels ,config.hidden_sizes[1:] ) # verify backbone works with out_features=None _a : Tuple = None _a : List[Any] = ConvNextVaBackbone(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : List[str] = model(_UpperCAmelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) ,1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) ,[self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) ,1 ) self.parent.assertListEqual(model.channels ,[config.hidden_sizes[-1]] ) def __lowercase ( self : Optional[Any] ): _a : Any = self.prepare_config_and_inputs() _a , _a , _a : Union[str, Any] = config_and_inputs _a : Any = {'pixel_values': pixel_values} return config, inputs_dict def __lowercase ( self : str ): _a : Tuple = self.prepare_config_and_inputs() _a , _a , _a : Tuple = config_and_inputs _a : List[Any] = {'pixel_values': pixel_values, 'labels': labels} return config, inputs_dict @require_torch class __magic_name__ ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): lowerCAmelCase : str = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) lowerCAmelCase : str = ( {'feature-extraction': ConvNextVaModel, 'image-classification': ConvNextVaForImageClassification} if is_torch_available() else {} ) lowerCAmelCase : int = False lowerCAmelCase : str = False lowerCAmelCase : Optional[Any] = False lowerCAmelCase : List[str] = False lowerCAmelCase : Optional[int] = False def __lowercase ( self : List[Any] ): _a : str = ConvNextVaModelTester(self ) _a : Tuple = ConfigTester(self ,config_class=_UpperCAmelCase ,has_text_modality=_UpperCAmelCase ,hidden_size=37 ) def __lowercase ( self : Optional[Any] ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __lowercase ( self : str ): return @unittest.skip(reason='ConvNextV2 does not use inputs_embeds' ) def __lowercase ( self : List[Any] ): pass @unittest.skip(reason='ConvNextV2 does not support input and output embeddings' ) def __lowercase ( self : Optional[int] ): pass @unittest.skip(reason='ConvNextV2 does not use feedforward chunking' ) def __lowercase ( self : Any ): pass def __lowercase ( self : List[str] ): if not self.model_tester.is_training: return for model_class in self.all_model_classes: _a , _a : List[Any] = self.model_tester.prepare_config_and_inputs_with_labels() _a : Any = True if model_class.__name__ in [ *get_values(_UpperCAmelCase ), *get_values(_UpperCAmelCase ), ]: continue _a : Optional[Any] = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.train() _a : str = self._prepare_for_class(_UpperCAmelCase ,_UpperCAmelCase ,return_labels=_UpperCAmelCase ) _a : Optional[int] = model(**_UpperCAmelCase ).loss loss.backward() def __lowercase ( self : str ): if not self.model_tester.is_training: return for model_class in self.all_model_classes: _a , _a : Optional[Any] = self.model_tester.prepare_config_and_inputs_with_labels() _a : Optional[int] = False _a : Tuple = True if ( model_class.__name__ in [*get_values(_UpperCAmelCase ), *get_values(_UpperCAmelCase )] or not model_class.supports_gradient_checkpointing ): continue _a : Tuple = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.gradient_checkpointing_enable() model.train() _a : Any = self._prepare_for_class(_UpperCAmelCase ,_UpperCAmelCase ,return_labels=_UpperCAmelCase ) _a : List[Any] = model(**_UpperCAmelCase ).loss loss.backward() def __lowercase ( self : List[Any] ): _a , _a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : int = model_class(_UpperCAmelCase ) _a : Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _a : Dict = [*signature.parameters.keys()] _a : int = ['pixel_values'] self.assertListEqual(arg_names[:1] ,_UpperCAmelCase ) def __lowercase ( self : int ): _a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase ) def __lowercase ( self : Any ): def check_hidden_states_output(_UpperCAmelCase : List[Any] ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Dict ): _a : Union[str, Any] = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() with torch.no_grad(): _a : List[Any] = model(**self._prepare_for_class(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Any = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _a : str = self.model_tester.num_stages self.assertEqual(len(_UpperCAmelCase ) ,expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) ,[self.model_tester.image_size // 4, self.model_tester.image_size // 4] ,) _a , _a : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : int = True check_hidden_states_output(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _a : Optional[Any] = True check_hidden_states_output(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) def __lowercase ( self : List[Any] ): _a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase ) @slow def __lowercase ( self : int ): for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Any = ConvNextVaModel.from_pretrained(_UpperCAmelCase ) self.assertIsNotNone(_UpperCAmelCase ) def __lowerCamelCase ( ) -> List[Any]: _a : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class __magic_name__ ( unittest.TestCase ): @cached_property def __lowercase ( self : Optional[Any] ): return AutoImageProcessor.from_pretrained('facebook/convnextv2-tiny-1k-224' ) if is_vision_available() else None @slow def __lowercase ( self : Any ): _a : List[str] = ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224' ).to(_UpperCAmelCase ) _a : Optional[int] = self.default_image_processor _a : str = prepare_img() _a : str = preprocessor(images=_UpperCAmelCase ,return_tensors='pt' ).to(_UpperCAmelCase ) # forward pass with torch.no_grad(): _a : Dict = model(**_UpperCAmelCase ) # verify the logits _a : Optional[Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape ,_UpperCAmelCase ) _a : Optional[Any] = torch.tensor([0.99_96, 0.19_66, -0.43_86] ).to(_UpperCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,_UpperCAmelCase ,atol=1E-4 ) )
89
0
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer from ...utils import logging __lowerCAmelCase : str = logging.get_logger(__name__) __lowerCAmelCase : Dict = '▁' __lowerCAmelCase : Optional[Any] = {'vocab_file': 'sentencepiece.bpe.model'} __lowerCAmelCase : Union[str, Any] = { 'vocab_file': { 'facebook/mbart-large-en-ro': ( 'https://huggingface.co/facebook/mbart-large-en-ro/resolve/main/sentencepiece.bpe.model' ), 'facebook/mbart-large-cc25': ( 'https://huggingface.co/facebook/mbart-large-cc25/resolve/main/sentencepiece.bpe.model' ), } } __lowerCAmelCase : Union[str, Any] = { 'facebook/mbart-large-en-ro': 1024, 'facebook/mbart-large-cc25': 1024, } # fmt: off __lowerCAmelCase : Optional[Any] = ['ar_AR', 'cs_CZ', 'de_DE', 'en_XX', 'es_XX', 'et_EE', 'fi_FI', 'fr_XX', 'gu_IN', 'hi_IN', 'it_IT', 'ja_XX', 'kk_KZ', 'ko_KR', 'lt_LT', 'lv_LV', 'my_MM', 'ne_NP', 'nl_XX', 'ro_RO', 'ru_RU', 'si_LK', 'tr_TR', 'vi_VN', 'zh_CN'] class UpperCAmelCase_ ( _A ): '''simple docstring''' a__ = VOCAB_FILES_NAMES a__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ = PRETRAINED_VOCAB_FILES_MAP a__ = ["""input_ids""", """attention_mask"""] a__ = [] a__ = [] def __init__( self : List[str] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Tuple="<s>" , UpperCamelCase__ : int="</s>" , UpperCamelCase__ : Any="</s>" , UpperCamelCase__ : int="<s>" , UpperCamelCase__ : Dict="<unk>" , UpperCamelCase__ : Tuple="<pad>" , UpperCamelCase__ : str="<mask>" , UpperCamelCase__ : Dict=None , UpperCamelCase__ : str=None , UpperCamelCase__ : Any=None , UpperCamelCase__ : Optional[Dict[str, Any]] = None , UpperCamelCase__ : Optional[int]=None , **UpperCamelCase__ : int , ) -> List[Any]: """simple docstring""" __magic_name__ = AddedToken(UpperCamelCase__ , lstrip=UpperCamelCase__ , rstrip=UpperCamelCase__ ) if isinstance(UpperCamelCase__ , UpperCamelCase__ ) else mask_token __magic_name__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=UpperCamelCase__ , eos_token=UpperCamelCase__ , unk_token=UpperCamelCase__ , sep_token=UpperCamelCase__ , cls_token=UpperCamelCase__ , pad_token=UpperCamelCase__ , mask_token=UpperCamelCase__ , tokenizer_file=UpperCamelCase__ , src_lang=UpperCamelCase__ , tgt_lang=UpperCamelCase__ , additional_special_tokens=UpperCamelCase__ , sp_model_kwargs=self.sp_model_kwargs , **UpperCamelCase__ , ) __magic_name__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(UpperCamelCase__ ) ) __magic_name__ = vocab_file # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | '<s>' | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's' | '▁de' | '-' # spm | '<unk>' | '<s>' | '</s>' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a' # Mimic fairseq token-to-id alignment for the first 4 token __magic_name__ = {"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3} # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab __magic_name__ = 1 __magic_name__ = len(self.sp_model ) __magic_name__ = { code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(UpperCamelCase__ ) } __magic_name__ = {v: k for k, v in self.lang_code_to_id.items()} __magic_name__ = len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset self.fairseq_tokens_to_ids.update(self.lang_code_to_id ) __magic_name__ = {v: k for k, v in self.fairseq_tokens_to_ids.items()} __magic_name__ = list(self.lang_code_to_id.keys() ) if additional_special_tokens is not None: # Only add those special tokens if they are not already there. self._additional_special_tokens.extend( [t for t in additional_special_tokens if t not in self._additional_special_tokens] ) __magic_name__ = src_lang if src_lang is not None else """en_XX""" __magic_name__ = self.lang_code_to_id[self._src_lang] __magic_name__ = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) def __getstate__( self : int ) -> int: """simple docstring""" __magic_name__ = self.__dict__.copy() __magic_name__ = None __magic_name__ = self.sp_model.serialized_model_proto() return state def __setstate__( self : Tuple , UpperCamelCase__ : int ) -> Dict: """simple docstring""" __magic_name__ = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): __magic_name__ = {} __magic_name__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.LoadFromSerializedProto(self.sp_model_proto ) @property def _lowercase ( self : Dict ) -> str: """simple docstring""" return len(self.sp_model ) + len(self.lang_code_to_id ) + self.fairseq_offset + 1 # Plus 1 for the mask token @property def _lowercase ( self : Union[str, Any] ) -> str: """simple docstring""" return self._src_lang @src_lang.setter def _lowercase ( self : Optional[int] , UpperCamelCase__ : str ) -> None: """simple docstring""" __magic_name__ = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None , UpperCamelCase__ : bool = 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__ ) __magic_name__ = [1] * len(self.prefix_tokens ) __magic_name__ = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(UpperCamelCase__ )) + suffix_ones return prefix_ones + ([0] * len(UpperCamelCase__ )) + ([0] * len(UpperCamelCase__ )) + suffix_ones def _lowercase ( self : List[Any] , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = 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 : Union[str, Any] , UpperCamelCase__ : List[int] , UpperCamelCase__ : Optional[List[int]] = None ) -> List[int]: """simple docstring""" __magic_name__ = [self.sep_token_id] __magic_name__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def _lowercase ( self : Optional[Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : str , UpperCamelCase__ : Optional[str] , UpperCamelCase__ : Optional[str] , **UpperCamelCase__ : int ) -> List[Any]: """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""" ) __magic_name__ = src_lang __magic_name__ = self(UpperCamelCase__ , add_special_tokens=UpperCamelCase__ , return_tensors=UpperCamelCase__ , **UpperCamelCase__ ) __magic_name__ = self.convert_tokens_to_ids(UpperCamelCase__ ) __magic_name__ = tgt_lang_id return inputs def _lowercase ( self : Optional[int] ) -> Any: """simple docstring""" __magic_name__ = {self.convert_ids_to_tokens(UpperCamelCase__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def _lowercase ( self : Optional[Any] , UpperCamelCase__ : str ) -> List[str]: """simple docstring""" return self.sp_model.encode(UpperCamelCase__ , out_type=UpperCamelCase__ ) def _lowercase ( self : Dict , UpperCamelCase__ : Optional[int] ) -> List[str]: """simple docstring""" if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] __magic_name__ = self.sp_model.PieceToId(UpperCamelCase__ ) # Need to return unknown token if the SP model returned 0 return spm_id + self.fairseq_offset if spm_id else self.unk_token_id def _lowercase ( self : Any , UpperCamelCase__ : List[Any] ) -> Any: """simple docstring""" if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def _lowercase ( self : Any , UpperCamelCase__ : Tuple ) -> str: """simple docstring""" __magic_name__ = """""".join(UpperCamelCase__ ).replace(UpperCamelCase__ , """ """ ).strip() return out_string def _lowercase ( self : Dict , UpperCamelCase__ : str , UpperCamelCase__ : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(UpperCamelCase__ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return __magic_name__ = os.path.join( UpperCamelCase__ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) 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: __magic_name__ = self.sp_model.serialized_model_proto() fi.write(UpperCamelCase__ ) return (out_vocab_file,) def _lowercase ( self : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : str = "en_XX" , UpperCamelCase__ : Optional[List[str]] = None , UpperCamelCase__ : str = "ro_RO" , **UpperCamelCase__ : int , ) -> BatchEncoding: """simple docstring""" __magic_name__ = src_lang __magic_name__ = tgt_lang return super().prepare_seqaseq_batch(UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__ ) def _lowercase ( self : Optional[int] ) -> List[str]: """simple docstring""" return self.set_src_lang_special_tokens(self.src_lang ) def _lowercase ( self : Optional[Any] ) -> Union[str, Any]: """simple docstring""" return self.set_tgt_lang_special_tokens(self.tgt_lang ) def _lowercase ( self : Union[str, Any] , UpperCamelCase__ : str ) -> None: """simple docstring""" __magic_name__ = self.lang_code_to_id[src_lang] __magic_name__ = [] __magic_name__ = [self.eos_token_id, self.cur_lang_code] def _lowercase ( self : Tuple , UpperCamelCase__ : str ) -> None: """simple docstring""" __magic_name__ = self.lang_code_to_id[lang] __magic_name__ = [] __magic_name__ = [self.eos_token_id, self.cur_lang_code]
88
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCAmelCase = { '''configuration_lilt''': ['''LILT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LiltConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''LILT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''LiltForQuestionAnswering''', '''LiltForSequenceClassification''', '''LiltForTokenClassification''', '''LiltModel''', '''LiltPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_lilt import LILT_PRETRAINED_CONFIG_ARCHIVE_MAP, LiltConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lilt import ( LILT_PRETRAINED_MODEL_ARCHIVE_LIST, LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, LiltPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
89
0
import argparse import os import pickle import sys import torch from transformers import TransfoXLConfig, TransfoXLLMHeadModel, load_tf_weights_in_transfo_xl from transformers.models.transfo_xl import tokenization_transfo_xl as data_utils from transformers.models.transfo_xl.tokenization_transfo_xl import CORPUS_NAME, VOCAB_FILES_NAMES from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging logging.set_verbosity_info() # We do this to be able to load python 2 datasets pickles # See e.g. https://stackoverflow.com/questions/2121874/python-pickling-after-changing-a-modules-directory/2121918#2121918 __A = data_utils.TransfoXLTokenizer __A = data_utils.TransfoXLCorpus __A = data_utils __A = data_utils def lowerCamelCase_ ( UpperCamelCase__ : List[str] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Optional[Any] ) -> Union[str, Any]: """simple docstring""" if transfo_xl_dataset_file: # Convert a pre-processed corpus (see original TensorFlow repo) with open(UpperCamelCase__ , 'rb' ) as fp: __lowerCamelCase = pickle.load(UpperCamelCase__ , encoding='latin1' ) # Save vocabulary and dataset cache as Dictionaries (should be better than pickles for the long-term) __lowerCamelCase = pytorch_dump_folder_path + '/' + VOCAB_FILES_NAMES['pretrained_vocab_file'] print(F"""Save vocabulary to {pytorch_vocab_dump_path}""" ) __lowerCamelCase = corpus.vocab.__dict__ torch.save(UpperCamelCase__ , UpperCamelCase__ ) __lowerCamelCase = corpus.__dict__ corpus_dict_no_vocab.pop('vocab' , UpperCamelCase__ ) __lowerCamelCase = pytorch_dump_folder_path + '/' + CORPUS_NAME print(F"""Save dataset to {pytorch_dataset_dump_path}""" ) torch.save(UpperCamelCase__ , UpperCamelCase__ ) if tf_checkpoint_path: # Convert a pre-trained TensorFlow model __lowerCamelCase = os.path.abspath(UpperCamelCase__ ) __lowerCamelCase = os.path.abspath(UpperCamelCase__ ) print(F"""Converting Transformer XL checkpoint from {tf_path} with config at {config_path}.""" ) # Initialise PyTorch model if transfo_xl_config_file == "": __lowerCamelCase = TransfoXLConfig() else: __lowerCamelCase = TransfoXLConfig.from_json_file(UpperCamelCase__ ) print(F"""Building PyTorch model from configuration: {config}""" ) __lowerCamelCase = TransfoXLLMHeadModel(UpperCamelCase__ ) __lowerCamelCase = load_tf_weights_in_transfo_xl(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) # Save pytorch-model __lowerCamelCase = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) __lowerCamelCase = os.path.join(UpperCamelCase__ , UpperCamelCase__ ) print(F"""Save PyTorch model to {os.path.abspath(UpperCamelCase__ )}""" ) torch.save(model.state_dict() , UpperCamelCase__ ) print(F"""Save configuration file to {os.path.abspath(UpperCamelCase__ )}""" ) with open(UpperCamelCase__ , 'w' , encoding='utf-8' ) as f: f.write(config.to_json_string() ) if __name__ == "__main__": __A = argparse.ArgumentParser() parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, required=True, help="Path to the folder to store the PyTorch model or dataset/vocab.", ) parser.add_argument( "--tf_checkpoint_path", default="", type=str, help="An optional path to a TensorFlow checkpoint path to be converted.", ) parser.add_argument( "--transfo_xl_config_file", default="", type=str, help=( "An optional config json file corresponding to the pre-trained BERT model. \n" "This specifies the model architecture." ), ) parser.add_argument( "--transfo_xl_dataset_file", default="", type=str, help="An optional dataset file to be converted in a vocabulary.", ) __A = parser.parse_args() convert_transfo_xl_checkpoint_to_pytorch( args.tf_checkpoint_path, args.transfo_xl_config_file, args.pytorch_dump_folder_path, args.transfo_xl_dataset_file, )
90
'''simple docstring''' import math def __lowerCamelCase ( lowerCAmelCase_ ) -> bool: _a : Optional[int] = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(lowerCAmelCase_ ) def __lowerCamelCase ( lowerCAmelCase_ = 1 / 12345 ) -> int: _a : int = 0 _a : Optional[Any] = 0 _a : int = 3 while True: _a : Tuple = (integer**2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(lowerCAmelCase_ ): _a : Union[str, Any] = int(lowerCAmelCase_ ) total_partitions += 1 if check_partition_perfect(lowerCAmelCase_ ): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return int(lowerCAmelCase_ ) integer += 1 if __name__ == "__main__": print(f"""{solution() = }""")
89
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available UpperCAmelCase_ : Optional[Any] = { """configuration_tapas""": ["""TAPAS_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TapasConfig"""], """tokenization_tapas""": ["""TapasTokenizer"""], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ : int = [ """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: UpperCAmelCase_ : int = [ """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 UpperCAmelCase_ : Optional[int] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
91
'''simple docstring''' import argparse import json import torch from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=1 ) -> Dict: if n_shave_prefix_segments >= 0: return ".".join(path.split('.' )[n_shave_prefix_segments:] ) else: return ".".join(path.split('.' )[:n_shave_prefix_segments] ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=0 ) -> Tuple: _a : Any = [] for old_item in old_list: _a : Union[str, Any] = old_item.replace('in_layers.0' , 'norm1' ) _a : Optional[int] = new_item.replace('in_layers.2' , 'conv1' ) _a : str = new_item.replace('out_layers.0' , 'norm2' ) _a : List[str] = new_item.replace('out_layers.3' , 'conv2' ) _a : str = new_item.replace('emb_layers.1' , 'time_emb_proj' ) _a : Tuple = new_item.replace('skip_connection' , 'conv_shortcut' ) _a : Any = shave_segments(lowerCAmelCase_ , n_shave_prefix_segments=lowerCAmelCase_ ) mapping.append({'old': old_item, 'new': new_item} ) return mapping def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=0 ) -> Any: _a : List[str] = [] for old_item in old_list: _a : List[Any] = old_item _a : Optional[int] = new_item.replace('norm.weight' , 'group_norm.weight' ) _a : Optional[Any] = new_item.replace('norm.bias' , 'group_norm.bias' ) _a : Any = new_item.replace('proj_out.weight' , 'proj_attn.weight' ) _a : Optional[Any] = new_item.replace('proj_out.bias' , 'proj_attn.bias' ) _a : Optional[int] = shave_segments(lowerCAmelCase_ , n_shave_prefix_segments=lowerCAmelCase_ ) mapping.append({'old': old_item, 'new': new_item} ) return mapping def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None , lowerCAmelCase_=None , lowerCAmelCase_=None ) -> Any: assert isinstance(lowerCAmelCase_ , lowerCAmelCase_ ), "Paths should be a list of dicts containing 'old' and 'new' keys." # Splits the attention layers into three variables. if attention_paths_to_split is not None: for path, path_map in attention_paths_to_split.items(): _a : Optional[Any] = old_checkpoint[path] _a : Optional[Any] = old_tensor.shape[0] // 3 _a : Any = (-1, channels) if len(old_tensor.shape ) == 3 else (-1) _a : int = old_tensor.shape[0] // config['num_head_channels'] // 3 _a : str = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:] ) _a , _a , _a : Tuple = old_tensor.split(channels // num_heads , dim=1 ) _a : Dict = query.reshape(lowerCAmelCase_ ) _a : str = key.reshape(lowerCAmelCase_ ) _a : Optional[int] = value.reshape(lowerCAmelCase_ ) for path in paths: _a : Dict = path['new'] # These have already been assigned if attention_paths_to_split is not None and new_path in attention_paths_to_split: continue # Global renaming happens here _a : Any = new_path.replace('middle_block.0' , 'mid_block.resnets.0' ) _a : str = new_path.replace('middle_block.1' , 'mid_block.attentions.0' ) _a : Union[str, Any] = new_path.replace('middle_block.2' , 'mid_block.resnets.1' ) if additional_replacements is not None: for replacement in additional_replacements: _a : int = new_path.replace(replacement['old'] , replacement['new'] ) # proj_attn.weight has to be converted from conv 1D to linear if "proj_attn.weight" in new_path: _a : List[str] = old_checkpoint[path['old']][:, :, 0] else: _a : Dict = old_checkpoint[path['old']] def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> List[Any]: _a : Optional[int] = {} _a : Dict = checkpoint['time_embed.0.weight'] _a : Tuple = checkpoint['time_embed.0.bias'] _a : Union[str, Any] = checkpoint['time_embed.2.weight'] _a : List[str] = checkpoint['time_embed.2.bias'] _a : List[str] = checkpoint['input_blocks.0.0.weight'] _a : Union[str, Any] = checkpoint['input_blocks.0.0.bias'] _a : Optional[int] = checkpoint['out.0.weight'] _a : int = checkpoint['out.0.bias'] _a : List[str] = checkpoint['out.2.weight'] _a : Optional[int] = checkpoint['out.2.bias'] # Retrieves the keys for the input blocks only _a : Optional[int] = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'input_blocks' in layer} ) _a : Dict = { layer_id: [key for key in checkpoint if f"""input_blocks.{layer_id}""" in key] for layer_id in range(lowerCAmelCase_ ) } # Retrieves the keys for the middle blocks only _a : List[Any] = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'middle_block' in layer} ) _a : Union[str, Any] = { layer_id: [key for key in checkpoint if f"""middle_block.{layer_id}""" in key] for layer_id in range(lowerCAmelCase_ ) } # Retrieves the keys for the output blocks only _a : Optional[int] = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'output_blocks' in layer} ) _a : str = { layer_id: [key for key in checkpoint if f"""output_blocks.{layer_id}""" in key] for layer_id in range(lowerCAmelCase_ ) } for i in range(1 , lowerCAmelCase_ ): _a : List[Any] = (i - 1) // (config['num_res_blocks'] + 1) _a : Optional[int] = (i - 1) % (config['num_res_blocks'] + 1) _a : Optional[int] = [key for key in input_blocks[i] if f"""input_blocks.{i}.0""" in key] _a : Optional[Any] = [key for key in input_blocks[i] if f"""input_blocks.{i}.1""" in key] if f"""input_blocks.{i}.0.op.weight""" in checkpoint: _a : List[Any] = checkpoint[ f"""input_blocks.{i}.0.op.weight""" ] _a : Union[str, Any] = checkpoint[ f"""input_blocks.{i}.0.op.bias""" ] continue _a : Any = renew_resnet_paths(lowerCAmelCase_ ) _a : List[str] = {'old': f"""input_blocks.{i}.0""", 'new': f"""down_blocks.{block_id}.resnets.{layer_in_block_id}"""} _a : Optional[Any] = {'old': 'resnets.2.op', 'new': 'downsamplers.0.op'} assign_to_checkpoint( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , additional_replacements=[meta_path, resnet_op] , config=lowerCAmelCase_ ) if len(lowerCAmelCase_ ): _a : List[str] = renew_attention_paths(lowerCAmelCase_ ) _a : List[Any] = { 'old': f"""input_blocks.{i}.1""", 'new': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}""", } _a : Optional[Any] = { f"""input_blocks.{i}.1.qkv.bias""": { 'key': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias""", 'query': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias""", 'value': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias""", }, f"""input_blocks.{i}.1.qkv.weight""": { 'key': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight""", 'query': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight""", 'value': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight""", }, } assign_to_checkpoint( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , additional_replacements=[meta_path] , attention_paths_to_split=lowerCAmelCase_ , config=lowerCAmelCase_ , ) _a : str = middle_blocks[0] _a : Tuple = middle_blocks[1] _a : Any = middle_blocks[2] _a : List[Any] = renew_resnet_paths(lowerCAmelCase_ ) assign_to_checkpoint(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , config=lowerCAmelCase_ ) _a : Any = renew_resnet_paths(lowerCAmelCase_ ) assign_to_checkpoint(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , config=lowerCAmelCase_ ) _a : int = renew_attention_paths(lowerCAmelCase_ ) _a : int = { 'middle_block.1.qkv.bias': { 'key': 'mid_block.attentions.0.key.bias', 'query': 'mid_block.attentions.0.query.bias', 'value': 'mid_block.attentions.0.value.bias', }, 'middle_block.1.qkv.weight': { 'key': 'mid_block.attentions.0.key.weight', 'query': 'mid_block.attentions.0.query.weight', 'value': 'mid_block.attentions.0.value.weight', }, } assign_to_checkpoint( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , attention_paths_to_split=lowerCAmelCase_ , config=lowerCAmelCase_ ) for i in range(lowerCAmelCase_ ): _a : List[str] = i // (config['num_res_blocks'] + 1) _a : Any = i % (config['num_res_blocks'] + 1) _a : Union[str, Any] = [shave_segments(lowerCAmelCase_ , 2 ) for name in output_blocks[i]] _a : Optional[Any] = {} for layer in output_block_layers: _a , _a : str = layer.split('.' )[0], shave_segments(lowerCAmelCase_ , 1 ) if layer_id in output_block_list: output_block_list[layer_id].append(lowerCAmelCase_ ) else: _a : str = [layer_name] if len(lowerCAmelCase_ ) > 1: _a : str = [key for key in output_blocks[i] if f"""output_blocks.{i}.0""" in key] _a : Optional[Any] = [key for key in output_blocks[i] if f"""output_blocks.{i}.1""" in key] _a : Dict = renew_resnet_paths(lowerCAmelCase_ ) _a : str = renew_resnet_paths(lowerCAmelCase_ ) _a : Optional[int] = {'old': f"""output_blocks.{i}.0""", 'new': f"""up_blocks.{block_id}.resnets.{layer_in_block_id}"""} assign_to_checkpoint(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , additional_replacements=[meta_path] , config=lowerCAmelCase_ ) if ["conv.weight", "conv.bias"] in output_block_list.values(): _a : List[Any] = list(output_block_list.values() ).index(['conv.weight', 'conv.bias'] ) _a : Tuple = checkpoint[ f"""output_blocks.{i}.{index}.conv.weight""" ] _a : List[str] = checkpoint[ f"""output_blocks.{i}.{index}.conv.bias""" ] # Clear attentions as they have been attributed above. if len(lowerCAmelCase_ ) == 2: _a : Union[str, Any] = [] if len(lowerCAmelCase_ ): _a : Tuple = renew_attention_paths(lowerCAmelCase_ ) _a : str = { 'old': f"""output_blocks.{i}.1""", 'new': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}""", } _a : List[Any] = { f"""output_blocks.{i}.1.qkv.bias""": { 'key': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias""", 'query': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias""", 'value': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias""", }, f"""output_blocks.{i}.1.qkv.weight""": { 'key': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight""", 'query': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight""", 'value': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight""", }, } assign_to_checkpoint( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , additional_replacements=[meta_path] , attention_paths_to_split=to_split if any('qkv' in key for key in attentions ) else None , config=lowerCAmelCase_ , ) else: _a : List[Any] = renew_resnet_paths(lowerCAmelCase_ , n_shave_prefix_segments=1 ) for path in resnet_0_paths: _a : int = '.'.join(['output_blocks', str(lowerCAmelCase_ ), path['old']] ) _a : Union[str, Any] = '.'.join(['up_blocks', str(lowerCAmelCase_ ), 'resnets', str(lowerCAmelCase_ ), path['new']] ) _a : Union[str, Any] = checkpoint[old_path] return new_checkpoint if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the architecture.''', ) parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') __lowerCAmelCase = parser.parse_args() __lowerCAmelCase = torch.load(args.checkpoint_path) with open(args.config_file) as f: __lowerCAmelCase = json.loads(f.read()) __lowerCAmelCase = convert_ldm_checkpoint(checkpoint, config) if "ldm" in config: del config["ldm"] __lowerCAmelCase = UNetaDModel(**config) model.load_state_dict(converted_checkpoint) try: __lowerCAmelCase = DDPMScheduler.from_config('''/'''.join(args.checkpoint_path.split('''/''')[:-1])) __lowerCAmelCase = VQModel.from_pretrained('''/'''.join(args.checkpoint_path.split('''/''')[:-1])) __lowerCAmelCase = LDMPipeline(unet=model, scheduler=scheduler, vae=vqvae) pipe.save_pretrained(args.dump_path) except: # noqa: E722 model.save_pretrained(args.dump_path)
89
0
def _a ( SCREAMING_SNAKE_CASE_ : int ): if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): raise ValueError("multiplicative_persistence() only accepts integral values" ) if num < 0: raise ValueError("multiplicative_persistence() does not accept negative values" ) __lowerCAmelCase = 0 __lowerCAmelCase = str(SCREAMING_SNAKE_CASE_ ) while len(SCREAMING_SNAKE_CASE_ ) != 1: __lowerCAmelCase = [int(SCREAMING_SNAKE_CASE_ ) for i in num_string] __lowerCAmelCase = 1 for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) ): total *= numbers[i] __lowerCAmelCase = str(SCREAMING_SNAKE_CASE_ ) steps += 1 return steps def _a ( SCREAMING_SNAKE_CASE_ : int ): if not isinstance(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ): raise ValueError("additive_persistence() only accepts integral values" ) if num < 0: raise ValueError("additive_persistence() does not accept negative values" ) __lowerCAmelCase = 0 __lowerCAmelCase = str(SCREAMING_SNAKE_CASE_ ) while len(SCREAMING_SNAKE_CASE_ ) != 1: __lowerCAmelCase = [int(SCREAMING_SNAKE_CASE_ ) for i in num_string] __lowerCAmelCase = 0 for i in range(0 , len(SCREAMING_SNAKE_CASE_ ) ): total += numbers[i] __lowerCAmelCase = str(SCREAMING_SNAKE_CASE_ ) steps += 1 return steps if __name__ == "__main__": import doctest doctest.testmod()
92
'''simple docstring''' import datetime import platform import subprocess from typing import Optional, Tuple, Union import numpy as np def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> np.array: _a : Optional[int] = f"""{sampling_rate}""" _a : Any = '1' _a : Optional[int] = 'f32le' _a : Any = [ 'ffmpeg', '-i', 'pipe:0', '-ac', ac, '-ar', ar, '-f', format_for_conversion, '-hide_banner', '-loglevel', 'quiet', 'pipe:1', ] try: with subprocess.Popen(lowerCAmelCase_ , stdin=subprocess.PIPE , stdout=subprocess.PIPE ) as ffmpeg_process: _a : int = ffmpeg_process.communicate(lowerCAmelCase_ ) except FileNotFoundError as error: raise ValueError('ffmpeg was not found but is required to load audio files from filename' ) from error _a : int = output_stream[0] _a : List[str] = np.frombuffer(lowerCAmelCase_ , np.floataa ) if audio.shape[0] == 0: raise ValueError('Malformed soundfile' ) return audio def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = "f32le" , ) -> Union[str, Any]: _a : List[str] = f"""{sampling_rate}""" _a : List[str] = '1' if format_for_conversion == "s16le": _a : List[Any] = 2 elif format_for_conversion == "f32le": _a : Dict = 4 else: raise ValueError(f"""Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`""" ) _a : Any = platform.system() if system == "Linux": _a : Union[str, Any] = 'alsa' _a : Union[str, Any] = 'default' elif system == "Darwin": _a : Any = 'avfoundation' _a : Optional[int] = ':0' elif system == "Windows": _a : str = 'dshow' _a : Tuple = 'default' _a : str = [ 'ffmpeg', '-f', format_, '-i', input_, '-ac', ac, '-ar', ar, '-f', format_for_conversion, '-fflags', 'nobuffer', '-hide_banner', '-loglevel', 'quiet', 'pipe:1', ] _a : Any = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample _a : Union[str, Any] = _ffmpeg_stream(lowerCAmelCase_ , lowerCAmelCase_ ) for item in iterator: yield item def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = "f32le" , ) -> str: if stream_chunk_s is not None: _a : str = stream_chunk_s else: _a : List[str] = chunk_length_s _a : int = ffmpeg_microphone(lowerCAmelCase_ , lowerCAmelCase_ , format_for_conversion=lowerCAmelCase_ ) if format_for_conversion == "s16le": _a : Optional[Any] = np.intaa _a : List[Any] = 2 elif format_for_conversion == "f32le": _a : Tuple = np.floataa _a : Any = 4 else: raise ValueError(f"""Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`""" ) if stride_length_s is None: _a : str = chunk_length_s / 6 _a : Any = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample if isinstance(lowerCAmelCase_ , (int, float) ): _a : List[str] = [stride_length_s, stride_length_s] _a : str = int(round(sampling_rate * stride_length_s[0] ) ) * size_of_sample _a : List[str] = int(round(sampling_rate * stride_length_s[1] ) ) * size_of_sample _a : Any = datetime.datetime.now() _a : Dict = datetime.timedelta(seconds=lowerCAmelCase_ ) for item in chunk_bytes_iter(lowerCAmelCase_ , lowerCAmelCase_ , stride=(stride_left, stride_right) , stream=lowerCAmelCase_ ): # Put everything back in numpy scale _a : List[Any] = np.frombuffer(item['raw'] , dtype=lowerCAmelCase_ ) _a : List[str] = ( item['stride'][0] // size_of_sample, item['stride'][1] // size_of_sample, ) _a : Union[str, Any] = sampling_rate audio_time += delta if datetime.datetime.now() > audio_time + 10 * delta: # We're late !! SKIP continue yield item def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = False ) -> List[Any]: _a : Tuple = B'' _a , _a : str = stride if stride_left + stride_right >= chunk_len: raise ValueError( f"""Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}""" ) _a : Optional[int] = 0 for raw in iterator: acc += raw if stream and len(lowerCAmelCase_ ) < chunk_len: _a : str = (_stride_left, 0) yield {"raw": acc[:chunk_len], "stride": stride, "partial": True} else: while len(lowerCAmelCase_ ) >= chunk_len: # We are flushing the accumulator _a : Union[str, Any] = (_stride_left, stride_right) _a : Dict = {'raw': acc[:chunk_len], 'stride': stride} if stream: _a : List[str] = False yield item _a : int = stride_left _a : List[Any] = acc[chunk_len - stride_left - stride_right :] # Last chunk if len(lowerCAmelCase_ ) > stride_left: _a : str = {'raw': acc, 'stride': (_stride_left, 0)} if stream: _a : str = False yield item def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> Tuple: _a : Optional[Any] = 2**24 # 16Mo try: with subprocess.Popen(lowerCAmelCase_ , stdout=subprocess.PIPE , bufsize=lowerCAmelCase_ ) as ffmpeg_process: while True: _a : Any = ffmpeg_process.stdout.read(lowerCAmelCase_ ) if raw == b"": break yield raw except FileNotFoundError as error: raise ValueError('ffmpeg was not found but is required to stream audio files from filename' ) from error
89
0
'''simple docstring''' import inspect import unittest from datasets import load_dataset from packaging import version from transformers import BeitConfig from transformers.models.auto import get_values from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_MAPPING, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, ) from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): import PIL from PIL import Image from transformers import BeitImageProcessor class lowerCAmelCase__ : def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=1_00 , __SCREAMING_SNAKE_CASE=13 , __SCREAMING_SNAKE_CASE=30 , __SCREAMING_SNAKE_CASE=2 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=True , __SCREAMING_SNAKE_CASE=32 , __SCREAMING_SNAKE_CASE=4 , __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=10 , __SCREAMING_SNAKE_CASE=0.02 , __SCREAMING_SNAKE_CASE=3 , __SCREAMING_SNAKE_CASE=None , __SCREAMING_SNAKE_CASE=[0, 1, 2, 3] , ): """simple docstring""" lowercase_ : Optional[int] = parent lowercase_ : Tuple = 1_00 lowercase_ : Any = batch_size lowercase_ : Union[str, Any] = image_size lowercase_ : Dict = patch_size lowercase_ : List[str] = num_channels lowercase_ : str = is_training lowercase_ : Any = use_labels lowercase_ : Optional[int] = hidden_size lowercase_ : List[Any] = num_hidden_layers lowercase_ : Optional[int] = num_attention_heads lowercase_ : Union[str, Any] = intermediate_size lowercase_ : Any = hidden_act lowercase_ : List[Any] = hidden_dropout_prob lowercase_ : Tuple = attention_probs_dropout_prob lowercase_ : Dict = type_sequence_label_size lowercase_ : Optional[Any] = initializer_range lowercase_ : str = scope lowercase_ : str = out_indices lowercase_ : List[str] = num_labels # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) lowercase_ : Tuple = (image_size // patch_size) ** 2 lowercase_ : int = num_patches + 1 def _snake_case ( self ): """simple docstring""" lowercase_ : List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase_ : List[str] = None lowercase_ : int = None if self.use_labels: lowercase_ : str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase_ : Dict = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels ) lowercase_ : int = self.get_config() return config, pixel_values, labels, pixel_labels def _snake_case ( self ): """simple docstring""" return BeitConfig( vocab_size=self.vocab_size , image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__SCREAMING_SNAKE_CASE , initializer_range=self.initializer_range , out_indices=self.out_indices , ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[str] = BeitModel(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() lowercase_ : 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 ): """simple docstring""" lowercase_ : str = BeitForMaskedImageModeling(config=__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() lowercase_ : int = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length - 1, self.vocab_size) ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : List[Any] = self.type_sequence_label_size lowercase_ : List[Any] = BeitForImageClassification(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() lowercase_ : List[str] = model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images lowercase_ : Optional[int] = 1 lowercase_ : Optional[Any] = BeitForImageClassification(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() lowercase_ : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowercase_ : Tuple = model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def _snake_case ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Tuple = self.num_labels lowercase_ : List[str] = BeitForSemanticSegmentation(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.eval() lowercase_ : List[str] = model(__SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) lowercase_ : int = model(__SCREAMING_SNAKE_CASE , labels=__SCREAMING_SNAKE_CASE ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2) ) def _snake_case ( self ): """simple docstring""" lowercase_ : List[str] = self.prepare_config_and_inputs() lowercase_ , lowercase_ , lowercase_ , lowercase_ : Optional[Any] = config_and_inputs lowercase_ : Dict = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowerCAmelCase__ ( lowerCamelCase_ , lowerCamelCase_ , unittest.TestCase ): lowerCAmelCase_ = ( (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation) if is_torch_available() else () ) lowerCAmelCase_ = ( { '''feature-extraction''': BeitModel, '''image-classification''': BeitForImageClassification, '''image-segmentation''': BeitForSemanticSegmentation, } if is_torch_available() else {} ) lowerCAmelCase_ = False lowerCAmelCase_ = False lowerCAmelCase_ = False def _snake_case ( self ): """simple docstring""" lowercase_ : Any = BeitModelTester(self ) lowercase_ : Dict = ConfigTester(self , config_class=__SCREAMING_SNAKE_CASE , has_text_modality=__SCREAMING_SNAKE_CASE , hidden_size=37 ) def _snake_case ( self ): """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='''BEiT does not use inputs_embeds''' ) def _snake_case ( self ): """simple docstring""" pass @require_torch_multi_gpu @unittest.skip(reason='''BEiT has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def _snake_case ( self ): """simple docstring""" pass def _snake_case ( self ): """simple docstring""" lowercase_ , lowercase_ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase_ : Any = model_class(__SCREAMING_SNAKE_CASE ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowercase_ : int = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE , nn.Linear ) ) def _snake_case ( self ): """simple docstring""" lowercase_ , lowercase_ : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase_ : List[str] = model_class(__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase_ : int = [*signature.parameters.keys()] lowercase_ : List[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , __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_model(*__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" lowercase_ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_semantic_segmentation(*__SCREAMING_SNAKE_CASE ) def _snake_case ( self ): """simple docstring""" if not self.model_tester.is_training: return lowercase_ , lowercase_ : Any = self.model_tester.prepare_config_and_inputs_for_common() lowercase_ : List[Any] = True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if model_class in [*get_values(__SCREAMING_SNAKE_CASE ), BeitForMaskedImageModeling]: continue lowercase_ : int = model_class(__SCREAMING_SNAKE_CASE ) model.to(__SCREAMING_SNAKE_CASE ) model.train() lowercase_ : str = self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , return_labels=__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = model(**__SCREAMING_SNAKE_CASE ).loss loss.backward() def _snake_case ( self ): """simple docstring""" lowercase_ , lowercase_ : str = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return lowercase_ : Any = False lowercase_ : List[str] = True for model_class in self.all_model_classes: # we don't test BeitForMaskedImageModeling if ( model_class in [*get_values(__SCREAMING_SNAKE_CASE ), BeitForMaskedImageModeling] or not model_class.supports_gradient_checkpointing ): continue lowercase_ : int = model_class(__SCREAMING_SNAKE_CASE ) model.gradient_checkpointing_enable() model.to(__SCREAMING_SNAKE_CASE ) model.train() lowercase_ : Dict = self._prepare_for_class(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , return_labels=__SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = model(**__SCREAMING_SNAKE_CASE ).loss loss.backward() def _snake_case ( self ): """simple docstring""" lowercase_ , lowercase_ : Dict = self.model_tester.prepare_config_and_inputs_for_common() lowercase_ : str = _config_zero_init(__SCREAMING_SNAKE_CASE ) for model_class in self.all_model_classes: lowercase_ : Optional[Any] = model_class(config=__SCREAMING_SNAKE_CASE ) for name, param in model.named_parameters(): # we skip lambda parameters as these require special initial values # determined by config.layer_scale_init_value if "lambda" in name: continue if param.requires_grad: self.assertIn( ((param.data.mean() * 1E9).round() / 1E9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @slow def _snake_case ( self ): """simple docstring""" for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase_ : Dict = BeitModel.from_pretrained(__SCREAMING_SNAKE_CASE ) self.assertIsNotNone(__SCREAMING_SNAKE_CASE ) def snake_case_ ( ): """simple docstring""" lowercase_ : Optional[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCAmelCase__ ( unittest.TestCase ): @cached_property def _snake_case ( self ): """simple docstring""" return BeitImageProcessor.from_pretrained('''microsoft/beit-base-patch16-224''' ) if is_vision_available() else None @slow def _snake_case ( self ): """simple docstring""" lowercase_ : int = BeitForMaskedImageModeling.from_pretrained('''microsoft/beit-base-patch16-224-pt22k''' ).to(__SCREAMING_SNAKE_CASE ) lowercase_ : int = self.default_image_processor lowercase_ : Optional[int] = prepare_img() lowercase_ : str = image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).pixel_values.to(__SCREAMING_SNAKE_CASE ) # prepare bool_masked_pos lowercase_ : Union[str, Any] = torch.ones((1, 1_96) , dtype=torch.bool ).to(__SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): lowercase_ : str = model(pixel_values=__SCREAMING_SNAKE_CASE , bool_masked_pos=__SCREAMING_SNAKE_CASE ) lowercase_ : Any = outputs.logits # verify the logits lowercase_ : Optional[int] = torch.Size((1, 1_96, 81_92) ) self.assertEqual(logits.shape , __SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = torch.tensor( [[-3.2_437, 0.5_072, -13.9_174], [-3.2_456, 0.4_948, -13.9_401], [-3.2_033, 0.5_121, -13.8_550]] ).to(__SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3] , __SCREAMING_SNAKE_CASE , atol=1E-2 ) ) @slow def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[Any] = BeitForImageClassification.from_pretrained('''microsoft/beit-base-patch16-224''' ).to(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = self.default_image_processor lowercase_ : Union[str, Any] = prepare_img() lowercase_ : Any = image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).to(__SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): lowercase_ : List[Any] = model(**__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = outputs.logits # verify the logits lowercase_ : Any = torch.Size((1, 10_00) ) self.assertEqual(logits.shape , __SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = torch.tensor([-1.2_385, -1.0_987, -1.0_108] ).to(__SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(logits[0, :3] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) ) lowercase_ : Any = 2_81 self.assertEqual(logits.argmax(-1 ).item() , __SCREAMING_SNAKE_CASE ) @slow def _snake_case ( self ): """simple docstring""" lowercase_ : Dict = BeitForImageClassification.from_pretrained('''microsoft/beit-large-patch16-224-pt22k-ft22k''' ).to( __SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = self.default_image_processor lowercase_ : Any = prepare_img() lowercase_ : Any = image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).to(__SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): lowercase_ : List[str] = model(**__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = outputs.logits # verify the logits lowercase_ : Union[str, Any] = torch.Size((1, 2_18_41) ) self.assertEqual(logits.shape , __SCREAMING_SNAKE_CASE ) lowercase_ : List[Any] = torch.tensor([1.6_881, -0.2_787, 0.5_901] ).to(__SCREAMING_SNAKE_CASE ) self.assertTrue(torch.allclose(logits[0, :3] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) ) lowercase_ : str = 23_96 self.assertEqual(logits.argmax(-1 ).item() , __SCREAMING_SNAKE_CASE ) @slow def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[int] = BeitForSemanticSegmentation.from_pretrained('''microsoft/beit-base-finetuned-ade-640-640''' ) lowercase_ : Any = model.to(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = BeitImageProcessor(do_resize=__SCREAMING_SNAKE_CASE , size=6_40 , do_center_crop=__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = load_dataset('''hf-internal-testing/fixtures_ade20k''' , split='''test''' ) lowercase_ : Any = Image.open(ds[0]['''file'''] ) lowercase_ : Tuple = image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).to(__SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): lowercase_ : Union[str, Any] = model(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = outputs.logits # verify the logits lowercase_ : Any = torch.Size((1, 1_50, 1_60, 1_60) ) self.assertEqual(logits.shape , __SCREAMING_SNAKE_CASE ) lowercase_ : int = version.parse(PIL.__version__ ) < version.parse('''9.0.0''' ) if is_pillow_less_than_a: lowercase_ : Dict = torch.tensor( [ [[-4.9_225, -2.3_954, -3.0_522], [-2.8_822, -1.0_046, -1.7_561], [-2.9_549, -1.3_228, -2.1_347]], [[-5.8_168, -3.4_129, -4.0_778], [-3.8_651, -2.2_214, -3.0_277], [-3.8_356, -2.4_643, -3.3_535]], [[-0.0_078, 3.9_952, 4.0_754], [2.9_856, 4.6_944, 5.0_035], [3.2_413, 4.7_813, 4.9_969]], ] , device=__SCREAMING_SNAKE_CASE , ) else: lowercase_ : int = torch.tensor( [ [[-4.8_960, -2.3_688, -3.0_355], [-2.8_478, -0.9_836, -1.7_418], [-2.9_449, -1.3_332, -2.1_456]], [[-5.8_081, -3.4_124, -4.1_006], [-3.8_561, -2.2_081, -3.0_323], [-3.8_365, -2.4_601, -3.3_669]], [[-0.0_309, 3.9_868, 4.0_540], [2.9_640, 4.6_877, 4.9_976], [3.2_081, 4.7_690, 4.9_942]], ] , device=__SCREAMING_SNAKE_CASE , ) self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , __SCREAMING_SNAKE_CASE , atol=1E-4 ) ) @slow def _snake_case ( self ): """simple docstring""" lowercase_ : Tuple = BeitForSemanticSegmentation.from_pretrained('''microsoft/beit-base-finetuned-ade-640-640''' ) lowercase_ : str = model.to(__SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = BeitImageProcessor(do_resize=__SCREAMING_SNAKE_CASE , size=6_40 , do_center_crop=__SCREAMING_SNAKE_CASE ) lowercase_ : int = load_dataset('''hf-internal-testing/fixtures_ade20k''' , split='''test''' ) lowercase_ : Optional[int] = Image.open(ds[0]['''file'''] ) lowercase_ : Union[str, Any] = image_processor(images=__SCREAMING_SNAKE_CASE , return_tensors='''pt''' ).to(__SCREAMING_SNAKE_CASE ) # forward pass with torch.no_grad(): lowercase_ : str = model(**__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = outputs.logits.detach().cpu() lowercase_ : Optional[int] = image_processor.post_process_semantic_segmentation(outputs=__SCREAMING_SNAKE_CASE , target_sizes=[(5_00, 3_00)] ) lowercase_ : List[Any] = torch.Size((5_00, 3_00) ) self.assertEqual(segmentation[0].shape , __SCREAMING_SNAKE_CASE ) lowercase_ : List[str] = image_processor.post_process_semantic_segmentation(outputs=__SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = torch.Size((1_60, 1_60) ) self.assertEqual(segmentation[0].shape , __SCREAMING_SNAKE_CASE )
93
'''simple docstring''' __lowerCAmelCase = { '''A''': ['''B''', '''C''', '''E'''], '''B''': ['''A''', '''D''', '''E'''], '''C''': ['''A''', '''F''', '''G'''], '''D''': ['''B'''], '''E''': ['''A''', '''B''', '''D'''], '''F''': ['''C'''], '''G''': ['''C'''], } def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> list[str]: _a : List[Any] = set() # keep track of all the paths to be checked _a : Any = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue _a : Tuple = queue.pop(0 ) # get the last node from the path _a : Tuple = path[-1] if node not in explored: _a : Optional[Any] = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: _a : Any = list(lowerCAmelCase_ ) new_path.append(lowerCAmelCase_ ) queue.append(lowerCAmelCase_ ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(lowerCAmelCase_ ) # in case there's no path between the 2 nodes return [] def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> int: if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 _a : Optional[int] = [start] _a : Dict = set(lowerCAmelCase_ ) # Keep tab on distances from `start` node. _a : Dict = {start: 0, target: -1} while queue: _a : List[str] = queue.pop(0 ) if node == target: _a : Any = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(lowerCAmelCase_ ) queue.append(lowerCAmelCase_ ) _a : Any = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, '''G''', '''D''')) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, '''G''', '''D''')) # returns 4
89
0
from . import ( albert, align, altclip, audio_spectrogram_transformer, auto, autoformer, bark, bart, barthez, bartpho, beit, bert, bert_generation, bert_japanese, bertweet, big_bird, bigbird_pegasus, biogpt, bit, blenderbot, blenderbot_small, blip, blip_a, bloom, bridgetower, byta, camembert, canine, chinese_clip, clap, clip, clipseg, codegen, conditional_detr, convbert, convnext, convnextva, cpm, cpmant, ctrl, cvt, dataavec, deberta, deberta_va, decision_transformer, deformable_detr, deit, deprecated, deta, detr, dialogpt, dinat, distilbert, dit, donut, dpr, dpt, efficientformer, efficientnet, electra, encodec, encoder_decoder, ernie, ernie_m, esm, falcon, flaubert, flava, fnet, focalnet, fsmt, funnel, git, glpn, gpta, gpt_bigcode, gpt_neo, gpt_neox, gpt_neox_japanese, gpt_swa, gptj, gptsan_japanese, graphormer, groupvit, herbert, hubert, ibert, imagegpt, informer, instructblip, jukebox, layoutlm, layoutlmva, layoutlmva, layoutxlm, led, levit, lilt, llama, longformer, longta, luke, lxmert, mam_aaa, marian, markuplm, maskaformer, maskformer, mbart, mbartaa, mega, megatron_bert, megatron_gpta, mgp_str, mluke, mobilebert, mobilenet_va, mobilenet_va, mobilevit, mobilevitva, mpnet, mra, mta, musicgen, mvp, nat, nezha, nllb, nllb_moe, nystromformer, oneformer, open_llama, openai, opt, owlvit, pegasus, pegasus_x, perceiver, phobert, pixastruct, plbart, poolformer, prophetnet, qdqbert, rag, realm, reformer, regnet, rembert, resnet, roberta, roberta_prelayernorm, roc_bert, roformer, rwkv, sam, segformer, sew, sew_d, speech_encoder_decoder, speech_to_text, speech_to_text_a, speechta, splinter, squeezebert, swiftformer, swin, swinasr, swinva, switch_transformers, ta, table_transformer, tapas, time_series_transformer, timesformer, timm_backbone, transfo_xl, trocr, tvlt, umta, unispeech, unispeech_sat, upernet, videomae, vilt, vision_encoder_decoder, vision_text_dual_encoder, visual_bert, vit, vit_hybrid, vit_mae, vit_msn, vivit, wavaveca, wavaveca_conformer, wavaveca_phoneme, wavaveca_with_lm, wavlm, whisper, x_clip, xglm, xlm, xlm_prophetnet, xlm_roberta, xlm_roberta_xl, xlnet, xmod, yolos, yoso, )
94
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __lowerCAmelCase = {'''configuration_swin''': ['''SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SwinConfig''', '''SwinOnnxConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''SWIN_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SwinForImageClassification''', '''SwinForMaskedImageModeling''', '''SwinModel''', '''SwinPreTrainedModel''', '''SwinBackbone''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFSwinForImageClassification''', '''TFSwinForMaskedImageModeling''', '''TFSwinModel''', '''TFSwinPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_swin import SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinConfig, SwinOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swin import ( SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, SwinBackbone, SwinForImageClassification, SwinForMaskedImageModeling, SwinModel, SwinPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_swin import ( TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, TFSwinForImageClassification, TFSwinForMaskedImageModeling, TFSwinModel, TFSwinPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
89
0
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase : Any = logging.get_logger(__name__) UpperCAmelCase : Optional[int] = { """uclanlp/visualbert-vqa""": """https://huggingface.co/uclanlp/visualbert-vqa/resolve/main/config.json""", """uclanlp/visualbert-vqa-pre""": """https://huggingface.co/uclanlp/visualbert-vqa-pre/resolve/main/config.json""", """uclanlp/visualbert-vqa-coco-pre""": ( """https://huggingface.co/uclanlp/visualbert-vqa-coco-pre/resolve/main/config.json""" ), """uclanlp/visualbert-vcr""": """https://huggingface.co/uclanlp/visualbert-vcr/resolve/main/config.json""", """uclanlp/visualbert-vcr-pre""": """https://huggingface.co/uclanlp/visualbert-vcr-pre/resolve/main/config.json""", """uclanlp/visualbert-vcr-coco-pre""": ( """https://huggingface.co/uclanlp/visualbert-vcr-coco-pre/resolve/main/config.json""" ), """uclanlp/visualbert-nlvr2""": """https://huggingface.co/uclanlp/visualbert-nlvr2/resolve/main/config.json""", """uclanlp/visualbert-nlvr2-pre""": """https://huggingface.co/uclanlp/visualbert-nlvr2-pre/resolve/main/config.json""", """uclanlp/visualbert-nlvr2-coco-pre""": ( """https://huggingface.co/uclanlp/visualbert-nlvr2-coco-pre/resolve/main/config.json""" ) # See all VisualBERT models at https://huggingface.co/models?filter=visual_bert } class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Union[str, Any] = """visual_bert""" def __init__( self , lowerCAmelCase__=3_0_5_2_2 , lowerCAmelCase__=7_6_8 , lowerCAmelCase__=5_1_2 , lowerCAmelCase__=1_2 , lowerCAmelCase__=1_2 , lowerCAmelCase__=3_0_7_2 , lowerCAmelCase__="gelu" , lowerCAmelCase__=0.1 , lowerCAmelCase__=0.1 , lowerCAmelCase__=5_1_2 , lowerCAmelCase__=2 , lowerCAmelCase__=0.02 , lowerCAmelCase__=1E-12 , lowerCAmelCase__=False , lowerCAmelCase__=True , lowerCAmelCase__=1 , lowerCAmelCase__=0 , lowerCAmelCase__=2 , **lowerCAmelCase__ , ) -> Dict: '''simple docstring''' super().__init__(pad_token_id=lowerCAmelCase__ , bos_token_id=lowerCAmelCase__ , eos_token_id=lowerCAmelCase__ , **lowerCAmelCase__ ) a__ : Any =vocab_size a__ : Optional[Any] =max_position_embeddings a__ : str =hidden_size a__ : str =visual_embedding_dim a__ : Optional[int] =num_hidden_layers a__ : Dict =num_attention_heads a__ : Tuple =intermediate_size a__ : List[str] =hidden_act a__ : int =hidden_dropout_prob a__ : Dict =attention_probs_dropout_prob a__ : int =initializer_range a__ : Dict =type_vocab_size a__ : List[Any] =layer_norm_eps a__ : Optional[int] =bypass_transformer a__ : Any =special_visual_initialize
95
'''simple docstring''' import unittest from transformers import BarthezTokenizer, BarthezTokenizerFast, BatchEncoding from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers @require_sentencepiece @slow # see https://github.com/huggingface/transformers/issues/11457 class __magic_name__ ( _UpperCamelCase , unittest.TestCase ): lowerCAmelCase : Optional[int] = BarthezTokenizer lowerCAmelCase : int = BarthezTokenizerFast lowerCAmelCase : Dict = True lowerCAmelCase : str = True def __lowercase ( self : List[Any] ): super().setUp() _a : List[Any] = BarthezTokenizerFast.from_pretrained('moussaKam/mbarthez' ) tokenizer.save_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ,legacy_format=_UpperCAmelCase ) _a : Union[str, Any] = tokenizer def __lowercase ( self : Tuple ): _a : Optional[Any] = '<pad>' _a : List[Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_UpperCAmelCase ) ,_UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_UpperCAmelCase ) ,_UpperCAmelCase ) def __lowercase ( self : str ): _a : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] ,'<s>' ) self.assertEqual(vocab_keys[1] ,'<pad>' ) self.assertEqual(vocab_keys[-1] ,'<mask>' ) self.assertEqual(len(_UpperCAmelCase ) ,101122 ) def __lowercase ( self : Dict ): self.assertEqual(self.get_tokenizer().vocab_size ,101122 ) @require_torch def __lowercase ( self : Dict ): _a : Any = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] _a : Dict = [0, 57, 3018, 70307, 91, 2] _a : Dict = self.tokenizer( _UpperCAmelCase ,max_length=len(_UpperCAmelCase ) ,padding=_UpperCAmelCase ,truncation=_UpperCAmelCase ,return_tensors='pt' ) self.assertIsInstance(_UpperCAmelCase ,_UpperCAmelCase ) self.assertEqual((2, 6) ,batch.input_ids.shape ) self.assertEqual((2, 6) ,batch.attention_mask.shape ) _a : Tuple = batch.input_ids.tolist()[0] self.assertListEqual(_UpperCAmelCase ,_UpperCAmelCase ) def __lowercase ( self : Optional[Any] ): if not self.test_rust_tokenizer: return _a : str = self.get_tokenizer() _a : List[str] = self.get_rust_tokenizer() _a : Dict = 'I was born in 92000, and this is falsé.' _a : List[Any] = tokenizer.tokenize(_UpperCAmelCase ) _a : Tuple = rust_tokenizer.tokenize(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase ,_UpperCAmelCase ) _a : Optional[Any] = tokenizer.encode(_UpperCAmelCase ,add_special_tokens=_UpperCAmelCase ) _a : Optional[int] = rust_tokenizer.encode(_UpperCAmelCase ,add_special_tokens=_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase ,_UpperCAmelCase ) _a : Union[str, Any] = self.get_rust_tokenizer() _a : Any = tokenizer.encode(_UpperCAmelCase ) _a : Optional[int] = rust_tokenizer.encode(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase ,_UpperCAmelCase ) @slow def __lowercase ( self : Optional[int] ): # fmt: off _a : Optional[int] = {'input_ids': [[0, 490, 14328, 4507, 354, 47, 43669, 95, 25, 78117, 20215, 19779, 190, 22, 400, 4, 35343, 80310, 603, 86, 24937, 105, 33438, 94762, 196, 39642, 7, 15, 15933, 173, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 10534, 87, 25, 66, 3358, 196, 55289, 8, 82961, 81, 2204, 75203, 7, 15, 763, 12956, 216, 178, 14328, 9595, 1377, 69693, 7, 448, 71021, 196, 18106, 1437, 13974, 108, 9083, 4, 49315, 7, 39, 86, 1326, 2793, 46333, 4, 448, 196, 74588, 7, 49315, 7, 39, 21, 822, 38470, 74, 21, 66723, 62480, 8, 22050, 5, 2]], '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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # moussaKam/mbarthez is a french model. So we also use french texts. _a : Optional[Any] = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=_UpperCAmelCase ,model_name='moussaKam/mbarthez' ,revision='c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6' ,sequences=_UpperCAmelCase ,)
89
0
"""simple docstring""" # Usage: # ./gen-card-allenai-wmt16.py import os from pathlib import Path def _snake_case ( lowercase__ , lowercase__ , lowercase__ , lowercase__ ): _lowerCamelCase : int = { 'en': 'Machine learning is great, isn\'t it?', 'ru': 'Машинное обучение - это здорово, не так ли?', 'de': 'Maschinelles Lernen ist großartig, nicht wahr?', } # BLUE scores as follows: # "pair": [fairseq, transformers] _lowerCamelCase : List[Any] = { 'wmt16-en-de-dist-12-1': [2_8.3, 2_7.5_2], 'wmt16-en-de-dist-6-1': [2_7.4, 2_7.1_1], 'wmt16-en-de-12-1': [2_6.9, 2_5.7_5], } _lowerCamelCase : str = f'''{src_lang}-{tgt_lang}''' _lowerCamelCase : Tuple = f''' --- language: - {src_lang} - {tgt_lang} thumbnail: tags: - translation - wmt16 - allenai license: apache-2.0 datasets: - wmt16 metrics: - bleu --- # FSMT ## Model description This is a ported version of fairseq-based [wmt16 transformer](https://github.com/jungokasai/deep-shallow/) for {src_lang}-{tgt_lang}. For more details, please, see [Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation](https://arxiv.org/abs/2006.10369). All 3 models are available: * [wmt16-en-de-dist-12-1](https://huggingface.co/allenai/wmt16-en-de-dist-12-1) * [wmt16-en-de-dist-6-1](https://huggingface.co/allenai/wmt16-en-de-dist-6-1) * [wmt16-en-de-12-1](https://huggingface.co/allenai/wmt16-en-de-12-1) ## Intended uses & limitations #### How to use ```python from transformers import FSMTForConditionalGeneration, FSMTTokenizer mname = "allenai/{model_name}" tokenizer = FSMTTokenizer.from_pretrained(mname) model = FSMTForConditionalGeneration.from_pretrained(mname) input = "{texts[src_lang]}" input_ids = tokenizer.encode(input, return_tensors="pt") outputs = model.generate(input_ids) decoded = tokenizer.decode(outputs[0], skip_special_tokens=True) print(decoded) # {texts[tgt_lang]} ``` #### Limitations and bias ## Training data Pretrained weights were left identical to the original model released by allenai. For more details, please, see the [paper](https://arxiv.org/abs/2006.10369). ## Eval results Here are the BLEU scores: model | fairseq | transformers -------|---------|---------- {model_name} | {scores[model_name][0]} | {scores[model_name][1]} The score is slightly below the score reported in the paper, as the researchers don\'t use `sacrebleu` and measure the score on tokenized outputs. `transformers` score was measured using `sacrebleu` on detokenized outputs. The score was calculated using this code: ```bash git clone https://github.com/huggingface/transformers cd transformers export PAIR={pair} export DATA_DIR=data/$PAIR export SAVE_DIR=data/$PAIR export BS=8 export NUM_BEAMS=5 mkdir -p $DATA_DIR sacrebleu -t wmt16 -l $PAIR --echo src > $DATA_DIR/val.source sacrebleu -t wmt16 -l $PAIR --echo ref > $DATA_DIR/val.target echo $PAIR PYTHONPATH="src:examples/seq2seq" python examples/seq2seq/run_eval.py allenai/{model_name} $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS ``` ## Data Sources - [training, etc.](http://www.statmt.org/wmt16/) - [test set](http://matrix.statmt.org/test_sets/newstest2016.tgz?1504722372) ### BibTeX entry and citation info ``` @misc{{kasai2020deep, title={{Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation}}, author={{Jungo Kasai and Nikolaos Pappas and Hao Peng and James Cross and Noah A. Smith}}, year={{2020}}, eprint={{2006.10369}}, archivePrefix={{arXiv}}, primaryClass={{cs.CL}} }} ``` ''' model_card_dir.mkdir(parents=lowercase__ , exist_ok=lowercase__ ) _lowerCamelCase : int = os.path.join(lowercase__ , 'README.md' ) print(f'''Generating {path}''' ) with open(lowercase__ , 'w' , encoding='utf-8' ) as f: f.write(lowercase__ ) # make sure we are under the root of the project lowercase__ = Path(__file__).resolve().parent.parent.parent lowercase__ = repo_dir / """model_cards""" for model_name in ["wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1"]: lowercase__ = model_cards_dir / """allenai""" / model_name write_model_card(model_card_dir, src_lang="""en""", tgt_lang="""de""", model_name=model_name)
96
'''simple docstring''' import subprocess import sys from transformers import BertConfig, BertModel, BertTokenizer, pipeline from transformers.testing_utils import TestCasePlus, require_torch class __magic_name__ ( _UpperCamelCase ): @require_torch def __lowercase ( self : Tuple ): # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched _a : Optional[int] = '\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n ' _a : List[str] = '\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n ' _a : Tuple = '\nimport socket\ndef offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn\'t access internet")\nsocket.socket = offline_socket\n ' # Force fetching the files so that we can use the cache _a : List[Any] = 'hf-internal-testing/tiny-random-bert' BertConfig.from_pretrained(_UpperCAmelCase ) BertModel.from_pretrained(_UpperCAmelCase ) BertTokenizer.from_pretrained(_UpperCAmelCase ) pipeline(task='fill-mask' ,model=_UpperCAmelCase ) # baseline - just load from_pretrained with normal network _a : Optional[int] = [sys.executable, '-c', '\n'.join([load, run, mock] )] # should succeed _a : Tuple = self.get_env() # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files _a : int = '1' _a : List[Any] = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) @require_torch def __lowercase ( self : Any ): # python one-liner segments # this must be loaded before socket.socket is monkey-patched _a : Dict = '\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n ' _a : Optional[int] = '\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n ' _a : Optional[Any] = '\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet")\nsocket.socket = offline_socket\n ' # Force fetching the files so that we can use the cache _a : int = 'hf-internal-testing/tiny-random-bert' BertConfig.from_pretrained(_UpperCAmelCase ) BertModel.from_pretrained(_UpperCAmelCase ) BertTokenizer.from_pretrained(_UpperCAmelCase ) pipeline(task='fill-mask' ,model=_UpperCAmelCase ) # baseline - just load from_pretrained with normal network _a : Optional[int] = [sys.executable, '-c', '\n'.join([load, run, mock] )] # should succeed _a : str = self.get_env() _a : Optional[Any] = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) @require_torch def __lowercase ( self : List[str] ): # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched _a : Union[str, Any] = '\nfrom transformers import BertConfig, BertModel, BertTokenizer\n ' _a : Optional[Any] = '\nmname = "hf-internal-testing/tiny-random-bert-sharded"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nprint("success")\n ' _a : str = '\nimport socket\ndef offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled")\nsocket.socket = offline_socket\n ' # baseline - just load from_pretrained with normal network _a : Optional[Any] = [sys.executable, '-c', '\n'.join([load, run] )] # should succeed _a : Dict = self.get_env() _a : int = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) # next emulate no network _a : List[Any] = [sys.executable, '-c', '\n'.join([load, mock, run] )] # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this. # env["TRANSFORMERS_OFFLINE"] = "0" # result = subprocess.run(cmd, env=env, check=False, capture_output=True) # self.assertEqual(result.returncode, 1, result.stderr) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files _a : int = '1' _a : Any = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) @require_torch def __lowercase ( self : int ): _a : Optional[Any] = '\nfrom transformers import pipeline\n ' _a : str = '\nmname = "hf-internal-testing/tiny-random-bert"\npipe = pipeline(model=mname)\n ' _a : List[str] = '\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled")\nsocket.socket = offline_socket\n ' _a : List[Any] = self.get_env() _a : Dict = '1' _a : Dict = [sys.executable, '-c', '\n'.join([load, mock, run] )] _a : str = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,1 ,result.stderr ) self.assertIn( 'You cannot infer task automatically within `pipeline` when using offline mode' ,result.stderr.decode().replace('\n' ,'' ) ,) @require_torch def __lowercase ( self : int ): _a : Optional[int] = '\nfrom transformers import AutoModel\n ' _a : List[Any] = '\nmname = "hf-internal-testing/test_dynamic_model"\nAutoModel.from_pretrained(mname, trust_remote_code=True)\nprint("success")\n ' # baseline - just load from_pretrained with normal network _a : Union[str, Any] = [sys.executable, '-c', '\n'.join([load, run] )] # should succeed _a : Tuple = self.get_env() _a : List[str] = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files _a : Optional[Any] = '1' _a : Any = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() )
89
0
'''simple docstring''' import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class lowercase ( unittest.TestCase ): """simple docstring""" def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :Dict = '''laion/clap-htsat-unfused''' UpperCamelCase__ :Optional[int] = tempfile.mkdtemp() def lowerCAmelCase__ ( self , **UpperCamelCase_ ): '''simple docstring''' return RobertaTokenizer.from_pretrained(self.checkpoint , **UpperCamelCase_ ) def lowerCAmelCase__ ( self , **UpperCamelCase_ ): '''simple docstring''' return ClapFeatureExtractor.from_pretrained(self.checkpoint , **UpperCamelCase_ ) def lowerCAmelCase__ ( self ): '''simple docstring''' shutil.rmtree(self.tmpdirname ) def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :str = self.get_tokenizer() UpperCamelCase__ :Tuple = self.get_feature_extractor() UpperCamelCase__ :Union[str, Any] = ClapProcessor(tokenizer=UpperCamelCase_ , feature_extractor=UpperCamelCase_ ) processor.save_pretrained(self.tmpdirname ) UpperCamelCase__ :Optional[int] = ClapProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , UpperCamelCase_ ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , UpperCamelCase_ ) def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :Union[str, Any] = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() ) processor.save_pretrained(self.tmpdirname ) UpperCamelCase__ :Union[str, Any] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) UpperCamelCase__ :Union[str, Any] = self.get_feature_extractor(do_normalize=UpperCamelCase_ , padding_value=1.0 ) UpperCamelCase__ :int = ClapProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=UpperCamelCase_ , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , UpperCamelCase_ ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.feature_extractor , UpperCamelCase_ ) def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :str = self.get_feature_extractor() UpperCamelCase__ :int = self.get_tokenizer() UpperCamelCase__ :List[Any] = ClapProcessor(tokenizer=UpperCamelCase_ , feature_extractor=UpperCamelCase_ ) UpperCamelCase__ :Any = floats_list((3, 1000) ) UpperCamelCase__ :Union[str, Any] = feature_extractor(UpperCamelCase_ , return_tensors='''np''' ) UpperCamelCase__ :Dict = processor(audios=UpperCamelCase_ , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :List[Any] = self.get_feature_extractor() UpperCamelCase__ :Optional[int] = self.get_tokenizer() UpperCamelCase__ :Tuple = ClapProcessor(tokenizer=UpperCamelCase_ , feature_extractor=UpperCamelCase_ ) UpperCamelCase__ :List[Any] = '''This is a test string''' UpperCamelCase__ :int = processor(text=UpperCamelCase_ ) UpperCamelCase__ :Optional[Any] = tokenizer(UpperCamelCase_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :Tuple = self.get_feature_extractor() UpperCamelCase__ :List[str] = self.get_tokenizer() UpperCamelCase__ :int = ClapProcessor(tokenizer=UpperCamelCase_ , feature_extractor=UpperCamelCase_ ) UpperCamelCase__ :int = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] UpperCamelCase__ :str = processor.batch_decode(UpperCamelCase_ ) UpperCamelCase__ :List[Any] = tokenizer.batch_decode(UpperCamelCase_ ) self.assertListEqual(UpperCamelCase_ , UpperCamelCase_ ) def lowerCAmelCase__ ( self ): '''simple docstring''' UpperCamelCase__ :Tuple = self.get_feature_extractor() UpperCamelCase__ :List[str] = self.get_tokenizer() UpperCamelCase__ :Tuple = ClapProcessor(tokenizer=UpperCamelCase_ , feature_extractor=UpperCamelCase_ ) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg='''`processor` and `feature_extractor` model input names do not match''' , )
97
'''simple docstring''' def __lowerCamelCase ( ) -> Tuple: for n in range(1 , 1000000 ): yield n * (n + 1) // 2 def __lowerCamelCase ( lowerCAmelCase_ ) -> List[Any]: _a : Any = 1 _a : Tuple = 2 while i * i <= n: _a : Tuple = 0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def __lowerCamelCase ( ) -> str: return next(i for i in triangle_number_generator() if count_divisors(lowerCAmelCase_ ) > 500 ) if __name__ == "__main__": print(solution())
89
0
"""simple docstring""" def a_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase ): return not any( neighbour == 1 and colored_vertices[i] == color for i, neighbour in enumerate(lowerCamelCase ) ) def a_ ( lowerCamelCase , lowerCamelCase , lowerCamelCase , lowerCamelCase ): # Base Case if index == len(lowerCamelCase ): return True # Recursive Step for i in range(lowerCamelCase ): if valid_coloring(graph[index] , lowerCamelCase , lowerCamelCase ): # Color current vertex UpperCAmelCase__ = i # Validate coloring if util_color(lowerCamelCase , lowerCamelCase , lowerCamelCase , index + 1 ): return True # Backtrack UpperCAmelCase__ = -1 return False def a_ ( lowerCamelCase , lowerCamelCase ): UpperCAmelCase__ = [-1] * len(lowerCamelCase ) if util_color(lowerCamelCase , lowerCamelCase , lowerCamelCase , 0 ): return colored_vertices return []
98
'''simple docstring''' import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class __magic_name__ ( _UpperCamelCase ): def __init__( self : Optional[int] ,_UpperCAmelCase : Union[str, "sqlalchemy.sql.Selectable"] ,_UpperCAmelCase : Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] ,_UpperCAmelCase : Optional[Features] = None ,_UpperCAmelCase : str = None ,_UpperCAmelCase : bool = False ,**_UpperCAmelCase : Dict ,): super().__init__(features=_UpperCAmelCase ,cache_dir=_UpperCAmelCase ,keep_in_memory=_UpperCAmelCase ,**_UpperCAmelCase ) _a : Tuple = Sql( cache_dir=_UpperCAmelCase ,features=_UpperCAmelCase ,sql=_UpperCAmelCase ,con=_UpperCAmelCase ,**_UpperCAmelCase ,) def __lowercase ( self : Dict ): _a : Optional[Any] = None _a : Dict = None _a : Dict = None _a : Optional[int] = None self.builder.download_and_prepare( download_config=_UpperCAmelCase ,download_mode=_UpperCAmelCase ,verification_mode=_UpperCAmelCase ,base_path=_UpperCAmelCase ,) # Build dataset for splits _a : List[str] = self.builder.as_dataset( split='train' ,verification_mode=_UpperCAmelCase ,in_memory=self.keep_in_memory ) return dataset class __magic_name__ : def __init__( self : Optional[int] ,_UpperCAmelCase : Dataset ,_UpperCAmelCase : str ,_UpperCAmelCase : Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] ,_UpperCAmelCase : Optional[int] = None ,_UpperCAmelCase : Optional[int] = None ,**_UpperCAmelCase : Dict ,): if num_proc is not None and num_proc <= 0: raise ValueError(F"""num_proc {num_proc} must be an integer > 0.""" ) _a : Dict = dataset _a : List[Any] = name _a : Tuple = con _a : Union[str, Any] = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE _a : List[Any] = num_proc _a : Tuple = to_sql_kwargs def __lowercase ( self : List[Any] ): _a : Tuple = self.to_sql_kwargs.pop('sql' ,_UpperCAmelCase ) _a : str = self.to_sql_kwargs.pop('con' ,_UpperCAmelCase ) _a : Optional[Any] = self.to_sql_kwargs.pop('index' ,_UpperCAmelCase ) _a : Any = self._write(index=_UpperCAmelCase ,**self.to_sql_kwargs ) return written def __lowercase ( self : Optional[int] ,_UpperCAmelCase : Dict ): _a , _a , _a : Any = args _a : Tuple = {**to_sql_kwargs, 'if_exists': 'append'} if offset > 0 else to_sql_kwargs _a : Dict = query_table( table=self.dataset.data ,key=slice(_UpperCAmelCase ,offset + self.batch_size ) ,indices=self.dataset._indices ,) _a : Tuple = batch.to_pandas() _a : Dict = df.to_sql(self.name ,self.con ,index=_UpperCAmelCase ,**_UpperCAmelCase ) return num_rows or len(_UpperCAmelCase ) def __lowercase ( self : int ,_UpperCAmelCase : Optional[int] ,**_UpperCAmelCase : List[Any] ): _a : Union[str, Any] = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 ,len(self.dataset ) ,self.batch_size ) ,unit='ba' ,disable=not logging.is_progress_bar_enabled() ,desc='Creating SQL from Arrow format' ,): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: _a , _a : List[Any] = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql ,[(offset, index, to_sql_kwargs) for offset in range(0 ,_UpperCAmelCase ,_UpperCAmelCase )] ,) ,total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size ,unit='ba' ,disable=not logging.is_progress_bar_enabled() ,desc='Creating SQL from Arrow format' ,): written += num_rows return written
89
0
from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : Optional[Any] = logging.get_logger(__name__) lowercase : Tuple = { """microsoft/biogpt""": """https://huggingface.co/microsoft/biogpt/resolve/main/config.json""", # See all BioGPT models at https://huggingface.co/models?filter=biogpt } class A__ ( __UpperCAmelCase ): """simple docstring""" __A : Optional[Any] = '''biogpt''' def __init__( self , lowercase=4_2384 , lowercase=1024 , lowercase=24 , lowercase=16 , lowercase=4096 , lowercase="gelu" , lowercase=0.1 , lowercase=0.1 , lowercase=1024 , lowercase=0.02 , lowercase=1e-12 , lowercase=True , lowercase=True , lowercase=0.0 , lowercase=0.0 , lowercase=1 , lowercase=0 , lowercase=2 , **lowercase , ) -> Optional[Any]: '''simple docstring''' a__ : List[Any] = vocab_size a__ : Tuple = max_position_embeddings a__ : Union[str, Any] = hidden_size a__ : Tuple = num_hidden_layers a__ : Union[str, Any] = num_attention_heads a__ : str = intermediate_size a__ : int = hidden_act a__ : Dict = hidden_dropout_prob a__ : Dict = attention_probs_dropout_prob a__ : Any = initializer_range a__ : str = layer_norm_eps a__ : Tuple = scale_embedding a__ : str = use_cache a__ : Optional[int] = layerdrop a__ : int = activation_dropout super().__init__(pad_token_id=lowercase , bos_token_id=lowercase , eos_token_id=lowercase , **lowercase)
99
'''simple docstring''' from pathlib import Path import cva import numpy as np from matplotlib import pyplot as plt def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> np.ndarray: _a : Union[str, Any] = cva.getAffineTransform(lowerCAmelCase_ , lowerCAmelCase_ ) return cva.warpAffine(lowerCAmelCase_ , lowerCAmelCase_ , (rows, cols) ) if __name__ == "__main__": # read original image __lowerCAmelCase = cva.imread( str(Path(__file__).resolve().parent.parent / '''image_data''' / '''lena.jpg''') ) # turn image in gray scale value __lowerCAmelCase = cva.cvtColor(image, cva.COLOR_BGR2GRAY) # get image shape __lowerCAmelCase , __lowerCAmelCase = gray_img.shape # set different points to rotate image __lowerCAmelCase = np.array([[50, 50], [200, 50], [50, 200]], np.floataa) __lowerCAmelCase = np.array([[10, 100], [200, 50], [100, 250]], np.floataa) __lowerCAmelCase = np.array([[50, 50], [150, 50], [120, 200]], np.floataa) __lowerCAmelCase = np.array([[10, 100], [80, 50], [180, 250]], np.floataa) # add all rotated images in a list __lowerCAmelCase = [ gray_img, get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), get_rotation(gray_img, ptsa, ptsa, img_rows, img_cols), ] # plot different image rotations __lowerCAmelCase = plt.figure(1) __lowerCAmelCase = ['''Original''', '''Rotation 1''', '''Rotation 2''', '''Rotation 3'''] for i, image in enumerate(images): plt.subplot(2, 2, i + 1), plt.imshow(image, '''gray''') plt.title(titles[i]) plt.axis('''off''') plt.subplots_adjust(left=0.0, bottom=0.05, right=1.0, top=0.95) plt.show()
89
0
"""simple docstring""" import os from itertools import chain from random import randrange, shuffle import pytest from .sola import PokerHand __magic_name__ = ( "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) ) __magic_name__ = ( ("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"), ) __magic_name__ = ( ("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), ) __magic_name__ = ( ("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), ) __magic_name__ = ( ("2H 4D 3C AS 5S", True, [5, 4, 3, 2, 14]), ("2H 5D 3C AS 5S", False, [14, 5, 5, 3, 2]), ("JH QD KC AS TS", False, [14, 13, 12, 11, 10]), ("9D 3S 2C 7S 7C", False, [9, 7, 7, 3, 2]), ) __magic_name__ = ( ("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), ) __magic_name__ = ( ("JH AH TH KH QH", 23), ("JH 9H TH KH QH", 22), ("JC KH JS JD JH", 21), ("KH KC 3S 3H 3D", 20), ("8C 9C 5C 3C TC", 19), ("JS QS 9H TS KH", 18), ("7C 7S KH 2H 7H", 17), ("3C KH 5D 5S KH", 16), ("QH 8H KD JH 8S", 15), ("2D 6D 9D TH 7D", 14), ) def _lowerCAmelCase ( ): __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = randrange(len(UpperCamelCase_ ) ), randrange(len(UpperCamelCase_ ) ) __SCREAMING_SNAKE_CASE = ["""Loss""", """Tie""", """Win"""][(play >= oppo) + (play > oppo)] __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = SORTED_HANDS[play], SORTED_HANDS[oppo] return hand, other, expected def _lowerCAmelCase ( UpperCamelCase_ = 100 ): return (generate_random_hand() for _ in range(UpperCamelCase_ )) @pytest.mark.parametrize("""hand, expected""" , UpperCamelCase_ ) def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ ): assert PokerHand(UpperCamelCase_ )._is_flush() == expected @pytest.mark.parametrize("""hand, expected""" , UpperCamelCase_ ) def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ ): assert PokerHand(UpperCamelCase_ )._is_straight() == expected @pytest.mark.parametrize("""hand, expected, card_values""" , UpperCamelCase_ ) def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): __SCREAMING_SNAKE_CASE = 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_ ): assert PokerHand(UpperCamelCase_ )._is_same_kind() == expected @pytest.mark.parametrize("""hand, expected""" , UpperCamelCase_ ) def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ ): assert PokerHand(UpperCamelCase_ )._hand_type == expected @pytest.mark.parametrize("""hand, other, expected""" , UpperCamelCase_ ) def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): assert PokerHand(UpperCamelCase_ ).compare_with(PokerHand(UpperCamelCase_ ) ) == expected @pytest.mark.parametrize("""hand, other, expected""" , generate_random_hands() ) def _lowerCAmelCase ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ): assert PokerHand(UpperCamelCase_ ).compare_with(PokerHand(UpperCamelCase_ ) ) == expected def _lowerCAmelCase ( ): __SCREAMING_SNAKE_CASE = [PokerHand(UpperCamelCase_ ) for hand in SORTED_HANDS] __SCREAMING_SNAKE_CASE = poker_hands.copy() shuffle(UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = chain(sorted(UpperCamelCase_ ) ) for index, hand in enumerate(UpperCamelCase_ ): assert hand == poker_hands[index] def _lowerCAmelCase ( ): # Test that five high straights are compared correctly. __SCREAMING_SNAKE_CASE = [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 ( ): # Multiple calls to five_high_straight function should still return True # and shouldn't mutate the list in every call other than the first. __SCREAMING_SNAKE_CASE = PokerHand("""2C 4S AS 3D 5C""" ) __SCREAMING_SNAKE_CASE = True __SCREAMING_SNAKE_CASE = [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 ( ): # Problem number 54 from Project Euler # Testing from poker_hands.txt file __SCREAMING_SNAKE_CASE = 0 __SCREAMING_SNAKE_CASE = os.path.abspath(os.path.dirname(UpperCamelCase_ ) ) __SCREAMING_SNAKE_CASE = os.path.join(UpperCamelCase_ , """poker_hands.txt""" ) with open(UpperCamelCase_ ) as file_hand: for line in file_hand: __SCREAMING_SNAKE_CASE = line[:14].strip() __SCREAMING_SNAKE_CASE = line[15:].strip() __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = PokerHand(UpperCamelCase_ ), PokerHand(UpperCamelCase_ ) __SCREAMING_SNAKE_CASE = player.compare_with(UpperCamelCase_ ) if output == "Win": answer += 1 assert answer == 376
100
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCAmelCase = { '''configuration_bigbird_pegasus''': [ '''BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''BigBirdPegasusConfig''', '''BigBirdPegasusOnnxConfig''', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST''', '''BigBirdPegasusForCausalLM''', '''BigBirdPegasusForConditionalGeneration''', '''BigBirdPegasusForQuestionAnswering''', '''BigBirdPegasusForSequenceClassification''', '''BigBirdPegasusModel''', '''BigBirdPegasusPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP, BigBirdPegasusConfig, BigBirdPegasusOnnxConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bigbird_pegasus import ( BIGBIRD_PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST, BigBirdPegasusForCausalLM, BigBirdPegasusForConditionalGeneration, BigBirdPegasusForQuestionAnswering, BigBirdPegasusForSequenceClassification, BigBirdPegasusModel, BigBirdPegasusPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
89
0
from random import shuffle import tensorflow as tf from numpy import array def UpperCamelCase ( lowerCAmelCase__ , lowerCAmelCase__ ): '''simple docstring''' lowercase = int(lowerCAmelCase__ ) assert noofclusters < len(lowerCAmelCase__ ) # Find out the dimensionality lowercase = len(vectors[0] ) # Will help select random centroids from among the available vectors lowercase = list(range(len(lowerCAmelCase__ ) ) ) shuffle(lowerCAmelCase__ ) # GRAPH OF COMPUTATION # We initialize a new graph and set it as the default during each run # of this algorithm. This ensures that as this function is called # multiple times, the default graph doesn't keep getting crowded with # unused ops and Variables from previous function calls. lowercase = tf.Graph() with graph.as_default(): # SESSION OF COMPUTATION lowercase = tf.Session() ##CONSTRUCTING THE ELEMENTS OF COMPUTATION ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points lowercase = [ tf.Variable(vectors[vector_indices[i]] ) for i in range(lowerCAmelCase__ ) ] ##These nodes will assign the centroid Variables the appropriate ##values lowercase = tf.placeholder('''float64''' , [dim] ) lowercase = [] for centroid in centroids: cent_assigns.append(tf.assign(lowerCAmelCase__ , lowerCAmelCase__ ) ) ##Variables for cluster assignments of individual vectors(initialized ##to 0 at first) lowercase = [tf.Variable(0 ) for i in range(len(lowerCAmelCase__ ) )] ##These nodes will assign an assignment Variable the appropriate ##value lowercase = tf.placeholder('''int32''' ) lowercase = [] for assignment in assignments: cluster_assigns.append(tf.assign(lowerCAmelCase__ , lowerCAmelCase__ ) ) ##Now lets construct the node that will compute the mean # The placeholder for the input lowercase = tf.placeholder('''float''' , [None, dim] ) # The Node/op takes the input and computes a mean along the 0th # dimension, i.e. the list of input vectors lowercase = tf.reduce_mean(lowerCAmelCase__ , 0 ) ##Node for computing Euclidean distances # Placeholders for input lowercase = tf.placeholder('''float''' , [dim] ) lowercase = tf.placeholder('''float''' , [dim] ) lowercase = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(lowerCAmelCase__ , lowerCAmelCase__ ) , 2 ) ) ) ##This node will figure out which cluster to assign a vector to, ##based on Euclidean distances of the vector from the centroids. # Placeholder for input lowercase = tf.placeholder('''float''' , [noofclusters] ) lowercase = tf.argmin(lowerCAmelCase__ , 0 ) ##INITIALIZING STATE VARIABLES ##This will help initialization of all Variables defined with respect ##to the graph. The Variable-initializer should be defined after ##all the Variables have been constructed, so that each of them ##will be included in the initialization. lowercase = tf.initialize_all_variables() # Initialize all variables sess.run(lowerCAmelCase__ ) ##CLUSTERING ITERATIONS # Now perform the Expectation-Maximization steps of K-Means clustering # iterations. To keep things simple, we will only do a set number of # iterations, instead of using a Stopping Criterion. lowercase = 100 for _ in range(lowerCAmelCase__ ): ##EXPECTATION STEP ##Based on the centroid locations till last iteration, compute ##the _expected_ centroid assignments. # Iterate over each vector for vector_n in range(len(lowerCAmelCase__ ) ): lowercase = vectors[vector_n] # Compute Euclidean distance between this vector and each # centroid. Remember that this list cannot be named #'centroid_distances', since that is the input to the # cluster assignment node. lowercase = [ sess.run(lowerCAmelCase__ , feed_dict={va: vect, va: sess.run(lowerCAmelCase__ )} ) for centroid in centroids ] # Now use the cluster assignment node, with the distances # as the input lowercase = sess.run( lowerCAmelCase__ , feed_dict={centroid_distances: distances} ) # Now assign the value to the appropriate state variable sess.run( cluster_assigns[vector_n] , feed_dict={assignment_value: assignment} ) ##MAXIMIZATION STEP # Based on the expected state computed from the Expectation Step, # compute the locations of the centroids so as to maximize the # overall objective of minimizing within-cluster Sum-of-Squares for cluster_n in range(lowerCAmelCase__ ): # Collect all the vectors assigned to this cluster lowercase = [ vectors[i] for i in range(len(lowerCAmelCase__ ) ) if sess.run(assignments[i] ) == cluster_n ] # Compute new centroid location lowercase = sess.run( lowerCAmelCase__ , feed_dict={mean_input: array(lowerCAmelCase__ )} ) # Assign value to appropriate variable sess.run( cent_assigns[cluster_n] , feed_dict={centroid_value: new_location} ) # Return centroids and assignments lowercase = sess.run(lowerCAmelCase__ ) lowercase = sess.run(lowerCAmelCase__ ) return centroids, assignments
101
'''simple docstring''' import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=1024 , lowerCAmelCase_=1024 , lowerCAmelCase_=False , **lowerCAmelCase_ ) -> List[Any]: _a : str = AutoTokenizer.from_pretrained(lowerCAmelCase_ ) _a : List[Any] = SeqaSeqDataset(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , type_path='train' , **lowerCAmelCase_ ) _a : List[str] = tok.pad_token_id def get_lens(lowerCAmelCase_ ): _a : Dict = tqdm( DataLoader(lowerCAmelCase_ , batch_size=512 , num_workers=8 , shuffle=lowerCAmelCase_ , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) _a : Union[str, Any] = [] for batch in dl: _a : Optional[Any] = batch['input_ids'].ne(lowerCAmelCase_ ).sum(1 ).tolist() _a : Optional[Any] = batch['labels'].ne(lowerCAmelCase_ ).sum(1 ).tolist() if consider_target: for src, tgt in zip(lowerCAmelCase_ , lowerCAmelCase_ ): max_lens.append(max(lowerCAmelCase_ , lowerCAmelCase_ ) ) else: max_lens.extend(lowerCAmelCase_ ) return max_lens _a : str = get_lens(lowerCAmelCase_ ) _a : Optional[int] = SeqaSeqDataset(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , type_path='val' , **lowerCAmelCase_ ) _a : Dict = get_lens(lowerCAmelCase_ ) pickle_save(lowerCAmelCase_ , train_ds.len_file ) pickle_save(lowerCAmelCase_ , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
89
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE : List[str] = { """configuration_time_series_transformer""": [ """TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TimeSeriesTransformerConfig""", ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE : Union[str, Any] = [ """TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST""", """TimeSeriesTransformerForPrediction""", """TimeSeriesTransformerModel""", """TimeSeriesTransformerPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimeSeriesTransformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_time_series_transformer import ( TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimeSeriesTransformerForPrediction, TimeSeriesTransformerModel, TimeSeriesTransformerPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE : List[str] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
102
'''simple docstring''' from typing import Any class __magic_name__ : def __init__( self : List[Any] ,_UpperCAmelCase : Any ): _a : List[Any] = data _a : Union[str, Any] = None def __repr__( self : Any ): return F"""Node({self.data})""" class __magic_name__ : def __init__( self : int ): _a : Tuple = None def __iter__( self : str ): _a : int = self.head while node: yield node.data _a : Union[str, Any] = node.next def __len__( self : Optional[Any] ): return sum(1 for _ in self ) def __repr__( self : str ): return "->".join([str(_UpperCAmelCase ) for item in self] ) def __getitem__( self : Tuple ,_UpperCAmelCase : int ): if not 0 <= index < len(self ): raise ValueError('list index out of range.' ) for i, node in enumerate(self ): if i == index: return node return None def __setitem__( self : Union[str, Any] ,_UpperCAmelCase : int ,_UpperCAmelCase : Any ): if not 0 <= index < len(self ): raise ValueError('list index out of range.' ) _a : Any = self.head for _ in range(_UpperCAmelCase ): _a : Optional[Any] = current.next _a : Optional[int] = data def __lowercase ( self : Optional[int] ,_UpperCAmelCase : Any ): self.insert_nth(len(self ) ,_UpperCAmelCase ) def __lowercase ( self : Union[str, Any] ,_UpperCAmelCase : Any ): self.insert_nth(0 ,_UpperCAmelCase ) def __lowercase ( self : str ,_UpperCAmelCase : int ,_UpperCAmelCase : Any ): if not 0 <= index <= len(self ): raise IndexError('list index out of range' ) _a : int = Node(_UpperCAmelCase ) if self.head is None: _a : str = new_node elif index == 0: _a : List[str] = self.head # link new_node to head _a : Union[str, Any] = new_node else: _a : int = self.head for _ in range(index - 1 ): _a : Union[str, Any] = temp.next _a : List[str] = temp.next _a : Optional[int] = new_node def __lowercase ( self : Optional[int] ): # print every node data print(self ) def __lowercase ( self : str ): return self.delete_nth(0 ) def __lowercase ( self : str ): # delete from tail return self.delete_nth(len(self ) - 1 ) def __lowercase ( self : List[str] ,_UpperCAmelCase : int = 0 ): if not 0 <= index <= len(self ) - 1: # test if index is valid raise IndexError('List index out of range.' ) _a : Optional[Any] = self.head # default first node if index == 0: _a : int = self.head.next else: _a : int = self.head for _ in range(index - 1 ): _a : str = temp.next _a : str = temp.next _a : int = temp.next.next return delete_node.data def __lowercase ( self : List[Any] ): return self.head is None def __lowercase ( self : Tuple ): _a : List[Any] = None _a : Tuple = self.head while current: # Store the current node's next node. _a : Dict = current.next # Make the current node's next point backwards _a : str = prev # Make the previous node be the current node _a : Tuple = current # Make the current node the next node (to progress iteration) _a : Optional[Any] = next_node # Return prev in order to put the head at the end _a : int = prev def __lowerCamelCase ( ) -> None: _a : List[str] = LinkedList() assert linked_list.is_empty() is True assert str(lowerCAmelCase_ ) == "" try: linked_list.delete_head() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. try: linked_list.delete_tail() raise AssertionError # This should not happen. except IndexError: assert True # This should happen. for i in range(10 ): assert len(lowerCAmelCase_ ) == i linked_list.insert_nth(lowerCAmelCase_ , i + 1 ) assert str(lowerCAmelCase_ ) == "->".join(str(lowerCAmelCase_ ) for i in range(1 , 11 ) ) linked_list.insert_head(0 ) linked_list.insert_tail(11 ) assert str(lowerCAmelCase_ ) == "->".join(str(lowerCAmelCase_ ) for i in range(0 , 12 ) ) assert linked_list.delete_head() == 0 assert linked_list.delete_nth(9 ) == 10 assert linked_list.delete_tail() == 11 assert len(lowerCAmelCase_ ) == 9 assert str(lowerCAmelCase_ ) == "->".join(str(lowerCAmelCase_ ) for i in range(1 , 10 ) ) assert all(linked_list[i] == i + 1 for i in range(0 , 9 ) ) is True for i in range(0 , 9 ): _a : Union[str, Any] = -i assert all(linked_list[i] == -i for i in range(0 , 9 ) ) is True linked_list.reverse() assert str(lowerCAmelCase_ ) == "->".join(str(lowerCAmelCase_ ) for i in range(-8 , 1 ) ) def __lowerCamelCase ( ) -> None: _a : Dict = [ -9, 100, Node(77345112 ), 'dlrow olleH', 7, 5555, 0, -192.55_555, 'Hello, world!', 77.9, Node(10 ), None, None, 12.20, ] _a : List[Any] = LinkedList() for i in test_input: linked_list.insert_tail(lowerCAmelCase_ ) # Check if it's empty or not assert linked_list.is_empty() is False assert ( str(lowerCAmelCase_ ) == "-9->100->Node(77345112)->dlrow olleH->7->5555->0->" "-192.55555->Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the head _a : List[str] = linked_list.delete_head() assert result == -9 assert ( str(lowerCAmelCase_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None->12.2" ) # Delete the tail _a : Dict = linked_list.delete_tail() assert result == 12.2 assert ( str(lowerCAmelCase_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None->None" ) # Delete a node in specific location in linked list _a : Optional[Any] = linked_list.delete_nth(10 ) assert result is None assert ( str(lowerCAmelCase_ ) == "100->Node(77345112)->dlrow olleH->7->5555->0->-192.55555->" "Hello, world!->77.9->Node(10)->None" ) # Add a Node instance to its head linked_list.insert_head(Node('Hello again, world!' ) ) assert ( str(lowerCAmelCase_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None" ) # Add None to its tail linked_list.insert_tail(lowerCAmelCase_ ) assert ( str(lowerCAmelCase_ ) == "Node(Hello again, world!)->100->Node(77345112)->dlrow olleH->" "7->5555->0->-192.55555->Hello, world!->77.9->Node(10)->None->None" ) # Reverse the linked list linked_list.reverse() assert ( str(lowerCAmelCase_ ) == "None->None->Node(10)->77.9->Hello, world!->-192.55555->0->5555->" "7->dlrow olleH->Node(77345112)->100->Node(Hello again, world!)" ) def __lowerCamelCase ( ) -> Union[str, Any]: from doctest import testmod testmod() _a : Optional[int] = LinkedList() linked_list.insert_head(input('Inserting 1st at head ' ).strip() ) linked_list.insert_head(input('Inserting 2nd at head ' ).strip() ) print('\nPrint list:' ) linked_list.print_list() linked_list.insert_tail(input('\nInserting 1st at tail ' ).strip() ) linked_list.insert_tail(input('Inserting 2nd at tail ' ).strip() ) print('\nPrint list:' ) linked_list.print_list() print('\nDelete head' ) linked_list.delete_head() print('Delete tail' ) linked_list.delete_tail() print('\nPrint list:' ) linked_list.print_list() print('\nReverse linked list' ) linked_list.reverse() print('\nPrint list:' ) linked_list.print_list() print('\nString representation of linked list:' ) print(lowerCAmelCase_ ) print('\nReading/changing Node data using indexing:' ) print(f"""Element at Position 1: {linked_list[1]}""" ) _a : Optional[Any] = input('Enter New Value: ' ).strip() print('New list:' ) print(lowerCAmelCase_ ) print(f"""length of linked_list is : {len(lowerCAmelCase_ )}""" ) if __name__ == "__main__": main()
89
0
import unittest import numpy as np import torch from diffusers import VersatileDiffusionImageVariationPipeline from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device A__ : Union[str, Any] = False class __snake_case ( unittest.TestCase ): pass @slow @require_torch_gpu class __snake_case ( unittest.TestCase ): def UpperCAmelCase__ ( self : Union[str, Any]): lowerCAmelCase_ : List[Any] = VersatileDiffusionImageVariationPipeline.from_pretrained('''shi-labs/versatile-diffusion''') pipe.to(A_) pipe.set_progress_bar_config(disable=A_) lowerCAmelCase_ : Optional[Any] = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg''') lowerCAmelCase_ : Union[str, Any] = torch.manual_seed(0) lowerCAmelCase_ : Optional[int] = pipe( image=A_ , generator=A_ , guidance_scale=7.5 , num_inference_steps=5_0 , output_type='''numpy''' , ).images lowerCAmelCase_ : Union[str, Any] = image[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1] assert image.shape == (1, 5_1_2, 5_1_2, 3) lowerCAmelCase_ : str = np.array([0.0441, 0.0469, 0.0507, 0.0575, 0.0632, 0.0650, 0.0865, 0.0909, 0.0945]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
103
'''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 __lowerCAmelCase = logging.getLogger() @unittest.skip('Temporarily disable the doc tests.' ) @require_torch @require_tf @slow class __magic_name__ ( unittest.TestCase ): def __lowercase ( self : str ,_UpperCAmelCase : Path ,_UpperCAmelCase : Union[str, None] = None ,_UpperCAmelCase : Union[List[str], None] = None ,_UpperCAmelCase : Union[str, List[str], None] = None ,_UpperCAmelCase : bool = True ,): _a : Dict = [file for file in os.listdir(_UpperCAmelCase ) if os.path.isfile(os.path.join(_UpperCAmelCase ,_UpperCAmelCase ) )] if identifier is not None: _a : str = [file for file in files if identifier in file] if n_identifier is not None: if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): for n_ in n_identifier: _a : int = [file for file in files if n_ not in file] else: _a : Optional[Any] = [file for file in files if n_identifier not in file] _a : Dict = ignore_files or [] ignore_files.append('__init__.py' ) _a : List[str] = [file for file in files if file not in ignore_files] for file in files: # Open all files print('Testing' ,_UpperCAmelCase ) if only_modules: _a : Any = file.split('.' )[0] try: _a : Optional[int] = getattr(_UpperCAmelCase ,_UpperCAmelCase ) _a : Dict = doctest.DocTestSuite(_UpperCAmelCase ) _a : Optional[int] = unittest.TextTestRunner().run(_UpperCAmelCase ) self.assertIs(len(result.failures ) ,0 ) except AttributeError: logger.info(F"""{module_identifier} is not a module.""" ) else: _a : str = doctest.testfile(str('..' / directory / file ) ,optionflags=doctest.ELLIPSIS ) self.assertIs(result.failed ,0 ) def __lowercase ( self : Union[str, Any] ): _a : Optional[Any] = Path('src/transformers' ) _a : Optional[Any] = 'modeling' _a : Union[str, Any] = [ 'modeling_ctrl.py', 'modeling_tf_ctrl.py', ] self.analyze_directory(_UpperCAmelCase ,identifier=_UpperCAmelCase ,ignore_files=_UpperCAmelCase ) def __lowercase ( self : int ): _a : str = Path('src/transformers' ) _a : List[str] = 'tokenization' self.analyze_directory(_UpperCAmelCase ,identifier=_UpperCAmelCase ) def __lowercase ( self : int ): _a : Any = Path('src/transformers' ) _a : str = 'configuration' self.analyze_directory(_UpperCAmelCase ,identifier=_UpperCAmelCase ) def __lowercase ( self : Dict ): _a : Tuple = Path('src/transformers' ) _a : Optional[int] = ['configuration', 'modeling', 'tokenization'] self.analyze_directory(_UpperCAmelCase ,n_identifier=_UpperCAmelCase ) def __lowercase ( self : Optional[Any] ): _a : Union[str, Any] = Path('docs/source' ) _a : List[str] = ['favicon.ico'] self.analyze_directory(_UpperCAmelCase ,ignore_files=_UpperCAmelCase ,only_modules=_UpperCAmelCase )
89
0
'''simple docstring''' import argparse import glob import importlib.util import os import re import black from doc_builder.style_doc import style_docstrings_in_code # 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 lowerCAmelCase__ = '''src/diffusers''' lowerCAmelCase__ = '''.''' # This is to make sure the diffusers module imported is the one in the repo. lowerCAmelCase__ = importlib.util.spec_from_file_location( '''diffusers''', os.path.join(DIFFUSERS_PATH, '''__init__.py'''), submodule_search_locations=[DIFFUSERS_PATH], ) lowerCAmelCase__ = spec.loader.load_module() def _A ( A__ , A__ ): """simple docstring""" return line.startswith(A__ ) or len(A__ ) <= 1 or re.search(R'''^\s*\)(\s*->.*:|:)\s*$''' , A__ ) is not None def _A ( A__ ): """simple docstring""" __lowercase = object_name.split('''.''' ) __lowercase = 0 # First let's find the module where our object lives. __lowercase = parts[i] while i < len(A__ ) and not os.path.isfile(os.path.join(A__ , F"{module}.py" ) ): i += 1 if i < len(A__ ): __lowercase = os.path.join(A__ , parts[i] ) if i >= len(A__ ): raise ValueError(F"`object_name` should begin with the name of a module of diffusers but got {object_name}." ) with open(os.path.join(A__ , F"{module}.py" ) , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: __lowercase = f.readlines() # Now let's find the class / func in the code! __lowercase = '''''' __lowercase = 0 for name in parts[i + 1 :]: while ( line_index < len(A__ ) and re.search(RF"^{indent}(class|def)\s+{name}(\(|\:)" , lines[line_index] ) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(A__ ): raise ValueError(F" {object_name} does not match any function or class in {module}." ) # We found the beginning of the class / func, now let's find the end (when the indent diminishes). __lowercase = line_index while line_index < len(A__ ) and _should_continue(lines[line_index] , A__ ): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 __lowercase = lines[start_index:line_index] return "".join(A__ ) lowerCAmelCase__ = re.compile(R'''^(\s*)#\s*Copied from\s+diffusers\.(\S+\.\S+)\s*($|\S.*$)''') lowerCAmelCase__ = re.compile(R'''^\s*(\S+)->(\S+)(\s+.*|$)''') lowerCAmelCase__ = re.compile(R'''<FILL\s+[^>]*>''') def _A ( A__ ): """simple docstring""" __lowercase = code.split('''\n''' ) __lowercase = 0 while idx < len(A__ ) and len(lines[idx] ) == 0: idx += 1 if idx < len(A__ ): return re.search(R'''^(\s*)\S''' , lines[idx] ).groups()[0] return "" def _A ( A__ ): """simple docstring""" __lowercase = len(get_indent(A__ ) ) > 0 if has_indent: __lowercase = F"class Bla:\n{code}" __lowercase = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 , preview=A__ ) __lowercase = black.format_str(A__ , mode=A__ ) __lowercase , __lowercase = style_docstrings_in_code(A__ ) return result[len('''class Bla:\n''' ) :] if has_indent else result def _A ( A__ , A__=False ): """simple docstring""" with open(A__ , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f: __lowercase = f.readlines() __lowercase = [] __lowercase = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(A__ ): __lowercase = _re_copy_warning.search(lines[line_index] ) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. __lowercase , __lowercase , __lowercase = search.groups() __lowercase = find_code_in_diffusers(A__ ) __lowercase = get_indent(A__ ) __lowercase = line_index + 1 if indent == theoretical_indent else line_index + 2 __lowercase = theoretical_indent __lowercase = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. __lowercase = True while line_index < len(A__ ) and should_continue: line_index += 1 if line_index >= len(A__ ): break __lowercase = lines[line_index] __lowercase = _should_continue(A__ , A__ ) and re.search(F"^{indent}# End copy" , A__ ) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1] ) <= 1: line_index -= 1 __lowercase = lines[start_index:line_index] __lowercase = ''''''.join(A__ ) # Remove any nested `Copied from` comments to avoid circular copies __lowercase = [line for line in theoretical_code.split('''\n''' ) if _re_copy_warning.search(A__ ) is None] __lowercase = '''\n'''.join(A__ ) # Before comparing, use the `replace_pattern` on the original code. if len(A__ ) > 0: __lowercase = replace_pattern.replace('''with''' , '''''' ).split(''',''' ) __lowercase = [_re_replace_pattern.search(A__ ) for p in patterns] for pattern in patterns: if pattern is None: continue __lowercase , __lowercase , __lowercase = pattern.groups() __lowercase = re.sub(A__ , A__ , A__ ) if option.strip() == "all-casing": __lowercase = re.sub(obja.lower() , obja.lower() , A__ ) __lowercase = re.sub(obja.upper() , obja.upper() , A__ ) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line __lowercase = blackify(lines[start_index - 1] + theoretical_code ) __lowercase = theoretical_code[len(lines[start_index - 1] ) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index] ) if overwrite: __lowercase = lines[:start_index] + [theoretical_code] + lines[line_index:] __lowercase = start_index + 1 if overwrite and len(A__ ) > 0: # Warn the user a file has been modified. print(F"Detected changes, rewriting {filename}." ) with open(A__ , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f: f.writelines(A__ ) return diffs def _A ( A__ = False ): """simple docstring""" __lowercase = glob.glob(os.path.join(A__ , '''**/*.py''' ) , recursive=A__ ) __lowercase = [] for filename in all_files: __lowercase = is_copy_consistent(A__ , A__ ) diffs += [F"- {filename}: copy does not match {d[0]} at line {d[1]}" for d in new_diffs] if not overwrite and len(A__ ) > 0: __lowercase = '''\n'''.join(A__ ) raise Exception( '''Found the following copy inconsistencies:\n''' + diff + '''\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them.''' ) if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') lowerCAmelCase__ = parser.parse_args() check_copies(args.fix_and_overwrite)
104
'''simple docstring''' import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_processing_utils import ImageProcessingMixin from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = OrderedDict( [ ('''align''', '''EfficientNetImageProcessor'''), ('''beit''', '''BeitImageProcessor'''), ('''bit''', '''BitImageProcessor'''), ('''blip''', '''BlipImageProcessor'''), ('''blip-2''', '''BlipImageProcessor'''), ('''bridgetower''', '''BridgeTowerImageProcessor'''), ('''chinese_clip''', '''ChineseCLIPImageProcessor'''), ('''clip''', '''CLIPImageProcessor'''), ('''clipseg''', '''ViTImageProcessor'''), ('''conditional_detr''', '''ConditionalDetrImageProcessor'''), ('''convnext''', '''ConvNextImageProcessor'''), ('''convnextv2''', '''ConvNextImageProcessor'''), ('''cvt''', '''ConvNextImageProcessor'''), ('''data2vec-vision''', '''BeitImageProcessor'''), ('''deformable_detr''', '''DeformableDetrImageProcessor'''), ('''deit''', '''DeiTImageProcessor'''), ('''deta''', '''DetaImageProcessor'''), ('''detr''', '''DetrImageProcessor'''), ('''dinat''', '''ViTImageProcessor'''), ('''donut-swin''', '''DonutImageProcessor'''), ('''dpt''', '''DPTImageProcessor'''), ('''efficientformer''', '''EfficientFormerImageProcessor'''), ('''efficientnet''', '''EfficientNetImageProcessor'''), ('''flava''', '''FlavaImageProcessor'''), ('''focalnet''', '''BitImageProcessor'''), ('''git''', '''CLIPImageProcessor'''), ('''glpn''', '''GLPNImageProcessor'''), ('''groupvit''', '''CLIPImageProcessor'''), ('''imagegpt''', '''ImageGPTImageProcessor'''), ('''instructblip''', '''BlipImageProcessor'''), ('''layoutlmv2''', '''LayoutLMv2ImageProcessor'''), ('''layoutlmv3''', '''LayoutLMv3ImageProcessor'''), ('''levit''', '''LevitImageProcessor'''), ('''mask2former''', '''Mask2FormerImageProcessor'''), ('''maskformer''', '''MaskFormerImageProcessor'''), ('''mgp-str''', '''ViTImageProcessor'''), ('''mobilenet_v1''', '''MobileNetV1ImageProcessor'''), ('''mobilenet_v2''', '''MobileNetV2ImageProcessor'''), ('''mobilevit''', '''MobileViTImageProcessor'''), ('''mobilevit''', '''MobileViTImageProcessor'''), ('''mobilevitv2''', '''MobileViTImageProcessor'''), ('''nat''', '''ViTImageProcessor'''), ('''oneformer''', '''OneFormerImageProcessor'''), ('''owlvit''', '''OwlViTImageProcessor'''), ('''perceiver''', '''PerceiverImageProcessor'''), ('''pix2struct''', '''Pix2StructImageProcessor'''), ('''poolformer''', '''PoolFormerImageProcessor'''), ('''regnet''', '''ConvNextImageProcessor'''), ('''resnet''', '''ConvNextImageProcessor'''), ('''sam''', '''SamImageProcessor'''), ('''segformer''', '''SegformerImageProcessor'''), ('''swiftformer''', '''ViTImageProcessor'''), ('''swin''', '''ViTImageProcessor'''), ('''swin2sr''', '''Swin2SRImageProcessor'''), ('''swinv2''', '''ViTImageProcessor'''), ('''table-transformer''', '''DetrImageProcessor'''), ('''timesformer''', '''VideoMAEImageProcessor'''), ('''tvlt''', '''TvltImageProcessor'''), ('''upernet''', '''SegformerImageProcessor'''), ('''van''', '''ConvNextImageProcessor'''), ('''videomae''', '''VideoMAEImageProcessor'''), ('''vilt''', '''ViltImageProcessor'''), ('''vit''', '''ViTImageProcessor'''), ('''vit_hybrid''', '''ViTHybridImageProcessor'''), ('''vit_mae''', '''ViTImageProcessor'''), ('''vit_msn''', '''ViTImageProcessor'''), ('''xclip''', '''CLIPImageProcessor'''), ('''yolos''', '''YolosImageProcessor'''), ] ) __lowerCAmelCase = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def __lowerCamelCase ( lowerCAmelCase_ ) -> Optional[Any]: for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: _a : List[Any] = model_type_to_module_name(lowerCAmelCase_ ) _a : Optional[Any] = importlib.import_module(f""".{module_name}""" , 'transformers.models' ) try: return getattr(lowerCAmelCase_ , lowerCAmelCase_ ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(lowerCAmelCase_ , '__name__' , lowerCAmelCase_ ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. _a : Dict = importlib.import_module('transformers' ) if hasattr(lowerCAmelCase_ , lowerCAmelCase_ ): return getattr(lowerCAmelCase_ , lowerCAmelCase_ ) return None def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = False , lowerCAmelCase_ = False , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = False , **lowerCAmelCase_ , ) -> Tuple: _a : List[str] = get_file_from_repo( lowerCAmelCase_ , lowerCAmelCase_ , cache_dir=lowerCAmelCase_ , force_download=lowerCAmelCase_ , resume_download=lowerCAmelCase_ , proxies=lowerCAmelCase_ , use_auth_token=lowerCAmelCase_ , revision=lowerCAmelCase_ , local_files_only=lowerCAmelCase_ , ) if resolved_config_file is None: logger.info( 'Could not locate the image processor configuration file, will try to use the model config instead.' ) return {} with open(lowerCAmelCase_ , encoding='utf-8' ) as reader: return json.load(lowerCAmelCase_ ) class __magic_name__ : def __init__( self : List[str] ): raise EnvironmentError( 'AutoImageProcessor is designed to be instantiated ' 'using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.' ) @classmethod @replace_list_option_in_docstrings(_UpperCAmelCase ) def __lowercase ( cls : Dict ,_UpperCAmelCase : Union[str, Any] ,**_UpperCAmelCase : Optional[Any] ): _a : Any = kwargs.pop('config' ,_UpperCAmelCase ) _a : Dict = kwargs.pop('trust_remote_code' ,_UpperCAmelCase ) _a : Any = True _a , _a : Tuple = ImageProcessingMixin.get_image_processor_dict(_UpperCAmelCase ,**_UpperCAmelCase ) _a : List[Any] = config_dict.get('image_processor_type' ,_UpperCAmelCase ) _a : int = None if "AutoImageProcessor" in config_dict.get('auto_map' ,{} ): _a : Any = config_dict['auto_map']['AutoImageProcessor'] # If we still don't have the image processor class, check if we're loading from a previous feature extractor config # and if so, infer the image processor class from there. if image_processor_class is None and image_processor_auto_map is None: _a : List[Any] = config_dict.pop('feature_extractor_type' ,_UpperCAmelCase ) if feature_extractor_class is not None: logger.warning( 'Could not find image processor class in the image processor config or the model config. Loading' ' based on pattern matching with the model\'s feature extractor configuration.' ) _a : Optional[int] = feature_extractor_class.replace('FeatureExtractor' ,'ImageProcessor' ) if "AutoFeatureExtractor" in config_dict.get('auto_map' ,{} ): _a : List[Any] = config_dict['auto_map']['AutoFeatureExtractor'] _a : List[str] = feature_extractor_auto_map.replace('FeatureExtractor' ,'ImageProcessor' ) logger.warning( 'Could not find image processor auto map in the image processor config or the model config.' ' Loading based on pattern matching with the model\'s feature extractor configuration.' ) # If we don't find the image processor class in the image processor config, let's try the model config. if image_processor_class is None and image_processor_auto_map is None: if not isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : Dict = AutoConfig.from_pretrained(_UpperCAmelCase ,**_UpperCAmelCase ) # It could be in `config.image_processor_type`` _a : Optional[int] = getattr(_UpperCAmelCase ,'image_processor_type' ,_UpperCAmelCase ) if hasattr(_UpperCAmelCase ,'auto_map' ) and "AutoImageProcessor" in config.auto_map: _a : Union[str, Any] = config.auto_map['AutoImageProcessor'] if image_processor_class is not None: _a : Optional[int] = image_processor_class_from_name(_UpperCAmelCase ) _a : List[str] = image_processor_auto_map is not None _a : Optional[int] = image_processor_class is not None or type(_UpperCAmelCase ) in IMAGE_PROCESSOR_MAPPING _a : Optional[int] = resolve_trust_remote_code( _UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) if has_remote_code and trust_remote_code: _a : Dict = get_class_from_dynamic_module( _UpperCAmelCase ,_UpperCAmelCase ,**_UpperCAmelCase ) _a : int = kwargs.pop('code_revision' ,_UpperCAmelCase ) if os.path.isdir(_UpperCAmelCase ): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(_UpperCAmelCase ,**_UpperCAmelCase ) elif image_processor_class is not None: return image_processor_class.from_dict(_UpperCAmelCase ,**_UpperCAmelCase ) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(_UpperCAmelCase ) in IMAGE_PROCESSOR_MAPPING: _a : Dict = IMAGE_PROCESSOR_MAPPING[type(_UpperCAmelCase )] return image_processor_class.from_dict(_UpperCAmelCase ,**_UpperCAmelCase ) raise ValueError( F"""Unrecognized image processor in {pretrained_model_name_or_path}. Should have a """ F"""`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following """ F"""`model_type` keys in its {CONFIG_NAME}: {', '.join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys() )}""" ) @staticmethod def __lowercase ( _UpperCAmelCase : Optional[Any] ,_UpperCAmelCase : Dict ): IMAGE_PROCESSOR_MAPPING.register(_UpperCAmelCase ,_UpperCAmelCase )
89
0
"""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 a : Dict = logging.get_logger(__name__) a : Optional[Any] = 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'''), ] ) a : Optional[int] = 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'''), ] ) a : Dict = 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'''), ] ) a : str = 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'''), ] ) a : int = OrderedDict( [ # Model for Image-classsification ('''beit''', '''FlaxBeitForImageClassification'''), ('''regnet''', '''FlaxRegNetForImageClassification'''), ('''resnet''', '''FlaxResNetForImageClassification'''), ('''vit''', '''FlaxViTForImageClassification'''), ] ) a : str = OrderedDict( [ ('''vision-encoder-decoder''', '''FlaxVisionEncoderDecoderModel'''), ] ) a : Any = OrderedDict( [ # Model for Causal LM mapping ('''bart''', '''FlaxBartForCausalLM'''), ('''bert''', '''FlaxBertForCausalLM'''), ('''big_bird''', '''FlaxBigBirdForCausalLM'''), ('''electra''', '''FlaxElectraForCausalLM'''), ('''gpt-sw3''', '''FlaxGPT2LMHeadModel'''), ('''gpt2''', '''FlaxGPT2LMHeadModel'''), ('''gpt_neo''', '''FlaxGPTNeoForCausalLM'''), ('''gptj''', '''FlaxGPTJForCausalLM'''), ('''opt''', '''FlaxOPTForCausalLM'''), ('''roberta''', '''FlaxRobertaForCausalLM'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormForCausalLM'''), ('''xglm''', '''FlaxXGLMForCausalLM'''), ('''xlm-roberta''', '''FlaxXLMRobertaForCausalLM'''), ] ) a : Union[str, Any] = 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'''), ] ) a : str = OrderedDict( [ # Model for Question Answering mapping ('''albert''', '''FlaxAlbertForQuestionAnswering'''), ('''bart''', '''FlaxBartForQuestionAnswering'''), ('''bert''', '''FlaxBertForQuestionAnswering'''), ('''big_bird''', '''FlaxBigBirdForQuestionAnswering'''), ('''distilbert''', '''FlaxDistilBertForQuestionAnswering'''), ('''electra''', '''FlaxElectraForQuestionAnswering'''), ('''mbart''', '''FlaxMBartForQuestionAnswering'''), ('''roberta''', '''FlaxRobertaForQuestionAnswering'''), ('''roberta-prelayernorm''', '''FlaxRobertaPreLayerNormForQuestionAnswering'''), ('''roformer''', '''FlaxRoFormerForQuestionAnswering'''), ('''xlm-roberta''', '''FlaxXLMRobertaForQuestionAnswering'''), ] ) a : List[str] = 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'''), ] ) a : Any = 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'''), ] ) a : Dict = OrderedDict( [ ('''bert''', '''FlaxBertForNextSentencePrediction'''), ] ) a : Tuple = OrderedDict( [ ('''speech-encoder-decoder''', '''FlaxSpeechEncoderDecoderModel'''), ('''whisper''', '''FlaxWhisperForConditionalGeneration'''), ] ) a : List[Any] = OrderedDict( [ ('''whisper''', '''FlaxWhisperForAudioClassification'''), ] ) a : Optional[Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_MAPPING_NAMES) a : Optional[int] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_PRETRAINING_MAPPING_NAMES) a : Union[str, Any] = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MASKED_LM_MAPPING_NAMES) a : Tuple = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES ) a : Union[str, Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES ) a : int = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES) a : Any = _LazyAutoMapping(CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) a : Dict = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES ) a : Tuple = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES ) a : Union[str, Any] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES ) a : int = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) a : Any = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) a : Optional[int] = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES ) a : int = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES ) class __UpperCamelCase ( _BaseAutoModelClass ): lowerCamelCase : str =FLAX_MODEL_MAPPING a : Optional[Any] = auto_class_update(FlaxAutoModel) class __UpperCamelCase ( _BaseAutoModelClass ): lowerCamelCase : Any =FLAX_MODEL_FOR_PRETRAINING_MAPPING a : Optional[Any] = auto_class_update(FlaxAutoModelForPreTraining, head_doc='''pretraining''') class __UpperCamelCase ( _BaseAutoModelClass ): lowerCamelCase : Optional[int] =FLAX_MODEL_FOR_CAUSAL_LM_MAPPING a : str = auto_class_update(FlaxAutoModelForCausalLM, head_doc='''causal language modeling''') class __UpperCamelCase ( _BaseAutoModelClass ): lowerCamelCase : List[Any] =FLAX_MODEL_FOR_MASKED_LM_MAPPING a : Optional[Any] = auto_class_update(FlaxAutoModelForMaskedLM, head_doc='''masked language modeling''') class __UpperCamelCase ( _BaseAutoModelClass ): lowerCamelCase : Optional[Any] =FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING a : Tuple = auto_class_update( FlaxAutoModelForSeqaSeqLM, head_doc='''sequence-to-sequence language modeling''', checkpoint_for_example='''t5-base''' ) class __UpperCamelCase ( _BaseAutoModelClass ): lowerCamelCase : Tuple =FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING a : Optional[Any] = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc='''sequence classification''' ) class __UpperCamelCase ( _BaseAutoModelClass ): lowerCamelCase : str =FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING a : List[Any] = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc='''question answering''') class __UpperCamelCase ( _BaseAutoModelClass ): lowerCamelCase : Dict =FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING a : Union[str, Any] = auto_class_update( FlaxAutoModelForTokenClassification, head_doc='''token classification''' ) class __UpperCamelCase ( _BaseAutoModelClass ): lowerCamelCase : int =FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING a : Dict = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc='''multiple choice''') class __UpperCamelCase ( _BaseAutoModelClass ): lowerCamelCase : Union[str, Any] =FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING a : Tuple = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc='''next sentence prediction''' ) class __UpperCamelCase ( _BaseAutoModelClass ): lowerCamelCase : Any =FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING a : List[Any] = auto_class_update( FlaxAutoModelForImageClassification, head_doc='''image classification''' ) class __UpperCamelCase ( _BaseAutoModelClass ): lowerCamelCase : List[Any] =FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING a : List[Any] = auto_class_update(FlaxAutoModelForVisionaSeq, head_doc='''vision-to-text modeling''') class __UpperCamelCase ( _BaseAutoModelClass ): lowerCamelCase : Any =FLAX_MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING a : Optional[Any] = auto_class_update( FlaxAutoModelForSpeechSeqaSeq, head_doc='''sequence-to-sequence speech-to-text modeling''' )
105
'''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 __lowerCAmelCase = None __lowerCAmelCase = '''<''' 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 __lowerCAmelCase = [ 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 __magic_name__ : lowerCAmelCase : bool = True lowerCAmelCase : Optional[str] = None # Automatically constructed lowerCAmelCase : ClassVar[str] = "PIL.Image.Image" lowerCAmelCase : ClassVar[Any] = pa.struct({'bytes': pa.binary(), 'path': pa.string()} ) lowerCAmelCase : str = field(default='Image' , init=_UpperCamelCase , repr=_UpperCamelCase ) def __call__( self : Union[str, Any] ): return self.pa_type def __lowercase ( self : Any ,_UpperCAmelCase : Union[str, bytes, dict, np.ndarray, "PIL.Image.Image"] ): if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support encoding images, please install \'Pillow\'.' ) if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : Optional[Any] = np.array(_UpperCAmelCase ) if isinstance(_UpperCAmelCase ,_UpperCAmelCase ): return {"path": value, "bytes": None} elif isinstance(_UpperCAmelCase ,_UpperCAmelCase ): return {"path": None, "bytes": value} elif isinstance(_UpperCAmelCase ,np.ndarray ): # convert the image array to PNG/TIFF bytes return encode_np_array(_UpperCAmelCase ) elif isinstance(_UpperCAmelCase ,PIL.Image.Image ): # convert the PIL image to bytes (default format is PNG/TIFF) return encode_pil_image(_UpperCAmelCase ) 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 __lowercase ( self : Optional[Any] ,_UpperCAmelCase : dict ,_UpperCAmelCase : Optional[int]=None ): 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 : Dict = {} _a , _a : str = 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(_UpperCAmelCase ): _a : Any = PIL.Image.open(_UpperCAmelCase ) else: _a : List[Any] = path.split('::' )[-1] try: _a : str = string_to_dict(_UpperCAmelCase ,config.HUB_DATASETS_URL )['repo_id'] _a : Optional[Any] = token_per_repo_id.get(_UpperCAmelCase ) except ValueError: _a : int = None with xopen(_UpperCAmelCase ,'rb' ,use_auth_token=_UpperCAmelCase ) as f: _a : Tuple = BytesIO(f.read() ) _a : Union[str, Any] = PIL.Image.open(bytes_ ) else: _a : Optional[int] = PIL.Image.open(BytesIO(bytes_ ) ) image.load() # to avoid "Too many open files" errors return image def __lowercase ( self : int ): from .features import Value return ( self if self.decode else { "bytes": Value('binary' ), "path": Value('string' ), } ) def __lowercase ( self : str ,_UpperCAmelCase : Union[pa.StringArray, pa.StructArray, pa.ListArray] ): if pa.types.is_string(storage.type ): _a : Union[str, Any] = pa.array([None] * len(_UpperCAmelCase ) ,type=pa.binary() ) _a : Union[str, 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(_UpperCAmelCase ) ,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 : Tuple = pa.array([None] * len(_UpperCAmelCase ) ,type=pa.binary() ) if storage.type.get_field_index('path' ) >= 0: _a : Union[str, Any] = storage.field('path' ) else: _a : Dict = pa.array([None] * len(_UpperCAmelCase ) ,type=pa.string() ) _a : Optional[Any] = pa.StructArray.from_arrays([bytes_array, path_array] ,['bytes', 'path'] ,mask=storage.is_null() ) elif pa.types.is_list(storage.type ): _a : List[str] = pa.array( [encode_np_array(np.array(_UpperCAmelCase ) )['bytes'] if arr is not None else None for arr in storage.to_pylist()] ,type=pa.binary() ,) _a : int = pa.array([None] * len(_UpperCAmelCase ) ,type=pa.string() ) _a : Optional[Any] = pa.StructArray.from_arrays( [bytes_array, path_array] ,['bytes', 'path'] ,mask=bytes_array.is_null() ) return array_cast(_UpperCAmelCase ,self.pa_type ) def __lowercase ( self : Dict ,_UpperCAmelCase : pa.StructArray ): @no_op_if_value_is_null def path_to_bytes(_UpperCAmelCase : Tuple ): with xopen(_UpperCAmelCase ,'rb' ) as f: _a : int = f.read() return bytes_ _a : Any = 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 : Optional[Any] = pa.array( [os.path.basename(_UpperCAmelCase ) if path is not None else None for path in storage.field('path' ).to_pylist()] ,type=pa.string() ,) _a : Dict = pa.StructArray.from_arrays([bytes_array, path_array] ,['bytes', 'path'] ,mask=bytes_array.is_null() ) return array_cast(_UpperCAmelCase ,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 ( lowerCAmelCase_ ) -> bytes: _a : Optional[int] = BytesIO() if image.format in list_image_compression_formats(): _a : Optional[Any] = image.format else: _a : str = 'PNG' if image.mode in ['1', 'L', 'LA', 'RGB', 'RGBA'] else 'TIFF' image.save(lowerCAmelCase_ , format=lowerCAmelCase_ ) return buffer.getvalue() def __lowerCamelCase ( lowerCAmelCase_ ) -> dict: if hasattr(lowerCAmelCase_ , 'filename' ) and image.filename != "": return {"path": image.filename, "bytes": None} else: return {"path": None, "bytes": image_to_bytes(lowerCAmelCase_ )} def __lowerCamelCase ( lowerCAmelCase_ ) -> dict: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support encoding images, please install \'Pillow\'.' ) _a : List[Any] = array.dtype _a : Optional[int] = dtype.byteorder if dtype.byteorder != '=' else _NATIVE_BYTEORDER _a : Union[str, Any] = dtype.kind _a : Union[str, Any] = dtype.itemsize _a : List[Any] = None # Multi-channel array case (only np.dtype("|u1") is allowed) if array.shape[2:]: _a : Optional[int] = 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 : Union[str, 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 : str = dtype_byteorder + dtype_kind + str(lowerCAmelCase_ ) _a : List[Any] = np.dtype(lowerCAmelCase_ ) 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(lowerCAmelCase_ ) ) return {"path": None, "bytes": image_to_bytes(lowerCAmelCase_ )} def __lowerCamelCase ( lowerCAmelCase_ ) -> List[dict]: if config.PIL_AVAILABLE: import PIL.Image else: raise ImportError('To support encoding images, please install \'Pillow\'.' ) if objs: _a , _a : Optional[Any] = first_non_null_value(lowerCAmelCase_ ) if isinstance(lowerCAmelCase_ , lowerCAmelCase_ ): return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs] if isinstance(lowerCAmelCase_ , np.ndarray ): _a : List[str] = no_op_if_value_is_null(lowerCAmelCase_ ) return [obj_to_image_dict_func(lowerCAmelCase_ ) for obj in objs] elif isinstance(lowerCAmelCase_ , PIL.Image.Image ): _a : List[str] = no_op_if_value_is_null(lowerCAmelCase_ ) return [obj_to_image_dict_func(lowerCAmelCase_ ) for obj in objs] else: return objs else: return objs
89
0
"""simple docstring""" from __future__ import annotations import sys from collections import deque from typing import Generic, TypeVar __UpperCamelCase : Tuple = TypeVar('''T''') class SCREAMING_SNAKE_CASE ( Generic[T] ): """simple docstring""" lowercase__ = 42 # Cache store of keys lowercase__ = 42 # References of the keys in cache lowercase__ = 10 # Maximum capacity of cache def __init__( self : Dict ,lowercase_ : int ): lowerCAmelCase__ : str = deque() lowerCAmelCase__ : Any = set() if not n: lowerCAmelCase__ : Optional[Any] = sys.maxsize elif n < 0: raise ValueError('''n should be an integer greater than 0.''' ) else: lowerCAmelCase__ : int = n def __lowerCAmelCase ( self : str ,lowercase_ : T ): if x not in self.key_reference: if len(self.dq_store ) == LRUCache._MAX_CAPACITY: lowerCAmelCase__ : Any = self.dq_store.pop() self.key_reference.remove(lowercase_ ) else: self.dq_store.remove(lowercase_ ) self.dq_store.appendleft(lowercase_ ) self.key_reference.add(lowercase_ ) def __lowerCAmelCase ( self : int ): for k in self.dq_store: print(lowercase_ ) def __repr__( self : Tuple ): return F'LRUCache({self._MAX_CAPACITY}) => {list(self.dq_store )}' if __name__ == "__main__": import doctest doctest.testmod() __UpperCamelCase : LRUCache[str | int] = LRUCache(4) lru_cache.refer('''A''') lru_cache.refer(2) lru_cache.refer(3) lru_cache.refer('''A''') lru_cache.refer(4) lru_cache.refer(5) lru_cache.display() print(lru_cache) assert str(lru_cache) == "LRUCache(4) => [5, 4, 'A', 3]"
106
'''simple docstring''' from __future__ import annotations from collections.abc import Sequence from typing import Literal def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> str | Literal[False]: _a : Optional[int] = list(lowerCAmelCase_ ) _a : Optional[Any] = list(lowerCAmelCase_ ) _a : Union[str, Any] = 0 for i in range(len(lowerCAmelCase_ ) ): if lista[i] != lista[i]: count += 1 _a : Optional[int] = '_' if count > 1: return False else: return "".join(lowerCAmelCase_ ) def __lowerCamelCase ( lowerCAmelCase_ ) -> list[str]: _a : Optional[int] = [] while True: _a : Any = ['$'] * len(lowerCAmelCase_ ) _a : List[str] = [] for i in range(len(lowerCAmelCase_ ) ): for j in range(i + 1 , len(lowerCAmelCase_ ) ): _a : Optional[int] = compare_string(binary[i] , binary[j] ) if k is False: _a : Optional[Any] = '*' _a : Optional[Any] = '*' temp.append('X' ) for i in range(len(lowerCAmelCase_ ) ): if checka[i] == "$": pi.append(binary[i] ) if len(lowerCAmelCase_ ) == 0: return pi _a : Any = list(set(lowerCAmelCase_ ) ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> list[str]: _a : int = [] for minterm in minterms: _a : Optional[int] = '' for _ in range(lowerCAmelCase_ ): _a : Union[str, Any] = str(minterm % 2 ) + string minterm //= 2 temp.append(lowerCAmelCase_ ) return temp def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> bool: _a : int = list(lowerCAmelCase_ ) _a : Union[str, Any] = list(lowerCAmelCase_ ) _a : str = 0 for i in range(len(lowerCAmelCase_ ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> list[str]: _a : List[Any] = [] _a : Optional[Any] = [0] * len(lowerCAmelCase_ ) for i in range(len(chart[0] ) ): _a : Union[str, Any] = 0 _a : int = -1 for j in range(len(lowerCAmelCase_ ) ): if chart[j][i] == 1: count += 1 _a : int = j if count == 1: _a : List[Any] = 1 for i in range(len(lowerCAmelCase_ ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(lowerCAmelCase_ ) ): _a : Any = 0 temp.append(prime_implicants[i] ) while True: _a : Union[str, Any] = 0 _a : List[Any] = -1 _a : str = 0 for i in range(len(lowerCAmelCase_ ) ): _a : Union[str, Any] = chart[i].count(1 ) if count_n > max_n: _a : Any = count_n _a : int = i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(lowerCAmelCase_ ) ): _a : List[str] = 0 def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> list[list[int]]: _a : int = [[0 for x in range(len(lowerCAmelCase_ ) )] for x in range(len(lowerCAmelCase_ ) )] for i in range(len(lowerCAmelCase_ ) ): _a : str = prime_implicants[i].count('_' ) for j in range(len(lowerCAmelCase_ ) ): if is_for_table(prime_implicants[i] , binary[j] , lowerCAmelCase_ ): _a : Optional[Any] = 1 return chart def __lowerCamelCase ( ) -> None: _a : Optional[int] = int(input('Enter the no. of variables\n' ) ) _a : List[Any] = [ float(lowerCAmelCase_ ) for x in input( 'Enter the decimal representation of Minterms \'Spaces Separated\'\n' ).split() ] _a : List[str] = decimal_to_binary(lowerCAmelCase_ , lowerCAmelCase_ ) _a : Dict = check(lowerCAmelCase_ ) print('Prime Implicants are:' ) print(lowerCAmelCase_ ) _a : List[Any] = prime_implicant_chart(lowerCAmelCase_ , lowerCAmelCase_ ) _a : int = selection(lowerCAmelCase_ , lowerCAmelCase_ ) print('Essential Prime Implicants are:' ) print(lowerCAmelCase_ ) if __name__ == "__main__": import doctest doctest.testmod() main()
89
0
import unittest from transformers import BigBirdConfig, 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 from transformers.models.big_bird.modeling_flax_big_bird import ( FlaxBigBirdForCausalLM, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForPreTraining, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, FlaxBigBirdModel, ) class snake_case__ (unittest.TestCase ): """simple docstring""" def __init__( self : List[Any] , __lowerCamelCase : Optional[int] , __lowerCamelCase : List[str]=2 , __lowerCamelCase : str=56 , __lowerCamelCase : int=True , __lowerCamelCase : Any=True , __lowerCamelCase : Dict=True , __lowerCamelCase : List[str]=True , __lowerCamelCase : Optional[int]=99 , __lowerCamelCase : List[str]=32 , __lowerCamelCase : Any=2 , __lowerCamelCase : Union[str, Any]=2 , __lowerCamelCase : List[Any]=7 , __lowerCamelCase : Optional[int]="gelu_new" , __lowerCamelCase : Dict=0.1 , __lowerCamelCase : Dict=0.1 , __lowerCamelCase : Union[str, Any]=5_12 , __lowerCamelCase : Optional[int]=16 , __lowerCamelCase : Union[str, Any]=2 , __lowerCamelCase : Optional[Any]=0.02 , __lowerCamelCase : str=4 , __lowerCamelCase : List[Any]="block_sparse" , __lowerCamelCase : Optional[Any]=True , __lowerCamelCase : List[Any]=False , __lowerCamelCase : List[str]=2 , __lowerCamelCase : Any=3 , ) -> List[str]: a = parent a = batch_size a = seq_length a = is_training a = use_attention_mask a = use_token_type_ids a = use_labels a = vocab_size a = hidden_size a = num_hidden_layers a = num_attention_heads a = intermediate_size a = hidden_act a = hidden_dropout_prob a = attention_probs_dropout_prob a = max_position_embeddings a = type_vocab_size a = type_sequence_label_size a = initializer_range a = num_choices a = rescale_embeddings a = attention_type a = use_bias a = block_size a = num_random_blocks def __UpperCAmelCase ( self : Any ) -> List[Any]: a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a = None if self.use_attention_mask: a = random_attention_mask([self.batch_size, self.seq_length] ) a = None if self.use_token_type_ids: a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a = BigBirdConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__lowerCamelCase , initializer_range=self.initializer_range , attention_type=self.attention_type , block_size=self.block_size , num_random_blocks=self.num_random_blocks , use_bias=self.use_bias , rescale_embeddings=self.rescale_embeddings , ) return config, input_ids, token_type_ids, attention_mask def __UpperCAmelCase ( self : Optional[Any] ) -> List[str]: a = self.prepare_config_and_inputs() a , a , a , a = config_and_inputs a = { "input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": attention_mask, } return config, inputs_dict @require_flax class snake_case__ (_UpperCamelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] = ( ( FlaxBigBirdForCausalLM, FlaxBigBirdModel, FlaxBigBirdForPreTraining, FlaxBigBirdForMaskedLM, FlaxBigBirdForMultipleChoice, FlaxBigBirdForQuestionAnswering, FlaxBigBirdForSequenceClassification, FlaxBigBirdForTokenClassification, ) if is_flax_available() else () ) SCREAMING_SNAKE_CASE_ : Optional[int] = False SCREAMING_SNAKE_CASE_ : Union[str, Any] = False def __UpperCAmelCase ( self : Tuple ) -> Any: a = FlaxBigBirdModelTester(self ) @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __UpperCAmelCase ( self : Dict ) -> List[Any]: super().test_from_pretrained_save_pretrained() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __UpperCAmelCase ( self : Optional[int] ) -> str: super().test_from_pretrained_with_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __UpperCAmelCase ( self : Optional[int] ) -> Union[str, Any]: super().test_no_automatic_init() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __UpperCAmelCase ( self : Optional[Any] ) -> str: super().test_hidden_states_output() @slow def __UpperCAmelCase ( self : int ) -> List[str]: for model_class_name in self.all_model_classes: a = model_class_name.from_pretrained("google/bigbird-roberta-base" ) self.assertIsNotNone(__lowerCamelCase ) def __UpperCAmelCase ( self : Union[str, Any] ) -> List[Any]: if self.test_attn_probs: super().test_attention_outputs() @slow # copied from `test_modeling_flax_common` because it takes much longer than other models def __UpperCAmelCase ( self : Tuple ) -> Optional[Any]: a , a = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): a = self._prepare_for_class(__lowerCamelCase , __lowerCamelCase ) a = model_class(__lowerCamelCase ) @jax.jit def model_jitted(__lowerCamelCase : int , __lowerCamelCase : Optional[Any]=None , **__lowerCamelCase : Tuple ): return model(input_ids=__lowerCamelCase , attention_mask=__lowerCamelCase , **__lowerCamelCase ) with self.subTest("JIT Enabled" ): a = model_jitted(**__lowerCamelCase ).to_tuple() with self.subTest("JIT Disabled" ): with jax.disable_jit(): a = model_jitted(**__lowerCamelCase ).to_tuple() self.assertEqual(len(__lowerCamelCase ) , len(__lowerCamelCase ) ) for jitted_output, output in zip(__lowerCamelCase , __lowerCamelCase ): self.assertEqual(jitted_output.shape , output.shape ) def __UpperCAmelCase ( self : Dict , __lowerCamelCase : List[Any] , __lowerCamelCase : Any , __lowerCamelCase : Dict , __lowerCamelCase : Union[str, Any]=1e-5 , __lowerCamelCase : List[str]="outputs" , __lowerCamelCase : Dict=None ) -> Any: # `bigbird_block_sparse_attention` in `FlaxBigBird` returns `attention_probs = None`, while in PyTorch version, # an effort was done to return `attention_probs` (yet to be verified). if name.startswith("outputs.attentions" ): return else: super().check_pt_flax_outputs(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase )
107
'''simple docstring''' # Copyright 2022 The HuggingFace Team and The OpenBMB Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available __lowerCAmelCase = { '''configuration_cpmant''': ['''CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CpmAntConfig'''], '''tokenization_cpmant''': ['''CpmAntTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CpmAntForCausalLM''', '''CpmAntModel''', '''CpmAntPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
89
0
"""simple docstring""" import numpy as np def a__ ( SCREAMING_SNAKE_CASE : np.array ): '''simple docstring''' return (2 / (1 + np.exp(-2 * vector ))) - 1 if __name__ == "__main__": import doctest doctest.testmod()
108
'''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 __magic_name__ ( _UpperCamelCase , unittest.TestCase ): lowerCAmelCase : str = LayoutLMTokenizer lowerCAmelCase : Tuple = LayoutLMTokenizerFast lowerCAmelCase : List[Any] = True lowerCAmelCase : int = True def __lowercase ( self : Dict ): super().setUp() _a : int = [ '[UNK]', '[CLS]', '[SEP]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] _a : List[str] = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file ,'w' ,encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def __lowercase ( self : Dict ,**_UpperCAmelCase : List[str] ): return LayoutLMTokenizer.from_pretrained(self.tmpdirname ,**_UpperCAmelCase ) def __lowercase ( self : Optional[Any] ,_UpperCAmelCase : Tuple ): _a : Optional[int] = 'UNwant\u00E9d,running' _a : List[Any] = 'unwanted, running' return input_text, output_text def __lowercase ( self : Optional[int] ): _a : Optional[Any] = self.tokenizer_class(self.vocab_file ) _a : Optional[Any] = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(_UpperCAmelCase ,['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_UpperCAmelCase ) ,[7, 4, 5, 10, 8, 9] ) def __lowercase ( self : Optional[int] ): pass
89
0
"""simple docstring""" import argparse import torch from transformers import BertForMaskedLM if __name__ == "__main__": A: Union[str, Any] = argparse.ArgumentParser( description=( "Extraction some layers of the full BertForMaskedLM or RObertaForMaskedLM for Transfer Learned" " Distillation" ) ) parser.add_argument("--model_type", default="bert", choices=["bert"]) parser.add_argument("--model_name", default="bert-base-uncased", type=str) parser.add_argument("--dump_checkpoint", default="serialization_dir/tf_bert-base-uncased_0247911.pth", type=str) parser.add_argument("--vocab_transform", action="store_true") A: Union[str, Any] = parser.parse_args() if args.model_type == "bert": A: Dict = BertForMaskedLM.from_pretrained(args.model_name) A: Dict = "bert" else: raise ValueError("args.model_type should be \"bert\".") A: str = model.state_dict() A: str = {} for w in ["word_embeddings", "position_embeddings"]: A: Any = state_dict[f"""{prefix}.embeddings.{w}.weight"""] for w in ["weight", "bias"]: A: Optional[Any] = state_dict[f"""{prefix}.embeddings.LayerNorm.{w}"""] A: int = 0 for teacher_idx in [0, 2, 4, 7, 9, 1_1]: for w in ["weight", "bias"]: A: Optional[int] = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.query.{w}""" ] A: List[str] = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.key.{w}""" ] A: List[Any] = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.self.value.{w}""" ] A: List[Any] = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.output.dense.{w}""" ] A: Dict = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.attention.output.LayerNorm.{w}""" ] A: Optional[Any] = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.intermediate.dense.{w}""" ] A: Optional[int] = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.output.dense.{w}""" ] A: Union[str, Any] = state_dict[ f"""{prefix}.encoder.layer.{teacher_idx}.output.LayerNorm.{w}""" ] std_idx += 1 A: Dict = state_dict["cls.predictions.decoder.weight"] A: Union[str, Any] = state_dict["cls.predictions.bias"] if args.vocab_transform: for w in ["weight", "bias"]: A: List[str] = state_dict[f"""cls.predictions.transform.dense.{w}"""] A: Optional[Any] = state_dict[f"""cls.predictions.transform.LayerNorm.{w}"""] print(f"""N layers selected for distillation: {std_idx}""") print(f"""Number of params transferred for distillation: {len(compressed_sd.keys())}""") print(f"""Save transferred checkpoint to {args.dump_checkpoint}.""") torch.save(compressed_sd, args.dump_checkpoint)
109
'''simple docstring''' import copy from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { '''microsoft/conditional-detr-resnet-50''': ( '''https://huggingface.co/microsoft/conditional-detr-resnet-50/resolve/main/config.json''' ), } class __magic_name__ ( _UpperCamelCase ): lowerCAmelCase : Any = 'conditional_detr' lowerCAmelCase : List[str] = ['past_key_values'] lowerCAmelCase : Optional[int] = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : Optional[int] ,_UpperCAmelCase : Optional[int]=True ,_UpperCAmelCase : Union[str, Any]=None ,_UpperCAmelCase : List[Any]=3 ,_UpperCAmelCase : List[Any]=300 ,_UpperCAmelCase : Dict=6 ,_UpperCAmelCase : List[str]=2048 ,_UpperCAmelCase : Optional[int]=8 ,_UpperCAmelCase : List[Any]=6 ,_UpperCAmelCase : Optional[int]=2048 ,_UpperCAmelCase : Dict=8 ,_UpperCAmelCase : int=0.0 ,_UpperCAmelCase : Optional[Any]=0.0 ,_UpperCAmelCase : Optional[Any]=True ,_UpperCAmelCase : str="relu" ,_UpperCAmelCase : Tuple=256 ,_UpperCAmelCase : Optional[int]=0.1 ,_UpperCAmelCase : str=0.0 ,_UpperCAmelCase : Optional[int]=0.0 ,_UpperCAmelCase : Union[str, Any]=0.02 ,_UpperCAmelCase : List[str]=1.0 ,_UpperCAmelCase : Any=False ,_UpperCAmelCase : int="sine" ,_UpperCAmelCase : List[str]="resnet50" ,_UpperCAmelCase : Optional[int]=True ,_UpperCAmelCase : str=False ,_UpperCAmelCase : str=2 ,_UpperCAmelCase : int=5 ,_UpperCAmelCase : Optional[int]=2 ,_UpperCAmelCase : str=1 ,_UpperCAmelCase : Union[str, Any]=1 ,_UpperCAmelCase : List[str]=2 ,_UpperCAmelCase : Union[str, Any]=5 ,_UpperCAmelCase : List[Any]=2 ,_UpperCAmelCase : Optional[int]=0.25 ,**_UpperCAmelCase : Tuple ,): if backbone_config is not None and use_timm_backbone: raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.' ) if not use_timm_backbone: if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) _a : Optional[Any] = CONFIG_MAPPING['resnet'](out_features=['stage4'] ) elif isinstance(_UpperCAmelCase ,_UpperCAmelCase ): _a : str = backbone_config.get('model_type' ) _a : Union[str, Any] = CONFIG_MAPPING[backbone_model_type] _a : List[Any] = config_class.from_dict(_UpperCAmelCase ) _a : Tuple = use_timm_backbone _a : Union[str, Any] = backbone_config _a : List[Any] = num_channels _a : Union[str, Any] = num_queries _a : Optional[Any] = d_model _a : Tuple = encoder_ffn_dim _a : Dict = encoder_layers _a : List[str] = encoder_attention_heads _a : Union[str, Any] = decoder_ffn_dim _a : Optional[int] = decoder_layers _a : int = decoder_attention_heads _a : Optional[int] = dropout _a : Tuple = attention_dropout _a : List[Any] = activation_dropout _a : str = activation_function _a : Optional[Any] = init_std _a : Union[str, Any] = init_xavier_std _a : List[Any] = encoder_layerdrop _a : List[Any] = decoder_layerdrop _a : Dict = encoder_layers _a : List[Any] = auxiliary_loss _a : Optional[int] = position_embedding_type _a : List[Any] = backbone _a : Optional[int] = use_pretrained_backbone _a : Optional[int] = dilation # Hungarian matcher _a : Tuple = class_cost _a : str = bbox_cost _a : Any = giou_cost # Loss coefficients _a : Tuple = mask_loss_coefficient _a : Dict = dice_loss_coefficient _a : Tuple = cls_loss_coefficient _a : Any = bbox_loss_coefficient _a : Dict = giou_loss_coefficient _a : Union[str, Any] = focal_alpha super().__init__(is_encoder_decoder=_UpperCAmelCase ,**_UpperCAmelCase ) @property def __lowercase ( self : Dict ): return self.encoder_attention_heads @property def __lowercase ( self : str ): return self.d_model def __lowercase ( self : int ): _a : List[str] = copy.deepcopy(self.__dict__ ) if self.backbone_config is not None: _a : Dict = self.backbone_config.to_dict() _a : Union[str, Any] = self.__class__.model_type return output class __magic_name__ ( _UpperCamelCase ): lowerCAmelCase : str = version.parse('1.11' ) @property def __lowercase ( self : Dict ): return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('pixel_mask', {0: 'batch'}), ] ) @property def __lowercase ( self : Any ): return 1E-5 @property def __lowercase ( self : List[Any] ): return 12
89
0
lowerCAmelCase = [ 999, 800, 799, 600, 599, 500, 400, 399, 377, 355, 333, 311, 288, 266, 244, 222, 200, 199, 177, 155, 133, 111, 88, 66, 44, 22, 0, ] lowerCAmelCase = [ 999, 976, 952, 928, 905, 882, 858, 857, 810, 762, 715, 714, 572, 429, 428, 286, 285, 238, 190, 143, 142, 118, 95, 71, 47, 24, 0, ] lowerCAmelCase = [ 999, 988, 977, 966, 955, 944, 933, 922, 911, 900, 899, 879, 859, 840, 820, 800, 799, 766, 733, 700, 699, 650, 600, 599, 500, 499, 400, 399, 350, 300, 299, 266, 233, 200, 199, 179, 159, 140, 120, 100, 99, 88, 77, 66, 55, 44, 33, 22, 11, 0, ] lowerCAmelCase = [ 999, 995, 992, 989, 985, 981, 978, 975, 971, 967, 964, 961, 957, 956, 951, 947, 942, 937, 933, 928, 923, 919, 914, 913, 908, 903, 897, 892, 887, 881, 876, 871, 870, 864, 858, 852, 846, 840, 834, 828, 827, 820, 813, 806, 799, 792, 785, 784, 777, 770, 763, 756, 749, 742, 741, 733, 724, 716, 707, 699, 698, 688, 677, 666, 656, 655, 645, 634, 623, 613, 612, 598, 584, 570, 569, 555, 541, 527, 526, 505, 484, 483, 462, 440, 439, 396, 395, 352, 351, 308, 307, 264, 263, 220, 219, 176, 132, 88, 44, 0, ] lowerCAmelCase = [ 999, 997, 995, 992, 990, 988, 986, 984, 981, 979, 977, 975, 972, 970, 968, 966, 964, 961, 959, 957, 956, 954, 951, 949, 946, 944, 941, 939, 936, 934, 931, 929, 926, 924, 921, 919, 916, 914, 913, 910, 907, 905, 902, 899, 896, 893, 891, 888, 885, 882, 879, 877, 874, 871, 870, 867, 864, 861, 858, 855, 852, 849, 846, 843, 840, 837, 834, 831, 828, 827, 824, 821, 817, 814, 811, 808, 804, 801, 798, 795, 791, 788, 785, 784, 780, 777, 774, 770, 766, 763, 760, 756, 752, 749, 746, 742, 741, 737, 733, 730, 726, 722, 718, 714, 710, 707, 703, 699, 698, 694, 690, 685, 681, 677, 673, 669, 664, 660, 656, 655, 650, 646, 641, 636, 632, 627, 622, 618, 613, 612, 607, 602, 596, 591, 586, 580, 575, 570, 569, 563, 557, 551, 545, 539, 533, 527, 526, 519, 512, 505, 498, 491, 484, 483, 474, 466, 457, 449, 440, 439, 428, 418, 407, 396, 395, 381, 366, 352, 351, 330, 308, 307, 286, 264, 263, 242, 220, 219, 176, 175, 132, 131, 88, 44, 0, ] lowerCAmelCase = [ 999, 991, 982, 974, 966, 958, 950, 941, 933, 925, 916, 908, 900, 899, 874, 850, 825, 800, 799, 700, 600, 500, 400, 300, 200, 100, 0, ] lowerCAmelCase = [ 999, 992, 985, 978, 971, 964, 957, 949, 942, 935, 928, 921, 914, 907, 900, 899, 879, 859, 840, 820, 800, 799, 766, 733, 700, 699, 650, 600, 599, 500, 499, 400, 399, 300, 299, 200, 199, 100, 99, 0, ] lowerCAmelCase = [ 999, 996, 992, 989, 985, 982, 979, 975, 972, 968, 965, 961, 958, 955, 951, 948, 944, 941, 938, 934, 931, 927, 924, 920, 917, 914, 910, 907, 903, 900, 899, 891, 884, 876, 869, 861, 853, 846, 838, 830, 823, 815, 808, 800, 799, 788, 777, 766, 755, 744, 733, 722, 711, 700, 699, 688, 677, 666, 655, 644, 633, 622, 611, 600, 599, 585, 571, 557, 542, 528, 514, 500, 499, 485, 471, 457, 442, 428, 414, 400, 399, 379, 359, 340, 320, 300, 299, 279, 259, 240, 220, 200, 199, 166, 133, 100, 99, 66, 33, 0, ]
110
'''simple docstring''' import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __magic_name__ : def __init__( self : List[str] ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : List[str]=13 ,_UpperCAmelCase : Any=32 ,_UpperCAmelCase : Union[str, Any]=3 ,_UpperCAmelCase : Optional[int]=4 ,_UpperCAmelCase : Optional[Any]=[10, 20, 30, 40] ,_UpperCAmelCase : Tuple=[2, 2, 3, 2] ,_UpperCAmelCase : Optional[int]=True ,_UpperCAmelCase : Optional[int]=True ,_UpperCAmelCase : Union[str, Any]=37 ,_UpperCAmelCase : Optional[int]="gelu" ,_UpperCAmelCase : Optional[Any]=10 ,_UpperCAmelCase : Tuple=0.02 ,_UpperCAmelCase : Any=["stage2", "stage3", "stage4"] ,_UpperCAmelCase : Any=[2, 3, 4] ,_UpperCAmelCase : Tuple=None ,): _a : Optional[Any] = parent _a : List[Any] = batch_size _a : str = image_size _a : Union[str, Any] = num_channels _a : List[Any] = num_stages _a : Dict = hidden_sizes _a : int = depths _a : Tuple = is_training _a : List[str] = use_labels _a : Dict = intermediate_size _a : int = hidden_act _a : int = num_labels _a : Any = initializer_range _a : Tuple = out_features _a : int = out_indices _a : List[Any] = scope def __lowercase ( self : Dict ): _a : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _a : Union[str, Any] = None if self.use_labels: _a : Tuple = ids_tensor([self.batch_size] ,self.num_labels ) _a : str = self.get_config() return config, pixel_values, labels def __lowercase ( self : Any ): return ConvNextVaConfig( num_channels=self.num_channels ,hidden_sizes=self.hidden_sizes ,depths=self.depths ,num_stages=self.num_stages ,hidden_act=self.hidden_act ,is_decoder=_UpperCAmelCase ,initializer_range=self.initializer_range ,out_features=self.out_features ,out_indices=self.out_indices ,num_labels=self.num_labels ,) def __lowercase ( self : Tuple ,_UpperCAmelCase : Any ,_UpperCAmelCase : Any ,_UpperCAmelCase : Optional[Any] ): _a : Optional[Any] = ConvNextVaModel(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : Any = model(_UpperCAmelCase ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape ,(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) ,) def __lowercase ( self : Tuple ,_UpperCAmelCase : Union[str, Any] ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : int ): _a : List[Any] = ConvNextVaForImageClassification(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : List[str] = model(_UpperCAmelCase ,labels=_UpperCAmelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def __lowercase ( self : str ,_UpperCAmelCase : List[Any] ,_UpperCAmelCase : str ,_UpperCAmelCase : Optional[Any] ): _a : Optional[int] = ConvNextVaBackbone(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : Dict = model(_UpperCAmelCase ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) ,len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) ,[self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) ,len(config.out_features ) ) self.parent.assertListEqual(model.channels ,config.hidden_sizes[1:] ) # verify backbone works with out_features=None _a : Tuple = None _a : List[Any] = ConvNextVaBackbone(config=_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() _a : List[str] = model(_UpperCAmelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) ,1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) ,[self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) ,1 ) self.parent.assertListEqual(model.channels ,[config.hidden_sizes[-1]] ) def __lowercase ( self : Optional[Any] ): _a : Any = self.prepare_config_and_inputs() _a , _a , _a : Union[str, Any] = config_and_inputs _a : Any = {'pixel_values': pixel_values} return config, inputs_dict def __lowercase ( self : str ): _a : Tuple = self.prepare_config_and_inputs() _a , _a , _a : Tuple = config_and_inputs _a : List[Any] = {'pixel_values': pixel_values, 'labels': labels} return config, inputs_dict @require_torch class __magic_name__ ( _UpperCamelCase , _UpperCamelCase , unittest.TestCase ): lowerCAmelCase : str = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) lowerCAmelCase : str = ( {'feature-extraction': ConvNextVaModel, 'image-classification': ConvNextVaForImageClassification} if is_torch_available() else {} ) lowerCAmelCase : int = False lowerCAmelCase : str = False lowerCAmelCase : Optional[Any] = False lowerCAmelCase : List[str] = False lowerCAmelCase : Optional[int] = False def __lowercase ( self : List[Any] ): _a : str = ConvNextVaModelTester(self ) _a : Tuple = ConfigTester(self ,config_class=_UpperCAmelCase ,has_text_modality=_UpperCAmelCase ,hidden_size=37 ) def __lowercase ( self : Optional[Any] ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __lowercase ( self : str ): return @unittest.skip(reason='ConvNextV2 does not use inputs_embeds' ) def __lowercase ( self : List[Any] ): pass @unittest.skip(reason='ConvNextV2 does not support input and output embeddings' ) def __lowercase ( self : Optional[int] ): pass @unittest.skip(reason='ConvNextV2 does not use feedforward chunking' ) def __lowercase ( self : Any ): pass def __lowercase ( self : List[str] ): if not self.model_tester.is_training: return for model_class in self.all_model_classes: _a , _a : List[Any] = self.model_tester.prepare_config_and_inputs_with_labels() _a : Any = True if model_class.__name__ in [ *get_values(_UpperCAmelCase ), *get_values(_UpperCAmelCase ), ]: continue _a : Optional[Any] = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.train() _a : str = self._prepare_for_class(_UpperCAmelCase ,_UpperCAmelCase ,return_labels=_UpperCAmelCase ) _a : Optional[int] = model(**_UpperCAmelCase ).loss loss.backward() def __lowercase ( self : str ): if not self.model_tester.is_training: return for model_class in self.all_model_classes: _a , _a : Optional[Any] = self.model_tester.prepare_config_and_inputs_with_labels() _a : Optional[int] = False _a : Tuple = True if ( model_class.__name__ in [*get_values(_UpperCAmelCase ), *get_values(_UpperCAmelCase )] or not model_class.supports_gradient_checkpointing ): continue _a : Tuple = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.gradient_checkpointing_enable() model.train() _a : Any = self._prepare_for_class(_UpperCAmelCase ,_UpperCAmelCase ,return_labels=_UpperCAmelCase ) _a : List[Any] = model(**_UpperCAmelCase ).loss loss.backward() def __lowercase ( self : List[Any] ): _a , _a : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : int = model_class(_UpperCAmelCase ) _a : Optional[Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _a : Dict = [*signature.parameters.keys()] _a : int = ['pixel_values'] self.assertListEqual(arg_names[:1] ,_UpperCAmelCase ) def __lowercase ( self : int ): _a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_UpperCAmelCase ) def __lowercase ( self : Any ): def check_hidden_states_output(_UpperCAmelCase : List[Any] ,_UpperCAmelCase : Tuple ,_UpperCAmelCase : Dict ): _a : Union[str, Any] = model_class(_UpperCAmelCase ) model.to(_UpperCAmelCase ) model.eval() with torch.no_grad(): _a : List[Any] = model(**self._prepare_for_class(_UpperCAmelCase ,_UpperCAmelCase ) ) _a : Any = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _a : str = self.model_tester.num_stages self.assertEqual(len(_UpperCAmelCase ) ,expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) ,[self.model_tester.image_size // 4, self.model_tester.image_size // 4] ,) _a , _a : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _a : int = True check_hidden_states_output(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _a : Optional[Any] = True check_hidden_states_output(_UpperCAmelCase ,_UpperCAmelCase ,_UpperCAmelCase ) def __lowercase ( self : List[Any] ): _a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase ) @slow def __lowercase ( self : int ): for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a : Any = ConvNextVaModel.from_pretrained(_UpperCAmelCase ) self.assertIsNotNone(_UpperCAmelCase ) def __lowerCamelCase ( ) -> List[Any]: _a : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class __magic_name__ ( unittest.TestCase ): @cached_property def __lowercase ( self : Optional[Any] ): return AutoImageProcessor.from_pretrained('facebook/convnextv2-tiny-1k-224' ) if is_vision_available() else None @slow def __lowercase ( self : Any ): _a : List[str] = ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224' ).to(_UpperCAmelCase ) _a : Optional[int] = self.default_image_processor _a : str = prepare_img() _a : str = preprocessor(images=_UpperCAmelCase ,return_tensors='pt' ).to(_UpperCAmelCase ) # forward pass with torch.no_grad(): _a : Dict = model(**_UpperCAmelCase ) # verify the logits _a : Optional[Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape ,_UpperCAmelCase ) _a : Optional[Any] = torch.tensor([0.99_96, 0.19_66, -0.43_86] ).to(_UpperCAmelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,_UpperCAmelCase ,atol=1E-4 ) )
89
0
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING a_ = logging.get_logger(__name__) a_ = { 'salesforce/blip2-opt-2.7b': 'https://huggingface.co/salesforce/blip2-opt-2.7b/resolve/main/config.json', } class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): snake_case_ = 'blip_2_vision_model' def __init__( self : List[Any] , __lowercase : List[Any]=14_08 , __lowercase : Optional[int]=61_44 , __lowercase : List[str]=39 , __lowercase : Dict=16 , __lowercase : Optional[Any]=2_24 , __lowercase : Any=14 , __lowercase : Optional[int]="gelu" , __lowercase : Optional[int]=0.00001 , __lowercase : Tuple=0.0 , __lowercase : Union[str, Any]=1e-10 , __lowercase : Any=True , **__lowercase : Dict , ) -> Optional[Any]: super().__init__(**_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : int =hidden_size SCREAMING_SNAKE_CASE__ : List[str] =intermediate_size SCREAMING_SNAKE_CASE__ : List[Any] =num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[int] =num_attention_heads SCREAMING_SNAKE_CASE__ : Tuple =patch_size SCREAMING_SNAKE_CASE__ : List[str] =image_size SCREAMING_SNAKE_CASE__ : int =initializer_range SCREAMING_SNAKE_CASE__ : Union[str, Any] =attention_dropout SCREAMING_SNAKE_CASE__ : Union[str, Any] =layer_norm_eps SCREAMING_SNAKE_CASE__ : List[str] =hidden_act SCREAMING_SNAKE_CASE__ : Any =qkv_bias @classmethod def __magic_name__ ( cls : Tuple , __lowercase : Union[str, os.PathLike] , **__lowercase : Any ) -> Optional[int]: cls._set_token_in_kwargs(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : List[Any] =cls.get_config_dict(_UpperCAmelCase , **_UpperCAmelCase ) # get the vision config dict if we are loading from Blip2Config if config_dict.get('''model_type''' ) == "blip-2": SCREAMING_SNAKE_CASE__ : Union[str, Any] =config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F"You are using a model of type {config_dict['model_type']} to instantiate a model of type " F"{cls.model_type}. This is not supported for all configurations of models and can yield errors." ) return cls.from_dict(_UpperCAmelCase , **_UpperCAmelCase ) class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): snake_case_ = 'blip_2_qformer' def __init__( self : int , __lowercase : List[str]=3_05_22 , __lowercase : Dict=7_68 , __lowercase : Tuple=12 , __lowercase : Any=12 , __lowercase : int=30_72 , __lowercase : str="gelu" , __lowercase : Dict=0.1 , __lowercase : str=0.1 , __lowercase : int=5_12 , __lowercase : Union[str, Any]=0.02 , __lowercase : List[str]=1e-12 , __lowercase : int=0 , __lowercase : Optional[int]="absolute" , __lowercase : List[str]=2 , __lowercase : Any=14_08 , **__lowercase : Optional[int] , ) -> List[Any]: super().__init__(pad_token_id=_UpperCAmelCase , **_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Any =vocab_size SCREAMING_SNAKE_CASE__ : Optional[int] =hidden_size SCREAMING_SNAKE_CASE__ : Dict =num_hidden_layers SCREAMING_SNAKE_CASE__ : Dict =num_attention_heads SCREAMING_SNAKE_CASE__ : str =hidden_act SCREAMING_SNAKE_CASE__ : Any =intermediate_size SCREAMING_SNAKE_CASE__ : Dict =hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str =attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] =max_position_embeddings SCREAMING_SNAKE_CASE__ : Tuple =initializer_range SCREAMING_SNAKE_CASE__ : Optional[int] =layer_norm_eps SCREAMING_SNAKE_CASE__ : int =position_embedding_type SCREAMING_SNAKE_CASE__ : Optional[Any] =cross_attention_frequency SCREAMING_SNAKE_CASE__ : List[str] =encoder_hidden_size @classmethod def __magic_name__ ( cls : Dict , __lowercase : Union[str, os.PathLike] , **__lowercase : Union[str, Any] ) -> Union[str, Any]: cls._set_token_in_kwargs(_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : str =cls.get_config_dict(_UpperCAmelCase , **_UpperCAmelCase ) # get the qformer config dict if we are loading from Blip2Config if config_dict.get('''model_type''' ) == "blip-2": SCREAMING_SNAKE_CASE__ : Any =config_dict['qformer_config'] if "model_type" in config_dict and hasattr(cls , '''model_type''' ) and config_dict["model_type"] != cls.model_type: logger.warning( F"You are using a model of type {config_dict['model_type']} to instantiate a model of type " F"{cls.model_type}. This is not supported for all configurations of models and can yield errors." ) return cls.from_dict(_UpperCAmelCase , **_UpperCAmelCase ) class __SCREAMING_SNAKE_CASE ( _UpperCamelCase ): snake_case_ = 'blip-2' snake_case_ = True def __init__( self : Any , __lowercase : Union[str, Any]=None , __lowercase : Tuple=None , __lowercase : Dict=None , __lowercase : int=32 , **__lowercase : str ) -> List[Any]: super().__init__(**_UpperCAmelCase ) if vision_config is None: SCREAMING_SNAKE_CASE__ : str ={} logger.info('''vision_config is None. initializing the Blip2VisionConfig with default values.''' ) if qformer_config is None: SCREAMING_SNAKE_CASE__ : List[str] ={} logger.info('''qformer_config is None. Initializing the Blip2QFormerConfig with default values.''' ) if text_config is None: SCREAMING_SNAKE_CASE__ : List[Any] ={} logger.info('''text_config is None. Initializing the text config with default values (`OPTConfig`).''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] =BlipaVisionConfig(**_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Tuple =BlipaQFormerConfig(**_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Optional[int] =text_config['model_type'] if 'model_type' in text_config else 'opt' SCREAMING_SNAKE_CASE__ : Any =CONFIG_MAPPING[text_model_type](**_UpperCAmelCase ) SCREAMING_SNAKE_CASE__ : Dict =self.text_config.tie_word_embeddings SCREAMING_SNAKE_CASE__ : Union[str, Any] =self.text_config.is_encoder_decoder SCREAMING_SNAKE_CASE__ : int =num_query_tokens SCREAMING_SNAKE_CASE__ : str =self.vision_config.hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] =self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES SCREAMING_SNAKE_CASE__ : Optional[int] =1.0 SCREAMING_SNAKE_CASE__ : str =0.02 @classmethod def __magic_name__ ( cls : str , __lowercase : BlipaVisionConfig , __lowercase : BlipaQFormerConfig , __lowercase : PretrainedConfig , **__lowercase : List[Any] , ) -> List[Any]: return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **_UpperCAmelCase , ) def __magic_name__ ( self : int ) -> List[Any]: SCREAMING_SNAKE_CASE__ : Dict =copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ : Any =self.vision_config.to_dict() SCREAMING_SNAKE_CASE__ : Optional[int] =self.qformer_config.to_dict() SCREAMING_SNAKE_CASE__ : Dict =self.text_config.to_dict() SCREAMING_SNAKE_CASE__ : Optional[Any] =self.__class__.model_type return output
152
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCAmelCase = { '''configuration_lilt''': ['''LILT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''LiltConfig'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''LILT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''LiltForQuestionAnswering''', '''LiltForSequenceClassification''', '''LiltForTokenClassification''', '''LiltModel''', '''LiltPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_lilt import LILT_PRETRAINED_CONFIG_ARCHIVE_MAP, LiltConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_lilt import ( LILT_PRETRAINED_MODEL_ARCHIVE_LIST, LiltForQuestionAnswering, LiltForSequenceClassification, LiltForTokenClassification, LiltModel, LiltPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
89
0
import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTImageProcessor, ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase__ : Optional[int] = logging.get_logger(__name__) def UpperCamelCase__ ( A__ , A__=False ) -> List[Any]: snake_case__ : List[str] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((F"""blocks.{i}.norm1.weight""", F"""vit.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((F"""blocks.{i}.norm1.bias""", F"""vit.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append((F"""blocks.{i}.attn.proj.weight""", F"""vit.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append((F"""blocks.{i}.attn.proj.bias""", F"""vit.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((F"""blocks.{i}.norm2.weight""", F"""vit.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((F"""blocks.{i}.norm2.bias""", F"""vit.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append((F"""blocks.{i}.mlp.fc1.weight""", F"""vit.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((F"""blocks.{i}.mlp.fc1.bias""", F"""vit.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((F"""blocks.{i}.mlp.fc2.weight""", F"""vit.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((F"""blocks.{i}.mlp.fc2.bias""", F"""vit.encoder.layer.{i}.output.dense.bias""") ) # projection layer + position embeddings rename_keys.extend( [ ('cls_token', 'vit.embeddings.cls_token'), ('patch_embed.proj.weight', 'vit.embeddings.patch_embeddings.projection.weight'), ('patch_embed.proj.bias', 'vit.embeddings.patch_embeddings.projection.bias'), ('pos_embed', 'vit.embeddings.position_embeddings'), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ('norm.weight', 'layernorm.weight'), ('norm.bias', 'layernorm.bias'), ('pre_logits.fc.weight', 'pooler.dense.weight'), ('pre_logits.fc.bias', 'pooler.dense.bias'), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" snake_case__ : Dict = [(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 UpperCamelCase__ ( A__ , A__ , A__=False ) -> Dict: for i in range(config.num_hidden_layers ): if base_model: snake_case__ : Union[str, Any] = '' else: snake_case__ : Optional[Any] = 'vit.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) snake_case__ : Dict = state_dict.pop(F"""blocks.{i}.attn.qkv.weight""" ) snake_case__ : Tuple = state_dict.pop(F"""blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict snake_case__ : Union[str, Any] = in_proj_weight[ : config.hidden_size, : ] snake_case__ : Union[str, Any] = in_proj_bias[: config.hidden_size] snake_case__ : Union[str, Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] snake_case__ : int = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] snake_case__ : Dict = in_proj_weight[ -config.hidden_size :, : ] snake_case__ : Optional[Any] = in_proj_bias[-config.hidden_size :] def UpperCamelCase__ ( A__ ) -> Optional[Any]: snake_case__ : int = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(lowerCAmelCase_ , lowerCAmelCase_ ) def UpperCamelCase__ ( A__ , A__ , A__ ) -> List[str]: snake_case__ : Tuple = dct.pop(lowerCAmelCase_ ) snake_case__ : Optional[Any] = val def UpperCamelCase__ ( ) -> Any: snake_case__ : Tuple = 'http://images.cocodataset.org/val2017/000000039769.jpg' snake_case__ : List[Any] = Image.open(requests.get(lowerCAmelCase_ , stream=lowerCAmelCase_ ).raw ) return im @torch.no_grad() def UpperCamelCase__ ( A__ , A__ ) -> Any: snake_case__ : Any = ViTConfig() snake_case__ : List[Any] = False # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size if vit_name[-5:] == "in21k": snake_case__ : List[Any] = True snake_case__ : str = int(vit_name[-12:-10] ) snake_case__ : Any = int(vit_name[-9:-6] ) else: snake_case__ : str = 1000 snake_case__ : List[Any] = 'huggingface/label-files' snake_case__ : int = 'imagenet-1k-id2label.json' snake_case__ : Any = json.load(open(hf_hub_download(lowerCAmelCase_ , lowerCAmelCase_ , repo_type='dataset' ) , 'r' ) ) snake_case__ : Optional[int] = {int(lowerCAmelCase_ ): v for k, v in idalabel.items()} snake_case__ : str = idalabel snake_case__ : int = {v: k for k, v in idalabel.items()} snake_case__ : List[Any] = int(vit_name[-6:-4] ) snake_case__ : Optional[int] = int(vit_name[-3:] ) # size of the architecture if "deit" in vit_name: if vit_name[9:].startswith('tiny' ): snake_case__ : Optional[int] = 192 snake_case__ : Dict = 768 snake_case__ : List[Any] = 12 snake_case__ : Union[str, Any] = 3 elif vit_name[9:].startswith('small' ): snake_case__ : Optional[Any] = 384 snake_case__ : str = 1536 snake_case__ : str = 12 snake_case__ : Union[str, Any] = 6 else: pass else: if vit_name[4:].startswith('small' ): snake_case__ : int = 768 snake_case__ : str = 2304 snake_case__ : List[str] = 8 snake_case__ : Optional[int] = 8 elif vit_name[4:].startswith('base' ): pass elif vit_name[4:].startswith('large' ): snake_case__ : Any = 1024 snake_case__ : Optional[int] = 4096 snake_case__ : Union[str, Any] = 24 snake_case__ : Any = 16 elif vit_name[4:].startswith('huge' ): snake_case__ : str = 1280 snake_case__ : Dict = 5120 snake_case__ : str = 32 snake_case__ : str = 16 # load original model from timm snake_case__ : Union[str, Any] = timm.create_model(lowerCAmelCase_ , pretrained=lowerCAmelCase_ ) timm_model.eval() # load state_dict of original model, remove and rename some keys snake_case__ : str = timm_model.state_dict() if base_model: remove_classification_head_(lowerCAmelCase_ ) snake_case__ : Optional[Any] = create_rename_keys(lowerCAmelCase_ , lowerCAmelCase_ ) for src, dest in rename_keys: rename_key(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) read_in_q_k_v(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) # load HuggingFace model if vit_name[-5:] == "in21k": snake_case__ : Union[str, Any] = ViTModel(lowerCAmelCase_ ).eval() else: snake_case__ : str = ViTForImageClassification(lowerCAmelCase_ ).eval() model.load_state_dict(lowerCAmelCase_ ) # Check outputs on an image, prepared by ViTImageProcessor/DeiTImageProcessor if "deit" in vit_name: snake_case__ : Any = DeiTImageProcessor(size=config.image_size ) else: snake_case__ : Union[str, Any] = ViTImageProcessor(size=config.image_size ) snake_case__ : List[str] = image_processor(images=prepare_img() , return_tensors='pt' ) snake_case__ : str = encoding['pixel_values'] snake_case__ : List[str] = model(lowerCAmelCase_ ) if base_model: snake_case__ : Optional[Any] = timm_model.forward_features(lowerCAmelCase_ ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(lowerCAmelCase_ , outputs.pooler_output , atol=1e-3 ) else: snake_case__ : Union[str, Any] = timm_model(lowerCAmelCase_ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(lowerCAmelCase_ , outputs.logits , atol=1e-3 ) Path(lowerCAmelCase_ ).mkdir(exist_ok=lowerCAmelCase_ ) print(F"""Saving model {vit_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(lowerCAmelCase_ ) print(F"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(lowerCAmelCase_ ) if __name__ == "__main__": lowerCAmelCase__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--vit_name''', default='''vit_base_patch16_224''', type=str, help='''Name of the ViT timm model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model directory.''' ) lowerCAmelCase__ : Union[str, Any] = parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path)
143
'''simple docstring''' import math def __lowerCamelCase ( lowerCAmelCase_ ) -> bool: _a : Optional[int] = math.loga(math.sqrt(4 * positive_integer + 1 ) / 2 + 1 / 2 ) return exponent == int(lowerCAmelCase_ ) def __lowerCamelCase ( lowerCAmelCase_ = 1 / 12345 ) -> int: _a : int = 0 _a : Optional[Any] = 0 _a : int = 3 while True: _a : Tuple = (integer**2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(lowerCAmelCase_ ): _a : Union[str, Any] = int(lowerCAmelCase_ ) total_partitions += 1 if check_partition_perfect(lowerCAmelCase_ ): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return int(lowerCAmelCase_ ) integer += 1 if __name__ == "__main__": print(f"""{solution() = }""")
89
0
def __A ( )-> Tuple: """simple docstring""" for n in range(1 , 1_000_000 ): yield n * (n + 1) // 2 def __A ( __lowerCAmelCase )-> List[Any]: """simple docstring""" _UpperCAmelCase = 1 _UpperCAmelCase = 2 while i * i <= n: _UpperCAmelCase = 0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def __A ( )-> str: """simple docstring""" return next(i for i in triangle_number_generator() if count_divisors(lowerCAmelCase_ ) > 500 ) if __name__ == "__main__": print(solution())
39
'''simple docstring''' import argparse import json import torch from diffusers import DDPMScheduler, LDMPipeline, UNetaDModel, VQModel def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=1 ) -> Dict: if n_shave_prefix_segments >= 0: return ".".join(path.split('.' )[n_shave_prefix_segments:] ) else: return ".".join(path.split('.' )[:n_shave_prefix_segments] ) def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=0 ) -> Tuple: _a : Any = [] for old_item in old_list: _a : Union[str, Any] = old_item.replace('in_layers.0' , 'norm1' ) _a : Optional[int] = new_item.replace('in_layers.2' , 'conv1' ) _a : str = new_item.replace('out_layers.0' , 'norm2' ) _a : List[str] = new_item.replace('out_layers.3' , 'conv2' ) _a : str = new_item.replace('emb_layers.1' , 'time_emb_proj' ) _a : Tuple = new_item.replace('skip_connection' , 'conv_shortcut' ) _a : Any = shave_segments(lowerCAmelCase_ , n_shave_prefix_segments=lowerCAmelCase_ ) mapping.append({'old': old_item, 'new': new_item} ) return mapping def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_=0 ) -> Any: _a : List[str] = [] for old_item in old_list: _a : List[Any] = old_item _a : Optional[int] = new_item.replace('norm.weight' , 'group_norm.weight' ) _a : Optional[Any] = new_item.replace('norm.bias' , 'group_norm.bias' ) _a : Any = new_item.replace('proj_out.weight' , 'proj_attn.weight' ) _a : Optional[Any] = new_item.replace('proj_out.bias' , 'proj_attn.bias' ) _a : Optional[int] = shave_segments(lowerCAmelCase_ , n_shave_prefix_segments=lowerCAmelCase_ ) mapping.append({'old': old_item, 'new': new_item} ) return mapping def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=None , lowerCAmelCase_=None , lowerCAmelCase_=None ) -> Any: assert isinstance(lowerCAmelCase_ , lowerCAmelCase_ ), "Paths should be a list of dicts containing 'old' and 'new' keys." # Splits the attention layers into three variables. if attention_paths_to_split is not None: for path, path_map in attention_paths_to_split.items(): _a : Optional[Any] = old_checkpoint[path] _a : Optional[Any] = old_tensor.shape[0] // 3 _a : Any = (-1, channels) if len(old_tensor.shape ) == 3 else (-1) _a : int = old_tensor.shape[0] // config['num_head_channels'] // 3 _a : str = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:] ) _a , _a , _a : Tuple = old_tensor.split(channels // num_heads , dim=1 ) _a : Dict = query.reshape(lowerCAmelCase_ ) _a : str = key.reshape(lowerCAmelCase_ ) _a : Optional[int] = value.reshape(lowerCAmelCase_ ) for path in paths: _a : Dict = path['new'] # These have already been assigned if attention_paths_to_split is not None and new_path in attention_paths_to_split: continue # Global renaming happens here _a : Any = new_path.replace('middle_block.0' , 'mid_block.resnets.0' ) _a : str = new_path.replace('middle_block.1' , 'mid_block.attentions.0' ) _a : Union[str, Any] = new_path.replace('middle_block.2' , 'mid_block.resnets.1' ) if additional_replacements is not None: for replacement in additional_replacements: _a : int = new_path.replace(replacement['old'] , replacement['new'] ) # proj_attn.weight has to be converted from conv 1D to linear if "proj_attn.weight" in new_path: _a : List[str] = old_checkpoint[path['old']][:, :, 0] else: _a : Dict = old_checkpoint[path['old']] def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> List[Any]: _a : Optional[int] = {} _a : Dict = checkpoint['time_embed.0.weight'] _a : Tuple = checkpoint['time_embed.0.bias'] _a : Union[str, Any] = checkpoint['time_embed.2.weight'] _a : List[str] = checkpoint['time_embed.2.bias'] _a : List[str] = checkpoint['input_blocks.0.0.weight'] _a : Union[str, Any] = checkpoint['input_blocks.0.0.bias'] _a : Optional[int] = checkpoint['out.0.weight'] _a : int = checkpoint['out.0.bias'] _a : List[str] = checkpoint['out.2.weight'] _a : Optional[int] = checkpoint['out.2.bias'] # Retrieves the keys for the input blocks only _a : Optional[int] = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'input_blocks' in layer} ) _a : Dict = { layer_id: [key for key in checkpoint if f"""input_blocks.{layer_id}""" in key] for layer_id in range(lowerCAmelCase_ ) } # Retrieves the keys for the middle blocks only _a : List[Any] = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'middle_block' in layer} ) _a : Union[str, Any] = { layer_id: [key for key in checkpoint if f"""middle_block.{layer_id}""" in key] for layer_id in range(lowerCAmelCase_ ) } # Retrieves the keys for the output blocks only _a : Optional[int] = len({'.'.join(layer.split('.' )[:2] ) for layer in checkpoint if 'output_blocks' in layer} ) _a : str = { layer_id: [key for key in checkpoint if f"""output_blocks.{layer_id}""" in key] for layer_id in range(lowerCAmelCase_ ) } for i in range(1 , lowerCAmelCase_ ): _a : List[Any] = (i - 1) // (config['num_res_blocks'] + 1) _a : Optional[int] = (i - 1) % (config['num_res_blocks'] + 1) _a : Optional[int] = [key for key in input_blocks[i] if f"""input_blocks.{i}.0""" in key] _a : Optional[Any] = [key for key in input_blocks[i] if f"""input_blocks.{i}.1""" in key] if f"""input_blocks.{i}.0.op.weight""" in checkpoint: _a : List[Any] = checkpoint[ f"""input_blocks.{i}.0.op.weight""" ] _a : Union[str, Any] = checkpoint[ f"""input_blocks.{i}.0.op.bias""" ] continue _a : Any = renew_resnet_paths(lowerCAmelCase_ ) _a : List[str] = {'old': f"""input_blocks.{i}.0""", 'new': f"""down_blocks.{block_id}.resnets.{layer_in_block_id}"""} _a : Optional[Any] = {'old': 'resnets.2.op', 'new': 'downsamplers.0.op'} assign_to_checkpoint( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , additional_replacements=[meta_path, resnet_op] , config=lowerCAmelCase_ ) if len(lowerCAmelCase_ ): _a : List[str] = renew_attention_paths(lowerCAmelCase_ ) _a : List[Any] = { 'old': f"""input_blocks.{i}.1""", 'new': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}""", } _a : Optional[Any] = { f"""input_blocks.{i}.1.qkv.bias""": { 'key': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias""", 'query': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias""", 'value': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias""", }, f"""input_blocks.{i}.1.qkv.weight""": { 'key': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight""", 'query': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight""", 'value': f"""down_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight""", }, } assign_to_checkpoint( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , additional_replacements=[meta_path] , attention_paths_to_split=lowerCAmelCase_ , config=lowerCAmelCase_ , ) _a : str = middle_blocks[0] _a : Tuple = middle_blocks[1] _a : Any = middle_blocks[2] _a : List[Any] = renew_resnet_paths(lowerCAmelCase_ ) assign_to_checkpoint(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , config=lowerCAmelCase_ ) _a : Any = renew_resnet_paths(lowerCAmelCase_ ) assign_to_checkpoint(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , config=lowerCAmelCase_ ) _a : int = renew_attention_paths(lowerCAmelCase_ ) _a : int = { 'middle_block.1.qkv.bias': { 'key': 'mid_block.attentions.0.key.bias', 'query': 'mid_block.attentions.0.query.bias', 'value': 'mid_block.attentions.0.value.bias', }, 'middle_block.1.qkv.weight': { 'key': 'mid_block.attentions.0.key.weight', 'query': 'mid_block.attentions.0.query.weight', 'value': 'mid_block.attentions.0.value.weight', }, } assign_to_checkpoint( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , attention_paths_to_split=lowerCAmelCase_ , config=lowerCAmelCase_ ) for i in range(lowerCAmelCase_ ): _a : List[str] = i // (config['num_res_blocks'] + 1) _a : Any = i % (config['num_res_blocks'] + 1) _a : Union[str, Any] = [shave_segments(lowerCAmelCase_ , 2 ) for name in output_blocks[i]] _a : Optional[Any] = {} for layer in output_block_layers: _a , _a : str = layer.split('.' )[0], shave_segments(lowerCAmelCase_ , 1 ) if layer_id in output_block_list: output_block_list[layer_id].append(lowerCAmelCase_ ) else: _a : str = [layer_name] if len(lowerCAmelCase_ ) > 1: _a : str = [key for key in output_blocks[i] if f"""output_blocks.{i}.0""" in key] _a : Optional[Any] = [key for key in output_blocks[i] if f"""output_blocks.{i}.1""" in key] _a : Dict = renew_resnet_paths(lowerCAmelCase_ ) _a : str = renew_resnet_paths(lowerCAmelCase_ ) _a : Optional[int] = {'old': f"""output_blocks.{i}.0""", 'new': f"""up_blocks.{block_id}.resnets.{layer_in_block_id}"""} assign_to_checkpoint(lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , additional_replacements=[meta_path] , config=lowerCAmelCase_ ) if ["conv.weight", "conv.bias"] in output_block_list.values(): _a : List[Any] = list(output_block_list.values() ).index(['conv.weight', 'conv.bias'] ) _a : Tuple = checkpoint[ f"""output_blocks.{i}.{index}.conv.weight""" ] _a : List[str] = checkpoint[ f"""output_blocks.{i}.{index}.conv.bias""" ] # Clear attentions as they have been attributed above. if len(lowerCAmelCase_ ) == 2: _a : Union[str, Any] = [] if len(lowerCAmelCase_ ): _a : Tuple = renew_attention_paths(lowerCAmelCase_ ) _a : str = { 'old': f"""output_blocks.{i}.1""", 'new': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}""", } _a : List[Any] = { f"""output_blocks.{i}.1.qkv.bias""": { 'key': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.key.bias""", 'query': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.query.bias""", 'value': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.value.bias""", }, f"""output_blocks.{i}.1.qkv.weight""": { 'key': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.key.weight""", 'query': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.query.weight""", 'value': f"""up_blocks.{block_id}.attentions.{layer_in_block_id}.value.weight""", }, } assign_to_checkpoint( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , additional_replacements=[meta_path] , attention_paths_to_split=to_split if any('qkv' in key for key in attentions ) else None , config=lowerCAmelCase_ , ) else: _a : List[Any] = renew_resnet_paths(lowerCAmelCase_ , n_shave_prefix_segments=1 ) for path in resnet_0_paths: _a : int = '.'.join(['output_blocks', str(lowerCAmelCase_ ), path['old']] ) _a : Union[str, Any] = '.'.join(['up_blocks', str(lowerCAmelCase_ ), 'resnets', str(lowerCAmelCase_ ), path['new']] ) _a : Union[str, Any] = checkpoint[old_path] return new_checkpoint if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() parser.add_argument( '''--checkpoint_path''', default=None, type=str, required=True, help='''Path to the checkpoint to convert.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the architecture.''', ) parser.add_argument('''--dump_path''', default=None, type=str, required=True, help='''Path to the output model.''') __lowerCAmelCase = parser.parse_args() __lowerCAmelCase = torch.load(args.checkpoint_path) with open(args.config_file) as f: __lowerCAmelCase = json.loads(f.read()) __lowerCAmelCase = convert_ldm_checkpoint(checkpoint, config) if "ldm" in config: del config["ldm"] __lowerCAmelCase = UNetaDModel(**config) model.load_state_dict(converted_checkpoint) try: __lowerCAmelCase = DDPMScheduler.from_config('''/'''.join(args.checkpoint_path.split('''/''')[:-1])) __lowerCAmelCase = VQModel.from_pretrained('''/'''.join(args.checkpoint_path.split('''/''')[:-1])) __lowerCAmelCase = LDMPipeline(unet=model, scheduler=scheduler, vae=vqvae) pipe.save_pretrained(args.dump_path) except: # noqa: E722 model.save_pretrained(args.dump_path)
89
0
import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class A (unittest.TestCase ): '''simple docstring''' @property def a_ ( self : Optional[int] ) -> str: """simple docstring""" torch.manual_seed(0 ) A__ = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("""DownBlock2D""", """AttnDownBlock2D""") , up_block_types=("""AttnUpBlock2D""", """UpBlock2D""") , ) return model def a_ ( self : Optional[int] ) -> int: """simple docstring""" A__ = self.dummy_uncond_unet A__ = KarrasVeScheduler() A__ = KarrasVePipeline(unet=_UpperCAmelCase , scheduler=_UpperCAmelCase ) pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) A__ = torch.manual_seed(0 ) A__ = pipe(num_inference_steps=2 , generator=_UpperCAmelCase , output_type="""numpy""" ).images A__ = torch.manual_seed(0 ) A__ = pipe(num_inference_steps=2 , generator=_UpperCAmelCase , output_type="""numpy""" , return_dict=_UpperCAmelCase )[0] A__ = image[0, -3:, -3:, -1] A__ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) A__ = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class A (unittest.TestCase ): '''simple docstring''' def a_ ( self : List[str] ) -> List[str]: """simple docstring""" A__ = 'google/ncsnpp-celebahq-256' A__ = UNetaDModel.from_pretrained(_UpperCAmelCase ) A__ = KarrasVeScheduler() A__ = KarrasVePipeline(unet=_UpperCAmelCase , scheduler=_UpperCAmelCase ) pipe.to(_UpperCAmelCase ) pipe.set_progress_bar_config(disable=_UpperCAmelCase ) A__ = torch.manual_seed(0 ) A__ = pipe(num_inference_steps=20 , generator=_UpperCAmelCase , output_type="""numpy""" ).images A__ = image[0, -3:, -3:, -1] assert image.shape == (1, 2_56, 2_56, 3) A__ = np.array([0.5_7_8, 0.5_8_1_1, 0.5_9_2_4, 0.5_8_0_9, 0.5_8_7, 0.5_8_8_6, 0.5_8_6_1, 0.5_8_0_2, 0.5_8_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
274
'''simple docstring''' import datetime import platform import subprocess from typing import Optional, Tuple, Union import numpy as np def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> np.array: _a : Optional[int] = f"""{sampling_rate}""" _a : Any = '1' _a : Optional[int] = 'f32le' _a : Any = [ 'ffmpeg', '-i', 'pipe:0', '-ac', ac, '-ar', ar, '-f', format_for_conversion, '-hide_banner', '-loglevel', 'quiet', 'pipe:1', ] try: with subprocess.Popen(lowerCAmelCase_ , stdin=subprocess.PIPE , stdout=subprocess.PIPE ) as ffmpeg_process: _a : int = ffmpeg_process.communicate(lowerCAmelCase_ ) except FileNotFoundError as error: raise ValueError('ffmpeg was not found but is required to load audio files from filename' ) from error _a : int = output_stream[0] _a : List[str] = np.frombuffer(lowerCAmelCase_ , np.floataa ) if audio.shape[0] == 0: raise ValueError('Malformed soundfile' ) return audio def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = "f32le" , ) -> Union[str, Any]: _a : List[str] = f"""{sampling_rate}""" _a : List[str] = '1' if format_for_conversion == "s16le": _a : List[Any] = 2 elif format_for_conversion == "f32le": _a : Dict = 4 else: raise ValueError(f"""Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`""" ) _a : Any = platform.system() if system == "Linux": _a : Union[str, Any] = 'alsa' _a : Union[str, Any] = 'default' elif system == "Darwin": _a : Any = 'avfoundation' _a : Optional[int] = ':0' elif system == "Windows": _a : str = 'dshow' _a : Tuple = 'default' _a : str = [ 'ffmpeg', '-f', format_, '-i', input_, '-ac', ac, '-ar', ar, '-f', format_for_conversion, '-fflags', 'nobuffer', '-hide_banner', '-loglevel', 'quiet', 'pipe:1', ] _a : Any = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample _a : Union[str, Any] = _ffmpeg_stream(lowerCAmelCase_ , lowerCAmelCase_ ) for item in iterator: yield item def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = None , lowerCAmelCase_ = None , lowerCAmelCase_ = "f32le" , ) -> str: if stream_chunk_s is not None: _a : str = stream_chunk_s else: _a : List[str] = chunk_length_s _a : int = ffmpeg_microphone(lowerCAmelCase_ , lowerCAmelCase_ , format_for_conversion=lowerCAmelCase_ ) if format_for_conversion == "s16le": _a : Optional[Any] = np.intaa _a : List[Any] = 2 elif format_for_conversion == "f32le": _a : Tuple = np.floataa _a : Any = 4 else: raise ValueError(f"""Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`""" ) if stride_length_s is None: _a : str = chunk_length_s / 6 _a : Any = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample if isinstance(lowerCAmelCase_ , (int, float) ): _a : List[str] = [stride_length_s, stride_length_s] _a : str = int(round(sampling_rate * stride_length_s[0] ) ) * size_of_sample _a : List[str] = int(round(sampling_rate * stride_length_s[1] ) ) * size_of_sample _a : Any = datetime.datetime.now() _a : Dict = datetime.timedelta(seconds=lowerCAmelCase_ ) for item in chunk_bytes_iter(lowerCAmelCase_ , lowerCAmelCase_ , stride=(stride_left, stride_right) , stream=lowerCAmelCase_ ): # Put everything back in numpy scale _a : List[Any] = np.frombuffer(item['raw'] , dtype=lowerCAmelCase_ ) _a : List[str] = ( item['stride'][0] // size_of_sample, item['stride'][1] // size_of_sample, ) _a : Union[str, Any] = sampling_rate audio_time += delta if datetime.datetime.now() > audio_time + 10 * delta: # We're late !! SKIP continue yield item def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ = False ) -> List[Any]: _a : Tuple = B'' _a , _a : str = stride if stride_left + stride_right >= chunk_len: raise ValueError( f"""Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}""" ) _a : Optional[int] = 0 for raw in iterator: acc += raw if stream and len(lowerCAmelCase_ ) < chunk_len: _a : str = (_stride_left, 0) yield {"raw": acc[:chunk_len], "stride": stride, "partial": True} else: while len(lowerCAmelCase_ ) >= chunk_len: # We are flushing the accumulator _a : Union[str, Any] = (_stride_left, stride_right) _a : Dict = {'raw': acc[:chunk_len], 'stride': stride} if stream: _a : List[str] = False yield item _a : int = stride_left _a : List[Any] = acc[chunk_len - stride_left - stride_right :] # Last chunk if len(lowerCAmelCase_ ) > stride_left: _a : str = {'raw': acc, 'stride': (_stride_left, 0)} if stream: _a : str = False yield item def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ ) -> Tuple: _a : Optional[Any] = 2**24 # 16Mo try: with subprocess.Popen(lowerCAmelCase_ , stdout=subprocess.PIPE , bufsize=lowerCAmelCase_ ) as ffmpeg_process: while True: _a : Any = ffmpeg_process.stdout.read(lowerCAmelCase_ ) if raw == b"": break yield raw except FileNotFoundError as error: raise ValueError('ffmpeg was not found but is required to stream audio files from filename' ) from error
89
0
from ..utils import DummyObject, requires_backends class a__ ( metaclass=_UpperCamelCase ): A = ['note_seq'] def __init__( self : Tuple,*_A : List[Any],**_A : str ): """simple docstring""" requires_backends(self,["note_seq"] ) @classmethod def __UpperCamelCase ( cls : List[Any],*_A : str,**_A : Optional[Any] ): """simple docstring""" requires_backends(cls,["note_seq"] ) @classmethod def __UpperCamelCase ( cls : Union[str, Any],*_A : Dict,**_A : Any ): """simple docstring""" requires_backends(cls,["note_seq"] )
18
'''simple docstring''' __lowerCAmelCase = { '''A''': ['''B''', '''C''', '''E'''], '''B''': ['''A''', '''D''', '''E'''], '''C''': ['''A''', '''F''', '''G'''], '''D''': ['''B'''], '''E''': ['''A''', '''B''', '''D'''], '''F''': ['''C'''], '''G''': ['''C'''], } def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> list[str]: _a : List[Any] = set() # keep track of all the paths to be checked _a : Any = [[start]] # return path if start is goal if start == goal: return [start] # keeps looping until all possible paths have been checked while queue: # pop the first path from the queue _a : Tuple = queue.pop(0 ) # get the last node from the path _a : Tuple = path[-1] if node not in explored: _a : Optional[Any] = graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: _a : Any = list(lowerCAmelCase_ ) new_path.append(lowerCAmelCase_ ) queue.append(lowerCAmelCase_ ) # return path if neighbour is goal if neighbour == goal: return new_path # mark node as explored explored.add(lowerCAmelCase_ ) # in case there's no path between the 2 nodes return [] def __lowerCamelCase ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ ) -> int: if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 _a : Optional[int] = [start] _a : Dict = set(lowerCAmelCase_ ) # Keep tab on distances from `start` node. _a : Dict = {start: 0, target: -1} while queue: _a : List[str] = queue.pop(0 ) if node == target: _a : Any = ( dist[node] if dist[target] == -1 else min(dist[target] , dist[node] ) ) for adjacent in graph[node]: if adjacent not in visited: visited.add(lowerCAmelCase_ ) queue.append(lowerCAmelCase_ ) _a : Any = dist[node] + 1 return dist[target] if __name__ == "__main__": print(bfs_shortest_path(demo_graph, '''G''', '''D''')) # returns ['G', 'C', 'A', 'B', 'D'] print(bfs_shortest_path_distance(demo_graph, '''G''', '''D''')) # returns 4
89
0
lowercase__ : List[Any] = ''' # 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 ''' lowercase__ : List[str] = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}] lowercase__ : List[Any] = { '''{processor_class}''': '''FakeProcessorClass''', '''{model_class}''': '''FakeModelClass''', '''{object_class}''': '''FakeObjectClass''', }
338
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available __lowerCAmelCase = {'''configuration_swin''': ['''SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''SwinConfig''', '''SwinOnnxConfig''']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''SWIN_PRETRAINED_MODEL_ARCHIVE_LIST''', '''SwinForImageClassification''', '''SwinForMaskedImageModeling''', '''SwinModel''', '''SwinPreTrainedModel''', '''SwinBackbone''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCAmelCase = [ '''TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST''', '''TFSwinForImageClassification''', '''TFSwinForMaskedImageModeling''', '''TFSwinModel''', '''TFSwinPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_swin import SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinConfig, SwinOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swin import ( SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, SwinBackbone, SwinForImageClassification, SwinForMaskedImageModeling, SwinModel, SwinPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_swin import ( TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, TFSwinForImageClassification, TFSwinForMaskedImageModeling, TFSwinModel, TFSwinPreTrainedModel, ) else: import sys __lowerCAmelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
89
0
"""simple docstring""" def _lowercase ( __snake_case ) -> Any: __lowerCAmelCase : List[str] = [], [] while len(lowerCAmelCase_ ) > 1: __lowerCAmelCase : Tuple = min(lowerCAmelCase_ ), max(lowerCAmelCase_ ) start.append(lowerCAmelCase_ ) end.append(lowerCAmelCase_ ) collection.remove(lowerCAmelCase_ ) collection.remove(lowerCAmelCase_ ) end.reverse() return start + collection + end if __name__ == "__main__": __snake_case : Union[str, Any] = input('Enter numbers separated by a comma:\n').strip() __snake_case : Any = [int(item) for item in user_input.split(',')] print(*merge_sort(unsorted), sep=',')
269
'''simple docstring''' import unittest from transformers import BarthezTokenizer, BarthezTokenizerFast, BatchEncoding from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers @require_sentencepiece @slow # see https://github.com/huggingface/transformers/issues/11457 class __magic_name__ ( _UpperCamelCase , unittest.TestCase ): lowerCAmelCase : Optional[int] = BarthezTokenizer lowerCAmelCase : int = BarthezTokenizerFast lowerCAmelCase : Dict = True lowerCAmelCase : str = True def __lowercase ( self : List[Any] ): super().setUp() _a : List[Any] = BarthezTokenizerFast.from_pretrained('moussaKam/mbarthez' ) tokenizer.save_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname ,legacy_format=_UpperCAmelCase ) _a : Union[str, Any] = tokenizer def __lowercase ( self : Tuple ): _a : Optional[Any] = '<pad>' _a : List[Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_UpperCAmelCase ) ,_UpperCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_UpperCAmelCase ) ,_UpperCAmelCase ) def __lowercase ( self : str ): _a : Any = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] ,'<s>' ) self.assertEqual(vocab_keys[1] ,'<pad>' ) self.assertEqual(vocab_keys[-1] ,'<mask>' ) self.assertEqual(len(_UpperCAmelCase ) ,101122 ) def __lowercase ( self : Dict ): self.assertEqual(self.get_tokenizer().vocab_size ,101122 ) @require_torch def __lowercase ( self : Dict ): _a : Any = ['A long paragraph for summarization.', 'Another paragraph for summarization.'] _a : Dict = [0, 57, 3018, 70307, 91, 2] _a : Dict = self.tokenizer( _UpperCAmelCase ,max_length=len(_UpperCAmelCase ) ,padding=_UpperCAmelCase ,truncation=_UpperCAmelCase ,return_tensors='pt' ) self.assertIsInstance(_UpperCAmelCase ,_UpperCAmelCase ) self.assertEqual((2, 6) ,batch.input_ids.shape ) self.assertEqual((2, 6) ,batch.attention_mask.shape ) _a : Tuple = batch.input_ids.tolist()[0] self.assertListEqual(_UpperCAmelCase ,_UpperCAmelCase ) def __lowercase ( self : Optional[Any] ): if not self.test_rust_tokenizer: return _a : str = self.get_tokenizer() _a : List[str] = self.get_rust_tokenizer() _a : Dict = 'I was born in 92000, and this is falsé.' _a : List[Any] = tokenizer.tokenize(_UpperCAmelCase ) _a : Tuple = rust_tokenizer.tokenize(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase ,_UpperCAmelCase ) _a : Optional[Any] = tokenizer.encode(_UpperCAmelCase ,add_special_tokens=_UpperCAmelCase ) _a : Optional[int] = rust_tokenizer.encode(_UpperCAmelCase ,add_special_tokens=_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase ,_UpperCAmelCase ) _a : Union[str, Any] = self.get_rust_tokenizer() _a : Any = tokenizer.encode(_UpperCAmelCase ) _a : Optional[int] = rust_tokenizer.encode(_UpperCAmelCase ) self.assertListEqual(_UpperCAmelCase ,_UpperCAmelCase ) @slow def __lowercase ( self : Optional[int] ): # fmt: off _a : Optional[int] = {'input_ids': [[0, 490, 14328, 4507, 354, 47, 43669, 95, 25, 78117, 20215, 19779, 190, 22, 400, 4, 35343, 80310, 603, 86, 24937, 105, 33438, 94762, 196, 39642, 7, 15, 15933, 173, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 10534, 87, 25, 66, 3358, 196, 55289, 8, 82961, 81, 2204, 75203, 7, 15, 763, 12956, 216, 178, 14328, 9595, 1377, 69693, 7, 448, 71021, 196, 18106, 1437, 13974, 108, 9083, 4, 49315, 7, 39, 86, 1326, 2793, 46333, 4, 448, 196, 74588, 7, 49315, 7, 39, 21, 822, 38470, 74, 21, 66723, 62480, 8, 22050, 5, 2]], '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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # moussaKam/mbarthez is a french model. So we also use french texts. _a : Optional[Any] = [ 'Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ' 'utilisé principalement dans le domaine du traitement automatique des langues (TAL).', 'À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ' 'pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ' 'telles que la traduction et la synthèse de texte.', ] self.tokenizer_integration_test_util( expected_encoding=_UpperCAmelCase ,model_name='moussaKam/mbarthez' ,revision='c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6' ,sequences=_UpperCAmelCase ,)
89
0
def A_ ( _lowerCAmelCase = 400_0000 ) -> int: UpperCamelCase : Optional[Any] = [0, 1] UpperCamelCase : str = 0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1] ) if fib[i + 2] > n: break i += 1 UpperCamelCase : List[Any] = 0 for j in range(len(lowerCAmelCase_ ) - 1 ): if fib[j] % 2 == 0: total += fib[j] return total if __name__ == "__main__": print(f"""{solution() = }""")
52
'''simple docstring''' import subprocess import sys from transformers import BertConfig, BertModel, BertTokenizer, pipeline from transformers.testing_utils import TestCasePlus, require_torch class __magic_name__ ( _UpperCamelCase ): @require_torch def __lowercase ( self : Tuple ): # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched _a : Optional[int] = '\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n ' _a : List[str] = '\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n ' _a : Tuple = '\nimport socket\ndef offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn\'t access internet")\nsocket.socket = offline_socket\n ' # Force fetching the files so that we can use the cache _a : List[Any] = 'hf-internal-testing/tiny-random-bert' BertConfig.from_pretrained(_UpperCAmelCase ) BertModel.from_pretrained(_UpperCAmelCase ) BertTokenizer.from_pretrained(_UpperCAmelCase ) pipeline(task='fill-mask' ,model=_UpperCAmelCase ) # baseline - just load from_pretrained with normal network _a : Optional[int] = [sys.executable, '-c', '\n'.join([load, run, mock] )] # should succeed _a : Tuple = self.get_env() # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files _a : int = '1' _a : List[Any] = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) @require_torch def __lowercase ( self : Any ): # python one-liner segments # this must be loaded before socket.socket is monkey-patched _a : Dict = '\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n ' _a : Optional[int] = '\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n ' _a : Optional[Any] = '\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet")\nsocket.socket = offline_socket\n ' # Force fetching the files so that we can use the cache _a : int = 'hf-internal-testing/tiny-random-bert' BertConfig.from_pretrained(_UpperCAmelCase ) BertModel.from_pretrained(_UpperCAmelCase ) BertTokenizer.from_pretrained(_UpperCAmelCase ) pipeline(task='fill-mask' ,model=_UpperCAmelCase ) # baseline - just load from_pretrained with normal network _a : Optional[int] = [sys.executable, '-c', '\n'.join([load, run, mock] )] # should succeed _a : str = self.get_env() _a : Optional[Any] = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) @require_torch def __lowercase ( self : List[str] ): # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched _a : Union[str, Any] = '\nfrom transformers import BertConfig, BertModel, BertTokenizer\n ' _a : Optional[Any] = '\nmname = "hf-internal-testing/tiny-random-bert-sharded"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nprint("success")\n ' _a : str = '\nimport socket\ndef offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled")\nsocket.socket = offline_socket\n ' # baseline - just load from_pretrained with normal network _a : Optional[Any] = [sys.executable, '-c', '\n'.join([load, run] )] # should succeed _a : Dict = self.get_env() _a : int = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) # next emulate no network _a : List[Any] = [sys.executable, '-c', '\n'.join([load, mock, run] )] # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this. # env["TRANSFORMERS_OFFLINE"] = "0" # result = subprocess.run(cmd, env=env, check=False, capture_output=True) # self.assertEqual(result.returncode, 1, result.stderr) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files _a : int = '1' _a : Any = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) @require_torch def __lowercase ( self : int ): _a : Optional[Any] = '\nfrom transformers import pipeline\n ' _a : str = '\nmname = "hf-internal-testing/tiny-random-bert"\npipe = pipeline(model=mname)\n ' _a : List[str] = '\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled")\nsocket.socket = offline_socket\n ' _a : List[Any] = self.get_env() _a : Dict = '1' _a : Dict = [sys.executable, '-c', '\n'.join([load, mock, run] )] _a : str = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,1 ,result.stderr ) self.assertIn( 'You cannot infer task automatically within `pipeline` when using offline mode' ,result.stderr.decode().replace('\n' ,'' ) ,) @require_torch def __lowercase ( self : int ): _a : Optional[int] = '\nfrom transformers import AutoModel\n ' _a : List[Any] = '\nmname = "hf-internal-testing/test_dynamic_model"\nAutoModel.from_pretrained(mname, trust_remote_code=True)\nprint("success")\n ' # baseline - just load from_pretrained with normal network _a : Union[str, Any] = [sys.executable, '-c', '\n'.join([load, run] )] # should succeed _a : Tuple = self.get_env() _a : List[str] = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() ) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files _a : Optional[Any] = '1' _a : Any = subprocess.run(_UpperCAmelCase ,env=_UpperCAmelCase ,check=_UpperCAmelCase ,capture_output=_UpperCAmelCase ) self.assertEqual(result.returncode ,0 ,result.stderr ) self.assertIn('success' ,result.stdout.decode() )
89
0
import json import os import torch from diffusers import UNetaDModel os.makedirs('''hub/hopper-medium-v2/unet/hor32''', exist_ok=True) os.makedirs('''hub/hopper-medium-v2/unet/hor128''', exist_ok=True) os.makedirs('''hub/hopper-medium-v2/value_function''', exist_ok=True) def __SCREAMING_SNAKE_CASE ( __UpperCamelCase : str ) -> Optional[int]: """simple docstring""" if hor == 1_28: SCREAMING_SNAKE_CASE__ = ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D') SCREAMING_SNAKE_CASE__ = (32, 1_28, 2_56) SCREAMING_SNAKE_CASE__ = ('UpResnetBlock1D', 'UpResnetBlock1D') elif hor == 32: SCREAMING_SNAKE_CASE__ = ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D') SCREAMING_SNAKE_CASE__ = (32, 64, 1_28, 2_56) SCREAMING_SNAKE_CASE__ = ('UpResnetBlock1D', 'UpResnetBlock1D', 'UpResnetBlock1D') SCREAMING_SNAKE_CASE__ = torch.load(f"""/Users/bglickenhaus/Documents/diffuser/temporal_unet-hopper-mediumv2-hor{hor}.torch""" ) SCREAMING_SNAKE_CASE__ = model.state_dict() SCREAMING_SNAKE_CASE__ = { 'down_block_types': down_block_types, 'block_out_channels': block_out_channels, 'up_block_types': up_block_types, 'layers_per_block': 1, 'use_timestep_embedding': True, 'out_block_type': 'OutConv1DBlock', 'norm_num_groups': 8, 'downsample_each_block': False, 'in_channels': 14, 'out_channels': 14, 'extra_in_channels': 0, 'time_embedding_type': 'positional', 'flip_sin_to_cos': False, 'freq_shift': 1, 'sample_size': 6_55_36, 'mid_block_type': 'MidResTemporalBlock1D', 'act_fn': 'mish', } SCREAMING_SNAKE_CASE__ = UNetaDModel(**lowerCAmelCase_ ) print(f"""length of state dict: {len(state_dict.keys() )}""" ) print(f"""length of value function dict: {len(hf_value_function.state_dict().keys() )}""" ) SCREAMING_SNAKE_CASE__ = dict(zip(model.state_dict().keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): SCREAMING_SNAKE_CASE__ = state_dict.pop(lowerCAmelCase_ ) hf_value_function.load_state_dict(lowerCAmelCase_ ) torch.save(hf_value_function.state_dict() , f"""hub/hopper-medium-v2/unet/hor{hor}/diffusion_pytorch_model.bin""" ) with open(f"""hub/hopper-medium-v2/unet/hor{hor}/config.json""" , """w""" ) as f: json.dump(lowerCAmelCase_ , lowerCAmelCase_ ) def __SCREAMING_SNAKE_CASE ( ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ = { 'in_channels': 14, 'down_block_types': ('DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D', 'DownResnetBlock1D'), 'up_block_types': (), 'out_block_type': 'ValueFunction', 'mid_block_type': 'ValueFunctionMidBlock1D', 'block_out_channels': (32, 64, 1_28, 2_56), 'layers_per_block': 1, 'downsample_each_block': True, 'sample_size': 6_55_36, 'out_channels': 14, 'extra_in_channels': 0, 'time_embedding_type': 'positional', 'use_timestep_embedding': True, 'flip_sin_to_cos': False, 'freq_shift': 1, 'norm_num_groups': 8, 'act_fn': 'mish', } SCREAMING_SNAKE_CASE__ = torch.load("""/Users/bglickenhaus/Documents/diffuser/value_function-hopper-mediumv2-hor32.torch""" ) SCREAMING_SNAKE_CASE__ = model SCREAMING_SNAKE_CASE__ = UNetaDModel(**lowerCAmelCase_ ) print(f"""length of state dict: {len(state_dict.keys() )}""" ) print(f"""length of value function dict: {len(hf_value_function.state_dict().keys() )}""" ) SCREAMING_SNAKE_CASE__ = dict(zip(state_dict.keys() , hf_value_function.state_dict().keys() ) ) for k, v in mapping.items(): SCREAMING_SNAKE_CASE__ = state_dict.pop(lowerCAmelCase_ ) hf_value_function.load_state_dict(lowerCAmelCase_ ) torch.save(hf_value_function.state_dict() , """hub/hopper-medium-v2/value_function/diffusion_pytorch_model.bin""" ) with open("""hub/hopper-medium-v2/value_function/config.json""" , """w""" ) as f: json.dump(lowerCAmelCase_ , lowerCAmelCase_ ) if __name__ == "__main__": unet(32) # unet(128) value_function()
219
'''simple docstring''' def __lowerCamelCase ( ) -> Tuple: for n in range(1 , 1000000 ): yield n * (n + 1) // 2 def __lowerCamelCase ( lowerCAmelCase_ ) -> List[Any]: _a : Any = 1 _a : Tuple = 2 while i * i <= n: _a : Tuple = 0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count def __lowerCamelCase ( ) -> str: return next(i for i in triangle_number_generator() if count_divisors(lowerCAmelCase_ ) > 500 ) if __name__ == "__main__": print(solution())
89
0
"""simple docstring""" def lowercase__ ( _UpperCAmelCase ) -> str: '''simple docstring''' lowercase : Optional[Any] = '' for ch in key: if ch == " " or ch not in key_no_dups and ch.isalpha(): key_no_dups += ch return key_no_dups def lowercase__ ( _UpperCAmelCase ) -> dict[str, str]: '''simple docstring''' lowercase : List[str] = [chr(i + 65 ) for i in range(26 )] # Remove duplicate characters from key lowercase : int = remove_duplicates(key.upper() ) lowercase : str = len(lowerCAmelCase_ ) # First fill cipher with key characters lowercase : Dict = {alphabet[i]: char for i, char in enumerate(lowerCAmelCase_ )} # Then map remaining characters in alphabet to # the alphabet from the beginning for i in range(len(lowerCAmelCase_ ) , 26 ): lowercase : Optional[int] = alphabet[i - offset] # Ensure we are not mapping letters to letters previously mapped while char in key: offset -= 1 lowercase : Tuple = alphabet[i - offset] lowercase : Optional[Any] = char return cipher_alphabet def lowercase__ ( _UpperCAmelCase , _UpperCAmelCase ) -> str: '''simple docstring''' return "".join(cipher_map.get(lowerCAmelCase_ , lowerCAmelCase_ ) for ch in message.upper() ) def lowercase__ ( _UpperCAmelCase , _UpperCAmelCase ) -> str: '''simple docstring''' lowercase : Dict = {v: k for k, v in cipher_map.items()} return "".join(rev_cipher_map.get(lowerCAmelCase_ , lowerCAmelCase_ ) for ch in message.upper() ) def lowercase__ ( ) -> None: '''simple docstring''' lowercase : Optional[int] = input('Enter message to encode or decode: ' ).strip() lowercase : Dict = input('Enter keyword: ' ).strip() lowercase : Optional[int] = input('Encipher or decipher? E/D:' ).strip()[0].lower() try: lowercase : List[str] = {'e': encipher, 'd': decipher}[option] except KeyError: raise KeyError('invalid input option' ) lowercase : Dict = create_cipher_map(lowerCAmelCase_ ) print(func(lowerCAmelCase_ , lowerCAmelCase_ ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
255
'''simple docstring''' import multiprocessing from typing import TYPE_CHECKING, Optional, Union from .. import Dataset, Features, config from ..formatting import query_table from ..packaged_modules.sql.sql import Sql from ..utils import logging from .abc import AbstractDatasetInputStream if TYPE_CHECKING: import sqlitea import sqlalchemy class __magic_name__ ( _UpperCamelCase ): def __init__( self : Optional[int] ,_UpperCAmelCase : Union[str, "sqlalchemy.sql.Selectable"] ,_UpperCAmelCase : Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] ,_UpperCAmelCase : Optional[Features] = None ,_UpperCAmelCase : str = None ,_UpperCAmelCase : bool = False ,**_UpperCAmelCase : Dict ,): super().__init__(features=_UpperCAmelCase ,cache_dir=_UpperCAmelCase ,keep_in_memory=_UpperCAmelCase ,**_UpperCAmelCase ) _a : Tuple = Sql( cache_dir=_UpperCAmelCase ,features=_UpperCAmelCase ,sql=_UpperCAmelCase ,con=_UpperCAmelCase ,**_UpperCAmelCase ,) def __lowercase ( self : Dict ): _a : Optional[Any] = None _a : Dict = None _a : Dict = None _a : Optional[int] = None self.builder.download_and_prepare( download_config=_UpperCAmelCase ,download_mode=_UpperCAmelCase ,verification_mode=_UpperCAmelCase ,base_path=_UpperCAmelCase ,) # Build dataset for splits _a : List[str] = self.builder.as_dataset( split='train' ,verification_mode=_UpperCAmelCase ,in_memory=self.keep_in_memory ) return dataset class __magic_name__ : def __init__( self : Optional[int] ,_UpperCAmelCase : Dataset ,_UpperCAmelCase : str ,_UpperCAmelCase : Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"] ,_UpperCAmelCase : Optional[int] = None ,_UpperCAmelCase : Optional[int] = None ,**_UpperCAmelCase : Dict ,): if num_proc is not None and num_proc <= 0: raise ValueError(F"""num_proc {num_proc} must be an integer > 0.""" ) _a : Dict = dataset _a : List[Any] = name _a : Tuple = con _a : Union[str, Any] = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE _a : List[Any] = num_proc _a : Tuple = to_sql_kwargs def __lowercase ( self : List[Any] ): _a : Tuple = self.to_sql_kwargs.pop('sql' ,_UpperCAmelCase ) _a : str = self.to_sql_kwargs.pop('con' ,_UpperCAmelCase ) _a : Optional[Any] = self.to_sql_kwargs.pop('index' ,_UpperCAmelCase ) _a : Any = self._write(index=_UpperCAmelCase ,**self.to_sql_kwargs ) return written def __lowercase ( self : Optional[int] ,_UpperCAmelCase : Dict ): _a , _a , _a : Any = args _a : Tuple = {**to_sql_kwargs, 'if_exists': 'append'} if offset > 0 else to_sql_kwargs _a : Dict = query_table( table=self.dataset.data ,key=slice(_UpperCAmelCase ,offset + self.batch_size ) ,indices=self.dataset._indices ,) _a : Tuple = batch.to_pandas() _a : Dict = df.to_sql(self.name ,self.con ,index=_UpperCAmelCase ,**_UpperCAmelCase ) return num_rows or len(_UpperCAmelCase ) def __lowercase ( self : int ,_UpperCAmelCase : Optional[int] ,**_UpperCAmelCase : List[Any] ): _a : Union[str, Any] = 0 if self.num_proc is None or self.num_proc == 1: for offset in logging.tqdm( range(0 ,len(self.dataset ) ,self.batch_size ) ,unit='ba' ,disable=not logging.is_progress_bar_enabled() ,desc='Creating SQL from Arrow format' ,): written += self._batch_sql((offset, index, to_sql_kwargs) ) else: _a , _a : List[Any] = len(self.dataset ), self.batch_size with multiprocessing.Pool(self.num_proc ) as pool: for num_rows in logging.tqdm( pool.imap( self._batch_sql ,[(offset, index, to_sql_kwargs) for offset in range(0 ,_UpperCAmelCase ,_UpperCAmelCase )] ,) ,total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size ,unit='ba' ,disable=not logging.is_progress_bar_enabled() ,desc='Creating SQL from Arrow format' ,): written += num_rows return written
89
0