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
"""simple docstring""" import torch from diffusers import DDIMParallelScheduler from .test_schedulers import SchedulerCommonTest class __A ( _SCREAMING_SNAKE_CASE ): """simple docstring""" __lowerCAmelCase = (DDIMParallelScheduler,) __lowerCAmelCase = (("eta", 0.0), ("num_inference_steps", 50)) def SCREAMING_SNAKE_CASE ( self , **__A ) -> Optional[Any]: a ={ '''num_train_timesteps''': 1000, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', '''clip_sample''': True, } config.update(**__A ) return config def SCREAMING_SNAKE_CASE ( self , **__A ) -> Tuple: a =self.scheduler_classes[0] a =self.get_scheduler_config(**__A ) a =scheduler_class(**__A ) a , a =10, 0.0 a =self.dummy_model() a =self.dummy_sample_deter scheduler.set_timesteps(__A ) for t in scheduler.timesteps: a =model(__A , __A ) a =scheduler.step(__A , __A , __A , __A ).prev_sample return sample def SCREAMING_SNAKE_CASE ( self ) -> str: for timesteps in [100, 500, 1000]: self.check_over_configs(num_train_timesteps=__A ) def SCREAMING_SNAKE_CASE ( self ) -> str: for steps_offset in [0, 1]: self.check_over_configs(steps_offset=__A ) a =self.scheduler_classes[0] a =self.get_scheduler_config(steps_offset=1 ) a =scheduler_class(**__A ) scheduler.set_timesteps(5 ) assert torch.equal(scheduler.timesteps , torch.LongTensor([801, 601, 401, 201, 1] ) ) def SCREAMING_SNAKE_CASE ( self ) -> Any: for beta_start, beta_end in zip([0.0_001, 0.001, 0.01, 0.1] , [0.002, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=__A , beta_end=__A ) def SCREAMING_SNAKE_CASE ( self ) -> str: for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=__A ) def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__A ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: for clip_sample in [True, False]: self.check_over_configs(clip_sample=__A ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: for timestep_spacing in ["trailing", "leading"]: self.check_over_configs(timestep_spacing=__A ) def SCREAMING_SNAKE_CASE ( self ) -> List[str]: for rescale_betas_zero_snr in [True, False]: self.check_over_configs(rescale_betas_zero_snr=__A ) def SCREAMING_SNAKE_CASE ( self ) -> Any: self.check_over_configs(thresholding=__A ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs( thresholding=__A , prediction_type=__A , sample_max_value=__A , ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: for t in [1, 10, 49]: self.check_over_forward(time_step=__A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: for t, num_inference_steps in zip([1, 10, 50] , [10, 50, 500] ): self.check_over_forward(time_step=__A , num_inference_steps=__A ) def SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]: for t, eta in zip([1, 10, 49] , [0.0, 0.5, 1.0] ): self.check_over_forward(time_step=__A , eta=__A ) def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =self.scheduler_classes[0] a =self.get_scheduler_config() a =scheduler_class(**__A ) assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(420 , 400 ) - 0.14_771 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(980 , 960 ) - 0.32_460 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(0 , 0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(487 , 486 ) - 0.00_979 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(999 , 998 ) - 0.02 ) ) < 1E-5 def SCREAMING_SNAKE_CASE ( self ) -> Union[str, Any]: a =self.scheduler_classes[0] a =self.get_scheduler_config() a =scheduler_class(**__A ) a , a =10, 0.0 scheduler.set_timesteps(__A ) a =self.dummy_model() a =self.dummy_sample_deter a =self.dummy_sample_deter + 0.1 a =self.dummy_sample_deter - 0.1 a =samplea.shape[0] a =torch.stack([samplea, samplea, samplea] , dim=0 ) a =torch.arange(__A )[0:3, None].repeat(1 , __A ) a =model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) a =scheduler.batch_step_no_noise(__A , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) , __A ) a =torch.sum(torch.abs(__A ) ) a =torch.mean(torch.abs(__A ) ) assert abs(result_sum.item() - 1_147.7_904 ) < 1E-2 assert abs(result_mean.item() - 0.4_982 ) < 1E-3 def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: a =self.full_loop() a =torch.sum(torch.abs(__A ) ) a =torch.mean(torch.abs(__A ) ) assert abs(result_sum.item() - 172.0_067 ) < 1E-2 assert abs(result_mean.item() - 0.223_967 ) < 1E-3 def SCREAMING_SNAKE_CASE ( self ) -> Dict: a =self.full_loop(prediction_type='''v_prediction''' ) a =torch.sum(torch.abs(__A ) ) a =torch.mean(torch.abs(__A ) ) assert abs(result_sum.item() - 52.5_302 ) < 1E-2 assert abs(result_mean.item() - 0.0_684 ) < 1E-3 def SCREAMING_SNAKE_CASE ( self ) -> Any: # We specify different beta, so that the first alpha is 0.99 a =self.full_loop(set_alpha_to_one=__A , beta_start=0.01 ) a =torch.sum(torch.abs(__A ) ) a =torch.mean(torch.abs(__A ) ) assert abs(result_sum.item() - 149.8_295 ) < 1E-2 assert abs(result_mean.item() - 0.1_951 ) < 1E-3 def SCREAMING_SNAKE_CASE ( self ) -> Optional[int]: # We specify different beta, so that the first alpha is 0.99 a =self.full_loop(set_alpha_to_one=__A , beta_start=0.01 ) a =torch.sum(torch.abs(__A ) ) a =torch.mean(torch.abs(__A ) ) assert abs(result_sum.item() - 149.0_784 ) < 1E-2 assert abs(result_mean.item() - 0.1_941 ) < 1E-3
81
import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available SCREAMING_SNAKE_CASE__ : Optional[int] = logging.getLogger(__name__) @dataclass class lowerCAmelCase__ : a__ : str a__ : List[str] a__ : Optional[List[str]] @dataclass class lowerCAmelCase__ : a__ : List[int] a__ : List[int] a__ : Optional[List[int]] = None a__ : Optional[List[int]] = None class lowerCAmelCase__ ( __lowercase ): a__ : Optional[Any] = """train""" a__ : Optional[int] = """dev""" a__ : Dict = """test""" class lowerCAmelCase__ : @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[Split, str] ) -> List[InputExample]: raise NotImplementedError @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : str ) -> List[str]: raise NotImplementedError @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : List[InputExample] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : List[str]="[CLS]" , SCREAMING_SNAKE_CASE__ : Tuple=1 , SCREAMING_SNAKE_CASE__ : str="[SEP]" , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False , SCREAMING_SNAKE_CASE__ : Tuple=0 , SCREAMING_SNAKE_CASE__ : int=0 , SCREAMING_SNAKE_CASE__ : str=-1_00 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE__ : List[Any]=True , ) -> List[InputFeatures]: __lowerCamelCase = {label: i for i, label in enumerate(SCREAMING_SNAKE_CASE__ )} __lowerCamelCase = [] for ex_index, example in enumerate(SCREAMING_SNAKE_CASE__ ): if ex_index % 1_00_00 == 0: logger.info('''Writing example %d of %d''' , SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = [] __lowerCamelCase = [] for word, label in zip(example.words , example.labels ): __lowerCamelCase = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(SCREAMING_SNAKE_CASE__ ) > 0: tokens.extend(SCREAMING_SNAKE_CASE__ ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(SCREAMING_SNAKE_CASE__ ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. __lowerCamelCase = tokenizer.num_special_tokens_to_add() if len(SCREAMING_SNAKE_CASE__ ) > max_seq_length - special_tokens_count: __lowerCamelCase = tokens[: (max_seq_length - special_tokens_count)] __lowerCamelCase = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] __lowerCamelCase = [sequence_a_segment_id] * len(SCREAMING_SNAKE_CASE__ ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: __lowerCamelCase = [cls_token] + tokens __lowerCamelCase = [pad_token_label_id] + label_ids __lowerCamelCase = [cls_token_segment_id] + segment_ids __lowerCamelCase = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. __lowerCamelCase = [1 if mask_padding_with_zero else 0] * len(SCREAMING_SNAKE_CASE__ ) # Zero-pad up to the sequence length. __lowerCamelCase = max_seq_length - len(SCREAMING_SNAKE_CASE__ ) if pad_on_left: __lowerCamelCase = ([pad_token] * padding_length) + input_ids __lowerCamelCase = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask __lowerCamelCase = ([pad_token_segment_id] * padding_length) + segment_ids __lowerCamelCase = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length if ex_index < 5: logger.info('''*** Example ***''' ) logger.info('''guid: %s''' , example.guid ) logger.info('''tokens: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in tokens] ) ) logger.info('''input_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in input_ids] ) ) logger.info('''input_mask: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in input_mask] ) ) logger.info('''segment_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in segment_ids] ) ) logger.info('''label_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: __lowerCamelCase = None features.append( InputFeatures( input_ids=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , label_ids=SCREAMING_SNAKE_CASE__ ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class lowerCAmelCase__ ( __lowercase ): a__ : List[InputFeatures] a__ : int = nn.CrossEntropyLoss().ignore_index def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : TokenClassificationTask , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False , SCREAMING_SNAKE_CASE__ : Split = Split.train , ) -> Union[str, Any]: # Load data features from cache or dataset file __lowerCamelCase = os.path.join( SCREAMING_SNAKE_CASE__ , '''cached_{}_{}_{}'''.format(mode.value , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE__ ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. __lowerCamelCase = cached_features_file + '''.lock''' with FileLock(SCREAMING_SNAKE_CASE__ ): if os.path.exists(SCREAMING_SNAKE_CASE__ ) and not overwrite_cache: logger.info(f'''Loading features from cached file {cached_features_file}''' ) __lowerCamelCase = torch.load(SCREAMING_SNAKE_CASE__ ) else: logger.info(f'''Creating features from dataset file at {data_dir}''' ) __lowerCamelCase = token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # TODO clean up all this to leverage built-in features of tokenizers __lowerCamelCase = token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f'''Saving features into cached file {cached_features_file}''' ) torch.save(self.features , SCREAMING_SNAKE_CASE__ ) def __len__( self : Dict ) -> str: return len(self.features ) def __getitem__( self : Any , SCREAMING_SNAKE_CASE__ : Dict ) -> InputFeatures: return self.features[i] if is_tf_available(): import tensorflow as tf class lowerCAmelCase__ : a__ : List[InputFeatures] a__ : int = -100 def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : TokenClassificationTask , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Split = Split.train , ) -> List[Any]: __lowerCamelCase = token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # TODO clean up all this to leverage built-in features of tokenizers __lowerCamelCase = token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: __lowerCamelCase = tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa}, tf.intaa) , ( {'''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: __lowerCamelCase = tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa}, tf.intaa) , ( { '''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] ), '''token_type_ids''': tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __A ( self : Union[str, Any] ) -> Union[str, Any]: __lowerCamelCase = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self : List[Any] ) -> Any: return len(self.features ) def __getitem__( self : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> InputFeatures: return self.features[i]
270
0
from dataclasses import dataclass, field from typing import Optional from transformers import AutoConfig, AutoImageProcessor, AutoTokenizer, FlaxVisionEncoderDecoderModel, HfArgumentParser @dataclass class __lowerCAmelCase : __lowerCamelCase = field( metadata={'''help''': '''The output directory where the model will be written.'''} , ) __lowerCamelCase = field( metadata={ '''help''': ( '''The encoder model checkpoint for weights initialization.''' '''Don\'t set if you want to train an encoder model from scratch.''' ) } , ) __lowerCamelCase = field( metadata={ '''help''': ( '''The decoder model checkpoint for weights initialization.''' '''Don\'t set if you want to train a decoder model from scratch.''' ) } , ) __lowerCamelCase = field( default=lowerCamelCase__ , metadata={'''help''': '''Pretrained encoder config name or path if not the same as encoder_model_name'''} ) __lowerCamelCase = field( default=lowerCamelCase__ , metadata={'''help''': '''Pretrained decoder config name or path if not the same as decoder_model_name'''} ) def _UpperCAmelCase ( ): """simple docstring""" _lowerCAmelCase = HfArgumentParser((ModelArguments,) ) ((_lowerCAmelCase) , ) = parser.parse_args_into_dataclasses() # Load pretrained model and tokenizer # Use explicit specified encoder config if model_args.encoder_config_name: _lowerCAmelCase = AutoConfig.from_pretrained(model_args.encoder_config_name ) # Use pretrained encoder model's config else: _lowerCAmelCase = AutoConfig.from_pretrained(model_args.encoder_model_name_or_path ) # Use explicit specified decoder config if model_args.decoder_config_name: _lowerCAmelCase = AutoConfig.from_pretrained(model_args.decoder_config_name ) # Use pretrained decoder model's config else: _lowerCAmelCase = AutoConfig.from_pretrained(model_args.decoder_model_name_or_path ) # necessary for `from_encoder_decoder_pretrained` when `decoder_config` is passed _lowerCAmelCase = True _lowerCAmelCase = True _lowerCAmelCase = FlaxVisionEncoderDecoderModel.from_encoder_decoder_pretrained( encoder_pretrained_model_name_or_path=model_args.encoder_model_name_or_path , decoder_pretrained_model_name_or_path=model_args.decoder_model_name_or_path , encoder_config=snake_case , decoder_config=snake_case , ) # GPT2 only has bos/eos tokens but not decoder_start/pad tokens _lowerCAmelCase = decoder_config.decoder_start_token_id _lowerCAmelCase = decoder_config.pad_token_id if decoder_start_token_id is None: _lowerCAmelCase = decoder_config.bos_token_id if pad_token_id is None: _lowerCAmelCase = decoder_config.eos_token_id # This is necessary to make Flax's generate() work _lowerCAmelCase = decoder_config.eos_token_id _lowerCAmelCase = decoder_start_token_id _lowerCAmelCase = pad_token_id _lowerCAmelCase = AutoImageProcessor.from_pretrained(model_args.encoder_model_name_or_path ) _lowerCAmelCase = AutoTokenizer.from_pretrained(model_args.decoder_model_name_or_path ) _lowerCAmelCase = tokenizer.convert_ids_to_tokens(model.config.pad_token_id ) model.save_pretrained(model_args.output_dir ) image_processor.save_pretrained(model_args.output_dir ) tokenizer.save_pretrained(model_args.output_dir ) if __name__ == "__main__": main()
82
from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class lowerCAmelCase__ ( __lowercase ): def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : NestedDataStructureLike[PathLike] , SCREAMING_SNAKE_CASE__ : Optional[NamedSplit] = None , SCREAMING_SNAKE_CASE__ : Optional[Features] = None , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[int] = None , **SCREAMING_SNAKE_CASE__ : str , ) -> Union[str, Any]: super().__init__( SCREAMING_SNAKE_CASE__ , split=SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ , keep_in_memory=SCREAMING_SNAKE_CASE__ , streaming=SCREAMING_SNAKE_CASE__ , num_proc=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = path_or_paths if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else {self.split: path_or_paths} __lowerCamelCase = Text( cache_dir=SCREAMING_SNAKE_CASE__ , data_files=SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def __A ( self : int ) -> Dict: # Build iterable dataset if self.streaming: __lowerCamelCase = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None self.builder.download_and_prepare( download_config=SCREAMING_SNAKE_CASE__ , download_mode=SCREAMING_SNAKE_CASE__ , verification_mode=SCREAMING_SNAKE_CASE__ , base_path=SCREAMING_SNAKE_CASE__ , num_proc=self.num_proc , ) __lowerCamelCase = self.builder.as_dataset( split=self.split , verification_mode=SCREAMING_SNAKE_CASE__ , in_memory=self.keep_in_memory ) return dataset
270
0
'''simple docstring''' from collections import OrderedDict from typing import List, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging snake_case_ : List[Any] = logging.get_logger(__name__) snake_case_ : Tuple = { 'google/efficientnet-b7': 'https://huggingface.co/google/efficientnet-b7/resolve/main/config.json', } class lowercase__ ( lowercase ): lowercase__ = """efficientnet""" def __init__( self : Optional[Any] ,lowerCamelCase__ : int = 3 ,lowerCamelCase__ : int = 600 ,lowerCamelCase__ : float = 2.0 ,lowerCamelCase__ : float = 3.1 ,lowerCamelCase__ : int = 8 ,lowerCamelCase__ : List[int] = [3, 3, 5, 3, 5, 5, 3] ,lowerCamelCase__ : List[int] = [32, 16, 24, 40, 80, 112, 192] ,lowerCamelCase__ : List[int] = [16, 24, 40, 80, 112, 192, 320] ,lowerCamelCase__ : List[int] = [] ,lowerCamelCase__ : List[int] = [1, 2, 2, 2, 1, 2, 1] ,lowerCamelCase__ : List[int] = [1, 2, 2, 3, 3, 4, 1] ,lowerCamelCase__ : List[int] = [1, 6, 6, 6, 6, 6, 6] ,lowerCamelCase__ : float = 0.2_5 ,lowerCamelCase__ : str = "swish" ,lowerCamelCase__ : int = 2560 ,lowerCamelCase__ : str = "mean" ,lowerCamelCase__ : float = 0.0_2 ,lowerCamelCase__ : float = 0.0_0_1 ,lowerCamelCase__ : float = 0.9_9 ,lowerCamelCase__ : float = 0.5 ,lowerCamelCase__ : float = 0.2 ,**lowerCamelCase__ : List[str] ,): '''simple docstring''' super().__init__(**lowerCamelCase__ ) _UpperCamelCase : Union[str, Any] = num_channels _UpperCamelCase : str = image_size _UpperCamelCase : List[Any] = width_coefficient _UpperCamelCase : Optional[Any] = depth_coefficient _UpperCamelCase : List[str] = depth_divisor _UpperCamelCase : int = kernel_sizes _UpperCamelCase : Tuple = in_channels _UpperCamelCase : Optional[Any] = out_channels _UpperCamelCase : Dict = depthwise_padding _UpperCamelCase : List[Any] = strides _UpperCamelCase : Tuple = num_block_repeats _UpperCamelCase : Optional[int] = expand_ratios _UpperCamelCase : Any = squeeze_expansion_ratio _UpperCamelCase : Any = hidden_act _UpperCamelCase : List[str] = hidden_dim _UpperCamelCase : List[str] = pooling_type _UpperCamelCase : Dict = initializer_range _UpperCamelCase : List[str] = batch_norm_eps _UpperCamelCase : List[str] = batch_norm_momentum _UpperCamelCase : str = dropout_rate _UpperCamelCase : int = drop_connect_rate _UpperCamelCase : List[str] = sum(lowerCamelCase__ ) * 4 class lowercase__ ( lowercase ): lowercase__ = version.parse("""1.11""" ) @property def UpperCamelCase_ ( self : Optional[int] ): '''simple docstring''' return OrderedDict( [ ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) @property def UpperCamelCase_ ( self : str ): '''simple docstring''' return 1E-5
83
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(">=", "4.25.0")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
270
0
"""simple docstring""" import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging __UpperCAmelCase = logging.get_logger(__name__) __UpperCAmelCase = '▁' __UpperCAmelCase = { 'vocab_file': 'vocab.json', 'spm_file': 'sentencepiece.bpe.model', 'tokenizer_config_file': 'tokenizer_config.json', } __UpperCAmelCase = { 'vocab_file': { 'facebook/m2m100_418M': 'https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json', 'facebook/m2m100_1.2B': 'https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json', }, 'spm_file': { 'facebook/m2m100_418M': 'https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model', 'facebook/m2m100_1.2B': 'https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model', }, 'tokenizer_config_file': { 'facebook/m2m100_418M': 'https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json', 'facebook/m2m100_1.2B': 'https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json', }, } __UpperCAmelCase = { 'facebook/m2m100_418M': 10_24, } # fmt: off __UpperCAmelCase = { 'm2m100': ['af', 'am', 'ar', 'ast', 'az', 'ba', 'be', 'bg', 'bn', 'br', 'bs', 'ca', 'ceb', 'cs', 'cy', 'da', 'de', 'el', 'en', 'es', 'et', 'fa', 'ff', 'fi', 'fr', 'fy', 'ga', 'gd', 'gl', 'gu', 'ha', 'he', 'hi', 'hr', 'ht', 'hu', 'hy', 'id', 'ig', 'ilo', 'is', 'it', 'ja', 'jv', 'ka', 'kk', 'km', 'kn', 'ko', 'lb', 'lg', 'ln', 'lo', 'lt', 'lv', 'mg', 'mk', 'ml', 'mn', 'mr', 'ms', 'my', 'ne', 'nl', 'no', 'ns', 'oc', 'or', 'pa', 'pl', 'ps', 'pt', 'ro', 'ru', 'sd', 'si', 'sk', 'sl', 'so', 'sq', 'sr', 'ss', 'su', 'sv', 'sw', 'ta', 'th', 'tl', 'tn', 'tr', 'uk', 'ur', 'uz', 'vi', 'wo', 'xh', 'yi', 'yo', 'zh', 'zu'], 'wmt21': ['en', 'ha', 'is', 'ja', 'cs', 'ru', 'zh', 'de'] } class _SCREAMING_SNAKE_CASE ( A__ ): UpperCAmelCase_ :Dict = VOCAB_FILES_NAMES UpperCAmelCase_ :List[Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES UpperCAmelCase_ :Optional[int] = PRETRAINED_VOCAB_FILES_MAP UpperCAmelCase_ :Tuple = ["input_ids", "attention_mask"] UpperCAmelCase_ :List[int] = [] UpperCAmelCase_ :List[int] = [] def __init__( self , __A , __A , __A=None , __A=None , __A="<s>" , __A="</s>" , __A="</s>" , __A="<pad>" , __A="<unk>" , __A="m2m100" , __A = None , __A=8 , **__A , ) -> None: lowerCAmelCase_ :Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs lowerCAmelCase_ :List[str] = language_codes lowerCAmelCase_ :Dict = FAIRSEQ_LANGUAGE_CODES[language_codes] lowerCAmelCase_ :List[str] = {lang_code: f"""__{lang_code}__""" for lang_code in fairseq_language_code} lowerCAmelCase_ :List[Any] = kwargs.get("""additional_special_tokens""" , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(__A ) for lang_code in fairseq_language_code if self.get_lang_token(__A ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=__A , tgt_lang=__A , bos_token=__A , eos_token=__A , sep_token=__A , unk_token=__A , pad_token=__A , language_codes=__A , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=__A , **__A , ) lowerCAmelCase_ :int = vocab_file lowerCAmelCase_ :Tuple = load_json(__A ) lowerCAmelCase_ :Tuple = {v: k for k, v in self.encoder.items()} lowerCAmelCase_ :List[str] = spm_file lowerCAmelCase_ :Optional[Any] = load_spm(__A , self.sp_model_kwargs ) lowerCAmelCase_ :str = len(self.encoder ) lowerCAmelCase_ :Union[str, Any] = { self.get_lang_token(__A ): self.encoder_size + i for i, lang_code in enumerate(__A ) } lowerCAmelCase_ :List[str] = {lang_code: self.encoder_size + i for i, lang_code in enumerate(__A )} lowerCAmelCase_ :Dict = {v: k for k, v in self.lang_token_to_id.items()} lowerCAmelCase_ :List[str] = src_lang if src_lang is not None else """en""" lowerCAmelCase_ :int = tgt_lang lowerCAmelCase_ :Optional[Any] = self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) lowerCAmelCase_ :Optional[int] = num_madeup_words @property def __lowerCAmelCase ( self ) -> int: return len(self.encoder ) + len(self.lang_token_to_id ) @property def __lowerCAmelCase ( self ) -> str: return self._src_lang @src_lang.setter def __lowerCAmelCase ( self , __A ) -> None: lowerCAmelCase_ :Dict = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def __lowerCAmelCase ( self , __A ) -> List[str]: return self.sp_model.encode(__A , out_type=__A ) def __lowerCAmelCase ( self , __A ) -> Any: if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(__A , self.encoder[self.unk_token] ) def __lowerCAmelCase ( self , __A ) -> str: if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(__A , self.unk_token ) def __lowerCAmelCase ( self , __A ) -> Optional[int]: lowerCAmelCase_ :str = [] lowerCAmelCase_ :int = """""" 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 lowerCAmelCase_ :Dict = [] else: current_sub_tokens.append(__A ) out_string += self.sp_model.decode(__A ) return out_string.strip() def __lowerCAmelCase ( self , __A , __A = None , __A = False ) -> List[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__A , token_ids_a=__A , already_has_special_tokens=__A ) lowerCAmelCase_ :Any = [1] * len(self.prefix_tokens ) lowerCAmelCase_ :Union[str, Any] = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__A )) + suffix_ones return prefix_ones + ([0] * len(__A )) + ([0] * len(__A )) + suffix_ones def __lowerCAmelCase ( self , __A , __A = None ) -> List[int]: 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 __lowerCAmelCase ( self ) -> Dict: lowerCAmelCase_ :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 ) -> Dict: lowerCAmelCase_ :List[Any] = self.__dict__.copy() lowerCAmelCase_ :List[str] = None return state def __setstate__( self , __A ) -> None: lowerCAmelCase_ :List[Any] = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): lowerCAmelCase_ :List[Any] = {} lowerCAmelCase_ :str = load_spm(self.spm_file , self.sp_model_kwargs ) def __lowerCAmelCase ( self , __A , __A = None ) -> Tuple[str]: lowerCAmelCase_ :Optional[Any] = Path(__A ) if not save_dir.is_dir(): raise OSError(f"""{save_directory} should be a directory""" ) lowerCAmelCase_ :Any = save_dir / ( (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""vocab_file"""] ) lowerCAmelCase_ :Tuple = save_dir / ( (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""spm_file"""] ) save_json(self.encoder , __A ) if os.path.abspath(self.spm_file ) != os.path.abspath(__A ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , __A ) elif not os.path.isfile(self.spm_file ): with open(__A , """wb""" ) as fi: lowerCAmelCase_ :Union[str, Any] = self.sp_model.serialized_model_proto() fi.write(__A ) return (str(__A ), str(__A )) def __lowerCAmelCase ( self , __A , __A = "en" , __A = None , __A = "ro" , **__A , ) -> BatchEncoding: lowerCAmelCase_ :Union[str, Any] = src_lang lowerCAmelCase_ :List[Any] = tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(__A , __A , **__A ) def __lowerCAmelCase ( self , __A , __A , __A , **__A ) -> Tuple: if src_lang is None or tgt_lang is None: raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model""" ) lowerCAmelCase_ :Dict = src_lang lowerCAmelCase_ :Optional[int] = self(__A , add_special_tokens=__A , **__A ) lowerCAmelCase_ :Union[str, Any] = self.get_lang_id(__A ) lowerCAmelCase_ :Union[str, Any] = tgt_lang_id return inputs def __lowerCAmelCase ( self ) -> Any: self.set_src_lang_special_tokens(self.src_lang ) def __lowerCAmelCase ( self ) -> Dict: self.set_tgt_lang_special_tokens(self.tgt_lang ) def __lowerCAmelCase ( self , __A ) -> None: lowerCAmelCase_ :str = self.get_lang_token(__A ) lowerCAmelCase_ :Any = self.lang_token_to_id[lang_token] lowerCAmelCase_ :Optional[Any] = [self.cur_lang_id] lowerCAmelCase_ :List[str] = [self.eos_token_id] def __lowerCAmelCase ( self , __A ) -> None: lowerCAmelCase_ :str = self.get_lang_token(__A ) lowerCAmelCase_ :int = self.lang_token_to_id[lang_token] lowerCAmelCase_ :str = [self.cur_lang_id] lowerCAmelCase_ :Union[str, Any] = [self.eos_token_id] def __lowerCAmelCase ( self , __A ) -> str: return self.lang_code_to_token[lang] def __lowerCAmelCase ( self , __A ) -> int: lowerCAmelCase_ :Optional[Any] = self.get_lang_token(__A ) return self.lang_token_to_id[lang_token] def _snake_case ( lowercase__ : str , lowercase__ : Dict[str, Any] ) -> sentencepiece.SentencePieceProcessor: '''simple docstring''' lowerCAmelCase_ :Any = sentencepiece.SentencePieceProcessor(**lowercase__ ) spm.Load(str(lowercase__ ) ) return spm def _snake_case ( lowercase__ : str ) -> Union[Dict, List]: '''simple docstring''' with open(lowercase__ , """r""" ) as f: return json.load(lowercase__ ) def _snake_case ( lowercase__ : Union[str, Any] , lowercase__ : str ) -> None: '''simple docstring''' with open(lowercase__ , """w""" ) as f: json.dump(lowercase__ , lowercase__ , indent=2 )
84
import sacrebleu as scb from packaging import version from sacrebleu import CHRF import datasets SCREAMING_SNAKE_CASE__ : Union[str, Any] = "\\n@inproceedings{popovic-2015-chrf,\n title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",\n month = sep,\n year = \"2015\",\n address = \"Lisbon, Portugal\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W15-3049\",\n doi = \"10.18653/v1/W15-3049\",\n pages = \"392--395\",\n}\n@inproceedings{popovic-2017-chrf,\n title = \"chr{F}++: words helping character n-grams\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Second Conference on Machine Translation\",\n month = sep,\n year = \"2017\",\n address = \"Copenhagen, Denmark\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W17-4770\",\n doi = \"10.18653/v1/W17-4770\",\n pages = \"612--618\",\n}\n@inproceedings{post-2018-call,\n title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n author = \"Post, Matt\",\n booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n month = oct,\n year = \"2018\",\n address = \"Belgium, Brussels\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W18-6319\",\n pages = \"186--191\",\n}\n" SCREAMING_SNAKE_CASE__ : int = "\\nChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,\nand ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation\nthat is already present in sacrebleu.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.\n" SCREAMING_SNAKE_CASE__ : Optional[Any] = "\nProduces ChrF(++) scores for hypotheses given reference translations.\n\nArgs:\n predictions (list of str): The predicted sentences.\n references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.\n char_order (int): Character n-gram order. Defaults to `6`.\n word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.\n beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.\n lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.\n whitespace (bool): If `True`, include whitespaces when extracting character n-grams.\n eps_smoothing (bool): If `True`, applies epsilon smoothing similar\n to reference chrF++.py, NLTK and Moses implementations. If `False`,\n it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.\n\nReturns:\n 'score' (float): The chrF (chrF++) score,\n 'char_order' (int): The character n-gram order,\n 'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,\n 'beta' (int): Determine the importance of recall w.r.t precision\n\nExamples:\n Example 1--a simple example of calculating chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction, references=reference)\n >>> print(results)\n {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}\n\n Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2)\n >>> print(results)\n {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}\n\n Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2,\n ... lowercase=True)\n >>> print(results)\n {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): def __A ( self : Dict ) -> Tuple: if version.parse(scb.__version__ ) < version.parse('''1.4.12''' ): raise ImportWarning( '''To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n''' '''You can install it with `pip install "sacrebleu>=1.4.12"`.''' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/mjpost/sacreBLEU#chrf--chrf''' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Sequence(datasets.Value('''string''' , id='''sequence''' ) , id='''references''' ), } ) , codebase_urls=['''https://github.com/mjpost/sacreBLEU#chrf--chrf'''] , reference_urls=[ '''https://github.com/m-popovic/chrF''', ] , ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int = CHRF.CHAR_ORDER , SCREAMING_SNAKE_CASE__ : int = CHRF.WORD_ORDER , SCREAMING_SNAKE_CASE__ : int = CHRF.BETA , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , ) -> Optional[Any]: __lowerCamelCase = len(references[0] ) if any(len(SCREAMING_SNAKE_CASE__ ) != references_per_prediction for refs in references ): raise ValueError('''Sacrebleu requires the same number of references for each prediction''' ) __lowerCamelCase = [[refs[i] for refs in references] for i in range(SCREAMING_SNAKE_CASE__ )] __lowerCamelCase = CHRF(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = sb_chrf.corpus_score(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return { "score": output.score, "char_order": output.char_order, "word_order": output.word_order, "beta": output.beta, }
270
0
'''simple docstring''' from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class _snake_case : lowerCAmelCase_ : torch.Tensor # [batch_size x 3] lowerCAmelCase_ : torch.Tensor # [batch_size x 3] lowerCAmelCase_ : torch.Tensor # [batch_size x 3] lowerCAmelCase_ : torch.Tensor # [batch_size x 3] lowerCAmelCase_ : int lowerCAmelCase_ : int lowerCAmelCase_ : float lowerCAmelCase_ : float lowerCAmelCase_ : Tuple[int] def lowerCAmelCase__ ( self ) -> int: '''simple docstring''' assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def lowerCAmelCase__ ( self ) -> Any: '''simple docstring''' return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def lowerCAmelCase__ ( self ) -> Dict: '''simple docstring''' return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def lowerCAmelCase__ ( self ) -> torch.Tensor: '''simple docstring''' snake_case_ = torch.arange(self.height * self.width ) snake_case_ = torch.stack( [ pixel_indices % self.width, torch.div(a__ , self.width , rounding_mode="trunc" ), ] , axis=1 , ) return coords @property def lowerCAmelCase__ ( self ) -> Optional[Any]: '''simple docstring''' snake_case_ , *snake_case_ = self.shape snake_case_ = int(np.prod(a__ ) ) snake_case_ = self.get_image_coords() snake_case_ = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) snake_case_ = self.get_camera_rays(a__ ) snake_case_ = rays.view(a__ , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def lowerCAmelCase__ ( self , a__ ) -> torch.Tensor: '''simple docstring''' snake_case_ , *snake_case_ , snake_case_ = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] snake_case_ = coords.view(a__ , -1 , 2 ) snake_case_ = self.resolution() snake_case_ = self.fov() snake_case_ = (flat.float() / (res - 1)) * 2 - 1 snake_case_ = fracs * torch.tan(fov / 2 ) snake_case_ = fracs.view(a__ , -1 , 2 ) snake_case_ = ( self.z.view(a__ , 1 , 3 ) + self.x.view(a__ , 1 , 3 ) * fracs[:, :, :1] + self.y.view(a__ , 1 , 3 ) * fracs[:, :, 1:] ) snake_case_ = directions / directions.norm(dim=-1 , keepdim=a__ ) snake_case_ = torch.stack( [ torch.broadcast_to(self.origin.view(a__ , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(a__ , *a__ , 2 , 3 ) def lowerCAmelCase__ ( self , a__ , a__ ) -> "DifferentiableProjectiveCamera": '''simple docstring''' assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=a__ , height=a__ , x_fov=self.x_fov , y_fov=self.y_fov , ) def UpperCamelCase_( snake_case : int ): '''simple docstring''' snake_case_ = [] snake_case_ = [] snake_case_ = [] snake_case_ = [] for theta in np.linspace(0 , 2 * np.pi , num=2_0 ): snake_case_ = np.array([np.sin(snake_case ), np.cos(snake_case ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) snake_case_ = -z * 4 snake_case_ = np.array([np.cos(snake_case ), -np.sin(snake_case ), 0.0] ) snake_case_ = np.cross(snake_case , snake_case ) origins.append(snake_case ) xs.append(snake_case ) ys.append(snake_case ) zs.append(snake_case ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(snake_case , axis=0 ) ).float() , x=torch.from_numpy(np.stack(snake_case , axis=0 ) ).float() , y=torch.from_numpy(np.stack(snake_case , axis=0 ) ).float() , z=torch.from_numpy(np.stack(snake_case , axis=0 ) ).float() , width=snake_case , height=snake_case , x_fov=0.7 , y_fov=0.7 , shape=(1, len(snake_case )) , )
85
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : List[Any] = { "configuration_resnet": ["RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "ResNetConfig", "ResNetOnnxConfig"] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "ResNetForImageClassification", "ResNetModel", "ResNetPreTrainedModel", "ResNetBackbone", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = [ "TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFResNetForImageClassification", "TFResNetModel", "TFResNetPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ "FlaxResNetForImageClassification", "FlaxResNetModel", "FlaxResNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_resnet import RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ResNetConfig, ResNetOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_resnet import ( RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, ResNetBackbone, ResNetForImageClassification, ResNetModel, ResNetPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_resnet import ( TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFResNetForImageClassification, TFResNetModel, TFResNetPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel, FlaxResNetPreTrainedModel else: import sys SCREAMING_SNAKE_CASE__ : Any = _LazyModule(__name__, globals()["__file__"], _import_structure)
270
0
"""simple docstring""" from __future__ import annotations from collections.abc import Generator def __lowerCAmelCase (): __lowerCAmelCase : dict[int, int] = {} __lowerCAmelCase : List[str] = 2 while True: __lowerCAmelCase : List[Any] = factor_map.pop(_UpperCamelCase , _UpperCamelCase ) if factor: __lowerCAmelCase : Optional[Any] = factor + prime while x in factor_map: x += factor __lowerCAmelCase : str = factor else: __lowerCAmelCase : List[Any] = prime yield prime prime += 1 def __lowerCAmelCase (_UpperCamelCase = 1e1_0 ): __lowerCAmelCase : Dict = sieve() __lowerCAmelCase : Optional[Any] = 1 while True: __lowerCAmelCase : int = next(_UpperCamelCase ) if (2 * prime * n) > limit: return n # Ignore the next prime as the reminder will be 2. next(_UpperCamelCase ) n += 2 if __name__ == "__main__": print(solution())
86
import unittest import numpy as np import requests from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: SCREAMING_SNAKE_CASE__ : str = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any]=7 , SCREAMING_SNAKE_CASE__ : List[str]=3 , SCREAMING_SNAKE_CASE__ : Tuple=18 , SCREAMING_SNAKE_CASE__ : int=30 , SCREAMING_SNAKE_CASE__ : Any=4_00 , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , ) -> Union[str, Any]: __lowerCamelCase = size if size is not None else {'''height''': 20, '''width''': 20} __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = num_channels __lowerCamelCase = image_size __lowerCamelCase = min_resolution __lowerCamelCase = max_resolution __lowerCamelCase = size __lowerCamelCase = do_normalize __lowerCamelCase = do_convert_rgb __lowerCamelCase = [5_12, 10_24, 20_48, 40_96] __lowerCamelCase = patch_size if patch_size is not None else {'''height''': 16, '''width''': 16} def __A ( self : Union[str, Any] ) -> Union[str, Any]: return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def __A ( self : int ) -> Any: __lowerCamelCase = '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg''' __lowerCamelCase = Image.open(requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ ).raw ).convert('''RGB''' ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`.""" , ) @require_torch @require_vision class lowerCAmelCase__ ( __lowercase , unittest.TestCase ): a__ : Dict = PixaStructImageProcessor if is_vision_available() else None def __A ( self : Optional[Any] ) -> List[Any]: __lowerCamelCase = PixaStructImageProcessingTester(self ) @property def __A ( self : Optional[int] ) -> Optional[int]: return self.image_processor_tester.prepare_image_processor_dict() def __A ( self : Tuple ) -> Dict: __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_normalize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_convert_rgb''' ) ) def __A ( self : int ) -> str: __lowerCamelCase = self.image_processor_tester.prepare_dummy_image() __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) __lowerCamelCase = 20_48 __lowerCamelCase = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) ) def __A ( self : Union[str, Any] ) -> Dict: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : Dict ) -> str: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 __lowerCamelCase = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches __lowerCamelCase = '''Hello''' __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ , header_text=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ , header_text=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : List[str] ) -> Any: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : Tuple ) -> List[str]: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`.""" , ) @require_torch @require_vision class lowerCAmelCase__ ( __lowercase , unittest.TestCase ): a__ : Any = PixaStructImageProcessor if is_vision_available() else None def __A ( self : Union[str, Any] ) -> Optional[Any]: __lowerCamelCase = PixaStructImageProcessingTester(self , num_channels=4 ) __lowerCamelCase = 3 @property def __A ( self : List[Any] ) -> Optional[Any]: return self.image_processor_tester.prepare_image_processor_dict() def __A ( self : Union[str, Any] ) -> List[str]: __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_normalize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_convert_rgb''' ) ) def __A ( self : Optional[int] ) -> str: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
270
0
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase = logging.get_logger(__name__) UpperCamelCase = { '''microsoft/cvt-13''': '''https://huggingface.co/microsoft/cvt-13/resolve/main/config.json''', # See all Cvt models at https://huggingface.co/models?filter=cvt } class snake_case_ ( __A ): __A : str = "cvt" def __init__( self : Dict , lowercase_ : int=3 , lowercase_ : Optional[Any]=[7, 3, 3] , lowercase_ : Dict=[4, 2, 2] , lowercase_ : List[Any]=[2, 1, 1] , lowercase_ : Union[str, Any]=[64, 1_92, 3_84] , lowercase_ : Union[str, Any]=[1, 3, 6] , lowercase_ : Optional[Any]=[1, 2, 10] , lowercase_ : Tuple=[4.0, 4.0, 4.0] , lowercase_ : Tuple=[0.0, 0.0, 0.0] , lowercase_ : str=[0.0, 0.0, 0.0] , lowercase_ : Union[str, Any]=[0.0, 0.0, 0.1] , lowercase_ : int=[True, True, True] , lowercase_ : str=[False, False, True] , lowercase_ : Dict=["dw_bn", "dw_bn", "dw_bn"] , lowercase_ : Any=[3, 3, 3] , lowercase_ : Dict=[1, 1, 1] , lowercase_ : Any=[2, 2, 2] , lowercase_ : List[str]=[1, 1, 1] , lowercase_ : Any=[1, 1, 1] , lowercase_ : List[Any]=0.02 , lowercase_ : Optional[int]=1E-12 , **lowercase_ : Any , ) -> List[Any]: super().__init__(**lowercase_ ) lowercase__ : Tuple = num_channels lowercase__ : Optional[Any] = patch_sizes lowercase__ : Optional[int] = patch_stride lowercase__ : Tuple = patch_padding lowercase__ : Dict = embed_dim lowercase__ : str = num_heads lowercase__ : Dict = depth lowercase__ : List[str] = mlp_ratio lowercase__ : Any = attention_drop_rate lowercase__ : Union[str, Any] = drop_rate lowercase__ : Optional[int] = drop_path_rate lowercase__ : Any = qkv_bias lowercase__ : Optional[Any] = cls_token lowercase__ : Optional[Any] = qkv_projection_method lowercase__ : Optional[Any] = kernel_qkv lowercase__ : Optional[int] = padding_kv lowercase__ : Union[str, Any] = stride_kv lowercase__ : str = padding_q lowercase__ : Optional[Any] = stride_q lowercase__ : Tuple = initializer_range lowercase__ : str = layer_norm_eps
87
import shutil import tempfile import unittest from unittest.mock import patch from transformers import ( DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, Trainer, TrainerCallback, TrainingArguments, is_torch_available, ) from transformers.testing_utils import require_torch if is_torch_available(): from transformers.trainer import DEFAULT_CALLBACKS from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel class lowerCAmelCase__ ( __lowercase ): def __init__( self : int ) -> Optional[int]: __lowerCamelCase = [] def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> Tuple: self.events.append('''on_init_end''' ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Any: self.events.append('''on_train_begin''' ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : int ) -> Any: self.events.append('''on_train_end''' ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: self.events.append('''on_epoch_begin''' ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Tuple ) -> Optional[Any]: self.events.append('''on_epoch_end''' ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: self.events.append('''on_step_begin''' ) def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: self.events.append('''on_step_end''' ) def __A ( self : int , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> Union[str, Any]: self.events.append('''on_evaluate''' ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : str ) -> str: self.events.append('''on_predict''' ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Tuple: self.events.append('''on_save''' ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : List[str] ) -> List[str]: self.events.append('''on_log''' ) def __A ( self : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: self.events.append('''on_prediction_step''' ) @require_torch class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Union[str, Any] ) -> Optional[Any]: __lowerCamelCase = tempfile.mkdtemp() def __A ( self : int ) -> List[str]: shutil.rmtree(self.output_dir ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any]=0 , SCREAMING_SNAKE_CASE__ : Any=0 , SCREAMING_SNAKE_CASE__ : List[str]=64 , SCREAMING_SNAKE_CASE__ : Optional[int]=64 , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Optional[int]=False , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Union[str, Any]: # disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure # its set to False since the tests later on depend on its value. __lowerCamelCase = RegressionDataset(length=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionDataset(length=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionModelConfig(a=SCREAMING_SNAKE_CASE__ , b=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionPreTrainedModel(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = TrainingArguments(self.output_dir , disable_tqdm=SCREAMING_SNAKE_CASE__ , report_to=[] , **SCREAMING_SNAKE_CASE__ ) return Trainer( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , train_dataset=SCREAMING_SNAKE_CASE__ , eval_dataset=SCREAMING_SNAKE_CASE__ , callbacks=SCREAMING_SNAKE_CASE__ , ) def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> Optional[int]: self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) ) # Order doesn't matter __lowerCamelCase = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : cb.__name__ if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cb.__class__.__name__ ) __lowerCamelCase = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : cb.__name__ if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cb.__class__.__name__ ) for cba, cba in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(SCREAMING_SNAKE_CASE__ , cba.__class__ ) elif not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(cba.__class__ , SCREAMING_SNAKE_CASE__ ) else: self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: __lowerCamelCase = ['''on_init_end''', '''on_train_begin'''] __lowerCamelCase = 0 __lowerCamelCase = len(trainer.get_eval_dataloader() ) __lowerCamelCase = ['''on_prediction_step'''] * len(trainer.get_eval_dataloader() ) + ['''on_log''', '''on_evaluate'''] for _ in range(trainer.state.num_train_epochs ): expected_events.append('''on_epoch_begin''' ) for _ in range(SCREAMING_SNAKE_CASE__ ): step += 1 expected_events += ["on_step_begin", "on_step_end"] if step % trainer.args.logging_steps == 0: expected_events.append('''on_log''' ) if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0: expected_events += evaluation_events.copy() if step % trainer.args.save_steps == 0: expected_events.append('''on_save''' ) expected_events.append('''on_epoch_end''' ) if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH: expected_events += evaluation_events.copy() expected_events += ["on_log", "on_train_end"] return expected_events def __A ( self : Union[str, Any] ) -> int: __lowerCamelCase = self.get_trainer() __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [ProgressCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # Callbacks passed at init are added to the default callbacks __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] ) expected_callbacks.append(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback __lowerCamelCase = self.get_trainer(disable_tqdm=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [PrinterCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) def __A ( self : List[Any] ) -> str: __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [ProgressCallback] __lowerCamelCase = self.get_trainer() # We can add, pop, or remove by class name trainer.remove_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.remove(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.pop_callback(SCREAMING_SNAKE_CASE__ ) self.assertEqual(cb.__class__ , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) trainer.add_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.insert(0 , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # We can also add, pop, or remove by instance __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.callback_handler.callbacks[0] trainer.remove_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.remove(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.callback_handler.callbacks[0] __lowerCamelCase = trainer.pop_callback(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) trainer.add_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.insert(0 , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] ) -> Any: import warnings # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested warnings.simplefilter(action='''ignore''' , category=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # Independent log/save/eval __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , logging_steps=5 ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , save_steps=5 ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , eval_steps=5 , evaluation_strategy='''steps''' ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , evaluation_strategy='''epoch''' ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # A bit of everything __lowerCamelCase = self.get_trainer( callbacks=[MyTestTrainerCallback] , logging_steps=3 , save_steps=10 , eval_steps=5 , evaluation_strategy='''steps''' , ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # warning should be emitted for duplicated callbacks with patch('''transformers.trainer_callback.logger.warning''' ) as warn_mock: __lowerCamelCase = self.get_trainer( callbacks=[MyTestTrainerCallback, MyTestTrainerCallback] , ) assert str(SCREAMING_SNAKE_CASE__ ) in warn_mock.call_args[0][0]
270
0
import unittest from transformers import MobileBertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertModel, ) class UpperCAmelCase_ : '''simple docstring''' def __init__( self : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : str=13 , UpperCamelCase__ : List[Any]=7 , UpperCamelCase__ : Any=True , UpperCamelCase__ : List[Any]=True , UpperCamelCase__ : Tuple=True , UpperCamelCase__ : Union[str, Any]=True , UpperCamelCase__ : List[Any]=99 , UpperCamelCase__ : List[Any]=64 , UpperCamelCase__ : Optional[Any]=32 , UpperCamelCase__ : Dict=5 , UpperCamelCase__ : str=4 , UpperCamelCase__ : List[str]=37 , UpperCamelCase__ : List[Any]="gelu" , UpperCamelCase__ : str=0.1 , UpperCamelCase__ : List[Any]=0.1 , UpperCamelCase__ : Tuple=512 , UpperCamelCase__ : int=16 , UpperCamelCase__ : Optional[Any]=2 , UpperCamelCase__ : Union[str, Any]=0.02 , UpperCamelCase__ : Optional[int]=3 , UpperCamelCase__ : Any=4 , UpperCamelCase__ : int=None , ) -> List[Any]: """simple docstring""" __magic_name__ = parent __magic_name__ = batch_size __magic_name__ = seq_length __magic_name__ = is_training __magic_name__ = use_input_mask __magic_name__ = use_token_type_ids __magic_name__ = use_labels __magic_name__ = vocab_size __magic_name__ = hidden_size __magic_name__ = embedding_size __magic_name__ = num_hidden_layers __magic_name__ = num_attention_heads __magic_name__ = intermediate_size __magic_name__ = hidden_act __magic_name__ = hidden_dropout_prob __magic_name__ = attention_probs_dropout_prob __magic_name__ = max_position_embeddings __magic_name__ = type_vocab_size __magic_name__ = type_sequence_label_size __magic_name__ = initializer_range __magic_name__ = num_labels __magic_name__ = num_choices __magic_name__ = scope def _lowercase ( self : Union[str, Any] ) -> List[str]: """simple docstring""" __magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __magic_name__ = None if self.use_input_mask: __magic_name__ = random_attention_mask([self.batch_size, self.seq_length] ) __magic_name__ = None if self.use_token_type_ids: __magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __magic_name__ = None __magic_name__ = None __magic_name__ = None if self.use_labels: __magic_name__ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __magic_name__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __magic_name__ = ids_tensor([self.batch_size] , self.num_choices ) __magic_name__ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowercase ( self : Dict ) -> Optional[Any]: """simple docstring""" return MobileBertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , embedding_size=self.embedding_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=UpperCamelCase__ , initializer_range=self.initializer_range , ) def _lowercase ( self : Any , UpperCamelCase__ : Dict , UpperCamelCase__ : int , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : List[str] , UpperCamelCase__ : Any , UpperCamelCase__ : Dict ) -> Optional[Any]: """simple docstring""" __magic_name__ = MobileBertModel(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ ) __magic_name__ = model(UpperCamelCase__ , token_type_ids=UpperCamelCase__ ) __magic_name__ = model(UpperCamelCase__ ) 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 _lowercase ( self : int , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Dict , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : List[Any] ) -> Union[str, Any]: """simple docstring""" __magic_name__ = MobileBertForMaskedLM(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _lowercase ( self : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Tuple , UpperCamelCase__ : List[str] , UpperCamelCase__ : Any , UpperCamelCase__ : Dict , UpperCamelCase__ : int , UpperCamelCase__ : Union[str, Any] ) -> Tuple: """simple docstring""" __magic_name__ = MobileBertForNextSentencePrediction(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 2) ) def _lowercase ( self : List[Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : str , UpperCamelCase__ : str , UpperCamelCase__ : int , UpperCamelCase__ : Tuple , UpperCamelCase__ : Optional[int] ) -> Dict: """simple docstring""" __magic_name__ = MobileBertForPreTraining(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ , next_sentence_label=UpperCamelCase__ , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.seq_relationship_logits.shape , (self.batch_size, 2) ) def _lowercase ( self : List[Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : str , UpperCamelCase__ : Union[str, Any] , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Any , UpperCamelCase__ : List[str] , UpperCamelCase__ : Any ) -> str: """simple docstring""" __magic_name__ = MobileBertForQuestionAnswering(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , start_positions=UpperCamelCase__ , end_positions=UpperCamelCase__ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _lowercase ( self : Dict , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Dict , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Any , UpperCamelCase__ : str ) -> int: """simple docstring""" __magic_name__ = self.num_labels __magic_name__ = MobileBertForSequenceClassification(UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _lowercase ( self : Optional[int] , UpperCamelCase__ : Any , UpperCamelCase__ : List[Any] , UpperCamelCase__ : Tuple , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Tuple , UpperCamelCase__ : Union[str, Any] ) -> str: """simple docstring""" __magic_name__ = self.num_labels __magic_name__ = MobileBertForTokenClassification(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = model(UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _lowercase ( self : Optional[Any] , UpperCamelCase__ : List[str] , UpperCamelCase__ : List[str] , UpperCamelCase__ : Any , UpperCamelCase__ : List[str] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : Optional[Any] , UpperCamelCase__ : str ) -> Optional[int]: """simple docstring""" __magic_name__ = self.num_choices __magic_name__ = MobileBertForMultipleChoice(config=UpperCamelCase__ ) model.to(UpperCamelCase__ ) model.eval() __magic_name__ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __magic_name__ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __magic_name__ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() __magic_name__ = model( UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _lowercase ( self : List[Any] ) -> Tuple: """simple docstring""" __magic_name__ = self.prepare_config_and_inputs() ( ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ( __magic_name__ ) , ) = config_and_inputs __magic_name__ = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask} return config, inputs_dict @require_torch class UpperCAmelCase_ ( _A , _A , unittest.TestCase ): '''simple docstring''' a__ = ( ( MobileBertModel, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, ) if is_torch_available() else () ) a__ = ( { """feature-extraction""": MobileBertModel, """fill-mask""": MobileBertForMaskedLM, """question-answering""": MobileBertForQuestionAnswering, """text-classification""": MobileBertForSequenceClassification, """token-classification""": MobileBertForTokenClassification, """zero-shot""": MobileBertForSequenceClassification, } if is_torch_available() else {} ) a__ = True def _lowercase ( self : Optional[Any] , UpperCamelCase__ : str , UpperCamelCase__ : Optional[int] , UpperCamelCase__ : Any=False ) -> Tuple: """simple docstring""" __magic_name__ = super()._prepare_for_class(UpperCamelCase__ , UpperCamelCase__ , return_labels=UpperCamelCase__ ) if return_labels: if model_class in get_values(UpperCamelCase__ ): __magic_name__ = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=UpperCamelCase__ ) __magic_name__ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCamelCase__ ) return inputs_dict def _lowercase ( self : List[Any] ) -> str: """simple docstring""" __magic_name__ = MobileBertModelTester(self ) __magic_name__ = ConfigTester(self , config_class=UpperCamelCase__ , hidden_size=37 ) def _lowercase ( self : Optional[int] ) -> List[str]: """simple docstring""" self.config_tester.run_common_tests() def _lowercase ( self : List[str] ) -> Any: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_model(*UpperCamelCase__ ) def _lowercase ( self : Optional[int] ) -> Optional[Any]: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_masked_lm(*UpperCamelCase__ ) def _lowercase ( self : List[str] ) -> Tuple: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_multiple_choice(*UpperCamelCase__ ) def _lowercase ( self : Union[str, Any] ) -> Optional[int]: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*UpperCamelCase__ ) def _lowercase ( self : int ) -> int: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_pretraining(*UpperCamelCase__ ) def _lowercase ( self : List[str] ) -> List[str]: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_question_answering(*UpperCamelCase__ ) def _lowercase ( self : Dict ) -> Dict: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_sequence_classification(*UpperCamelCase__ ) def _lowercase ( self : Any ) -> List[str]: """simple docstring""" __magic_name__ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mobilebert_for_token_classification(*UpperCamelCase__ ) def a__ ( A_ ): '''simple docstring''' return torch.tensor( A_, dtype=torch.long, device=A_, ) __lowerCAmelCase : Optional[Any] = 1e-3 @require_torch @require_sentencepiece @require_tokenizers class UpperCAmelCase_ ( unittest.TestCase ): '''simple docstring''' @slow def _lowercase ( self : str ) -> List[str]: """simple docstring""" __magic_name__ = MobileBertModel.from_pretrained("""google/mobilebert-uncased""" ).to(UpperCamelCase__ ) __magic_name__ = _long_tensor([[101, 7110, 1005, 1056, 2023, 1_1333, 1_7413, 1029, 102]] ) with torch.no_grad(): __magic_name__ = model(UpperCamelCase__ )[0] __magic_name__ = torch.Size((1, 9, 512) ) self.assertEqual(output.shape , UpperCamelCase__ ) __magic_name__ = torch.tensor( [ [ [-2.473_6526E07, 8.269_1656E04, 1.652_1838E05], [-5.754_1704E-01, 3.905_6022E00, 4.401_1507E00], [2.604_7359E00, 1.567_7652E00, -1.732_4188E-01], ] ] , device=UpperCamelCase__ , ) # MobileBERT results range from 10e0 to 10e8. Even a 0.0000001% difference with a value of 10e8 results in a # ~1 difference, it's therefore not a good idea to measure using addition. # Here, we instead divide the expected result with the result in order to obtain ~1. We then check that the # result is held between bounds: 1 - TOLERANCE < expected_result / result < 1 + TOLERANCE __magic_name__ = torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE ) __magic_name__ = torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE ) self.assertTrue(lower_bound and upper_bound )
88
import numpy as np from cva import destroyAllWindows, imread, imshow, waitKey class lowerCAmelCase__ : def __init__( self : Any , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> Dict: if dst_width < 0 or dst_height < 0: raise ValueError('''Destination width/height should be > 0''' ) __lowerCamelCase = img __lowerCamelCase = img.shape[1] __lowerCamelCase = img.shape[0] __lowerCamelCase = dst_width __lowerCamelCase = dst_height __lowerCamelCase = self.src_w / self.dst_w __lowerCamelCase = self.src_h / self.dst_h __lowerCamelCase = __lowerCamelCase = ( np.ones((self.dst_h, self.dst_w, 3) , np.uinta ) * 2_55 ) def __A ( self : List[Any] ) -> str: for i in range(self.dst_h ): for j in range(self.dst_w ): __lowerCamelCase = self.img[self.get_y(SCREAMING_SNAKE_CASE__ )][self.get_x(SCREAMING_SNAKE_CASE__ )] def __A ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> int: return int(self.ratio_x * x ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> int: return int(self.ratio_y * y ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = 800, 600 SCREAMING_SNAKE_CASE__ : int = imread("image_data/lena.jpg", 1) SCREAMING_SNAKE_CASE__ : Union[str, Any] = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( F'Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}', n.output ) waitKey(0) destroyAllWindows()
270
0
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block @dataclass class __magic_name__ ( _UpperCamelCase ): lowerCAmelCase : torch.FloatTensor class __magic_name__ ( _UpperCamelCase , _UpperCamelCase ): @register_to_config def __init__( self : Tuple ,_UpperCAmelCase : int = 65536 ,_UpperCAmelCase : Optional[int] = None ,_UpperCAmelCase : int = 2 ,_UpperCAmelCase : int = 2 ,_UpperCAmelCase : int = 0 ,_UpperCAmelCase : str = "fourier" ,_UpperCAmelCase : bool = True ,_UpperCAmelCase : bool = False ,_UpperCAmelCase : float = 0.0 ,_UpperCAmelCase : Tuple[str] = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D") ,_UpperCAmelCase : Tuple[str] = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip") ,_UpperCAmelCase : Tuple[str] = "UNetMidBlock1D" ,_UpperCAmelCase : str = None ,_UpperCAmelCase : Tuple[int] = (32, 32, 64) ,_UpperCAmelCase : str = None ,_UpperCAmelCase : int = 8 ,_UpperCAmelCase : int = 1 ,_UpperCAmelCase : bool = False ,): super().__init__() _a : str = sample_size # time if time_embedding_type == "fourier": _a : Union[str, Any] = GaussianFourierProjection( embedding_size=8 ,set_W_to_weight=_UpperCAmelCase ,log=_UpperCAmelCase ,flip_sin_to_cos=_UpperCAmelCase ) _a : Optional[int] = 2 * block_out_channels[0] elif time_embedding_type == "positional": _a : Optional[Any] = Timesteps( block_out_channels[0] ,flip_sin_to_cos=_UpperCAmelCase ,downscale_freq_shift=_UpperCAmelCase ) _a : Dict = block_out_channels[0] if use_timestep_embedding: _a : Tuple = block_out_channels[0] * 4 _a : Any = TimestepEmbedding( in_channels=_UpperCAmelCase ,time_embed_dim=_UpperCAmelCase ,act_fn=_UpperCAmelCase ,out_dim=block_out_channels[0] ,) _a : Dict = nn.ModuleList([] ) _a : Optional[Any] = None _a : Union[str, Any] = nn.ModuleList([] ) _a : Optional[Any] = None # down _a : List[Any] = in_channels for i, down_block_type in enumerate(_UpperCAmelCase ): _a : Optional[Any] = output_channel _a : Any = block_out_channels[i] if i == 0: input_channel += extra_in_channels _a : Tuple = i == len(_UpperCAmelCase ) - 1 _a : Any = get_down_block( _UpperCAmelCase ,num_layers=_UpperCAmelCase ,in_channels=_UpperCAmelCase ,out_channels=_UpperCAmelCase ,temb_channels=block_out_channels[0] ,add_downsample=not is_final_block or downsample_each_block ,) self.down_blocks.append(_UpperCAmelCase ) # mid _a : List[Any] = get_mid_block( _UpperCAmelCase ,in_channels=block_out_channels[-1] ,mid_channels=block_out_channels[-1] ,out_channels=block_out_channels[-1] ,embed_dim=block_out_channels[0] ,num_layers=_UpperCAmelCase ,add_downsample=_UpperCAmelCase ,) # up _a : List[str] = list(reversed(_UpperCAmelCase ) ) _a : List[Any] = reversed_block_out_channels[0] if out_block_type is None: _a : List[Any] = out_channels else: _a : List[str] = block_out_channels[0] for i, up_block_type in enumerate(_UpperCAmelCase ): _a : str = output_channel _a : List[str] = ( reversed_block_out_channels[i + 1] if i < len(_UpperCAmelCase ) - 1 else final_upsample_channels ) _a : str = i == len(_UpperCAmelCase ) - 1 _a : Tuple = get_up_block( _UpperCAmelCase ,num_layers=_UpperCAmelCase ,in_channels=_UpperCAmelCase ,out_channels=_UpperCAmelCase ,temb_channels=block_out_channels[0] ,add_upsample=not is_final_block ,) self.up_blocks.append(_UpperCAmelCase ) _a : Optional[Any] = output_channel # out _a : Dict = norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4 ,32 ) _a : List[str] = get_out_block( out_block_type=_UpperCAmelCase ,num_groups_out=_UpperCAmelCase ,embed_dim=block_out_channels[0] ,out_channels=_UpperCAmelCase ,act_fn=_UpperCAmelCase ,fc_dim=block_out_channels[-1] // 4 ,) def __lowercase ( self : Dict ,_UpperCAmelCase : torch.FloatTensor ,_UpperCAmelCase : Union[torch.Tensor, float, int] ,_UpperCAmelCase : bool = True ,): _a : Union[str, Any] = timestep if not torch.is_tensor(_UpperCAmelCase ): _a : Dict = torch.tensor([timesteps] ,dtype=torch.long ,device=sample.device ) elif torch.is_tensor(_UpperCAmelCase ) and len(timesteps.shape ) == 0: _a : Optional[Any] = timesteps[None].to(sample.device ) _a : int = self.time_proj(_UpperCAmelCase ) if self.config.use_timestep_embedding: _a : Optional[Any] = self.time_mlp(_UpperCAmelCase ) else: _a : Optional[int] = timestep_embed[..., None] _a : Union[str, Any] = timestep_embed.repeat([1, 1, sample.shape[2]] ).to(sample.dtype ) _a : Any = timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:]) ) # 2. down _a : Optional[Any] = () for downsample_block in self.down_blocks: _a , _a : str = downsample_block(hidden_states=_UpperCAmelCase ,temb=_UpperCAmelCase ) down_block_res_samples += res_samples # 3. mid if self.mid_block: _a : Union[str, Any] = self.mid_block(_UpperCAmelCase ,_UpperCAmelCase ) # 4. up for i, upsample_block in enumerate(self.up_blocks ): _a : List[Any] = down_block_res_samples[-1:] _a : str = down_block_res_samples[:-1] _a : Union[str, Any] = upsample_block(_UpperCAmelCase ,res_hidden_states_tuple=_UpperCAmelCase ,temb=_UpperCAmelCase ) # 5. post-process if self.out_block: _a : int = self.out_block(_UpperCAmelCase ,_UpperCAmelCase ) if not return_dict: return (sample,) return UNetaDOutput(sample=_UpperCAmelCase )
89
from queue import PriorityQueue from typing import Any import numpy as np def __magic_name__ ( __lowerCAmelCase : dict , __lowerCAmelCase : str , __lowerCAmelCase : set , __lowerCAmelCase : set , __lowerCAmelCase : dict , __lowerCAmelCase : dict , __lowerCAmelCase : PriorityQueue , __lowerCAmelCase : dict , __lowerCAmelCase : float | int , ) -> float | int: for nxt, d in graph[v]: if nxt in visited_forward: continue __lowerCamelCase = cst_fwd.get(__lowerCAmelCase , np.inf ) __lowerCamelCase = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) __lowerCamelCase = new_cost_f __lowerCamelCase = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: __lowerCamelCase = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def __magic_name__ ( __lowerCAmelCase : str , __lowerCAmelCase : str , __lowerCAmelCase : dict , __lowerCAmelCase : dict ) -> int: __lowerCamelCase = -1 __lowerCamelCase = set() __lowerCamelCase = set() __lowerCamelCase = {source: 0} __lowerCamelCase = {destination: 0} __lowerCamelCase = {source: None} __lowerCamelCase = {destination: None} __lowerCamelCase = PriorityQueue() __lowerCamelCase = PriorityQueue() __lowerCamelCase = np.inf queue_forward.put((0, source) ) queue_backward.put((0, destination) ) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): __lowerCamelCase , __lowerCamelCase = queue_forward.get() visited_forward.add(__lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = queue_backward.get() visited_backward.add(__lowerCAmelCase ) __lowerCamelCase = pass_and_relaxation( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) __lowerCamelCase = pass_and_relaxation( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: __lowerCamelCase = shortest_distance return shortest_path_distance SCREAMING_SNAKE_CASE__ : List[Any] = { "B": [["C", 1]], "C": [["D", 1]], "D": [["F", 1]], "E": [["B", 1], ["G", 2]], "F": [], "G": [["F", 1]], } SCREAMING_SNAKE_CASE__ : Optional[int] = { "B": [["E", 1]], "C": [["B", 1]], "D": [["C", 1]], "F": [["D", 1], ["G", 1]], "E": [[None, np.inf]], "G": [["E", 2]], } if __name__ == "__main__": import doctest doctest.testmod()
270
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available, ) __A = { "configuration_layoutlmv2": ["LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP", "LayoutLMv2Config"], "processing_layoutlmv2": ["LayoutLMv2Processor"], "tokenization_layoutlmv2": ["LayoutLMv2Tokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["LayoutLMv2TokenizerFast"] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = ["LayoutLMv2FeatureExtractor"] __A = ["LayoutLMv2ImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __A = [ "LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST", "LayoutLMv2ForQuestionAnswering", "LayoutLMv2ForSequenceClassification", "LayoutLMv2ForTokenClassification", "LayoutLMv2Layer", "LayoutLMv2Model", "LayoutLMv2PreTrainedModel", ] if TYPE_CHECKING: from .configuration_layoutlmva import LAYOUTLMV2_PRETRAINED_CONFIG_ARCHIVE_MAP, LayoutLMvaConfig from .processing_layoutlmva import LayoutLMvaProcessor from .tokenization_layoutlmva import LayoutLMvaTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor, LayoutLMvaImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_layoutlmva import ( LAYOUTLMV2_PRETRAINED_MODEL_ARCHIVE_LIST, LayoutLMvaForQuestionAnswering, LayoutLMvaForSequenceClassification, LayoutLMvaForTokenClassification, LayoutLMvaLayer, LayoutLMvaModel, LayoutLMvaPreTrainedModel, ) else: import sys __A = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
90
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ : List[Any] = TypeVar("T") def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (position - 1) // 2 def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (2 * position) + 1 def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (2 * position) + 2 class lowerCAmelCase__ ( Generic[T] ): def __init__( self : List[str] ) -> None: __lowerCamelCase = [] __lowerCamelCase = {} __lowerCamelCase = 0 def __len__( self : Optional[int] ) -> int: return self.elements def __repr__( self : Optional[int] ) -> str: return str(self.heap ) def __A ( self : Union[str, Any] ) -> bool: # Check if the priority queue is empty return self.elements == 0 def __A ( self : str , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Add an element with given priority to the queue self.heap.append((elem, weight) ) __lowerCamelCase = self.elements self.elements += 1 self._bubble_up(SCREAMING_SNAKE_CASE__ ) def __A ( self : Any ) -> T: # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) __lowerCamelCase , __lowerCamelCase = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __lowerCamelCase , __lowerCamelCase = self.heap[0] self._bubble_down(SCREAMING_SNAKE_CASE__ ) return elem def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Update the weight of the given key __lowerCamelCase = self.position_map[elem] __lowerCamelCase = (elem, weight) if position > 0: __lowerCamelCase = get_parent_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase = self.heap[parent_position] if parent_weight > weight: self._bubble_up(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Place a node at the proper position (upward movement) [to be used internally # only] __lowerCamelCase = self.position_map[elem] if curr_pos == 0: return None __lowerCamelCase = get_parent_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase = self.heap[curr_pos] __lowerCamelCase , __lowerCamelCase = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_up(SCREAMING_SNAKE_CASE__ ) return None def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Place a node at the proper position (downward movement) [to be used # internally only] __lowerCamelCase = self.position_map[elem] __lowerCamelCase , __lowerCamelCase = self.heap[curr_pos] __lowerCamelCase = get_child_left_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = get_child_right_position(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements and child_right_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_left_position] __lowerCamelCase , __lowerCamelCase = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: return None if child_right_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) return None def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: # Swap the nodes at the given positions __lowerCamelCase = self.heap[nodea_pos][0] __lowerCamelCase = self.heap[nodea_pos][0] __lowerCamelCase , __lowerCamelCase = ( self.heap[nodea_pos], self.heap[nodea_pos], ) __lowerCamelCase = nodea_pos __lowerCamelCase = nodea_pos class lowerCAmelCase__ ( Generic[T] ): def __init__( self : Tuple ) -> None: __lowerCamelCase = {} __lowerCamelCase = 0 def __repr__( self : Optional[int] ) -> str: return str(self.connections ) def __len__( self : List[str] ) -> int: return self.nodes def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Add a node in the graph if it is not in the graph if node not in self.connections: __lowerCamelCase = {} self.nodes += 1 def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Add an edge between 2 nodes in the graph self.add_node(SCREAMING_SNAKE_CASE__ ) self.add_node(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = weight __lowerCamelCase = weight def __magic_name__ ( __lowerCAmelCase : GraphUndirectedWeighted[T] , ) -> tuple[dict[T, int], dict[T, T | None]]: __lowerCamelCase = {node: maxsize for node in graph.connections} __lowerCamelCase = {node: None for node in graph.connections} __lowerCamelCase = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(__lowerCAmelCase , __lowerCAmelCase ) if priority_queue.is_empty(): return dist, parent # initialization __lowerCamelCase = priority_queue.extract_min() __lowerCamelCase = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __lowerCamelCase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(__lowerCAmelCase , dist[neighbour] ) __lowerCamelCase = node # running prim's algorithm while not priority_queue.is_empty(): __lowerCamelCase = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __lowerCamelCase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(__lowerCAmelCase , dist[neighbour] ) __lowerCamelCase = node return dist, parent
270
0
"""simple docstring""" from functools import reduce UpperCAmelCase_ : Tuple = ( """73167176531330624919225119674426574742355349194934""" """96983520312774506326239578318016984801869478851843""" """85861560789112949495459501737958331952853208805511""" """12540698747158523863050715693290963295227443043557""" """66896648950445244523161731856403098711121722383113""" """62229893423380308135336276614282806444486645238749""" """30358907296290491560440772390713810515859307960866""" """70172427121883998797908792274921901699720888093776""" """65727333001053367881220235421809751254540594752243""" """52584907711670556013604839586446706324415722155397""" """53697817977846174064955149290862569321978468622482""" """83972241375657056057490261407972968652414535100474""" """82166370484403199890008895243450658541227588666881""" """16427171479924442928230863465674813919123162824586""" """17866458359124566529476545682848912883142607690042""" """24219022671055626321111109370544217506941658960408""" """07198403850962455444362981230987879927244284909188""" """84580156166097919133875499200524063689912560717606""" """05886116467109405077541002256983155200055935729725""" """71636269561882670428252483600823257530420752963450""" ) def _A (__a = N ) -> int: """simple docstring""" return max( # mypy cannot properly interpret reduce int(reduce(lambda __a , __a : str(int(__a ) * int(__a ) ) , n[i : i + 13] ) ) for i in range(len(__a ) - 12 ) ) if __name__ == "__main__": print(f'''{solution() = }''')
91
from __future__ import annotations from statistics import mean def __magic_name__ ( __lowerCAmelCase : list[int] , __lowerCAmelCase : list[int] , __lowerCAmelCase : int ) -> list[int]: __lowerCamelCase = [0] * no_of_processes __lowerCamelCase = [0] * no_of_processes # Initialize remaining_time to waiting_time. for i in range(__lowerCAmelCase ): __lowerCamelCase = burst_time[i] __lowerCamelCase = [] __lowerCamelCase = 0 __lowerCamelCase = 0 # When processes are not completed, # A process whose arrival time has passed \ # and has remaining execution time is put into the ready_process. # The shortest process in the ready_process, target_process is executed. while completed != no_of_processes: __lowerCamelCase = [] __lowerCamelCase = -1 for i in range(__lowerCAmelCase ): if (arrival_time[i] <= total_time) and (remaining_time[i] > 0): ready_process.append(__lowerCAmelCase ) if len(__lowerCAmelCase ) > 0: __lowerCamelCase = ready_process[0] for i in ready_process: if remaining_time[i] < remaining_time[target_process]: __lowerCamelCase = i total_time += burst_time[target_process] completed += 1 __lowerCamelCase = 0 __lowerCamelCase = ( total_time - arrival_time[target_process] - burst_time[target_process] ) else: total_time += 1 return waiting_time def __magic_name__ ( __lowerCAmelCase : list[int] , __lowerCAmelCase : int , __lowerCAmelCase : list[int] ) -> list[int]: __lowerCamelCase = [0] * no_of_processes for i in range(__lowerCAmelCase ): __lowerCamelCase = burst_time[i] + waiting_time[i] return turn_around_time if __name__ == "__main__": print("[TEST CASE 01]") SCREAMING_SNAKE_CASE__ : Tuple = 4 SCREAMING_SNAKE_CASE__ : Optional[int] = [2, 5, 3, 7] SCREAMING_SNAKE_CASE__ : List[str] = [0, 0, 0, 0] SCREAMING_SNAKE_CASE__ : str = calculate_waitingtime(arrival_time, burst_time, no_of_processes) SCREAMING_SNAKE_CASE__ : Union[str, Any] = calculate_turnaroundtime( burst_time, no_of_processes, waiting_time ) # Printing the Result print("PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time") for i, process_id in enumerate(list(range(1, 5))): print( F'{process_id}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t' F'{waiting_time[i]}\t\t\t\t{turn_around_time[i]}' ) print(F'\nAverage waiting time = {mean(waiting_time):.5f}') print(F'Average turnaround time = {mean(turn_around_time):.5f}')
270
0
import argparse import json import os import tensorstore as ts import torch from flax import serialization from flax.traverse_util import flatten_dict, unflatten_dict from tensorflow.io import gfile from transformers.modeling_utils import dtype_byte_size from transformers.models.switch_transformers.convert_switch_transformers_original_flax_checkpoint_to_pytorch import ( rename_keys, ) from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME from transformers.utils.hub import convert_file_size_to_int def _a ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Dict ): if flax_key_tuple[-1] == "kernel" and flax_tensor.ndim == 3: # expert layer __lowerCAmelCase = flax_key_tuple[:-1] + ("weight",) __lowerCAmelCase = torch.permute(SCREAMING_SNAKE_CASE_ , (0, 2, 1) ) elif flax_key_tuple[-1] == "kernel" and ".".join(SCREAMING_SNAKE_CASE_ ): # linear layer __lowerCAmelCase = flax_key_tuple[:-1] + ("weight",) __lowerCAmelCase = flax_tensor.T elif flax_key_tuple[-1] in ["scale", "embedding"]: __lowerCAmelCase = flax_key_tuple[:-1] + ("weight",) return flax_key_tuple, flax_tensor def _a ( SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : List[str] ): if "metadata" in layer: __lowerCAmelCase = layer.split("metadata" ) __lowerCAmelCase = "".join(split_layer[0] )[:-1] __lowerCAmelCase = [tuple(("metadata" + split_layer[1]).split("/" ) )] elif "kvstore" in layer: __lowerCAmelCase = layer.split("kvstore" ) __lowerCAmelCase = "".join(split_layer[0] )[:-1] __lowerCAmelCase = [tuple(("kvstore" + split_layer[1]).split("/" ) )] else: __lowerCAmelCase = layer.split("/" ) __lowerCAmelCase = "/".join(split_layer[:-1] ) __lowerCAmelCase = (split_layer[-1],) if "kvstore/path" in layer: __lowerCAmelCase = F"""{switch_checkpoint_path}/{checkpoint_info[layer]}""" elif "kvstore/driver" in layer: __lowerCAmelCase = "file" else: __lowerCAmelCase = checkpoint_info[layer] return curr_real_layer_name, split_layer, content def _a ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[str] ): __lowerCAmelCase = rename_keys(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = {} for k, v in current_block.items(): __lowerCAmelCase = v __lowerCAmelCase = new_current_block torch.save(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) def _a ( SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Union[str, Any] , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : str = WEIGHTS_NAME ): __lowerCAmelCase = convert_file_size_to_int(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = [] __lowerCAmelCase = {} __lowerCAmelCase = 0 __lowerCAmelCase = 0 os.makedirs(SCREAMING_SNAKE_CASE_ , exist_ok=SCREAMING_SNAKE_CASE_ ) with gfile.GFile(switch_checkpoint_path + "/checkpoint" , "rb" ) as fp: __lowerCAmelCase = serialization.msgpack_restore(fp.read() )["optimizer"]["target"] __lowerCAmelCase = flatten_dict(SCREAMING_SNAKE_CASE_ , sep="/" ) __lowerCAmelCase = {} for layer in checkpoint_info.keys(): __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase = get_key_and_tensorstore_dict( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) if curr_real_layer_name in all_layers: __lowerCAmelCase = content else: __lowerCAmelCase = {split_layer[-1]: content} for key in all_layers.keys(): # open tensorstore file __lowerCAmelCase = ts.open(unflatten_dict(all_layers[key] ) ).result().read().result() __lowerCAmelCase = torch.tensor(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = raw_weights.numel() * dtype_byte_size(raw_weights.dtype ) # use the renaming pattern from the small conversion scripts __lowerCAmelCase , __lowerCAmelCase = rename_base_flax_keys(tuple(key.split("/" ) ) , SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = "/".join(SCREAMING_SNAKE_CASE_ ) # If this weight is going to tip up over the maximal size, we split. if current_block_size + weight_size > max_shard_size: __lowerCAmelCase = os.path.join( SCREAMING_SNAKE_CASE_ , weights_name.replace(".bin" , F"""-{len(SCREAMING_SNAKE_CASE_ )+1:05d}-of-???.bin""" ) ) rename_and_save_block(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) sharded_state_dicts.append(current_block.keys() ) del current_block __lowerCAmelCase = {} __lowerCAmelCase = 0 __lowerCAmelCase = raw_weights.to(getattr(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) current_block_size += weight_size total_size += weight_size # Add the last block __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , weights_name.replace(".bin" , F"""-{len(SCREAMING_SNAKE_CASE_ )+1:05d}-of-???.bin""" ) ) rename_and_save_block(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) sharded_state_dicts.append(current_block.keys() ) # If we only have one shard, we return it if len(SCREAMING_SNAKE_CASE_ ) == 1: return {weights_name: sharded_state_dicts[0]}, None # Otherwise, let's build the index __lowerCAmelCase = {} __lowerCAmelCase = {} for idx, shard in enumerate(SCREAMING_SNAKE_CASE_ ): __lowerCAmelCase = weights_name.replace( ".bin" , F"""-{idx+1:05d}-of-{len(SCREAMING_SNAKE_CASE_ ):05d}.bin""" ) # len(sharded_state_dicts):05d} __lowerCAmelCase = os.path.join(SCREAMING_SNAKE_CASE_ , weights_name.replace(".bin" , F"""-{idx+1:05d}-of-???.bin""" ) ) os.rename(SCREAMING_SNAKE_CASE_ , os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) ) __lowerCAmelCase = shard for key in shard: __lowerCAmelCase = shard_file # Add the metadata __lowerCAmelCase = {"total_size": total_size} __lowerCAmelCase = {"metadata": metadata, "weight_map": weight_map} with open(os.path.join(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , "w" , encoding="utf-8" ) as f: __lowerCAmelCase = json.dumps(SCREAMING_SNAKE_CASE_ , indent=2 , sort_keys=SCREAMING_SNAKE_CASE_ ) + "\n" f.write(SCREAMING_SNAKE_CASE_ ) return metadata, index if __name__ == "__main__": UpperCamelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument( """--switch_t5x_checkpoint_path""", default="""/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128/checkpoint_634600""", type=str, required=False, help="""Path to a directory containing a folder per layer. Follows the original Google format.""", ) parser.add_argument("""--max_shard_size""", default="""10GB""", required=False, help="""Max shard size""") parser.add_argument("""--dtype""", default="""bfloat16""", type=str, required=False, help="""dtype of the saved model""") parser.add_argument( """--pytorch_dump_folder_path""", default="""/mnt/disks/disk_switch/original_checkpoints/switch-xxl-128-converted""", type=str, required=False, help="""Path to the output pytorch model.""", ) UpperCamelCase__ = parser.parse_args() shard_on_the_fly( args.switch_tax_checkpoint_path, args.pytorch_dump_folder_path, args.max_shard_size, args.dtype, ) def _a ( ): from transformers import SwitchTransformersConfig, SwitchTransformersForConditionalGeneration, TaTokenizer __lowerCAmelCase = SwitchTransformersConfig.from_pretrained("google/switch-base-8" ) config.save_pretrained("/home/arthur_huggingface_co/transformers/switch_converted" ) __lowerCAmelCase = SwitchTransformersForConditionalGeneration.from_pretrained( "/home/arthur_huggingface_co/transformers/switch_converted" , device_map="auto" ) __lowerCAmelCase = TaTokenizer.from_pretrained("t5-small" ) __lowerCAmelCase = "A <extra_id_0> walks into a bar a orders a <extra_id_1> with <extra_id_2> pinch of <extra_id_3>." __lowerCAmelCase = tokenizer(SCREAMING_SNAKE_CASE_ , return_tensors="pt" ).input_ids __lowerCAmelCase = model.generate(SCREAMING_SNAKE_CASE_ , decoder_start_token_id=0 ) print(tokenizer.decode(out[0] ) )
92
from abc import ABC, abstractmethod from argparse import ArgumentParser class lowerCAmelCase__ ( __lowercase ): @staticmethod @abstractmethod def __A ( SCREAMING_SNAKE_CASE__ : ArgumentParser ) -> str: raise NotImplementedError() @abstractmethod def __A ( self : Optional[int] ) -> Union[str, Any]: raise NotImplementedError()
270
0
'''simple docstring''' from typing import List, Optional, Union from ...image_utils import ImageInput from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class lowerCAmelCase__ ( lowerCamelCase_ ): lowerCAmelCase_ = ['''image_processor''', '''tokenizer'''] lowerCAmelCase_ = '''BlipImageProcessor''' lowerCAmelCase_ = ('''BertTokenizer''', '''BertTokenizerFast''') def __init__( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): """simple docstring""" lowercase_ : Union[str, Any] = False super().__init__(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Tuple = self.image_processor def __call__( self , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = 0 , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = True , __SCREAMING_SNAKE_CASE = None , **__SCREAMING_SNAKE_CASE , ): """simple docstring""" if images is None and text is None: raise ValueError('''You have to specify either images or text.''' ) # Get only text if images is None: lowercase_ : Dict = self.tokenizer lowercase_ : List[str] = self.tokenizer( text=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , stride=__SCREAMING_SNAKE_CASE , pad_to_multiple_of=__SCREAMING_SNAKE_CASE , return_attention_mask=__SCREAMING_SNAKE_CASE , return_overflowing_tokens=__SCREAMING_SNAKE_CASE , return_special_tokens_mask=__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , return_token_type_ids=__SCREAMING_SNAKE_CASE , return_length=__SCREAMING_SNAKE_CASE , verbose=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) return text_encoding # add pixel_values lowercase_ : Dict = self.image_processor(__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE ) if text is not None: lowercase_ : int = self.tokenizer( text=__SCREAMING_SNAKE_CASE , add_special_tokens=__SCREAMING_SNAKE_CASE , padding=__SCREAMING_SNAKE_CASE , truncation=__SCREAMING_SNAKE_CASE , max_length=__SCREAMING_SNAKE_CASE , stride=__SCREAMING_SNAKE_CASE , pad_to_multiple_of=__SCREAMING_SNAKE_CASE , return_attention_mask=__SCREAMING_SNAKE_CASE , return_overflowing_tokens=__SCREAMING_SNAKE_CASE , return_special_tokens_mask=__SCREAMING_SNAKE_CASE , return_offsets_mapping=__SCREAMING_SNAKE_CASE , return_token_type_ids=__SCREAMING_SNAKE_CASE , return_length=__SCREAMING_SNAKE_CASE , verbose=__SCREAMING_SNAKE_CASE , return_tensors=__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE , ) else: lowercase_ : Any = None if text_encoding is not None: encoding_image_processor.update(__SCREAMING_SNAKE_CASE ) return encoding_image_processor def _snake_case ( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return self.tokenizer.batch_decode(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) def _snake_case ( self , *__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ): """simple docstring""" return self.tokenizer.decode(*__SCREAMING_SNAKE_CASE , **__SCREAMING_SNAKE_CASE ) @property def _snake_case ( self ): """simple docstring""" lowercase_ : Optional[Any] = self.tokenizer.model_input_names lowercase_ : str = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
93
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv("""TEST_SAGEMAKER""" , """False""" ) ) is not True , reason="""Skipping test because should only be run when releasing minor transformers version""" , ) @pytest.mark.usefixtures("""sm_env""" ) @parameterized_class( [ { """framework""": """pytorch""", """script""": """run_glue_model_parallelism.py""", """model_name_or_path""": """roberta-large""", """instance_type""": """ml.p3dn.24xlarge""", """results""": {"""train_runtime""": 1_600, """eval_accuracy""": 0.3, """eval_loss""": 1.2}, }, { """framework""": """pytorch""", """script""": """run_glue.py""", """model_name_or_path""": """roberta-large""", """instance_type""": """ml.p3dn.24xlarge""", """results""": {"""train_runtime""": 1_600, """eval_accuracy""": 0.3, """eval_loss""": 1.2}, }, ] ) class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Optional[int] ) -> List[Any]: if self.framework == "pytorch": subprocess.run( f'''cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'''.split() , encoding='''utf-8''' , check=SCREAMING_SNAKE_CASE__ , ) assert hasattr(self , '''env''' ) def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: # configuration for running training on smdistributed Model Parallel __lowerCamelCase = { '''enabled''': True, '''processes_per_host''': 8, } __lowerCamelCase = { '''enabled''': True, '''parameters''': { '''microbatches''': 4, '''placement_strategy''': '''spread''', '''pipeline''': '''interleaved''', '''optimize''': '''speed''', '''partitions''': 4, '''ddp''': True, }, } __lowerCamelCase = {'''smdistributed''': {'''modelparallel''': smp_options}, '''mpi''': mpi_options} __lowerCamelCase = '''trainer''' if self.script == '''run_glue.py''' else '''smtrainer''' # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=f'''{self.env.base_job_name}-{instance_count}-smp-{name_extension}''' , instance_count=SCREAMING_SNAKE_CASE__ , instance_type=self.instance_type , debugger_hook_config=SCREAMING_SNAKE_CASE__ , hyperparameters={ **self.env.hyperparameters, '''model_name_or_path''': self.model_name_or_path, '''max_steps''': 5_00, } , metric_definitions=self.env.metric_definitions , distribution=SCREAMING_SNAKE_CASE__ , py_version='''py36''' , ) def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[str]: TrainingJobAnalytics(SCREAMING_SNAKE_CASE__ ).export_csv(f'''{self.env.test_path}/{job_name}_metrics.csv''' ) @parameterized.expand([(1,)] ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: # create estimator __lowerCamelCase = self.create_estimator(SCREAMING_SNAKE_CASE__ ) # run training estimator.fit() # result dataframe __lowerCamelCase = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __lowerCamelCase = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) __lowerCamelCase = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 99_99_99 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy ) assert all(t <= self.results['''eval_loss'''] for t in eval_loss ) # dump tests result into json file to share in PR with open(f'''{estimator.latest_training_job.name}.json''' , '''w''' ) as outfile: json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss} , SCREAMING_SNAKE_CASE__ )
270
0
from unittest.mock import patch import pyspark from datasets.packaged_modules.spark.spark import ( Spark, SparkExamplesIterable, _generate_iterable_examples, ) from ..utils import ( require_dill_gt_0_3_2, require_not_windows, ) def __lowerCamelCase ( UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Union[str, Any] ): """simple docstring""" a :Dict = [] for part_id in partition_order: a :str = df.where(F'''SPARK_PARTITION_ID() = {part_id}''' ).collect() for row_idx, row in enumerate(UpperCAmelCase_ ): expected_row_ids_and_row_dicts.append((F'''{part_id}_{row_idx}''', row.asDict()) ) return expected_row_ids_and_row_dicts @require_not_windows @require_dill_gt_0_3_2 def __lowerCamelCase ( ): """simple docstring""" a :Union[str, Any] = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() a :List[Any] = spark.range(100 ).repartition(1 ) a :Any = Spark(UpperCAmelCase_ ) # The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means # that each partition can hold 2 rows. spark_builder._repartition_df_if_needed(max_shard_size=16 ) # Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions. assert spark_builder.df.rdd.getNumPartitions() == 50 @require_not_windows @require_dill_gt_0_3_2 def __lowerCamelCase ( ): """simple docstring""" a :int = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() a :Tuple = spark.range(10 ).repartition(2 ) a :Optional[Any] = [1, 0] a :Any = _generate_iterable_examples(UpperCAmelCase_ , UpperCAmelCase_ ) # Reverse the partitions. a :int = _get_expected_row_ids_and_row_dicts_for_partition_order(UpperCAmelCase_ , UpperCAmelCase_ ) for i, (row_id, row_dict) in enumerate(generate_fn() ): a , a :int = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def __lowerCamelCase ( ): """simple docstring""" a :int = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() a :List[str] = spark.range(10 ).repartition(1 ) a :str = SparkExamplesIterable(UpperCAmelCase_ ) assert it.n_shards == 1 for i, (row_id, row_dict) in enumerate(UpperCAmelCase_ ): assert row_id == F'''0_{i}''' assert row_dict == {"id": i} @require_not_windows @require_dill_gt_0_3_2 def __lowerCamelCase ( ): """simple docstring""" a :List[Any] = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() a :Dict = spark.range(30 ).repartition(3 ) # Mock the generator so that shuffle reverses the partition indices. with patch('''numpy.random.Generator''' ) as generator_mock: a :Optional[int] = lambda UpperCAmelCase_ : x.reverse() a :Tuple = _get_expected_row_ids_and_row_dicts_for_partition_order(UpperCAmelCase_ , [2, 1, 0] ) a :str = SparkExamplesIterable(UpperCAmelCase_ ).shuffle_data_sources(UpperCAmelCase_ ) assert shuffled_it.n_shards == 3 for i, (row_id, row_dict) in enumerate(UpperCAmelCase_ ): a , a :str = expected_row_ids_and_row_dicts[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def __lowerCamelCase ( ): """simple docstring""" a :List[str] = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() a :Optional[Any] = spark.range(20 ).repartition(4 ) # Partitions 0 and 2 a :Tuple = SparkExamplesIterable(UpperCAmelCase_ ).shard_data_sources(worker_id=0 , num_workers=2 ) assert shard_it_a.n_shards == 2 a :List[str] = _get_expected_row_ids_and_row_dicts_for_partition_order(UpperCAmelCase_ , [0, 2] ) for i, (row_id, row_dict) in enumerate(UpperCAmelCase_ ): a , a :List[Any] = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict # Partitions 1 and 3 a :Tuple = SparkExamplesIterable(UpperCAmelCase_ ).shard_data_sources(worker_id=1 , num_workers=2 ) assert shard_it_a.n_shards == 2 a :Optional[int] = _get_expected_row_ids_and_row_dicts_for_partition_order(UpperCAmelCase_ , [1, 3] ) for i, (row_id, row_dict) in enumerate(UpperCAmelCase_ ): a , a :Any = expected_row_ids_and_row_dicts_a[i] assert row_id == expected_row_id assert row_dict == expected_row_dict @require_not_windows @require_dill_gt_0_3_2 def __lowerCamelCase ( ): """simple docstring""" a :List[Any] = pyspark.sql.SparkSession.builder.master('''local[*]''' ).appName('''pyspark''' ).getOrCreate() a :Dict = spark.range(100 ).repartition(1 ) a :Dict = Spark(UpperCAmelCase_ ) # Choose a small max_shard_size for maximum partitioning. spark_builder._repartition_df_if_needed(max_shard_size=1 ) # The new number of partitions should not be greater than the number of rows. assert spark_builder.df.rdd.getNumPartitions() == 100
94
from __future__ import annotations from fractions import Fraction def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> bool: return ( num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den ) def __magic_name__ ( __lowerCAmelCase : int ) -> list[str]: __lowerCamelCase = [] __lowerCamelCase = 11 __lowerCamelCase = int('''1''' + '''0''' * digit_len ) for num in range(__lowerCAmelCase , __lowerCAmelCase ): while den <= 99: if (num != den) and (num % 10 == den // 10) and (den % 10 != 0): if is_digit_cancelling(__lowerCAmelCase , __lowerCAmelCase ): solutions.append(f'''{num}/{den}''' ) den += 1 num += 1 __lowerCamelCase = 10 return solutions def __magic_name__ ( __lowerCAmelCase : int = 2 ) -> int: __lowerCamelCase = 1.0 for fraction in fraction_list(__lowerCAmelCase ): __lowerCamelCase = Fraction(__lowerCAmelCase ) result *= frac.denominator / frac.numerator return int(__lowerCAmelCase ) if __name__ == "__main__": print(solution())
270
0
from ....configuration_utils import PretrainedConfig from ....utils import logging UpperCAmelCase : Any = logging.get_logger(__name__) # TODO: upload to AWS UpperCAmelCase : Dict = { """yjernite/retribert-base-uncased""": ( """https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/config.json""" ), } class __lowerCAmelCase ( UpperCamelCase__): _lowercase : Optional[Any] = """retribert""" def __init__( self , lowerCAmelCase__=3_0_5_2_2 , lowerCAmelCase__=7_6_8 , lowerCAmelCase__=8 , 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__=True , lowerCAmelCase__=1_2_8 , lowerCAmelCase__=0 , **lowerCAmelCase__ , ) -> str: '''simple docstring''' super().__init__(pad_token_id=lowerCAmelCase__ , **lowerCAmelCase__ ) a__ : Tuple =vocab_size a__ : Any =hidden_size a__ : Optional[Any] =num_hidden_layers a__ : Optional[int] =num_attention_heads a__ : List[Any] =hidden_act a__ : Dict =intermediate_size a__ : Optional[int] =hidden_dropout_prob a__ : Dict =attention_probs_dropout_prob a__ : Optional[int] =max_position_embeddings a__ : List[str] =type_vocab_size a__ : Union[str, Any] =initializer_range a__ : Optional[Any] =layer_norm_eps a__ : int =share_encoders a__ : List[str] =projection_dim
95
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE__ : List[str] = { "configuration_blip": [ "BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlipConfig", "BlipTextConfig", "BlipVisionConfig", ], "processing_blip": ["BlipProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = ["BlipImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "BLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "BlipModel", "BlipPreTrainedModel", "BlipForConditionalGeneration", "BlipForQuestionAnswering", "BlipVisionModel", "BlipTextModel", "BlipForImageTextRetrieval", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Any = [ "TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "TFBlipModel", "TFBlipPreTrainedModel", "TFBlipForConditionalGeneration", "TFBlipForQuestionAnswering", "TFBlipVisionModel", "TFBlipTextModel", "TFBlipForImageTextRetrieval", ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
270
0
"""simple docstring""" import gc import unittest import numpy as np import torch from diffusers import StableDiffusionKDiffusionPipeline from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() @slow @require_torch_gpu class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' def A_ ( self ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def A_ ( self ): _lowerCamelCase : Tuple = StableDiffusionKDiffusionPipeline.from_pretrained('CompVis/stable-diffusion-v1-4' ) _lowerCamelCase : Any = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) sd_pipe.set_scheduler('sample_euler' ) _lowerCamelCase : Dict = 'A painting of a squirrel eating a burger' _lowerCamelCase : List[Any] = torch.manual_seed(0 ) _lowerCamelCase : Dict = sd_pipe([prompt] , generator=lowercase , guidance_scale=9.0 , num_inference_steps=20 , output_type='np' ) _lowerCamelCase : Union[str, Any] = output.images _lowerCamelCase : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCamelCase : Dict = np.array([0.04_47, 0.04_92, 0.04_68, 0.04_08, 0.03_83, 0.04_08, 0.03_54, 0.03_80, 0.03_39] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def A_ ( self ): _lowerCamelCase : Any = StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base' ) _lowerCamelCase : Any = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) sd_pipe.set_scheduler('sample_euler' ) _lowerCamelCase : Union[str, Any] = 'A painting of a squirrel eating a burger' _lowerCamelCase : List[str] = torch.manual_seed(0 ) _lowerCamelCase : Tuple = sd_pipe([prompt] , generator=lowercase , guidance_scale=9.0 , num_inference_steps=20 , output_type='np' ) _lowerCamelCase : Optional[int] = output.images _lowerCamelCase : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCamelCase : List[str] = np.array([0.12_37, 0.13_20, 0.14_38, 0.13_59, 0.13_90, 0.11_32, 0.12_77, 0.11_75, 0.11_12] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5E-1 def A_ ( self ): _lowerCamelCase : Union[str, Any] = StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base' ) _lowerCamelCase : int = sd_pipe.to(lowercase ) sd_pipe.set_progress_bar_config(disable=lowercase ) sd_pipe.set_scheduler('sample_dpmpp_2m' ) _lowerCamelCase : int = 'A painting of a squirrel eating a burger' _lowerCamelCase : List[str] = torch.manual_seed(0 ) _lowerCamelCase : Any = sd_pipe( [prompt] , generator=lowercase , guidance_scale=7.5 , num_inference_steps=15 , output_type='np' , use_karras_sigmas=lowercase , ) _lowerCamelCase : List[Any] = output.images _lowerCamelCase : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) _lowerCamelCase : Any = np.array( [0.11_38_16_89, 0.12_11_29_21, 0.1_38_94_57, 0.12_54_96_06, 0.1_24_49_64, 0.10_83_15_17, 0.11_56_28_66, 0.10_86_78_16, 0.10_49_90_48] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
96
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Optional[Any] = {"configuration_wavlm": ["WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "WavLMConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST", "WavLMForAudioFrameClassification", "WavLMForCTC", "WavLMForSequenceClassification", "WavLMForXVector", "WavLMModel", "WavLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_wavlm import WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP, WavLMConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavlm import ( WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST, WavLMForAudioFrameClassification, WavLMForCTC, WavLMForSequenceClassification, WavLMForXVector, WavLMModel, WavLMPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
270
0
'''simple docstring''' from __future__ import annotations import typing from collections import Counter def a ( __a ) -> typing.Counter[int]: '''simple docstring''' UpperCamelCase__ :typing.Counter[int] = Counter() for base in range(1 , max_perimeter + 1 ): for perpendicular in range(__a , max_perimeter + 1 ): UpperCamelCase__ :int = (base * base + perpendicular * perpendicular) ** 0.5 if hypotenuse == int(__a ): UpperCamelCase__ :Optional[Any] = int(base + perpendicular + hypotenuse ) if perimeter > max_perimeter: continue triplets[perimeter] += 1 return triplets def a ( __a = 1000 ) -> int: '''simple docstring''' UpperCamelCase__ :int = pythagorean_triple(__a ) return triplets.most_common(1 )[0][0] if __name__ == "__main__": print(F"""Perimeter {solution()} has maximum solutions""")
97
import pprint import requests SCREAMING_SNAKE_CASE__ : str = "https://zenquotes.io/api" def __magic_name__ ( ) -> list: return requests.get(API_ENDPOINT_URL + '''/today''' ).json() def __magic_name__ ( ) -> list: return requests.get(API_ENDPOINT_URL + '''/random''' ).json() if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : int = random_quotes() pprint.pprint(response)
270
0
"""simple docstring""" from __future__ import annotations import queue class snake_case : """simple docstring""" def __init__( self : int ,lowerCamelCase__ : List[str] ): UpperCAmelCase__ = data UpperCAmelCase__ = None UpperCAmelCase__ = None def a_ ( ): print('\n********Press N to stop entering at any point of time********\n' ) UpperCAmelCase__ = input('Enter the value of the root node: ' ).strip().lower() UpperCAmelCase__ = queue.Queue() UpperCAmelCase__ = TreeNode(int(lowerCamelCase ) ) q.put(lowerCamelCase ) while not q.empty(): UpperCAmelCase__ = q.get() UpperCAmelCase__ = f'''Enter the left node of {node_found.data}: ''' UpperCAmelCase__ = input(lowerCamelCase ).strip().lower() or 'n' if check == "n": return tree_node UpperCAmelCase__ = TreeNode(int(lowerCamelCase ) ) UpperCAmelCase__ = left_node q.put(lowerCamelCase ) UpperCAmelCase__ = f'''Enter the right node of {node_found.data}: ''' UpperCAmelCase__ = input(lowerCamelCase ).strip().lower() or 'n' if check == "n": return tree_node UpperCAmelCase__ = TreeNode(int(lowerCamelCase ) ) UpperCAmelCase__ = right_node q.put(lowerCamelCase ) raise def a_ ( lowerCamelCase ): if not isinstance(lowerCamelCase , lowerCamelCase ) or not node: return print(node.data , end=',' ) pre_order(node.left ) pre_order(node.right ) def a_ ( lowerCamelCase ): if not isinstance(lowerCamelCase , lowerCamelCase ) or not node: return in_order(node.left ) print(node.data , end=',' ) in_order(node.right ) def a_ ( lowerCamelCase ): if not isinstance(lowerCamelCase , lowerCamelCase ) or not node: return post_order(node.left ) post_order(node.right ) print(node.data , end=',' ) def a_ ( lowerCamelCase ): if not isinstance(lowerCamelCase , lowerCamelCase ) or not node: return UpperCAmelCase__ = queue.Queue() q.put(lowerCamelCase ) while not q.empty(): UpperCAmelCase__ = q.get() print(node_dequeued.data , end=',' ) if node_dequeued.left: q.put(node_dequeued.left ) if node_dequeued.right: q.put(node_dequeued.right ) def a_ ( lowerCamelCase ): if not isinstance(lowerCamelCase , lowerCamelCase ) or not node: return UpperCAmelCase__ = queue.Queue() q.put(lowerCamelCase ) while not q.empty(): UpperCAmelCase__ = [] while not q.empty(): UpperCAmelCase__ = q.get() print(node_dequeued.data , end=',' ) if node_dequeued.left: list_.append(node_dequeued.left ) if node_dequeued.right: list_.append(node_dequeued.right ) print() for node in list_: q.put(lowerCamelCase ) def a_ ( lowerCamelCase ): if not isinstance(lowerCamelCase , lowerCamelCase ) or not node: return UpperCAmelCase__ = [] UpperCAmelCase__ = node while n or stack: while n: # start from root node, find its left child print(n.data , end=',' ) stack.append(lowerCamelCase ) UpperCAmelCase__ = n.left # end of while means current node doesn't have left child UpperCAmelCase__ = stack.pop() # start to traverse its right child UpperCAmelCase__ = n.right def a_ ( lowerCamelCase ): if not isinstance(lowerCamelCase , lowerCamelCase ) or not node: return UpperCAmelCase__ = [] UpperCAmelCase__ = node while n or stack: while n: stack.append(lowerCamelCase ) UpperCAmelCase__ = n.left UpperCAmelCase__ = stack.pop() print(n.data , end=',' ) UpperCAmelCase__ = n.right def a_ ( lowerCamelCase ): if not isinstance(lowerCamelCase , lowerCamelCase ) or not node: return UpperCAmelCase__ , UpperCAmelCase__ = [], [] UpperCAmelCase__ = node stacka.append(lowerCamelCase ) while stacka: # to find the reversed order of post order, store it in stack2 UpperCAmelCase__ = stacka.pop() if n.left: stacka.append(n.left ) if n.right: stacka.append(n.right ) stacka.append(lowerCamelCase ) while stacka: # pop up from stack2 will be the post order print(stacka.pop().data , end=',' ) def a_ ( lowerCamelCase = "" , lowerCamelCase=5_0 , lowerCamelCase="*" ): if not s: return "\n" + width * char UpperCAmelCase__ , UpperCAmelCase__ = divmod(width - len(lowerCamelCase ) - 2 , 2 ) return f'''{left * char} {s} {(left + extra) * char}''' if __name__ == "__main__": import doctest doctest.testmod() print(prompt('Binary Tree Traversals')) lowerCAmelCase__ : TreeNode = build_tree() print(prompt('Pre Order Traversal')) pre_order(node) print(prompt() + '\n') print(prompt('In Order Traversal')) in_order(node) print(prompt() + '\n') print(prompt('Post Order Traversal')) post_order(node) print(prompt() + '\n') print(prompt('Level Order Traversal')) level_order(node) print(prompt() + '\n') print(prompt('Actual Level Order Traversal')) level_order_actual(node) print('*' * 50 + '\n') print(prompt('Pre Order Traversal - Iteration Version')) pre_order_iter(node) print(prompt() + '\n') print(prompt('In Order Traversal - Iteration Version')) in_order_iter(node) print(prompt() + '\n') print(prompt('Post Order Traversal - Iteration Version')) post_order_iter(node) print(prompt())
98
from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def __magic_name__ ( __lowerCAmelCase : int ) -> int: __lowerCamelCase = prime_factors(__lowerCAmelCase ) if is_square_free(__lowerCAmelCase ): return -1 if len(__lowerCAmelCase ) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
270
0
import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel lowercase : List[str] = { """text_branch""": """text_model""", """audio_branch""": """audio_model.audio_encoder""", """attn""": """attention.self""", """self.proj""": """output.dense""", """attention.self_mask""": """attn_mask""", """mlp.fc1""": """intermediate.dense""", """mlp.fc2""": """output.dense""", """norm1""": """layernorm_before""", """norm2""": """layernorm_after""", """bn0""": """batch_norm""", } lowercase : Union[str, Any] = AutoFeatureExtractor.from_pretrained("""laion/clap-htsat-unfused""", truncation="""rand_trunc""") def A_ ( A__ , A__=False ) -> List[Any]: a__ , a__ : Union[str, Any] = create_model( 'HTSAT-tiny' , 'roberta' , A__ , precision='fp32' , device='cuda:0' if torch.cuda.is_available() else 'cpu' , enable_fusion=A__ , fusion_type='aff_2d' if enable_fusion else None , ) return model, model_cfg def A_ ( A__ ) -> str: a__ : Dict = {} a__ : Optional[Any] = R'.*sequential.(\d+).*' a__ : Optional[Any] = R'.*_projection.(\d+).*' for key, value in state_dict.items(): # check if any key needs to be modified for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: a__ : str = key.replace(A__ , A__ ) if re.match(A__ , A__ ): # replace sequential layers with list a__ : List[Any] = re.match(A__ , A__ ).group(1 ) a__ : int = key.replace(F'sequential.{sequential_layer}.' , F'layers.{int(A__ )//3}.linear.' ) elif re.match(A__ , A__ ): a__ : str = int(re.match(A__ , A__ ).group(1 ) ) # Because in CLAP they use `nn.Sequential`... a__ : int = 1 if projecton_layer == 0 else 2 a__ : Union[str, Any] = key.replace(F'_projection.{projecton_layer}.' , F'_projection.linear{transformers_projection_layer}.' ) if "audio" and "qkv" in key: # split qkv into query key and value a__ : int = value a__ : Tuple = mixed_qkv.size(0 ) // 3 a__ : Union[str, Any] = mixed_qkv[:qkv_dim] a__ : Union[str, Any] = mixed_qkv[qkv_dim : qkv_dim * 2] a__ : List[Any] = mixed_qkv[qkv_dim * 2 :] a__ : str = query_layer a__ : Union[str, Any] = key_layer a__ : int = value_layer else: a__ : Tuple = value return model_state_dict def A_ ( A__ , A__ , A__ , A__=False ) -> Dict: a__ , a__ : Optional[int] = init_clap(A__ , enable_fusion=A__ ) clap_model.eval() a__ : Optional[int] = clap_model.state_dict() a__ : Tuple = rename_state_dict(A__ ) a__ : Union[str, Any] = ClapConfig() a__ : str = enable_fusion a__ : Tuple = ClapModel(A__ ) # ignore the spectrogram embedding layer model.load_state_dict(A__ , strict=A__ ) model.save_pretrained(A__ ) transformers_config.save_pretrained(A__ ) if __name__ == "__main__": lowercase : int = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument("""--enable_fusion""", action="""store_true""", help="""Whether to enable fusion or not""") lowercase : Any = parser.parse_args() convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)
99
import argparse import collections import json import os import re import string import sys import numpy as np SCREAMING_SNAKE_CASE__ : Union[str, Any] = re.compile(r"\b(a|an|the)\b", re.UNICODE) SCREAMING_SNAKE_CASE__ : int = None def __magic_name__ ( ) -> str: __lowerCamelCase = argparse.ArgumentParser('''Official evaluation script for SQuAD version 2.0.''' ) parser.add_argument('''data_file''' , metavar='''data.json''' , help='''Input data JSON file.''' ) parser.add_argument('''pred_file''' , metavar='''pred.json''' , help='''Model predictions.''' ) parser.add_argument( '''--out-file''' , '''-o''' , metavar='''eval.json''' , help='''Write accuracy metrics to file (default is stdout).''' ) parser.add_argument( '''--na-prob-file''' , '''-n''' , metavar='''na_prob.json''' , help='''Model estimates of probability of no answer.''' ) parser.add_argument( '''--na-prob-thresh''' , '''-t''' , type=__lowerCAmelCase , default=1.0 , help='''Predict "" if no-answer probability exceeds this (default = 1.0).''' , ) parser.add_argument( '''--out-image-dir''' , '''-p''' , metavar='''out_images''' , default=__lowerCAmelCase , help='''Save precision-recall curves to directory.''' ) parser.add_argument('''--verbose''' , '''-v''' , action='''store_true''' ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def __magic_name__ ( __lowerCAmelCase : List[str] ) -> Union[str, Any]: __lowerCamelCase = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __lowerCamelCase = bool(qa['''answers''']['''text'''] ) return qid_to_has_ans def __magic_name__ ( __lowerCAmelCase : Dict ) -> Optional[Any]: def remove_articles(__lowerCAmelCase : Optional[int] ): return ARTICLES_REGEX.sub(''' ''' , __lowerCAmelCase ) def white_space_fix(__lowerCAmelCase : Optional[int] ): return " ".join(text.split() ) def remove_punc(__lowerCAmelCase : Union[str, Any] ): __lowerCamelCase = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(__lowerCAmelCase : Dict ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(__lowerCAmelCase ) ) ) ) def __magic_name__ ( __lowerCAmelCase : List[Any] ) -> Optional[int]: if not s: return [] return normalize_answer(__lowerCAmelCase ).split() def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple ) -> int: return int(normalize_answer(__lowerCAmelCase ) == normalize_answer(__lowerCAmelCase ) ) def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : Tuple ) -> str: __lowerCamelCase = get_tokens(__lowerCAmelCase ) __lowerCamelCase = get_tokens(__lowerCAmelCase ) __lowerCamelCase = collections.Counter(__lowerCAmelCase ) & collections.Counter(__lowerCAmelCase ) __lowerCamelCase = sum(common.values() ) if len(__lowerCAmelCase ) == 0 or len(__lowerCAmelCase ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 __lowerCamelCase = 1.0 * num_same / len(__lowerCAmelCase ) __lowerCamelCase = 1.0 * num_same / len(__lowerCAmelCase ) __lowerCamelCase = (2 * precision * recall) / (precision + recall) return fa def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : List[str] ) -> Optional[Any]: __lowerCamelCase = {} __lowerCamelCase = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __lowerCamelCase = qa['''id'''] __lowerCamelCase = [t for t in qa['''answers''']['''text'''] if normalize_answer(__lowerCAmelCase )] if not gold_answers: # For unanswerable questions, only correct answer is empty string __lowerCamelCase = [''''''] if qid not in preds: print(f'''Missing prediction for {qid}''' ) continue __lowerCamelCase = preds[qid] # Take max over all gold answers __lowerCamelCase = max(compute_exact(__lowerCAmelCase , __lowerCAmelCase ) for a in gold_answers ) __lowerCamelCase = max(compute_fa(__lowerCAmelCase , __lowerCAmelCase ) for a in gold_answers ) return exact_scores, fa_scores def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Union[str, Any] ) -> List[str]: __lowerCamelCase = {} for qid, s in scores.items(): __lowerCamelCase = na_probs[qid] > na_prob_thresh if pred_na: __lowerCamelCase = float(not qid_to_has_ans[qid] ) else: __lowerCamelCase = s return new_scores def __magic_name__ ( __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[Any]=None ) -> Union[str, Any]: if not qid_list: __lowerCamelCase = len(__lowerCAmelCase ) return collections.OrderedDict( [ ('''exact''', 100.0 * sum(exact_scores.values() ) / total), ('''f1''', 100.0 * sum(fa_scores.values() ) / total), ('''total''', total), ] ) else: __lowerCamelCase = len(__lowerCAmelCase ) return collections.OrderedDict( [ ('''exact''', 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ('''f1''', 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ('''total''', total), ] ) def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : str , __lowerCAmelCase : Optional[Any] ) -> int: for k in new_eval: __lowerCamelCase = new_eval[k] def __magic_name__ ( __lowerCAmelCase : Optional[int] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : Union[str, Any] ) -> Optional[Any]: plt.step(__lowerCAmelCase , __lowerCAmelCase , color='''b''' , alpha=0.2 , where='''post''' ) plt.fill_between(__lowerCAmelCase , __lowerCAmelCase , step='''post''' , alpha=0.2 , color='''b''' ) plt.xlabel('''Recall''' ) plt.ylabel('''Precision''' ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(__lowerCAmelCase ) plt.savefig(__lowerCAmelCase ) plt.clf() def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[Any]=None , __lowerCAmelCase : Tuple=None ) -> int: __lowerCamelCase = sorted(__lowerCAmelCase , key=lambda __lowerCAmelCase : na_probs[k] ) __lowerCamelCase = 0.0 __lowerCamelCase = 1.0 __lowerCamelCase = 0.0 __lowerCamelCase = [1.0] __lowerCamelCase = [0.0] __lowerCamelCase = 0.0 for i, qid in enumerate(__lowerCAmelCase ): if qid_to_has_ans[qid]: true_pos += scores[qid] __lowerCamelCase = true_pos / float(i + 1 ) __lowerCamelCase = true_pos / float(__lowerCAmelCase ) if i == len(__lowerCAmelCase ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(__lowerCAmelCase ) recalls.append(__lowerCAmelCase ) if out_image: plot_pr_curve(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) return {"ap": 100.0 * avg_prec} def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Tuple , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : List[Any] ) -> List[Any]: if out_image_dir and not os.path.exists(__lowerCAmelCase ): os.makedirs(__lowerCAmelCase ) __lowerCamelCase = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_exact.png''' ) , title='''Precision-Recall curve for Exact Match score''' , ) __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_f1.png''' ) , title='''Precision-Recall curve for F1 score''' , ) __lowerCamelCase = {k: float(__lowerCAmelCase ) for k, v in qid_to_has_ans.items()} __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_oracle.png''' ) , title='''Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)''' , ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_exact''' ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_f1''' ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_oracle''' ) def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Any , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : int ) -> Optional[Any]: if not qid_list: return __lowerCamelCase = [na_probs[k] for k in qid_list] __lowerCamelCase = np.ones_like(__lowerCAmelCase ) / float(len(__lowerCAmelCase ) ) plt.hist(__lowerCAmelCase , weights=__lowerCAmelCase , bins=20 , range=(0.0, 1.0) ) plt.xlabel('''Model probability of no-answer''' ) plt.ylabel('''Proportion of dataset''' ) plt.title(f'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(__lowerCAmelCase , f'''na_prob_hist_{name}.png''' ) ) plt.clf() def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Union[str, Any] ) -> Optional[int]: __lowerCamelCase = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) __lowerCamelCase = num_no_ans __lowerCamelCase = cur_score __lowerCamelCase = 0.0 __lowerCamelCase = sorted(__lowerCAmelCase , key=lambda __lowerCAmelCase : na_probs[k] ) for i, qid in enumerate(__lowerCAmelCase ): if qid not in scores: continue if qid_to_has_ans[qid]: __lowerCamelCase = scores[qid] else: if preds[qid]: __lowerCamelCase = -1 else: __lowerCamelCase = 0 cur_score += diff if cur_score > best_score: __lowerCamelCase = cur_score __lowerCamelCase = na_probs[qid] return 100.0 * best_score / len(__lowerCAmelCase ), best_thresh def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : int , __lowerCAmelCase : Optional[Any] ) -> int: __lowerCamelCase , __lowerCamelCase = find_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = find_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = best_exact __lowerCamelCase = exact_thresh __lowerCamelCase = best_fa __lowerCamelCase = fa_thresh def __magic_name__ ( ) -> Optional[int]: with open(OPTS.data_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) __lowerCamelCase = dataset_json['''data'''] with open(OPTS.pred_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) else: __lowerCamelCase = {k: 0.0 for k in preds} __lowerCamelCase = make_qid_to_has_ans(__lowerCAmelCase ) # maps qid to True/False __lowerCamelCase = [k for k, v in qid_to_has_ans.items() if v] __lowerCamelCase = [k for k, v in qid_to_has_ans.items() if not v] __lowerCamelCase , __lowerCamelCase = get_raw_scores(__lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = apply_no_ans_threshold(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.na_prob_thresh ) __lowerCamelCase = apply_no_ans_threshold(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.na_prob_thresh ) __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase ) if has_ans_qids: __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase , qid_list=__lowerCAmelCase ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''HasAns''' ) if no_ans_qids: __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase , qid_list=__lowerCAmelCase ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''NoAns''' ) if OPTS.na_prob_file: find_all_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir ) histogram_na_prob(__lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir , '''hasAns''' ) histogram_na_prob(__lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir , '''noAns''' ) if OPTS.out_file: with open(OPTS.out_file , '''w''' ) as f: json.dump(__lowerCAmelCase , __lowerCAmelCase ) else: print(json.dumps(__lowerCAmelCase , indent=2 ) ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Any = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt main()
270
0
"""simple docstring""" from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class SCREAMING_SNAKE_CASE_ : """simple docstring""" __lowercase : List[str] __lowercase : Optional[str] = None # Automatically constructed __lowercase : ClassVar[str] = "dict" __lowercase : ClassVar[Any] = None __lowercase : str = field(default='''Translation''' , init=__a , repr=__a ) def __call__( self): return pa.struct({lang: pa.string() for lang in sorted(self.languages)}) def snake_case_ ( self): from .features import Value return {k: Value("""string""") for k in sorted(self.languages)} @dataclass class SCREAMING_SNAKE_CASE_ : """simple docstring""" __lowercase : Optional[List] = None __lowercase : Optional[int] = None __lowercase : Optional[str] = None # Automatically constructed __lowercase : ClassVar[str] = "dict" __lowercase : ClassVar[Any] = None __lowercase : str = field(default='''TranslationVariableLanguages''' , init=__a , repr=__a ) def snake_case_ ( self): __SCREAMING_SNAKE_CASE = sorted(set(self.languages)) if self.languages else None __SCREAMING_SNAKE_CASE = len(self.languages) if self.languages else None def __call__( self): return pa.struct({"""language""": pa.list_(pa.string()), """translation""": pa.list_(pa.string())}) def snake_case_ ( self , lowerCAmelCase__): __SCREAMING_SNAKE_CASE = set(self.languages) if self.languages and set(lowerCAmelCase__) - lang_set: raise ValueError( f"Some languages in example ({', '.join(sorted(set(lowerCAmelCase__) - lang_set))}) are not in valid set ({', '.join(lowerCAmelCase__)}).") # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. __SCREAMING_SNAKE_CASE = [] for lang, text in translation_dict.items(): if isinstance(lowerCAmelCase__ , lowerCAmelCase__): translation_tuples.append((lang, text)) else: translation_tuples.extend([(lang, el) for el in text]) # Ensure translations are in ascending order by language code. __SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE = zip(*sorted(lowerCAmelCase__)) return {"language": languages, "translation": translations} def snake_case_ ( self): from .features import Sequence, Value return { "language": Sequence(Value("""string""")), "translation": Sequence(Value("""string""")), }
100
import math import os import re import sys import unittest from pathlib import Path from typing import Tuple from unittest.mock import patch from parameterized import parameterized from transformers.testing_utils import ( CaptureStderr, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, get_torch_dist_unique_port, require_apex, require_bitsandbytes, require_fairscale, require_torch, require_torch_gpu, require_torch_multi_gpu, require_torch_non_multi_gpu, slow, ) from transformers.trainer_callback import TrainerState from transformers.trainer_utils import set_seed SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.abspath(os.path.dirname(__file__)) with ExtendSysPath(F'{bindir}/../../examples/pytorch/translation'): from run_translation import main # noqa set_seed(42) SCREAMING_SNAKE_CASE__ : Any = "sshleifer/student_marian_en_ro_6_1" SCREAMING_SNAKE_CASE__ : Tuple = "sshleifer/tiny-mbart" @require_torch class lowerCAmelCase__ ( __lowercase ): def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple=False , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Optional[int]=True , ) -> Optional[int]: __lowerCamelCase = self.run_trainer( eval_steps=1 , max_len=12 , model_name=SCREAMING_SNAKE_CASE__ , num_train_epochs=1 , distributed=SCREAMING_SNAKE_CASE__ , extra_args_str=SCREAMING_SNAKE_CASE__ , predict_with_generate=SCREAMING_SNAKE_CASE__ , do_train=SCREAMING_SNAKE_CASE__ , do_eval=SCREAMING_SNAKE_CASE__ , do_predict=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = TrainerState.load_from_json(os.path.join(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history if not do_eval: return __lowerCamelCase = [log for log in logs if '''eval_loss''' in log.keys()] __lowerCamelCase = eval_metrics[0] if predict_with_generate: assert "eval_bleu" in first_step_stats __lowerCamelCase = eval_metrics[-1] assert isinstance(last_step_stats['''eval_bleu'''] , SCREAMING_SNAKE_CASE__ ) assert not math.isnan(float(last_step_stats['''eval_loss'''] ) ), "eval_loss must not be `nan`" @require_torch_non_multi_gpu def __A ( self : Optional[int] ) -> int: self.run_seqaseq_quick() @require_torch_multi_gpu def __A ( self : int ) -> List[str]: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ ) @require_torch_multi_gpu def __A ( self : Optional[Any] ) -> Tuple: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Dict ) -> Tuple: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp simple''' ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Optional[int] ) -> List[str]: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp simple --fp16''' ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Tuple ) -> Any: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp zero_dp_2''' , predict_with_generate=SCREAMING_SNAKE_CASE__ ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Dict ) -> Tuple: self.run_seqaseq_quick( distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp zero_dp_2 --fp16''' , predict_with_generate=SCREAMING_SNAKE_CASE__ ) @require_apex @require_torch_gpu def __A ( self : Union[str, Any] ) -> List[str]: # XXX: apex breaks the trainer if it's run twice e.g. run_seq2seq.main() from the same # program and it breaks other tests that run from the same pytest worker, therefore until this is # sorted out it must be run only in an external program, that is distributed=True in this # test and only under one or more gpus - if we want cpu will need to make a special test # # specifically to the problem traced it to self.optimizer.step() - if it's run 2nd time via # 2nd main() call it botches the future eval. # self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--fp16 --fp16_backend=apex''' ) # test 2nd time - was getting eval_loss': nan' # to reproduce the problem set distributed=False self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--fp16 --fp16_backend=apex''' ) @parameterized.expand(['''base''', '''low''', '''high''', '''mixed'''] ) @require_torch_multi_gpu def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[str] ) -> Optional[Any]: # as each sub-test is slow-ish split into multiple sub-tests to avoid CI timeout __lowerCamelCase = { # test with the default log_level - should be info and thus log info once '''base''': {'''extra_args_str''': '''''', '''n_matches''': 1}, # test with low log_level and log_level_replica - should be noisy on all processes # now the info string should appear twice on 2 processes '''low''': {'''extra_args_str''': '''--log_level debug --log_level_replica debug''', '''n_matches''': 2}, # test with high log_level and low log_level_replica # now the info string should appear once only on the replica '''high''': {'''extra_args_str''': '''--log_level error --log_level_replica debug''', '''n_matches''': 1}, # test with high log_level and log_level_replica - should be quiet on all processes '''mixed''': {'''extra_args_str''': '''--log_level error --log_level_replica error''', '''n_matches''': 0}, } __lowerCamelCase = experiments[experiment_id] __lowerCamelCase = {'''distributed''': True, '''predict_with_generate''': False, '''do_eval''': False, '''do_predict''': False} __lowerCamelCase = '''Running training''' with CaptureStderr() as cl: self.run_seqaseq_quick(**SCREAMING_SNAKE_CASE__ , extra_args_str=data['''extra_args_str'''] ) __lowerCamelCase = len(re.findall(SCREAMING_SNAKE_CASE__ , cl.err ) ) self.assertEqual(SCREAMING_SNAKE_CASE__ , data['''n_matches'''] ) @slow def __A ( self : Any ) -> Optional[Any]: __lowerCamelCase = self.run_trainer( eval_steps=2 , max_len=1_28 , model_name=SCREAMING_SNAKE_CASE__ , learning_rate=3e-4 , num_train_epochs=10 , distributed=SCREAMING_SNAKE_CASE__ , ) # Check metrics __lowerCamelCase = TrainerState.load_from_json(os.path.join(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history __lowerCamelCase = [log for log in logs if '''eval_loss''' in log.keys()] __lowerCamelCase = eval_metrics[0] __lowerCamelCase = eval_metrics[-1] assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing" assert isinstance(last_step_stats['''eval_bleu'''] , SCREAMING_SNAKE_CASE__ ) # test if do_predict saves generations and metrics __lowerCamelCase = os.listdir(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = {os.path.basename(SCREAMING_SNAKE_CASE__ ) for p in contents} assert "generated_predictions.txt" in contents assert "predict_results.json" in contents @slow @require_bitsandbytes def __A ( self : Optional[int] ) -> str: from transformers.training_args import OptimizerNames def train_and_return_metrics(SCREAMING_SNAKE_CASE__ : str ) -> Tuple[int, float]: __lowerCamelCase = '''--skip_memory_metrics 0''' __lowerCamelCase = self.run_trainer( max_len=1_28 , model_name=SCREAMING_SNAKE_CASE__ , learning_rate=3e-4 , num_train_epochs=1 , optim=SCREAMING_SNAKE_CASE__ , distributed=SCREAMING_SNAKE_CASE__ , extra_args_str=SCREAMING_SNAKE_CASE__ , do_eval=SCREAMING_SNAKE_CASE__ , do_predict=SCREAMING_SNAKE_CASE__ , n_gpus_to_use=1 , ) # Check metrics __lowerCamelCase = TrainerState.load_from_json(Path(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history __lowerCamelCase = int(logs[0]['''train_mem_gpu_peaked_delta'''] / 2**20 ) __lowerCamelCase = int(logs[0]['''train_mem_gpu_alloc_delta'''] / 2**20 ) __lowerCamelCase = logs[0]['''train_loss'''] return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = train_and_return_metrics(OptimizerNames.ADAMW_BNB.value ) __lowerCamelCase = gpu_alloc_mem_orig - gpu_alloc_mem_bnb __lowerCamelCase = gpu_peak_mem_orig + gpu_alloc_mem_orig __lowerCamelCase = gpu_peak_mem_bnb + gpu_alloc_mem_bnb __lowerCamelCase = gpu_total_mem_orig - gpu_total_mem_bnb # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized # in 2 bytes and the diff in optim memory usage is derived as so: # # - normal 25*8=~200MB (8 bytes per param) # - bnb 25*2= ~50MB (2 bytes per param) # # Thus we should expect ~150MB total memory saved. # # Peak memory should be the same - the total should be different by about that same margin # # After leaving a small margin to accommodate for differences between gpus let's check # that we have at least 120MB in savings __lowerCamelCase = 1_20 # uncomment the following if this test starts failing - requires py38 for a new print feature # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB") # print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB") # print(f"{gpu_alloc_mem_diff=}MB") # print(f"{gpu_peak_mem_diff=}MB") # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB") # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB") self.assertGreater( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got''' f''' a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and''' f''' gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB''' , ) self.assertGreater( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''should use ~150MB less total gpu memory with BNB, compared to without it for this model but got''' f''' a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and''' f''' gpu_total_mem_bnb={gpu_total_mem_bnb}MB''' , ) self.assertEqual( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , f'''loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}''' ) def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float = 3e-3 , SCREAMING_SNAKE_CASE__ : str = "adafactor" , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : int = None , ) -> List[Any]: __lowerCamelCase = self.test_file_dir / '''../fixtures/tests_samples/wmt_en_ro''' __lowerCamelCase = self.get_auto_remove_tmp_dir() __lowerCamelCase = f''' --model_name_or_path {model_name} --train_file {data_dir}/train.json --validation_file {data_dir}/val.json --test_file {data_dir}/test.json --output_dir {output_dir} --overwrite_output_dir --max_train_samples 8 --max_source_length {max_len} --max_target_length {max_len} --do_train --num_train_epochs {str(SCREAMING_SNAKE_CASE__ )} --per_device_train_batch_size 4 --learning_rate {learning_rate} --warmup_steps 8 --logging_steps 0 --logging_strategy no --save_steps {str(SCREAMING_SNAKE_CASE__ )} --group_by_length --label_smoothing_factor 0.1 --target_lang ro_RO --source_lang en_XX '''.split() __lowerCamelCase = f''' --do_eval --per_device_eval_batch_size 4 --max_eval_samples 8 --val_max_target_length {max_len} --evaluation_strategy steps --eval_steps {str(SCREAMING_SNAKE_CASE__ )} '''.split() __lowerCamelCase = ''' --do_predict '''.split() __lowerCamelCase = [] if do_train: args += args_train if do_eval: args += args_eval if do_predict: args += args_predict if predict_with_generate: args += "--predict_with_generate".split() if do_train: if optim == "adafactor": args += "--adafactor".split() else: args += f'''--optim {optim}'''.split() if extra_args_str is not None: args += extra_args_str.split() if distributed: if n_gpus_to_use is None: __lowerCamelCase = get_gpu_count() __lowerCamelCase = get_torch_dist_unique_port() __lowerCamelCase = f''' -m torch.distributed.run --nproc_per_node={n_gpus_to_use} --master_port={master_port} {self.examples_dir_str}/pytorch/translation/run_translation.py '''.split() __lowerCamelCase = [sys.executable] + distributed_args + args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(SCREAMING_SNAKE_CASE__ , env=self.get_env() ) else: __lowerCamelCase = ['''run_translation.py'''] + args with patch.object(SCREAMING_SNAKE_CASE__ , '''argv''' , SCREAMING_SNAKE_CASE__ ): main() return output_dir
270
0
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 lowercase ( SCREAMING_SNAKE_CASE__ ): def __init__( self ,A__ ,A__ ,A__ = None ,A__ = None ,A__ = False ,**A__ ,): super().__init__(features=A__ ,cache_dir=A__ ,keep_in_memory=A__ ,**A__) lowercase = Sql( cache_dir=A__ ,features=A__ ,sql=A__ ,con=A__ ,**A__ ,) def A__ ( self): lowercase = None lowercase = None lowercase = None lowercase = None self.builder.download_and_prepare( download_config=A__ ,download_mode=A__ ,verification_mode=A__ ,base_path=A__ ,) # Build dataset for splits lowercase = self.builder.as_dataset( split='''train''' ,verification_mode=A__ ,in_memory=self.keep_in_memory) return dataset class lowercase : def __init__( self ,A__ ,A__ ,A__ ,A__ = None ,A__ = None ,**A__ ,): if num_proc is not None and num_proc <= 0: raise ValueError(f'num_proc {num_proc} must be an integer > 0.') lowercase = dataset lowercase = name lowercase = con lowercase = batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE lowercase = num_proc lowercase = to_sql_kwargs def A__ ( self): lowercase = self.to_sql_kwargs.pop('''sql''' ,A__) lowercase = self.to_sql_kwargs.pop('''con''' ,A__) lowercase = self.to_sql_kwargs.pop('''index''' ,A__) lowercase = self._write(index=A__ ,**self.to_sql_kwargs) return written def A__ ( self ,A__): lowercase , lowercase , lowercase = args lowercase = {**to_sql_kwargs, '''if_exists''': '''append'''} if offset > 0 else to_sql_kwargs lowercase = query_table( table=self.dataset.data ,key=slice(A__ ,offset + self.batch_size) ,indices=self.dataset._indices ,) lowercase = batch.to_pandas() lowercase = df.to_sql(self.name ,self.con ,index=A__ ,**A__) return num_rows or len(A__) def A__ ( self ,A__ ,**A__): lowercase = 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: lowercase , lowercase = 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 ,A__ ,A__)] ,) ,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
101
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING SCREAMING_SNAKE_CASE__ : Dict = { "facebook/mask2former-swin-small-coco-instance": ( "https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json" ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) class lowerCAmelCase__ ( __lowercase ): a__ : Any = """mask2former""" a__ : Dict = ["""swin"""] a__ : Any = {"""hidden_size""": """hidden_dim"""} def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Optional[Dict] = None , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 10_24 , SCREAMING_SNAKE_CASE__ : str = "relu" , SCREAMING_SNAKE_CASE__ : int = 6 , SCREAMING_SNAKE_CASE__ : int = 10 , SCREAMING_SNAKE_CASE__ : int = 8 , SCREAMING_SNAKE_CASE__ : float = 0.0 , SCREAMING_SNAKE_CASE__ : int = 20_48 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : int = 4 , SCREAMING_SNAKE_CASE__ : int = 2_55 , SCREAMING_SNAKE_CASE__ : int = 1_00 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 2.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : int = 1_25_44 , SCREAMING_SNAKE_CASE__ : float = 3.0 , SCREAMING_SNAKE_CASE__ : float = 0.75 , SCREAMING_SNAKE_CASE__ : float = 0.02 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 16, 32] , SCREAMING_SNAKE_CASE__ : bool = None , **SCREAMING_SNAKE_CASE__ : Tuple , ) -> str: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.''' ) __lowerCamelCase = CONFIG_MAPPING['''swin''']( image_size=2_24 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=SCREAMING_SNAKE_CASE__ , out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] , ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = backbone_config.pop('''model_type''' ) __lowerCamelCase = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase = config_class.from_dict(SCREAMING_SNAKE_CASE__ ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( f'''Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. ''' f'''Supported model types: {','.join(self.backbones_supported )}''' ) __lowerCamelCase = backbone_config __lowerCamelCase = feature_size __lowerCamelCase = mask_feature_size __lowerCamelCase = hidden_dim __lowerCamelCase = encoder_feedforward_dim __lowerCamelCase = activation_function __lowerCamelCase = encoder_layers __lowerCamelCase = decoder_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = dropout __lowerCamelCase = dim_feedforward __lowerCamelCase = pre_norm __lowerCamelCase = enforce_input_projection __lowerCamelCase = common_stride __lowerCamelCase = ignore_value __lowerCamelCase = num_queries __lowerCamelCase = no_object_weight __lowerCamelCase = class_weight __lowerCamelCase = mask_weight __lowerCamelCase = dice_weight __lowerCamelCase = train_num_points __lowerCamelCase = oversample_ratio __lowerCamelCase = importance_sample_ratio __lowerCamelCase = init_std __lowerCamelCase = init_xavier_std __lowerCamelCase = use_auxiliary_loss __lowerCamelCase = feature_strides __lowerCamelCase = output_auxiliary_logits __lowerCamelCase = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__ ) @classmethod def __A ( cls : Any , SCREAMING_SNAKE_CASE__ : PretrainedConfig , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: return cls( backbone_config=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def __A ( self : Any ) -> Dict[str, any]: __lowerCamelCase = copy.deepcopy(self.__dict__ ) __lowerCamelCase = self.backbone_config.to_dict() __lowerCamelCase = self.__class__.model_type return output
270
0
"""simple docstring""" import inspect import os import unittest import torch import accelerate from accelerate import debug_launcher from accelerate.test_utils import ( execute_subprocess_async, require_cpu, require_huggingface_suite, require_multi_gpu, require_single_gpu, ) from accelerate.utils import patch_environment @require_huggingface_suite class _UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : int = inspect.getfile(accelerate.test_utils ) __snake_case : List[Any] = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''external_deps''', '''test_metrics.py'''] ) from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401 __snake_case : Any = test_metrics @require_cpu def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' debug_launcher(self.test_metrics.main , num_processes=1 ) @require_cpu def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' debug_launcher(self.test_metrics.main ) @require_single_gpu def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' self.test_metrics.main() @require_multi_gpu def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' print(f"""Found {torch.cuda.device_count()} devices.""" ) __snake_case : str = ['''torchrun''', f"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(a_ , env=os.environ.copy() )
102
import os def __magic_name__ ( ) -> str: __lowerCamelCase = os.path.join(os.path.dirname(__lowerCAmelCase ) , '''num.txt''' ) with open(__lowerCAmelCase ) as file_hand: return str(sum(int(__lowerCAmelCase ) for line in file_hand ) )[:10] if __name__ == "__main__": print(solution())
270
0
from __future__ import annotations def UpperCamelCase( __UpperCamelCase : str ): return [ord(__UpperCamelCase ) - 96 for elem in plain] def UpperCamelCase( __UpperCamelCase : list[int] ): return "".join(chr(elem + 96 ) for elem in encoded ) def UpperCamelCase( ): lowerCAmelCase_ : Dict = encode(input('''-> ''' ).strip().lower() ) print('''Encoded: ''' ,__UpperCamelCase ) print('''Decoded:''' ,decode(__UpperCamelCase ) ) if __name__ == "__main__": main()
103
import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available SCREAMING_SNAKE_CASE__ : Optional[int] = logging.getLogger(__name__) @dataclass class lowerCAmelCase__ : a__ : str a__ : List[str] a__ : Optional[List[str]] @dataclass class lowerCAmelCase__ : a__ : List[int] a__ : List[int] a__ : Optional[List[int]] = None a__ : Optional[List[int]] = None class lowerCAmelCase__ ( __lowercase ): a__ : Optional[Any] = """train""" a__ : Optional[int] = """dev""" a__ : Dict = """test""" class lowerCAmelCase__ : @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[Split, str] ) -> List[InputExample]: raise NotImplementedError @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : str ) -> List[str]: raise NotImplementedError @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : List[InputExample] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : List[str]="[CLS]" , SCREAMING_SNAKE_CASE__ : Tuple=1 , SCREAMING_SNAKE_CASE__ : str="[SEP]" , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False , SCREAMING_SNAKE_CASE__ : Tuple=0 , SCREAMING_SNAKE_CASE__ : int=0 , SCREAMING_SNAKE_CASE__ : str=-1_00 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE__ : List[Any]=True , ) -> List[InputFeatures]: __lowerCamelCase = {label: i for i, label in enumerate(SCREAMING_SNAKE_CASE__ )} __lowerCamelCase = [] for ex_index, example in enumerate(SCREAMING_SNAKE_CASE__ ): if ex_index % 1_00_00 == 0: logger.info('''Writing example %d of %d''' , SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = [] __lowerCamelCase = [] for word, label in zip(example.words , example.labels ): __lowerCamelCase = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(SCREAMING_SNAKE_CASE__ ) > 0: tokens.extend(SCREAMING_SNAKE_CASE__ ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(SCREAMING_SNAKE_CASE__ ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. __lowerCamelCase = tokenizer.num_special_tokens_to_add() if len(SCREAMING_SNAKE_CASE__ ) > max_seq_length - special_tokens_count: __lowerCamelCase = tokens[: (max_seq_length - special_tokens_count)] __lowerCamelCase = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] __lowerCamelCase = [sequence_a_segment_id] * len(SCREAMING_SNAKE_CASE__ ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: __lowerCamelCase = [cls_token] + tokens __lowerCamelCase = [pad_token_label_id] + label_ids __lowerCamelCase = [cls_token_segment_id] + segment_ids __lowerCamelCase = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. __lowerCamelCase = [1 if mask_padding_with_zero else 0] * len(SCREAMING_SNAKE_CASE__ ) # Zero-pad up to the sequence length. __lowerCamelCase = max_seq_length - len(SCREAMING_SNAKE_CASE__ ) if pad_on_left: __lowerCamelCase = ([pad_token] * padding_length) + input_ids __lowerCamelCase = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask __lowerCamelCase = ([pad_token_segment_id] * padding_length) + segment_ids __lowerCamelCase = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length if ex_index < 5: logger.info('''*** Example ***''' ) logger.info('''guid: %s''' , example.guid ) logger.info('''tokens: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in tokens] ) ) logger.info('''input_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in input_ids] ) ) logger.info('''input_mask: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in input_mask] ) ) logger.info('''segment_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in segment_ids] ) ) logger.info('''label_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: __lowerCamelCase = None features.append( InputFeatures( input_ids=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , label_ids=SCREAMING_SNAKE_CASE__ ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class lowerCAmelCase__ ( __lowercase ): a__ : List[InputFeatures] a__ : int = nn.CrossEntropyLoss().ignore_index def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : TokenClassificationTask , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False , SCREAMING_SNAKE_CASE__ : Split = Split.train , ) -> Union[str, Any]: # Load data features from cache or dataset file __lowerCamelCase = os.path.join( SCREAMING_SNAKE_CASE__ , '''cached_{}_{}_{}'''.format(mode.value , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE__ ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. __lowerCamelCase = cached_features_file + '''.lock''' with FileLock(SCREAMING_SNAKE_CASE__ ): if os.path.exists(SCREAMING_SNAKE_CASE__ ) and not overwrite_cache: logger.info(f'''Loading features from cached file {cached_features_file}''' ) __lowerCamelCase = torch.load(SCREAMING_SNAKE_CASE__ ) else: logger.info(f'''Creating features from dataset file at {data_dir}''' ) __lowerCamelCase = token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # TODO clean up all this to leverage built-in features of tokenizers __lowerCamelCase = token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f'''Saving features into cached file {cached_features_file}''' ) torch.save(self.features , SCREAMING_SNAKE_CASE__ ) def __len__( self : Dict ) -> str: return len(self.features ) def __getitem__( self : Any , SCREAMING_SNAKE_CASE__ : Dict ) -> InputFeatures: return self.features[i] if is_tf_available(): import tensorflow as tf class lowerCAmelCase__ : a__ : List[InputFeatures] a__ : int = -100 def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : TokenClassificationTask , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Split = Split.train , ) -> List[Any]: __lowerCamelCase = token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # TODO clean up all this to leverage built-in features of tokenizers __lowerCamelCase = token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: __lowerCamelCase = tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa}, tf.intaa) , ( {'''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: __lowerCamelCase = tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa}, tf.intaa) , ( { '''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] ), '''token_type_ids''': tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __A ( self : Union[str, Any] ) -> Union[str, Any]: __lowerCamelCase = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self : List[Any] ) -> Any: return len(self.features ) def __getitem__( self : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> InputFeatures: return self.features[i]
270
0
'''simple docstring''' from dataclasses import dataclass from typing import Optional, Tuple, Union import torch import torch.nn as nn from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps from .modeling_utils import ModelMixin from .unet_ad_blocks import get_down_block, get_mid_block, get_out_block, get_up_block @dataclass class lowercase_ (lowerCamelCase__ ): """simple docstring""" SCREAMING_SNAKE_CASE : torch.FloatTensor class lowercase_ (lowerCamelCase__ , lowerCamelCase__ ): """simple docstring""" @register_to_config def __init__( self : List[str] ,lowercase__ : int = 6_5_5_3_6 ,lowercase__ : Optional[int] = None ,lowercase__ : int = 2 ,lowercase__ : int = 2 ,lowercase__ : int = 0 ,lowercase__ : str = "fourier" ,lowercase__ : bool = True ,lowercase__ : bool = False ,lowercase__ : float = 0.0 ,lowercase__ : Tuple[str] = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D") ,lowercase__ : Tuple[str] = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip") ,lowercase__ : Tuple[str] = "UNetMidBlock1D" ,lowercase__ : str = None ,lowercase__ : Tuple[int] = (3_2, 3_2, 6_4) ,lowercase__ : str = None ,lowercase__ : int = 8 ,lowercase__ : int = 1 ,lowercase__ : bool = False ,): super().__init__() __lowercase = sample_size # time if time_embedding_type == "fourier": __lowercase = GaussianFourierProjection( embedding_size=8 ,set_W_to_weight=lowercase__ ,log=lowercase__ ,flip_sin_to_cos=lowercase__ ) __lowercase = 2 * block_out_channels[0] elif time_embedding_type == "positional": __lowercase = Timesteps( block_out_channels[0] ,flip_sin_to_cos=lowercase__ ,downscale_freq_shift=lowercase__ ) __lowercase = block_out_channels[0] if use_timestep_embedding: __lowercase = block_out_channels[0] * 4 __lowercase = TimestepEmbedding( in_channels=lowercase__ ,time_embed_dim=lowercase__ ,act_fn=lowercase__ ,out_dim=block_out_channels[0] ,) __lowercase = nn.ModuleList([] ) __lowercase = None __lowercase = nn.ModuleList([] ) __lowercase = None # down __lowercase = in_channels for i, down_block_type in enumerate(lowercase__ ): __lowercase = output_channel __lowercase = block_out_channels[i] if i == 0: input_channel += extra_in_channels __lowercase = i == len(lowercase__ ) - 1 __lowercase = get_down_block( lowercase__ ,num_layers=lowercase__ ,in_channels=lowercase__ ,out_channels=lowercase__ ,temb_channels=block_out_channels[0] ,add_downsample=not is_final_block or downsample_each_block ,) self.down_blocks.append(lowercase__ ) # mid __lowercase = get_mid_block( lowercase__ ,in_channels=block_out_channels[-1] ,mid_channels=block_out_channels[-1] ,out_channels=block_out_channels[-1] ,embed_dim=block_out_channels[0] ,num_layers=lowercase__ ,add_downsample=lowercase__ ,) # up __lowercase = list(reversed(lowercase__ ) ) __lowercase = reversed_block_out_channels[0] if out_block_type is None: __lowercase = out_channels else: __lowercase = block_out_channels[0] for i, up_block_type in enumerate(lowercase__ ): __lowercase = output_channel __lowercase = ( reversed_block_out_channels[i + 1] if i < len(lowercase__ ) - 1 else final_upsample_channels ) __lowercase = i == len(lowercase__ ) - 1 __lowercase = get_up_block( lowercase__ ,num_layers=lowercase__ ,in_channels=lowercase__ ,out_channels=lowercase__ ,temb_channels=block_out_channels[0] ,add_upsample=not is_final_block ,) self.up_blocks.append(lowercase__ ) __lowercase = output_channel # out __lowercase = norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4 ,3_2 ) __lowercase = get_out_block( out_block_type=lowercase__ ,num_groups_out=lowercase__ ,embed_dim=block_out_channels[0] ,out_channels=lowercase__ ,act_fn=lowercase__ ,fc_dim=block_out_channels[-1] // 4 ,) def SCREAMING_SNAKE_CASE ( self : Any ,lowercase__ : torch.FloatTensor ,lowercase__ : Union[torch.Tensor, float, int] ,lowercase__ : bool = True ,): __lowercase = timestep if not torch.is_tensor(lowercase__ ): __lowercase = torch.tensor([timesteps] ,dtype=torch.long ,device=sample.device ) elif torch.is_tensor(lowercase__ ) and len(timesteps.shape ) == 0: __lowercase = timesteps[None].to(sample.device ) __lowercase = self.time_proj(lowercase__ ) if self.config.use_timestep_embedding: __lowercase = self.time_mlp(lowercase__ ) else: __lowercase = timestep_embed[..., None] __lowercase = timestep_embed.repeat([1, 1, sample.shape[2]] ).to(sample.dtype ) __lowercase = timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:]) ) # 2. down __lowercase = () for downsample_block in self.down_blocks: __lowercase , __lowercase = downsample_block(hidden_states=lowercase__ ,temb=lowercase__ ) down_block_res_samples += res_samples # 3. mid if self.mid_block: __lowercase = self.mid_block(lowercase__ ,lowercase__ ) # 4. up for i, upsample_block in enumerate(self.up_blocks ): __lowercase = down_block_res_samples[-1:] __lowercase = down_block_res_samples[:-1] __lowercase = upsample_block(lowercase__ ,res_hidden_states_tuple=lowercase__ ,temb=lowercase__ ) # 5. post-process if self.out_block: __lowercase = self.out_block(lowercase__ ,lowercase__ ) if not return_dict: return (sample,) return UNetaDOutput(sample=lowercase__ )
104
from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class lowerCAmelCase__ ( __lowercase ): def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : NestedDataStructureLike[PathLike] , SCREAMING_SNAKE_CASE__ : Optional[NamedSplit] = None , SCREAMING_SNAKE_CASE__ : Optional[Features] = None , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[int] = None , **SCREAMING_SNAKE_CASE__ : str , ) -> Union[str, Any]: super().__init__( SCREAMING_SNAKE_CASE__ , split=SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ , keep_in_memory=SCREAMING_SNAKE_CASE__ , streaming=SCREAMING_SNAKE_CASE__ , num_proc=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = path_or_paths if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else {self.split: path_or_paths} __lowerCamelCase = Text( cache_dir=SCREAMING_SNAKE_CASE__ , data_files=SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def __A ( self : int ) -> Dict: # Build iterable dataset if self.streaming: __lowerCamelCase = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None self.builder.download_and_prepare( download_config=SCREAMING_SNAKE_CASE__ , download_mode=SCREAMING_SNAKE_CASE__ , verification_mode=SCREAMING_SNAKE_CASE__ , base_path=SCREAMING_SNAKE_CASE__ , num_proc=self.num_proc , ) __lowerCamelCase = self.builder.as_dataset( split=self.split , verification_mode=SCREAMING_SNAKE_CASE__ , in_memory=self.keep_in_memory ) return dataset
270
0
"""simple docstring""" import argparse import os import sys from unittest.mock import patch import pytorch_lightning as pl import timeout_decorator import torch from distillation import SummarizationDistiller, distill_main from finetune import SummarizationModule, main from transformers import MarianMTModel from transformers.file_utils import cached_path from transformers.testing_utils import TestCasePlus, require_torch_gpu, slow from utils import load_json a : Tuple = '''sshleifer/mar_enro_6_3_student''' class __UpperCamelCase ( a__ ): def __a ( self ) -> Optional[Any]: super().setUp() a : Any = cached_path( "https://cdn-datasets.huggingface.co/translation/wmt_en_ro-tr40k-va0.5k-te0.5k.tar.gz" , extract_compressed_file=lowerCAmelCase__ , ) a : List[Any] = f"""{data_cached}/wmt_en_ro-tr40k-va0.5k-te0.5k""" @slow @require_torch_gpu def __a ( self ) -> List[Any]: MarianMTModel.from_pretrained(lowerCAmelCase__ ) @slow @require_torch_gpu def __a ( self ) -> List[str]: a : Optional[int] = { "$MAX_LEN": 64, "$BS": 64, "$GAS": 1, "$ENRO_DIR": self.data_dir, "facebook/mbart-large-cc25": MARIAN_MODEL, # "val_check_interval=0.25": "val_check_interval=1.0", "--learning_rate=3e-5": "--learning_rate 3e-4", "--num_train_epochs 6": "--num_train_epochs 1", } # Clean up bash script a : str = (self.test_file_dir / "train_mbart_cc25_enro.sh").open().read().split("finetune.py" )[1].strip() a : int = bash_script.replace("\\\n" , "" ).strip().replace("\"$@\"" , "" ) for k, v in env_vars_to_replace.items(): a : int = bash_script.replace(lowerCAmelCase__ , str(lowerCAmelCase__ ) ) a : Any = self.get_auto_remove_tmp_dir() # bash_script = bash_script.replace("--fp16 ", "") a : List[str] = f""" --output_dir {output_dir} --tokenizer_name Helsinki-NLP/opus-mt-en-ro --sortish_sampler --do_predict --gpus 1 --freeze_encoder --n_train 40000 --n_val 500 --n_test 500 --fp16_opt_level O1 --num_sanity_val_steps 0 --eval_beams 2 """.split() # XXX: args.gpus > 1 : handle multi_gpu in the future a : Dict = ["finetune.py"] + bash_script.split() + args with patch.object(lowerCAmelCase__ , "argv" , lowerCAmelCase__ ): a : List[Any] = argparse.ArgumentParser() a : Dict = pl.Trainer.add_argparse_args(lowerCAmelCase__ ) a : List[str] = SummarizationModule.add_model_specific_args(lowerCAmelCase__ , os.getcwd() ) a : str = parser.parse_args() a : Union[str, Any] = main(lowerCAmelCase__ ) # Check metrics a : List[str] = load_json(model.metrics_save_path ) a : Optional[int] = metrics["val"][0] a : Dict = metrics["val"][-1] self.assertEqual(len(metrics["val"] ) , (args.max_epochs / args.val_check_interval) ) assert isinstance(last_step_stats[f"""val_avg_{model.val_metric}"""] , lowerCAmelCase__ ) self.assertGreater(last_step_stats["val_avg_gen_time"] , 0.01 ) # model hanging on generate. Maybe bad config was saved. (XXX: old comment/assert?) self.assertLessEqual(last_step_stats["val_avg_gen_time"] , 1.0 ) # test learning requirements: # 1. BLEU improves over the course of training by more than 2 pts self.assertGreater(last_step_stats["val_avg_bleu"] - first_step_stats["val_avg_bleu"] , 2 ) # 2. BLEU finishes above 17 self.assertGreater(last_step_stats["val_avg_bleu"] , 17 ) # 3. test BLEU and val BLEU within ~1.1 pt. self.assertLess(abs(metrics["val"][-1]["val_avg_bleu"] - metrics["test"][-1]["test_avg_bleu"] ) , 1.1 ) # check lightning ckpt can be loaded and has a reasonable statedict a : int = os.listdir(lowerCAmelCase__ ) a : Tuple = [x for x in contents if x.endswith(".ckpt" )][0] a : Optional[Any] = os.path.join(args.output_dir , lowerCAmelCase__ ) a : Any = torch.load(lowerCAmelCase__ , map_location="cpu" ) a : Dict = "model.model.decoder.layers.0.encoder_attn_layer_norm.weight" assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: a : Dict = {os.path.basename(lowerCAmelCase__ ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics["test"] ) == 1 class __UpperCamelCase ( a__ ): @timeout_decorator.timeout(600 ) @slow @require_torch_gpu def __a ( self ) -> Union[str, Any]: a : int = f"""{self.test_file_dir_str}/test_data/wmt_en_ro""" a : Optional[Any] = { "--fp16_opt_level=O1": "", "$MAX_LEN": 128, "$BS": 16, "$GAS": 1, "$ENRO_DIR": data_dir, "$m": "sshleifer/student_marian_en_ro_6_1", "val_check_interval=0.25": "val_check_interval=1.0", } # Clean up bash script a : Any = ( (self.test_file_dir / "distil_marian_no_teacher.sh").open().read().split("distillation.py" )[1].strip() ) a : Union[str, Any] = bash_script.replace("\\\n" , "" ).strip().replace("\"$@\"" , "" ) a : Any = bash_script.replace("--fp16 " , " " ) for k, v in env_vars_to_replace.items(): a : Dict = bash_script.replace(lowerCAmelCase__ , str(lowerCAmelCase__ ) ) a : int = self.get_auto_remove_tmp_dir() a : Union[str, Any] = bash_script.replace("--fp16" , "" ) a : Optional[int] = 6 a : str = ( ["distillation.py"] + bash_script.split() + [ f"""--output_dir={output_dir}""", "--gpus=1", "--learning_rate=1e-3", f"""--num_train_epochs={epochs}""", "--warmup_steps=10", "--val_check_interval=1.0", "--do_predict", ] ) with patch.object(lowerCAmelCase__ , "argv" , lowerCAmelCase__ ): a : int = argparse.ArgumentParser() a : Optional[int] = pl.Trainer.add_argparse_args(lowerCAmelCase__ ) a : Tuple = SummarizationDistiller.add_model_specific_args(lowerCAmelCase__ , os.getcwd() ) a : List[str] = parser.parse_args() # assert args.gpus == gpus THIS BREAKS for multi_gpu a : Optional[int] = distill_main(lowerCAmelCase__ ) # Check metrics a : Tuple = load_json(model.metrics_save_path ) a : Union[str, Any] = metrics["val"][0] a : List[Any] = metrics["val"][-1] assert len(metrics["val"] ) >= (args.max_epochs / args.val_check_interval) # +1 accounts for val_sanity_check assert last_step_stats["val_avg_gen_time"] >= 0.01 assert first_step_stats["val_avg_bleu"] < last_step_stats["val_avg_bleu"] # model learned nothing assert 1.0 >= last_step_stats["val_avg_gen_time"] # model hanging on generate. Maybe bad config was saved. assert isinstance(last_step_stats[f"""val_avg_{model.val_metric}"""] , lowerCAmelCase__ ) # check lightning ckpt can be loaded and has a reasonable statedict a : List[str] = os.listdir(lowerCAmelCase__ ) a : Optional[Any] = [x for x in contents if x.endswith(".ckpt" )][0] a : Optional[int] = os.path.join(args.output_dir , lowerCAmelCase__ ) a : Optional[Any] = torch.load(lowerCAmelCase__ , map_location="cpu" ) a : int = "model.model.decoder.layers.0.encoder_attn_layer_norm.weight" assert expected_key in ckpt["state_dict"] assert ckpt["state_dict"]["model.model.decoder.layers.0.encoder_attn_layer_norm.weight"].dtype == torch.floataa # TODO: turn on args.do_predict when PL bug fixed. if args.do_predict: a : Optional[int] = {os.path.basename(lowerCAmelCase__ ) for p in contents} assert "test_generations.txt" in contents assert "test_results.txt" in contents # assert len(metrics["val"]) == desired_n_evals assert len(metrics["test"] ) == 1
105
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(">=", "4.25.0")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
270
0
"""simple docstring""" from .integrations import ( is_optuna_available, is_ray_available, is_sigopt_available, is_wandb_available, run_hp_search_optuna, run_hp_search_ray, run_hp_search_sigopt, run_hp_search_wandb, ) from .trainer_utils import ( HPSearchBackend, default_hp_space_optuna, default_hp_space_ray, default_hp_space_sigopt, default_hp_space_wandb, ) from .utils import logging __UpperCamelCase : Optional[Any] = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE : """simple docstring""" lowercase__ = 42 lowercase__ = None @staticmethod def __lowerCAmelCase ( ): raise NotImplementedError def __lowerCAmelCase ( self : List[Any] ,lowercase_ : List[Any] ,lowercase_ : int ,lowercase_ : str ,**lowercase_ : List[str] ): raise NotImplementedError def __lowerCAmelCase ( self : int ,lowercase_ : int ): raise NotImplementedError def __lowerCAmelCase ( self : List[str] ): if not self.is_available(): raise RuntimeError( F'You picked the {self.name} backend, but it is not installed. Run {self.pip_install()}.' ) @classmethod def __lowerCAmelCase ( cls : str ): return F'`pip install {cls.pip_package or cls.name}`' class SCREAMING_SNAKE_CASE ( a_ ): """simple docstring""" lowercase__ = "optuna" @staticmethod def __lowerCAmelCase ( ): return is_optuna_available() def __lowerCAmelCase ( self : Any ,lowercase_ : List[str] ,lowercase_ : int ,lowercase_ : str ,**lowercase_ : Any ): return run_hp_search_optuna(lowercase_ ,lowercase_ ,lowercase_ ,**lowercase_ ) def __lowerCAmelCase ( self : int ,lowercase_ : List[Any] ): return default_hp_space_optuna(lowercase_ ) class SCREAMING_SNAKE_CASE ( a_ ): """simple docstring""" lowercase__ = "ray" lowercase__ = "'ray[tune]'" @staticmethod def __lowerCAmelCase ( ): return is_ray_available() def __lowerCAmelCase ( self : str ,lowercase_ : int ,lowercase_ : int ,lowercase_ : str ,**lowercase_ : str ): return run_hp_search_ray(lowercase_ ,lowercase_ ,lowercase_ ,**lowercase_ ) def __lowerCAmelCase ( self : Dict ,lowercase_ : Tuple ): return default_hp_space_ray(lowercase_ ) class SCREAMING_SNAKE_CASE ( a_ ): """simple docstring""" lowercase__ = "sigopt" @staticmethod def __lowerCAmelCase ( ): return is_sigopt_available() def __lowerCAmelCase ( self : Tuple ,lowercase_ : List[str] ,lowercase_ : int ,lowercase_ : str ,**lowercase_ : List[Any] ): return run_hp_search_sigopt(lowercase_ ,lowercase_ ,lowercase_ ,**lowercase_ ) def __lowerCAmelCase ( self : str ,lowercase_ : Union[str, Any] ): return default_hp_space_sigopt(lowercase_ ) class SCREAMING_SNAKE_CASE ( a_ ): """simple docstring""" lowercase__ = "wandb" @staticmethod def __lowerCAmelCase ( ): return is_wandb_available() def __lowerCAmelCase ( self : str ,lowercase_ : Optional[int] ,lowercase_ : int ,lowercase_ : str ,**lowercase_ : List[Any] ): return run_hp_search_wandb(lowercase_ ,lowercase_ ,lowercase_ ,**lowercase_ ) def __lowerCAmelCase ( self : Any ,lowercase_ : Optional[int] ): return default_hp_space_wandb(lowercase_ ) __UpperCamelCase : Dict = { HPSearchBackend(backend.name): backend for backend in [OptunaBackend, RayTuneBackend, SigOptBackend, WandbBackend] } def __SCREAMING_SNAKE_CASE ( ): lowerCAmelCase__ : Tuple = [backend for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() if backend.is_available()] if len(A_ ) > 0: lowerCAmelCase__ : Optional[int] = available_backends[0].name if len(A_ ) > 1: logger.info( f'{len(A_ )} hyperparameter search backends available. Using {name} as the default.' ) return name raise RuntimeError( '''No hyperparameter search backend available.\n''' + '''\n'''.join( f' - To install {backend.name} run {backend.pip_install()}' for backend in ALL_HYPERPARAMETER_SEARCH_BACKENDS.values() ) )
106
import sacrebleu as scb from packaging import version from sacrebleu import CHRF import datasets SCREAMING_SNAKE_CASE__ : Union[str, Any] = "\\n@inproceedings{popovic-2015-chrf,\n title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",\n month = sep,\n year = \"2015\",\n address = \"Lisbon, Portugal\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W15-3049\",\n doi = \"10.18653/v1/W15-3049\",\n pages = \"392--395\",\n}\n@inproceedings{popovic-2017-chrf,\n title = \"chr{F}++: words helping character n-grams\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Second Conference on Machine Translation\",\n month = sep,\n year = \"2017\",\n address = \"Copenhagen, Denmark\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W17-4770\",\n doi = \"10.18653/v1/W17-4770\",\n pages = \"612--618\",\n}\n@inproceedings{post-2018-call,\n title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n author = \"Post, Matt\",\n booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n month = oct,\n year = \"2018\",\n address = \"Belgium, Brussels\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W18-6319\",\n pages = \"186--191\",\n}\n" SCREAMING_SNAKE_CASE__ : int = "\\nChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,\nand ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation\nthat is already present in sacrebleu.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.\n" SCREAMING_SNAKE_CASE__ : Optional[Any] = "\nProduces ChrF(++) scores for hypotheses given reference translations.\n\nArgs:\n predictions (list of str): The predicted sentences.\n references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.\n char_order (int): Character n-gram order. Defaults to `6`.\n word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.\n beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.\n lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.\n whitespace (bool): If `True`, include whitespaces when extracting character n-grams.\n eps_smoothing (bool): If `True`, applies epsilon smoothing similar\n to reference chrF++.py, NLTK and Moses implementations. If `False`,\n it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.\n\nReturns:\n 'score' (float): The chrF (chrF++) score,\n 'char_order' (int): The character n-gram order,\n 'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,\n 'beta' (int): Determine the importance of recall w.r.t precision\n\nExamples:\n Example 1--a simple example of calculating chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction, references=reference)\n >>> print(results)\n {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}\n\n Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2)\n >>> print(results)\n {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}\n\n Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2,\n ... lowercase=True)\n >>> print(results)\n {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): def __A ( self : Dict ) -> Tuple: if version.parse(scb.__version__ ) < version.parse('''1.4.12''' ): raise ImportWarning( '''To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n''' '''You can install it with `pip install "sacrebleu>=1.4.12"`.''' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/mjpost/sacreBLEU#chrf--chrf''' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Sequence(datasets.Value('''string''' , id='''sequence''' ) , id='''references''' ), } ) , codebase_urls=['''https://github.com/mjpost/sacreBLEU#chrf--chrf'''] , reference_urls=[ '''https://github.com/m-popovic/chrF''', ] , ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int = CHRF.CHAR_ORDER , SCREAMING_SNAKE_CASE__ : int = CHRF.WORD_ORDER , SCREAMING_SNAKE_CASE__ : int = CHRF.BETA , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , ) -> Optional[Any]: __lowerCamelCase = len(references[0] ) if any(len(SCREAMING_SNAKE_CASE__ ) != references_per_prediction for refs in references ): raise ValueError('''Sacrebleu requires the same number of references for each prediction''' ) __lowerCamelCase = [[refs[i] for refs in references] for i in range(SCREAMING_SNAKE_CASE__ )] __lowerCamelCase = CHRF(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = sb_chrf.corpus_score(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return { "score": output.score, "char_order": output.char_order, "word_order": output.word_order, "beta": output.beta, }
270
0
def __magic_name__ ( A : str, A : int ): '''simple docstring''' a = [[] for _ in range(A )] a = key - 1 if key <= 0: raise ValueError("Height of grid can't be 0 or negative" ) if key == 1 or len(A ) <= key: return input_string for position, character in enumerate(A ): a = position % (lowest * 2) # puts it in bounds a = min(A, lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append(A ) a = ["".join(A ) for row in temp_grid] a = "".join(A ) return output_string def __magic_name__ ( A : str, A : int ): '''simple docstring''' a = [] a = key - 1 if key <= 0: raise ValueError("Height of grid can't be 0 or negative" ) if key == 1: return input_string a = [[] for _ in range(A )] # generates template for position in range(len(A ) ): a = position % (lowest * 2) # puts it in bounds a = min(A, lowest * 2 - num ) # creates zigzag pattern temp_grid[num].append("*" ) a = 0 for row in temp_grid: # fills in the characters a = input_string[counter : counter + len(A )] grid.append(list(A ) ) counter += len(A ) a = "" # reads as zigzag for position in range(len(A ) ): a = position % (lowest * 2) # puts it in bounds a = min(A, lowest * 2 - num ) # creates zigzag pattern output_string += grid[num][0] grid[num].pop(0 ) return output_string def __magic_name__ ( A : str ): '''simple docstring''' a = {} for key_guess in range(1, len(A ) ): # tries every key a = decrypt(A, A ) return results if __name__ == "__main__": import doctest doctest.testmod()
107
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : List[Any] = { "configuration_resnet": ["RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "ResNetConfig", "ResNetOnnxConfig"] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "ResNetForImageClassification", "ResNetModel", "ResNetPreTrainedModel", "ResNetBackbone", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = [ "TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFResNetForImageClassification", "TFResNetModel", "TFResNetPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ "FlaxResNetForImageClassification", "FlaxResNetModel", "FlaxResNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_resnet import RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ResNetConfig, ResNetOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_resnet import ( RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, ResNetBackbone, ResNetForImageClassification, ResNetModel, ResNetPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_resnet import ( TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFResNetForImageClassification, TFResNetModel, TFResNetPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel, FlaxResNetPreTrainedModel else: import sys SCREAMING_SNAKE_CASE__ : Any = _LazyModule(__name__, globals()["__file__"], _import_structure)
270
0
"""simple docstring""" # Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version lowerCAmelCase__ = get_logger(__name__) class SCREAMING_SNAKE_CASE__ : """simple docstring""" a : Optional[Any] ="dummy_data" a : int ="datasets" a : Tuple =False def __init__( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ = None , snake_case__ = False , snake_case__ = True , snake_case__ = None , ): """simple docstring""" lowerCAmelCase : Tuple = 0 lowerCAmelCase : int = dataset_name lowerCAmelCase : List[Any] = cache_dir lowerCAmelCase : List[str] = use_local_dummy_data lowerCAmelCase : List[str] = config # download_callbacks take a single url as input lowerCAmelCase : List[Callable] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root lowerCAmelCase : Tuple = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general lowerCAmelCase : Union[str, Any] = str(snake_case__ ) # to be downloaded lowerCAmelCase : List[Any] = None lowerCAmelCase : List[Any] = None @property def lowercase__ ( self ): """simple docstring""" if self._dummy_file is None: lowerCAmelCase : Any = self.download_dummy_data() return self._dummy_file @property def lowercase__ ( self ): """simple docstring""" if self.config is not None: # structure is dummy / config_name / version_name return os.path.join("dummy" , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join("dummy" , self.version_name ) @property def lowercase__ ( self ): """simple docstring""" return os.path.join(self.dummy_data_folder , "dummy_data.zip" ) def lowercase__ ( self ): """simple docstring""" lowerCAmelCase : Optional[Any] = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) lowerCAmelCase : str = cached_path( snake_case__ , cache_dir=self.cache_dir , extract_compressed_file=snake_case__ , force_extract=snake_case__ ) return os.path.join(snake_case__ , self.dummy_file_name ) @property def lowercase__ ( self ): """simple docstring""" return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def lowercase__ ( self ): """simple docstring""" if self._bucket_url is None: lowerCAmelCase : Union[str, Any] = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , "/" ) ) return self._bucket_url @property def lowercase__ ( self ): """simple docstring""" if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , "/" ).split("/" )[:-1] ) def lowercase__ ( self , snake_case__ , *snake_case__ ): """simple docstring""" if self.load_existing_dummy_data: # dummy data is downloaded and tested lowerCAmelCase : int = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned lowerCAmelCase : List[Any] = self.dummy_file_name # special case when data_url is a dict if isinstance(snake_case__ , snake_case__ ): return self.create_dummy_data_dict(snake_case__ , snake_case__ ) elif isinstance(snake_case__ , (list, tuple) ): return self.create_dummy_data_list(snake_case__ , snake_case__ ) else: return self.create_dummy_data_single(snake_case__ , snake_case__ ) def lowercase__ ( self , snake_case__ , *snake_case__ ): """simple docstring""" return self.download_and_extract(snake_case__ ) def lowercase__ ( self , snake_case__ , snake_case__ ): """simple docstring""" return self.download_and_extract(snake_case__ ) def lowercase__ ( self , snake_case__ , *snake_case__ , **snake_case__ ): """simple docstring""" return path def lowercase__ ( self ): """simple docstring""" return {} def lowercase__ ( self , snake_case__ , snake_case__ ): """simple docstring""" lowerCAmelCase : List[Any] = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(snake_case__ , snake_case__ ): for single_url in single_urls: download_callback(snake_case__ ) else: lowerCAmelCase : List[str] = single_urls download_callback(snake_case__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(snake_case__ , snake_case__ ): lowerCAmelCase : Tuple = [os.path.join(snake_case__ , urllib.parse.quote_plus(Path(snake_case__ ).name ) ) for x in single_urls] else: lowerCAmelCase : int = single_urls lowerCAmelCase : Any = os.path.join(snake_case__ , urllib.parse.quote_plus(Path(snake_case__ ).name ) ) lowerCAmelCase : Union[str, Any] = value # make sure that values are unique if all(isinstance(snake_case__ , snake_case__ ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique lowerCAmelCase : Union[str, Any] = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def lowercase__ ( self , snake_case__ , snake_case__ ): """simple docstring""" lowerCAmelCase : Dict = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one lowerCAmelCase : Optional[Any] = all(bool(re.findall("[0-9]{3,}-of-[0-9]{3,}" , snake_case__ ) ) for url in data_url ) lowerCAmelCase : Any = all( url.startswith("https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed" ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): lowerCAmelCase : int = [data_url[0]] * len(snake_case__ ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(snake_case__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus lowerCAmelCase : Dict = os.path.join(snake_case__ , urllib.parse.quote_plus(single_url.split("/" )[-1] ) ) dummy_data_list.append(snake_case__ ) return dummy_data_list def lowercase__ ( self , snake_case__ , snake_case__ ): """simple docstring""" for download_callback in self.download_callbacks: download_callback(snake_case__ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus lowerCAmelCase : Tuple = os.path.join(snake_case__ , urllib.parse.quote_plus(data_url.split("/" )[-1] ) ) if os.path.exists(snake_case__ ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def lowercase__ ( self ): """simple docstring""" pass def lowercase__ ( self ): """simple docstring""" pass def lowercase__ ( self , snake_case__ ): """simple docstring""" def _iter_archive_members(snake_case__ ): # this preserves the order of the members inside the ZIP archive lowerCAmelCase : str = Path(self.dummy_file ).parent lowerCAmelCase : Optional[Any] = path.relative_to(snake_case__ ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: lowerCAmelCase : List[Any] = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(snake_case__ ) lowerCAmelCase : List[Any] = Path(snake_case__ ) lowerCAmelCase : str = _iter_archive_members(snake_case__ ) if self.use_local_dummy_data else path.rglob("*" ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith((".", "__") ): yield file_path.relative_to(snake_case__ ).as_posix(), file_path.open("rb" ) def lowercase__ ( self , snake_case__ ): """simple docstring""" if not isinstance(snake_case__ , snake_case__ ): lowerCAmelCase : List[Any] = [paths] for path in paths: if os.path.isfile(snake_case__ ): if os.path.basename(snake_case__ ).startswith((".", "__") ): return yield path else: for dirpath, dirnames, filenames in os.walk(snake_case__ ): if os.path.basename(snake_case__ ).startswith((".", "__") ): continue dirnames.sort() for filename in sorted(snake_case__ ): if filename.startswith((".", "__") ): continue yield os.path.join(snake_case__ , snake_case__ )
108
import unittest import numpy as np import requests from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: SCREAMING_SNAKE_CASE__ : str = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any]=7 , SCREAMING_SNAKE_CASE__ : List[str]=3 , SCREAMING_SNAKE_CASE__ : Tuple=18 , SCREAMING_SNAKE_CASE__ : int=30 , SCREAMING_SNAKE_CASE__ : Any=4_00 , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , ) -> Union[str, Any]: __lowerCamelCase = size if size is not None else {'''height''': 20, '''width''': 20} __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = num_channels __lowerCamelCase = image_size __lowerCamelCase = min_resolution __lowerCamelCase = max_resolution __lowerCamelCase = size __lowerCamelCase = do_normalize __lowerCamelCase = do_convert_rgb __lowerCamelCase = [5_12, 10_24, 20_48, 40_96] __lowerCamelCase = patch_size if patch_size is not None else {'''height''': 16, '''width''': 16} def __A ( self : Union[str, Any] ) -> Union[str, Any]: return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def __A ( self : int ) -> Any: __lowerCamelCase = '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg''' __lowerCamelCase = Image.open(requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ ).raw ).convert('''RGB''' ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`.""" , ) @require_torch @require_vision class lowerCAmelCase__ ( __lowercase , unittest.TestCase ): a__ : Dict = PixaStructImageProcessor if is_vision_available() else None def __A ( self : Optional[Any] ) -> List[Any]: __lowerCamelCase = PixaStructImageProcessingTester(self ) @property def __A ( self : Optional[int] ) -> Optional[int]: return self.image_processor_tester.prepare_image_processor_dict() def __A ( self : Tuple ) -> Dict: __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_normalize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_convert_rgb''' ) ) def __A ( self : int ) -> str: __lowerCamelCase = self.image_processor_tester.prepare_dummy_image() __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) __lowerCamelCase = 20_48 __lowerCamelCase = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) ) def __A ( self : Union[str, Any] ) -> Dict: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : Dict ) -> str: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 __lowerCamelCase = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches __lowerCamelCase = '''Hello''' __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ , header_text=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ , header_text=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : List[str] ) -> Any: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : Tuple ) -> List[str]: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`.""" , ) @require_torch @require_vision class lowerCAmelCase__ ( __lowercase , unittest.TestCase ): a__ : Any = PixaStructImageProcessor if is_vision_available() else None def __A ( self : Union[str, Any] ) -> Optional[Any]: __lowerCamelCase = PixaStructImageProcessingTester(self , num_channels=4 ) __lowerCamelCase = 3 @property def __A ( self : List[Any] ) -> Optional[Any]: return self.image_processor_tester.prepare_image_processor_dict() def __A ( self : Union[str, Any] ) -> List[str]: __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_normalize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_convert_rgb''' ) ) def __A ( self : Optional[int] ) -> str: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
270
0
"""simple docstring""" from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer from ...configuration_utils import PretrainedConfig from ...file_utils import TensorType, is_torch_available from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging A: Tuple = logging.get_logger(__name__) A: List[Any] = { "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/config.json", # See all BlenderbotSmall models at https://huggingface.co/models?filter=blenderbot_small } class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase__ ): __lowerCAmelCase : int = 'blenderbot-small' __lowerCAmelCase : Any = ['past_key_values'] __lowerCAmelCase : str = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self , _SCREAMING_SNAKE_CASE=50265 , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=2048 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=8 , _SCREAMING_SNAKE_CASE=2048 , _SCREAMING_SNAKE_CASE=16 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE=True , _SCREAMING_SNAKE_CASE="gelu" , _SCREAMING_SNAKE_CASE=512 , _SCREAMING_SNAKE_CASE=0.1 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.0 , _SCREAMING_SNAKE_CASE=0.02 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=False , _SCREAMING_SNAKE_CASE=0 , _SCREAMING_SNAKE_CASE=1 , _SCREAMING_SNAKE_CASE=2 , _SCREAMING_SNAKE_CASE=2 , **_SCREAMING_SNAKE_CASE , ) -> str: '''simple docstring''' UpperCAmelCase : Any = vocab_size UpperCAmelCase : Any = max_position_embeddings UpperCAmelCase : str = d_model UpperCAmelCase : List[Any] = encoder_ffn_dim UpperCAmelCase : Union[str, Any] = encoder_layers UpperCAmelCase : List[str] = encoder_attention_heads UpperCAmelCase : Optional[Any] = decoder_ffn_dim UpperCAmelCase : List[Any] = decoder_layers UpperCAmelCase : Any = decoder_attention_heads UpperCAmelCase : Union[str, Any] = dropout UpperCAmelCase : Union[str, Any] = attention_dropout UpperCAmelCase : int = activation_dropout UpperCAmelCase : int = activation_function UpperCAmelCase : Optional[Any] = init_std UpperCAmelCase : List[str] = encoder_layerdrop UpperCAmelCase : List[str] = decoder_layerdrop UpperCAmelCase : List[str] = use_cache UpperCAmelCase : Union[str, Any] = encoder_layers UpperCAmelCase : Any = scale_embedding # scale factor will be sqrt(d_model) if True super().__init__( pad_token_id=_SCREAMING_SNAKE_CASE , bos_token_id=_SCREAMING_SNAKE_CASE , eos_token_id=_SCREAMING_SNAKE_CASE , is_encoder_decoder=_SCREAMING_SNAKE_CASE , decoder_start_token_id=_SCREAMING_SNAKE_CASE , forced_eos_token_id=_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE , ) class SCREAMING_SNAKE_CASE__ ( UpperCAmelCase__ ): @property def SCREAMING_SNAKE_CASE ( self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: UpperCAmelCase : Dict = OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}), ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}), ] ) if self.use_past: UpperCAmelCase : int = {0: """batch"""} UpperCAmelCase : List[Any] = {0: """batch""", 1: """past_decoder_sequence + sequence"""} else: UpperCAmelCase : Optional[Any] = {0: """batch""", 1: """decoder_sequence"""} UpperCAmelCase : Any = {0: """batch""", 1: """decoder_sequence"""} if self.use_past: self.fill_with_past_key_values_(_SCREAMING_SNAKE_CASE , direction="""inputs""" ) elif self.task == "causal-lm": # TODO: figure this case out. UpperCAmelCase : int = OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}), ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}), ] ) if self.use_past: UpperCAmelCase , UpperCAmelCase : Tuple = self.num_layers for i in range(_SCREAMING_SNAKE_CASE ): UpperCAmelCase : Optional[Any] = {0: """batch""", 2: """past_sequence + sequence"""} UpperCAmelCase : List[Any] = {0: """batch""", 2: """past_sequence + sequence"""} else: UpperCAmelCase : Dict = OrderedDict( [ ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}), ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}), ("""decoder_input_ids""", {0: """batch""", 1: """decoder_sequence"""}), ("""decoder_attention_mask""", {0: """batch""", 1: """decoder_sequence"""}), ] ) return common_inputs @property def SCREAMING_SNAKE_CASE ( self ) -> Mapping[str, Mapping[int, str]]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: UpperCAmelCase : Union[str, Any] = super().outputs else: UpperCAmelCase : int = super(_SCREAMING_SNAKE_CASE , self ).outputs if self.use_past: UpperCAmelCase , UpperCAmelCase : Any = self.num_layers for i in range(_SCREAMING_SNAKE_CASE ): UpperCAmelCase : List[str] = {0: """batch""", 2: """past_sequence + sequence"""} UpperCAmelCase : List[str] = {0: """batch""", 2: """past_sequence + sequence"""} return common_outputs def SCREAMING_SNAKE_CASE ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = -1 , _SCREAMING_SNAKE_CASE = -1 , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = None , ) -> Mapping[str, Any]: '''simple docstring''' UpperCAmelCase : Dict = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Generate decoder inputs UpperCAmelCase : Optional[Any] = seq_length if not self.use_past else 1 UpperCAmelCase : Dict = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCAmelCase : Any = {F"decoder_{name}": tensor for name, tensor in decoder_inputs.items()} UpperCAmelCase : Union[str, Any] = dict(**_SCREAMING_SNAKE_CASE , **_SCREAMING_SNAKE_CASE ) if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch UpperCAmelCase , UpperCAmelCase : int = common_inputs["""input_ids"""].shape UpperCAmelCase : Any = common_inputs["""decoder_input_ids"""].shape[1] UpperCAmelCase , UpperCAmelCase : str = self.num_attention_heads UpperCAmelCase : Union[str, Any] = ( batch, num_encoder_attention_heads, encoder_seq_length, self._config.hidden_size // num_encoder_attention_heads, ) UpperCAmelCase : Union[str, Any] = decoder_seq_length + 3 UpperCAmelCase : Union[str, Any] = ( batch, num_decoder_attention_heads, decoder_past_length, self._config.hidden_size // num_decoder_attention_heads, ) UpperCAmelCase : Optional[Any] = torch.cat( [common_inputs["""decoder_attention_mask"""], torch.ones(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )] , dim=1 ) UpperCAmelCase : List[str] = [] # If the number of encoder and decoder layers are present in the model configuration, both are considered UpperCAmelCase , UpperCAmelCase : List[Any] = self.num_layers UpperCAmelCase : Optional[Any] = min(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) UpperCAmelCase : Optional[Any] = max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) - min_num_layers UpperCAmelCase : Optional[int] = """encoder""" if num_encoder_layers > num_decoder_layers else """decoder""" for _ in range(_SCREAMING_SNAKE_CASE ): common_inputs["past_key_values"].append( ( torch.zeros(_SCREAMING_SNAKE_CASE ), torch.zeros(_SCREAMING_SNAKE_CASE ), torch.zeros(_SCREAMING_SNAKE_CASE ), torch.zeros(_SCREAMING_SNAKE_CASE ), ) ) # TODO: test this. UpperCAmelCase : Dict = encoder_shape if remaining_side_name == """encoder""" else decoder_shape for _ in range(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): common_inputs["past_key_values"].append((torch.zeros(_SCREAMING_SNAKE_CASE ), torch.zeros(_SCREAMING_SNAKE_CASE )) ) return common_inputs def SCREAMING_SNAKE_CASE ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = -1 , _SCREAMING_SNAKE_CASE = -1 , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = None , ) -> Mapping[str, Any]: '''simple docstring''' UpperCAmelCase : Tuple = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) if self.use_past: if not is_torch_available(): raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed.""" ) else: import torch UpperCAmelCase , UpperCAmelCase : Optional[Any] = common_inputs["""input_ids"""].shape # Not using the same length for past_key_values UpperCAmelCase : Union[str, Any] = seqlen + 2 UpperCAmelCase , UpperCAmelCase : Optional[int] = self.num_layers UpperCAmelCase , UpperCAmelCase : Dict = self.num_attention_heads UpperCAmelCase : Any = ( batch, num_encoder_attention_heads, past_key_values_length, self._config.hidden_size // num_encoder_attention_heads, ) UpperCAmelCase : List[Any] = common_inputs["""attention_mask"""].dtype UpperCAmelCase : Any = torch.cat( [common_inputs["""attention_mask"""], torch.ones(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , dtype=_SCREAMING_SNAKE_CASE )] , dim=1 ) UpperCAmelCase : List[str] = [ (torch.zeros(_SCREAMING_SNAKE_CASE ), torch.zeros(_SCREAMING_SNAKE_CASE )) for _ in range(_SCREAMING_SNAKE_CASE ) ] return common_inputs def SCREAMING_SNAKE_CASE ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = -1 , _SCREAMING_SNAKE_CASE = -1 , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = None , ) -> Mapping[str, Any]: '''simple docstring''' UpperCAmelCase : str = compute_effective_axis_dimension( _SCREAMING_SNAKE_CASE , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCAmelCase : List[str] = tokenizer.num_special_tokens_to_add(_SCREAMING_SNAKE_CASE ) UpperCAmelCase : int = compute_effective_axis_dimension( _SCREAMING_SNAKE_CASE , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=_SCREAMING_SNAKE_CASE ) # Generate dummy inputs according to compute batch and sequence UpperCAmelCase : Dict = [""" """.join([tokenizer.unk_token] ) * seq_length] * batch_size UpperCAmelCase : Optional[int] = dict(tokenizer(_SCREAMING_SNAKE_CASE , return_tensors=_SCREAMING_SNAKE_CASE ) ) return common_inputs def SCREAMING_SNAKE_CASE ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = -1 , _SCREAMING_SNAKE_CASE = -1 , _SCREAMING_SNAKE_CASE = False , _SCREAMING_SNAKE_CASE = None , ) -> Mapping[str, Any]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: UpperCAmelCase : Optional[int] = self._generate_dummy_inputs_for_default_and_seqaseq_lm( _SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , seq_length=_SCREAMING_SNAKE_CASE , is_pair=_SCREAMING_SNAKE_CASE , framework=_SCREAMING_SNAKE_CASE ) elif self.task == "causal-lm": UpperCAmelCase : Optional[int] = self._generate_dummy_inputs_for_causal_lm( _SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , seq_length=_SCREAMING_SNAKE_CASE , is_pair=_SCREAMING_SNAKE_CASE , framework=_SCREAMING_SNAKE_CASE ) else: UpperCAmelCase : Tuple = self._generate_dummy_inputs_for_sequence_classification_and_question_answering( _SCREAMING_SNAKE_CASE , batch_size=_SCREAMING_SNAKE_CASE , seq_length=_SCREAMING_SNAKE_CASE , is_pair=_SCREAMING_SNAKE_CASE , framework=_SCREAMING_SNAKE_CASE ) return common_inputs def SCREAMING_SNAKE_CASE ( self , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> List[Any]: '''simple docstring''' if self.task in ["default", "seq2seq-lm"]: UpperCAmelCase : List[Any] = super()._flatten_past_key_values_(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) else: UpperCAmelCase : Dict = super(_SCREAMING_SNAKE_CASE , self )._flatten_past_key_values_( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE )
109
import shutil import tempfile import unittest from unittest.mock import patch from transformers import ( DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, Trainer, TrainerCallback, TrainingArguments, is_torch_available, ) from transformers.testing_utils import require_torch if is_torch_available(): from transformers.trainer import DEFAULT_CALLBACKS from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel class lowerCAmelCase__ ( __lowercase ): def __init__( self : int ) -> Optional[int]: __lowerCamelCase = [] def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> Tuple: self.events.append('''on_init_end''' ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Any: self.events.append('''on_train_begin''' ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : int ) -> Any: self.events.append('''on_train_end''' ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: self.events.append('''on_epoch_begin''' ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Tuple ) -> Optional[Any]: self.events.append('''on_epoch_end''' ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: self.events.append('''on_step_begin''' ) def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: self.events.append('''on_step_end''' ) def __A ( self : int , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> Union[str, Any]: self.events.append('''on_evaluate''' ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : str ) -> str: self.events.append('''on_predict''' ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Tuple: self.events.append('''on_save''' ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : List[str] ) -> List[str]: self.events.append('''on_log''' ) def __A ( self : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: self.events.append('''on_prediction_step''' ) @require_torch class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Union[str, Any] ) -> Optional[Any]: __lowerCamelCase = tempfile.mkdtemp() def __A ( self : int ) -> List[str]: shutil.rmtree(self.output_dir ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any]=0 , SCREAMING_SNAKE_CASE__ : Any=0 , SCREAMING_SNAKE_CASE__ : List[str]=64 , SCREAMING_SNAKE_CASE__ : Optional[int]=64 , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Optional[int]=False , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Union[str, Any]: # disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure # its set to False since the tests later on depend on its value. __lowerCamelCase = RegressionDataset(length=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionDataset(length=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionModelConfig(a=SCREAMING_SNAKE_CASE__ , b=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionPreTrainedModel(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = TrainingArguments(self.output_dir , disable_tqdm=SCREAMING_SNAKE_CASE__ , report_to=[] , **SCREAMING_SNAKE_CASE__ ) return Trainer( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , train_dataset=SCREAMING_SNAKE_CASE__ , eval_dataset=SCREAMING_SNAKE_CASE__ , callbacks=SCREAMING_SNAKE_CASE__ , ) def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> Optional[int]: self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) ) # Order doesn't matter __lowerCamelCase = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : cb.__name__ if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cb.__class__.__name__ ) __lowerCamelCase = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : cb.__name__ if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cb.__class__.__name__ ) for cba, cba in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(SCREAMING_SNAKE_CASE__ , cba.__class__ ) elif not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(cba.__class__ , SCREAMING_SNAKE_CASE__ ) else: self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: __lowerCamelCase = ['''on_init_end''', '''on_train_begin'''] __lowerCamelCase = 0 __lowerCamelCase = len(trainer.get_eval_dataloader() ) __lowerCamelCase = ['''on_prediction_step'''] * len(trainer.get_eval_dataloader() ) + ['''on_log''', '''on_evaluate'''] for _ in range(trainer.state.num_train_epochs ): expected_events.append('''on_epoch_begin''' ) for _ in range(SCREAMING_SNAKE_CASE__ ): step += 1 expected_events += ["on_step_begin", "on_step_end"] if step % trainer.args.logging_steps == 0: expected_events.append('''on_log''' ) if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0: expected_events += evaluation_events.copy() if step % trainer.args.save_steps == 0: expected_events.append('''on_save''' ) expected_events.append('''on_epoch_end''' ) if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH: expected_events += evaluation_events.copy() expected_events += ["on_log", "on_train_end"] return expected_events def __A ( self : Union[str, Any] ) -> int: __lowerCamelCase = self.get_trainer() __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [ProgressCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # Callbacks passed at init are added to the default callbacks __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] ) expected_callbacks.append(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback __lowerCamelCase = self.get_trainer(disable_tqdm=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [PrinterCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) def __A ( self : List[Any] ) -> str: __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [ProgressCallback] __lowerCamelCase = self.get_trainer() # We can add, pop, or remove by class name trainer.remove_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.remove(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.pop_callback(SCREAMING_SNAKE_CASE__ ) self.assertEqual(cb.__class__ , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) trainer.add_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.insert(0 , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # We can also add, pop, or remove by instance __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.callback_handler.callbacks[0] trainer.remove_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.remove(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.callback_handler.callbacks[0] __lowerCamelCase = trainer.pop_callback(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) trainer.add_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.insert(0 , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] ) -> Any: import warnings # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested warnings.simplefilter(action='''ignore''' , category=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # Independent log/save/eval __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , logging_steps=5 ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , save_steps=5 ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , eval_steps=5 , evaluation_strategy='''steps''' ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , evaluation_strategy='''epoch''' ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # A bit of everything __lowerCamelCase = self.get_trainer( callbacks=[MyTestTrainerCallback] , logging_steps=3 , save_steps=10 , eval_steps=5 , evaluation_strategy='''steps''' , ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # warning should be emitted for duplicated callbacks with patch('''transformers.trainer_callback.logger.warning''' ) as warn_mock: __lowerCamelCase = self.get_trainer( callbacks=[MyTestTrainerCallback, MyTestTrainerCallback] , ) assert str(SCREAMING_SNAKE_CASE__ ) in warn_mock.call_args[0][0]
270
0
import pandas as pd from matplotlib import pyplot as plt from sklearn.linear_model import LinearRegression # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split # Fitting Polynomial Regression to the dataset from sklearn.preprocessing import PolynomialFeatures # Importing the dataset lowercase__ : int = pd.read_csv( "https://s3.us-west-2.amazonaws.com/public.gamelab.fun/dataset/" "position_salaries.csv" ) lowercase__ : Tuple = dataset.iloc[:, 1:2].values lowercase__ : Tuple = dataset.iloc[:, 2].values lowercase__ : Optional[int] = train_test_split(X, y, test_size=0.2, random_state=0) lowercase__ : Optional[Any] = PolynomialFeatures(degree=4) lowercase__ : List[Any] = poly_reg.fit_transform(X) lowercase__ : List[Any] = LinearRegression() pol_reg.fit(X_poly, y) def lowerCamelCase__ ( ): '''simple docstring''' plt.scatter(__lowerCAmelCase , __lowerCAmelCase , color="red" ) plt.plot(__lowerCAmelCase , pol_reg.predict(poly_reg.fit_transform(__lowerCAmelCase ) ) , color="blue" ) plt.title("Truth or Bluff (Linear Regression)" ) plt.xlabel("Position level" ) plt.ylabel("Salary" ) plt.show() if __name__ == "__main__": viz_polymonial() # Predicting a new result with Polymonial Regression pol_reg.predict(poly_reg.fit_transform([[5.5]])) # output should be 132148.43750003
187
import numpy as np from cva import destroyAllWindows, imread, imshow, waitKey class lowerCAmelCase__ : def __init__( self : Any , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> Dict: if dst_width < 0 or dst_height < 0: raise ValueError('''Destination width/height should be > 0''' ) __lowerCamelCase = img __lowerCamelCase = img.shape[1] __lowerCamelCase = img.shape[0] __lowerCamelCase = dst_width __lowerCamelCase = dst_height __lowerCamelCase = self.src_w / self.dst_w __lowerCamelCase = self.src_h / self.dst_h __lowerCamelCase = __lowerCamelCase = ( np.ones((self.dst_h, self.dst_w, 3) , np.uinta ) * 2_55 ) def __A ( self : List[Any] ) -> str: for i in range(self.dst_h ): for j in range(self.dst_w ): __lowerCamelCase = self.img[self.get_y(SCREAMING_SNAKE_CASE__ )][self.get_x(SCREAMING_SNAKE_CASE__ )] def __A ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> int: return int(self.ratio_x * x ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> int: return int(self.ratio_y * y ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = 800, 600 SCREAMING_SNAKE_CASE__ : int = imread("image_data/lena.jpg", 1) SCREAMING_SNAKE_CASE__ : Union[str, Any] = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( F'Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}', n.output ) waitKey(0) destroyAllWindows()
270
0
from heapq import heappop, heappush import numpy as np def __lowerCamelCase ( snake_case__ ,snake_case__ ,snake_case__ ,snake_case__ ,) -> tuple[float | int, list[tuple[int, int]]]: """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = grid.shape _SCREAMING_SNAKE_CASE = [-1, 1, 0, 0] _SCREAMING_SNAKE_CASE = [0, 0, -1, 1] if allow_diagonal: dx += [-1, -1, 1, 1] dy += [-1, 1, -1, 1] _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = [(0, source)], set() _SCREAMING_SNAKE_CASE = np.full((rows, cols) ,np.inf ) _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = np.empty((rows, cols) ,dtype=__lowerCAmelCase ) _SCREAMING_SNAKE_CASE = None while queue: ((_SCREAMING_SNAKE_CASE) , (_SCREAMING_SNAKE_CASE)) = heappop(__lowerCAmelCase ) if (x, y) in visited: continue visited.add((x, y) ) if (x, y) == destination: _SCREAMING_SNAKE_CASE = [] while (x, y) != source: path.append((x, y) ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = predecessors[x, y] path.append(__lowerCAmelCase ) # add the source manually path.reverse() return matrix[destination], path for i in range(len(__lowerCAmelCase ) ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = x + dx[i], y + dy[i] if 0 <= nx < rows and 0 <= ny < cols: _SCREAMING_SNAKE_CASE = grid[nx][ny] if next_node == 1 and matrix[nx, ny] > dist + 1: heappush(__lowerCAmelCase ,(dist + 1, (nx, ny)) ) _SCREAMING_SNAKE_CASE = dist + 1 _SCREAMING_SNAKE_CASE = (x, y) return np.inf, [] if __name__ == "__main__": import doctest doctest.testmod()
306
from queue import PriorityQueue from typing import Any import numpy as np def __magic_name__ ( __lowerCAmelCase : dict , __lowerCAmelCase : str , __lowerCAmelCase : set , __lowerCAmelCase : set , __lowerCAmelCase : dict , __lowerCAmelCase : dict , __lowerCAmelCase : PriorityQueue , __lowerCAmelCase : dict , __lowerCAmelCase : float | int , ) -> float | int: for nxt, d in graph[v]: if nxt in visited_forward: continue __lowerCamelCase = cst_fwd.get(__lowerCAmelCase , np.inf ) __lowerCamelCase = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) __lowerCamelCase = new_cost_f __lowerCamelCase = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: __lowerCamelCase = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def __magic_name__ ( __lowerCAmelCase : str , __lowerCAmelCase : str , __lowerCAmelCase : dict , __lowerCAmelCase : dict ) -> int: __lowerCamelCase = -1 __lowerCamelCase = set() __lowerCamelCase = set() __lowerCamelCase = {source: 0} __lowerCamelCase = {destination: 0} __lowerCamelCase = {source: None} __lowerCamelCase = {destination: None} __lowerCamelCase = PriorityQueue() __lowerCamelCase = PriorityQueue() __lowerCamelCase = np.inf queue_forward.put((0, source) ) queue_backward.put((0, destination) ) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): __lowerCamelCase , __lowerCamelCase = queue_forward.get() visited_forward.add(__lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = queue_backward.get() visited_backward.add(__lowerCAmelCase ) __lowerCamelCase = pass_and_relaxation( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) __lowerCamelCase = pass_and_relaxation( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: __lowerCamelCase = shortest_distance return shortest_path_distance SCREAMING_SNAKE_CASE__ : List[Any] = { "B": [["C", 1]], "C": [["D", 1]], "D": [["F", 1]], "E": [["B", 1], ["G", 2]], "F": [], "G": [["F", 1]], } SCREAMING_SNAKE_CASE__ : Optional[int] = { "B": [["E", 1]], "C": [["B", 1]], "D": [["C", 1]], "F": [["D", 1], ["G", 1]], "E": [[None, np.inf]], "G": [["E", 2]], } if __name__ == "__main__": import doctest doctest.testmod()
270
0
'''simple docstring''' import copy from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase : List[Any] =logging.get_logger(__name__) class a_ ( __lowercase ): __A = """encoder-decoder""" __A = True def __init__( self : Union[str, Any] , **lowercase : Any ): """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE__ ) assert ( "encoder" in kwargs and "decoder" in kwargs ), "Config has to be initialized with encoder and decoder config" lowercase_ :Optional[int] = kwargs.pop("encoder" ) lowercase_ :int = encoder_config.pop("model_type" ) lowercase_ :Any = kwargs.pop("decoder" ) lowercase_ :int = decoder_config.pop("model_type" ) from ..auto.configuration_auto import AutoConfig lowercase_ :List[Any] = AutoConfig.for_model(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) lowercase_ :Optional[Any] = AutoConfig.for_model(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) lowercase_ :List[Any] = True @classmethod def lowercase__ ( cls : Tuple , lowercase : PretrainedConfig , lowercase : PretrainedConfig , **lowercase : Dict ): """simple docstring""" logger.info("Set `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config" ) lowercase_ :Union[str, Any] = True lowercase_ :str = True return cls(encoder=encoder_config.to_dict() , decoder=decoder_config.to_dict() , **SCREAMING_SNAKE_CASE__ ) def lowercase__ ( self : Any ): """simple docstring""" lowercase_ :List[Any] = copy.deepcopy(self.__dict__ ) lowercase_ :List[str] = self.encoder.to_dict() lowercase_ :Union[str, Any] = self.decoder.to_dict() lowercase_ :Any = self.__class__.model_type return output
223
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ : List[Any] = TypeVar("T") def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (position - 1) // 2 def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (2 * position) + 1 def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (2 * position) + 2 class lowerCAmelCase__ ( Generic[T] ): def __init__( self : List[str] ) -> None: __lowerCamelCase = [] __lowerCamelCase = {} __lowerCamelCase = 0 def __len__( self : Optional[int] ) -> int: return self.elements def __repr__( self : Optional[int] ) -> str: return str(self.heap ) def __A ( self : Union[str, Any] ) -> bool: # Check if the priority queue is empty return self.elements == 0 def __A ( self : str , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Add an element with given priority to the queue self.heap.append((elem, weight) ) __lowerCamelCase = self.elements self.elements += 1 self._bubble_up(SCREAMING_SNAKE_CASE__ ) def __A ( self : Any ) -> T: # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) __lowerCamelCase , __lowerCamelCase = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __lowerCamelCase , __lowerCamelCase = self.heap[0] self._bubble_down(SCREAMING_SNAKE_CASE__ ) return elem def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Update the weight of the given key __lowerCamelCase = self.position_map[elem] __lowerCamelCase = (elem, weight) if position > 0: __lowerCamelCase = get_parent_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase = self.heap[parent_position] if parent_weight > weight: self._bubble_up(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Place a node at the proper position (upward movement) [to be used internally # only] __lowerCamelCase = self.position_map[elem] if curr_pos == 0: return None __lowerCamelCase = get_parent_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase = self.heap[curr_pos] __lowerCamelCase , __lowerCamelCase = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_up(SCREAMING_SNAKE_CASE__ ) return None def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Place a node at the proper position (downward movement) [to be used # internally only] __lowerCamelCase = self.position_map[elem] __lowerCamelCase , __lowerCamelCase = self.heap[curr_pos] __lowerCamelCase = get_child_left_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = get_child_right_position(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements and child_right_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_left_position] __lowerCamelCase , __lowerCamelCase = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: return None if child_right_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) return None def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: # Swap the nodes at the given positions __lowerCamelCase = self.heap[nodea_pos][0] __lowerCamelCase = self.heap[nodea_pos][0] __lowerCamelCase , __lowerCamelCase = ( self.heap[nodea_pos], self.heap[nodea_pos], ) __lowerCamelCase = nodea_pos __lowerCamelCase = nodea_pos class lowerCAmelCase__ ( Generic[T] ): def __init__( self : Tuple ) -> None: __lowerCamelCase = {} __lowerCamelCase = 0 def __repr__( self : Optional[int] ) -> str: return str(self.connections ) def __len__( self : List[str] ) -> int: return self.nodes def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Add a node in the graph if it is not in the graph if node not in self.connections: __lowerCamelCase = {} self.nodes += 1 def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Add an edge between 2 nodes in the graph self.add_node(SCREAMING_SNAKE_CASE__ ) self.add_node(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = weight __lowerCamelCase = weight def __magic_name__ ( __lowerCAmelCase : GraphUndirectedWeighted[T] , ) -> tuple[dict[T, int], dict[T, T | None]]: __lowerCamelCase = {node: maxsize for node in graph.connections} __lowerCamelCase = {node: None for node in graph.connections} __lowerCamelCase = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(__lowerCAmelCase , __lowerCAmelCase ) if priority_queue.is_empty(): return dist, parent # initialization __lowerCamelCase = priority_queue.extract_min() __lowerCamelCase = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __lowerCamelCase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(__lowerCAmelCase , dist[neighbour] ) __lowerCamelCase = node # running prim's algorithm while not priority_queue.is_empty(): __lowerCamelCase = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __lowerCamelCase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(__lowerCAmelCase , dist[neighbour] ) __lowerCamelCase = node return dist, parent
270
0
'''simple docstring''' import sacrebleu as scb from packaging import version from sacrebleu import CHRF import datasets __lowerCAmelCase : Union[str, Any] ="\\n@inproceedings{popovic-2015-chrf,\n title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",\n month = sep,\n year = \"2015\",\n address = \"Lisbon, Portugal\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W15-3049\",\n doi = \"10.18653/v1/W15-3049\",\n pages = \"392--395\",\n}\n@inproceedings{popovic-2017-chrf,\n title = \"chr{F}++: words helping character n-grams\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Second Conference on Machine Translation\",\n month = sep,\n year = \"2017\",\n address = \"Copenhagen, Denmark\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W17-4770\",\n doi = \"10.18653/v1/W17-4770\",\n pages = \"612--618\",\n}\n@inproceedings{post-2018-call,\n title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n author = \"Post, Matt\",\n booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n month = oct,\n year = \"2018\",\n address = \"Belgium, Brussels\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W18-6319\",\n pages = \"186--191\",\n}\n" __lowerCAmelCase : int ="\\nChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,\nand ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation\nthat is already present in sacrebleu.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.\n" __lowerCAmelCase : Optional[Any] ="\nProduces ChrF(++) scores for hypotheses given reference translations.\n\nArgs:\n predictions (list of str): The predicted sentences.\n references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.\n char_order (int): Character n-gram order. Defaults to `6`.\n word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.\n beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.\n lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.\n whitespace (bool): If `True`, include whitespaces when extracting character n-grams.\n eps_smoothing (bool): If `True`, applies epsilon smoothing similar\n to reference chrF++.py, NLTK and Moses implementations. If `False`,\n it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.\n\nReturns:\n 'score' (float): The chrF (chrF++) score,\n 'char_order' (int): The character n-gram order,\n 'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,\n 'beta' (int): Determine the importance of recall w.r.t precision\n\nExamples:\n Example 1--a simple example of calculating chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction, references=reference)\n >>> print(results)\n {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}\n\n Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2)\n >>> print(results)\n {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}\n\n Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2,\n ... lowercase=True)\n >>> print(results)\n {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase ( datasets.Metric ): def UpperCAmelCase_ ( self :Dict )-> Tuple: if version.parse(scb.__version__ ) < version.parse("1.4.12" ): raise ImportWarning( "To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n" "You can install it with `pip install \"sacrebleu>=1.4.12\"`." ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="https://github.com/mjpost/sacreBLEU#chrf--chrf" , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Value("string" , id="sequence" ), "references": datasets.Sequence(datasets.Value("string" , id="sequence" ) , id="references" ), } ) , codebase_urls=["https://github.com/mjpost/sacreBLEU#chrf--chrf"] , reference_urls=[ "https://github.com/m-popovic/chrF", ] , ) def UpperCAmelCase_ ( self :Union[str, Any] , lowercase_ :Optional[Any] , lowercase_ :Optional[Any] , lowercase_ :int = CHRF.CHAR_ORDER , lowercase_ :int = CHRF.WORD_ORDER , lowercase_ :int = CHRF.BETA , lowercase_ :bool = False , lowercase_ :bool = False , lowercase_ :bool = False , )-> Optional[Any]: A__ = len(references[0] ) if any(len(SCREAMING_SNAKE_CASE__ ) != references_per_prediction for refs in references ): raise ValueError("Sacrebleu requires the same number of references for each prediction" ) A__ = [[refs[i] for refs in references] for i in range(SCREAMING_SNAKE_CASE__ )] A__ = CHRF(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) A__ = sb_chrf.corpus_score(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return { "score": output.score, "char_order": output.char_order, "word_order": output.word_order, "beta": output.beta, }
237
from __future__ import annotations from statistics import mean def __magic_name__ ( __lowerCAmelCase : list[int] , __lowerCAmelCase : list[int] , __lowerCAmelCase : int ) -> list[int]: __lowerCamelCase = [0] * no_of_processes __lowerCamelCase = [0] * no_of_processes # Initialize remaining_time to waiting_time. for i in range(__lowerCAmelCase ): __lowerCamelCase = burst_time[i] __lowerCamelCase = [] __lowerCamelCase = 0 __lowerCamelCase = 0 # When processes are not completed, # A process whose arrival time has passed \ # and has remaining execution time is put into the ready_process. # The shortest process in the ready_process, target_process is executed. while completed != no_of_processes: __lowerCamelCase = [] __lowerCamelCase = -1 for i in range(__lowerCAmelCase ): if (arrival_time[i] <= total_time) and (remaining_time[i] > 0): ready_process.append(__lowerCAmelCase ) if len(__lowerCAmelCase ) > 0: __lowerCamelCase = ready_process[0] for i in ready_process: if remaining_time[i] < remaining_time[target_process]: __lowerCamelCase = i total_time += burst_time[target_process] completed += 1 __lowerCamelCase = 0 __lowerCamelCase = ( total_time - arrival_time[target_process] - burst_time[target_process] ) else: total_time += 1 return waiting_time def __magic_name__ ( __lowerCAmelCase : list[int] , __lowerCAmelCase : int , __lowerCAmelCase : list[int] ) -> list[int]: __lowerCamelCase = [0] * no_of_processes for i in range(__lowerCAmelCase ): __lowerCamelCase = burst_time[i] + waiting_time[i] return turn_around_time if __name__ == "__main__": print("[TEST CASE 01]") SCREAMING_SNAKE_CASE__ : Tuple = 4 SCREAMING_SNAKE_CASE__ : Optional[int] = [2, 5, 3, 7] SCREAMING_SNAKE_CASE__ : List[str] = [0, 0, 0, 0] SCREAMING_SNAKE_CASE__ : str = calculate_waitingtime(arrival_time, burst_time, no_of_processes) SCREAMING_SNAKE_CASE__ : Union[str, Any] = calculate_turnaroundtime( burst_time, no_of_processes, waiting_time ) # Printing the Result print("PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time") for i, process_id in enumerate(list(range(1, 5))): print( F'{process_id}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t' F'{waiting_time[i]}\t\t\t\t{turn_around_time[i]}' ) print(F'\nAverage waiting time = {mean(waiting_time):.5f}') print(F'Average turnaround time = {mean(turn_around_time):.5f}')
270
0
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar lowerCAmelCase__ = TypeVar("""T""") def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: int ) -> int: '''simple docstring''' return (position - 1) // 2 def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: int ) -> int: '''simple docstring''' return (2 * position) + 1 def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: int ) -> int: '''simple docstring''' return (2 * position) + 2 class a__ ( Generic[T] ): """simple docstring""" def __init__( self ) -> None: '''simple docstring''' A__ = [] A__ = {} A__ = 0 def __len__( self ) -> int: '''simple docstring''' return self.elements def __repr__( self ) -> str: '''simple docstring''' return str(self.heap ) def UpperCamelCase ( self ) -> bool: '''simple docstring''' return self.elements == 0 def UpperCamelCase ( self , lowercase , lowercase ) -> None: '''simple docstring''' self.heap.append((elem, weight) ) A__ = self.elements self.elements += 1 self._bubble_up(SCREAMING_SNAKE_CASE__ ) def UpperCamelCase ( self ) -> T: '''simple docstring''' if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) A__ , A__ = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: A__ , A__ = self.heap[0] self._bubble_down(SCREAMING_SNAKE_CASE__ ) return elem def UpperCamelCase ( self , lowercase , lowercase ) -> None: '''simple docstring''' A__ = self.position_map[elem] A__ = (elem, weight) if position > 0: A__ = get_parent_position(SCREAMING_SNAKE_CASE__ ) A__ , A__ = self.heap[parent_position] if parent_weight > weight: self._bubble_up(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) def UpperCamelCase ( self , lowercase ) -> None: '''simple docstring''' A__ = self.position_map[elem] if curr_pos == 0: return None A__ = get_parent_position(SCREAMING_SNAKE_CASE__ ) A__ , A__ = self.heap[curr_pos] A__ , A__ = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_up(SCREAMING_SNAKE_CASE__ ) return None def UpperCamelCase ( self , lowercase ) -> None: '''simple docstring''' A__ = self.position_map[elem] A__ , A__ = self.heap[curr_pos] A__ = get_child_left_position(SCREAMING_SNAKE_CASE__ ) A__ = get_child_right_position(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements and child_right_position < self.elements: A__ , A__ = self.heap[child_left_position] A__ , A__ = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements: A__ , A__ = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: return None if child_right_position < self.elements: A__ , A__ = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) return None def UpperCamelCase ( self , lowercase , lowercase ) -> None: '''simple docstring''' A__ = self.heap[nodea_pos][0] A__ = self.heap[nodea_pos][0] A__ , A__ = ( self.heap[nodea_pos], self.heap[nodea_pos], ) A__ = nodea_pos A__ = nodea_pos class a__ ( Generic[T] ): """simple docstring""" def __init__( self ) -> None: '''simple docstring''' A__ = {} A__ = 0 def __repr__( self ) -> str: '''simple docstring''' return str(self.connections ) def __len__( self ) -> int: '''simple docstring''' return self.nodes def UpperCamelCase ( self , lowercase ) -> None: '''simple docstring''' if node not in self.connections: A__ = {} self.nodes += 1 def UpperCamelCase ( self , lowercase , lowercase , lowercase ) -> None: '''simple docstring''' self.add_node(SCREAMING_SNAKE_CASE__ ) self.add_node(SCREAMING_SNAKE_CASE__ ) A__ = weight A__ = weight def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: GraphUndirectedWeighted[T] , ) -> tuple[dict[T, int], dict[T, T | None]]: '''simple docstring''' A__ = {node: maxsize for node in graph.connections} A__ = {node: None for node in graph.connections} A__ = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(__lowerCAmelCase , __lowerCAmelCase ) if priority_queue.is_empty(): return dist, parent # initialization A__ = priority_queue.extract_min() A__ = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: A__ = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(__lowerCAmelCase , dist[neighbour] ) A__ = node # running prim's algorithm while not priority_queue.is_empty(): A__ = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: A__ = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(__lowerCAmelCase , dist[neighbour] ) A__ = node return dist, parent
68
from abc import ABC, abstractmethod from argparse import ArgumentParser class lowerCAmelCase__ ( __lowercase ): @staticmethod @abstractmethod def __A ( SCREAMING_SNAKE_CASE__ : ArgumentParser ) -> str: raise NotImplementedError() @abstractmethod def __A ( self : Optional[int] ) -> Union[str, Any]: raise NotImplementedError()
270
0
"""simple docstring""" # We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation import warnings from .state import AcceleratorState, GradientState warnings.filterwarnings('''ignore''', category=UserWarning, module='''torch.optim.lr_scheduler''') class __lowerCamelCase : '''simple docstring''' def __init__( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = True , __UpperCAmelCase = False ) -> Any: _a = scheduler _a = optimizers if isinstance(SCREAMING_SNAKE_CASE__ , (list, tuple) ) else [optimizers] _a = split_batches _a = step_with_optimizer _a = GradientState() def _UpperCAmelCase ( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> List[str]: if not self.step_with_optimizer: # No link between scheduler and optimizer -> just step self.scheduler.step(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) return # Otherwise, first make sure the optimizer was stepped. if not self.gradient_state.sync_gradients: if self.gradient_state.adjust_scheduler: self.scheduler._step_count += 1 return for opt in self.optimizers: if opt.step_was_skipped: return if self.split_batches: # Split batches -> the training dataloader batch size is not changed so one step per training step self.scheduler.step(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) else: # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do # num_processes steps per training step _a = AcceleratorState().num_processes for _ in range(SCREAMING_SNAKE_CASE__ ): # Special case when using OneCycle and `drop_last` was not used if hasattr(self.scheduler , '''total_steps''' ): if self.scheduler._step_count <= self.scheduler.total_steps: self.scheduler.step(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) else: self.scheduler.step(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( self ) -> str: return self.scheduler.get_last_lr() def _UpperCAmelCase ( self ) -> int: return self.scheduler.state_dict() def _UpperCAmelCase ( self , __UpperCAmelCase ) -> List[Any]: self.scheduler.load_state_dict(SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( self ) -> Optional[Any]: return self.scheduler.get_lr() def _UpperCAmelCase ( self , *__UpperCAmelCase , **__UpperCAmelCase ) -> Union[str, Any]: return self.scheduler.print_lr(*SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
320
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv("""TEST_SAGEMAKER""" , """False""" ) ) is not True , reason="""Skipping test because should only be run when releasing minor transformers version""" , ) @pytest.mark.usefixtures("""sm_env""" ) @parameterized_class( [ { """framework""": """pytorch""", """script""": """run_glue_model_parallelism.py""", """model_name_or_path""": """roberta-large""", """instance_type""": """ml.p3dn.24xlarge""", """results""": {"""train_runtime""": 1_600, """eval_accuracy""": 0.3, """eval_loss""": 1.2}, }, { """framework""": """pytorch""", """script""": """run_glue.py""", """model_name_or_path""": """roberta-large""", """instance_type""": """ml.p3dn.24xlarge""", """results""": {"""train_runtime""": 1_600, """eval_accuracy""": 0.3, """eval_loss""": 1.2}, }, ] ) class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Optional[int] ) -> List[Any]: if self.framework == "pytorch": subprocess.run( f'''cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'''.split() , encoding='''utf-8''' , check=SCREAMING_SNAKE_CASE__ , ) assert hasattr(self , '''env''' ) def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: # configuration for running training on smdistributed Model Parallel __lowerCamelCase = { '''enabled''': True, '''processes_per_host''': 8, } __lowerCamelCase = { '''enabled''': True, '''parameters''': { '''microbatches''': 4, '''placement_strategy''': '''spread''', '''pipeline''': '''interleaved''', '''optimize''': '''speed''', '''partitions''': 4, '''ddp''': True, }, } __lowerCamelCase = {'''smdistributed''': {'''modelparallel''': smp_options}, '''mpi''': mpi_options} __lowerCamelCase = '''trainer''' if self.script == '''run_glue.py''' else '''smtrainer''' # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=f'''{self.env.base_job_name}-{instance_count}-smp-{name_extension}''' , instance_count=SCREAMING_SNAKE_CASE__ , instance_type=self.instance_type , debugger_hook_config=SCREAMING_SNAKE_CASE__ , hyperparameters={ **self.env.hyperparameters, '''model_name_or_path''': self.model_name_or_path, '''max_steps''': 5_00, } , metric_definitions=self.env.metric_definitions , distribution=SCREAMING_SNAKE_CASE__ , py_version='''py36''' , ) def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[str]: TrainingJobAnalytics(SCREAMING_SNAKE_CASE__ ).export_csv(f'''{self.env.test_path}/{job_name}_metrics.csv''' ) @parameterized.expand([(1,)] ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: # create estimator __lowerCamelCase = self.create_estimator(SCREAMING_SNAKE_CASE__ ) # run training estimator.fit() # result dataframe __lowerCamelCase = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __lowerCamelCase = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) __lowerCamelCase = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 99_99_99 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy ) assert all(t <= self.results['''eval_loss'''] for t in eval_loss ) # dump tests result into json file to share in PR with open(f'''{estimator.latest_training_job.name}.json''' , '''w''' ) as outfile: json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss} , SCREAMING_SNAKE_CASE__ )
270
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) A : Optional[int] = {"configuration_fnet": ["FNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "FNetConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Optional[int] = ["FNetTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : Tuple = ["FNetTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: A : List[str] = [ "FNET_PRETRAINED_MODEL_ARCHIVE_LIST", "FNetForMaskedLM", "FNetForMultipleChoice", "FNetForNextSentencePrediction", "FNetForPreTraining", "FNetForQuestionAnswering", "FNetForSequenceClassification", "FNetForTokenClassification", "FNetLayer", "FNetModel", "FNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys A : List[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
305
from __future__ import annotations from fractions import Fraction def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> bool: return ( num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den ) def __magic_name__ ( __lowerCAmelCase : int ) -> list[str]: __lowerCamelCase = [] __lowerCamelCase = 11 __lowerCamelCase = int('''1''' + '''0''' * digit_len ) for num in range(__lowerCAmelCase , __lowerCAmelCase ): while den <= 99: if (num != den) and (num % 10 == den // 10) and (den % 10 != 0): if is_digit_cancelling(__lowerCAmelCase , __lowerCAmelCase ): solutions.append(f'''{num}/{den}''' ) den += 1 num += 1 __lowerCamelCase = 10 return solutions def __magic_name__ ( __lowerCAmelCase : int = 2 ) -> int: __lowerCamelCase = 1.0 for fraction in fraction_list(__lowerCAmelCase ): __lowerCamelCase = Fraction(__lowerCAmelCase ) result *= frac.denominator / frac.numerator return int(__lowerCAmelCase ) if __name__ == "__main__": print(solution())
270
0
'''simple docstring''' from __future__ import annotations def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : list[list[int]] ): '''simple docstring''' for i in range(1 , len(matrix[0] ) ): matrix[0][i] += matrix[0][i - 1] # preprocessing the first column for i in range(1 , len(__lowerCAmelCase ) ): matrix[i][0] += matrix[i - 1][0] # updating the path cost for current position for i in range(1 , len(__lowerCAmelCase ) ): for j in range(1 , len(matrix[0] ) ): matrix[i][j] += min(matrix[i - 1][j] , matrix[i][j - 1] ) return matrix[-1][-1] if __name__ == "__main__": import doctest doctest.testmod()
346
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE__ : List[str] = { "configuration_blip": [ "BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlipConfig", "BlipTextConfig", "BlipVisionConfig", ], "processing_blip": ["BlipProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = ["BlipImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "BLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "BlipModel", "BlipPreTrainedModel", "BlipForConditionalGeneration", "BlipForQuestionAnswering", "BlipVisionModel", "BlipTextModel", "BlipForImageTextRetrieval", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Any = [ "TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "TFBlipModel", "TFBlipPreTrainedModel", "TFBlipForConditionalGeneration", "TFBlipForQuestionAnswering", "TFBlipVisionModel", "TFBlipTextModel", "TFBlipForImageTextRetrieval", ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
270
0
import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionPanoramaPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() @skip_mps class _lowercase ( __lowercase , __lowercase , unittest.TestCase): """simple docstring""" A__ = StableDiffusionPanoramaPipeline A__ = TEXT_TO_IMAGE_PARAMS A__ = TEXT_TO_IMAGE_BATCH_PARAMS A__ = TEXT_TO_IMAGE_IMAGE_PARAMS A__ = TEXT_TO_IMAGE_IMAGE_PARAMS def lowerCAmelCase ( self : List[Any] ): '''simple docstring''' torch.manual_seed(0 ) lowerCamelCase__ : Dict = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) lowerCamelCase__ : int = DDIMScheduler() torch.manual_seed(0 ) lowerCamelCase__ : Optional[int] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) torch.manual_seed(0 ) lowerCamelCase__ : int = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) lowerCamelCase__ : Union[str, Any] = CLIPTextModel(SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Union[str, Any] = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) lowerCamelCase__ : int = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, } return components def lowerCAmelCase ( self : Optional[int] , __lowerCamelCase : List[str] , __lowerCamelCase : int=0 ): '''simple docstring''' lowerCamelCase__ : Any = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : str = { "prompt": "a photo of the dolomites", "generator": generator, # Setting height and width to None to prevent OOMs on CPU. "height": None, "width": None, "num_inference_steps": 1, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def lowerCAmelCase ( self : List[Any] ): '''simple docstring''' lowerCamelCase__ : List[Any] = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCamelCase__ : Any = self.get_dummy_components() lowerCamelCase__ : Optional[Any] = StableDiffusionPanoramaPipeline(**SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Tuple = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Union[str, Any] = sd_pipe(**SCREAMING_SNAKE_CASE__ ).images lowerCamelCase__ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowerCamelCase__ : Tuple = np.array([0.6_1_8_6, 0.5_3_7_4, 0.4_9_1_5, 0.4_1_3_5, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_7, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' super().test_inference_batch_consistent(batch_sizes=[1, 2] ) def lowerCAmelCase ( self : Tuple ): '''simple docstring''' super().test_inference_batch_single_identical(batch_size=2 , expected_max_diff=3.2_5E-3 ) def lowerCAmelCase ( self : Optional[Any] ): '''simple docstring''' lowerCamelCase__ : Dict = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCamelCase__ : List[str] = self.get_dummy_components() lowerCamelCase__ : Dict = StableDiffusionPanoramaPipeline(**SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Any = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : List[Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : List[str] = "french fries" lowerCamelCase__ : Optional[int] = sd_pipe(**SCREAMING_SNAKE_CASE__ , negative_prompt=SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : List[str] = output.images lowerCamelCase__ : int = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowerCamelCase__ : Optional[Any] = np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def lowerCAmelCase ( self : Any ): '''simple docstring''' lowerCamelCase__ : int = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCamelCase__ : int = self.get_dummy_components() lowerCamelCase__ : List[str] = StableDiffusionPanoramaPipeline(**SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Union[str, Any] = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : str = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Tuple = sd_pipe(**SCREAMING_SNAKE_CASE__ , view_batch_size=2 ) lowerCamelCase__ : int = output.images lowerCamelCase__ : str = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowerCamelCase__ : int = np.array([0.6_1_8_7, 0.5_3_7_5, 0.4_9_1_5, 0.4_1_3_6, 0.4_1_1_4, 0.4_5_6_3, 0.5_1_2_8, 0.4_9_7_6, 0.4_7_5_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def lowerCAmelCase ( self : Tuple ): '''simple docstring''' lowerCamelCase__ : Union[str, Any] = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCamelCase__ : Dict = self.get_dummy_components() lowerCamelCase__ : Tuple = EulerAncestralDiscreteScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="scaled_linear" ) lowerCamelCase__ : List[Any] = StableDiffusionPanoramaPipeline(**SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : int = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Tuple = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : int = sd_pipe(**SCREAMING_SNAKE_CASE__ ).images lowerCamelCase__ : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowerCamelCase__ : Union[str, Any] = np.array([0.4_0_2_4, 0.6_5_1_0, 0.4_9_0_1, 0.5_3_7_8, 0.5_8_1_3, 0.5_6_2_2, 0.4_7_9_5, 0.4_4_6_7, 0.4_9_5_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def lowerCAmelCase ( self : List[Any] ): '''simple docstring''' lowerCamelCase__ : int = "cpu" # ensure determinism for the device-dependent torch.Generator lowerCamelCase__ : Any = self.get_dummy_components() lowerCamelCase__ : Optional[int] = PNDMScheduler( beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule="scaled_linear" , skip_prk_steps=SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Tuple = StableDiffusionPanoramaPipeline(**SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Optional[Any] = sd_pipe.to(SCREAMING_SNAKE_CASE__ ) sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Union[str, Any] = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Tuple = sd_pipe(**SCREAMING_SNAKE_CASE__ ).images lowerCamelCase__ : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) lowerCamelCase__ : Dict = np.array([0.6_3_9_1, 0.6_2_9_1, 0.4_8_6_1, 0.5_1_3_4, 0.5_5_5_2, 0.4_5_7_8, 0.5_0_3_2, 0.5_0_2_3, 0.4_5_3_9] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch_gpu class _lowercase ( unittest.TestCase): """simple docstring""" def lowerCAmelCase ( self : Any ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : List[Any] , __lowerCamelCase : str=0 ): '''simple docstring''' lowerCamelCase__ : List[str] = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Optional[Any] = { "prompt": "a photo of the dolomites", "generator": generator, "num_inference_steps": 3, "guidance_scale": 7.5, "output_type": "numpy", } return inputs def lowerCAmelCase ( self : Union[str, Any] ): '''simple docstring''' lowerCamelCase__ : Tuple = "stabilityai/stable-diffusion-2-base" lowerCamelCase__ : List[Any] = DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ , subfolder="scheduler" ) lowerCamelCase__ : Dict = StableDiffusionPanoramaPipeline.from_pretrained(SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ , safety_checker=SCREAMING_SNAKE_CASE__ ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) pipe.enable_attention_slicing() lowerCamelCase__ : Dict = self.get_inputs() lowerCamelCase__ : Optional[int] = pipe(**SCREAMING_SNAKE_CASE__ ).images lowerCamelCase__ : Optional[Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2048, 3) lowerCamelCase__ : Optional[Any] = np.array( [ 0.3_6_9_6_8_3_9_2, 0.2_7_0_2_5_3_7_2, 0.3_2_4_4_6_7_6_6, 0.2_8_3_7_9_3_8_7, 0.3_6_3_6_3_2_7_4, 0.3_0_7_3_3_3_4_7, 0.2_7_1_0_0_0_2_7, 0.2_7_0_5_4_1_2_5, 0.2_5_5_3_6_0_9_6, ] ) assert np.abs(expected_slice - image_slice ).max() < 1E-2 def lowerCAmelCase ( self : List[str] ): '''simple docstring''' lowerCamelCase__ : Any = StableDiffusionPanoramaPipeline.from_pretrained( "stabilityai/stable-diffusion-2-base" , safety_checker=SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : str = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) pipe.enable_attention_slicing() lowerCamelCase__ : Dict = self.get_inputs() lowerCamelCase__ : str = pipe(**SCREAMING_SNAKE_CASE__ ).images lowerCamelCase__ : str = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 2048, 3) lowerCamelCase__ : List[str] = np.array( [ [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ] ] ) assert np.abs(expected_slice - image_slice ).max() < 1E-3 def lowerCAmelCase ( self : Tuple ): '''simple docstring''' lowerCamelCase__ : Tuple = 0 def callback_fn(__lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : torch.FloatTensor ) -> None: lowerCamelCase__ : Tuple = True nonlocal number_of_steps number_of_steps += 1 if step == 1: lowerCamelCase__ : List[Any] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) lowerCamelCase__ : str = latents[0, -3:, -3:, -1] lowerCamelCase__ : Optional[int] = np.array( [ 0.1_8_6_8_1_8_6_9, 0.3_3_9_0_7_8_1_6, 0.5_3_6_1_2_7_6, 0.1_4_4_3_2_8_6_5, -0.0_2_8_5_6_6_1_1, -0.7_3_9_4_1_1_2_3, 0.2_3_3_9_7_9_8_7, 0.4_7_3_2_2_6_8_2, -0.3_7_8_2_3_1_6_4, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 elif step == 2: lowerCamelCase__ : List[str] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 256) lowerCamelCase__ : str = latents[0, -3:, -3:, -1] lowerCamelCase__ : Optional[int] = np.array( [ 0.1_8_5_3_9_6_4_5, 0.3_3_9_8_7_2_4_8, 0.5_3_7_8_5_5_9, 0.1_4_4_3_7_1_4_2, -0.0_2_4_5_5_2_6_1, -0.7_3_3_8_3_1_7, 0.2_3_9_9_0_7_5_5, 0.4_7_3_5_6_2_7_2, -0.3_7_8_6_5_0_5, ] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5E-2 lowerCamelCase__ : Any = False lowerCamelCase__ : Dict = "stabilityai/stable-diffusion-2-base" lowerCamelCase__ : Optional[int] = DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ , subfolder="scheduler" ) lowerCamelCase__ : List[Any] = StableDiffusionPanoramaPipeline.from_pretrained(SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ , safety_checker=SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Tuple = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) pipe.enable_attention_slicing() lowerCamelCase__ : List[str] = self.get_inputs() pipe(**SCREAMING_SNAKE_CASE__ , callback=SCREAMING_SNAKE_CASE__ , callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def lowerCAmelCase ( self : Union[str, Any] ): '''simple docstring''' torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() lowerCamelCase__ : Any = "stabilityai/stable-diffusion-2-base" lowerCamelCase__ : Optional[Any] = DDIMScheduler.from_pretrained(SCREAMING_SNAKE_CASE__ , subfolder="scheduler" ) lowerCamelCase__ : List[Any] = StableDiffusionPanoramaPipeline.from_pretrained(SCREAMING_SNAKE_CASE__ , scheduler=SCREAMING_SNAKE_CASE__ , safety_checker=SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : List[Any] = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() lowerCamelCase__ : Tuple = self.get_inputs() lowerCamelCase__ : Any = pipe(**SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Dict = torch.cuda.max_memory_allocated() # make sure that less than 5.2 GB is allocated assert mem_bytes < 5.5 * 10**9
184
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Optional[Any] = {"configuration_wavlm": ["WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "WavLMConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST", "WavLMForAudioFrameClassification", "WavLMForCTC", "WavLMForSequenceClassification", "WavLMForXVector", "WavLMModel", "WavLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_wavlm import WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP, WavLMConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavlm import ( WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST, WavLMForAudioFrameClassification, WavLMForCTC, WavLMForSequenceClassification, WavLMForXVector, WavLMModel, WavLMPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
270
0
"""simple docstring""" import inspect import unittest import numpy as np from transformers import BeitConfig from transformers.testing_utils import require_flax, require_vision, slow from transformers.utils import cached_property, is_flax_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor if is_flax_available(): import jax from transformers import FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class A_ ( unittest.TestCase ): """simple docstring""" def __init__( self :Optional[int] , lowerCamelCase_ :Any , lowerCamelCase_ :Optional[Any]=100 , lowerCamelCase_ :List[str]=13 , lowerCamelCase_ :List[Any]=30 , lowerCamelCase_ :int=2 , lowerCamelCase_ :int=3 , lowerCamelCase_ :Union[str, Any]=True , lowerCamelCase_ :List[str]=True , lowerCamelCase_ :Any=32 , lowerCamelCase_ :List[str]=5 , lowerCamelCase_ :Tuple=4 , lowerCamelCase_ :Any=37 , lowerCamelCase_ :List[Any]="gelu" , lowerCamelCase_ :int=0.1 , lowerCamelCase_ :Dict=0.1 , lowerCamelCase_ :int=10 , lowerCamelCase_ :Dict=0.02 , lowerCamelCase_ :Dict=3 , ): """simple docstring""" lowerCamelCase__ : Union[str, Any] =parent lowerCamelCase__ : str =vocab_size lowerCamelCase__ : int =batch_size lowerCamelCase__ : Any =image_size lowerCamelCase__ : Any =patch_size lowerCamelCase__ : Optional[int] =num_channels lowerCamelCase__ : Any =is_training lowerCamelCase__ : List[str] =use_labels lowerCamelCase__ : Tuple =hidden_size lowerCamelCase__ : Dict =num_hidden_layers lowerCamelCase__ : str =num_attention_heads lowerCamelCase__ : List[Any] =intermediate_size lowerCamelCase__ : Any =hidden_act lowerCamelCase__ : Optional[int] =hidden_dropout_prob lowerCamelCase__ : Optional[Any] =attention_probs_dropout_prob lowerCamelCase__ : List[str] =type_sequence_label_size lowerCamelCase__ : List[Any] =initializer_range # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) lowerCamelCase__ : List[str] =(image_size // patch_size) ** 2 lowerCamelCase__ : Union[str, Any] =num_patches + 1 def UpperCAmelCase__ ( self :Union[str, Any] ): """simple docstring""" lowerCamelCase__ : int =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowerCamelCase__ : List[Any] =None if self.use_labels: lowerCamelCase__ : List[Any] =ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCamelCase__ : Union[str, Any] =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 , ) return config, pixel_values, labels def UpperCAmelCase__ ( self :List[Any] , lowerCamelCase_ :List[str] , lowerCamelCase_ :Optional[Any] , lowerCamelCase_ :Union[str, Any] ): """simple docstring""" lowerCamelCase__ : List[Any] =FlaxBeitModel(config=SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : int =model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCAmelCase__ ( self :Any , lowerCamelCase_ :Union[str, Any] , lowerCamelCase_ :str , lowerCamelCase_ :List[str] ): """simple docstring""" lowerCamelCase__ : List[Any] =FlaxBeitForMaskedImageModeling(config=SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Optional[Any] =model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length - 1, self.vocab_size) ) def UpperCAmelCase__ ( self :int , lowerCamelCase_ :Optional[int] , lowerCamelCase_ :int , lowerCamelCase_ :Optional[int] ): """simple docstring""" lowerCamelCase__ : List[Any] =self.type_sequence_label_size lowerCamelCase__ : List[str] =FlaxBeitForImageClassification(config=SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Any =model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images lowerCamelCase__ : Optional[int] =1 lowerCamelCase__ : str =FlaxBeitForImageClassification(SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Optional[int] =floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowerCamelCase__ : List[Any] =model(SCREAMING_SNAKE_CASE__ ) def UpperCAmelCase__ ( self :Tuple ): """simple docstring""" lowerCamelCase__ : int =self.prepare_config_and_inputs() ( ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ) : List[Any] =config_and_inputs lowerCamelCase__ : Optional[Any] ={'pixel_values': pixel_values} return config, inputs_dict @require_flax class A_ ( __lowercase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ = ( (FlaxBeitModel, FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling) if is_flax_available() else () ) def UpperCAmelCase__ ( self :int ): """simple docstring""" lowerCamelCase__ : Optional[Any] =FlaxBeitModelTester(self ) lowerCamelCase__ : int =ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , has_text_modality=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def UpperCAmelCase__ ( self :Optional[int] ): """simple docstring""" self.config_tester.run_common_tests() def UpperCAmelCase__ ( self :List[Any] ): """simple docstring""" lowerCamelCase__ , lowerCamelCase__ : Union[str, Any] =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCamelCase__ : Optional[int] =model_class(SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Tuple =inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCamelCase__ : Optional[Any] =[*signature.parameters.keys()] lowerCamelCase__ : Dict =['pixel_values'] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def UpperCAmelCase__ ( self :Union[str, Any] ): """simple docstring""" lowerCamelCase__ , lowerCamelCase__ : int =self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowerCamelCase__ : List[Any] =self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : int =model_class(SCREAMING_SNAKE_CASE__ ) @jax.jit def model_jitted(lowerCamelCase_ :str , **lowerCamelCase_ :Dict ): return model(pixel_values=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) with self.subTest('JIT Enabled' ): lowerCamelCase__ : Optional[Any] =model_jitted(**SCREAMING_SNAKE_CASE__ ).to_tuple() with self.subTest('JIT Disabled' ): with jax.disable_jit(): lowerCamelCase__ : Any =model_jitted(**SCREAMING_SNAKE_CASE__ ).to_tuple() self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) ) for jitted_output, output in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(jitted_output.shape , output.shape ) def UpperCAmelCase__ ( self :Any ): """simple docstring""" lowerCamelCase__ : List[str] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def UpperCAmelCase__ ( self :Any ): """simple docstring""" lowerCamelCase__ : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE__ ) def UpperCAmelCase__ ( self :Optional[int] ): """simple docstring""" lowerCamelCase__ : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__ ) @slow def UpperCAmelCase__ ( self :List[Any] ): """simple docstring""" for model_class_name in self.all_model_classes: lowerCamelCase__ : int =model_class_name.from_pretrained('microsoft/beit-base-patch16-224' ) lowerCamelCase__ : int =model(np.ones((1, 3, 224, 224) ) ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def lowerCAmelCase_ ( ) ->List[str]: lowerCamelCase__ : Dict =Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_vision @require_flax class A_ ( unittest.TestCase ): """simple docstring""" @cached_property def UpperCAmelCase__ ( self :List[str] ): """simple docstring""" return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224' ) if is_vision_available() else None @slow def UpperCAmelCase__ ( self :int ): """simple docstring""" lowerCamelCase__ : List[str] =FlaxBeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k' ) lowerCamelCase__ : List[str] =self.default_image_processor lowerCamelCase__ : List[str] =prepare_img() lowerCamelCase__ : Tuple =image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ).pixel_values # prepare bool_masked_pos lowerCamelCase__ : Optional[int] =np.ones((1, 196) , dtype=SCREAMING_SNAKE_CASE__ ) # forward pass lowerCamelCase__ : int =model(pixel_values=SCREAMING_SNAKE_CASE__ , bool_masked_pos=SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Union[str, Any] =outputs.logits # verify the logits lowerCamelCase__ : int =(1, 196, 8_192) self.assertEqual(logits.shape , SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : str =np.array( [[-3.24_37, 0.50_72, -13.91_74], [-3.24_56, 0.49_48, -13.94_01], [-3.20_33, 0.51_21, -13.85_50]] ) self.assertTrue(np.allclose(logits[bool_masked_pos][:3, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-2 ) ) @slow def UpperCAmelCase__ ( self :int ): """simple docstring""" lowerCamelCase__ : Dict =FlaxBeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224' ) lowerCamelCase__ : int =self.default_image_processor lowerCamelCase__ : Any =prepare_img() lowerCamelCase__ : Union[str, Any] =image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) # forward pass lowerCamelCase__ : Dict =model(**SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Tuple =outputs.logits # verify the logits lowerCamelCase__ : Dict =(1, 1_000) self.assertEqual(logits.shape , SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : int =np.array([-1.23_85, -1.09_87, -1.01_08] ) self.assertTrue(np.allclose(logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) lowerCamelCase__ : Any =281 self.assertEqual(logits.argmax(-1 ).item() , SCREAMING_SNAKE_CASE__ ) @slow def UpperCAmelCase__ ( self :Dict ): """simple docstring""" lowerCamelCase__ : Union[str, Any] =FlaxBeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k' ) lowerCamelCase__ : List[str] =self.default_image_processor lowerCamelCase__ : int =prepare_img() lowerCamelCase__ : Tuple =image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors='np' ) # forward pass lowerCamelCase__ : List[str] =model(**SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : List[Any] =outputs.logits # verify the logits lowerCamelCase__ : str =(1, 21_841) self.assertEqual(logits.shape , SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Dict =np.array([1.68_81, -0.27_87, 0.59_01] ) self.assertTrue(np.allclose(logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) lowerCamelCase__ : Optional[int] =2_396 self.assertEqual(logits.argmax(-1 ).item() , SCREAMING_SNAKE_CASE__ )
126
import pprint import requests SCREAMING_SNAKE_CASE__ : str = "https://zenquotes.io/api" def __magic_name__ ( ) -> list: return requests.get(API_ENDPOINT_URL + '''/today''' ).json() def __magic_name__ ( ) -> list: return requests.get(API_ENDPOINT_URL + '''/random''' ).json() if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : int = random_quotes() pprint.pprint(response)
270
0
"""simple docstring""" import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def snake_case__ ( __lowerCamelCase : str ): """simple docstring""" lowerCamelCase__ : Dict =filter(lambda __lowerCamelCase : p.requires_grad , model.parameters() ) lowerCamelCase__ : Tuple =sum([np.prod(p.size() ) for p in model_parameters] ) return params _lowercase : Union[str, Any] = logging.getLogger(__name__) def snake_case__ ( __lowerCamelCase : Any , __lowerCamelCase : Dict ): """simple docstring""" if metric == "rouge2": lowerCamelCase__ : Dict ='''{val_avg_rouge2:.4f}-{step_count}''' elif metric == "bleu": lowerCamelCase__ : int ='''{val_avg_bleu:.4f}-{step_count}''' elif metric == "em": lowerCamelCase__ : Any ='''{val_avg_em:.4f}-{step_count}''' elif metric == "loss": lowerCamelCase__ : Tuple ='''{val_avg_loss:.4f}-{step_count}''' else: raise NotImplementedError( f'''seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this''' ''' function.''' ) lowerCamelCase__ : Any =ModelCheckpoint( dirpath=__lowerCAmelCase , filename=__lowerCAmelCase , monitor=f'''val_{metric}''' , mode='''max''' , save_top_k=1 , every_n_epochs=1 , ) return checkpoint_callback def snake_case__ ( __lowerCamelCase : int , __lowerCamelCase : List[Any] ): """simple docstring""" return EarlyStopping( monitor=f'''val_{metric}''' , mode='''min''' if '''loss''' in metric else '''max''' , patience=__lowerCAmelCase , verbose=__lowerCAmelCase , ) class __SCREAMING_SNAKE_CASE ( pl.Callback ): '''simple docstring''' def snake_case ( self : List[str], lowerCamelCase : Optional[int], lowerCamelCase : Dict )-> Union[str, Any]: lowerCamelCase__ : Tuple ={F'''lr_group_{i}''': param['''lr'''] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(SCREAMING_SNAKE_CASE__ ) @rank_zero_only def snake_case ( self : Tuple, lowerCamelCase : pl.Trainer, lowerCamelCase : pl.LightningModule, lowerCamelCase : str, lowerCamelCase : List[str]=True )-> None: logger.info(F'''***** {type_path} results at step {trainer.global_step:05d} *****''' ) lowerCamelCase__ : Union[str, Any] =trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ['''log''', '''progress_bar''', '''preds''']} ) # Log results lowerCamelCase__ : Optional[Any] =Path(pl_module.hparams.output_dir ) if type_path == "test": lowerCamelCase__ : Any =od / '''test_results.txt''' lowerCamelCase__ : Union[str, Any] =od / '''test_generations.txt''' else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. lowerCamelCase__ : str =od / F'''{type_path}_results/{trainer.global_step:05d}.txt''' lowerCamelCase__ : Optional[Any] =od / F'''{type_path}_generations/{trainer.global_step:05d}.txt''' results_file.parent.mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) generations_file.parent.mkdir(exist_ok=SCREAMING_SNAKE_CASE__ ) with open(SCREAMING_SNAKE_CASE__, '''a+''' ) as writer: for key in sorted(SCREAMING_SNAKE_CASE__ ): if key in ["log", "progress_bar", "preds"]: continue lowerCamelCase__ : Tuple =metrics[key] if isinstance(SCREAMING_SNAKE_CASE__, torch.Tensor ): lowerCamelCase__ : List[str] =val.item() lowerCamelCase__ : str =F'''{key}: {val:.6f}\n''' writer.write(SCREAMING_SNAKE_CASE__ ) if not save_generations: return if "preds" in metrics: lowerCamelCase__ : Tuple ='''\n'''.join(metrics['''preds'''] ) generations_file.open('''w+''' ).write(SCREAMING_SNAKE_CASE__ ) @rank_zero_only def snake_case ( self : str, lowerCamelCase : int, lowerCamelCase : List[Any] )-> Any: try: lowerCamelCase__ : int =pl_module.model.model.num_parameters() except AttributeError: lowerCamelCase__ : Tuple =pl_module.model.num_parameters() lowerCamelCase__ : int =count_trainable_parameters(SCREAMING_SNAKE_CASE__ ) # mp stands for million parameters trainer.logger.log_metrics({'''n_params''': npars, '''mp''': npars / 1E6, '''grad_mp''': n_trainable_pars / 1E6} ) @rank_zero_only def snake_case ( self : Union[str, Any], lowerCamelCase : pl.Trainer, lowerCamelCase : pl.LightningModule )-> List[str]: save_json(pl_module.metrics, pl_module.metrics_save_path ) return self._write_logs(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, '''test''' ) @rank_zero_only def snake_case ( self : Optional[int], lowerCamelCase : pl.Trainer, lowerCamelCase : List[str] )-> Dict: save_json(pl_module.metrics, pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
238
from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def __magic_name__ ( __lowerCAmelCase : int ) -> int: __lowerCamelCase = prime_factors(__lowerCAmelCase ) if is_square_free(__lowerCAmelCase ): return -1 if len(__lowerCAmelCase ) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
270
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowercase__ : List[Any] = logging.get_logger(__name__) lowercase__ : Any = { "facebook/xlm-roberta-xl": "https://huggingface.co/facebook/xlm-roberta-xl/resolve/main/config.json", "facebook/xlm-roberta-xxl": "https://huggingface.co/facebook/xlm-roberta-xxl/resolve/main/config.json", # See all XLM-RoBERTa-XL models at https://huggingface.co/models?filter=xlm-roberta-xl } class UpperCAmelCase ( __lowercase ): '''simple docstring''' lowerCAmelCase_ = """xlm-roberta-xl""" def __init__( self : str , __lowercase : List[Any]=25_08_80 , __lowercase : Tuple=25_60 , __lowercase : Any=36 , __lowercase : Any=32 , __lowercase : str=1_02_40 , __lowercase : Union[str, Any]="gelu" , __lowercase : List[str]=0.1 , __lowercase : Optional[Any]=0.1 , __lowercase : Tuple=5_14 , __lowercase : Optional[int]=1 , __lowercase : int=0.02 , __lowercase : Optional[Any]=1E-05 , __lowercase : Optional[Any]=1 , __lowercase : Dict=0 , __lowercase : Union[str, Any]=2 , __lowercase : List[Any]="absolute" , __lowercase : int=True , __lowercase : Tuple=None , **__lowercase : Union[str, Any] , ): """simple docstring""" super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ , bos_token_id=SCREAMING_SNAKE_CASE__ , eos_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) snake_case_ = vocab_size snake_case_ = hidden_size snake_case_ = num_hidden_layers snake_case_ = num_attention_heads snake_case_ = hidden_act snake_case_ = intermediate_size snake_case_ = hidden_dropout_prob snake_case_ = attention_probs_dropout_prob snake_case_ = max_position_embeddings snake_case_ = type_vocab_size snake_case_ = initializer_range snake_case_ = layer_norm_eps snake_case_ = position_embedding_type snake_case_ = use_cache snake_case_ = classifier_dropout class UpperCAmelCase ( __lowercase ): '''simple docstring''' @property def snake_case__ ( self : Any ): """simple docstring""" if self.task == "multiple-choice": snake_case_ = {0: "batch", 1: "choice", 2: "sequence"} else: snake_case_ = {0: "batch", 1: "sequence"} return OrderedDict( [ ("input_ids", dynamic_axis), ("attention_mask", dynamic_axis), ] )
187
import argparse import collections import json import os import re import string import sys import numpy as np SCREAMING_SNAKE_CASE__ : Union[str, Any] = re.compile(r"\b(a|an|the)\b", re.UNICODE) SCREAMING_SNAKE_CASE__ : int = None def __magic_name__ ( ) -> str: __lowerCamelCase = argparse.ArgumentParser('''Official evaluation script for SQuAD version 2.0.''' ) parser.add_argument('''data_file''' , metavar='''data.json''' , help='''Input data JSON file.''' ) parser.add_argument('''pred_file''' , metavar='''pred.json''' , help='''Model predictions.''' ) parser.add_argument( '''--out-file''' , '''-o''' , metavar='''eval.json''' , help='''Write accuracy metrics to file (default is stdout).''' ) parser.add_argument( '''--na-prob-file''' , '''-n''' , metavar='''na_prob.json''' , help='''Model estimates of probability of no answer.''' ) parser.add_argument( '''--na-prob-thresh''' , '''-t''' , type=__lowerCAmelCase , default=1.0 , help='''Predict "" if no-answer probability exceeds this (default = 1.0).''' , ) parser.add_argument( '''--out-image-dir''' , '''-p''' , metavar='''out_images''' , default=__lowerCAmelCase , help='''Save precision-recall curves to directory.''' ) parser.add_argument('''--verbose''' , '''-v''' , action='''store_true''' ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def __magic_name__ ( __lowerCAmelCase : List[str] ) -> Union[str, Any]: __lowerCamelCase = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __lowerCamelCase = bool(qa['''answers''']['''text'''] ) return qid_to_has_ans def __magic_name__ ( __lowerCAmelCase : Dict ) -> Optional[Any]: def remove_articles(__lowerCAmelCase : Optional[int] ): return ARTICLES_REGEX.sub(''' ''' , __lowerCAmelCase ) def white_space_fix(__lowerCAmelCase : Optional[int] ): return " ".join(text.split() ) def remove_punc(__lowerCAmelCase : Union[str, Any] ): __lowerCamelCase = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(__lowerCAmelCase : Dict ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(__lowerCAmelCase ) ) ) ) def __magic_name__ ( __lowerCAmelCase : List[Any] ) -> Optional[int]: if not s: return [] return normalize_answer(__lowerCAmelCase ).split() def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple ) -> int: return int(normalize_answer(__lowerCAmelCase ) == normalize_answer(__lowerCAmelCase ) ) def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : Tuple ) -> str: __lowerCamelCase = get_tokens(__lowerCAmelCase ) __lowerCamelCase = get_tokens(__lowerCAmelCase ) __lowerCamelCase = collections.Counter(__lowerCAmelCase ) & collections.Counter(__lowerCAmelCase ) __lowerCamelCase = sum(common.values() ) if len(__lowerCAmelCase ) == 0 or len(__lowerCAmelCase ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 __lowerCamelCase = 1.0 * num_same / len(__lowerCAmelCase ) __lowerCamelCase = 1.0 * num_same / len(__lowerCAmelCase ) __lowerCamelCase = (2 * precision * recall) / (precision + recall) return fa def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : List[str] ) -> Optional[Any]: __lowerCamelCase = {} __lowerCamelCase = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __lowerCamelCase = qa['''id'''] __lowerCamelCase = [t for t in qa['''answers''']['''text'''] if normalize_answer(__lowerCAmelCase )] if not gold_answers: # For unanswerable questions, only correct answer is empty string __lowerCamelCase = [''''''] if qid not in preds: print(f'''Missing prediction for {qid}''' ) continue __lowerCamelCase = preds[qid] # Take max over all gold answers __lowerCamelCase = max(compute_exact(__lowerCAmelCase , __lowerCAmelCase ) for a in gold_answers ) __lowerCamelCase = max(compute_fa(__lowerCAmelCase , __lowerCAmelCase ) for a in gold_answers ) return exact_scores, fa_scores def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Union[str, Any] ) -> List[str]: __lowerCamelCase = {} for qid, s in scores.items(): __lowerCamelCase = na_probs[qid] > na_prob_thresh if pred_na: __lowerCamelCase = float(not qid_to_has_ans[qid] ) else: __lowerCamelCase = s return new_scores def __magic_name__ ( __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[Any]=None ) -> Union[str, Any]: if not qid_list: __lowerCamelCase = len(__lowerCAmelCase ) return collections.OrderedDict( [ ('''exact''', 100.0 * sum(exact_scores.values() ) / total), ('''f1''', 100.0 * sum(fa_scores.values() ) / total), ('''total''', total), ] ) else: __lowerCamelCase = len(__lowerCAmelCase ) return collections.OrderedDict( [ ('''exact''', 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ('''f1''', 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ('''total''', total), ] ) def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : str , __lowerCAmelCase : Optional[Any] ) -> int: for k in new_eval: __lowerCamelCase = new_eval[k] def __magic_name__ ( __lowerCAmelCase : Optional[int] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : Union[str, Any] ) -> Optional[Any]: plt.step(__lowerCAmelCase , __lowerCAmelCase , color='''b''' , alpha=0.2 , where='''post''' ) plt.fill_between(__lowerCAmelCase , __lowerCAmelCase , step='''post''' , alpha=0.2 , color='''b''' ) plt.xlabel('''Recall''' ) plt.ylabel('''Precision''' ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(__lowerCAmelCase ) plt.savefig(__lowerCAmelCase ) plt.clf() def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[Any]=None , __lowerCAmelCase : Tuple=None ) -> int: __lowerCamelCase = sorted(__lowerCAmelCase , key=lambda __lowerCAmelCase : na_probs[k] ) __lowerCamelCase = 0.0 __lowerCamelCase = 1.0 __lowerCamelCase = 0.0 __lowerCamelCase = [1.0] __lowerCamelCase = [0.0] __lowerCamelCase = 0.0 for i, qid in enumerate(__lowerCAmelCase ): if qid_to_has_ans[qid]: true_pos += scores[qid] __lowerCamelCase = true_pos / float(i + 1 ) __lowerCamelCase = true_pos / float(__lowerCAmelCase ) if i == len(__lowerCAmelCase ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(__lowerCAmelCase ) recalls.append(__lowerCAmelCase ) if out_image: plot_pr_curve(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) return {"ap": 100.0 * avg_prec} def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Tuple , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : List[Any] ) -> List[Any]: if out_image_dir and not os.path.exists(__lowerCAmelCase ): os.makedirs(__lowerCAmelCase ) __lowerCamelCase = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_exact.png''' ) , title='''Precision-Recall curve for Exact Match score''' , ) __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_f1.png''' ) , title='''Precision-Recall curve for F1 score''' , ) __lowerCamelCase = {k: float(__lowerCAmelCase ) for k, v in qid_to_has_ans.items()} __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_oracle.png''' ) , title='''Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)''' , ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_exact''' ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_f1''' ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_oracle''' ) def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Any , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : int ) -> Optional[Any]: if not qid_list: return __lowerCamelCase = [na_probs[k] for k in qid_list] __lowerCamelCase = np.ones_like(__lowerCAmelCase ) / float(len(__lowerCAmelCase ) ) plt.hist(__lowerCAmelCase , weights=__lowerCAmelCase , bins=20 , range=(0.0, 1.0) ) plt.xlabel('''Model probability of no-answer''' ) plt.ylabel('''Proportion of dataset''' ) plt.title(f'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(__lowerCAmelCase , f'''na_prob_hist_{name}.png''' ) ) plt.clf() def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Union[str, Any] ) -> Optional[int]: __lowerCamelCase = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) __lowerCamelCase = num_no_ans __lowerCamelCase = cur_score __lowerCamelCase = 0.0 __lowerCamelCase = sorted(__lowerCAmelCase , key=lambda __lowerCAmelCase : na_probs[k] ) for i, qid in enumerate(__lowerCAmelCase ): if qid not in scores: continue if qid_to_has_ans[qid]: __lowerCamelCase = scores[qid] else: if preds[qid]: __lowerCamelCase = -1 else: __lowerCamelCase = 0 cur_score += diff if cur_score > best_score: __lowerCamelCase = cur_score __lowerCamelCase = na_probs[qid] return 100.0 * best_score / len(__lowerCAmelCase ), best_thresh def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : int , __lowerCAmelCase : Optional[Any] ) -> int: __lowerCamelCase , __lowerCamelCase = find_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = find_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = best_exact __lowerCamelCase = exact_thresh __lowerCamelCase = best_fa __lowerCamelCase = fa_thresh def __magic_name__ ( ) -> Optional[int]: with open(OPTS.data_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) __lowerCamelCase = dataset_json['''data'''] with open(OPTS.pred_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) else: __lowerCamelCase = {k: 0.0 for k in preds} __lowerCamelCase = make_qid_to_has_ans(__lowerCAmelCase ) # maps qid to True/False __lowerCamelCase = [k for k, v in qid_to_has_ans.items() if v] __lowerCamelCase = [k for k, v in qid_to_has_ans.items() if not v] __lowerCamelCase , __lowerCamelCase = get_raw_scores(__lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = apply_no_ans_threshold(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.na_prob_thresh ) __lowerCamelCase = apply_no_ans_threshold(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.na_prob_thresh ) __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase ) if has_ans_qids: __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase , qid_list=__lowerCAmelCase ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''HasAns''' ) if no_ans_qids: __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase , qid_list=__lowerCAmelCase ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''NoAns''' ) if OPTS.na_prob_file: find_all_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir ) histogram_na_prob(__lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir , '''hasAns''' ) histogram_na_prob(__lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir , '''noAns''' ) if OPTS.out_file: with open(OPTS.out_file , '''w''' ) as f: json.dump(__lowerCAmelCase , __lowerCAmelCase ) else: print(json.dumps(__lowerCAmelCase , indent=2 ) ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Any = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt main()
270
0
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DetrConfig, DetrForObjectDetection, DetrForSegmentation, DetrImageProcessor, ResNetConfig from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase = logging.get_logger(__name__) def __lowerCamelCase ( snake_case__ ) -> List[Any]: """simple docstring""" if "resnet-50" in model_name: _SCREAMING_SNAKE_CASE = ResNetConfig.from_pretrained("""microsoft/resnet-50""" ) elif "resnet-101" in model_name: _SCREAMING_SNAKE_CASE = ResNetConfig.from_pretrained("""microsoft/resnet-101""" ) else: raise ValueError("""Model name should include either resnet50 or resnet101""" ) _SCREAMING_SNAKE_CASE = DetrConfig(use_timm_backbone=__lowerCAmelCase ,backbone_config=__lowerCAmelCase ) # set label attributes _SCREAMING_SNAKE_CASE = """panoptic""" in model_name if is_panoptic: _SCREAMING_SNAKE_CASE = 2_50 else: _SCREAMING_SNAKE_CASE = 91 _SCREAMING_SNAKE_CASE = """huggingface/label-files""" _SCREAMING_SNAKE_CASE = """coco-detection-id2label.json""" _SCREAMING_SNAKE_CASE = json.load(open(hf_hub_download(__lowerCAmelCase ,__lowerCAmelCase ,repo_type="""dataset""" ) ,"""r""" ) ) _SCREAMING_SNAKE_CASE = {int(__lowerCAmelCase ): v for k, v in idalabel.items()} _SCREAMING_SNAKE_CASE = idalabel _SCREAMING_SNAKE_CASE = {v: k for k, v in idalabel.items()} return config, is_panoptic def __lowerCamelCase ( snake_case__ ) -> Union[str, Any]: """simple docstring""" _SCREAMING_SNAKE_CASE = [] # stem # fmt: off rename_keys.append(("""backbone.0.body.conv1.weight""", """backbone.conv_encoder.model.embedder.embedder.convolution.weight""") ) rename_keys.append(("""backbone.0.body.bn1.weight""", """backbone.conv_encoder.model.embedder.embedder.normalization.weight""") ) rename_keys.append(("""backbone.0.body.bn1.bias""", """backbone.conv_encoder.model.embedder.embedder.normalization.bias""") ) rename_keys.append(("""backbone.0.body.bn1.running_mean""", """backbone.conv_encoder.model.embedder.embedder.normalization.running_mean""") ) rename_keys.append(("""backbone.0.body.bn1.running_var""", """backbone.conv_encoder.model.embedder.embedder.normalization.running_var""") ) # stages for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): # shortcut if layer_idx == 0: rename_keys.append( ( F'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.0.weight', F'backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.convolution.weight', ) ) rename_keys.append( ( F'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.weight', F'backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.weight', ) ) rename_keys.append( ( F'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.bias', F'backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.bias', ) ) rename_keys.append( ( F'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_mean', F'backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_mean', ) ) rename_keys.append( ( F'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_var', F'backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_var', ) ) # 3 convs for i in range(3 ): rename_keys.append( ( F'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.conv{i+1}.weight', F'backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.convolution.weight', ) ) rename_keys.append( ( F'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.weight', F'backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.weight', ) ) rename_keys.append( ( F'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.bias', F'backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.bias', ) ) rename_keys.append( ( F'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_mean', F'backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_mean', ) ) rename_keys.append( ( F'backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_var', F'backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var', ) ) # fmt: on for i in range(config.encoder_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( ( F'transformer.encoder.layers.{i}.self_attn.out_proj.weight', F'encoder.layers.{i}.self_attn.out_proj.weight', ) ) rename_keys.append( (F'transformer.encoder.layers.{i}.self_attn.out_proj.bias', F'encoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append((F'transformer.encoder.layers.{i}.linear1.weight', F'encoder.layers.{i}.fc1.weight') ) rename_keys.append((F'transformer.encoder.layers.{i}.linear1.bias', F'encoder.layers.{i}.fc1.bias') ) rename_keys.append((F'transformer.encoder.layers.{i}.linear2.weight', F'encoder.layers.{i}.fc2.weight') ) rename_keys.append((F'transformer.encoder.layers.{i}.linear2.bias', F'encoder.layers.{i}.fc2.bias') ) rename_keys.append( (F'transformer.encoder.layers.{i}.norm1.weight', F'encoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append( (F'transformer.encoder.layers.{i}.norm1.bias', F'encoder.layers.{i}.self_attn_layer_norm.bias') ) rename_keys.append( (F'transformer.encoder.layers.{i}.norm2.weight', F'encoder.layers.{i}.final_layer_norm.weight') ) rename_keys.append((F'transformer.encoder.layers.{i}.norm2.bias', F'encoder.layers.{i}.final_layer_norm.bias') ) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( ( F'transformer.decoder.layers.{i}.self_attn.out_proj.weight', F'decoder.layers.{i}.self_attn.out_proj.weight', ) ) rename_keys.append( (F'transformer.decoder.layers.{i}.self_attn.out_proj.bias', F'decoder.layers.{i}.self_attn.out_proj.bias') ) rename_keys.append( ( F'transformer.decoder.layers.{i}.multihead_attn.out_proj.weight', F'decoder.layers.{i}.encoder_attn.out_proj.weight', ) ) rename_keys.append( ( F'transformer.decoder.layers.{i}.multihead_attn.out_proj.bias', F'decoder.layers.{i}.encoder_attn.out_proj.bias', ) ) rename_keys.append((F'transformer.decoder.layers.{i}.linear1.weight', F'decoder.layers.{i}.fc1.weight') ) rename_keys.append((F'transformer.decoder.layers.{i}.linear1.bias', F'decoder.layers.{i}.fc1.bias') ) rename_keys.append((F'transformer.decoder.layers.{i}.linear2.weight', F'decoder.layers.{i}.fc2.weight') ) rename_keys.append((F'transformer.decoder.layers.{i}.linear2.bias', F'decoder.layers.{i}.fc2.bias') ) rename_keys.append( (F'transformer.decoder.layers.{i}.norm1.weight', F'decoder.layers.{i}.self_attn_layer_norm.weight') ) rename_keys.append( (F'transformer.decoder.layers.{i}.norm1.bias', F'decoder.layers.{i}.self_attn_layer_norm.bias') ) rename_keys.append( (F'transformer.decoder.layers.{i}.norm2.weight', F'decoder.layers.{i}.encoder_attn_layer_norm.weight') ) rename_keys.append( (F'transformer.decoder.layers.{i}.norm2.bias', F'decoder.layers.{i}.encoder_attn_layer_norm.bias') ) rename_keys.append( (F'transformer.decoder.layers.{i}.norm3.weight', F'decoder.layers.{i}.final_layer_norm.weight') ) rename_keys.append((F'transformer.decoder.layers.{i}.norm3.bias', F'decoder.layers.{i}.final_layer_norm.bias') ) # convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("""input_proj.weight""", """input_projection.weight"""), ("""input_proj.bias""", """input_projection.bias"""), ("""query_embed.weight""", """query_position_embeddings.weight"""), ("""transformer.decoder.norm.weight""", """decoder.layernorm.weight"""), ("""transformer.decoder.norm.bias""", """decoder.layernorm.bias"""), ("""class_embed.weight""", """class_labels_classifier.weight"""), ("""class_embed.bias""", """class_labels_classifier.bias"""), ("""bbox_embed.layers.0.weight""", """bbox_predictor.layers.0.weight"""), ("""bbox_embed.layers.0.bias""", """bbox_predictor.layers.0.bias"""), ("""bbox_embed.layers.1.weight""", """bbox_predictor.layers.1.weight"""), ("""bbox_embed.layers.1.bias""", """bbox_predictor.layers.1.bias"""), ("""bbox_embed.layers.2.weight""", """bbox_predictor.layers.2.weight"""), ("""bbox_embed.layers.2.bias""", """bbox_predictor.layers.2.bias"""), ] ) return rename_keys def __lowerCamelCase ( snake_case__ ,snake_case__ ,snake_case__ ) -> int: """simple docstring""" _SCREAMING_SNAKE_CASE = state_dict.pop(__lowerCAmelCase ) _SCREAMING_SNAKE_CASE = val def __lowerCamelCase ( snake_case__ ,snake_case__=False ) -> Tuple: """simple docstring""" _SCREAMING_SNAKE_CASE = """""" if is_panoptic: _SCREAMING_SNAKE_CASE = """detr.""" # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) _SCREAMING_SNAKE_CASE = state_dict.pop(F'{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight' ) _SCREAMING_SNAKE_CASE = state_dict.pop(F'{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias' ) # next, add query, keys and values (in that order) to the state dict _SCREAMING_SNAKE_CASE = in_proj_weight[:2_56, :] _SCREAMING_SNAKE_CASE = in_proj_bias[:2_56] _SCREAMING_SNAKE_CASE = in_proj_weight[2_56:5_12, :] _SCREAMING_SNAKE_CASE = in_proj_bias[2_56:5_12] _SCREAMING_SNAKE_CASE = in_proj_weight[-2_56:, :] _SCREAMING_SNAKE_CASE = in_proj_bias[-2_56:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention _SCREAMING_SNAKE_CASE = state_dict.pop(F'{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight' ) _SCREAMING_SNAKE_CASE = state_dict.pop(F'{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias' ) # next, add query, keys and values (in that order) to the state dict _SCREAMING_SNAKE_CASE = in_proj_weight[:2_56, :] _SCREAMING_SNAKE_CASE = in_proj_bias[:2_56] _SCREAMING_SNAKE_CASE = in_proj_weight[2_56:5_12, :] _SCREAMING_SNAKE_CASE = in_proj_bias[2_56:5_12] _SCREAMING_SNAKE_CASE = in_proj_weight[-2_56:, :] _SCREAMING_SNAKE_CASE = in_proj_bias[-2_56:] # read in weights + bias of input projection layer of cross-attention _SCREAMING_SNAKE_CASE = state_dict.pop( F'{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight' ) _SCREAMING_SNAKE_CASE = state_dict.pop(F'{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias' ) # next, add query, keys and values (in that order) of cross-attention to the state dict _SCREAMING_SNAKE_CASE = in_proj_weight_cross_attn[:2_56, :] _SCREAMING_SNAKE_CASE = in_proj_bias_cross_attn[:2_56] _SCREAMING_SNAKE_CASE = in_proj_weight_cross_attn[2_56:5_12, :] _SCREAMING_SNAKE_CASE = in_proj_bias_cross_attn[2_56:5_12] _SCREAMING_SNAKE_CASE = in_proj_weight_cross_attn[-2_56:, :] _SCREAMING_SNAKE_CASE = in_proj_bias_cross_attn[-2_56:] def __lowerCamelCase ( ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE = """http://images.cocodataset.org/val2017/000000039769.jpg""" _SCREAMING_SNAKE_CASE = Image.open(requests.get(__lowerCAmelCase ,stream=__lowerCAmelCase ).raw ) return im @torch.no_grad() def __lowerCamelCase ( snake_case__ ,snake_case__=None ,snake_case__=False ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = get_detr_config(__lowerCAmelCase ) # load original model from torch hub _SCREAMING_SNAKE_CASE = { """detr-resnet-50""": """detr_resnet50""", """detr-resnet-101""": """detr_resnet101""", } logger.info(F'Converting model {model_name}...' ) _SCREAMING_SNAKE_CASE = torch.hub.load("""facebookresearch/detr""" ,model_name_to_original_name[model_name] ,pretrained=__lowerCAmelCase ).eval() _SCREAMING_SNAKE_CASE = detr.state_dict() # rename keys for src, dest in create_rename_keys(__lowerCAmelCase ): if is_panoptic: _SCREAMING_SNAKE_CASE = """detr.""" + src rename_key(__lowerCAmelCase ,__lowerCAmelCase ,__lowerCAmelCase ) # query, key and value matrices need special treatment read_in_q_k_v(__lowerCAmelCase ,is_panoptic=__lowerCAmelCase ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them _SCREAMING_SNAKE_CASE = """detr.model.""" if is_panoptic else """model.""" for key in state_dict.copy().keys(): if is_panoptic: if ( key.startswith("""detr""" ) and not key.startswith("""class_labels_classifier""" ) and not key.startswith("""bbox_predictor""" ) ): _SCREAMING_SNAKE_CASE = state_dict.pop(__lowerCAmelCase ) _SCREAMING_SNAKE_CASE = val elif "class_labels_classifier" in key or "bbox_predictor" in key: _SCREAMING_SNAKE_CASE = state_dict.pop(__lowerCAmelCase ) _SCREAMING_SNAKE_CASE = val elif key.startswith("""bbox_attention""" ) or key.startswith("""mask_head""" ): continue else: _SCREAMING_SNAKE_CASE = state_dict.pop(__lowerCAmelCase ) _SCREAMING_SNAKE_CASE = val else: if not key.startswith("""class_labels_classifier""" ) and not key.startswith("""bbox_predictor""" ): _SCREAMING_SNAKE_CASE = state_dict.pop(__lowerCAmelCase ) _SCREAMING_SNAKE_CASE = val # finally, create HuggingFace model and load state dict _SCREAMING_SNAKE_CASE = DetrForSegmentation(__lowerCAmelCase ) if is_panoptic else DetrForObjectDetection(__lowerCAmelCase ) model.load_state_dict(__lowerCAmelCase ) model.eval() # verify our conversion on an image _SCREAMING_SNAKE_CASE = """coco_panoptic""" if is_panoptic else """coco_detection""" _SCREAMING_SNAKE_CASE = DetrImageProcessor(format=__lowerCAmelCase ) _SCREAMING_SNAKE_CASE = processor(images=prepare_img() ,return_tensors="""pt""" ) _SCREAMING_SNAKE_CASE = encoding["""pixel_values"""] _SCREAMING_SNAKE_CASE = detr(__lowerCAmelCase ) _SCREAMING_SNAKE_CASE = model(__lowerCAmelCase ) assert torch.allclose(outputs.logits ,original_outputs["""pred_logits"""] ,atol=1e-3 ) assert torch.allclose(outputs.pred_boxes ,original_outputs["""pred_boxes"""] ,atol=1e-3 ) if is_panoptic: assert torch.allclose(outputs.pred_masks ,original_outputs["""pred_masks"""] ,atol=1e-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(F'Saving PyTorch model and image processor to {pytorch_dump_folder_path}...' ) Path(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase ) model.save_pretrained(__lowerCAmelCase ) processor.save_pretrained(__lowerCAmelCase ) if push_to_hub: # Upload model and image processor to the hub logger.info("""Uploading PyTorch model and image processor to the hub...""" ) model.push_to_hub(F'nielsr/{model_name}' ) processor.push_to_hub(F'nielsr/{model_name}' ) if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() parser.add_argument( '''--model_name''', default='''detr-resnet-50''', type=str, choices=['''detr-resnet-50''', '''detr-resnet-101'''], help='''Name of the DETR model you\'d like to convert.''', ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the folder to output PyTorch model.''' ) parser.add_argument('''--push_to_hub''', action='''store_true''', help='''Whether to push the model to the hub or not.''') UpperCamelCase = parser.parse_args() convert_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
306
import math import os import re import sys import unittest from pathlib import Path from typing import Tuple from unittest.mock import patch from parameterized import parameterized from transformers.testing_utils import ( CaptureStderr, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, get_torch_dist_unique_port, require_apex, require_bitsandbytes, require_fairscale, require_torch, require_torch_gpu, require_torch_multi_gpu, require_torch_non_multi_gpu, slow, ) from transformers.trainer_callback import TrainerState from transformers.trainer_utils import set_seed SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.abspath(os.path.dirname(__file__)) with ExtendSysPath(F'{bindir}/../../examples/pytorch/translation'): from run_translation import main # noqa set_seed(42) SCREAMING_SNAKE_CASE__ : Any = "sshleifer/student_marian_en_ro_6_1" SCREAMING_SNAKE_CASE__ : Tuple = "sshleifer/tiny-mbart" @require_torch class lowerCAmelCase__ ( __lowercase ): def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple=False , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Optional[int]=True , ) -> Optional[int]: __lowerCamelCase = self.run_trainer( eval_steps=1 , max_len=12 , model_name=SCREAMING_SNAKE_CASE__ , num_train_epochs=1 , distributed=SCREAMING_SNAKE_CASE__ , extra_args_str=SCREAMING_SNAKE_CASE__ , predict_with_generate=SCREAMING_SNAKE_CASE__ , do_train=SCREAMING_SNAKE_CASE__ , do_eval=SCREAMING_SNAKE_CASE__ , do_predict=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = TrainerState.load_from_json(os.path.join(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history if not do_eval: return __lowerCamelCase = [log for log in logs if '''eval_loss''' in log.keys()] __lowerCamelCase = eval_metrics[0] if predict_with_generate: assert "eval_bleu" in first_step_stats __lowerCamelCase = eval_metrics[-1] assert isinstance(last_step_stats['''eval_bleu'''] , SCREAMING_SNAKE_CASE__ ) assert not math.isnan(float(last_step_stats['''eval_loss'''] ) ), "eval_loss must not be `nan`" @require_torch_non_multi_gpu def __A ( self : Optional[int] ) -> int: self.run_seqaseq_quick() @require_torch_multi_gpu def __A ( self : int ) -> List[str]: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ ) @require_torch_multi_gpu def __A ( self : Optional[Any] ) -> Tuple: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Dict ) -> Tuple: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp simple''' ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Optional[int] ) -> List[str]: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp simple --fp16''' ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Tuple ) -> Any: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp zero_dp_2''' , predict_with_generate=SCREAMING_SNAKE_CASE__ ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Dict ) -> Tuple: self.run_seqaseq_quick( distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp zero_dp_2 --fp16''' , predict_with_generate=SCREAMING_SNAKE_CASE__ ) @require_apex @require_torch_gpu def __A ( self : Union[str, Any] ) -> List[str]: # XXX: apex breaks the trainer if it's run twice e.g. run_seq2seq.main() from the same # program and it breaks other tests that run from the same pytest worker, therefore until this is # sorted out it must be run only in an external program, that is distributed=True in this # test and only under one or more gpus - if we want cpu will need to make a special test # # specifically to the problem traced it to self.optimizer.step() - if it's run 2nd time via # 2nd main() call it botches the future eval. # self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--fp16 --fp16_backend=apex''' ) # test 2nd time - was getting eval_loss': nan' # to reproduce the problem set distributed=False self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--fp16 --fp16_backend=apex''' ) @parameterized.expand(['''base''', '''low''', '''high''', '''mixed'''] ) @require_torch_multi_gpu def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[str] ) -> Optional[Any]: # as each sub-test is slow-ish split into multiple sub-tests to avoid CI timeout __lowerCamelCase = { # test with the default log_level - should be info and thus log info once '''base''': {'''extra_args_str''': '''''', '''n_matches''': 1}, # test with low log_level and log_level_replica - should be noisy on all processes # now the info string should appear twice on 2 processes '''low''': {'''extra_args_str''': '''--log_level debug --log_level_replica debug''', '''n_matches''': 2}, # test with high log_level and low log_level_replica # now the info string should appear once only on the replica '''high''': {'''extra_args_str''': '''--log_level error --log_level_replica debug''', '''n_matches''': 1}, # test with high log_level and log_level_replica - should be quiet on all processes '''mixed''': {'''extra_args_str''': '''--log_level error --log_level_replica error''', '''n_matches''': 0}, } __lowerCamelCase = experiments[experiment_id] __lowerCamelCase = {'''distributed''': True, '''predict_with_generate''': False, '''do_eval''': False, '''do_predict''': False} __lowerCamelCase = '''Running training''' with CaptureStderr() as cl: self.run_seqaseq_quick(**SCREAMING_SNAKE_CASE__ , extra_args_str=data['''extra_args_str'''] ) __lowerCamelCase = len(re.findall(SCREAMING_SNAKE_CASE__ , cl.err ) ) self.assertEqual(SCREAMING_SNAKE_CASE__ , data['''n_matches'''] ) @slow def __A ( self : Any ) -> Optional[Any]: __lowerCamelCase = self.run_trainer( eval_steps=2 , max_len=1_28 , model_name=SCREAMING_SNAKE_CASE__ , learning_rate=3e-4 , num_train_epochs=10 , distributed=SCREAMING_SNAKE_CASE__ , ) # Check metrics __lowerCamelCase = TrainerState.load_from_json(os.path.join(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history __lowerCamelCase = [log for log in logs if '''eval_loss''' in log.keys()] __lowerCamelCase = eval_metrics[0] __lowerCamelCase = eval_metrics[-1] assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing" assert isinstance(last_step_stats['''eval_bleu'''] , SCREAMING_SNAKE_CASE__ ) # test if do_predict saves generations and metrics __lowerCamelCase = os.listdir(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = {os.path.basename(SCREAMING_SNAKE_CASE__ ) for p in contents} assert "generated_predictions.txt" in contents assert "predict_results.json" in contents @slow @require_bitsandbytes def __A ( self : Optional[int] ) -> str: from transformers.training_args import OptimizerNames def train_and_return_metrics(SCREAMING_SNAKE_CASE__ : str ) -> Tuple[int, float]: __lowerCamelCase = '''--skip_memory_metrics 0''' __lowerCamelCase = self.run_trainer( max_len=1_28 , model_name=SCREAMING_SNAKE_CASE__ , learning_rate=3e-4 , num_train_epochs=1 , optim=SCREAMING_SNAKE_CASE__ , distributed=SCREAMING_SNAKE_CASE__ , extra_args_str=SCREAMING_SNAKE_CASE__ , do_eval=SCREAMING_SNAKE_CASE__ , do_predict=SCREAMING_SNAKE_CASE__ , n_gpus_to_use=1 , ) # Check metrics __lowerCamelCase = TrainerState.load_from_json(Path(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history __lowerCamelCase = int(logs[0]['''train_mem_gpu_peaked_delta'''] / 2**20 ) __lowerCamelCase = int(logs[0]['''train_mem_gpu_alloc_delta'''] / 2**20 ) __lowerCamelCase = logs[0]['''train_loss'''] return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = train_and_return_metrics(OptimizerNames.ADAMW_BNB.value ) __lowerCamelCase = gpu_alloc_mem_orig - gpu_alloc_mem_bnb __lowerCamelCase = gpu_peak_mem_orig + gpu_alloc_mem_orig __lowerCamelCase = gpu_peak_mem_bnb + gpu_alloc_mem_bnb __lowerCamelCase = gpu_total_mem_orig - gpu_total_mem_bnb # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized # in 2 bytes and the diff in optim memory usage is derived as so: # # - normal 25*8=~200MB (8 bytes per param) # - bnb 25*2= ~50MB (2 bytes per param) # # Thus we should expect ~150MB total memory saved. # # Peak memory should be the same - the total should be different by about that same margin # # After leaving a small margin to accommodate for differences between gpus let's check # that we have at least 120MB in savings __lowerCamelCase = 1_20 # uncomment the following if this test starts failing - requires py38 for a new print feature # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB") # print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB") # print(f"{gpu_alloc_mem_diff=}MB") # print(f"{gpu_peak_mem_diff=}MB") # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB") # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB") self.assertGreater( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got''' f''' a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and''' f''' gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB''' , ) self.assertGreater( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''should use ~150MB less total gpu memory with BNB, compared to without it for this model but got''' f''' a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and''' f''' gpu_total_mem_bnb={gpu_total_mem_bnb}MB''' , ) self.assertEqual( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , f'''loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}''' ) def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float = 3e-3 , SCREAMING_SNAKE_CASE__ : str = "adafactor" , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : int = None , ) -> List[Any]: __lowerCamelCase = self.test_file_dir / '''../fixtures/tests_samples/wmt_en_ro''' __lowerCamelCase = self.get_auto_remove_tmp_dir() __lowerCamelCase = f''' --model_name_or_path {model_name} --train_file {data_dir}/train.json --validation_file {data_dir}/val.json --test_file {data_dir}/test.json --output_dir {output_dir} --overwrite_output_dir --max_train_samples 8 --max_source_length {max_len} --max_target_length {max_len} --do_train --num_train_epochs {str(SCREAMING_SNAKE_CASE__ )} --per_device_train_batch_size 4 --learning_rate {learning_rate} --warmup_steps 8 --logging_steps 0 --logging_strategy no --save_steps {str(SCREAMING_SNAKE_CASE__ )} --group_by_length --label_smoothing_factor 0.1 --target_lang ro_RO --source_lang en_XX '''.split() __lowerCamelCase = f''' --do_eval --per_device_eval_batch_size 4 --max_eval_samples 8 --val_max_target_length {max_len} --evaluation_strategy steps --eval_steps {str(SCREAMING_SNAKE_CASE__ )} '''.split() __lowerCamelCase = ''' --do_predict '''.split() __lowerCamelCase = [] if do_train: args += args_train if do_eval: args += args_eval if do_predict: args += args_predict if predict_with_generate: args += "--predict_with_generate".split() if do_train: if optim == "adafactor": args += "--adafactor".split() else: args += f'''--optim {optim}'''.split() if extra_args_str is not None: args += extra_args_str.split() if distributed: if n_gpus_to_use is None: __lowerCamelCase = get_gpu_count() __lowerCamelCase = get_torch_dist_unique_port() __lowerCamelCase = f''' -m torch.distributed.run --nproc_per_node={n_gpus_to_use} --master_port={master_port} {self.examples_dir_str}/pytorch/translation/run_translation.py '''.split() __lowerCamelCase = [sys.executable] + distributed_args + args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(SCREAMING_SNAKE_CASE__ , env=self.get_env() ) else: __lowerCamelCase = ['''run_translation.py'''] + args with patch.object(SCREAMING_SNAKE_CASE__ , '''argv''' , SCREAMING_SNAKE_CASE__ ): main() return output_dir
270
0
'''simple docstring''' import collections import inspect import unittest from transformers import FocalNetConfig 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_backbone_common import BackboneTesterMixin 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 ( FocalNetBackbone, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetModel, ) from transformers.models.focalnet.modeling_focalnet import FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class a_ : def __init__( self : int , lowercase : List[str] , lowercase : Optional[int]=13 , lowercase : Optional[Any]=32 , lowercase : List[str]=2 , lowercase : int=3 , lowercase : List[str]=16 , lowercase : Dict=[32, 64, 128] , lowercase : Dict=[1, 2, 1] , lowercase : int=[2, 2, 4] , lowercase : List[str]=2 , lowercase : Optional[Any]=2.0 , lowercase : Tuple=True , lowercase : Optional[int]=0.0 , lowercase : Tuple=0.0 , lowercase : List[Any]=0.1 , lowercase : Tuple="gelu" , lowercase : Tuple=False , lowercase : str=True , lowercase : Optional[Any]=0.02 , lowercase : int=1e-5 , lowercase : Tuple=True , lowercase : Optional[int]=None , lowercase : Optional[Any]=True , lowercase : List[str]=10 , lowercase : str=8 , lowercase : Tuple=["stage1", "stage2"] , lowercase : str=[1, 2] , ): """simple docstring""" lowercase_ :Tuple = parent lowercase_ :List[str] = batch_size lowercase_ :Optional[Any] = image_size lowercase_ :Tuple = patch_size lowercase_ :List[str] = num_channels lowercase_ :Any = embed_dim lowercase_ :List[Any] = hidden_sizes lowercase_ :Any = depths lowercase_ :Optional[Any] = num_heads lowercase_ :Union[str, Any] = window_size lowercase_ :Optional[int] = mlp_ratio lowercase_ :List[Any] = qkv_bias lowercase_ :List[Any] = hidden_dropout_prob lowercase_ :Optional[Any] = attention_probs_dropout_prob lowercase_ :int = drop_path_rate lowercase_ :Dict = hidden_act lowercase_ :Union[str, Any] = use_absolute_embeddings lowercase_ :Dict = patch_norm lowercase_ :Dict = layer_norm_eps lowercase_ :Optional[Any] = initializer_range lowercase_ :int = is_training lowercase_ :Tuple = scope lowercase_ :int = use_labels lowercase_ :Optional[Any] = type_sequence_label_size lowercase_ :List[str] = encoder_stride lowercase_ :Optional[Any] = out_features lowercase_ :Dict = out_indices def lowercase__ ( self : Tuple ): """simple docstring""" lowercase_ :Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase_ :Tuple = None if self.use_labels: lowercase_ :str = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase_ :Tuple = self.get_config() return config, pixel_values, labels def lowercase__ ( self : Optional[int] ): """simple docstring""" return FocalNetConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , hidden_sizes=self.hidden_sizes , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , out_features=self.out_features , out_indices=self.out_indices , ) def lowercase__ ( self : Dict , lowercase : Dict , lowercase : Optional[int] , lowercase : Union[str, Any] ): """simple docstring""" lowercase_ :List[Any] = FocalNetModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowercase_ :Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ) lowercase_ :str = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) lowercase_ :List[Any] = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def lowercase__ ( self : Any , lowercase : Dict , lowercase : Tuple , lowercase : List[str] ): """simple docstring""" lowercase_ :List[str] = FocalNetBackbone(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowercase_ :Dict = model(SCREAMING_SNAKE_CASE__ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.image_size, 8, 8] ) # 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 lowercase_ :Union[str, Any] = None lowercase_ :Optional[int] = FocalNetBackbone(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowercase_ :List[Any] = model(SCREAMING_SNAKE_CASE__ ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.image_size * 2, 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def lowercase__ ( self : Any , lowercase : str , lowercase : Any , lowercase : Any ): """simple docstring""" lowercase_ :int = FocalNetForMaskedImageModeling(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowercase_ :Union[str, Any] = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images lowercase_ :Optional[int] = 1 lowercase_ :Tuple = FocalNetForMaskedImageModeling(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowercase_ :List[str] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowercase_ :List[str] = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def lowercase__ ( self : Optional[Any] , lowercase : Optional[Any] , lowercase : Optional[Any] , lowercase : List[Any] ): """simple docstring""" lowercase_ :Dict = self.type_sequence_label_size lowercase_ :str = FocalNetForImageClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowercase_ :List[Any] = 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_ :List[Any] = 1 lowercase_ :Dict = FocalNetForImageClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowercase_ :Optional[int] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) lowercase_ :List[str] = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def lowercase__ ( self : List[Any] ): """simple docstring""" lowercase_ :Optional[Any] = self.prepare_config_and_inputs() lowercase_ , lowercase_ , lowercase_ :Optional[int] = config_and_inputs lowercase_ :int = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class a_ ( __lowercase , __lowercase , unittest.TestCase ): __A = ( ( FocalNetModel, FocalNetForImageClassification, FocalNetForMaskedImageModeling, FocalNetBackbone, ) if is_torch_available() else () ) __A = ( {"""feature-extraction""": FocalNetModel, """image-classification""": FocalNetForImageClassification} if is_torch_available() else {} ) __A = False __A = False __A = False __A = False __A = False def lowercase__ ( self : List[Any] ): """simple docstring""" lowercase_ :Any = FocalNetModelTester(self ) lowercase_ :Dict = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , embed_dim=37 , has_text_modality=SCREAMING_SNAKE_CASE__ ) def lowercase__ ( self : Optional[int] ): """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 lowercase__ ( self : Union[str, Any] ): """simple docstring""" return def lowercase__ ( self : int ): """simple docstring""" lowercase_ :Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__ ) def lowercase__ ( self : int ): """simple docstring""" lowercase_ :str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*SCREAMING_SNAKE_CASE__ ) def lowercase__ ( self : List[Any] ): """simple docstring""" lowercase_ :int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*SCREAMING_SNAKE_CASE__ ) def lowercase__ ( self : Tuple ): """simple docstring""" lowercase_ :Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__ ) @unittest.skip(reason="FocalNet does not use inputs_embeds" ) def lowercase__ ( self : Any ): """simple docstring""" pass @unittest.skip(reason="FocalNet does not use feedforward chunking" ) def lowercase__ ( self : str ): """simple docstring""" pass def lowercase__ ( self : List[Any] ): """simple docstring""" lowercase_ , lowercase_ :List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: lowercase_ :List[str] = model_class(SCREAMING_SNAKE_CASE__ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowercase_ :Any = model.get_output_embeddings() self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__ , nn.Linear ) ) def lowercase__ ( self : List[Any] ): """simple docstring""" lowercase_ , lowercase_ :Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes[:-1]: 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_ :str = [*signature.parameters.keys()] lowercase_ :List[str] = ["pixel_values"] self.assertListEqual(arg_names[:1] , SCREAMING_SNAKE_CASE__ ) def lowercase__ ( self : int , lowercase : int , lowercase : List[Any] , lowercase : Tuple , lowercase : List[Any] ): """simple docstring""" lowercase_ :Optional[int] = model_class(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() with torch.no_grad(): lowercase_ :Optional[Any] = model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) lowercase_ :Tuple = outputs.hidden_states lowercase_ :Optional[int] = getattr( self.model_tester , "expected_num_hidden_layers" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) # FocalNet has a different seq_length lowercase_ :Optional[int] = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) lowercase_ :str = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) lowercase_ :Dict = outputs.reshaped_hidden_states self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) lowercase_ , lowercase_ , lowercase_ , lowercase_ :str = reshaped_hidden_states[0].shape lowercase_ :List[str] = ( reshaped_hidden_states[0].view(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def lowercase__ ( self : str ): """simple docstring""" lowercase_ , lowercase_ :int = self.model_tester.prepare_config_and_inputs_for_common() lowercase_ :Any = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes[:-1]: lowercase_ :str = True self.check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase_ :str = True self.check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def lowercase__ ( self : Optional[Any] ): """simple docstring""" lowercase_ , lowercase_ :List[str] = self.model_tester.prepare_config_and_inputs_for_common() lowercase_ :Any = 3 lowercase_ :Dict = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) lowercase_ :List[str] = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) lowercase_ :int = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) lowercase_ :Any = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes[:-1]: lowercase_ :Any = True self.check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase_ :int = True self.check_hidden_states_output(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , (padded_height, padded_width) ) @slow def lowercase__ ( self : int ): """simple docstring""" for model_name in FOCALNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowercase_ :Any = FocalNetModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) def lowercase__ ( self : int ): """simple docstring""" lowercase_ , lowercase_ :Tuple = self.model_tester.prepare_config_and_inputs_for_common() lowercase_ :List[str] = _config_zero_init(SCREAMING_SNAKE_CASE__ ) for model_class in self.all_model_classes: lowercase_ :Tuple = model_class(config=SCREAMING_SNAKE_CASE__ ) for name, param in model.named_parameters(): if "embeddings" not in name and 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' , ) @require_vision @require_torch class a_ ( unittest.TestCase ): @cached_property def lowercase__ ( self : List[Any] ): """simple docstring""" return AutoImageProcessor.from_pretrained("microsoft/focalnet-tiny" ) if is_vision_available() else None @slow def lowercase__ ( self : Tuple ): """simple docstring""" lowercase_ :int = FocalNetForImageClassification.from_pretrained("microsoft/focalnet-tiny" ).to(SCREAMING_SNAKE_CASE__ ) lowercase_ :int = self.default_image_processor lowercase_ :Optional[int] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) lowercase_ :List[Any] = image_processor(images=SCREAMING_SNAKE_CASE__ , return_tensors="pt" ).to(SCREAMING_SNAKE_CASE__ ) # forward pass with torch.no_grad(): lowercase_ :Optional[int] = model(**SCREAMING_SNAKE_CASE__ ) # verify the logits lowercase_ :int = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , SCREAMING_SNAKE_CASE__ ) lowercase_ :Union[str, Any] = torch.tensor([0.21_66, -0.43_68, 0.21_91] ).to(SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , SCREAMING_SNAKE_CASE__ , atol=1e-4 ) ) self.assertTrue(outputs.logits.argmax(dim=-1 ).item() , 281 ) @require_torch class a_ ( __lowercase , unittest.TestCase ): __A = (FocalNetBackbone,) if is_torch_available() else () __A = FocalNetConfig __A = False def lowercase__ ( self : Union[str, Any] ): """simple docstring""" lowercase_ :Union[str, Any] = FocalNetModelTester(self )
223
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING SCREAMING_SNAKE_CASE__ : Dict = { "facebook/mask2former-swin-small-coco-instance": ( "https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json" ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) class lowerCAmelCase__ ( __lowercase ): a__ : Any = """mask2former""" a__ : Dict = ["""swin"""] a__ : Any = {"""hidden_size""": """hidden_dim"""} def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Optional[Dict] = None , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 10_24 , SCREAMING_SNAKE_CASE__ : str = "relu" , SCREAMING_SNAKE_CASE__ : int = 6 , SCREAMING_SNAKE_CASE__ : int = 10 , SCREAMING_SNAKE_CASE__ : int = 8 , SCREAMING_SNAKE_CASE__ : float = 0.0 , SCREAMING_SNAKE_CASE__ : int = 20_48 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : int = 4 , SCREAMING_SNAKE_CASE__ : int = 2_55 , SCREAMING_SNAKE_CASE__ : int = 1_00 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 2.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : int = 1_25_44 , SCREAMING_SNAKE_CASE__ : float = 3.0 , SCREAMING_SNAKE_CASE__ : float = 0.75 , SCREAMING_SNAKE_CASE__ : float = 0.02 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 16, 32] , SCREAMING_SNAKE_CASE__ : bool = None , **SCREAMING_SNAKE_CASE__ : Tuple , ) -> str: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.''' ) __lowerCamelCase = CONFIG_MAPPING['''swin''']( image_size=2_24 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=SCREAMING_SNAKE_CASE__ , out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] , ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = backbone_config.pop('''model_type''' ) __lowerCamelCase = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase = config_class.from_dict(SCREAMING_SNAKE_CASE__ ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( f'''Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. ''' f'''Supported model types: {','.join(self.backbones_supported )}''' ) __lowerCamelCase = backbone_config __lowerCamelCase = feature_size __lowerCamelCase = mask_feature_size __lowerCamelCase = hidden_dim __lowerCamelCase = encoder_feedforward_dim __lowerCamelCase = activation_function __lowerCamelCase = encoder_layers __lowerCamelCase = decoder_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = dropout __lowerCamelCase = dim_feedforward __lowerCamelCase = pre_norm __lowerCamelCase = enforce_input_projection __lowerCamelCase = common_stride __lowerCamelCase = ignore_value __lowerCamelCase = num_queries __lowerCamelCase = no_object_weight __lowerCamelCase = class_weight __lowerCamelCase = mask_weight __lowerCamelCase = dice_weight __lowerCamelCase = train_num_points __lowerCamelCase = oversample_ratio __lowerCamelCase = importance_sample_ratio __lowerCamelCase = init_std __lowerCamelCase = init_xavier_std __lowerCamelCase = use_auxiliary_loss __lowerCamelCase = feature_strides __lowerCamelCase = output_auxiliary_logits __lowerCamelCase = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__ ) @classmethod def __A ( cls : Any , SCREAMING_SNAKE_CASE__ : PretrainedConfig , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: return cls( backbone_config=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def __A ( self : Any ) -> Dict[str, any]: __lowerCamelCase = copy.deepcopy(self.__dict__ ) __lowerCamelCase = self.backbone_config.to_dict() __lowerCamelCase = self.__class__.model_type return output
270
0
'''simple docstring''' # Lint as: python3 # pylint: enable=line-too-long # pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position __lowerCAmelCase : Union[str, Any] ="2.13.1" import platform import pyarrow from packaging import version if version.parse(platform.python_version()) < version.parse("3.7"): raise ImportWarning( "To use `datasets`, Python>=3.7 is required, and the current version of Python doesn't match this condition." ) if version.parse(pyarrow.__version__).major < 8: raise ImportWarning( "To use `datasets`, the module `pyarrow>=8.0.0` is required, and the current version of `pyarrow` doesn't match this condition.\n" "If you are running this in a Google Colab, you should probably just restart the runtime to use the right version of `pyarrow`." ) del platform del pyarrow del version from .arrow_dataset import Dataset from .arrow_reader import ReadInstruction from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder from .combine import concatenate_datasets, interleave_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .download import * from .features import * from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled from .info import DatasetInfo, MetricInfo from .inspect import ( get_dataset_config_info, get_dataset_config_names, get_dataset_infos, get_dataset_split_names, inspect_dataset, inspect_metric, list_datasets, list_metrics, ) from .iterable_dataset import IterableDataset from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric from .metric import Metric from .splits import ( NamedSplit, NamedSplitAll, Split, SplitBase, SplitDict, SplitGenerator, SplitInfo, SubSplitInfo, percent, ) from .tasks import * from .utils import * from .utils import logging # deprecated modules from datasets import arrow_dataset as _arrow_dataset # isort:skip from datasets import utils as _utils # isort:skip from datasets.utils import download_manager as _deprecated_download_manager # isort:skip __lowerCAmelCase : Tuple =concatenate_datasets __lowerCAmelCase : Optional[int] =DownloadConfig __lowerCAmelCase : Any =DownloadManager __lowerCAmelCase : Tuple =DownloadMode __lowerCAmelCase : Optional[Any] =DownloadConfig __lowerCAmelCase : Dict =DownloadMode __lowerCAmelCase : Optional[int] =DownloadManager del _arrow_dataset, _utils, _deprecated_download_manager
237
import os def __magic_name__ ( ) -> str: __lowerCamelCase = os.path.join(os.path.dirname(__lowerCAmelCase ) , '''num.txt''' ) with open(__lowerCAmelCase ) as file_hand: return str(sum(int(__lowerCAmelCase ) for line in file_hand ) )[:10] if __name__ == "__main__": print(solution())
270
0
from string import ascii_lowercase, ascii_uppercase def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str ) -> str: '''simple docstring''' if not sentence: return "" A__ = dict(zip(__lowerCAmelCase , __lowerCAmelCase ) ) return lower_to_upper.get(sentence[0] , sentence[0] ) + sentence[1:] if __name__ == "__main__": from doctest import testmod testmod()
68
import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available SCREAMING_SNAKE_CASE__ : Optional[int] = logging.getLogger(__name__) @dataclass class lowerCAmelCase__ : a__ : str a__ : List[str] a__ : Optional[List[str]] @dataclass class lowerCAmelCase__ : a__ : List[int] a__ : List[int] a__ : Optional[List[int]] = None a__ : Optional[List[int]] = None class lowerCAmelCase__ ( __lowercase ): a__ : Optional[Any] = """train""" a__ : Optional[int] = """dev""" a__ : Dict = """test""" class lowerCAmelCase__ : @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[Split, str] ) -> List[InputExample]: raise NotImplementedError @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : str ) -> List[str]: raise NotImplementedError @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : List[InputExample] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : List[str]="[CLS]" , SCREAMING_SNAKE_CASE__ : Tuple=1 , SCREAMING_SNAKE_CASE__ : str="[SEP]" , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False , SCREAMING_SNAKE_CASE__ : Tuple=0 , SCREAMING_SNAKE_CASE__ : int=0 , SCREAMING_SNAKE_CASE__ : str=-1_00 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE__ : List[Any]=True , ) -> List[InputFeatures]: __lowerCamelCase = {label: i for i, label in enumerate(SCREAMING_SNAKE_CASE__ )} __lowerCamelCase = [] for ex_index, example in enumerate(SCREAMING_SNAKE_CASE__ ): if ex_index % 1_00_00 == 0: logger.info('''Writing example %d of %d''' , SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = [] __lowerCamelCase = [] for word, label in zip(example.words , example.labels ): __lowerCamelCase = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(SCREAMING_SNAKE_CASE__ ) > 0: tokens.extend(SCREAMING_SNAKE_CASE__ ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(SCREAMING_SNAKE_CASE__ ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. __lowerCamelCase = tokenizer.num_special_tokens_to_add() if len(SCREAMING_SNAKE_CASE__ ) > max_seq_length - special_tokens_count: __lowerCamelCase = tokens[: (max_seq_length - special_tokens_count)] __lowerCamelCase = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] __lowerCamelCase = [sequence_a_segment_id] * len(SCREAMING_SNAKE_CASE__ ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: __lowerCamelCase = [cls_token] + tokens __lowerCamelCase = [pad_token_label_id] + label_ids __lowerCamelCase = [cls_token_segment_id] + segment_ids __lowerCamelCase = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. __lowerCamelCase = [1 if mask_padding_with_zero else 0] * len(SCREAMING_SNAKE_CASE__ ) # Zero-pad up to the sequence length. __lowerCamelCase = max_seq_length - len(SCREAMING_SNAKE_CASE__ ) if pad_on_left: __lowerCamelCase = ([pad_token] * padding_length) + input_ids __lowerCamelCase = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask __lowerCamelCase = ([pad_token_segment_id] * padding_length) + segment_ids __lowerCamelCase = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length if ex_index < 5: logger.info('''*** Example ***''' ) logger.info('''guid: %s''' , example.guid ) logger.info('''tokens: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in tokens] ) ) logger.info('''input_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in input_ids] ) ) logger.info('''input_mask: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in input_mask] ) ) logger.info('''segment_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in segment_ids] ) ) logger.info('''label_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: __lowerCamelCase = None features.append( InputFeatures( input_ids=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , label_ids=SCREAMING_SNAKE_CASE__ ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class lowerCAmelCase__ ( __lowercase ): a__ : List[InputFeatures] a__ : int = nn.CrossEntropyLoss().ignore_index def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : TokenClassificationTask , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False , SCREAMING_SNAKE_CASE__ : Split = Split.train , ) -> Union[str, Any]: # Load data features from cache or dataset file __lowerCamelCase = os.path.join( SCREAMING_SNAKE_CASE__ , '''cached_{}_{}_{}'''.format(mode.value , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE__ ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. __lowerCamelCase = cached_features_file + '''.lock''' with FileLock(SCREAMING_SNAKE_CASE__ ): if os.path.exists(SCREAMING_SNAKE_CASE__ ) and not overwrite_cache: logger.info(f'''Loading features from cached file {cached_features_file}''' ) __lowerCamelCase = torch.load(SCREAMING_SNAKE_CASE__ ) else: logger.info(f'''Creating features from dataset file at {data_dir}''' ) __lowerCamelCase = token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # TODO clean up all this to leverage built-in features of tokenizers __lowerCamelCase = token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f'''Saving features into cached file {cached_features_file}''' ) torch.save(self.features , SCREAMING_SNAKE_CASE__ ) def __len__( self : Dict ) -> str: return len(self.features ) def __getitem__( self : Any , SCREAMING_SNAKE_CASE__ : Dict ) -> InputFeatures: return self.features[i] if is_tf_available(): import tensorflow as tf class lowerCAmelCase__ : a__ : List[InputFeatures] a__ : int = -100 def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : TokenClassificationTask , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Split = Split.train , ) -> List[Any]: __lowerCamelCase = token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # TODO clean up all this to leverage built-in features of tokenizers __lowerCamelCase = token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: __lowerCamelCase = tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa}, tf.intaa) , ( {'''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: __lowerCamelCase = tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa}, tf.intaa) , ( { '''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] ), '''token_type_ids''': tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __A ( self : Union[str, Any] ) -> Union[str, Any]: __lowerCamelCase = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self : List[Any] ) -> Any: return len(self.features ) def __getitem__( self : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> InputFeatures: return self.features[i]
270
0
"""simple docstring""" from typing import Optional, Tuple import jax import jax.numpy as jnp from flax import linen as nn from flax.core.frozen_dict import FrozenDict from transformers import CLIPConfig, FlaxPreTrainedModel from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule def A_ ( _lowerCAmelCase : str, _lowerCAmelCase : List[Any], _lowerCAmelCase : Dict=1e-1_2 ): """simple docstring""" _a = jnp.divide(emb_a.T, jnp.clip(jnp.linalg.norm(__lowerCAmelCase, axis=1 ), a_min=__lowerCAmelCase ) ).T _a = jnp.divide(emb_a.T, jnp.clip(jnp.linalg.norm(__lowerCAmelCase, axis=1 ), a_min=__lowerCAmelCase ) ).T return jnp.matmul(__lowerCAmelCase, norm_emb_a.T ) class __lowerCamelCase ( nn.Module ): '''simple docstring''' A_ : CLIPConfig A_ : jnp.dtype = jnp.floataa def _UpperCAmelCase ( self ) -> List[str]: _a = FlaxCLIPVisionModule(self.config.vision_config ) _a = nn.Dense(self.config.projection_dim , use_bias=SCREAMING_SNAKE_CASE__ , dtype=self.dtype ) _a = self.param('''concept_embeds''' , jax.nn.initializers.ones , (17, self.config.projection_dim) ) _a = self.param( '''special_care_embeds''' , jax.nn.initializers.ones , (3, self.config.projection_dim) ) _a = self.param('''concept_embeds_weights''' , jax.nn.initializers.ones , (17,) ) _a = self.param('''special_care_embeds_weights''' , jax.nn.initializers.ones , (3,) ) def __call__( self , __UpperCAmelCase ) -> Tuple: _a = self.vision_model(SCREAMING_SNAKE_CASE__ )[1] _a = self.visual_projection(SCREAMING_SNAKE_CASE__ ) _a = jax_cosine_distance(SCREAMING_SNAKE_CASE__ , self.special_care_embeds ) _a = jax_cosine_distance(SCREAMING_SNAKE_CASE__ , self.concept_embeds ) # increase this value to create a stronger `nfsw` filter # at the cost of increasing the possibility of filtering benign image inputs _a = 0.0 _a = special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment _a = jnp.round(SCREAMING_SNAKE_CASE__ , 3 ) _a = jnp.any(special_scores > 0 , axis=1 , keepdims=SCREAMING_SNAKE_CASE__ ) # Use a lower threshold if an image has any special care concept _a = is_special_care * 0.01 _a = cos_dist - self.concept_embeds_weights[None, :] + special_adjustment _a = jnp.round(SCREAMING_SNAKE_CASE__ , 3 ) _a = jnp.any(concept_scores > 0 , axis=1 ) return has_nsfw_concepts class __lowerCamelCase ( __lowercase ): '''simple docstring''' A_ : List[str] = CLIPConfig A_ : List[Any] = """clip_input""" A_ : Union[str, Any] = FlaxStableDiffusionSafetyCheckerModule def __init__( self , __UpperCAmelCase , __UpperCAmelCase = None , __UpperCAmelCase = 0 , __UpperCAmelCase = jnp.floataa , __UpperCAmelCase = True , **__UpperCAmelCase , ) -> Optional[Any]: if input_shape is None: _a = (1, 224, 224, 3) _a = self.module_class(config=SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) super().__init__(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , input_shape=SCREAMING_SNAKE_CASE__ , seed=SCREAMING_SNAKE_CASE__ , dtype=SCREAMING_SNAKE_CASE__ , _do_init=_do_init ) def _UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = None ) -> FrozenDict: # init input tensor _a = jax.random.normal(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) _a , _a = jax.random.split(SCREAMING_SNAKE_CASE__ ) _a = {'''params''': params_rng, '''dropout''': dropout_rng} _a = self.module.init(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )['''params'''] return random_params def __call__( self , __UpperCAmelCase , __UpperCAmelCase = None , ) -> Optional[int]: _a = jnp.transpose(SCREAMING_SNAKE_CASE__ , (0, 2, 3, 1) ) return self.module.apply( {'''params''': params or self.params} , jnp.array(SCREAMING_SNAKE_CASE__ , dtype=jnp.floataa ) , rngs={} , )
320
from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class lowerCAmelCase__ ( __lowercase ): def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : NestedDataStructureLike[PathLike] , SCREAMING_SNAKE_CASE__ : Optional[NamedSplit] = None , SCREAMING_SNAKE_CASE__ : Optional[Features] = None , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[int] = None , **SCREAMING_SNAKE_CASE__ : str , ) -> Union[str, Any]: super().__init__( SCREAMING_SNAKE_CASE__ , split=SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ , keep_in_memory=SCREAMING_SNAKE_CASE__ , streaming=SCREAMING_SNAKE_CASE__ , num_proc=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = path_or_paths if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else {self.split: path_or_paths} __lowerCamelCase = Text( cache_dir=SCREAMING_SNAKE_CASE__ , data_files=SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def __A ( self : int ) -> Dict: # Build iterable dataset if self.streaming: __lowerCamelCase = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None self.builder.download_and_prepare( download_config=SCREAMING_SNAKE_CASE__ , download_mode=SCREAMING_SNAKE_CASE__ , verification_mode=SCREAMING_SNAKE_CASE__ , base_path=SCREAMING_SNAKE_CASE__ , num_proc=self.num_proc , ) __lowerCamelCase = self.builder.as_dataset( split=self.split , verification_mode=SCREAMING_SNAKE_CASE__ , in_memory=self.keep_in_memory ) return dataset
270
0
from math import sqrt def UpperCamelCase ( __magic_name__ : int ) -> int: """simple docstring""" lowercase__ = 0 for i in range(1 , int(sqrt(__lowerCAmelCase ) + 1 ) ): if n % i == 0 and i != sqrt(__lowerCAmelCase ): total += i + n // i elif i == sqrt(__lowerCAmelCase ): total += i return total - n def UpperCamelCase ( __magic_name__ : int = 1_0000 ) -> int: """simple docstring""" lowercase__ = sum( i for i in range(1 , __lowerCAmelCase ) if sum_of_divisors(sum_of_divisors(__lowerCAmelCase ) ) == i and sum_of_divisors(__lowerCAmelCase ) != i ) return total if __name__ == "__main__": print(solution(int(str(input()).strip())))
305
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(">=", "4.25.0")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
270
0
'''simple docstring''' import numpy as np from cva import destroyAllWindows, imread, imshow, waitKey class lowerCAmelCase_ : '''simple docstring''' def __init__( self : Any , _UpperCAmelCase : List[str] , _UpperCAmelCase : int , _UpperCAmelCase : int ): """simple docstring""" if dst_width < 0 or dst_height < 0: raise ValueError("""Destination width/height should be > 0""" ) UpperCAmelCase__ = img UpperCAmelCase__ = img.shape[1] UpperCAmelCase__ = img.shape[0] UpperCAmelCase__ = dst_width UpperCAmelCase__ = dst_height UpperCAmelCase__ = self.src_w / self.dst_w UpperCAmelCase__ = self.src_h / self.dst_h UpperCAmelCase__ = UpperCAmelCase__ = ( np.ones((self.dst_h, self.dst_w, 3) , np.uinta ) * 2_55 ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): """simple docstring""" for i in range(self.dst_h ): for j in range(self.dst_w ): UpperCAmelCase__ = self.img[self.get_y(SCREAMING_SNAKE_CASE__ )][self.get_x(SCREAMING_SNAKE_CASE__ )] def SCREAMING_SNAKE_CASE__ ( self : str , _UpperCAmelCase : int ): """simple docstring""" return int(self.ratio_x * x ) def SCREAMING_SNAKE_CASE__ ( self : str , _UpperCAmelCase : int ): """simple docstring""" return int(self.ratio_y * y ) if __name__ == "__main__": UpperCAmelCase_ = 8_0_0, 6_0_0 UpperCAmelCase_ = imread('image_data/lena.jpg', 1) UpperCAmelCase_ = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( f"Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}", n.output ) waitKey(0) destroyAllWindows()
346
import sacrebleu as scb from packaging import version from sacrebleu import CHRF import datasets SCREAMING_SNAKE_CASE__ : Union[str, Any] = "\\n@inproceedings{popovic-2015-chrf,\n title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",\n month = sep,\n year = \"2015\",\n address = \"Lisbon, Portugal\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W15-3049\",\n doi = \"10.18653/v1/W15-3049\",\n pages = \"392--395\",\n}\n@inproceedings{popovic-2017-chrf,\n title = \"chr{F}++: words helping character n-grams\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Second Conference on Machine Translation\",\n month = sep,\n year = \"2017\",\n address = \"Copenhagen, Denmark\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W17-4770\",\n doi = \"10.18653/v1/W17-4770\",\n pages = \"612--618\",\n}\n@inproceedings{post-2018-call,\n title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n author = \"Post, Matt\",\n booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n month = oct,\n year = \"2018\",\n address = \"Belgium, Brussels\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W18-6319\",\n pages = \"186--191\",\n}\n" SCREAMING_SNAKE_CASE__ : int = "\\nChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,\nand ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation\nthat is already present in sacrebleu.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.\n" SCREAMING_SNAKE_CASE__ : Optional[Any] = "\nProduces ChrF(++) scores for hypotheses given reference translations.\n\nArgs:\n predictions (list of str): The predicted sentences.\n references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.\n char_order (int): Character n-gram order. Defaults to `6`.\n word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.\n beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.\n lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.\n whitespace (bool): If `True`, include whitespaces when extracting character n-grams.\n eps_smoothing (bool): If `True`, applies epsilon smoothing similar\n to reference chrF++.py, NLTK and Moses implementations. If `False`,\n it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.\n\nReturns:\n 'score' (float): The chrF (chrF++) score,\n 'char_order' (int): The character n-gram order,\n 'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,\n 'beta' (int): Determine the importance of recall w.r.t precision\n\nExamples:\n Example 1--a simple example of calculating chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction, references=reference)\n >>> print(results)\n {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}\n\n Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2)\n >>> print(results)\n {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}\n\n Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2,\n ... lowercase=True)\n >>> print(results)\n {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): def __A ( self : Dict ) -> Tuple: if version.parse(scb.__version__ ) < version.parse('''1.4.12''' ): raise ImportWarning( '''To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n''' '''You can install it with `pip install "sacrebleu>=1.4.12"`.''' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/mjpost/sacreBLEU#chrf--chrf''' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Sequence(datasets.Value('''string''' , id='''sequence''' ) , id='''references''' ), } ) , codebase_urls=['''https://github.com/mjpost/sacreBLEU#chrf--chrf'''] , reference_urls=[ '''https://github.com/m-popovic/chrF''', ] , ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int = CHRF.CHAR_ORDER , SCREAMING_SNAKE_CASE__ : int = CHRF.WORD_ORDER , SCREAMING_SNAKE_CASE__ : int = CHRF.BETA , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , ) -> Optional[Any]: __lowerCamelCase = len(references[0] ) if any(len(SCREAMING_SNAKE_CASE__ ) != references_per_prediction for refs in references ): raise ValueError('''Sacrebleu requires the same number of references for each prediction''' ) __lowerCamelCase = [[refs[i] for refs in references] for i in range(SCREAMING_SNAKE_CASE__ )] __lowerCamelCase = CHRF(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = sb_chrf.corpus_score(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return { "score": output.score, "char_order": output.char_order, "word_order": output.word_order, "beta": output.beta, }
270
0
def lowercase_ ( _A : int = 600851475143 ): """simple docstring""" try: lowerCamelCase__ : Tuple = int(__lowerCAmelCase ) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int." ) if n <= 0: raise ValueError("Parameter n must be greater than or equal to one." ) lowerCamelCase__ : Tuple = 2 lowerCamelCase__ : List[str] = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 lowerCamelCase__ : int = i while n % i == 0: lowerCamelCase__ : Union[str, Any] = n // i i += 1 return int(__lowerCAmelCase ) if __name__ == "__main__": print(f'{solution() = }')
184
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : List[Any] = { "configuration_resnet": ["RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "ResNetConfig", "ResNetOnnxConfig"] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "ResNetForImageClassification", "ResNetModel", "ResNetPreTrainedModel", "ResNetBackbone", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = [ "TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFResNetForImageClassification", "TFResNetModel", "TFResNetPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ "FlaxResNetForImageClassification", "FlaxResNetModel", "FlaxResNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_resnet import RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ResNetConfig, ResNetOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_resnet import ( RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, ResNetBackbone, ResNetForImageClassification, ResNetModel, ResNetPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_resnet import ( TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFResNetForImageClassification, TFResNetModel, TFResNetPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel, FlaxResNetPreTrainedModel else: import sys SCREAMING_SNAKE_CASE__ : Any = _LazyModule(__name__, globals()["__file__"], _import_structure)
270
0
"""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_ ( snake_case_ : dict , snake_case_ : List[str] , snake_case_ : int ) ->list[str]: lowerCamelCase__ : List[Any] =set() # keep track of all the paths to be checked lowerCamelCase__ : 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 lowerCamelCase__ : List[Any] =queue.pop(0 ) # get the last node from the path lowerCamelCase__ : Union[str, Any] =path[-1] if node not in explored: lowerCamelCase__ : Dict =graph[node] # go through all neighbour nodes, construct a new path and # push it into the queue for neighbour in neighbours: lowerCamelCase__ : List[str] =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_ ( snake_case_ : dict , snake_case_ : List[str] , snake_case_ : Optional[int] ) ->int: if not graph or start not in graph or target not in graph: return -1 if start == target: return 0 lowerCamelCase__ : List[str] =[start] lowerCamelCase__ : List[Any] =set(__lowerCAmelCase ) # Keep tab on distances from `start` node. lowerCamelCase__ : Optional[int] ={start: 0, target: -1} while queue: lowerCamelCase__ : List[str] =queue.pop(0 ) if node == target: lowerCamelCase__ : str =( 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 ) lowerCamelCase__ : Dict =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
126
import unittest import numpy as np import requests from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: SCREAMING_SNAKE_CASE__ : str = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any]=7 , SCREAMING_SNAKE_CASE__ : List[str]=3 , SCREAMING_SNAKE_CASE__ : Tuple=18 , SCREAMING_SNAKE_CASE__ : int=30 , SCREAMING_SNAKE_CASE__ : Any=4_00 , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , ) -> Union[str, Any]: __lowerCamelCase = size if size is not None else {'''height''': 20, '''width''': 20} __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = num_channels __lowerCamelCase = image_size __lowerCamelCase = min_resolution __lowerCamelCase = max_resolution __lowerCamelCase = size __lowerCamelCase = do_normalize __lowerCamelCase = do_convert_rgb __lowerCamelCase = [5_12, 10_24, 20_48, 40_96] __lowerCamelCase = patch_size if patch_size is not None else {'''height''': 16, '''width''': 16} def __A ( self : Union[str, Any] ) -> Union[str, Any]: return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def __A ( self : int ) -> Any: __lowerCamelCase = '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg''' __lowerCamelCase = Image.open(requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ ).raw ).convert('''RGB''' ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`.""" , ) @require_torch @require_vision class lowerCAmelCase__ ( __lowercase , unittest.TestCase ): a__ : Dict = PixaStructImageProcessor if is_vision_available() else None def __A ( self : Optional[Any] ) -> List[Any]: __lowerCamelCase = PixaStructImageProcessingTester(self ) @property def __A ( self : Optional[int] ) -> Optional[int]: return self.image_processor_tester.prepare_image_processor_dict() def __A ( self : Tuple ) -> Dict: __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_normalize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_convert_rgb''' ) ) def __A ( self : int ) -> str: __lowerCamelCase = self.image_processor_tester.prepare_dummy_image() __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) __lowerCamelCase = 20_48 __lowerCamelCase = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) ) def __A ( self : Union[str, Any] ) -> Dict: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : Dict ) -> str: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 __lowerCamelCase = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches __lowerCamelCase = '''Hello''' __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ , header_text=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ , header_text=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : List[str] ) -> Any: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : Tuple ) -> List[str]: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`.""" , ) @require_torch @require_vision class lowerCAmelCase__ ( __lowercase , unittest.TestCase ): a__ : Any = PixaStructImageProcessor if is_vision_available() else None def __A ( self : Union[str, Any] ) -> Optional[Any]: __lowerCamelCase = PixaStructImageProcessingTester(self , num_channels=4 ) __lowerCamelCase = 3 @property def __A ( self : List[Any] ) -> Optional[Any]: return self.image_processor_tester.prepare_image_processor_dict() def __A ( self : Union[str, Any] ) -> List[str]: __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_normalize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_convert_rgb''' ) ) def __A ( self : Optional[int] ) -> str: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
270
0
"""simple docstring""" from __future__ import annotations from cmath import sqrt def snake_case__ ( __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int ): """simple docstring""" if a == 0: raise ValueError('''Coefficient \'a\' must not be zero.''' ) lowerCamelCase__ : List[str] =b * b - 4 * a * c lowerCamelCase__ : str =(-b + sqrt(__lowerCAmelCase )) / (2 * a) lowerCamelCase__ : Tuple =(-b - sqrt(__lowerCAmelCase )) / (2 * a) return ( root_a.real if not root_a.imag else root_a, root_a.real if not root_a.imag else root_a, ) def snake_case__ ( ): """simple docstring""" lowerCamelCase__ , lowerCamelCase__ : Optional[int] =quadratic_roots(a=5 , b=6 , c=1 ) print(f'''The solutions are: {solutiona} and {solutiona}''' ) if __name__ == "__main__": main()
238
import shutil import tempfile import unittest from unittest.mock import patch from transformers import ( DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, Trainer, TrainerCallback, TrainingArguments, is_torch_available, ) from transformers.testing_utils import require_torch if is_torch_available(): from transformers.trainer import DEFAULT_CALLBACKS from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel class lowerCAmelCase__ ( __lowercase ): def __init__( self : int ) -> Optional[int]: __lowerCamelCase = [] def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> Tuple: self.events.append('''on_init_end''' ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Any: self.events.append('''on_train_begin''' ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : int ) -> Any: self.events.append('''on_train_end''' ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: self.events.append('''on_epoch_begin''' ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Tuple ) -> Optional[Any]: self.events.append('''on_epoch_end''' ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: self.events.append('''on_step_begin''' ) def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: self.events.append('''on_step_end''' ) def __A ( self : int , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> Union[str, Any]: self.events.append('''on_evaluate''' ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : str ) -> str: self.events.append('''on_predict''' ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Tuple: self.events.append('''on_save''' ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : List[str] ) -> List[str]: self.events.append('''on_log''' ) def __A ( self : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: self.events.append('''on_prediction_step''' ) @require_torch class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Union[str, Any] ) -> Optional[Any]: __lowerCamelCase = tempfile.mkdtemp() def __A ( self : int ) -> List[str]: shutil.rmtree(self.output_dir ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any]=0 , SCREAMING_SNAKE_CASE__ : Any=0 , SCREAMING_SNAKE_CASE__ : List[str]=64 , SCREAMING_SNAKE_CASE__ : Optional[int]=64 , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Optional[int]=False , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Union[str, Any]: # disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure # its set to False since the tests later on depend on its value. __lowerCamelCase = RegressionDataset(length=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionDataset(length=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionModelConfig(a=SCREAMING_SNAKE_CASE__ , b=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionPreTrainedModel(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = TrainingArguments(self.output_dir , disable_tqdm=SCREAMING_SNAKE_CASE__ , report_to=[] , **SCREAMING_SNAKE_CASE__ ) return Trainer( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , train_dataset=SCREAMING_SNAKE_CASE__ , eval_dataset=SCREAMING_SNAKE_CASE__ , callbacks=SCREAMING_SNAKE_CASE__ , ) def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> Optional[int]: self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) ) # Order doesn't matter __lowerCamelCase = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : cb.__name__ if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cb.__class__.__name__ ) __lowerCamelCase = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : cb.__name__ if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cb.__class__.__name__ ) for cba, cba in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(SCREAMING_SNAKE_CASE__ , cba.__class__ ) elif not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(cba.__class__ , SCREAMING_SNAKE_CASE__ ) else: self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: __lowerCamelCase = ['''on_init_end''', '''on_train_begin'''] __lowerCamelCase = 0 __lowerCamelCase = len(trainer.get_eval_dataloader() ) __lowerCamelCase = ['''on_prediction_step'''] * len(trainer.get_eval_dataloader() ) + ['''on_log''', '''on_evaluate'''] for _ in range(trainer.state.num_train_epochs ): expected_events.append('''on_epoch_begin''' ) for _ in range(SCREAMING_SNAKE_CASE__ ): step += 1 expected_events += ["on_step_begin", "on_step_end"] if step % trainer.args.logging_steps == 0: expected_events.append('''on_log''' ) if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0: expected_events += evaluation_events.copy() if step % trainer.args.save_steps == 0: expected_events.append('''on_save''' ) expected_events.append('''on_epoch_end''' ) if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH: expected_events += evaluation_events.copy() expected_events += ["on_log", "on_train_end"] return expected_events def __A ( self : Union[str, Any] ) -> int: __lowerCamelCase = self.get_trainer() __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [ProgressCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # Callbacks passed at init are added to the default callbacks __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] ) expected_callbacks.append(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback __lowerCamelCase = self.get_trainer(disable_tqdm=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [PrinterCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) def __A ( self : List[Any] ) -> str: __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [ProgressCallback] __lowerCamelCase = self.get_trainer() # We can add, pop, or remove by class name trainer.remove_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.remove(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.pop_callback(SCREAMING_SNAKE_CASE__ ) self.assertEqual(cb.__class__ , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) trainer.add_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.insert(0 , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # We can also add, pop, or remove by instance __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.callback_handler.callbacks[0] trainer.remove_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.remove(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.callback_handler.callbacks[0] __lowerCamelCase = trainer.pop_callback(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) trainer.add_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.insert(0 , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] ) -> Any: import warnings # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested warnings.simplefilter(action='''ignore''' , category=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # Independent log/save/eval __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , logging_steps=5 ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , save_steps=5 ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , eval_steps=5 , evaluation_strategy='''steps''' ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , evaluation_strategy='''epoch''' ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # A bit of everything __lowerCamelCase = self.get_trainer( callbacks=[MyTestTrainerCallback] , logging_steps=3 , save_steps=10 , eval_steps=5 , evaluation_strategy='''steps''' , ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # warning should be emitted for duplicated callbacks with patch('''transformers.trainer_callback.logger.warning''' ) as warn_mock: __lowerCamelCase = self.get_trainer( callbacks=[MyTestTrainerCallback, MyTestTrainerCallback] , ) assert str(SCREAMING_SNAKE_CASE__ ) in warn_mock.call_args[0][0]
270
0
from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class UpperCAmelCase ( __lowercase ): '''simple docstring''' def __init__( self : Tuple , __lowercase : NestedDataStructureLike[PathLike] , __lowercase : Optional[NamedSplit] = None , __lowercase : Optional[Features] = None , __lowercase : str = None , __lowercase : bool = False , __lowercase : bool = False , __lowercase : Optional[int] = None , **__lowercase : str , ): """simple docstring""" super().__init__( SCREAMING_SNAKE_CASE__ , split=SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ , keep_in_memory=SCREAMING_SNAKE_CASE__ , streaming=SCREAMING_SNAKE_CASE__ , num_proc=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) snake_case_ = path_or_paths if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else {self.split: path_or_paths} snake_case_ = Text( cache_dir=SCREAMING_SNAKE_CASE__ , data_files=SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def snake_case__ ( self : int ): """simple docstring""" if self.streaming: snake_case_ = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: snake_case_ = None snake_case_ = None snake_case_ = None snake_case_ = None self.builder.download_and_prepare( download_config=SCREAMING_SNAKE_CASE__ , download_mode=SCREAMING_SNAKE_CASE__ , verification_mode=SCREAMING_SNAKE_CASE__ , base_path=SCREAMING_SNAKE_CASE__ , num_proc=self.num_proc , ) snake_case_ = self.builder.as_dataset( split=self.split , verification_mode=SCREAMING_SNAKE_CASE__ , in_memory=self.keep_in_memory ) return dataset
187
import numpy as np from cva import destroyAllWindows, imread, imshow, waitKey class lowerCAmelCase__ : def __init__( self : Any , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> Dict: if dst_width < 0 or dst_height < 0: raise ValueError('''Destination width/height should be > 0''' ) __lowerCamelCase = img __lowerCamelCase = img.shape[1] __lowerCamelCase = img.shape[0] __lowerCamelCase = dst_width __lowerCamelCase = dst_height __lowerCamelCase = self.src_w / self.dst_w __lowerCamelCase = self.src_h / self.dst_h __lowerCamelCase = __lowerCamelCase = ( np.ones((self.dst_h, self.dst_w, 3) , np.uinta ) * 2_55 ) def __A ( self : List[Any] ) -> str: for i in range(self.dst_h ): for j in range(self.dst_w ): __lowerCamelCase = self.img[self.get_y(SCREAMING_SNAKE_CASE__ )][self.get_x(SCREAMING_SNAKE_CASE__ )] def __A ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> int: return int(self.ratio_x * x ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> int: return int(self.ratio_y * y ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = 800, 600 SCREAMING_SNAKE_CASE__ : int = imread("image_data/lena.jpg", 1) SCREAMING_SNAKE_CASE__ : Union[str, Any] = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( F'Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}', n.output ) waitKey(0) destroyAllWindows()
270
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 __UpperCAmelCase (__lowercase ,unittest.TestCase ): __snake_case : str = DiTPipeline __snake_case : List[Any] = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS __snake_case : str = PipelineTesterMixin.required_optional_params - { """latents""", """num_images_per_prompt""", """callback""", """callback_steps""", } __snake_case : List[str] = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS __snake_case : int = False def UpperCamelCase ( self: Any ): '''simple docstring''' torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = 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=SCREAMING_SNAKE_CASE__ , activation_fn="""gelu-approximate""" , num_embeds_ada_norm=1_000 , norm_type="""ada_norm_zero""" , norm_elementwise_affine=SCREAMING_SNAKE_CASE__ , ) _SCREAMING_SNAKE_CASE = AutoencoderKL() _SCREAMING_SNAKE_CASE = DDIMScheduler() _SCREAMING_SNAKE_CASE = {"""transformer""": transformer.eval(), """vae""": vae.eval(), """scheduler""": scheduler} return components def UpperCamelCase ( self: Any , UpperCAmelCase_: str , UpperCAmelCase_: Any=0 ): '''simple docstring''' if str(SCREAMING_SNAKE_CASE__ ).startswith("""mps""" ): _SCREAMING_SNAKE_CASE = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: _SCREAMING_SNAKE_CASE = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) _SCREAMING_SNAKE_CASE = { """class_labels""": [1], """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs def UpperCamelCase ( self: Tuple ): '''simple docstring''' _SCREAMING_SNAKE_CASE = """cpu""" _SCREAMING_SNAKE_CASE = self.get_dummy_components() _SCREAMING_SNAKE_CASE = self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) _SCREAMING_SNAKE_CASE = self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) _SCREAMING_SNAKE_CASE = pipe(**SCREAMING_SNAKE_CASE__ ).images _SCREAMING_SNAKE_CASE = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 16, 16, 3) ) _SCREAMING_SNAKE_CASE = np.array([0.29_46, 0.66_01, 0.43_29, 0.32_96, 0.41_44, 0.53_19, 0.72_73, 0.50_13, 0.44_57] ) _SCREAMING_SNAKE_CASE = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(SCREAMING_SNAKE_CASE__ , 1E-3 ) def UpperCamelCase ( self: Tuple ): '''simple docstring''' self._test_inference_batch_single_identical(relax_max_difference=SCREAMING_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 UpperCamelCase ( self: Any ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @require_torch_gpu @slow class __UpperCAmelCase (unittest.TestCase ): def UpperCamelCase ( self: Union[str, Any] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase ( self: Dict ): '''simple docstring''' _SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = DiTPipeline.from_pretrained("""facebook/DiT-XL-2-256""" ) pipe.to("""cuda""" ) _SCREAMING_SNAKE_CASE = ["""vase""", """umbrella""", """white shark""", """white wolf"""] _SCREAMING_SNAKE_CASE = pipe.get_label_ids(SCREAMING_SNAKE_CASE__ ) _SCREAMING_SNAKE_CASE = pipe(SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=40 , output_type="""np""" ).images for word, image in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): _SCREAMING_SNAKE_CASE = 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 UpperCamelCase ( self: Dict ): '''simple docstring''' _SCREAMING_SNAKE_CASE = DiTPipeline.from_pretrained("""facebook/DiT-XL-2-512""" ) _SCREAMING_SNAKE_CASE = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.to("""cuda""" ) _SCREAMING_SNAKE_CASE = ["""vase""", """umbrella"""] _SCREAMING_SNAKE_CASE = pipe.get_label_ids(SCREAMING_SNAKE_CASE__ ) _SCREAMING_SNAKE_CASE = torch.manual_seed(0 ) _SCREAMING_SNAKE_CASE = pipe(SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=25 , output_type="""np""" ).images for word, image in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): _SCREAMING_SNAKE_CASE = 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
306
from queue import PriorityQueue from typing import Any import numpy as np def __magic_name__ ( __lowerCAmelCase : dict , __lowerCAmelCase : str , __lowerCAmelCase : set , __lowerCAmelCase : set , __lowerCAmelCase : dict , __lowerCAmelCase : dict , __lowerCAmelCase : PriorityQueue , __lowerCAmelCase : dict , __lowerCAmelCase : float | int , ) -> float | int: for nxt, d in graph[v]: if nxt in visited_forward: continue __lowerCamelCase = cst_fwd.get(__lowerCAmelCase , np.inf ) __lowerCamelCase = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) __lowerCamelCase = new_cost_f __lowerCamelCase = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: __lowerCamelCase = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def __magic_name__ ( __lowerCAmelCase : str , __lowerCAmelCase : str , __lowerCAmelCase : dict , __lowerCAmelCase : dict ) -> int: __lowerCamelCase = -1 __lowerCamelCase = set() __lowerCamelCase = set() __lowerCamelCase = {source: 0} __lowerCamelCase = {destination: 0} __lowerCamelCase = {source: None} __lowerCamelCase = {destination: None} __lowerCamelCase = PriorityQueue() __lowerCamelCase = PriorityQueue() __lowerCamelCase = np.inf queue_forward.put((0, source) ) queue_backward.put((0, destination) ) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): __lowerCamelCase , __lowerCamelCase = queue_forward.get() visited_forward.add(__lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = queue_backward.get() visited_backward.add(__lowerCAmelCase ) __lowerCamelCase = pass_and_relaxation( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) __lowerCamelCase = pass_and_relaxation( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: __lowerCamelCase = shortest_distance return shortest_path_distance SCREAMING_SNAKE_CASE__ : List[Any] = { "B": [["C", 1]], "C": [["D", 1]], "D": [["F", 1]], "E": [["B", 1], ["G", 2]], "F": [], "G": [["F", 1]], } SCREAMING_SNAKE_CASE__ : Optional[int] = { "B": [["E", 1]], "C": [["B", 1]], "D": [["C", 1]], "F": [["D", 1], ["G", 1]], "E": [[None, np.inf]], "G": [["E", 2]], } if __name__ == "__main__": import doctest doctest.testmod()
270
0
'''simple docstring''' import math def UpperCAmelCase_ ( ): lowercase_ :Union[str, Any] = input("Enter message: " ) lowercase_ :Tuple = int(input(F'Enter key [2-{len(__lowerCAmelCase ) - 1}]: ' ) ) lowercase_ :str = input("Encryption/Decryption [e/d]: " ) if mode.lower().startswith("e" ): lowercase_ :Union[str, Any] = encrypt_message(__lowerCAmelCase ,__lowerCAmelCase ) elif mode.lower().startswith("d" ): lowercase_ :Tuple = decrypt_message(__lowerCAmelCase ,__lowerCAmelCase ) # Append pipe symbol (vertical bar) to identify spaces at the end. print(F'Output:\n{text + "|"}' ) def UpperCAmelCase_ ( __lowerCamelCase : int ,__lowerCamelCase : str ): lowercase_ :Optional[int] = [""] * key for col in range(__lowerCAmelCase ): lowercase_ :List[str] = col while pointer < len(__lowerCAmelCase ): cipher_text[col] += message[pointer] pointer += key return "".join(__lowerCAmelCase ) def UpperCAmelCase_ ( __lowerCamelCase : int ,__lowerCamelCase : str ): lowercase_ :Dict = math.ceil(len(__lowerCAmelCase ) / key ) lowercase_ :List[Any] = key lowercase_ :Any = (num_cols * num_rows) - len(__lowerCAmelCase ) lowercase_ :Tuple = [""] * num_cols lowercase_ :Union[str, Any] = 0 lowercase_ :List[str] = 0 for symbol in message: plain_text[col] += symbol col += 1 if ( (col == num_cols) or (col == num_cols - 1) and (row >= num_rows - num_shaded_boxes) ): lowercase_ :Optional[Any] = 0 row += 1 return "".join(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod() main()
223
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ : List[Any] = TypeVar("T") def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (position - 1) // 2 def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (2 * position) + 1 def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (2 * position) + 2 class lowerCAmelCase__ ( Generic[T] ): def __init__( self : List[str] ) -> None: __lowerCamelCase = [] __lowerCamelCase = {} __lowerCamelCase = 0 def __len__( self : Optional[int] ) -> int: return self.elements def __repr__( self : Optional[int] ) -> str: return str(self.heap ) def __A ( self : Union[str, Any] ) -> bool: # Check if the priority queue is empty return self.elements == 0 def __A ( self : str , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Add an element with given priority to the queue self.heap.append((elem, weight) ) __lowerCamelCase = self.elements self.elements += 1 self._bubble_up(SCREAMING_SNAKE_CASE__ ) def __A ( self : Any ) -> T: # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) __lowerCamelCase , __lowerCamelCase = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __lowerCamelCase , __lowerCamelCase = self.heap[0] self._bubble_down(SCREAMING_SNAKE_CASE__ ) return elem def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Update the weight of the given key __lowerCamelCase = self.position_map[elem] __lowerCamelCase = (elem, weight) if position > 0: __lowerCamelCase = get_parent_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase = self.heap[parent_position] if parent_weight > weight: self._bubble_up(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Place a node at the proper position (upward movement) [to be used internally # only] __lowerCamelCase = self.position_map[elem] if curr_pos == 0: return None __lowerCamelCase = get_parent_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase = self.heap[curr_pos] __lowerCamelCase , __lowerCamelCase = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_up(SCREAMING_SNAKE_CASE__ ) return None def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Place a node at the proper position (downward movement) [to be used # internally only] __lowerCamelCase = self.position_map[elem] __lowerCamelCase , __lowerCamelCase = self.heap[curr_pos] __lowerCamelCase = get_child_left_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = get_child_right_position(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements and child_right_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_left_position] __lowerCamelCase , __lowerCamelCase = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: return None if child_right_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) return None def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: # Swap the nodes at the given positions __lowerCamelCase = self.heap[nodea_pos][0] __lowerCamelCase = self.heap[nodea_pos][0] __lowerCamelCase , __lowerCamelCase = ( self.heap[nodea_pos], self.heap[nodea_pos], ) __lowerCamelCase = nodea_pos __lowerCamelCase = nodea_pos class lowerCAmelCase__ ( Generic[T] ): def __init__( self : Tuple ) -> None: __lowerCamelCase = {} __lowerCamelCase = 0 def __repr__( self : Optional[int] ) -> str: return str(self.connections ) def __len__( self : List[str] ) -> int: return self.nodes def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Add a node in the graph if it is not in the graph if node not in self.connections: __lowerCamelCase = {} self.nodes += 1 def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Add an edge between 2 nodes in the graph self.add_node(SCREAMING_SNAKE_CASE__ ) self.add_node(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = weight __lowerCamelCase = weight def __magic_name__ ( __lowerCAmelCase : GraphUndirectedWeighted[T] , ) -> tuple[dict[T, int], dict[T, T | None]]: __lowerCamelCase = {node: maxsize for node in graph.connections} __lowerCamelCase = {node: None for node in graph.connections} __lowerCamelCase = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(__lowerCAmelCase , __lowerCAmelCase ) if priority_queue.is_empty(): return dist, parent # initialization __lowerCamelCase = priority_queue.extract_min() __lowerCamelCase = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __lowerCamelCase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(__lowerCAmelCase , dist[neighbour] ) __lowerCamelCase = node # running prim's algorithm while not priority_queue.is_empty(): __lowerCamelCase = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __lowerCamelCase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(__lowerCAmelCase , dist[neighbour] ) __lowerCamelCase = node return dist, parent
270
0
'''simple docstring''' import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import XLMRobertaTokenizerFast from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class UpperCAmelCase ( __lowercase , unittest.TestCase ): __lowercase = KandinskyImgaImgPipeline __lowercase = ["""prompt""", """image_embeds""", """negative_image_embeds""", """image"""] __lowercase = [ """prompt""", """negative_prompt""", """image_embeds""", """negative_image_embeds""", """image""", ] __lowercase = [ """generator""", """height""", """width""", """strength""", """guidance_scale""", """negative_prompt""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] __lowercase = False @property def UpperCAmelCase_ ( self :List[Any] )-> int: return 32 @property def UpperCAmelCase_ ( self :Tuple )-> Optional[int]: return 32 @property def UpperCAmelCase_ ( self :List[Any] )-> List[Any]: return self.time_input_dim @property def UpperCAmelCase_ ( self :List[str] )-> List[Any]: return self.time_input_dim * 4 @property def UpperCAmelCase_ ( self :Union[str, Any] )-> str: return 1_00 @property def UpperCAmelCase_ ( self :int )-> List[str]: A__ = XLMRobertaTokenizerFast.from_pretrained("YiYiXu/tiny-random-mclip-base" ) return tokenizer @property def UpperCAmelCase_ ( self :List[Any] )-> List[str]: torch.manual_seed(0 ) A__ = MCLIPConfig( numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=10_05 , ) A__ = MultilingualCLIP(SCREAMING_SNAKE_CASE__ ) A__ = text_encoder.eval() return text_encoder @property def UpperCAmelCase_ ( self :Any )-> Union[str, Any]: torch.manual_seed(0 ) A__ = { "in_channels": 4, # Out channels is double in channels because predicts mean and variance "out_channels": 8, "addition_embed_type": "text_image", "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"), "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"), "mid_block_type": "UNetMidBlock2DSimpleCrossAttn", "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "layers_per_block": 1, "encoder_hid_dim": self.text_embedder_hidden_size, "encoder_hid_dim_type": "text_image_proj", "cross_attention_dim": self.cross_attention_dim, "attention_head_dim": 4, "resnet_time_scale_shift": "scale_shift", "class_embed_type": None, } A__ = UNetaDConditionModel(**SCREAMING_SNAKE_CASE__ ) return model @property def UpperCAmelCase_ ( self :Union[str, Any] )-> Tuple: return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def UpperCAmelCase_ ( self :Any )-> Optional[Any]: torch.manual_seed(0 ) A__ = VQModel(**self.dummy_movq_kwargs ) return model def UpperCAmelCase_ ( self :int )-> Dict: A__ = self.dummy_text_encoder A__ = self.dummy_tokenizer A__ = self.dummy_unet A__ = self.dummy_movq A__ = { "num_train_timesteps": 10_00, "beta_schedule": "linear", "beta_start": 0.0_0_0_8_5, "beta_end": 0.0_1_2, "clip_sample": False, "set_alpha_to_one": False, "steps_offset": 0, "prediction_type": "epsilon", "thresholding": False, } A__ = DDIMScheduler(**SCREAMING_SNAKE_CASE__ ) A__ = { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "movq": movq, } return components def UpperCAmelCase_ ( self :Tuple , lowercase_ :List[str] , lowercase_ :int=0 )-> Dict: A__ = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) A__ = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(SCREAMING_SNAKE_CASE__ ) # create init_image A__ = floats_tensor((1, 3, 64, 64) , rng=random.Random(SCREAMING_SNAKE_CASE__ ) ).to(SCREAMING_SNAKE_CASE__ ) A__ = image.cpu().permute(0 , 2 , 3 , 1 )[0] A__ = Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE__ ) ).convert("RGB" ).resize((2_56, 2_56) ) if str(SCREAMING_SNAKE_CASE__ ).startswith("mps" ): A__ = torch.manual_seed(SCREAMING_SNAKE_CASE__ ) else: A__ = torch.Generator(device=SCREAMING_SNAKE_CASE__ ).manual_seed(SCREAMING_SNAKE_CASE__ ) A__ = { "prompt": "horse", "image": init_image, "image_embeds": image_embeds, "negative_image_embeds": negative_image_embeds, "generator": generator, "height": 64, "width": 64, "num_inference_steps": 10, "guidance_scale": 7.0, "strength": 0.2, "output_type": "np", } return inputs def UpperCAmelCase_ ( self :Tuple )-> str: A__ = "cpu" A__ = self.get_dummy_components() A__ = self.pipeline_class(**SCREAMING_SNAKE_CASE__ ) A__ = pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A__ = pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) ) A__ = output.images A__ = pipe( **self.get_dummy_inputs(SCREAMING_SNAKE_CASE__ ) , return_dict=SCREAMING_SNAKE_CASE__ , )[0] A__ = image[0, -3:, -3:, -1] A__ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) A__ = np.array( [0.6_1_4_7_4_9_4_3, 0.6_0_7_3_5_3_9, 0.4_3_3_0_8_5_4_4, 0.5_9_2_8_2_6_9, 0.4_7_4_9_3_5_9_5, 0.4_6_7_5_5_9_7_3, 0.4_6_1_3_8_3_8, 0.4_5_3_6_8_7_9_7, 0.5_0_1_1_9_2_3_3] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), F" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), F" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" @slow @require_torch_gpu class UpperCAmelCase ( unittest.TestCase ): def UpperCAmelCase_ ( self :Optional[int] )-> Tuple: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase_ ( self :str )-> Union[str, Any]: A__ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/kandinsky_img2img_frog.npy" ) A__ = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/kandinsky/cat.png" ) A__ = "A red cartoon frog, 4k" A__ = KandinskyPriorPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1-prior" , torch_dtype=torch.floataa ) pipe_prior.to(SCREAMING_SNAKE_CASE__ ) A__ = KandinskyImgaImgPipeline.from_pretrained( "kandinsky-community/kandinsky-2-1" , torch_dtype=torch.floataa ) A__ = pipeline.to(SCREAMING_SNAKE_CASE__ ) pipeline.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) A__ = torch.Generator(device="cpu" ).manual_seed(0 ) A__, A__ = pipe_prior( SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=5 , negative_prompt="" , ).to_tuple() A__ = pipeline( SCREAMING_SNAKE_CASE__ , image=SCREAMING_SNAKE_CASE__ , image_embeds=SCREAMING_SNAKE_CASE__ , negative_image_embeds=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , num_inference_steps=1_00 , height=7_68 , width=7_68 , strength=0.2 , output_type="np" , ) A__ = output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
237
from __future__ import annotations from statistics import mean def __magic_name__ ( __lowerCAmelCase : list[int] , __lowerCAmelCase : list[int] , __lowerCAmelCase : int ) -> list[int]: __lowerCamelCase = [0] * no_of_processes __lowerCamelCase = [0] * no_of_processes # Initialize remaining_time to waiting_time. for i in range(__lowerCAmelCase ): __lowerCamelCase = burst_time[i] __lowerCamelCase = [] __lowerCamelCase = 0 __lowerCamelCase = 0 # When processes are not completed, # A process whose arrival time has passed \ # and has remaining execution time is put into the ready_process. # The shortest process in the ready_process, target_process is executed. while completed != no_of_processes: __lowerCamelCase = [] __lowerCamelCase = -1 for i in range(__lowerCAmelCase ): if (arrival_time[i] <= total_time) and (remaining_time[i] > 0): ready_process.append(__lowerCAmelCase ) if len(__lowerCAmelCase ) > 0: __lowerCamelCase = ready_process[0] for i in ready_process: if remaining_time[i] < remaining_time[target_process]: __lowerCamelCase = i total_time += burst_time[target_process] completed += 1 __lowerCamelCase = 0 __lowerCamelCase = ( total_time - arrival_time[target_process] - burst_time[target_process] ) else: total_time += 1 return waiting_time def __magic_name__ ( __lowerCAmelCase : list[int] , __lowerCAmelCase : int , __lowerCAmelCase : list[int] ) -> list[int]: __lowerCamelCase = [0] * no_of_processes for i in range(__lowerCAmelCase ): __lowerCamelCase = burst_time[i] + waiting_time[i] return turn_around_time if __name__ == "__main__": print("[TEST CASE 01]") SCREAMING_SNAKE_CASE__ : Tuple = 4 SCREAMING_SNAKE_CASE__ : Optional[int] = [2, 5, 3, 7] SCREAMING_SNAKE_CASE__ : List[str] = [0, 0, 0, 0] SCREAMING_SNAKE_CASE__ : str = calculate_waitingtime(arrival_time, burst_time, no_of_processes) SCREAMING_SNAKE_CASE__ : Union[str, Any] = calculate_turnaroundtime( burst_time, no_of_processes, waiting_time ) # Printing the Result print("PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time") for i, process_id in enumerate(list(range(1, 5))): print( F'{process_id}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t' F'{waiting_time[i]}\t\t\t\t{turn_around_time[i]}' ) print(F'\nAverage waiting time = {mean(waiting_time):.5f}') print(F'Average turnaround time = {mean(turn_around_time):.5f}')
270
0
def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: int = 1_0_0_0 ) -> int: '''simple docstring''' A__ , A__ = 1, 1 A__ = 2 while True: A__ = 0 A__ = fa + fa A__ , A__ = fa, f index += 1 for _ in str(__lowerCAmelCase ): i += 1 if i == n: break return index if __name__ == "__main__": print(solution(int(str(input()).strip())))
68
from abc import ABC, abstractmethod from argparse import ArgumentParser class lowerCAmelCase__ ( __lowercase ): @staticmethod @abstractmethod def __A ( SCREAMING_SNAKE_CASE__ : ArgumentParser ) -> str: raise NotImplementedError() @abstractmethod def __A ( self : Optional[int] ) -> Union[str, Any]: raise NotImplementedError()
270
0
"""simple docstring""" import warnings from diffusers import StableDiffusionInpaintPipeline as StableDiffusionInpaintPipeline # noqa F401 warnings.warn( '''The `inpainting.py` script is outdated. Please use directly `from diffusers import''' ''' StableDiffusionInpaintPipeline` instead.''' )
320
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv("""TEST_SAGEMAKER""" , """False""" ) ) is not True , reason="""Skipping test because should only be run when releasing minor transformers version""" , ) @pytest.mark.usefixtures("""sm_env""" ) @parameterized_class( [ { """framework""": """pytorch""", """script""": """run_glue_model_parallelism.py""", """model_name_or_path""": """roberta-large""", """instance_type""": """ml.p3dn.24xlarge""", """results""": {"""train_runtime""": 1_600, """eval_accuracy""": 0.3, """eval_loss""": 1.2}, }, { """framework""": """pytorch""", """script""": """run_glue.py""", """model_name_or_path""": """roberta-large""", """instance_type""": """ml.p3dn.24xlarge""", """results""": {"""train_runtime""": 1_600, """eval_accuracy""": 0.3, """eval_loss""": 1.2}, }, ] ) class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Optional[int] ) -> List[Any]: if self.framework == "pytorch": subprocess.run( f'''cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'''.split() , encoding='''utf-8''' , check=SCREAMING_SNAKE_CASE__ , ) assert hasattr(self , '''env''' ) def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: # configuration for running training on smdistributed Model Parallel __lowerCamelCase = { '''enabled''': True, '''processes_per_host''': 8, } __lowerCamelCase = { '''enabled''': True, '''parameters''': { '''microbatches''': 4, '''placement_strategy''': '''spread''', '''pipeline''': '''interleaved''', '''optimize''': '''speed''', '''partitions''': 4, '''ddp''': True, }, } __lowerCamelCase = {'''smdistributed''': {'''modelparallel''': smp_options}, '''mpi''': mpi_options} __lowerCamelCase = '''trainer''' if self.script == '''run_glue.py''' else '''smtrainer''' # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=f'''{self.env.base_job_name}-{instance_count}-smp-{name_extension}''' , instance_count=SCREAMING_SNAKE_CASE__ , instance_type=self.instance_type , debugger_hook_config=SCREAMING_SNAKE_CASE__ , hyperparameters={ **self.env.hyperparameters, '''model_name_or_path''': self.model_name_or_path, '''max_steps''': 5_00, } , metric_definitions=self.env.metric_definitions , distribution=SCREAMING_SNAKE_CASE__ , py_version='''py36''' , ) def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[str]: TrainingJobAnalytics(SCREAMING_SNAKE_CASE__ ).export_csv(f'''{self.env.test_path}/{job_name}_metrics.csv''' ) @parameterized.expand([(1,)] ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: # create estimator __lowerCamelCase = self.create_estimator(SCREAMING_SNAKE_CASE__ ) # run training estimator.fit() # result dataframe __lowerCamelCase = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __lowerCamelCase = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) __lowerCamelCase = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 99_99_99 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy ) assert all(t <= self.results['''eval_loss'''] for t in eval_loss ) # dump tests result into json file to share in PR with open(f'''{estimator.latest_training_job.name}.json''' , '''w''' ) as outfile: json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss} , SCREAMING_SNAKE_CASE__ )
270
0
import unittest from transformers import GPTSwaTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin A : str = get_tests_dir('fixtures/test_sentencepiece_with_bytefallback.model') @require_sentencepiece @require_tokenizers class A ( __lowercase , unittest.TestCase ): '''simple docstring''' A__ = GPTSwaTokenizer A__ = False A__ = True A__ = False def lowerCamelCase__ (self : Dict ) -> List[Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing lowercase__ = GPTSwaTokenizer(SCREAMING_SNAKE_CASE__ , eos_token="""<unk>""" , bos_token="""<unk>""" , pad_token="""<unk>""" ) tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase__ (self : List[str] , _UpperCAmelCase : Any ) -> Optional[Any]: """simple docstring""" lowercase__ = """This is a test""" lowercase__ = """This is a test""" return input_text, output_text def lowerCamelCase__ (self : str ) -> str: """simple docstring""" lowercase__ = """<s>""" lowercase__ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def lowerCamelCase__ (self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" lowercase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , """<unk>""" ) self.assertEqual(vocab_keys[1] , """<s>""" ) self.assertEqual(vocab_keys[-1] , """j""" ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 2000 ) def lowerCamelCase__ (self : Union[str, Any] ) -> Optional[int]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 2000 ) def lowerCamelCase__ (self : Union[str, Any] ) -> Union[str, Any]: """simple docstring""" lowercase__ = GPTSwaTokenizer(SCREAMING_SNAKE_CASE__ ) lowercase__ = tokenizer.tokenize("""This is a test""" ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [465, 287, 265, 631, 842] ) lowercase__ = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" ) # fmt: off self.assertListEqual( SCREAMING_SNAKE_CASE__ , ["""▁I""", """▁was""", """▁bor""", """n""", """▁in""", """▁""", """<0x39>""", """2""", """0""", """0""", """0""", """,""", """▁and""", """▁this""", """▁is""", """▁f""", """al""", """s""", """<0xC3>""", """<0xA9>""", """."""] , ) # fmt: on lowercase__ = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [262, 272, 1525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260] , ) lowercase__ = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) # fmt: off self.assertListEqual( SCREAMING_SNAKE_CASE__ , ["""▁I""", """▁was""", """▁bor""", """n""", """▁in""", """▁""", """<0x39>""", """2""", """0""", """0""", """0""", """,""", """▁and""", """▁this""", """▁is""", """▁f""", """al""", """s""", """<0xC3>""", """<0xA9>""", """."""] ) # fmt: on def lowerCamelCase__ (self : Any ) -> List[str]: """simple docstring""" lowercase__ = GPTSwaTokenizer(SCREAMING_SNAKE_CASE__ ) lowercase__ = ["""This is a test""", """I was born in 92000, and this is falsé."""] lowercase__ = [ [465, 287, 265, 631, 842], [262, 272, 1525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260], ] # Test that encode_fast returns the same as tokenize + convert_tokens_to_ids for text, expected_ids in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertListEqual(tokenizer.encode_fast(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) # Test that decode_fast returns the input text for text, token_ids in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(tokenizer.decode_fast(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) @slow def lowerCamelCase__ (self : List[Any] ) -> str: """simple docstring""" lowercase__ = [ """<|python|>def fibonacci(n)\n if n < 0:\n print(\'Incorrect input\')""", """Hey there, how are you doing this fine day?""", """This is a text with a trailing spaces followed by a dot .""", """Häj sväjs lillebrör! =)""", """Det är inget fel på Mr. Cool""", ] # fmt: off lowercase__ = {"""input_ids""": [[6_3423, 5, 6811, 1_4954, 282, 816, 3821, 6_3466, 6_3425, 6_3462, 18, 6_3978, 678, 301, 1320, 6_3423, 6_3455, 6_3458, 18, 6_3982, 4246, 3940, 1901, 4_7789, 5547, 1_8994], [1_9630, 1100, 6_3446, 1342, 633, 544, 4488, 593, 5102, 2416, 6_3495, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1652, 428, 268, 1936, 515, 268, 5_8593, 2_2413, 9106, 546, 268, 3_3213, 6_3979, 698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [5_5130, 6_3450, 924, 6_3449, 2249, 4062, 1558, 318, 6_3504, 2_1498, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [509, 377, 2827, 2559, 332, 6575, 6_3443, 2_6801, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """token_type_ids""": [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # fmt: on self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE__ , model_name="""AI-Sweden/gpt-sw3-126m""" , sequences=SCREAMING_SNAKE_CASE__ , )
305
from __future__ import annotations from fractions import Fraction def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> bool: return ( num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den ) def __magic_name__ ( __lowerCAmelCase : int ) -> list[str]: __lowerCamelCase = [] __lowerCamelCase = 11 __lowerCamelCase = int('''1''' + '''0''' * digit_len ) for num in range(__lowerCAmelCase , __lowerCAmelCase ): while den <= 99: if (num != den) and (num % 10 == den // 10) and (den % 10 != 0): if is_digit_cancelling(__lowerCAmelCase , __lowerCAmelCase ): solutions.append(f'''{num}/{den}''' ) den += 1 num += 1 __lowerCamelCase = 10 return solutions def __magic_name__ ( __lowerCAmelCase : int = 2 ) -> int: __lowerCamelCase = 1.0 for fraction in fraction_list(__lowerCAmelCase ): __lowerCamelCase = Fraction(__lowerCAmelCase ) result *= frac.denominator / frac.numerator return int(__lowerCAmelCase ) if __name__ == "__main__": print(solution())
270
0
'''simple docstring''' import unittest import numpy as np import requests from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: UpperCAmelCase_ = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def __init__( self : Tuple , _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : List[Any]=7 , _UpperCAmelCase : List[str]=3 , _UpperCAmelCase : Tuple=18 , _UpperCAmelCase : int=30 , _UpperCAmelCase : Any=4_00 , _UpperCAmelCase : Any=None , _UpperCAmelCase : str=True , _UpperCAmelCase : str=True , _UpperCAmelCase : Optional[Any]=None , ): """simple docstring""" UpperCAmelCase__ = size if size is not None else {"""height""": 20, """width""": 20} UpperCAmelCase__ = parent UpperCAmelCase__ = batch_size UpperCAmelCase__ = num_channels UpperCAmelCase__ = image_size UpperCAmelCase__ = min_resolution UpperCAmelCase__ = max_resolution UpperCAmelCase__ = size UpperCAmelCase__ = do_normalize UpperCAmelCase__ = do_convert_rgb UpperCAmelCase__ = [5_12, 10_24, 20_48, 40_96] UpperCAmelCase__ = patch_size if patch_size is not None else {"""height""": 16, """width""": 16} def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def SCREAMING_SNAKE_CASE__ ( self : int ): """simple docstring""" UpperCAmelCase__ = """https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg""" UpperCAmelCase__ = Image.open(requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ ).raw ).convert("""RGB""" ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`.""" , ) @require_torch @require_vision class lowerCAmelCase_ ( __lowercase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase_ : Dict = PixaStructImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ ( self : Optional[Any] ): """simple docstring""" UpperCAmelCase__ = PixaStructImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ ( self : Tuple ): """simple docstring""" UpperCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , """do_normalize""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , """do_convert_rgb""" ) ) def SCREAMING_SNAKE_CASE__ ( self : int ): """simple docstring""" UpperCAmelCase__ = self.image_processor_tester.prepare_dummy_image() UpperCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) UpperCAmelCase__ = 20_48 UpperCAmelCase__ = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors="""pt""" , max_patches=SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1E-3 , rtol=1E-3 ) ) def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" UpperCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input UpperCAmelCase__ = ( (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""]) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input UpperCAmelCase__ = image_processor( image_inputs[0] , return_tensors="""pt""" , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched UpperCAmelCase__ = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors="""pt""" , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def SCREAMING_SNAKE_CASE__ ( self : Dict ): """simple docstring""" UpperCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input UpperCAmelCase__ = ( (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""]) * self.image_processor_tester.num_channels ) + 2 UpperCAmelCase__ = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(SCREAMING_SNAKE_CASE__ ): UpperCAmelCase__ = image_processor( image_inputs[0] , return_tensors="""pt""" , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches UpperCAmelCase__ = """Hello""" UpperCAmelCase__ = image_processor( image_inputs[0] , return_tensors="""pt""" , max_patches=SCREAMING_SNAKE_CASE__ , header_text=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched UpperCAmelCase__ = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors="""pt""" , max_patches=SCREAMING_SNAKE_CASE__ , header_text=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def SCREAMING_SNAKE_CASE__ ( self : List[str] ): """simple docstring""" UpperCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) UpperCAmelCase__ = ( (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""]) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input UpperCAmelCase__ = image_processor( image_inputs[0] , return_tensors="""pt""" , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched UpperCAmelCase__ = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors="""pt""" , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def SCREAMING_SNAKE_CASE__ ( self : Tuple ): """simple docstring""" UpperCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input UpperCAmelCase__ = ( (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""]) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input UpperCAmelCase__ = image_processor( image_inputs[0] , return_tensors="""pt""" , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched UpperCAmelCase__ = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors="""pt""" , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`.""" , ) @require_torch @require_vision class lowerCAmelCase_ ( __lowercase , unittest.TestCase ): '''simple docstring''' lowerCAmelCase_ : Any = PixaStructImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" UpperCAmelCase__ = PixaStructImageProcessingTester(self , num_channels=4 ) UpperCAmelCase__ = 3 @property def SCREAMING_SNAKE_CASE__ ( self : List[Any] ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE__ ( self : Union[str, Any] ): """simple docstring""" UpperCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , """do_normalize""" ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , """do_convert_rgb""" ) ) def SCREAMING_SNAKE_CASE__ ( self : Optional[int] ): """simple docstring""" UpperCAmelCase__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCAmelCase__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input UpperCAmelCase__ = ( (self.image_processor_tester.patch_size["""height"""] * self.image_processor_tester.patch_size["""width"""]) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input UpperCAmelCase__ = image_processor( image_inputs[0] , return_tensors="""pt""" , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched UpperCAmelCase__ = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors="""pt""" , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
346
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE__ : List[str] = { "configuration_blip": [ "BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlipConfig", "BlipTextConfig", "BlipVisionConfig", ], "processing_blip": ["BlipProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = ["BlipImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "BLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "BlipModel", "BlipPreTrainedModel", "BlipForConditionalGeneration", "BlipForQuestionAnswering", "BlipVisionModel", "BlipTextModel", "BlipForImageTextRetrieval", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Any = [ "TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "TFBlipModel", "TFBlipPreTrainedModel", "TFBlipForConditionalGeneration", "TFBlipForQuestionAnswering", "TFBlipVisionModel", "TFBlipTextModel", "TFBlipForImageTextRetrieval", ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
270
0
from __future__ import annotations A : Optional[Any] = list[tuple[int, int]] A : Tuple = [ [0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], ] A : Optional[Any] = ([-1, 0], [0, -1], [1, 0], [0, 1]) # up, left, down, right class _lowercase : """simple docstring""" def __init__( self : Optional[Any] , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : float , __lowerCamelCase : Node | None , ): '''simple docstring''' lowerCamelCase__ : List[str] = pos_x lowerCamelCase__ : Tuple = pos_y lowerCamelCase__ : Any = (pos_y, pos_x) lowerCamelCase__ : List[Any] = goal_x lowerCamelCase__ : str = goal_y lowerCamelCase__ : List[Any] = g_cost lowerCamelCase__ : Any = parent lowerCamelCase__ : List[Any] = self.calculate_heuristic() def lowerCAmelCase ( self : Optional[int] ): '''simple docstring''' lowerCamelCase__ : List[Any] = abs(self.pos_x - self.goal_x ) lowerCamelCase__ : Any = abs(self.pos_y - self.goal_y ) return dx + dy def __lt__( self : Dict , __lowerCamelCase : List[str] ): '''simple docstring''' return self.f_cost < other.f_cost class _lowercase : """simple docstring""" def __init__( self : int , __lowerCamelCase : tuple[int, int] , __lowerCamelCase : tuple[int, int] ): '''simple docstring''' lowerCamelCase__ : int = Node(start[1] , start[0] , goal[1] , goal[0] , 0 , SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : List[str] = Node(goal[1] , goal[0] , goal[1] , goal[0] , 99999 , SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Optional[Any] = [self.start] lowerCamelCase__ : int = [] lowerCamelCase__ : int = False def lowerCAmelCase ( self : Dict ): '''simple docstring''' while self.open_nodes: # Open Nodes are sorted using __lt__ self.open_nodes.sort() lowerCamelCase__ : int = self.open_nodes.pop(0 ) if current_node.pos == self.target.pos: lowerCamelCase__ : List[Any] = True return self.retrace_path(SCREAMING_SNAKE_CASE__ ) self.closed_nodes.append(SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : List[str] = self.get_successors(SCREAMING_SNAKE_CASE__ ) for child_node in successors: if child_node in self.closed_nodes: continue if child_node not in self.open_nodes: self.open_nodes.append(SCREAMING_SNAKE_CASE__ ) else: # retrieve the best current path lowerCamelCase__ : str = self.open_nodes.pop(self.open_nodes.index(SCREAMING_SNAKE_CASE__ ) ) if child_node.g_cost < better_node.g_cost: self.open_nodes.append(SCREAMING_SNAKE_CASE__ ) else: self.open_nodes.append(SCREAMING_SNAKE_CASE__ ) if not self.reached: return [self.start.pos] return None def lowerCAmelCase ( self : List[Any] , __lowerCamelCase : Node ): '''simple docstring''' lowerCamelCase__ : Tuple = [] for action in delta: lowerCamelCase__ : Tuple = parent.pos_x + action[1] lowerCamelCase__ : List[Any] = parent.pos_y + action[0] if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(SCREAMING_SNAKE_CASE__ ) - 1): continue if grid[pos_y][pos_x] != 0: continue successors.append( Node( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , self.target.pos_y , self.target.pos_x , parent.g_cost + 1 , SCREAMING_SNAKE_CASE__ , ) ) return successors def lowerCAmelCase ( self : List[str] , __lowerCamelCase : Node | None ): '''simple docstring''' lowerCamelCase__ : str = node lowerCamelCase__ : str = [] while current_node is not None: path.append((current_node.pos_y, current_node.pos_x) ) lowerCamelCase__ : Union[str, Any] = current_node.parent path.reverse() return path if __name__ == "__main__": A : Optional[int] = (0, 0) A : Optional[Any] = (len(grid) - 1, len(grid[0]) - 1) for elem in grid: print(elem) print("------") A : str = GreedyBestFirst(init, goal) A : Dict = greedy_bf.search() if path: for pos_x, pos_y in path: A : Tuple = 2 for elem in grid: print(elem)
184
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Optional[Any] = {"configuration_wavlm": ["WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "WavLMConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST", "WavLMForAudioFrameClassification", "WavLMForCTC", "WavLMForSequenceClassification", "WavLMForXVector", "WavLMModel", "WavLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_wavlm import WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP, WavLMConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavlm import ( WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST, WavLMForAudioFrameClassification, WavLMForCTC, WavLMForSequenceClassification, WavLMForXVector, WavLMModel, WavLMPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
270
0
"""simple docstring""" import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionTextToImagePipeline from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device lowerCAmelCase = False class A_ ( unittest.TestCase ): """simple docstring""" pass @nightly @require_torch_gpu class A_ ( unittest.TestCase ): """simple docstring""" def UpperCAmelCase__ ( self :str ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCAmelCase__ ( self :List[str] ): """simple docstring""" lowerCamelCase__ : List[Any] =VersatileDiffusionTextToImagePipeline.from_pretrained('shi-labs/versatile-diffusion' ) # remove text_unet pipe.remove_unused_weights() pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Optional[Any] ='A painting of a squirrel eating a burger ' lowerCamelCase__ : Optional[Any] =torch.manual_seed(0 ) lowerCamelCase__ : int =pipe( prompt=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=7.5 , num_inference_steps=2 , output_type='numpy' ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Dict =VersatileDiffusionTextToImagePipeline.from_pretrained(SCREAMING_SNAKE_CASE__ ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Union[str, Any] =generator.manual_seed(0 ) lowerCamelCase__ : Any =pipe( prompt=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=7.5 , num_inference_steps=2 , output_type='numpy' ).images assert np.abs(image - new_image ).sum() < 1e-5, "Models don't have the same forward pass" def UpperCAmelCase__ ( self :int ): """simple docstring""" lowerCamelCase__ : List[Any] =VersatileDiffusionTextToImagePipeline.from_pretrained( 'shi-labs/versatile-diffusion' , torch_dtype=torch.floataa ) pipe.to(SCREAMING_SNAKE_CASE__ ) pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : List[str] ='A painting of a squirrel eating a burger ' lowerCamelCase__ : Union[str, Any] =torch.manual_seed(0 ) lowerCamelCase__ : Tuple =pipe( prompt=SCREAMING_SNAKE_CASE__ , generator=SCREAMING_SNAKE_CASE__ , guidance_scale=7.5 , num_inference_steps=50 , output_type='numpy' ).images lowerCamelCase__ : List[Any] =image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) lowerCamelCase__ : Union[str, Any] =np.array([0.33_67, 0.31_69, 0.26_56, 0.38_70, 0.47_90, 0.37_96, 0.40_09, 0.48_78, 0.47_78] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
126
import pprint import requests SCREAMING_SNAKE_CASE__ : str = "https://zenquotes.io/api" def __magic_name__ ( ) -> list: return requests.get(API_ENDPOINT_URL + '''/today''' ).json() def __magic_name__ ( ) -> list: return requests.get(API_ENDPOINT_URL + '''/random''' ).json() if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : int = random_quotes() pprint.pprint(response)
270
0
"""simple docstring""" import numpy as np import datasets _lowercase : Tuple = "\nCompute the Mahalanobis Distance\n\nMahalonobis distance is the distance between a point and a distribution.\nAnd not between two distinct points. It is effectively a multivariate equivalent of the Euclidean distance.\nIt was introduced by Prof. P. C. Mahalanobis in 1936\nand has been used in various statistical applications ever since\n[source: https://www.machinelearningplus.com/statistics/mahalanobis-distance/]\n" _lowercase : Optional[Any] = "\\n@article{de2000mahalanobis,\n title={The mahalanobis distance},\n author={De Maesschalck, Roy and Jouan-Rimbaud, Delphine and Massart, D{\'e}sir{\'e} L},\n journal={Chemometrics and intelligent laboratory systems},\n volume={50},\n number={1},\n pages={1--18},\n year={2000},\n publisher={Elsevier}\n}\n" _lowercase : Optional[int] = "\nArgs:\n X: List of datapoints to be compared with the `reference_distribution`.\n reference_distribution: List of datapoints from the reference distribution we want to compare to.\nReturns:\n mahalanobis: The Mahalonobis distance for each datapoint in `X`.\nExamples:\n\n >>> mahalanobis_metric = datasets.load_metric(\"mahalanobis\")\n >>> results = mahalanobis_metric.compute(reference_distribution=[[0, 1], [1, 0]], X=[[0, 1]])\n >>> print(results)\n {'mahalanobis': array([0.5])}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __SCREAMING_SNAKE_CASE ( datasets.Metric ): '''simple docstring''' def snake_case ( self : Tuple )-> Any: return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { '''X''': datasets.Sequence(datasets.Value('''float''', id='''sequence''' ), id='''X''' ), } ), ) def snake_case ( self : Dict, lowerCamelCase : Union[str, Any], lowerCamelCase : Dict )-> List[Any]: # convert to numpy arrays lowerCamelCase__ : int =np.array(SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : List[Any] =np.array(SCREAMING_SNAKE_CASE__ ) # Assert that arrays are 2D if len(X.shape ) != 2: raise ValueError('''Expected `X` to be a 2D vector''' ) if len(reference_distribution.shape ) != 2: raise ValueError('''Expected `reference_distribution` to be a 2D vector''' ) if reference_distribution.shape[0] < 2: raise ValueError( '''Expected `reference_distribution` to be a 2D vector with more than one element in the first dimension''' ) # Get mahalanobis distance for each prediction lowerCamelCase__ : List[str] =X - np.mean(SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Optional[Any] =np.cov(reference_distribution.T ) try: lowerCamelCase__ : str =np.linalg.inv(SCREAMING_SNAKE_CASE__ ) except np.linalg.LinAlgError: lowerCamelCase__ : Any =np.linalg.pinv(SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Dict =np.dot(SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : Any =np.dot(SCREAMING_SNAKE_CASE__, X_minus_mu.T ).diagonal() return {"mahalanobis": mahal_dist}
238
from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def __magic_name__ ( __lowerCAmelCase : int ) -> int: __lowerCamelCase = prime_factors(__lowerCAmelCase ) if is_square_free(__lowerCAmelCase ): return -1 if len(__lowerCAmelCase ) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
270
0
import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer lowercase__ : int = logging.get_logger(__name__) lowercase__ : Union[str, Any] = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"} lowercase__ : Optional[Any] = { "vocab_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt" ), "distilbert-base-german-cased": "https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt", "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt" ), }, "tokenizer_file": { "distilbert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json", "distilbert-base-uncased-distilled-squad": ( "https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-cased": "https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json", "distilbert-base-cased-distilled-squad": ( "https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json" ), "distilbert-base-german-cased": ( "https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json" ), "distilbert-base-multilingual-cased": ( "https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json" ), }, } lowercase__ : Tuple = { "distilbert-base-uncased": 512, "distilbert-base-uncased-distilled-squad": 512, "distilbert-base-cased": 512, "distilbert-base-cased-distilled-squad": 512, "distilbert-base-german-cased": 512, "distilbert-base-multilingual-cased": 512, } lowercase__ : Dict = { "distilbert-base-uncased": {"do_lower_case": True}, "distilbert-base-uncased-distilled-squad": {"do_lower_case": True}, "distilbert-base-cased": {"do_lower_case": False}, "distilbert-base-cased-distilled-squad": {"do_lower_case": False}, "distilbert-base-german-cased": {"do_lower_case": False}, "distilbert-base-multilingual-cased": {"do_lower_case": False}, } class UpperCAmelCase ( __lowercase ): '''simple docstring''' lowerCAmelCase_ = VOCAB_FILES_NAMES lowerCAmelCase_ = PRETRAINED_VOCAB_FILES_MAP lowerCAmelCase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCAmelCase_ = PRETRAINED_INIT_CONFIGURATION lowerCAmelCase_ = ["""input_ids""", """attention_mask"""] lowerCAmelCase_ = DistilBertTokenizer def __init__( self : List[Any] , __lowercase : Any=None , __lowercase : int=None , __lowercase : int=True , __lowercase : Optional[Any]="[UNK]" , __lowercase : Optional[int]="[SEP]" , __lowercase : Union[str, Any]="[PAD]" , __lowercase : List[Any]="[CLS]" , __lowercase : List[Any]="[MASK]" , __lowercase : Dict=True , __lowercase : int=None , **__lowercase : Optional[Any] , ): """simple docstring""" super().__init__( SCREAMING_SNAKE_CASE__ , tokenizer_file=SCREAMING_SNAKE_CASE__ , do_lower_case=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , tokenize_chinese_chars=SCREAMING_SNAKE_CASE__ , strip_accents=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) snake_case_ = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get("lowercase" , SCREAMING_SNAKE_CASE__ ) != do_lower_case or normalizer_state.get("strip_accents" , SCREAMING_SNAKE_CASE__ ) != strip_accents or normalizer_state.get("handle_chinese_chars" , SCREAMING_SNAKE_CASE__ ) != tokenize_chinese_chars ): snake_case_ = getattr(SCREAMING_SNAKE_CASE__ , normalizer_state.pop("type" ) ) snake_case_ = do_lower_case snake_case_ = strip_accents snake_case_ = tokenize_chinese_chars snake_case_ = normalizer_class(**SCREAMING_SNAKE_CASE__ ) snake_case_ = do_lower_case def snake_case__ ( self : Optional[Any] , __lowercase : Optional[Any] , __lowercase : int=None ): """simple docstring""" snake_case_ = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def snake_case__ ( self : Optional[int] , __lowercase : List[int] , __lowercase : Optional[List[int]] = None ): """simple docstring""" snake_case_ = [self.sep_token_id] snake_case_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def snake_case__ ( self : Optional[Any] , __lowercase : str , __lowercase : Optional[str] = None ): """simple docstring""" snake_case_ = self._tokenizer.model.save(SCREAMING_SNAKE_CASE__ , name=SCREAMING_SNAKE_CASE__ ) return tuple(SCREAMING_SNAKE_CASE__ )
187
import argparse import collections import json import os import re import string import sys import numpy as np SCREAMING_SNAKE_CASE__ : Union[str, Any] = re.compile(r"\b(a|an|the)\b", re.UNICODE) SCREAMING_SNAKE_CASE__ : int = None def __magic_name__ ( ) -> str: __lowerCamelCase = argparse.ArgumentParser('''Official evaluation script for SQuAD version 2.0.''' ) parser.add_argument('''data_file''' , metavar='''data.json''' , help='''Input data JSON file.''' ) parser.add_argument('''pred_file''' , metavar='''pred.json''' , help='''Model predictions.''' ) parser.add_argument( '''--out-file''' , '''-o''' , metavar='''eval.json''' , help='''Write accuracy metrics to file (default is stdout).''' ) parser.add_argument( '''--na-prob-file''' , '''-n''' , metavar='''na_prob.json''' , help='''Model estimates of probability of no answer.''' ) parser.add_argument( '''--na-prob-thresh''' , '''-t''' , type=__lowerCAmelCase , default=1.0 , help='''Predict "" if no-answer probability exceeds this (default = 1.0).''' , ) parser.add_argument( '''--out-image-dir''' , '''-p''' , metavar='''out_images''' , default=__lowerCAmelCase , help='''Save precision-recall curves to directory.''' ) parser.add_argument('''--verbose''' , '''-v''' , action='''store_true''' ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def __magic_name__ ( __lowerCAmelCase : List[str] ) -> Union[str, Any]: __lowerCamelCase = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __lowerCamelCase = bool(qa['''answers''']['''text'''] ) return qid_to_has_ans def __magic_name__ ( __lowerCAmelCase : Dict ) -> Optional[Any]: def remove_articles(__lowerCAmelCase : Optional[int] ): return ARTICLES_REGEX.sub(''' ''' , __lowerCAmelCase ) def white_space_fix(__lowerCAmelCase : Optional[int] ): return " ".join(text.split() ) def remove_punc(__lowerCAmelCase : Union[str, Any] ): __lowerCamelCase = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(__lowerCAmelCase : Dict ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(__lowerCAmelCase ) ) ) ) def __magic_name__ ( __lowerCAmelCase : List[Any] ) -> Optional[int]: if not s: return [] return normalize_answer(__lowerCAmelCase ).split() def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple ) -> int: return int(normalize_answer(__lowerCAmelCase ) == normalize_answer(__lowerCAmelCase ) ) def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : Tuple ) -> str: __lowerCamelCase = get_tokens(__lowerCAmelCase ) __lowerCamelCase = get_tokens(__lowerCAmelCase ) __lowerCamelCase = collections.Counter(__lowerCAmelCase ) & collections.Counter(__lowerCAmelCase ) __lowerCamelCase = sum(common.values() ) if len(__lowerCAmelCase ) == 0 or len(__lowerCAmelCase ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 __lowerCamelCase = 1.0 * num_same / len(__lowerCAmelCase ) __lowerCamelCase = 1.0 * num_same / len(__lowerCAmelCase ) __lowerCamelCase = (2 * precision * recall) / (precision + recall) return fa def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : List[str] ) -> Optional[Any]: __lowerCamelCase = {} __lowerCamelCase = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __lowerCamelCase = qa['''id'''] __lowerCamelCase = [t for t in qa['''answers''']['''text'''] if normalize_answer(__lowerCAmelCase )] if not gold_answers: # For unanswerable questions, only correct answer is empty string __lowerCamelCase = [''''''] if qid not in preds: print(f'''Missing prediction for {qid}''' ) continue __lowerCamelCase = preds[qid] # Take max over all gold answers __lowerCamelCase = max(compute_exact(__lowerCAmelCase , __lowerCAmelCase ) for a in gold_answers ) __lowerCamelCase = max(compute_fa(__lowerCAmelCase , __lowerCAmelCase ) for a in gold_answers ) return exact_scores, fa_scores def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Union[str, Any] ) -> List[str]: __lowerCamelCase = {} for qid, s in scores.items(): __lowerCamelCase = na_probs[qid] > na_prob_thresh if pred_na: __lowerCamelCase = float(not qid_to_has_ans[qid] ) else: __lowerCamelCase = s return new_scores def __magic_name__ ( __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[Any]=None ) -> Union[str, Any]: if not qid_list: __lowerCamelCase = len(__lowerCAmelCase ) return collections.OrderedDict( [ ('''exact''', 100.0 * sum(exact_scores.values() ) / total), ('''f1''', 100.0 * sum(fa_scores.values() ) / total), ('''total''', total), ] ) else: __lowerCamelCase = len(__lowerCAmelCase ) return collections.OrderedDict( [ ('''exact''', 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ('''f1''', 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ('''total''', total), ] ) def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : str , __lowerCAmelCase : Optional[Any] ) -> int: for k in new_eval: __lowerCamelCase = new_eval[k] def __magic_name__ ( __lowerCAmelCase : Optional[int] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : Union[str, Any] ) -> Optional[Any]: plt.step(__lowerCAmelCase , __lowerCAmelCase , color='''b''' , alpha=0.2 , where='''post''' ) plt.fill_between(__lowerCAmelCase , __lowerCAmelCase , step='''post''' , alpha=0.2 , color='''b''' ) plt.xlabel('''Recall''' ) plt.ylabel('''Precision''' ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(__lowerCAmelCase ) plt.savefig(__lowerCAmelCase ) plt.clf() def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[Any]=None , __lowerCAmelCase : Tuple=None ) -> int: __lowerCamelCase = sorted(__lowerCAmelCase , key=lambda __lowerCAmelCase : na_probs[k] ) __lowerCamelCase = 0.0 __lowerCamelCase = 1.0 __lowerCamelCase = 0.0 __lowerCamelCase = [1.0] __lowerCamelCase = [0.0] __lowerCamelCase = 0.0 for i, qid in enumerate(__lowerCAmelCase ): if qid_to_has_ans[qid]: true_pos += scores[qid] __lowerCamelCase = true_pos / float(i + 1 ) __lowerCamelCase = true_pos / float(__lowerCAmelCase ) if i == len(__lowerCAmelCase ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(__lowerCAmelCase ) recalls.append(__lowerCAmelCase ) if out_image: plot_pr_curve(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) return {"ap": 100.0 * avg_prec} def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Tuple , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : List[Any] ) -> List[Any]: if out_image_dir and not os.path.exists(__lowerCAmelCase ): os.makedirs(__lowerCAmelCase ) __lowerCamelCase = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_exact.png''' ) , title='''Precision-Recall curve for Exact Match score''' , ) __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_f1.png''' ) , title='''Precision-Recall curve for F1 score''' , ) __lowerCamelCase = {k: float(__lowerCAmelCase ) for k, v in qid_to_has_ans.items()} __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_oracle.png''' ) , title='''Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)''' , ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_exact''' ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_f1''' ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_oracle''' ) def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Any , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : int ) -> Optional[Any]: if not qid_list: return __lowerCamelCase = [na_probs[k] for k in qid_list] __lowerCamelCase = np.ones_like(__lowerCAmelCase ) / float(len(__lowerCAmelCase ) ) plt.hist(__lowerCAmelCase , weights=__lowerCAmelCase , bins=20 , range=(0.0, 1.0) ) plt.xlabel('''Model probability of no-answer''' ) plt.ylabel('''Proportion of dataset''' ) plt.title(f'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(__lowerCAmelCase , f'''na_prob_hist_{name}.png''' ) ) plt.clf() def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Union[str, Any] ) -> Optional[int]: __lowerCamelCase = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) __lowerCamelCase = num_no_ans __lowerCamelCase = cur_score __lowerCamelCase = 0.0 __lowerCamelCase = sorted(__lowerCAmelCase , key=lambda __lowerCAmelCase : na_probs[k] ) for i, qid in enumerate(__lowerCAmelCase ): if qid not in scores: continue if qid_to_has_ans[qid]: __lowerCamelCase = scores[qid] else: if preds[qid]: __lowerCamelCase = -1 else: __lowerCamelCase = 0 cur_score += diff if cur_score > best_score: __lowerCamelCase = cur_score __lowerCamelCase = na_probs[qid] return 100.0 * best_score / len(__lowerCAmelCase ), best_thresh def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : int , __lowerCAmelCase : Optional[Any] ) -> int: __lowerCamelCase , __lowerCamelCase = find_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = find_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = best_exact __lowerCamelCase = exact_thresh __lowerCamelCase = best_fa __lowerCamelCase = fa_thresh def __magic_name__ ( ) -> Optional[int]: with open(OPTS.data_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) __lowerCamelCase = dataset_json['''data'''] with open(OPTS.pred_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) else: __lowerCamelCase = {k: 0.0 for k in preds} __lowerCamelCase = make_qid_to_has_ans(__lowerCAmelCase ) # maps qid to True/False __lowerCamelCase = [k for k, v in qid_to_has_ans.items() if v] __lowerCamelCase = [k for k, v in qid_to_has_ans.items() if not v] __lowerCamelCase , __lowerCamelCase = get_raw_scores(__lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = apply_no_ans_threshold(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.na_prob_thresh ) __lowerCamelCase = apply_no_ans_threshold(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.na_prob_thresh ) __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase ) if has_ans_qids: __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase , qid_list=__lowerCAmelCase ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''HasAns''' ) if no_ans_qids: __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase , qid_list=__lowerCAmelCase ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''NoAns''' ) if OPTS.na_prob_file: find_all_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir ) histogram_na_prob(__lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir , '''hasAns''' ) histogram_na_prob(__lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir , '''noAns''' ) if OPTS.out_file: with open(OPTS.out_file , '''w''' ) as f: json.dump(__lowerCAmelCase , __lowerCAmelCase ) else: print(json.dumps(__lowerCAmelCase , indent=2 ) ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Any = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt main()
270
0
from copy import deepcopy class __UpperCAmelCase : def __init__( self: Tuple , UpperCAmelCase_: list[int] | None = None , UpperCAmelCase_: int | None = None ): '''simple docstring''' if arr is None and size is not None: _SCREAMING_SNAKE_CASE = size _SCREAMING_SNAKE_CASE = [0] * size elif arr is not None: self.init(SCREAMING_SNAKE_CASE__ ) else: raise ValueError("""Either arr or size must be specified""" ) def UpperCamelCase ( self: Union[str, Any] , UpperCAmelCase_: list[int] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = len(SCREAMING_SNAKE_CASE__ ) _SCREAMING_SNAKE_CASE = deepcopy(SCREAMING_SNAKE_CASE__ ) for i in range(1 , self.size ): _SCREAMING_SNAKE_CASE = self.next_(SCREAMING_SNAKE_CASE__ ) if j < self.size: self.tree[j] += self.tree[i] def UpperCamelCase ( self: Optional[Any] ): '''simple docstring''' _SCREAMING_SNAKE_CASE = self.tree[:] for i in range(self.size - 1 , 0 , -1 ): _SCREAMING_SNAKE_CASE = self.next_(SCREAMING_SNAKE_CASE__ ) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def UpperCamelCase ( UpperCAmelCase_: int ): '''simple docstring''' return index + (index & (-index)) @staticmethod def UpperCamelCase ( UpperCAmelCase_: int ): '''simple docstring''' return index - (index & (-index)) def UpperCamelCase ( self: str , UpperCAmelCase_: int , UpperCAmelCase_: int ): '''simple docstring''' if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value _SCREAMING_SNAKE_CASE = self.next_(SCREAMING_SNAKE_CASE__ ) def UpperCamelCase ( self: Dict , UpperCAmelCase_: int , UpperCAmelCase_: int ): '''simple docstring''' self.add(SCREAMING_SNAKE_CASE__ , value - self.get(SCREAMING_SNAKE_CASE__ ) ) def UpperCamelCase ( self: Union[str, Any] , UpperCAmelCase_: int ): '''simple docstring''' if right == 0: return 0 _SCREAMING_SNAKE_CASE = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] _SCREAMING_SNAKE_CASE = self.prev(SCREAMING_SNAKE_CASE__ ) return result def UpperCamelCase ( self: Optional[int] , UpperCAmelCase_: int , UpperCAmelCase_: int ): '''simple docstring''' return self.prefix(SCREAMING_SNAKE_CASE__ ) - self.prefix(SCREAMING_SNAKE_CASE__ ) def UpperCamelCase ( self: Tuple , UpperCAmelCase_: int ): '''simple docstring''' return self.query(SCREAMING_SNAKE_CASE__ , index + 1 ) def UpperCamelCase ( self: Optional[Any] , UpperCAmelCase_: int ): '''simple docstring''' value -= self.tree[0] if value < 0: return -1 _SCREAMING_SNAKE_CASE = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 _SCREAMING_SNAKE_CASE = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
306
import math import os import re import sys import unittest from pathlib import Path from typing import Tuple from unittest.mock import patch from parameterized import parameterized from transformers.testing_utils import ( CaptureStderr, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, get_torch_dist_unique_port, require_apex, require_bitsandbytes, require_fairscale, require_torch, require_torch_gpu, require_torch_multi_gpu, require_torch_non_multi_gpu, slow, ) from transformers.trainer_callback import TrainerState from transformers.trainer_utils import set_seed SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.abspath(os.path.dirname(__file__)) with ExtendSysPath(F'{bindir}/../../examples/pytorch/translation'): from run_translation import main # noqa set_seed(42) SCREAMING_SNAKE_CASE__ : Any = "sshleifer/student_marian_en_ro_6_1" SCREAMING_SNAKE_CASE__ : Tuple = "sshleifer/tiny-mbart" @require_torch class lowerCAmelCase__ ( __lowercase ): def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple=False , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Optional[int]=True , ) -> Optional[int]: __lowerCamelCase = self.run_trainer( eval_steps=1 , max_len=12 , model_name=SCREAMING_SNAKE_CASE__ , num_train_epochs=1 , distributed=SCREAMING_SNAKE_CASE__ , extra_args_str=SCREAMING_SNAKE_CASE__ , predict_with_generate=SCREAMING_SNAKE_CASE__ , do_train=SCREAMING_SNAKE_CASE__ , do_eval=SCREAMING_SNAKE_CASE__ , do_predict=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = TrainerState.load_from_json(os.path.join(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history if not do_eval: return __lowerCamelCase = [log for log in logs if '''eval_loss''' in log.keys()] __lowerCamelCase = eval_metrics[0] if predict_with_generate: assert "eval_bleu" in first_step_stats __lowerCamelCase = eval_metrics[-1] assert isinstance(last_step_stats['''eval_bleu'''] , SCREAMING_SNAKE_CASE__ ) assert not math.isnan(float(last_step_stats['''eval_loss'''] ) ), "eval_loss must not be `nan`" @require_torch_non_multi_gpu def __A ( self : Optional[int] ) -> int: self.run_seqaseq_quick() @require_torch_multi_gpu def __A ( self : int ) -> List[str]: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ ) @require_torch_multi_gpu def __A ( self : Optional[Any] ) -> Tuple: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Dict ) -> Tuple: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp simple''' ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Optional[int] ) -> List[str]: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp simple --fp16''' ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Tuple ) -> Any: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp zero_dp_2''' , predict_with_generate=SCREAMING_SNAKE_CASE__ ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Dict ) -> Tuple: self.run_seqaseq_quick( distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp zero_dp_2 --fp16''' , predict_with_generate=SCREAMING_SNAKE_CASE__ ) @require_apex @require_torch_gpu def __A ( self : Union[str, Any] ) -> List[str]: # XXX: apex breaks the trainer if it's run twice e.g. run_seq2seq.main() from the same # program and it breaks other tests that run from the same pytest worker, therefore until this is # sorted out it must be run only in an external program, that is distributed=True in this # test and only under one or more gpus - if we want cpu will need to make a special test # # specifically to the problem traced it to self.optimizer.step() - if it's run 2nd time via # 2nd main() call it botches the future eval. # self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--fp16 --fp16_backend=apex''' ) # test 2nd time - was getting eval_loss': nan' # to reproduce the problem set distributed=False self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--fp16 --fp16_backend=apex''' ) @parameterized.expand(['''base''', '''low''', '''high''', '''mixed'''] ) @require_torch_multi_gpu def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[str] ) -> Optional[Any]: # as each sub-test is slow-ish split into multiple sub-tests to avoid CI timeout __lowerCamelCase = { # test with the default log_level - should be info and thus log info once '''base''': {'''extra_args_str''': '''''', '''n_matches''': 1}, # test with low log_level and log_level_replica - should be noisy on all processes # now the info string should appear twice on 2 processes '''low''': {'''extra_args_str''': '''--log_level debug --log_level_replica debug''', '''n_matches''': 2}, # test with high log_level and low log_level_replica # now the info string should appear once only on the replica '''high''': {'''extra_args_str''': '''--log_level error --log_level_replica debug''', '''n_matches''': 1}, # test with high log_level and log_level_replica - should be quiet on all processes '''mixed''': {'''extra_args_str''': '''--log_level error --log_level_replica error''', '''n_matches''': 0}, } __lowerCamelCase = experiments[experiment_id] __lowerCamelCase = {'''distributed''': True, '''predict_with_generate''': False, '''do_eval''': False, '''do_predict''': False} __lowerCamelCase = '''Running training''' with CaptureStderr() as cl: self.run_seqaseq_quick(**SCREAMING_SNAKE_CASE__ , extra_args_str=data['''extra_args_str'''] ) __lowerCamelCase = len(re.findall(SCREAMING_SNAKE_CASE__ , cl.err ) ) self.assertEqual(SCREAMING_SNAKE_CASE__ , data['''n_matches'''] ) @slow def __A ( self : Any ) -> Optional[Any]: __lowerCamelCase = self.run_trainer( eval_steps=2 , max_len=1_28 , model_name=SCREAMING_SNAKE_CASE__ , learning_rate=3e-4 , num_train_epochs=10 , distributed=SCREAMING_SNAKE_CASE__ , ) # Check metrics __lowerCamelCase = TrainerState.load_from_json(os.path.join(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history __lowerCamelCase = [log for log in logs if '''eval_loss''' in log.keys()] __lowerCamelCase = eval_metrics[0] __lowerCamelCase = eval_metrics[-1] assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing" assert isinstance(last_step_stats['''eval_bleu'''] , SCREAMING_SNAKE_CASE__ ) # test if do_predict saves generations and metrics __lowerCamelCase = os.listdir(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = {os.path.basename(SCREAMING_SNAKE_CASE__ ) for p in contents} assert "generated_predictions.txt" in contents assert "predict_results.json" in contents @slow @require_bitsandbytes def __A ( self : Optional[int] ) -> str: from transformers.training_args import OptimizerNames def train_and_return_metrics(SCREAMING_SNAKE_CASE__ : str ) -> Tuple[int, float]: __lowerCamelCase = '''--skip_memory_metrics 0''' __lowerCamelCase = self.run_trainer( max_len=1_28 , model_name=SCREAMING_SNAKE_CASE__ , learning_rate=3e-4 , num_train_epochs=1 , optim=SCREAMING_SNAKE_CASE__ , distributed=SCREAMING_SNAKE_CASE__ , extra_args_str=SCREAMING_SNAKE_CASE__ , do_eval=SCREAMING_SNAKE_CASE__ , do_predict=SCREAMING_SNAKE_CASE__ , n_gpus_to_use=1 , ) # Check metrics __lowerCamelCase = TrainerState.load_from_json(Path(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history __lowerCamelCase = int(logs[0]['''train_mem_gpu_peaked_delta'''] / 2**20 ) __lowerCamelCase = int(logs[0]['''train_mem_gpu_alloc_delta'''] / 2**20 ) __lowerCamelCase = logs[0]['''train_loss'''] return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = train_and_return_metrics(OptimizerNames.ADAMW_BNB.value ) __lowerCamelCase = gpu_alloc_mem_orig - gpu_alloc_mem_bnb __lowerCamelCase = gpu_peak_mem_orig + gpu_alloc_mem_orig __lowerCamelCase = gpu_peak_mem_bnb + gpu_alloc_mem_bnb __lowerCamelCase = gpu_total_mem_orig - gpu_total_mem_bnb # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized # in 2 bytes and the diff in optim memory usage is derived as so: # # - normal 25*8=~200MB (8 bytes per param) # - bnb 25*2= ~50MB (2 bytes per param) # # Thus we should expect ~150MB total memory saved. # # Peak memory should be the same - the total should be different by about that same margin # # After leaving a small margin to accommodate for differences between gpus let's check # that we have at least 120MB in savings __lowerCamelCase = 1_20 # uncomment the following if this test starts failing - requires py38 for a new print feature # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB") # print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB") # print(f"{gpu_alloc_mem_diff=}MB") # print(f"{gpu_peak_mem_diff=}MB") # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB") # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB") self.assertGreater( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got''' f''' a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and''' f''' gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB''' , ) self.assertGreater( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''should use ~150MB less total gpu memory with BNB, compared to without it for this model but got''' f''' a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and''' f''' gpu_total_mem_bnb={gpu_total_mem_bnb}MB''' , ) self.assertEqual( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , f'''loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}''' ) def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float = 3e-3 , SCREAMING_SNAKE_CASE__ : str = "adafactor" , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : int = None , ) -> List[Any]: __lowerCamelCase = self.test_file_dir / '''../fixtures/tests_samples/wmt_en_ro''' __lowerCamelCase = self.get_auto_remove_tmp_dir() __lowerCamelCase = f''' --model_name_or_path {model_name} --train_file {data_dir}/train.json --validation_file {data_dir}/val.json --test_file {data_dir}/test.json --output_dir {output_dir} --overwrite_output_dir --max_train_samples 8 --max_source_length {max_len} --max_target_length {max_len} --do_train --num_train_epochs {str(SCREAMING_SNAKE_CASE__ )} --per_device_train_batch_size 4 --learning_rate {learning_rate} --warmup_steps 8 --logging_steps 0 --logging_strategy no --save_steps {str(SCREAMING_SNAKE_CASE__ )} --group_by_length --label_smoothing_factor 0.1 --target_lang ro_RO --source_lang en_XX '''.split() __lowerCamelCase = f''' --do_eval --per_device_eval_batch_size 4 --max_eval_samples 8 --val_max_target_length {max_len} --evaluation_strategy steps --eval_steps {str(SCREAMING_SNAKE_CASE__ )} '''.split() __lowerCamelCase = ''' --do_predict '''.split() __lowerCamelCase = [] if do_train: args += args_train if do_eval: args += args_eval if do_predict: args += args_predict if predict_with_generate: args += "--predict_with_generate".split() if do_train: if optim == "adafactor": args += "--adafactor".split() else: args += f'''--optim {optim}'''.split() if extra_args_str is not None: args += extra_args_str.split() if distributed: if n_gpus_to_use is None: __lowerCamelCase = get_gpu_count() __lowerCamelCase = get_torch_dist_unique_port() __lowerCamelCase = f''' -m torch.distributed.run --nproc_per_node={n_gpus_to_use} --master_port={master_port} {self.examples_dir_str}/pytorch/translation/run_translation.py '''.split() __lowerCamelCase = [sys.executable] + distributed_args + args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(SCREAMING_SNAKE_CASE__ , env=self.get_env() ) else: __lowerCamelCase = ['''run_translation.py'''] + args with patch.object(SCREAMING_SNAKE_CASE__ , '''argv''' , SCREAMING_SNAKE_CASE__ ): main() return output_dir
270
0
'''simple docstring''' import unittest from transformers import SPIECE_UNDERLINE, ReformerTokenizer, ReformerTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase : str =get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece @require_tokenizers class a_ ( __lowercase , unittest.TestCase ): __A = ReformerTokenizer __A = ReformerTokenizerFast __A = True __A = False __A = True def lowercase__ ( self : Dict ): """simple docstring""" super().setUp() lowercase_ :Optional[int] = ReformerTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) tokenizer.save_pretrained(self.tmpdirname ) def lowercase__ ( self : Any ): """simple docstring""" lowercase_ :Any = "<s>" lowercase_ :List[Any] = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def lowercase__ ( self : List[str] ): """simple docstring""" lowercase_ :str = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "j" ) self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , 1_000 ) def lowercase__ ( self : Tuple ): """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1_000 ) def lowercase__ ( self : List[str] ): """simple docstring""" if not self.test_rust_tokenizer: return lowercase_ :Optional[Any] = self.get_tokenizer() lowercase_ :Dict = self.get_rust_tokenizer() lowercase_ :int = "I was born in 92000, and this is falsé." lowercase_ :Dict = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) lowercase_ :Any = rust_tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowercase_ :Any = tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) lowercase_ :List[str] = rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) lowercase_ :int = self.get_rust_tokenizer() lowercase_ :Any = tokenizer.encode(SCREAMING_SNAKE_CASE__ ) lowercase_ :Optional[int] = rust_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def lowercase__ ( self : Union[str, Any] , lowercase : Optional[Any]=15 ): """simple docstring""" for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): lowercase_ :Any = self.rust_tokenizer_class.from_pretrained(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # Simple input lowercase_ :Dict = "This is a simple input" lowercase_ :Union[str, Any] = ["This is a simple input 1", "This is a simple input 2"] lowercase_ :List[Any] = ("This is a simple input", "This is a pair") lowercase_ :str = [ ("This is a simple input 1", "This is a simple input 2"), ("This is a simple pair 1", "This is a simple pair 2"), ] # Simple input tests self.assertRaises(SCREAMING_SNAKE_CASE__ , tokenizer_r.encode , SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , padding="max_length" ) # Simple input self.assertRaises(SCREAMING_SNAKE_CASE__ , tokenizer_r.encode_plus , SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , padding="max_length" ) # Simple input self.assertRaises( SCREAMING_SNAKE_CASE__ , tokenizer_r.batch_encode_plus , SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , padding="max_length" , ) # Pair input self.assertRaises(SCREAMING_SNAKE_CASE__ , tokenizer_r.encode , SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , padding="max_length" ) # Pair input self.assertRaises(SCREAMING_SNAKE_CASE__ , tokenizer_r.encode_plus , SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , padding="max_length" ) # Pair input self.assertRaises( SCREAMING_SNAKE_CASE__ , tokenizer_r.batch_encode_plus , SCREAMING_SNAKE_CASE__ , max_length=SCREAMING_SNAKE_CASE__ , padding="max_length" , ) def lowercase__ ( self : Optional[Any] ): """simple docstring""" pass def lowercase__ ( self : int ): """simple docstring""" lowercase_ :List[str] = ReformerTokenizer(SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ ) lowercase_ :Any = tokenizer.tokenize("This is a test" ) self.assertListEqual(SCREAMING_SNAKE_CASE__ , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) , [285, 46, 10, 170, 382] , ) lowercase_ :Union[str, Any] = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) lowercase_ :Optional[Any] = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) lowercase_ :str = tokenizer.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ) self.assertListEqual( SCREAMING_SNAKE_CASE__ , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) @cached_property def lowercase__ ( self : List[Any] ): """simple docstring""" return ReformerTokenizer.from_pretrained("google/reformer-crime-and-punishment" ) @slow def lowercase__ ( self : str ): """simple docstring""" lowercase_ :Union[str, Any] = "Hello World!" lowercase_ :List[str] = [126, 32, 262, 152, 38, 72, 287] self.assertListEqual(SCREAMING_SNAKE_CASE__ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) @slow def lowercase__ ( self : Dict ): """simple docstring""" lowercase_ :List[Any] = ( "This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) \" [ ] ! : - . Also we will" " add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth" ) lowercase_ :Optional[int] = [ 108, 265, 24, 111, 4, 258, 156, 35, 28, 275, 3, 259, 297, 260, 84, 4, 35, 110, 44, 8, 259, 91, 268, 21, 11, 209, 274, 109, 266, 277, 117, 86, 93, 315, 258, 278, 258, 277, 258, 0, 258, 288, 258, 319, 258, 0, 258, 0, 258, 0, 258, 0, 258, 287, 258, 315, 258, 289, 258, 278, 99, 269, 266, 262, 8, 259, 241, 4, 217, 230, 268, 266, 55, 168, 106, 75, 193, 266, 223, 27, 49, 26, 282, 25, 264, 299, 19, 26, 0, 258, 277, 117, 86, 93, 176, 183, 270, 11, 262, 42, 61, 265, ] self.assertListEqual(SCREAMING_SNAKE_CASE__ , self.big_tokenizer.encode(SCREAMING_SNAKE_CASE__ ) ) @require_torch @slow def lowercase__ ( self : Dict ): """simple docstring""" import torch from transformers import ReformerConfig, ReformerModel # Build sequence lowercase_ :Optional[int] = list(self.big_tokenizer.get_vocab().keys() )[:10] lowercase_ :Any = " ".join(SCREAMING_SNAKE_CASE__ ) lowercase_ :Any = self.big_tokenizer.encode_plus(SCREAMING_SNAKE_CASE__ , return_tensors="pt" ) lowercase_ :List[str] = self.big_tokenizer.batch_encode_plus([sequence, sequence] , return_tensors="pt" ) lowercase_ :List[Any] = ReformerConfig() # The input gets padded during training so adjust the axial position encodings from the pretrained model value of (512, 1024) lowercase_ :Dict = encoded_sequence["input_ids"].shape lowercase_ :Optional[int] = ReformerModel(SCREAMING_SNAKE_CASE__ ) # Reformer has config.vocab_size == tokenizer.vocab_size == len(tokenizer) - 1 = 320; len(tokenizer) is 321 (including a pad token with id 320) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**SCREAMING_SNAKE_CASE__ ) model(**SCREAMING_SNAKE_CASE__ ) @slow def lowercase__ ( self : int ): """simple docstring""" lowercase_ :Tuple = {"input_ids": [[108, 265, 24, 111, 4, 258, 156, 7, 51, 279, 58, 7, 76, 25, 69, 278], [140, 243, 264, 134, 17, 267, 77, 263, 22, 262, 297, 258, 304, 177, 279, 266, 14, 89, 13, 35, 261, 299, 272, 137, 275, 278]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # This tokenizer does not know some characters like ")". # That is the reason why we use very simple texts here. # Also see https://github.com/huggingface/transformers/pull/11737#issuecomment-850769064 lowercase_ :List[Any] = [ "This is a very simple sentence.", "The quick brown fox jumps over the lazy dog.", ] self.tokenizer_integration_test_util( expected_encoding=SCREAMING_SNAKE_CASE__ , model_name="google/reformer-crime-and-punishment" , revision="0e6c3decb8211d49bf881013425dc8b0448b3f5a" , padding=SCREAMING_SNAKE_CASE__ , sequences=SCREAMING_SNAKE_CASE__ , )
223
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING SCREAMING_SNAKE_CASE__ : Dict = { "facebook/mask2former-swin-small-coco-instance": ( "https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json" ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) class lowerCAmelCase__ ( __lowercase ): a__ : Any = """mask2former""" a__ : Dict = ["""swin"""] a__ : Any = {"""hidden_size""": """hidden_dim"""} def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Optional[Dict] = None , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 10_24 , SCREAMING_SNAKE_CASE__ : str = "relu" , SCREAMING_SNAKE_CASE__ : int = 6 , SCREAMING_SNAKE_CASE__ : int = 10 , SCREAMING_SNAKE_CASE__ : int = 8 , SCREAMING_SNAKE_CASE__ : float = 0.0 , SCREAMING_SNAKE_CASE__ : int = 20_48 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : int = 4 , SCREAMING_SNAKE_CASE__ : int = 2_55 , SCREAMING_SNAKE_CASE__ : int = 1_00 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 2.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : int = 1_25_44 , SCREAMING_SNAKE_CASE__ : float = 3.0 , SCREAMING_SNAKE_CASE__ : float = 0.75 , SCREAMING_SNAKE_CASE__ : float = 0.02 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 16, 32] , SCREAMING_SNAKE_CASE__ : bool = None , **SCREAMING_SNAKE_CASE__ : Tuple , ) -> str: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.''' ) __lowerCamelCase = CONFIG_MAPPING['''swin''']( image_size=2_24 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=SCREAMING_SNAKE_CASE__ , out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] , ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = backbone_config.pop('''model_type''' ) __lowerCamelCase = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase = config_class.from_dict(SCREAMING_SNAKE_CASE__ ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( f'''Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. ''' f'''Supported model types: {','.join(self.backbones_supported )}''' ) __lowerCamelCase = backbone_config __lowerCamelCase = feature_size __lowerCamelCase = mask_feature_size __lowerCamelCase = hidden_dim __lowerCamelCase = encoder_feedforward_dim __lowerCamelCase = activation_function __lowerCamelCase = encoder_layers __lowerCamelCase = decoder_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = dropout __lowerCamelCase = dim_feedforward __lowerCamelCase = pre_norm __lowerCamelCase = enforce_input_projection __lowerCamelCase = common_stride __lowerCamelCase = ignore_value __lowerCamelCase = num_queries __lowerCamelCase = no_object_weight __lowerCamelCase = class_weight __lowerCamelCase = mask_weight __lowerCamelCase = dice_weight __lowerCamelCase = train_num_points __lowerCamelCase = oversample_ratio __lowerCamelCase = importance_sample_ratio __lowerCamelCase = init_std __lowerCamelCase = init_xavier_std __lowerCamelCase = use_auxiliary_loss __lowerCamelCase = feature_strides __lowerCamelCase = output_auxiliary_logits __lowerCamelCase = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__ ) @classmethod def __A ( cls : Any , SCREAMING_SNAKE_CASE__ : PretrainedConfig , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: return cls( backbone_config=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def __A ( self : Any ) -> Dict[str, any]: __lowerCamelCase = copy.deepcopy(self.__dict__ ) __lowerCamelCase = self.backbone_config.to_dict() __lowerCamelCase = self.__class__.model_type return output
270
0
'''simple docstring''' from __future__ import annotations def UpperCamelCase ( _lowerCamelCase : list[int] ): if not nums: return 0 A__ = nums[0] A__ = 0 for num in nums[1:]: A__, A__ = ( max_excluding + num, max(__lowerCAmelCase , __lowerCAmelCase ), ) return max(__lowerCAmelCase , __lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
237
import os def __magic_name__ ( ) -> str: __lowerCamelCase = os.path.join(os.path.dirname(__lowerCAmelCase ) , '''num.txt''' ) with open(__lowerCAmelCase ) as file_hand: return str(sum(int(__lowerCAmelCase ) for line in file_hand ) )[:10] if __name__ == "__main__": print(solution())
270
0
from ...utils import ( OptionalDependencyNotAvailable, is_flax_available, is_torch_available, is_transformers_available, ) try: if not (is_transformers_available() and is_torch_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .multicontrolnet import MultiControlNetModel from .pipeline_controlnet import StableDiffusionControlNetPipeline from .pipeline_controlnet_imgaimg import StableDiffusionControlNetImgaImgPipeline from .pipeline_controlnet_inpaint import StableDiffusionControlNetInpaintPipeline if is_transformers_available() and is_flax_available(): from .pipeline_flax_controlnet import FlaxStableDiffusionControlNetPipeline
68
import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available SCREAMING_SNAKE_CASE__ : Optional[int] = logging.getLogger(__name__) @dataclass class lowerCAmelCase__ : a__ : str a__ : List[str] a__ : Optional[List[str]] @dataclass class lowerCAmelCase__ : a__ : List[int] a__ : List[int] a__ : Optional[List[int]] = None a__ : Optional[List[int]] = None class lowerCAmelCase__ ( __lowercase ): a__ : Optional[Any] = """train""" a__ : Optional[int] = """dev""" a__ : Dict = """test""" class lowerCAmelCase__ : @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[Split, str] ) -> List[InputExample]: raise NotImplementedError @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : str ) -> List[str]: raise NotImplementedError @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : List[InputExample] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : List[str]="[CLS]" , SCREAMING_SNAKE_CASE__ : Tuple=1 , SCREAMING_SNAKE_CASE__ : str="[SEP]" , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False , SCREAMING_SNAKE_CASE__ : Tuple=0 , SCREAMING_SNAKE_CASE__ : int=0 , SCREAMING_SNAKE_CASE__ : str=-1_00 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE__ : List[Any]=True , ) -> List[InputFeatures]: __lowerCamelCase = {label: i for i, label in enumerate(SCREAMING_SNAKE_CASE__ )} __lowerCamelCase = [] for ex_index, example in enumerate(SCREAMING_SNAKE_CASE__ ): if ex_index % 1_00_00 == 0: logger.info('''Writing example %d of %d''' , SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = [] __lowerCamelCase = [] for word, label in zip(example.words , example.labels ): __lowerCamelCase = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(SCREAMING_SNAKE_CASE__ ) > 0: tokens.extend(SCREAMING_SNAKE_CASE__ ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(SCREAMING_SNAKE_CASE__ ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. __lowerCamelCase = tokenizer.num_special_tokens_to_add() if len(SCREAMING_SNAKE_CASE__ ) > max_seq_length - special_tokens_count: __lowerCamelCase = tokens[: (max_seq_length - special_tokens_count)] __lowerCamelCase = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] __lowerCamelCase = [sequence_a_segment_id] * len(SCREAMING_SNAKE_CASE__ ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: __lowerCamelCase = [cls_token] + tokens __lowerCamelCase = [pad_token_label_id] + label_ids __lowerCamelCase = [cls_token_segment_id] + segment_ids __lowerCamelCase = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. __lowerCamelCase = [1 if mask_padding_with_zero else 0] * len(SCREAMING_SNAKE_CASE__ ) # Zero-pad up to the sequence length. __lowerCamelCase = max_seq_length - len(SCREAMING_SNAKE_CASE__ ) if pad_on_left: __lowerCamelCase = ([pad_token] * padding_length) + input_ids __lowerCamelCase = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask __lowerCamelCase = ([pad_token_segment_id] * padding_length) + segment_ids __lowerCamelCase = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length if ex_index < 5: logger.info('''*** Example ***''' ) logger.info('''guid: %s''' , example.guid ) logger.info('''tokens: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in tokens] ) ) logger.info('''input_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in input_ids] ) ) logger.info('''input_mask: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in input_mask] ) ) logger.info('''segment_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in segment_ids] ) ) logger.info('''label_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: __lowerCamelCase = None features.append( InputFeatures( input_ids=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , label_ids=SCREAMING_SNAKE_CASE__ ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class lowerCAmelCase__ ( __lowercase ): a__ : List[InputFeatures] a__ : int = nn.CrossEntropyLoss().ignore_index def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : TokenClassificationTask , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False , SCREAMING_SNAKE_CASE__ : Split = Split.train , ) -> Union[str, Any]: # Load data features from cache or dataset file __lowerCamelCase = os.path.join( SCREAMING_SNAKE_CASE__ , '''cached_{}_{}_{}'''.format(mode.value , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE__ ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. __lowerCamelCase = cached_features_file + '''.lock''' with FileLock(SCREAMING_SNAKE_CASE__ ): if os.path.exists(SCREAMING_SNAKE_CASE__ ) and not overwrite_cache: logger.info(f'''Loading features from cached file {cached_features_file}''' ) __lowerCamelCase = torch.load(SCREAMING_SNAKE_CASE__ ) else: logger.info(f'''Creating features from dataset file at {data_dir}''' ) __lowerCamelCase = token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # TODO clean up all this to leverage built-in features of tokenizers __lowerCamelCase = token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f'''Saving features into cached file {cached_features_file}''' ) torch.save(self.features , SCREAMING_SNAKE_CASE__ ) def __len__( self : Dict ) -> str: return len(self.features ) def __getitem__( self : Any , SCREAMING_SNAKE_CASE__ : Dict ) -> InputFeatures: return self.features[i] if is_tf_available(): import tensorflow as tf class lowerCAmelCase__ : a__ : List[InputFeatures] a__ : int = -100 def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : TokenClassificationTask , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Split = Split.train , ) -> List[Any]: __lowerCamelCase = token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # TODO clean up all this to leverage built-in features of tokenizers __lowerCamelCase = token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: __lowerCamelCase = tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa}, tf.intaa) , ( {'''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: __lowerCamelCase = tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa}, tf.intaa) , ( { '''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] ), '''token_type_ids''': tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __A ( self : Union[str, Any] ) -> Union[str, Any]: __lowerCamelCase = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self : List[Any] ) -> Any: return len(self.features ) def __getitem__( self : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> InputFeatures: return self.features[i]
270
0
"""simple docstring""" from abc import ABC, abstractmethod from argparse import ArgumentParser class __lowerCamelCase ( __lowercase ): '''simple docstring''' @staticmethod @abstractmethod def _UpperCAmelCase ( __UpperCAmelCase ) -> str: raise NotImplementedError() @abstractmethod def _UpperCAmelCase ( self ) -> Union[str, Any]: raise NotImplementedError()
320
from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class lowerCAmelCase__ ( __lowercase ): def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : NestedDataStructureLike[PathLike] , SCREAMING_SNAKE_CASE__ : Optional[NamedSplit] = None , SCREAMING_SNAKE_CASE__ : Optional[Features] = None , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[int] = None , **SCREAMING_SNAKE_CASE__ : str , ) -> Union[str, Any]: super().__init__( SCREAMING_SNAKE_CASE__ , split=SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ , keep_in_memory=SCREAMING_SNAKE_CASE__ , streaming=SCREAMING_SNAKE_CASE__ , num_proc=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = path_or_paths if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else {self.split: path_or_paths} __lowerCamelCase = Text( cache_dir=SCREAMING_SNAKE_CASE__ , data_files=SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def __A ( self : int ) -> Dict: # Build iterable dataset if self.streaming: __lowerCamelCase = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None self.builder.download_and_prepare( download_config=SCREAMING_SNAKE_CASE__ , download_mode=SCREAMING_SNAKE_CASE__ , verification_mode=SCREAMING_SNAKE_CASE__ , base_path=SCREAMING_SNAKE_CASE__ , num_proc=self.num_proc , ) __lowerCamelCase = self.builder.as_dataset( split=self.split , verification_mode=SCREAMING_SNAKE_CASE__ , in_memory=self.keep_in_memory ) return dataset
270
0
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 SPIECE_UNDERLINE, logging A : int = logging.get_logger(__name__) A : int = {"vocab_file": "spiece.model"} A : Union[str, Any] = { "vocab_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model", } } A : Optional[Any] = { "xlnet-base-cased": None, "xlnet-large-cased": None, } # Segments (not really needed) A : Optional[int] = 0 A : Optional[Any] = 1 A : Union[str, Any] = 2 A : Dict = 3 A : List[Any] = 4 class A ( __lowercase ): '''simple docstring''' A__ = VOCAB_FILES_NAMES A__ = PRETRAINED_VOCAB_FILES_MAP A__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ = """left""" def __init__(self : List[str] , _UpperCAmelCase : Dict , _UpperCAmelCase : Optional[int]=False , _UpperCAmelCase : Tuple=True , _UpperCAmelCase : str=False , _UpperCAmelCase : Dict="<s>" , _UpperCAmelCase : int="</s>" , _UpperCAmelCase : Dict="<unk>" , _UpperCAmelCase : int="<sep>" , _UpperCAmelCase : Tuple="<pad>" , _UpperCAmelCase : List[str]="<cls>" , _UpperCAmelCase : int="<mask>" , _UpperCAmelCase : Dict=["<eop>", "<eod>"] , _UpperCAmelCase : Optional[Dict[str, Any]] = None , **_UpperCAmelCase : Optional[int] , ) -> None: """simple docstring""" lowercase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else mask_token lowercase__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( do_lower_case=SCREAMING_SNAKE_CASE__ , remove_space=SCREAMING_SNAKE_CASE__ , keep_accents=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , additional_special_tokens=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) lowercase__ = 3 lowercase__ = do_lower_case lowercase__ = remove_space lowercase__ = keep_accents lowercase__ = vocab_file lowercase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def lowerCamelCase__ (self : Optional[int] ) -> Dict: """simple docstring""" return len(self.sp_model ) def lowerCamelCase__ (self : Tuple ) -> Tuple: """simple docstring""" lowercase__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__(self : int ) -> List[str]: """simple docstring""" lowercase__ = self.__dict__.copy() lowercase__ = None return state def __setstate__(self : str , _UpperCAmelCase : Tuple ) -> int: """simple docstring""" lowercase__ = d # for backward compatibility if not hasattr(self , """sp_model_kwargs""" ): lowercase__ = {} lowercase__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowerCamelCase__ (self : Tuple , _UpperCAmelCase : int ) -> List[Any]: """simple docstring""" if self.remove_space: lowercase__ = """ """.join(inputs.strip().split() ) else: lowercase__ = inputs lowercase__ = outputs.replace("""``""" , """\"""" ).replace("""\'\'""" , """\"""" ) if not self.keep_accents: lowercase__ = unicodedata.normalize("""NFKD""" , SCREAMING_SNAKE_CASE__ ) lowercase__ = """""".join([c for c in outputs if not unicodedata.combining(SCREAMING_SNAKE_CASE__ )] ) if self.do_lower_case: lowercase__ = outputs.lower() return outputs def lowerCamelCase__ (self : Optional[Any] , _UpperCAmelCase : str ) -> List[str]: """simple docstring""" lowercase__ = self.preprocess_text(SCREAMING_SNAKE_CASE__ ) lowercase__ = self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) lowercase__ = [] for piece in pieces: if len(SCREAMING_SNAKE_CASE__ ) > 1 and piece[-1] == str(""",""" ) and piece[-2].isdigit(): lowercase__ = self.sp_model.EncodeAsPieces(piece[:-1].replace(SCREAMING_SNAKE_CASE__ , """""" ) ) if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: if len(cur_pieces[0] ) == 1: lowercase__ = cur_pieces[1:] else: lowercase__ = cur_pieces[0][1:] cur_pieces.append(piece[-1] ) new_pieces.extend(SCREAMING_SNAKE_CASE__ ) else: new_pieces.append(SCREAMING_SNAKE_CASE__ ) return new_pieces def lowerCamelCase__ (self : Dict , _UpperCAmelCase : str ) -> Optional[int]: """simple docstring""" return self.sp_model.PieceToId(SCREAMING_SNAKE_CASE__ ) def lowerCamelCase__ (self : Union[str, Any] , _UpperCAmelCase : Tuple ) -> str: """simple docstring""" return self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) def lowerCamelCase__ (self : str , _UpperCAmelCase : str ) -> Union[str, Any]: """simple docstring""" lowercase__ = """""".join(SCREAMING_SNAKE_CASE__ ).replace(SCREAMING_SNAKE_CASE__ , """ """ ).strip() return out_string def lowerCamelCase__ (self : Optional[int] , _UpperCAmelCase : List[int] , _UpperCAmelCase : bool = False , _UpperCAmelCase : bool = None , _UpperCAmelCase : bool = True , **_UpperCAmelCase : List[Any] , ) -> str: """simple docstring""" lowercase__ = kwargs.pop("""use_source_tokenizer""" , SCREAMING_SNAKE_CASE__ ) lowercase__ = self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 lowercase__ = [] lowercase__ = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) lowercase__ = [] sub_texts.append(SCREAMING_SNAKE_CASE__ ) else: current_sub_text.append(SCREAMING_SNAKE_CASE__ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) # Mimic the behavior of the Rust tokenizer: # By default, there are no spaces between special tokens lowercase__ = """""".join(SCREAMING_SNAKE_CASE__ ) lowercase__ = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: lowercase__ = self.clean_up_tokenization(SCREAMING_SNAKE_CASE__ ) return clean_text else: return text def lowerCamelCase__ (self : Optional[int] , _UpperCAmelCase : List[int] , _UpperCAmelCase : Optional[List[int]] = None ) -> List[int]: """simple docstring""" lowercase__ = [self.sep_token_id] lowercase__ = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def lowerCamelCase__ (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=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is not None: return ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1, 1] return ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1, 1] def lowerCamelCase__ (self : Tuple , _UpperCAmelCase : List[int] , _UpperCAmelCase : Optional[List[int]] = None ) -> List[int]: """simple docstring""" lowercase__ = [self.sep_token_id] lowercase__ = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def lowerCamelCase__ (self : Optional[Any] , _UpperCAmelCase : str , _UpperCAmelCase : Optional[str] = None ) -> Tuple[str]: """simple docstring""" if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return lowercase__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , """wb""" ) as fi: lowercase__ = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,)
305
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(">=", "4.25.0")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
270
0
'''simple docstring''' UpperCAmelCase_ = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : bytes ): '''simple docstring''' if not isinstance(__lowerCAmelCase , __lowerCAmelCase ): UpperCAmelCase__ = F'''a bytes-like object is required, not \'{data.__class__.__name__}\'''' raise TypeError(__lowerCAmelCase ) UpperCAmelCase__ = """""".join(bin(__lowerCAmelCase )[2:].zfill(8 ) for byte in data ) UpperCAmelCase__ = len(__lowerCAmelCase ) % 6 != 0 if padding_needed: # The padding that will be added later UpperCAmelCase__ = b"""=""" * ((6 - len(__lowerCAmelCase ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(__lowerCAmelCase ) % 6) else: UpperCAmelCase__ = b"""""" # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] , 2 )] for index in range(0 , len(__lowerCAmelCase ) , 6 ) ).encode() + padding ) def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' if not isinstance(__lowerCAmelCase , __lowerCAmelCase ) and not isinstance(__lowerCAmelCase , __lowerCAmelCase ): UpperCAmelCase__ = ( """argument should be a bytes-like object or ASCII string, """ F'''not \'{encoded_data.__class__.__name__}\'''' ) raise TypeError(__lowerCAmelCase ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(__lowerCAmelCase , __lowerCAmelCase ): try: UpperCAmelCase__ = encoded_data.decode("""utf-8""" ) except UnicodeDecodeError: raise ValueError("""base64 encoded data should only contain ASCII characters""" ) UpperCAmelCase__ = encoded_data.count("""=""" ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(__lowerCAmelCase ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one UpperCAmelCase__ = encoded_data[:-padding] UpperCAmelCase__ = """""".join( bin(B64_CHARSET.index(__lowerCAmelCase ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: UpperCAmelCase__ = """""".join( bin(B64_CHARSET.index(__lowerCAmelCase ) )[2:].zfill(6 ) for char in encoded_data ) UpperCAmelCase__ = [ int(binary_stream[index : index + 8] , 2 ) for index in range(0 , len(__lowerCAmelCase ) , 8 ) ] return bytes(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
346
import sacrebleu as scb from packaging import version from sacrebleu import CHRF import datasets SCREAMING_SNAKE_CASE__ : Union[str, Any] = "\\n@inproceedings{popovic-2015-chrf,\n title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",\n month = sep,\n year = \"2015\",\n address = \"Lisbon, Portugal\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W15-3049\",\n doi = \"10.18653/v1/W15-3049\",\n pages = \"392--395\",\n}\n@inproceedings{popovic-2017-chrf,\n title = \"chr{F}++: words helping character n-grams\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Second Conference on Machine Translation\",\n month = sep,\n year = \"2017\",\n address = \"Copenhagen, Denmark\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W17-4770\",\n doi = \"10.18653/v1/W17-4770\",\n pages = \"612--618\",\n}\n@inproceedings{post-2018-call,\n title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n author = \"Post, Matt\",\n booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n month = oct,\n year = \"2018\",\n address = \"Belgium, Brussels\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W18-6319\",\n pages = \"186--191\",\n}\n" SCREAMING_SNAKE_CASE__ : int = "\\nChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,\nand ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation\nthat is already present in sacrebleu.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.\n" SCREAMING_SNAKE_CASE__ : Optional[Any] = "\nProduces ChrF(++) scores for hypotheses given reference translations.\n\nArgs:\n predictions (list of str): The predicted sentences.\n references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.\n char_order (int): Character n-gram order. Defaults to `6`.\n word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.\n beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.\n lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.\n whitespace (bool): If `True`, include whitespaces when extracting character n-grams.\n eps_smoothing (bool): If `True`, applies epsilon smoothing similar\n to reference chrF++.py, NLTK and Moses implementations. If `False`,\n it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.\n\nReturns:\n 'score' (float): The chrF (chrF++) score,\n 'char_order' (int): The character n-gram order,\n 'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,\n 'beta' (int): Determine the importance of recall w.r.t precision\n\nExamples:\n Example 1--a simple example of calculating chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction, references=reference)\n >>> print(results)\n {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}\n\n Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2)\n >>> print(results)\n {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}\n\n Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2,\n ... lowercase=True)\n >>> print(results)\n {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): def __A ( self : Dict ) -> Tuple: if version.parse(scb.__version__ ) < version.parse('''1.4.12''' ): raise ImportWarning( '''To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n''' '''You can install it with `pip install "sacrebleu>=1.4.12"`.''' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/mjpost/sacreBLEU#chrf--chrf''' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Sequence(datasets.Value('''string''' , id='''sequence''' ) , id='''references''' ), } ) , codebase_urls=['''https://github.com/mjpost/sacreBLEU#chrf--chrf'''] , reference_urls=[ '''https://github.com/m-popovic/chrF''', ] , ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int = CHRF.CHAR_ORDER , SCREAMING_SNAKE_CASE__ : int = CHRF.WORD_ORDER , SCREAMING_SNAKE_CASE__ : int = CHRF.BETA , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , ) -> Optional[Any]: __lowerCamelCase = len(references[0] ) if any(len(SCREAMING_SNAKE_CASE__ ) != references_per_prediction for refs in references ): raise ValueError('''Sacrebleu requires the same number of references for each prediction''' ) __lowerCamelCase = [[refs[i] for refs in references] for i in range(SCREAMING_SNAKE_CASE__ )] __lowerCamelCase = CHRF(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = sb_chrf.corpus_score(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return { "score": output.score, "char_order": output.char_order, "word_order": output.word_order, "beta": output.beta, }
270
0
def lowercase_ ( _A : Optional[Any] , _A : List[str] , _A : List[Any]=False ): """simple docstring""" if isinstance(__lowerCAmelCase , __lowerCAmelCase ) and isinstance(__lowerCAmelCase , __lowerCAmelCase ): lowerCamelCase__ : Dict = len(set_a.intersection(__lowerCAmelCase ) ) if alternative_union: lowerCamelCase__ : Dict = len(__lowerCAmelCase ) + len(__lowerCAmelCase ) else: lowerCamelCase__ : str = len(set_a.union(__lowerCAmelCase ) ) return intersection / union if isinstance(__lowerCAmelCase , (list, tuple) ) and isinstance(__lowerCAmelCase , (list, tuple) ): lowerCamelCase__ : Tuple = [element for element in set_a if element in set_b] if alternative_union: lowerCamelCase__ : Optional[int] = len(__lowerCAmelCase ) + len(__lowerCAmelCase ) return len(__lowerCAmelCase ) / union else: lowerCamelCase__ : Any = set_a + [element for element in set_b if element not in set_a] return len(__lowerCAmelCase ) / len(__lowerCAmelCase ) return len(__lowerCAmelCase ) / len(__lowerCAmelCase ) return None if __name__ == "__main__": A : Optional[int] = {"a", "b", "c", "d", "e"} A : List[Any] = {"c", "d", "e", "f", "h", "i"} print(jaccard_similarity(set_a, set_b))
184
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : List[Any] = { "configuration_resnet": ["RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "ResNetConfig", "ResNetOnnxConfig"] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "ResNetForImageClassification", "ResNetModel", "ResNetPreTrainedModel", "ResNetBackbone", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = [ "TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFResNetForImageClassification", "TFResNetModel", "TFResNetPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ "FlaxResNetForImageClassification", "FlaxResNetModel", "FlaxResNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_resnet import RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ResNetConfig, ResNetOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_resnet import ( RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, ResNetBackbone, ResNetForImageClassification, ResNetModel, ResNetPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_resnet import ( TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFResNetForImageClassification, TFResNetModel, TFResNetPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel, FlaxResNetPreTrainedModel else: import sys SCREAMING_SNAKE_CASE__ : Any = _LazyModule(__name__, globals()["__file__"], _import_structure)
270
0
"""simple docstring""" def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : int ) ->int: while b: lowerCamelCase__ , lowerCamelCase__ : Optional[Any] =b, a % b return a def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : int ) ->int: return a if b == 0 else euclidean_gcd_recursive(__lowerCAmelCase , a % b ) def lowerCAmelCase_ ( ) ->List[str]: print(f"""euclidean_gcd(3, 5) = {euclidean_gcd(3 , 5 )}""" ) print(f"""euclidean_gcd(5, 3) = {euclidean_gcd(5 , 3 )}""" ) print(f"""euclidean_gcd(1, 3) = {euclidean_gcd(1 , 3 )}""" ) print(f"""euclidean_gcd(3, 6) = {euclidean_gcd(3 , 6 )}""" ) print(f"""euclidean_gcd(6, 3) = {euclidean_gcd(6 , 3 )}""" ) print(f"""euclidean_gcd_recursive(3, 5) = {euclidean_gcd_recursive(3 , 5 )}""" ) print(f"""euclidean_gcd_recursive(5, 3) = {euclidean_gcd_recursive(5 , 3 )}""" ) print(f"""euclidean_gcd_recursive(1, 3) = {euclidean_gcd_recursive(1 , 3 )}""" ) print(f"""euclidean_gcd_recursive(3, 6) = {euclidean_gcd_recursive(3 , 6 )}""" ) print(f"""euclidean_gcd_recursive(6, 3) = {euclidean_gcd_recursive(6 , 3 )}""" ) if __name__ == "__main__": main()
126
import unittest import numpy as np import requests from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: SCREAMING_SNAKE_CASE__ : str = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any]=7 , SCREAMING_SNAKE_CASE__ : List[str]=3 , SCREAMING_SNAKE_CASE__ : Tuple=18 , SCREAMING_SNAKE_CASE__ : int=30 , SCREAMING_SNAKE_CASE__ : Any=4_00 , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , ) -> Union[str, Any]: __lowerCamelCase = size if size is not None else {'''height''': 20, '''width''': 20} __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = num_channels __lowerCamelCase = image_size __lowerCamelCase = min_resolution __lowerCamelCase = max_resolution __lowerCamelCase = size __lowerCamelCase = do_normalize __lowerCamelCase = do_convert_rgb __lowerCamelCase = [5_12, 10_24, 20_48, 40_96] __lowerCamelCase = patch_size if patch_size is not None else {'''height''': 16, '''width''': 16} def __A ( self : Union[str, Any] ) -> Union[str, Any]: return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def __A ( self : int ) -> Any: __lowerCamelCase = '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg''' __lowerCamelCase = Image.open(requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ ).raw ).convert('''RGB''' ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`.""" , ) @require_torch @require_vision class lowerCAmelCase__ ( __lowercase , unittest.TestCase ): a__ : Dict = PixaStructImageProcessor if is_vision_available() else None def __A ( self : Optional[Any] ) -> List[Any]: __lowerCamelCase = PixaStructImageProcessingTester(self ) @property def __A ( self : Optional[int] ) -> Optional[int]: return self.image_processor_tester.prepare_image_processor_dict() def __A ( self : Tuple ) -> Dict: __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_normalize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_convert_rgb''' ) ) def __A ( self : int ) -> str: __lowerCamelCase = self.image_processor_tester.prepare_dummy_image() __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) __lowerCamelCase = 20_48 __lowerCamelCase = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) ) def __A ( self : Union[str, Any] ) -> Dict: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : Dict ) -> str: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 __lowerCamelCase = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches __lowerCamelCase = '''Hello''' __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ , header_text=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ , header_text=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : List[str] ) -> Any: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : Tuple ) -> List[str]: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`.""" , ) @require_torch @require_vision class lowerCAmelCase__ ( __lowercase , unittest.TestCase ): a__ : Any = PixaStructImageProcessor if is_vision_available() else None def __A ( self : Union[str, Any] ) -> Optional[Any]: __lowerCamelCase = PixaStructImageProcessingTester(self , num_channels=4 ) __lowerCamelCase = 3 @property def __A ( self : List[Any] ) -> Optional[Any]: return self.image_processor_tester.prepare_image_processor_dict() def __A ( self : Union[str, Any] ) -> List[str]: __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_normalize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_convert_rgb''' ) ) def __A ( self : Optional[int] ) -> str: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
270
0
"""simple docstring""" import unittest from transformers import DebertaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( DebertaForMaskedLM, DebertaForQuestionAnswering, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaModel, ) from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST class __SCREAMING_SNAKE_CASE ( __lowercase ): '''simple docstring''' def __init__( self : Tuple, lowerCamelCase : List[str], lowerCamelCase : List[Any]=13, lowerCamelCase : int=7, lowerCamelCase : List[str]=True, lowerCamelCase : Optional[Any]=True, lowerCamelCase : Dict=True, lowerCamelCase : Any=True, lowerCamelCase : int=99, lowerCamelCase : List[Any]=32, lowerCamelCase : Any=5, lowerCamelCase : List[str]=4, lowerCamelCase : List[str]=37, lowerCamelCase : List[Any]="gelu", lowerCamelCase : Dict=0.1, lowerCamelCase : Any=0.1, lowerCamelCase : Dict=512, lowerCamelCase : Tuple=16, lowerCamelCase : int=2, lowerCamelCase : int=0.02, lowerCamelCase : Dict=False, lowerCamelCase : List[Any]=True, lowerCamelCase : List[str]="None", lowerCamelCase : Optional[int]=3, lowerCamelCase : Optional[int]=4, lowerCamelCase : Optional[int]=None, )-> Union[str, Any]: lowerCamelCase__ : Any =parent lowerCamelCase__ : Tuple =batch_size lowerCamelCase__ : str =seq_length lowerCamelCase__ : int =is_training lowerCamelCase__ : str =use_input_mask lowerCamelCase__ : Dict =use_token_type_ids lowerCamelCase__ : List[str] =use_labels lowerCamelCase__ : List[str] =vocab_size lowerCamelCase__ : Union[str, Any] =hidden_size lowerCamelCase__ : int =num_hidden_layers lowerCamelCase__ : int =num_attention_heads lowerCamelCase__ : Optional[Any] =intermediate_size lowerCamelCase__ : Any =hidden_act lowerCamelCase__ : List[Any] =hidden_dropout_prob lowerCamelCase__ : str =attention_probs_dropout_prob lowerCamelCase__ : Union[str, Any] =max_position_embeddings lowerCamelCase__ : List[Any] =type_vocab_size lowerCamelCase__ : Union[str, Any] =type_sequence_label_size lowerCamelCase__ : Dict =initializer_range lowerCamelCase__ : str =num_labels lowerCamelCase__ : Optional[Any] =num_choices lowerCamelCase__ : Dict =relative_attention lowerCamelCase__ : Optional[Any] =position_biased_input lowerCamelCase__ : Dict =pos_att_type lowerCamelCase__ : Optional[int] =scope def snake_case ( self : Any )-> str: lowerCamelCase__ : List[str] =ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) lowerCamelCase__ : Optional[Any] =None if self.use_input_mask: lowerCamelCase__ : List[Any] =ids_tensor([self.batch_size, self.seq_length], vocab_size=2 ) lowerCamelCase__ : str =None if self.use_token_type_ids: lowerCamelCase__ : Optional[int] =ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size ) lowerCamelCase__ : Optional[Any] =None lowerCamelCase__ : Any =None lowerCamelCase__ : Optional[Any] =None if self.use_labels: lowerCamelCase__ : Optional[Any] =ids_tensor([self.batch_size], self.type_sequence_label_size ) lowerCamelCase__ : str =ids_tensor([self.batch_size, self.seq_length], self.num_labels ) lowerCamelCase__ : str =ids_tensor([self.batch_size], self.num_choices ) lowerCamelCase__ : Union[str, Any] =self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def snake_case ( self : Any )-> List[str]: return DebertaConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, type_vocab_size=self.type_vocab_size, initializer_range=self.initializer_range, relative_attention=self.relative_attention, position_biased_input=self.position_biased_input, pos_att_type=self.pos_att_type, ) def snake_case ( self : Dict )-> Dict: lowerCamelCase__ : List[Any] =self.get_config() lowerCamelCase__ : Dict =300 return config def snake_case ( self : List[str], lowerCamelCase : List[Any] )-> Union[str, Any]: self.parent.assertListEqual(list(result.loss.size() ), [] ) def snake_case ( self : Optional[int], lowerCamelCase : Optional[int], lowerCamelCase : str, lowerCamelCase : int, lowerCamelCase : List[Any], lowerCamelCase : Optional[Any], lowerCamelCase : Union[str, Any], lowerCamelCase : Tuple )-> Optional[int]: lowerCamelCase__ : Any =DebertaModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCamelCase__ : int =model(SCREAMING_SNAKE_CASE__, attention_mask=SCREAMING_SNAKE_CASE__, token_type_ids=SCREAMING_SNAKE_CASE__ )[0] lowerCamelCase__ : Union[str, Any] =model(SCREAMING_SNAKE_CASE__, token_type_ids=SCREAMING_SNAKE_CASE__ )[0] lowerCamelCase__ : int =model(SCREAMING_SNAKE_CASE__ )[0] self.parent.assertListEqual(list(sequence_output.size() ), [self.batch_size, self.seq_length, self.hidden_size] ) def snake_case ( self : str, lowerCamelCase : List[Any], lowerCamelCase : Optional[int], lowerCamelCase : int, lowerCamelCase : Tuple, lowerCamelCase : Union[str, Any], lowerCamelCase : Dict, lowerCamelCase : List[str] )-> List[str]: lowerCamelCase__ : List[str] =DebertaForMaskedLM(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCamelCase__ : List[str] =model(SCREAMING_SNAKE_CASE__, attention_mask=SCREAMING_SNAKE_CASE__, token_type_ids=SCREAMING_SNAKE_CASE__, labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size) ) def snake_case ( self : Tuple, lowerCamelCase : Dict, lowerCamelCase : List[Any], lowerCamelCase : Tuple, lowerCamelCase : Optional[Any], lowerCamelCase : int, lowerCamelCase : Tuple, lowerCamelCase : Dict )-> List[str]: lowerCamelCase__ : str =self.num_labels lowerCamelCase__ : Tuple =DebertaForSequenceClassification(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCamelCase__ : Optional[Any] =model(SCREAMING_SNAKE_CASE__, attention_mask=SCREAMING_SNAKE_CASE__, token_type_ids=SCREAMING_SNAKE_CASE__, labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertListEqual(list(result.logits.size() ), [self.batch_size, self.num_labels] ) self.check_loss_output(SCREAMING_SNAKE_CASE__ ) def snake_case ( self : Optional[int], lowerCamelCase : Any, lowerCamelCase : Optional[int], lowerCamelCase : Any, lowerCamelCase : List[Any], lowerCamelCase : List[str], lowerCamelCase : int, lowerCamelCase : Optional[int] )-> Any: lowerCamelCase__ : Optional[int] =self.num_labels lowerCamelCase__ : str =DebertaForTokenClassification(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCamelCase__ : Optional[int] =model(SCREAMING_SNAKE_CASE__, attention_mask=SCREAMING_SNAKE_CASE__, token_type_ids=SCREAMING_SNAKE_CASE__, labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels) ) def snake_case ( self : int, lowerCamelCase : Tuple, lowerCamelCase : Optional[Any], lowerCamelCase : Optional[int], lowerCamelCase : str, lowerCamelCase : List[Any], lowerCamelCase : Any, lowerCamelCase : str )-> Any: lowerCamelCase__ : List[Any] =DebertaForQuestionAnswering(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() lowerCamelCase__ : Dict =model( SCREAMING_SNAKE_CASE__, attention_mask=SCREAMING_SNAKE_CASE__, token_type_ids=SCREAMING_SNAKE_CASE__, start_positions=SCREAMING_SNAKE_CASE__, end_positions=SCREAMING_SNAKE_CASE__, ) self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length) ) def snake_case ( self : str )-> str: lowerCamelCase__ : List[Any] =self.prepare_config_and_inputs() ( ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ( lowerCamelCase__ ) , ) : Optional[Any] =config_and_inputs lowerCamelCase__ : Tuple ={'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __SCREAMING_SNAKE_CASE ( __lowercase , __lowercase , unittest.TestCase ): '''simple docstring''' _a = ( ( DebertaModel, DebertaForMaskedLM, DebertaForSequenceClassification, DebertaForTokenClassification, DebertaForQuestionAnswering, ) if is_torch_available() else () ) _a = ( { """feature-extraction""": DebertaModel, """fill-mask""": DebertaForMaskedLM, """question-answering""": DebertaForQuestionAnswering, """text-classification""": DebertaForSequenceClassification, """token-classification""": DebertaForTokenClassification, """zero-shot""": DebertaForSequenceClassification, } if is_torch_available() else {} ) _a = True _a = False _a = False _a = False _a = False def snake_case ( self : List[str] )-> Tuple: lowerCamelCase__ : Optional[Any] =DebertaModelTester(self ) lowerCamelCase__ : str =ConfigTester(self, config_class=SCREAMING_SNAKE_CASE__, hidden_size=37 ) def snake_case ( self : Optional[int] )-> Any: self.config_tester.run_common_tests() def snake_case ( self : Optional[int] )-> Union[str, Any]: lowerCamelCase__ : Optional[int] =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_model(*SCREAMING_SNAKE_CASE__ ) def snake_case ( self : List[str] )-> Optional[Any]: lowerCamelCase__ : Tuple =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_sequence_classification(*SCREAMING_SNAKE_CASE__ ) def snake_case ( self : Any )-> List[Any]: lowerCamelCase__ : int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_masked_lm(*SCREAMING_SNAKE_CASE__ ) def snake_case ( self : List[Any] )-> Optional[Any]: lowerCamelCase__ : str =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_question_answering(*SCREAMING_SNAKE_CASE__ ) def snake_case ( self : Any )-> Dict: lowerCamelCase__ : int =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_deberta_for_token_classification(*SCREAMING_SNAKE_CASE__ ) @slow def snake_case ( self : Tuple )-> Optional[int]: for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCamelCase__ : Dict =DebertaModel.from_pretrained(SCREAMING_SNAKE_CASE__ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE__ ) @require_torch @require_sentencepiece @require_tokenizers class __SCREAMING_SNAKE_CASE ( unittest.TestCase ): '''simple docstring''' @unittest.skip(reason='''Model not available yet''' ) def snake_case ( self : Dict )-> List[str]: pass @slow def snake_case ( self : Optional[Any] )-> Optional[Any]: lowerCamelCase__ : Optional[int] =DebertaModel.from_pretrained('''microsoft/deberta-base''' ) lowerCamelCase__ : Union[str, Any] =torch.tensor([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]] ) lowerCamelCase__ : Union[str, Any] =torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): lowerCamelCase__ : Tuple =model(SCREAMING_SNAKE_CASE__, attention_mask=SCREAMING_SNAKE_CASE__ )[0] # compare the actual values for a slice. lowerCamelCase__ : Tuple =torch.tensor( [[[-0.5_986, -0.8_055, -0.8_462], [1.4_484, -0.9_348, -0.8_059], [0.3_123, 0.0_032, -1.4_131]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4], SCREAMING_SNAKE_CASE__, atol=1E-4 ), F'''{output[:, 1:4, 1:4]}''' )
238
import shutil import tempfile import unittest from unittest.mock import patch from transformers import ( DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, Trainer, TrainerCallback, TrainingArguments, is_torch_available, ) from transformers.testing_utils import require_torch if is_torch_available(): from transformers.trainer import DEFAULT_CALLBACKS from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel class lowerCAmelCase__ ( __lowercase ): def __init__( self : int ) -> Optional[int]: __lowerCamelCase = [] def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> Tuple: self.events.append('''on_init_end''' ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Any: self.events.append('''on_train_begin''' ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : int ) -> Any: self.events.append('''on_train_end''' ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: self.events.append('''on_epoch_begin''' ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Tuple ) -> Optional[Any]: self.events.append('''on_epoch_end''' ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: self.events.append('''on_step_begin''' ) def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: self.events.append('''on_step_end''' ) def __A ( self : int , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> Union[str, Any]: self.events.append('''on_evaluate''' ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : str ) -> str: self.events.append('''on_predict''' ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Tuple: self.events.append('''on_save''' ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : List[str] ) -> List[str]: self.events.append('''on_log''' ) def __A ( self : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: self.events.append('''on_prediction_step''' ) @require_torch class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Union[str, Any] ) -> Optional[Any]: __lowerCamelCase = tempfile.mkdtemp() def __A ( self : int ) -> List[str]: shutil.rmtree(self.output_dir ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any]=0 , SCREAMING_SNAKE_CASE__ : Any=0 , SCREAMING_SNAKE_CASE__ : List[str]=64 , SCREAMING_SNAKE_CASE__ : Optional[int]=64 , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Optional[int]=False , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Union[str, Any]: # disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure # its set to False since the tests later on depend on its value. __lowerCamelCase = RegressionDataset(length=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionDataset(length=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionModelConfig(a=SCREAMING_SNAKE_CASE__ , b=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionPreTrainedModel(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = TrainingArguments(self.output_dir , disable_tqdm=SCREAMING_SNAKE_CASE__ , report_to=[] , **SCREAMING_SNAKE_CASE__ ) return Trainer( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , train_dataset=SCREAMING_SNAKE_CASE__ , eval_dataset=SCREAMING_SNAKE_CASE__ , callbacks=SCREAMING_SNAKE_CASE__ , ) def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> Optional[int]: self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) ) # Order doesn't matter __lowerCamelCase = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : cb.__name__ if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cb.__class__.__name__ ) __lowerCamelCase = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : cb.__name__ if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cb.__class__.__name__ ) for cba, cba in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(SCREAMING_SNAKE_CASE__ , cba.__class__ ) elif not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(cba.__class__ , SCREAMING_SNAKE_CASE__ ) else: self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: __lowerCamelCase = ['''on_init_end''', '''on_train_begin'''] __lowerCamelCase = 0 __lowerCamelCase = len(trainer.get_eval_dataloader() ) __lowerCamelCase = ['''on_prediction_step'''] * len(trainer.get_eval_dataloader() ) + ['''on_log''', '''on_evaluate'''] for _ in range(trainer.state.num_train_epochs ): expected_events.append('''on_epoch_begin''' ) for _ in range(SCREAMING_SNAKE_CASE__ ): step += 1 expected_events += ["on_step_begin", "on_step_end"] if step % trainer.args.logging_steps == 0: expected_events.append('''on_log''' ) if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0: expected_events += evaluation_events.copy() if step % trainer.args.save_steps == 0: expected_events.append('''on_save''' ) expected_events.append('''on_epoch_end''' ) if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH: expected_events += evaluation_events.copy() expected_events += ["on_log", "on_train_end"] return expected_events def __A ( self : Union[str, Any] ) -> int: __lowerCamelCase = self.get_trainer() __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [ProgressCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # Callbacks passed at init are added to the default callbacks __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] ) expected_callbacks.append(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback __lowerCamelCase = self.get_trainer(disable_tqdm=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [PrinterCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) def __A ( self : List[Any] ) -> str: __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [ProgressCallback] __lowerCamelCase = self.get_trainer() # We can add, pop, or remove by class name trainer.remove_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.remove(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.pop_callback(SCREAMING_SNAKE_CASE__ ) self.assertEqual(cb.__class__ , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) trainer.add_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.insert(0 , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # We can also add, pop, or remove by instance __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.callback_handler.callbacks[0] trainer.remove_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.remove(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.callback_handler.callbacks[0] __lowerCamelCase = trainer.pop_callback(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) trainer.add_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.insert(0 , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] ) -> Any: import warnings # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested warnings.simplefilter(action='''ignore''' , category=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # Independent log/save/eval __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , logging_steps=5 ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , save_steps=5 ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , eval_steps=5 , evaluation_strategy='''steps''' ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , evaluation_strategy='''epoch''' ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # A bit of everything __lowerCamelCase = self.get_trainer( callbacks=[MyTestTrainerCallback] , logging_steps=3 , save_steps=10 , eval_steps=5 , evaluation_strategy='''steps''' , ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # warning should be emitted for duplicated callbacks with patch('''transformers.trainer_callback.logger.warning''' ) as warn_mock: __lowerCamelCase = self.get_trainer( callbacks=[MyTestTrainerCallback, MyTestTrainerCallback] , ) assert str(SCREAMING_SNAKE_CASE__ ) in warn_mock.call_args[0][0]
270
0
import argparse import math import traceback import dateutil.parser as date_parser import requests def lowerCamelCase__ ( _A ): '''simple docstring''' snake_case_ = {} snake_case_ = job["started_at"] snake_case_ = job["completed_at"] snake_case_ = date_parser.parse(__lowerCAmelCase ) snake_case_ = date_parser.parse(__lowerCAmelCase ) snake_case_ = round((end_datetime - start_datetime).total_seconds() / 60.0 ) snake_case_ = start snake_case_ = end snake_case_ = duration_in_min return job_info def lowerCamelCase__ ( _A , _A=None ): '''simple docstring''' snake_case_ = None if token is not None: snake_case_ = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"} snake_case_ = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100" snake_case_ = requests.get(__lowerCAmelCase , headers=__lowerCAmelCase ).json() snake_case_ = {} try: job_time.update({job["name"]: extract_time_from_single_job(__lowerCAmelCase ) for job in result["jobs"]} ) snake_case_ = math.ceil((result["total_count"] - 100) / 100 ) for i in range(__lowerCAmelCase ): snake_case_ = requests.get(url + f"&page={i + 2}" , headers=__lowerCAmelCase ).json() job_time.update({job["name"]: extract_time_from_single_job(__lowerCAmelCase ) for job in result["jobs"]} ) return job_time except Exception: print(f"Unknown error, could not fetch links:\n{traceback.format_exc()}" ) return {} if __name__ == "__main__": lowercase__ : int = argparse.ArgumentParser() # Required parameters parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.") lowercase__ : List[Any] = parser.parse_args() lowercase__ : List[str] = get_job_time(args.workflow_run_id) lowercase__ : List[Any] = dict(sorted(job_time.items(), key=lambda item: item[1]["duration"], reverse=True)) for k, v in job_time.items(): print(f'''{k}: {v['duration']}''')
187
import numpy as np from cva import destroyAllWindows, imread, imshow, waitKey class lowerCAmelCase__ : def __init__( self : Any , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> Dict: if dst_width < 0 or dst_height < 0: raise ValueError('''Destination width/height should be > 0''' ) __lowerCamelCase = img __lowerCamelCase = img.shape[1] __lowerCamelCase = img.shape[0] __lowerCamelCase = dst_width __lowerCamelCase = dst_height __lowerCamelCase = self.src_w / self.dst_w __lowerCamelCase = self.src_h / self.dst_h __lowerCamelCase = __lowerCamelCase = ( np.ones((self.dst_h, self.dst_w, 3) , np.uinta ) * 2_55 ) def __A ( self : List[Any] ) -> str: for i in range(self.dst_h ): for j in range(self.dst_w ): __lowerCamelCase = self.img[self.get_y(SCREAMING_SNAKE_CASE__ )][self.get_x(SCREAMING_SNAKE_CASE__ )] def __A ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> int: return int(self.ratio_x * x ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> int: return int(self.ratio_y * y ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = 800, 600 SCREAMING_SNAKE_CASE__ : int = imread("image_data/lena.jpg", 1) SCREAMING_SNAKE_CASE__ : Union[str, Any] = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( F'Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}', n.output ) waitKey(0) destroyAllWindows()
270
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available UpperCamelCase = { "configuration_gpt_neo": ["GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP", "GPTNeoConfig", "GPTNeoOnnxConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ "GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST", "GPTNeoForCausalLM", "GPTNeoForQuestionAnswering", "GPTNeoForSequenceClassification", "GPTNeoForTokenClassification", "GPTNeoModel", "GPTNeoPreTrainedModel", "load_tf_weights_in_gpt_neo", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCamelCase = [ "FlaxGPTNeoForCausalLM", "FlaxGPTNeoModel", "FlaxGPTNeoPreTrainedModel", ] if TYPE_CHECKING: from .configuration_gpt_neo import GPT_NEO_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoConfig, GPTNeoOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neo import ( GPT_NEO_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoForCausalLM, GPTNeoForQuestionAnswering, GPTNeoForSequenceClassification, GPTNeoForTokenClassification, GPTNeoModel, GPTNeoPreTrainedModel, load_tf_weights_in_gpt_neo, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_gpt_neo import FlaxGPTNeoForCausalLM, FlaxGPTNeoModel, FlaxGPTNeoPreTrainedModel else: import sys UpperCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
306
from queue import PriorityQueue from typing import Any import numpy as np def __magic_name__ ( __lowerCAmelCase : dict , __lowerCAmelCase : str , __lowerCAmelCase : set , __lowerCAmelCase : set , __lowerCAmelCase : dict , __lowerCAmelCase : dict , __lowerCAmelCase : PriorityQueue , __lowerCAmelCase : dict , __lowerCAmelCase : float | int , ) -> float | int: for nxt, d in graph[v]: if nxt in visited_forward: continue __lowerCamelCase = cst_fwd.get(__lowerCAmelCase , np.inf ) __lowerCamelCase = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) __lowerCamelCase = new_cost_f __lowerCamelCase = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: __lowerCamelCase = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def __magic_name__ ( __lowerCAmelCase : str , __lowerCAmelCase : str , __lowerCAmelCase : dict , __lowerCAmelCase : dict ) -> int: __lowerCamelCase = -1 __lowerCamelCase = set() __lowerCamelCase = set() __lowerCamelCase = {source: 0} __lowerCamelCase = {destination: 0} __lowerCamelCase = {source: None} __lowerCamelCase = {destination: None} __lowerCamelCase = PriorityQueue() __lowerCamelCase = PriorityQueue() __lowerCamelCase = np.inf queue_forward.put((0, source) ) queue_backward.put((0, destination) ) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): __lowerCamelCase , __lowerCamelCase = queue_forward.get() visited_forward.add(__lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = queue_backward.get() visited_backward.add(__lowerCAmelCase ) __lowerCamelCase = pass_and_relaxation( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) __lowerCamelCase = pass_and_relaxation( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: __lowerCamelCase = shortest_distance return shortest_path_distance SCREAMING_SNAKE_CASE__ : List[Any] = { "B": [["C", 1]], "C": [["D", 1]], "D": [["F", 1]], "E": [["B", 1], ["G", 2]], "F": [], "G": [["F", 1]], } SCREAMING_SNAKE_CASE__ : Optional[int] = { "B": [["E", 1]], "C": [["B", 1]], "D": [["C", 1]], "F": [["D", 1], ["G", 1]], "E": [[None, np.inf]], "G": [["E", 2]], } if __name__ == "__main__": import doctest doctest.testmod()
270
0
'''simple docstring''' from urllib.parse import quote import pytest from datasets.utils.hub import hf_hub_url @pytest.mark.parametrize("repo_id" ,["canonical_dataset_name", "org-name/dataset-name"] ) @pytest.mark.parametrize("path" ,["filename.csv", "filename with blanks.csv"] ) @pytest.mark.parametrize("revision" ,[None, "v2"] ) def UpperCAmelCase_ ( __lowerCamelCase : str ,__lowerCamelCase : str ,__lowerCamelCase : str ): lowercase_ :Union[str, Any] = hf_hub_url(repo_id=__lowerCAmelCase ,path=__lowerCAmelCase ,revision=__lowerCAmelCase ) assert url == F'https://huggingface.co/datasets/{repo_id}/resolve/{revision or "main"}/{quote(__lowerCAmelCase )}'
223
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ : List[Any] = TypeVar("T") def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (position - 1) // 2 def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (2 * position) + 1 def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (2 * position) + 2 class lowerCAmelCase__ ( Generic[T] ): def __init__( self : List[str] ) -> None: __lowerCamelCase = [] __lowerCamelCase = {} __lowerCamelCase = 0 def __len__( self : Optional[int] ) -> int: return self.elements def __repr__( self : Optional[int] ) -> str: return str(self.heap ) def __A ( self : Union[str, Any] ) -> bool: # Check if the priority queue is empty return self.elements == 0 def __A ( self : str , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Add an element with given priority to the queue self.heap.append((elem, weight) ) __lowerCamelCase = self.elements self.elements += 1 self._bubble_up(SCREAMING_SNAKE_CASE__ ) def __A ( self : Any ) -> T: # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) __lowerCamelCase , __lowerCamelCase = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __lowerCamelCase , __lowerCamelCase = self.heap[0] self._bubble_down(SCREAMING_SNAKE_CASE__ ) return elem def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Update the weight of the given key __lowerCamelCase = self.position_map[elem] __lowerCamelCase = (elem, weight) if position > 0: __lowerCamelCase = get_parent_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase = self.heap[parent_position] if parent_weight > weight: self._bubble_up(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Place a node at the proper position (upward movement) [to be used internally # only] __lowerCamelCase = self.position_map[elem] if curr_pos == 0: return None __lowerCamelCase = get_parent_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase = self.heap[curr_pos] __lowerCamelCase , __lowerCamelCase = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_up(SCREAMING_SNAKE_CASE__ ) return None def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Place a node at the proper position (downward movement) [to be used # internally only] __lowerCamelCase = self.position_map[elem] __lowerCamelCase , __lowerCamelCase = self.heap[curr_pos] __lowerCamelCase = get_child_left_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = get_child_right_position(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements and child_right_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_left_position] __lowerCamelCase , __lowerCamelCase = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: return None if child_right_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) return None def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: # Swap the nodes at the given positions __lowerCamelCase = self.heap[nodea_pos][0] __lowerCamelCase = self.heap[nodea_pos][0] __lowerCamelCase , __lowerCamelCase = ( self.heap[nodea_pos], self.heap[nodea_pos], ) __lowerCamelCase = nodea_pos __lowerCamelCase = nodea_pos class lowerCAmelCase__ ( Generic[T] ): def __init__( self : Tuple ) -> None: __lowerCamelCase = {} __lowerCamelCase = 0 def __repr__( self : Optional[int] ) -> str: return str(self.connections ) def __len__( self : List[str] ) -> int: return self.nodes def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Add a node in the graph if it is not in the graph if node not in self.connections: __lowerCamelCase = {} self.nodes += 1 def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Add an edge between 2 nodes in the graph self.add_node(SCREAMING_SNAKE_CASE__ ) self.add_node(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = weight __lowerCamelCase = weight def __magic_name__ ( __lowerCAmelCase : GraphUndirectedWeighted[T] , ) -> tuple[dict[T, int], dict[T, T | None]]: __lowerCamelCase = {node: maxsize for node in graph.connections} __lowerCamelCase = {node: None for node in graph.connections} __lowerCamelCase = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(__lowerCAmelCase , __lowerCAmelCase ) if priority_queue.is_empty(): return dist, parent # initialization __lowerCamelCase = priority_queue.extract_min() __lowerCamelCase = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __lowerCamelCase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(__lowerCAmelCase , dist[neighbour] ) __lowerCamelCase = node # running prim's algorithm while not priority_queue.is_empty(): __lowerCamelCase = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __lowerCamelCase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(__lowerCAmelCase , dist[neighbour] ) __lowerCamelCase = node return dist, parent
270
0
'''simple docstring''' import pprint import requests __lowerCAmelCase : str ="https://zenquotes.io/api" def UpperCamelCase ( ): return requests.get(API_ENDPOINT_URL + "/today" ).json() def UpperCamelCase ( ): return requests.get(API_ENDPOINT_URL + "/random" ).json() if __name__ == "__main__": __lowerCAmelCase : int =random_quotes() pprint.pprint(response)
237
from __future__ import annotations from statistics import mean def __magic_name__ ( __lowerCAmelCase : list[int] , __lowerCAmelCase : list[int] , __lowerCAmelCase : int ) -> list[int]: __lowerCamelCase = [0] * no_of_processes __lowerCamelCase = [0] * no_of_processes # Initialize remaining_time to waiting_time. for i in range(__lowerCAmelCase ): __lowerCamelCase = burst_time[i] __lowerCamelCase = [] __lowerCamelCase = 0 __lowerCamelCase = 0 # When processes are not completed, # A process whose arrival time has passed \ # and has remaining execution time is put into the ready_process. # The shortest process in the ready_process, target_process is executed. while completed != no_of_processes: __lowerCamelCase = [] __lowerCamelCase = -1 for i in range(__lowerCAmelCase ): if (arrival_time[i] <= total_time) and (remaining_time[i] > 0): ready_process.append(__lowerCAmelCase ) if len(__lowerCAmelCase ) > 0: __lowerCamelCase = ready_process[0] for i in ready_process: if remaining_time[i] < remaining_time[target_process]: __lowerCamelCase = i total_time += burst_time[target_process] completed += 1 __lowerCamelCase = 0 __lowerCamelCase = ( total_time - arrival_time[target_process] - burst_time[target_process] ) else: total_time += 1 return waiting_time def __magic_name__ ( __lowerCAmelCase : list[int] , __lowerCAmelCase : int , __lowerCAmelCase : list[int] ) -> list[int]: __lowerCamelCase = [0] * no_of_processes for i in range(__lowerCAmelCase ): __lowerCamelCase = burst_time[i] + waiting_time[i] return turn_around_time if __name__ == "__main__": print("[TEST CASE 01]") SCREAMING_SNAKE_CASE__ : Tuple = 4 SCREAMING_SNAKE_CASE__ : Optional[int] = [2, 5, 3, 7] SCREAMING_SNAKE_CASE__ : List[str] = [0, 0, 0, 0] SCREAMING_SNAKE_CASE__ : str = calculate_waitingtime(arrival_time, burst_time, no_of_processes) SCREAMING_SNAKE_CASE__ : Union[str, Any] = calculate_turnaroundtime( burst_time, no_of_processes, waiting_time ) # Printing the Result print("PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time") for i, process_id in enumerate(list(range(1, 5))): print( F'{process_id}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t' F'{waiting_time[i]}\t\t\t\t{turn_around_time[i]}' ) print(F'\nAverage waiting time = {mean(waiting_time):.5f}') print(F'Average turnaround time = {mean(turn_around_time):.5f}')
270
0
import numpy as np def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Any , SCREAMING_SNAKE_CASE_: List[str] , SCREAMING_SNAKE_CASE_: Tuple , SCREAMING_SNAKE_CASE_: str , SCREAMING_SNAKE_CASE_: List[str] ) -> List[Any]: '''simple docstring''' A__ = int(np.ceil((x_end - xa) / h ) ) A__ = np.zeros((n + 1,) ) A__ = ya A__ = xa for k in range(__lowerCAmelCase ): A__ = f(__lowerCAmelCase , y[k] ) A__ = f(x + 0.5 * h , y[k] + 0.5 * h * ka ) A__ = f(x + 0.5 * h , y[k] + 0.5 * h * ka ) A__ = f(x + h , y[k] + h * ka ) A__ = y[k] + (1 / 6) * h * (ka + 2 * ka + 2 * ka + ka) x += h return y if __name__ == "__main__": import doctest doctest.testmod()
68
from abc import ABC, abstractmethod from argparse import ArgumentParser class lowerCAmelCase__ ( __lowercase ): @staticmethod @abstractmethod def __A ( SCREAMING_SNAKE_CASE__ : ArgumentParser ) -> str: raise NotImplementedError() @abstractmethod def __A ( self : Optional[int] ) -> Union[str, Any]: raise NotImplementedError()
270
0
"""simple docstring""" import unittest from transformers import GPTNeoXJapaneseConfig, is_torch_available from transformers.models.gpt_neox_japanese.tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseModel class __lowerCamelCase : '''simple docstring''' def __init__( self , __UpperCAmelCase , __UpperCAmelCase=13 , __UpperCAmelCase=7 , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=99 , __UpperCAmelCase=32 , __UpperCAmelCase=5 , __UpperCAmelCase=4 , __UpperCAmelCase=4 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.0 , __UpperCAmelCase=0.1 , __UpperCAmelCase=True , __UpperCAmelCase=512 , __UpperCAmelCase=16 , __UpperCAmelCase=2 , __UpperCAmelCase=0.02 , __UpperCAmelCase=3 , __UpperCAmelCase=4 , __UpperCAmelCase=None , ) -> Optional[int]: _a = parent _a = batch_size _a = seq_length _a = is_training _a = use_input_mask _a = use_token_type_ids _a = use_labels _a = vocab_size _a = hidden_size _a = num_hidden_layers _a = num_attention_heads _a = intermediate_multiple_size _a = hidden_act _a = hidden_dropout _a = attention_dropout _a = weight_tying _a = max_position_embeddings _a = type_vocab_size _a = type_sequence_label_size _a = initializer_range _a = num_labels _a = num_choices _a = scope def _UpperCAmelCase ( self ) -> str: _a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a = None if self.use_input_mask: _a = random_attention_mask([self.batch_size, self.seq_length] ) _a = None if self.use_labels: _a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a = self.get_config() return config, input_ids, input_mask, token_labels def _UpperCAmelCase ( self ) -> List[Any]: return GPTNeoXJapaneseConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_multiple_size=self.intermediate_multiple_size , hidden_act=self.hidden_act , hidden_dropout=self.hidden_dropout , attention_dropout=self.attention_dropout , weight_tying=self.weight_tying , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=SCREAMING_SNAKE_CASE__ , initializer_range=self.initializer_range , ) def _UpperCAmelCase ( self ) -> str: _a , _a , _a , _a = self.prepare_config_and_inputs() _a = True return config, input_ids, input_mask, token_labels def _UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Any: _a = GPTNeoXJapaneseModel(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() _a = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) _a = model(SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Optional[Any]: _a = True _a = GPTNeoXJapaneseModel(SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() _a = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> int: _a = GPTNeoXJapaneseForCausalLM(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() _a = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , labels=SCREAMING_SNAKE_CASE__ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> Optional[Any]: _a = True _a = GPTNeoXJapaneseForCausalLM(config=SCREAMING_SNAKE_CASE__ ) model.to(SCREAMING_SNAKE_CASE__ ) model.eval() # first forward pass _a = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , use_cache=SCREAMING_SNAKE_CASE__ ) _a = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids _a = ids_tensor((self.batch_size, 3) , config.vocab_size ) _a = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and _a = torch.cat([input_ids, next_tokens] , dim=-1 ) _a = torch.cat([input_mask, next_mask] , dim=-1 ) _a = model(SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , output_hidden_states=SCREAMING_SNAKE_CASE__ ) _a = output_from_no_past['''hidden_states'''][0] _a = model( SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , past_key_values=SCREAMING_SNAKE_CASE__ , output_hidden_states=SCREAMING_SNAKE_CASE__ , )['''hidden_states'''][0] # select random slice _a = ids_tensor((1,) , output_from_past.shape[-1] ).item() _a = output_from_no_past[:, -3:, random_slice_idx].detach() _a = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , atol=1e-3 ) ) def _UpperCAmelCase ( self ) -> Dict: _a = self.prepare_config_and_inputs() _a , _a , _a , _a = config_and_inputs _a = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class __lowerCamelCase ( __lowercase , __lowercase , unittest.TestCase ): '''simple docstring''' A_ : List[Any] = (GPTNeoXJapaneseModel, GPTNeoXJapaneseForCausalLM) if is_torch_available() else () A_ : Tuple = (GPTNeoXJapaneseForCausalLM,) if is_torch_available() else () A_ : Dict = ( {"""feature-extraction""": GPTNeoXJapaneseModel, """text-generation""": GPTNeoXJapaneseForCausalLM} if is_torch_available() else {} ) A_ : int = False A_ : Any = False A_ : Optional[Any] = False A_ : List[Any] = False def _UpperCAmelCase ( self ) -> Optional[int]: _a = GPTNeoXJapaneseModelTester(self ) _a = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE__ , hidden_size=37 ) def _UpperCAmelCase ( self ) -> Optional[Any]: self.config_tester.run_common_tests() def _UpperCAmelCase ( self ) -> Union[str, Any]: _a , _a , _a , _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( self ) -> List[Any]: _a , _a , _a , _a = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_model_as_decoder(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( self ) -> str: # This regression test was failing with PyTorch < 1.3 _a , _a , _a , _a = self.model_tester.prepare_config_and_inputs_for_decoder() _a = None self.model_tester.create_and_check_model_as_decoder(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( self ) -> str: _a , _a , _a , _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def _UpperCAmelCase ( self ) -> List[Any]: _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_causal_lm(*SCREAMING_SNAKE_CASE__ ) @slow def _UpperCAmelCase ( self ) -> Tuple: _a = '''abeja/gpt-neox-japanese-2.7b''' _a = ['''データサイエンティストとは、''', '''100年後に必要とされる会社は、''', '''フルリモートの環境で働くために必要なことは、''', '''国境の長いトンネルを抜けると''', '''美味しい日本食といえば、'''] _a = [ '''データサイエンティストとは、データを分析し、ビジネスに役立つ知見を導き出す専門家のことです。''', '''100年後に必要とされる会社は、「人」が中心の会社です。''', '''フルリモートの環境で働くために必要なことは、「自分の時間をコントロールする」ことです。''', '''国境の長いトンネルを抜けると、そこは雪国だった。''', '''美味しい日本食といえば、やっぱりお寿司ですよね。''', ] _a = GPTNeoXJapaneseTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__ ) _a = GPTNeoXJapaneseForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE__ ) _a = [] for prompt in prompts: _a = tokenizer(SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' ).input_ids _a = model.generate(SCREAMING_SNAKE_CASE__ , max_length=50 ) _a = tokenizer.batch_decode(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) predicted_outputs += generated_string self.assertListEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
320
import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized, parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv("""TEST_SAGEMAKER""" , """False""" ) ) is not True , reason="""Skipping test because should only be run when releasing minor transformers version""" , ) @pytest.mark.usefixtures("""sm_env""" ) @parameterized_class( [ { """framework""": """pytorch""", """script""": """run_glue_model_parallelism.py""", """model_name_or_path""": """roberta-large""", """instance_type""": """ml.p3dn.24xlarge""", """results""": {"""train_runtime""": 1_600, """eval_accuracy""": 0.3, """eval_loss""": 1.2}, }, { """framework""": """pytorch""", """script""": """run_glue.py""", """model_name_or_path""": """roberta-large""", """instance_type""": """ml.p3dn.24xlarge""", """results""": {"""train_runtime""": 1_600, """eval_accuracy""": 0.3, """eval_loss""": 1.2}, }, ] ) class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Optional[int] ) -> List[Any]: if self.framework == "pytorch": subprocess.run( f'''cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'''.split() , encoding='''utf-8''' , check=SCREAMING_SNAKE_CASE__ , ) assert hasattr(self , '''env''' ) def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Optional[Any]: # configuration for running training on smdistributed Model Parallel __lowerCamelCase = { '''enabled''': True, '''processes_per_host''': 8, } __lowerCamelCase = { '''enabled''': True, '''parameters''': { '''microbatches''': 4, '''placement_strategy''': '''spread''', '''pipeline''': '''interleaved''', '''optimize''': '''speed''', '''partitions''': 4, '''ddp''': True, }, } __lowerCamelCase = {'''smdistributed''': {'''modelparallel''': smp_options}, '''mpi''': mpi_options} __lowerCamelCase = '''trainer''' if self.script == '''run_glue.py''' else '''smtrainer''' # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=f'''{self.env.base_job_name}-{instance_count}-smp-{name_extension}''' , instance_count=SCREAMING_SNAKE_CASE__ , instance_type=self.instance_type , debugger_hook_config=SCREAMING_SNAKE_CASE__ , hyperparameters={ **self.env.hyperparameters, '''model_name_or_path''': self.model_name_or_path, '''max_steps''': 5_00, } , metric_definitions=self.env.metric_definitions , distribution=SCREAMING_SNAKE_CASE__ , py_version='''py36''' , ) def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> List[str]: TrainingJobAnalytics(SCREAMING_SNAKE_CASE__ ).export_csv(f'''{self.env.test_path}/{job_name}_metrics.csv''' ) @parameterized.expand([(1,)] ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Optional[int]: # create estimator __lowerCamelCase = self.create_estimator(SCREAMING_SNAKE_CASE__ ) # run training estimator.fit() # result dataframe __lowerCamelCase = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis __lowerCamelCase = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) __lowerCamelCase = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping __lowerCamelCase = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 99_99_99 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy ) assert all(t <= self.results['''eval_loss'''] for t in eval_loss ) # dump tests result into json file to share in PR with open(f'''{estimator.latest_training_job.name}.json''' , '''w''' ) as outfile: json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss} , SCREAMING_SNAKE_CASE__ )
270
0
import qiskit def UpperCamelCase ( __magic_name__ : int , __magic_name__ : int ) -> qiskit.result.counts.Counts: """simple docstring""" lowercase__ = qiskit.Aer.get_backend("""aer_simulator""" ) # Create a Quantum Circuit acting on the q register lowercase__ = qiskit.QuantumCircuit(__lowerCAmelCase , __lowerCAmelCase ) # Apply X (NOT) Gate to Qubits 0 & 1 circuit.x(0 ) circuit.x(1 ) # Map the quantum measurement to the classical bits circuit.measure([0, 1] , [0, 1] ) # Execute the circuit on the qasm simulator lowercase__ = qiskit.execute(__lowerCAmelCase , __lowerCAmelCase , shots=1000 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(__lowerCAmelCase ) if __name__ == "__main__": A : Dict = single_qubit_measure(2, 2) print(F'Total count for various states are: {counts}')
305
from __future__ import annotations from fractions import Fraction def __magic_name__ ( __lowerCAmelCase : int , __lowerCAmelCase : int ) -> bool: return ( num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den ) def __magic_name__ ( __lowerCAmelCase : int ) -> list[str]: __lowerCamelCase = [] __lowerCamelCase = 11 __lowerCamelCase = int('''1''' + '''0''' * digit_len ) for num in range(__lowerCAmelCase , __lowerCAmelCase ): while den <= 99: if (num != den) and (num % 10 == den // 10) and (den % 10 != 0): if is_digit_cancelling(__lowerCAmelCase , __lowerCAmelCase ): solutions.append(f'''{num}/{den}''' ) den += 1 num += 1 __lowerCamelCase = 10 return solutions def __magic_name__ ( __lowerCAmelCase : int = 2 ) -> int: __lowerCamelCase = 1.0 for fraction in fraction_list(__lowerCAmelCase ): __lowerCamelCase = Fraction(__lowerCAmelCase ) result *= frac.denominator / frac.numerator return int(__lowerCAmelCase ) if __name__ == "__main__": print(solution())
270
0
'''simple docstring''' def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str ): '''simple docstring''' if not (isinstance(__lowerCAmelCase , __lowerCAmelCase ) and isinstance(__lowerCAmelCase , __lowerCAmelCase )): raise ValueError("""longest_common_substring() takes two strings for inputs""" ) UpperCAmelCase__ = len(__lowerCAmelCase ) UpperCAmelCase__ = len(__lowerCAmelCase ) UpperCAmelCase__ = [[0] * (texta_length + 1) for _ in range(texta_length + 1 )] UpperCAmelCase__ = 0 UpperCAmelCase__ = 0 for i in range(1 , texta_length + 1 ): for j in range(1 , texta_length + 1 ): if texta[i - 1] == texta[j - 1]: UpperCAmelCase__ = 1 + dp[i - 1][j - 1] if dp[i][j] > ans_length: UpperCAmelCase__ = i UpperCAmelCase__ = dp[i][j] return texta[ans_index - ans_length : ans_index] if __name__ == "__main__": import doctest doctest.testmod()
346
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE__ : List[str] = { "configuration_blip": [ "BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP", "BlipConfig", "BlipTextConfig", "BlipVisionConfig", ], "processing_blip": ["BlipProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : str = ["BlipImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "BLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "BlipModel", "BlipPreTrainedModel", "BlipForConditionalGeneration", "BlipForQuestionAnswering", "BlipVisionModel", "BlipTextModel", "BlipForImageTextRetrieval", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Any = [ "TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST", "TFBlipModel", "TFBlipPreTrainedModel", "TFBlipForConditionalGeneration", "TFBlipForQuestionAnswering", "TFBlipVisionModel", "TFBlipTextModel", "TFBlipForImageTextRetrieval", ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
270
0
import copy from dataclasses import dataclass from pathlib import Path from typing import Dict, Optional, Union @dataclass class _lowercase : """simple docstring""" A__ = None A__ = False A__ = False A__ = False A__ = None A__ = None A__ = False A__ = False A__ = False A__ = True A__ = None A__ = 1 A__ = None A__ = False A__ = None A__ = None def lowerCAmelCase ( self : int ): '''simple docstring''' return self.__class__(**{k: copy.deepcopy(SCREAMING_SNAKE_CASE__ ) for k, v in self.__dict__.items()} )
184
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : Optional[Any] = {"configuration_wavlm": ["WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP", "WavLMConfig"]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST", "WavLMForAudioFrameClassification", "WavLMForCTC", "WavLMForSequenceClassification", "WavLMForXVector", "WavLMModel", "WavLMPreTrainedModel", ] if TYPE_CHECKING: from .configuration_wavlm import WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP, WavLMConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavlm import ( WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST, WavLMForAudioFrameClassification, WavLMForCTC, WavLMForSequenceClassification, WavLMForXVector, WavLMModel, WavLMPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : int = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
270
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) lowerCAmelCase = { "configuration_resnet": ["RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "ResNetConfig", "ResNetOnnxConfig"] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase = [ "RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "ResNetForImageClassification", "ResNetModel", "ResNetPreTrainedModel", "ResNetBackbone", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase = [ "TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFResNetForImageClassification", "TFResNetModel", "TFResNetPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase = [ "FlaxResNetForImageClassification", "FlaxResNetModel", "FlaxResNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_resnet import RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ResNetConfig, ResNetOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_resnet import ( RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, ResNetBackbone, ResNetForImageClassification, ResNetModel, ResNetPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_resnet import ( TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFResNetForImageClassification, TFResNetModel, TFResNetPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel, FlaxResNetPreTrainedModel else: import sys lowerCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure)
126
import pprint import requests SCREAMING_SNAKE_CASE__ : str = "https://zenquotes.io/api" def __magic_name__ ( ) -> list: return requests.get(API_ENDPOINT_URL + '''/today''' ).json() def __magic_name__ ( ) -> list: return requests.get(API_ENDPOINT_URL + '''/random''' ).json() if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : int = random_quotes() pprint.pprint(response)
270
0
"""simple docstring""" from __future__ import annotations from fractions import Fraction from math import gcd, sqrt def snake_case__ ( __lowerCamelCase : int ): """simple docstring""" lowerCamelCase__ : Tuple =int(number**0.5 ) return number == sq * sq def snake_case__ ( __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int , __lowerCamelCase : int ): """simple docstring""" lowerCamelCase__ : Union[str, Any] =x_num * y_den * z_den + y_num * x_den * z_den + z_num * x_den * y_den lowerCamelCase__ : Optional[Any] =x_den * y_den * z_den lowerCamelCase__ : Tuple =gcd(__lowerCAmelCase , __lowerCAmelCase ) top //= hcf bottom //= hcf return top, bottom def snake_case__ ( __lowerCamelCase : int = 35 ): """simple docstring""" lowerCamelCase__ : Optional[Any] =set() lowerCamelCase__ : Optional[int] =42 lowerCamelCase__ : List[Any] =Fraction(0 ) lowerCamelCase__ : List[str] =42 for x_num in range(1 , order + 1 ): for x_den in range(x_num + 1 , order + 1 ): for y_num in range(1 , order + 1 ): for y_den in range(y_num + 1 , order + 1 ): # n=1 lowerCamelCase__ : Optional[int] =x_num * y_den + x_den * y_num lowerCamelCase__ : Union[str, Any] =x_den * y_den lowerCamelCase__ : List[str] =gcd(__lowerCAmelCase , __lowerCAmelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: lowerCamelCase__ : str =add_three( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) unique_s.add(__lowerCAmelCase ) # n=2 lowerCamelCase__ : str =( x_num * x_num * y_den * y_den + x_den * x_den * y_num * y_num ) lowerCamelCase__ : Optional[Any] =x_den * x_den * y_den * y_den if is_sq(__lowerCAmelCase ) and is_sq(__lowerCAmelCase ): lowerCamelCase__ : Optional[int] =int(sqrt(__lowerCAmelCase ) ) lowerCamelCase__ : Optional[int] =int(sqrt(__lowerCAmelCase ) ) lowerCamelCase__ : Tuple =gcd(__lowerCAmelCase , __lowerCAmelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: lowerCamelCase__ : List[Any] =add_three( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) unique_s.add(__lowerCAmelCase ) # n=-1 lowerCamelCase__ : Optional[int] =x_num * y_num lowerCamelCase__ : Union[str, Any] =x_den * y_num + x_num * y_den lowerCamelCase__ : Optional[int] =gcd(__lowerCAmelCase , __lowerCAmelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: lowerCamelCase__ : List[str] =add_three( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) unique_s.add(__lowerCAmelCase ) # n=2 lowerCamelCase__ : List[Any] =x_num * x_num * y_num * y_num lowerCamelCase__ : Any =( x_den * x_den * y_num * y_num + x_num * x_num * y_den * y_den ) if is_sq(__lowerCAmelCase ) and is_sq(__lowerCAmelCase ): lowerCamelCase__ : Optional[Any] =int(sqrt(__lowerCAmelCase ) ) lowerCamelCase__ : List[Any] =int(sqrt(__lowerCAmelCase ) ) lowerCamelCase__ : Optional[Any] =gcd(__lowerCAmelCase , __lowerCAmelCase ) z_num //= hcf z_den //= hcf if 0 < z_num < z_den <= order: lowerCamelCase__ : Union[str, Any] =add_three( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) unique_s.add(__lowerCAmelCase ) for num, den in unique_s: total += Fraction(__lowerCAmelCase , __lowerCAmelCase ) return total.denominator + total.numerator if __name__ == "__main__": print(f'{solution() = }')
238
from maths.is_square_free import is_square_free from maths.prime_factors import prime_factors def __magic_name__ ( __lowerCAmelCase : int ) -> int: __lowerCamelCase = prime_factors(__lowerCAmelCase ) if is_square_free(__lowerCAmelCase ): return -1 if len(__lowerCAmelCase ) % 2 else 1 return 0 if __name__ == "__main__": import doctest doctest.testmod()
270
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available lowercase__ : Optional[Any] = { "configuration_pix2struct": [ "PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Pix2StructConfig", "Pix2StructTextConfig", "Pix2StructVisionConfig", ], "processing_pix2struct": ["Pix2StructProcessor"], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : List[Any] = ["Pix2StructImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowercase__ : str = [ "PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST", "Pix2StructPreTrainedModel", "Pix2StructForConditionalGeneration", "Pix2StructVisionModel", "Pix2StructTextModel", ] if TYPE_CHECKING: from .configuration_pixastruct import ( PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP, PixaStructConfig, PixaStructTextConfig, PixaStructVisionConfig, ) from .processing_pixastruct import PixaStructProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_pixastruct import PixaStructImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_pixastruct import ( PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST, PixaStructForConditionalGeneration, PixaStructPreTrainedModel, PixaStructTextModel, PixaStructVisionModel, ) else: import sys lowercase__ : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
187
import argparse import collections import json import os import re import string import sys import numpy as np SCREAMING_SNAKE_CASE__ : Union[str, Any] = re.compile(r"\b(a|an|the)\b", re.UNICODE) SCREAMING_SNAKE_CASE__ : int = None def __magic_name__ ( ) -> str: __lowerCamelCase = argparse.ArgumentParser('''Official evaluation script for SQuAD version 2.0.''' ) parser.add_argument('''data_file''' , metavar='''data.json''' , help='''Input data JSON file.''' ) parser.add_argument('''pred_file''' , metavar='''pred.json''' , help='''Model predictions.''' ) parser.add_argument( '''--out-file''' , '''-o''' , metavar='''eval.json''' , help='''Write accuracy metrics to file (default is stdout).''' ) parser.add_argument( '''--na-prob-file''' , '''-n''' , metavar='''na_prob.json''' , help='''Model estimates of probability of no answer.''' ) parser.add_argument( '''--na-prob-thresh''' , '''-t''' , type=__lowerCAmelCase , default=1.0 , help='''Predict "" if no-answer probability exceeds this (default = 1.0).''' , ) parser.add_argument( '''--out-image-dir''' , '''-p''' , metavar='''out_images''' , default=__lowerCAmelCase , help='''Save precision-recall curves to directory.''' ) parser.add_argument('''--verbose''' , '''-v''' , action='''store_true''' ) if len(sys.argv ) == 1: parser.print_help() sys.exit(1 ) return parser.parse_args() def __magic_name__ ( __lowerCAmelCase : List[str] ) -> Union[str, Any]: __lowerCamelCase = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __lowerCamelCase = bool(qa['''answers''']['''text'''] ) return qid_to_has_ans def __magic_name__ ( __lowerCAmelCase : Dict ) -> Optional[Any]: def remove_articles(__lowerCAmelCase : Optional[int] ): return ARTICLES_REGEX.sub(''' ''' , __lowerCAmelCase ) def white_space_fix(__lowerCAmelCase : Optional[int] ): return " ".join(text.split() ) def remove_punc(__lowerCAmelCase : Union[str, Any] ): __lowerCamelCase = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(__lowerCAmelCase : Dict ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(__lowerCAmelCase ) ) ) ) def __magic_name__ ( __lowerCAmelCase : List[Any] ) -> Optional[int]: if not s: return [] return normalize_answer(__lowerCAmelCase ).split() def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple ) -> int: return int(normalize_answer(__lowerCAmelCase ) == normalize_answer(__lowerCAmelCase ) ) def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : Tuple ) -> str: __lowerCamelCase = get_tokens(__lowerCAmelCase ) __lowerCamelCase = get_tokens(__lowerCAmelCase ) __lowerCamelCase = collections.Counter(__lowerCAmelCase ) & collections.Counter(__lowerCAmelCase ) __lowerCamelCase = sum(common.values() ) if len(__lowerCAmelCase ) == 0 or len(__lowerCAmelCase ) == 0: # If either is no-answer, then F1 is 1 if they agree, 0 otherwise return int(gold_toks == pred_toks ) if num_same == 0: return 0 __lowerCamelCase = 1.0 * num_same / len(__lowerCAmelCase ) __lowerCamelCase = 1.0 * num_same / len(__lowerCAmelCase ) __lowerCamelCase = (2 * precision * recall) / (precision + recall) return fa def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : List[str] ) -> Optional[Any]: __lowerCamelCase = {} __lowerCamelCase = {} for article in dataset: for p in article["paragraphs"]: for qa in p["qas"]: __lowerCamelCase = qa['''id'''] __lowerCamelCase = [t for t in qa['''answers''']['''text'''] if normalize_answer(__lowerCAmelCase )] if not gold_answers: # For unanswerable questions, only correct answer is empty string __lowerCamelCase = [''''''] if qid not in preds: print(f'''Missing prediction for {qid}''' ) continue __lowerCamelCase = preds[qid] # Take max over all gold answers __lowerCamelCase = max(compute_exact(__lowerCAmelCase , __lowerCAmelCase ) for a in gold_answers ) __lowerCamelCase = max(compute_fa(__lowerCAmelCase , __lowerCAmelCase ) for a in gold_answers ) return exact_scores, fa_scores def __magic_name__ ( __lowerCAmelCase : Tuple , __lowerCAmelCase : str , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Union[str, Any] ) -> List[str]: __lowerCamelCase = {} for qid, s in scores.items(): __lowerCamelCase = na_probs[qid] > na_prob_thresh if pred_na: __lowerCamelCase = float(not qid_to_has_ans[qid] ) else: __lowerCamelCase = s return new_scores def __magic_name__ ( __lowerCAmelCase : List[Any] , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Optional[Any]=None ) -> Union[str, Any]: if not qid_list: __lowerCamelCase = len(__lowerCAmelCase ) return collections.OrderedDict( [ ('''exact''', 100.0 * sum(exact_scores.values() ) / total), ('''f1''', 100.0 * sum(fa_scores.values() ) / total), ('''total''', total), ] ) else: __lowerCamelCase = len(__lowerCAmelCase ) return collections.OrderedDict( [ ('''exact''', 100.0 * sum(exact_scores[k] for k in qid_list ) / total), ('''f1''', 100.0 * sum(fa_scores[k] for k in qid_list ) / total), ('''total''', total), ] ) def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : str , __lowerCAmelCase : Optional[Any] ) -> int: for k in new_eval: __lowerCamelCase = new_eval[k] def __magic_name__ ( __lowerCAmelCase : Optional[int] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Dict , __lowerCAmelCase : Union[str, Any] ) -> Optional[Any]: plt.step(__lowerCAmelCase , __lowerCAmelCase , color='''b''' , alpha=0.2 , where='''post''' ) plt.fill_between(__lowerCAmelCase , __lowerCAmelCase , step='''post''' , alpha=0.2 , color='''b''' ) plt.xlabel('''Recall''' ) plt.ylabel('''Precision''' ) plt.xlim([0.0, 1.05] ) plt.ylim([0.0, 1.05] ) plt.title(__lowerCAmelCase ) plt.savefig(__lowerCAmelCase ) plt.clf() def __magic_name__ ( __lowerCAmelCase : Any , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Tuple , __lowerCAmelCase : Tuple , __lowerCAmelCase : Optional[Any]=None , __lowerCAmelCase : Tuple=None ) -> int: __lowerCamelCase = sorted(__lowerCAmelCase , key=lambda __lowerCAmelCase : na_probs[k] ) __lowerCamelCase = 0.0 __lowerCamelCase = 1.0 __lowerCamelCase = 0.0 __lowerCamelCase = [1.0] __lowerCamelCase = [0.0] __lowerCamelCase = 0.0 for i, qid in enumerate(__lowerCAmelCase ): if qid_to_has_ans[qid]: true_pos += scores[qid] __lowerCamelCase = true_pos / float(i + 1 ) __lowerCamelCase = true_pos / float(__lowerCAmelCase ) if i == len(__lowerCAmelCase ) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]: # i.e., if we can put a threshold after this point avg_prec += cur_p * (cur_r - recalls[-1]) precisions.append(__lowerCAmelCase ) recalls.append(__lowerCAmelCase ) if out_image: plot_pr_curve(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) return {"ap": 100.0 * avg_prec} def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Tuple , __lowerCAmelCase : List[str] , __lowerCAmelCase : List[Any] , __lowerCAmelCase : List[Any] ) -> List[Any]: if out_image_dir and not os.path.exists(__lowerCAmelCase ): os.makedirs(__lowerCAmelCase ) __lowerCamelCase = sum(1 for v in qid_to_has_ans.values() if v ) if num_true_pos == 0: return __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_exact.png''' ) , title='''Precision-Recall curve for Exact Match score''' , ) __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_f1.png''' ) , title='''Precision-Recall curve for F1 score''' , ) __lowerCamelCase = {k: float(__lowerCAmelCase ) for k, v in qid_to_has_ans.items()} __lowerCamelCase = make_precision_recall_eval( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , out_image=os.path.join(__lowerCAmelCase , '''pr_oracle.png''' ) , title='''Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)''' , ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_exact''' ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_f1''' ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''pr_oracle''' ) def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Any , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : int ) -> Optional[Any]: if not qid_list: return __lowerCamelCase = [na_probs[k] for k in qid_list] __lowerCamelCase = np.ones_like(__lowerCAmelCase ) / float(len(__lowerCAmelCase ) ) plt.hist(__lowerCAmelCase , weights=__lowerCAmelCase , bins=20 , range=(0.0, 1.0) ) plt.xlabel('''Model probability of no-answer''' ) plt.ylabel('''Proportion of dataset''' ) plt.title(f'''Histogram of no-answer probability: {name}''' ) plt.savefig(os.path.join(__lowerCAmelCase , f'''na_prob_hist_{name}.png''' ) ) plt.clf() def __magic_name__ ( __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : List[str] , __lowerCAmelCase : Union[str, Any] ) -> Optional[int]: __lowerCamelCase = sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k] ) __lowerCamelCase = num_no_ans __lowerCamelCase = cur_score __lowerCamelCase = 0.0 __lowerCamelCase = sorted(__lowerCAmelCase , key=lambda __lowerCAmelCase : na_probs[k] ) for i, qid in enumerate(__lowerCAmelCase ): if qid not in scores: continue if qid_to_has_ans[qid]: __lowerCamelCase = scores[qid] else: if preds[qid]: __lowerCamelCase = -1 else: __lowerCamelCase = 0 cur_score += diff if cur_score > best_score: __lowerCamelCase = cur_score __lowerCamelCase = na_probs[qid] return 100.0 * best_score / len(__lowerCAmelCase ), best_thresh def __magic_name__ ( __lowerCAmelCase : Dict , __lowerCAmelCase : Optional[int] , __lowerCAmelCase : int , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : int , __lowerCAmelCase : Optional[Any] ) -> int: __lowerCamelCase , __lowerCamelCase = find_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = find_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = best_exact __lowerCamelCase = exact_thresh __lowerCamelCase = best_fa __lowerCamelCase = fa_thresh def __magic_name__ ( ) -> Optional[int]: with open(OPTS.data_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) __lowerCamelCase = dataset_json['''data'''] with open(OPTS.pred_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) if OPTS.na_prob_file: with open(OPTS.na_prob_file ) as f: __lowerCamelCase = json.load(__lowerCAmelCase ) else: __lowerCamelCase = {k: 0.0 for k in preds} __lowerCamelCase = make_qid_to_has_ans(__lowerCAmelCase ) # maps qid to True/False __lowerCamelCase = [k for k, v in qid_to_has_ans.items() if v] __lowerCamelCase = [k for k, v in qid_to_has_ans.items() if not v] __lowerCamelCase , __lowerCamelCase = get_raw_scores(__lowerCAmelCase , __lowerCAmelCase ) __lowerCamelCase = apply_no_ans_threshold(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.na_prob_thresh ) __lowerCamelCase = apply_no_ans_threshold(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.na_prob_thresh ) __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase ) if has_ans_qids: __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase , qid_list=__lowerCAmelCase ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''HasAns''' ) if no_ans_qids: __lowerCamelCase = make_eval_dict(__lowerCAmelCase , __lowerCAmelCase , qid_list=__lowerCAmelCase ) merge_eval(__lowerCAmelCase , __lowerCAmelCase , '''NoAns''' ) if OPTS.na_prob_file: find_all_best_thresh(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) if OPTS.na_prob_file and OPTS.out_image_dir: run_precision_recall_analysis(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir ) histogram_na_prob(__lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir , '''hasAns''' ) histogram_na_prob(__lowerCAmelCase , __lowerCAmelCase , OPTS.out_image_dir , '''noAns''' ) if OPTS.out_file: with open(OPTS.out_file , '''w''' ) as f: json.dump(__lowerCAmelCase , __lowerCAmelCase ) else: print(json.dumps(__lowerCAmelCase , indent=2 ) ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Any = parse_args() if OPTS.out_image_dir: import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt main()
270
0
import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def __lowerCamelCase ( snake_case__ ) -> Any: """simple docstring""" _SCREAMING_SNAKE_CASE = [ """encoder.version""", """decoder.version""", """model.encoder.version""", """model.decoder.version""", """_float_tensor""", """decoder.output_projection.weight""", ] for k in ignore_keys: state_dict.pop(__lowerCAmelCase ,__lowerCAmelCase ) def __lowerCamelCase ( snake_case__ ) -> Any: """simple docstring""" _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = emb.weight.shape _SCREAMING_SNAKE_CASE = nn.Linear(__lowerCAmelCase ,__lowerCAmelCase ,bias=__lowerCAmelCase ) _SCREAMING_SNAKE_CASE = emb.weight.data return lin_layer def __lowerCamelCase ( snake_case__ ,snake_case__="facebook/mbart-large-en-ro" ,snake_case__=False ,snake_case__=False ) -> List[Any]: """simple docstring""" _SCREAMING_SNAKE_CASE = torch.load(__lowerCAmelCase ,map_location="""cpu""" )["""model"""] remove_ignore_keys_(__lowerCAmelCase ) _SCREAMING_SNAKE_CASE = state_dict["""encoder.embed_tokens.weight"""].shape[0] _SCREAMING_SNAKE_CASE = MBartConfig.from_pretrained(__lowerCAmelCase ,vocab_size=__lowerCAmelCase ) if mbart_aa and finetuned: _SCREAMING_SNAKE_CASE = """relu""" _SCREAMING_SNAKE_CASE = state_dict["""decoder.embed_tokens.weight"""] _SCREAMING_SNAKE_CASE = MBartForConditionalGeneration(__lowerCAmelCase ) model.model.load_state_dict(__lowerCAmelCase ) if finetuned: _SCREAMING_SNAKE_CASE = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''fairseq_path''', type=str, help='''bart.large, bart.large.cnn or a path to a model.pt on local filesystem.''' ) parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument( '''--hf_config''', default='''facebook/mbart-large-cc25''', type=str, help='''Which huggingface architecture to use: mbart-large''', ) parser.add_argument('''--mbart_50''', action='''store_true''', help='''whether the model is mMART-50 checkpoint''') parser.add_argument('''--finetuned''', action='''store_true''', help='''whether the model is a fine-tuned checkpoint''') UpperCamelCase = parser.parse_args() UpperCamelCase = convert_fairseq_mbart_checkpoint_from_disk( args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_aa=args.mbart_aa ) model.save_pretrained(args.pytorch_dump_folder_path)
306
import math import os import re import sys import unittest from pathlib import Path from typing import Tuple from unittest.mock import patch from parameterized import parameterized from transformers.testing_utils import ( CaptureStderr, ExtendSysPath, TestCasePlus, execute_subprocess_async, get_gpu_count, get_torch_dist_unique_port, require_apex, require_bitsandbytes, require_fairscale, require_torch, require_torch_gpu, require_torch_multi_gpu, require_torch_non_multi_gpu, slow, ) from transformers.trainer_callback import TrainerState from transformers.trainer_utils import set_seed SCREAMING_SNAKE_CASE__ : Optional[int] = os.path.abspath(os.path.dirname(__file__)) with ExtendSysPath(F'{bindir}/../../examples/pytorch/translation'): from run_translation import main # noqa set_seed(42) SCREAMING_SNAKE_CASE__ : Any = "sshleifer/student_marian_en_ro_6_1" SCREAMING_SNAKE_CASE__ : Tuple = "sshleifer/tiny-mbart" @require_torch class lowerCAmelCase__ ( __lowercase ): def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Tuple=False , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=True , SCREAMING_SNAKE_CASE__ : Optional[int]=True , ) -> Optional[int]: __lowerCamelCase = self.run_trainer( eval_steps=1 , max_len=12 , model_name=SCREAMING_SNAKE_CASE__ , num_train_epochs=1 , distributed=SCREAMING_SNAKE_CASE__ , extra_args_str=SCREAMING_SNAKE_CASE__ , predict_with_generate=SCREAMING_SNAKE_CASE__ , do_train=SCREAMING_SNAKE_CASE__ , do_eval=SCREAMING_SNAKE_CASE__ , do_predict=SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = TrainerState.load_from_json(os.path.join(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history if not do_eval: return __lowerCamelCase = [log for log in logs if '''eval_loss''' in log.keys()] __lowerCamelCase = eval_metrics[0] if predict_with_generate: assert "eval_bleu" in first_step_stats __lowerCamelCase = eval_metrics[-1] assert isinstance(last_step_stats['''eval_bleu'''] , SCREAMING_SNAKE_CASE__ ) assert not math.isnan(float(last_step_stats['''eval_loss'''] ) ), "eval_loss must not be `nan`" @require_torch_non_multi_gpu def __A ( self : Optional[int] ) -> int: self.run_seqaseq_quick() @require_torch_multi_gpu def __A ( self : int ) -> List[str]: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ ) @require_torch_multi_gpu def __A ( self : Optional[Any] ) -> Tuple: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Dict ) -> Tuple: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp simple''' ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Optional[int] ) -> List[str]: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp simple --fp16''' ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Tuple ) -> Any: self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp zero_dp_2''' , predict_with_generate=SCREAMING_SNAKE_CASE__ ) @unittest.skip('''Requires an update of the env running those tests''' ) @require_torch_multi_gpu @require_fairscale def __A ( self : Dict ) -> Tuple: self.run_seqaseq_quick( distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--sharded_ddp zero_dp_2 --fp16''' , predict_with_generate=SCREAMING_SNAKE_CASE__ ) @require_apex @require_torch_gpu def __A ( self : Union[str, Any] ) -> List[str]: # XXX: apex breaks the trainer if it's run twice e.g. run_seq2seq.main() from the same # program and it breaks other tests that run from the same pytest worker, therefore until this is # sorted out it must be run only in an external program, that is distributed=True in this # test and only under one or more gpus - if we want cpu will need to make a special test # # specifically to the problem traced it to self.optimizer.step() - if it's run 2nd time via # 2nd main() call it botches the future eval. # self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--fp16 --fp16_backend=apex''' ) # test 2nd time - was getting eval_loss': nan' # to reproduce the problem set distributed=False self.run_seqaseq_quick(distributed=SCREAMING_SNAKE_CASE__ , extra_args_str='''--fp16 --fp16_backend=apex''' ) @parameterized.expand(['''base''', '''low''', '''high''', '''mixed'''] ) @require_torch_multi_gpu def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[str] ) -> Optional[Any]: # as each sub-test is slow-ish split into multiple sub-tests to avoid CI timeout __lowerCamelCase = { # test with the default log_level - should be info and thus log info once '''base''': {'''extra_args_str''': '''''', '''n_matches''': 1}, # test with low log_level and log_level_replica - should be noisy on all processes # now the info string should appear twice on 2 processes '''low''': {'''extra_args_str''': '''--log_level debug --log_level_replica debug''', '''n_matches''': 2}, # test with high log_level and low log_level_replica # now the info string should appear once only on the replica '''high''': {'''extra_args_str''': '''--log_level error --log_level_replica debug''', '''n_matches''': 1}, # test with high log_level and log_level_replica - should be quiet on all processes '''mixed''': {'''extra_args_str''': '''--log_level error --log_level_replica error''', '''n_matches''': 0}, } __lowerCamelCase = experiments[experiment_id] __lowerCamelCase = {'''distributed''': True, '''predict_with_generate''': False, '''do_eval''': False, '''do_predict''': False} __lowerCamelCase = '''Running training''' with CaptureStderr() as cl: self.run_seqaseq_quick(**SCREAMING_SNAKE_CASE__ , extra_args_str=data['''extra_args_str'''] ) __lowerCamelCase = len(re.findall(SCREAMING_SNAKE_CASE__ , cl.err ) ) self.assertEqual(SCREAMING_SNAKE_CASE__ , data['''n_matches'''] ) @slow def __A ( self : Any ) -> Optional[Any]: __lowerCamelCase = self.run_trainer( eval_steps=2 , max_len=1_28 , model_name=SCREAMING_SNAKE_CASE__ , learning_rate=3e-4 , num_train_epochs=10 , distributed=SCREAMING_SNAKE_CASE__ , ) # Check metrics __lowerCamelCase = TrainerState.load_from_json(os.path.join(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history __lowerCamelCase = [log for log in logs if '''eval_loss''' in log.keys()] __lowerCamelCase = eval_metrics[0] __lowerCamelCase = eval_metrics[-1] assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing" assert isinstance(last_step_stats['''eval_bleu'''] , SCREAMING_SNAKE_CASE__ ) # test if do_predict saves generations and metrics __lowerCamelCase = os.listdir(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = {os.path.basename(SCREAMING_SNAKE_CASE__ ) for p in contents} assert "generated_predictions.txt" in contents assert "predict_results.json" in contents @slow @require_bitsandbytes def __A ( self : Optional[int] ) -> str: from transformers.training_args import OptimizerNames def train_and_return_metrics(SCREAMING_SNAKE_CASE__ : str ) -> Tuple[int, float]: __lowerCamelCase = '''--skip_memory_metrics 0''' __lowerCamelCase = self.run_trainer( max_len=1_28 , model_name=SCREAMING_SNAKE_CASE__ , learning_rate=3e-4 , num_train_epochs=1 , optim=SCREAMING_SNAKE_CASE__ , distributed=SCREAMING_SNAKE_CASE__ , extra_args_str=SCREAMING_SNAKE_CASE__ , do_eval=SCREAMING_SNAKE_CASE__ , do_predict=SCREAMING_SNAKE_CASE__ , n_gpus_to_use=1 , ) # Check metrics __lowerCamelCase = TrainerState.load_from_json(Path(SCREAMING_SNAKE_CASE__ , '''trainer_state.json''' ) ).log_history __lowerCamelCase = int(logs[0]['''train_mem_gpu_peaked_delta'''] / 2**20 ) __lowerCamelCase = int(logs[0]['''train_mem_gpu_alloc_delta'''] / 2**20 ) __lowerCamelCase = logs[0]['''train_loss'''] return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value ) __lowerCamelCase , __lowerCamelCase , __lowerCamelCase = train_and_return_metrics(OptimizerNames.ADAMW_BNB.value ) __lowerCamelCase = gpu_alloc_mem_orig - gpu_alloc_mem_bnb __lowerCamelCase = gpu_peak_mem_orig + gpu_alloc_mem_orig __lowerCamelCase = gpu_peak_mem_bnb + gpu_alloc_mem_bnb __lowerCamelCase = gpu_total_mem_orig - gpu_total_mem_bnb # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized # in 2 bytes and the diff in optim memory usage is derived as so: # # - normal 25*8=~200MB (8 bytes per param) # - bnb 25*2= ~50MB (2 bytes per param) # # Thus we should expect ~150MB total memory saved. # # Peak memory should be the same - the total should be different by about that same margin # # After leaving a small margin to accommodate for differences between gpus let's check # that we have at least 120MB in savings __lowerCamelCase = 1_20 # uncomment the following if this test starts failing - requires py38 for a new print feature # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB") # print(f" {gpu_alloc_mem_bnb=}MB {gpu_peak_mem_bnb=}MB {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB") # print(f"{gpu_alloc_mem_diff=}MB") # print(f"{gpu_peak_mem_diff=}MB") # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB") # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB") self.assertGreater( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got''' f''' a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and''' f''' gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB''' , ) self.assertGreater( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , '''should use ~150MB less total gpu memory with BNB, compared to without it for this model but got''' f''' a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and''' f''' gpu_total_mem_bnb={gpu_total_mem_bnb}MB''' , ) self.assertEqual( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , f'''loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}''' ) def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : float = 3e-3 , SCREAMING_SNAKE_CASE__ : str = "adafactor" , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : int = 0 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : int = None , ) -> List[Any]: __lowerCamelCase = self.test_file_dir / '''../fixtures/tests_samples/wmt_en_ro''' __lowerCamelCase = self.get_auto_remove_tmp_dir() __lowerCamelCase = f''' --model_name_or_path {model_name} --train_file {data_dir}/train.json --validation_file {data_dir}/val.json --test_file {data_dir}/test.json --output_dir {output_dir} --overwrite_output_dir --max_train_samples 8 --max_source_length {max_len} --max_target_length {max_len} --do_train --num_train_epochs {str(SCREAMING_SNAKE_CASE__ )} --per_device_train_batch_size 4 --learning_rate {learning_rate} --warmup_steps 8 --logging_steps 0 --logging_strategy no --save_steps {str(SCREAMING_SNAKE_CASE__ )} --group_by_length --label_smoothing_factor 0.1 --target_lang ro_RO --source_lang en_XX '''.split() __lowerCamelCase = f''' --do_eval --per_device_eval_batch_size 4 --max_eval_samples 8 --val_max_target_length {max_len} --evaluation_strategy steps --eval_steps {str(SCREAMING_SNAKE_CASE__ )} '''.split() __lowerCamelCase = ''' --do_predict '''.split() __lowerCamelCase = [] if do_train: args += args_train if do_eval: args += args_eval if do_predict: args += args_predict if predict_with_generate: args += "--predict_with_generate".split() if do_train: if optim == "adafactor": args += "--adafactor".split() else: args += f'''--optim {optim}'''.split() if extra_args_str is not None: args += extra_args_str.split() if distributed: if n_gpus_to_use is None: __lowerCamelCase = get_gpu_count() __lowerCamelCase = get_torch_dist_unique_port() __lowerCamelCase = f''' -m torch.distributed.run --nproc_per_node={n_gpus_to_use} --master_port={master_port} {self.examples_dir_str}/pytorch/translation/run_translation.py '''.split() __lowerCamelCase = [sys.executable] + distributed_args + args # keep for quick debug # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die execute_subprocess_async(SCREAMING_SNAKE_CASE__ , env=self.get_env() ) else: __lowerCamelCase = ['''run_translation.py'''] + args with patch.object(SCREAMING_SNAKE_CASE__ , '''argv''' , SCREAMING_SNAKE_CASE__ ): main() return output_dir
270
0
'''simple docstring''' # Lint as: python3 import itertools import os import re lowerCAmelCase : Dict =re.compile(r'''([A-Z]+)([A-Z][a-z])''') lowerCAmelCase : int =re.compile(r'''([a-z\d])([A-Z])''') lowerCAmelCase : List[str] =re.compile(r'''(?<!_)_(?!_)''') lowerCAmelCase : Optional[Any] =re.compile(r'''(_{2,})''') lowerCAmelCase : Union[str, Any] =r"^\w+(\.\w+)*$" lowerCAmelCase : Optional[int] =r"<>:/\|?*" def UpperCAmelCase_ ( __lowerCamelCase : List[Any] ): lowercase_ :Any = _uppercase_uppercase_re.sub(r"\1_\2" ,__lowerCAmelCase ) lowercase_ :Optional[Any] = _lowercase_uppercase_re.sub(r"\1_\2" ,__lowerCAmelCase ) return name.lower() def UpperCAmelCase_ ( __lowerCamelCase : Tuple ): lowercase_ :int = _single_underscore_re.split(__lowerCAmelCase ) lowercase_ :List[Any] = [_multiple_underscores_re.split(__lowerCAmelCase ) for n in name] return "".join(n.capitalize() for n in itertools.chain.from_iterable(__lowerCAmelCase ) if n != "" ) def UpperCAmelCase_ ( __lowerCamelCase : Optional[int] ): if os.path.basename(__lowerCAmelCase ) != name: raise ValueError(F'Should be a dataset name, not a path: {name}' ) return camelcase_to_snakecase(__lowerCAmelCase ) def UpperCAmelCase_ ( __lowerCamelCase : Tuple ,__lowerCamelCase : str ): if os.path.basename(__lowerCAmelCase ) != name: raise ValueError(F'Should be a dataset name, not a path: {name}' ) if not re.match(_split_re ,__lowerCAmelCase ): raise ValueError(F'Split name should match \'{_split_re}\'\' but got \'{split}\'.' ) return F'{filename_prefix_for_name(__lowerCAmelCase )}-{split}' def UpperCAmelCase_ ( __lowerCamelCase : List[str] ,__lowerCamelCase : Optional[Any] ,__lowerCamelCase : Any ,__lowerCamelCase : List[Any]=None ): lowercase_ :List[str] = filename_prefix_for_split(__lowerCAmelCase ,__lowerCAmelCase ) if filetype_suffix: prefix += F'.{filetype_suffix}' lowercase_ :List[str] = os.path.join(__lowerCAmelCase ,__lowerCAmelCase ) return F'{filepath}*' def UpperCAmelCase_ ( __lowerCamelCase : Optional[int] ,__lowerCamelCase : str ,__lowerCamelCase : str ,__lowerCamelCase : Tuple=None ,__lowerCamelCase : Union[str, Any]=None ): lowercase_ :Tuple = filename_prefix_for_split(__lowerCAmelCase ,__lowerCAmelCase ) lowercase_ :str = os.path.join(__lowerCAmelCase ,__lowerCAmelCase ) if shard_lengths: lowercase_ :Optional[int] = len(__lowerCAmelCase ) lowercase_ :Any = [F'{prefix}-{shard_id:05d}-of-{num_shards:05d}' for shard_id in range(__lowerCAmelCase )] if filetype_suffix: lowercase_ :str = [filename + F'.{filetype_suffix}' for filename in filenames] return filenames else: lowercase_ :int = prefix if filetype_suffix: filename += F'.{filetype_suffix}' return [filename]
223
import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING SCREAMING_SNAKE_CASE__ : Dict = { "facebook/mask2former-swin-small-coco-instance": ( "https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json" ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) class lowerCAmelCase__ ( __lowercase ): a__ : Any = """mask2former""" a__ : Dict = ["""swin"""] a__ : Any = {"""hidden_size""": """hidden_dim"""} def __init__( self : Any , SCREAMING_SNAKE_CASE__ : Optional[Dict] = None , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 2_56 , SCREAMING_SNAKE_CASE__ : int = 10_24 , SCREAMING_SNAKE_CASE__ : str = "relu" , SCREAMING_SNAKE_CASE__ : int = 6 , SCREAMING_SNAKE_CASE__ : int = 10 , SCREAMING_SNAKE_CASE__ : int = 8 , SCREAMING_SNAKE_CASE__ : float = 0.0 , SCREAMING_SNAKE_CASE__ : int = 20_48 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : int = 4 , SCREAMING_SNAKE_CASE__ : int = 2_55 , SCREAMING_SNAKE_CASE__ : int = 1_00 , SCREAMING_SNAKE_CASE__ : float = 0.1 , SCREAMING_SNAKE_CASE__ : float = 2.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : float = 5.0 , SCREAMING_SNAKE_CASE__ : int = 1_25_44 , SCREAMING_SNAKE_CASE__ : float = 3.0 , SCREAMING_SNAKE_CASE__ : float = 0.75 , SCREAMING_SNAKE_CASE__ : float = 0.02 , SCREAMING_SNAKE_CASE__ : float = 1.0 , SCREAMING_SNAKE_CASE__ : bool = True , SCREAMING_SNAKE_CASE__ : List[int] = [4, 8, 16, 32] , SCREAMING_SNAKE_CASE__ : bool = None , **SCREAMING_SNAKE_CASE__ : Tuple , ) -> str: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.''' ) __lowerCamelCase = CONFIG_MAPPING['''swin''']( image_size=2_24 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=SCREAMING_SNAKE_CASE__ , out_features=['''stage1''', '''stage2''', '''stage3''', '''stage4'''] , ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = backbone_config.pop('''model_type''' ) __lowerCamelCase = CONFIG_MAPPING[backbone_model_type] __lowerCamelCase = config_class.from_dict(SCREAMING_SNAKE_CASE__ ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( f'''Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. ''' f'''Supported model types: {','.join(self.backbones_supported )}''' ) __lowerCamelCase = backbone_config __lowerCamelCase = feature_size __lowerCamelCase = mask_feature_size __lowerCamelCase = hidden_dim __lowerCamelCase = encoder_feedforward_dim __lowerCamelCase = activation_function __lowerCamelCase = encoder_layers __lowerCamelCase = decoder_layers __lowerCamelCase = num_attention_heads __lowerCamelCase = dropout __lowerCamelCase = dim_feedforward __lowerCamelCase = pre_norm __lowerCamelCase = enforce_input_projection __lowerCamelCase = common_stride __lowerCamelCase = ignore_value __lowerCamelCase = num_queries __lowerCamelCase = no_object_weight __lowerCamelCase = class_weight __lowerCamelCase = mask_weight __lowerCamelCase = dice_weight __lowerCamelCase = train_num_points __lowerCamelCase = oversample_ratio __lowerCamelCase = importance_sample_ratio __lowerCamelCase = init_std __lowerCamelCase = init_xavier_std __lowerCamelCase = use_auxiliary_loss __lowerCamelCase = feature_strides __lowerCamelCase = output_auxiliary_logits __lowerCamelCase = decoder_layers super().__init__(**SCREAMING_SNAKE_CASE__ ) @classmethod def __A ( cls : Any , SCREAMING_SNAKE_CASE__ : PretrainedConfig , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> List[Any]: return cls( backbone_config=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def __A ( self : Any ) -> Dict[str, any]: __lowerCamelCase = copy.deepcopy(self.__dict__ ) __lowerCamelCase = self.backbone_config.to_dict() __lowerCamelCase = self.__class__.model_type return output
270
0
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(">=", "4.25.0")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
237
import os def __magic_name__ ( ) -> str: __lowerCamelCase = os.path.join(os.path.dirname(__lowerCAmelCase ) , '''num.txt''' ) with open(__lowerCAmelCase ) as file_hand: return str(sum(int(__lowerCAmelCase ) for line in file_hand ) )[:10] if __name__ == "__main__": print(solution())
270
0
from __future__ import annotations from collections.abc import Sequence from typing import Literal def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str , SCREAMING_SNAKE_CASE_: str ) -> str | Literal[False]: '''simple docstring''' A__ = list(__lowerCAmelCase ) A__ = list(__lowerCAmelCase ) A__ = 0 for i in range(len(__lowerCAmelCase ) ): if lista[i] != lista[i]: count += 1 A__ = "_" if count > 1: return False else: return "".join(__lowerCAmelCase ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: list[str] ) -> list[str]: '''simple docstring''' A__ = [] while True: A__ = ["$"] * len(__lowerCAmelCase ) A__ = [] for i in range(len(__lowerCAmelCase ) ): for j in range(i + 1 , len(__lowerCAmelCase ) ): A__ = compare_string(binary[i] , binary[j] ) if k is False: A__ = "*" A__ = "*" temp.append("X" ) for i in range(len(__lowerCAmelCase ) ): if checka[i] == "$": pi.append(binary[i] ) if len(__lowerCAmelCase ) == 0: return pi A__ = list(set(__lowerCAmelCase ) ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: int , SCREAMING_SNAKE_CASE_: Sequence[float] ) -> list[str]: '''simple docstring''' A__ = [] for minterm in minterms: A__ = "" for _ in range(__lowerCAmelCase ): A__ = str(minterm % 2 ) + string minterm //= 2 temp.append(__lowerCAmelCase ) return temp def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str , SCREAMING_SNAKE_CASE_: str , SCREAMING_SNAKE_CASE_: int ) -> bool: '''simple docstring''' A__ = list(__lowerCAmelCase ) A__ = list(__lowerCAmelCase ) A__ = 0 for i in range(len(__lowerCAmelCase ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: list[list[int]] , SCREAMING_SNAKE_CASE_: list[str] ) -> list[str]: '''simple docstring''' A__ = [] A__ = [0] * len(__lowerCAmelCase ) for i in range(len(chart[0] ) ): A__ = 0 A__ = -1 for j in range(len(__lowerCAmelCase ) ): if chart[j][i] == 1: count += 1 A__ = j if count == 1: A__ = 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__ = 0 temp.append(prime_implicants[i] ) while True: A__ = 0 A__ = -1 A__ = 0 for i in range(len(__lowerCAmelCase ) ): A__ = chart[i].count(1 ) if count_n > max_n: A__ = count_n A__ = 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__ = 0 def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: list[str] , SCREAMING_SNAKE_CASE_: list[str] ) -> list[list[int]]: '''simple docstring''' A__ = [[0 for x in range(len(__lowerCAmelCase ) )] for x in range(len(__lowerCAmelCase ) )] for i in range(len(__lowerCAmelCase ) ): A__ = prime_implicants[i].count("_" ) for j in range(len(__lowerCAmelCase ) ): if is_for_table(prime_implicants[i] , binary[j] , __lowerCAmelCase ): A__ = 1 return chart def lowerCAmelCase__ ( ) -> None: '''simple docstring''' A__ = int(input("Enter the no. of variables\n" ) ) A__ = [ float(__lowerCAmelCase ) for x in input( "Enter the decimal representation of Minterms \'Spaces Separated\'\n" ).split() ] A__ = decimal_to_binary(__lowerCAmelCase , __lowerCAmelCase ) A__ = check(__lowerCAmelCase ) print("Prime Implicants are:" ) print(__lowerCAmelCase ) A__ = prime_implicant_chart(__lowerCAmelCase , __lowerCAmelCase ) A__ = selection(__lowerCAmelCase , __lowerCAmelCase ) print("Essential Prime Implicants are:" ) print(__lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod() main()
68
import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available SCREAMING_SNAKE_CASE__ : Optional[int] = logging.getLogger(__name__) @dataclass class lowerCAmelCase__ : a__ : str a__ : List[str] a__ : Optional[List[str]] @dataclass class lowerCAmelCase__ : a__ : List[int] a__ : List[int] a__ : Optional[List[int]] = None a__ : Optional[List[int]] = None class lowerCAmelCase__ ( __lowercase ): a__ : Optional[Any] = """train""" a__ : Optional[int] = """dev""" a__ : Dict = """test""" class lowerCAmelCase__ : @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[Split, str] ) -> List[InputExample]: raise NotImplementedError @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : str ) -> List[str]: raise NotImplementedError @staticmethod def __A ( SCREAMING_SNAKE_CASE__ : List[InputExample] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : List[str]="[CLS]" , SCREAMING_SNAKE_CASE__ : Tuple=1 , SCREAMING_SNAKE_CASE__ : str="[SEP]" , SCREAMING_SNAKE_CASE__ : List[Any]=False , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False , SCREAMING_SNAKE_CASE__ : Tuple=0 , SCREAMING_SNAKE_CASE__ : int=0 , SCREAMING_SNAKE_CASE__ : str=-1_00 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=0 , SCREAMING_SNAKE_CASE__ : List[Any]=True , ) -> List[InputFeatures]: __lowerCamelCase = {label: i for i, label in enumerate(SCREAMING_SNAKE_CASE__ )} __lowerCamelCase = [] for ex_index, example in enumerate(SCREAMING_SNAKE_CASE__ ): if ex_index % 1_00_00 == 0: logger.info('''Writing example %d of %d''' , SCREAMING_SNAKE_CASE__ , len(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = [] __lowerCamelCase = [] for word, label in zip(example.words , example.labels ): __lowerCamelCase = tokenizer.tokenize(SCREAMING_SNAKE_CASE__ ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(SCREAMING_SNAKE_CASE__ ) > 0: tokens.extend(SCREAMING_SNAKE_CASE__ ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(SCREAMING_SNAKE_CASE__ ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. __lowerCamelCase = tokenizer.num_special_tokens_to_add() if len(SCREAMING_SNAKE_CASE__ ) > max_seq_length - special_tokens_count: __lowerCamelCase = tokens[: (max_seq_length - special_tokens_count)] __lowerCamelCase = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] __lowerCamelCase = [sequence_a_segment_id] * len(SCREAMING_SNAKE_CASE__ ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: __lowerCamelCase = [cls_token] + tokens __lowerCamelCase = [pad_token_label_id] + label_ids __lowerCamelCase = [cls_token_segment_id] + segment_ids __lowerCamelCase = tokenizer.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. __lowerCamelCase = [1 if mask_padding_with_zero else 0] * len(SCREAMING_SNAKE_CASE__ ) # Zero-pad up to the sequence length. __lowerCamelCase = max_seq_length - len(SCREAMING_SNAKE_CASE__ ) if pad_on_left: __lowerCamelCase = ([pad_token] * padding_length) + input_ids __lowerCamelCase = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask __lowerCamelCase = ([pad_token_segment_id] * padding_length) + segment_ids __lowerCamelCase = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length assert len(SCREAMING_SNAKE_CASE__ ) == max_seq_length if ex_index < 5: logger.info('''*** Example ***''' ) logger.info('''guid: %s''' , example.guid ) logger.info('''tokens: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in tokens] ) ) logger.info('''input_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in input_ids] ) ) logger.info('''input_mask: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in input_mask] ) ) logger.info('''segment_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in segment_ids] ) ) logger.info('''label_ids: %s''' , ''' '''.join([str(SCREAMING_SNAKE_CASE__ ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: __lowerCamelCase = None features.append( InputFeatures( input_ids=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , token_type_ids=SCREAMING_SNAKE_CASE__ , label_ids=SCREAMING_SNAKE_CASE__ ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class lowerCAmelCase__ ( __lowercase ): a__ : List[InputFeatures] a__ : int = nn.CrossEntropyLoss().ignore_index def __init__( self : List[str] , SCREAMING_SNAKE_CASE__ : TokenClassificationTask , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Union[str, Any]=False , SCREAMING_SNAKE_CASE__ : Split = Split.train , ) -> Union[str, Any]: # Load data features from cache or dataset file __lowerCamelCase = os.path.join( SCREAMING_SNAKE_CASE__ , '''cached_{}_{}_{}'''.format(mode.value , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE__ ) ) , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. __lowerCamelCase = cached_features_file + '''.lock''' with FileLock(SCREAMING_SNAKE_CASE__ ): if os.path.exists(SCREAMING_SNAKE_CASE__ ) and not overwrite_cache: logger.info(f'''Loading features from cached file {cached_features_file}''' ) __lowerCamelCase = torch.load(SCREAMING_SNAKE_CASE__ ) else: logger.info(f'''Creating features from dataset file at {data_dir}''' ) __lowerCamelCase = token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # TODO clean up all this to leverage built-in features of tokenizers __lowerCamelCase = token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) logger.info(f'''Saving features into cached file {cached_features_file}''' ) torch.save(self.features , SCREAMING_SNAKE_CASE__ ) def __len__( self : Dict ) -> str: return len(self.features ) def __getitem__( self : Any , SCREAMING_SNAKE_CASE__ : Dict ) -> InputFeatures: return self.features[i] if is_tf_available(): import tensorflow as tf class lowerCAmelCase__ : a__ : List[InputFeatures] a__ : int = -100 def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : TokenClassificationTask , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : PreTrainedTokenizer , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Optional[int] = None , SCREAMING_SNAKE_CASE__ : Optional[Any]=False , SCREAMING_SNAKE_CASE__ : Split = Split.train , ) -> List[Any]: __lowerCamelCase = token_classification_task.read_examples_from_file(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) # TODO clean up all this to leverage built-in features of tokenizers __lowerCamelCase = token_classification_task.convert_examples_to_features( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , cls_token_at_end=bool(model_type in ['''xlnet'''] ) , cls_token=tokenizer.cls_token , cls_token_segment_id=2 if model_type in ['''xlnet'''] else 0 , sep_token=tokenizer.sep_token , sep_token_extra=SCREAMING_SNAKE_CASE__ , pad_on_left=bool(tokenizer.padding_side == '''left''' ) , pad_token=tokenizer.pad_token_id , pad_token_segment_id=tokenizer.pad_token_type_id , pad_token_label_id=self.pad_token_label_id , ) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: __lowerCamelCase = tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa}, tf.intaa) , ( {'''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] )}, tf.TensorShape([None] ), ) , ) else: __lowerCamelCase = tf.data.Dataset.from_generator( SCREAMING_SNAKE_CASE__ , ({'''input_ids''': tf.intaa, '''attention_mask''': tf.intaa, '''token_type_ids''': tf.intaa}, tf.intaa) , ( { '''input_ids''': tf.TensorShape([None] ), '''attention_mask''': tf.TensorShape([None] ), '''token_type_ids''': tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) , ) def __A ( self : Union[str, Any] ) -> Union[str, Any]: __lowerCamelCase = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self : List[Any] ) -> Any: return len(self.features ) def __getitem__( self : List[str] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> InputFeatures: return self.features[i]
270
0
"""simple docstring""" import unittest from typing import Dict, List, Optional, Union import numpy as np from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import BridgeTowerImageProcessor class __lowerCamelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self , __UpperCAmelCase , __UpperCAmelCase = True , __UpperCAmelCase = None , __UpperCAmelCase = 32 , __UpperCAmelCase = True , __UpperCAmelCase = 1 / 255 , __UpperCAmelCase = True , __UpperCAmelCase = True , __UpperCAmelCase = [0.48145466, 0.4578275, 0.40821073] , __UpperCAmelCase = [0.26862954, 0.26130258, 0.27577711] , __UpperCAmelCase = True , __UpperCAmelCase=7 , __UpperCAmelCase=30 , __UpperCAmelCase=400 , __UpperCAmelCase=3 , ) -> List[str]: _a = parent _a = do_resize _a = size if size is not None else {'''shortest_edge''': 288} _a = size_divisor _a = do_rescale _a = rescale_factor _a = do_normalize _a = do_center_crop _a = image_mean _a = image_std _a = do_pad _a = batch_size _a = num_channels _a = min_resolution _a = max_resolution def _UpperCAmelCase ( self ) -> List[Any]: return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, "size_divisor": self.size_divisor, } def _UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase=False ) -> int: if not batched: _a = self.size['''shortest_edge'''] _a = image_inputs[0] if isinstance(SCREAMING_SNAKE_CASE__ , Image.Image ): _a , _a = image.size else: _a , _a = image.shape[1], image.shape[2] _a = size / min(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if h < w: _a , _a = size, scale * w else: _a , _a = scale * h, size _a = int((1333 / 800) * size ) if max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) > max_size: _a = max_size / max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) _a = newh * scale _a = neww * scale _a , _a = int(newh + 0.5 ), int(neww + 0.5 ) _a , _a = ( newh // self.size_divisor * self.size_divisor, neww // self.size_divisor * self.size_divisor, ) else: _a = [] for image in image_inputs: _a , _a = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) _a = max(SCREAMING_SNAKE_CASE__ , key=lambda __UpperCAmelCase : item[0] )[0] _a = max(SCREAMING_SNAKE_CASE__ , key=lambda __UpperCAmelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class __lowerCamelCase ( __lowercase , unittest.TestCase ): '''simple docstring''' A_ : Union[str, Any] = BridgeTowerImageProcessor if is_vision_available() else None def _UpperCAmelCase ( self ) -> Union[str, Any]: _a = BridgeTowerImageProcessingTester(self ) @property def _UpperCAmelCase ( self ) -> Optional[Any]: return self.image_processor_tester.prepare_image_processor_dict() def _UpperCAmelCase ( self ) -> int: _a = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''image_mean''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''image_std''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_normalize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_resize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''size''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''size_divisor''' ) ) def _UpperCAmelCase ( self ) -> Optional[int]: pass def _UpperCAmelCase ( self ) -> str: # Initialize image processor _a = self.image_processing_class(**self.image_processor_dict ) # create random PIL images _a = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input _a = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values _a , _a = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _a = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' ).pixel_values _a , _a = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _UpperCAmelCase ( self ) -> List[str]: # Initialize image processor _a = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors _a = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) # Test not batched input _a = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values _a , _a = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _a = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' ).pixel_values _a , _a = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def _UpperCAmelCase ( self ) -> str: # Initialize image processor _a = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors _a = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input _a = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values _a , _a = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched _a = image_processing(SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' ).pixel_values _a , _a = self.image_processor_tester.get_expected_values(SCREAMING_SNAKE_CASE__ , batched=SCREAMING_SNAKE_CASE__ ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , )
320
from typing import Optional from .. import Features, NamedSplit from ..packaged_modules.text.text import Text from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader class lowerCAmelCase__ ( __lowercase ): def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : NestedDataStructureLike[PathLike] , SCREAMING_SNAKE_CASE__ : Optional[NamedSplit] = None , SCREAMING_SNAKE_CASE__ : Optional[Features] = None , SCREAMING_SNAKE_CASE__ : str = None , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Optional[int] = None , **SCREAMING_SNAKE_CASE__ : str , ) -> Union[str, Any]: super().__init__( SCREAMING_SNAKE_CASE__ , split=SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ , keep_in_memory=SCREAMING_SNAKE_CASE__ , streaming=SCREAMING_SNAKE_CASE__ , num_proc=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) __lowerCamelCase = path_or_paths if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else {self.split: path_or_paths} __lowerCamelCase = Text( cache_dir=SCREAMING_SNAKE_CASE__ , data_files=SCREAMING_SNAKE_CASE__ , features=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) def __A ( self : int ) -> Dict: # Build iterable dataset if self.streaming: __lowerCamelCase = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None __lowerCamelCase = None self.builder.download_and_prepare( download_config=SCREAMING_SNAKE_CASE__ , download_mode=SCREAMING_SNAKE_CASE__ , verification_mode=SCREAMING_SNAKE_CASE__ , base_path=SCREAMING_SNAKE_CASE__ , num_proc=self.num_proc , ) __lowerCamelCase = self.builder.as_dataset( split=self.split , verification_mode=SCREAMING_SNAKE_CASE__ , in_memory=self.keep_in_memory ) return dataset
270
0
from ..utils import DummyObject, requires_backends class A ( metaclass=__lowercase ): '''simple docstring''' A__ = ["""torch""", """transformers""", """onnx"""] def __init__(self : Optional[int] , *_UpperCAmelCase : int , **_UpperCAmelCase : List[Any] ) -> List[Any]: """simple docstring""" requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCamelCase__ (cls : Dict , *_UpperCAmelCase : Optional[Any] , **_UpperCAmelCase : Optional[Any] ) -> Any: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCamelCase__ (cls : List[Any] , *_UpperCAmelCase : Optional[int] , **_UpperCAmelCase : Optional[Any] ) -> Any: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class A ( metaclass=__lowercase ): '''simple docstring''' A__ = ["""torch""", """transformers""", """onnx"""] def __init__(self : Tuple , *_UpperCAmelCase : Any , **_UpperCAmelCase : Optional[Any] ) -> List[Any]: """simple docstring""" requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCamelCase__ (cls : Any , *_UpperCAmelCase : List[Any] , **_UpperCAmelCase : int ) -> Tuple: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCamelCase__ (cls : Dict , *_UpperCAmelCase : List[Any] , **_UpperCAmelCase : Optional[Any] ) -> Dict: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class A ( metaclass=__lowercase ): '''simple docstring''' A__ = ["""torch""", """transformers""", """onnx"""] def __init__(self : Tuple , *_UpperCAmelCase : Dict , **_UpperCAmelCase : Dict ) -> Optional[int]: """simple docstring""" requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCamelCase__ (cls : List[str] , *_UpperCAmelCase : Optional[Any] , **_UpperCAmelCase : Tuple ) -> List[Any]: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCamelCase__ (cls : List[Any] , *_UpperCAmelCase : Tuple , **_UpperCAmelCase : Union[str, Any] ) -> Optional[int]: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class A ( metaclass=__lowercase ): '''simple docstring''' A__ = ["""torch""", """transformers""", """onnx"""] def __init__(self : Optional[int] , *_UpperCAmelCase : List[Any] , **_UpperCAmelCase : List[Any] ) -> Tuple: """simple docstring""" requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCamelCase__ (cls : Dict , *_UpperCAmelCase : Optional[Any] , **_UpperCAmelCase : Optional[int] ) -> Optional[int]: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCamelCase__ (cls : str , *_UpperCAmelCase : Optional[Any] , **_UpperCAmelCase : Union[str, Any] ) -> List[Any]: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class A ( metaclass=__lowercase ): '''simple docstring''' A__ = ["""torch""", """transformers""", """onnx"""] def __init__(self : Any , *_UpperCAmelCase : Tuple , **_UpperCAmelCase : List[Any] ) -> List[str]: """simple docstring""" requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCamelCase__ (cls : Dict , *_UpperCAmelCase : int , **_UpperCAmelCase : Union[str, Any] ) -> Any: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCamelCase__ (cls : Dict , *_UpperCAmelCase : List[Any] , **_UpperCAmelCase : Union[str, Any] ) -> int: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) class A ( metaclass=__lowercase ): '''simple docstring''' A__ = ["""torch""", """transformers""", """onnx"""] def __init__(self : int , *_UpperCAmelCase : Union[str, Any] , **_UpperCAmelCase : Dict ) -> str: """simple docstring""" requires_backends(self , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCamelCase__ (cls : Tuple , *_UpperCAmelCase : int , **_UpperCAmelCase : List[Any] ) -> str: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] ) @classmethod def lowerCamelCase__ (cls : str , *_UpperCAmelCase : Optional[Any] , **_UpperCAmelCase : int ) -> str: """simple docstring""" requires_backends(cls , ["""torch""", """transformers""", """onnx"""] )
305
from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version(">=", "4.25.0")): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
270
0
'''simple docstring''' from __future__ import annotations from fractions import Fraction def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' return ( num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den ) def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : int ): '''simple docstring''' UpperCAmelCase__ = [] UpperCAmelCase__ = 11 UpperCAmelCase__ = int("""1""" + """0""" * digit_len ) for num in range(__lowerCAmelCase , __lowerCAmelCase ): while den <= 99: if (num != den) and (num % 10 == den // 10) and (den % 10 != 0): if is_digit_cancelling(__lowerCAmelCase , __lowerCAmelCase ): solutions.append(F'''{num}/{den}''' ) den += 1 num += 1 UpperCAmelCase__ = 10 return solutions def _UpperCamelCase ( SCREAMING_SNAKE_CASE__ : int = 2 ): '''simple docstring''' UpperCAmelCase__ = 1.0 for fraction in fraction_list(__lowerCAmelCase ): UpperCAmelCase__ = Fraction(__lowerCAmelCase ) result *= frac.denominator / frac.numerator return int(__lowerCAmelCase ) if __name__ == "__main__": print(solution())
346
import sacrebleu as scb from packaging import version from sacrebleu import CHRF import datasets SCREAMING_SNAKE_CASE__ : Union[str, Any] = "\\n@inproceedings{popovic-2015-chrf,\n title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",\n month = sep,\n year = \"2015\",\n address = \"Lisbon, Portugal\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W15-3049\",\n doi = \"10.18653/v1/W15-3049\",\n pages = \"392--395\",\n}\n@inproceedings{popovic-2017-chrf,\n title = \"chr{F}++: words helping character n-grams\",\n author = \"Popovi{\'c}, Maja\",\n booktitle = \"Proceedings of the Second Conference on Machine Translation\",\n month = sep,\n year = \"2017\",\n address = \"Copenhagen, Denmark\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://aclanthology.org/W17-4770\",\n doi = \"10.18653/v1/W17-4770\",\n pages = \"612--618\",\n}\n@inproceedings{post-2018-call,\n title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n author = \"Post, Matt\",\n booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n month = oct,\n year = \"2018\",\n address = \"Belgium, Brussels\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W18-6319\",\n pages = \"186--191\",\n}\n" SCREAMING_SNAKE_CASE__ : int = "\\nChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,\nand ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation\nthat is already present in sacrebleu.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.\n" SCREAMING_SNAKE_CASE__ : Optional[Any] = "\nProduces ChrF(++) scores for hypotheses given reference translations.\n\nArgs:\n predictions (list of str): The predicted sentences.\n references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.\n char_order (int): Character n-gram order. Defaults to `6`.\n word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.\n beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.\n lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.\n whitespace (bool): If `True`, include whitespaces when extracting character n-grams.\n eps_smoothing (bool): If `True`, applies epsilon smoothing similar\n to reference chrF++.py, NLTK and Moses implementations. If `False`,\n it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.\n\nReturns:\n 'score' (float): The chrF (chrF++) score,\n 'char_order' (int): The character n-gram order,\n 'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,\n 'beta' (int): Determine the importance of recall w.r.t precision\n\nExamples:\n Example 1--a simple example of calculating chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction, references=reference)\n >>> print(results)\n {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}\n\n Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2)\n >>> print(results)\n {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}\n\n Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:\n >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n >>> chrf = datasets.load_metric(\"chrf\")\n >>> results = chrf.compute(predictions=prediction,\n ... references=reference,\n ... word_order=2,\n ... lowercase=True)\n >>> print(results)\n {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class lowerCAmelCase__ ( datasets.Metric ): def __A ( self : Dict ) -> Tuple: if version.parse(scb.__version__ ) < version.parse('''1.4.12''' ): raise ImportWarning( '''To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n''' '''You can install it with `pip install "sacrebleu>=1.4.12"`.''' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage='''https://github.com/mjpost/sacreBLEU#chrf--chrf''' , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Value('''string''' , id='''sequence''' ), '''references''': datasets.Sequence(datasets.Value('''string''' , id='''sequence''' ) , id='''references''' ), } ) , codebase_urls=['''https://github.com/mjpost/sacreBLEU#chrf--chrf'''] , reference_urls=[ '''https://github.com/m-popovic/chrF''', ] , ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : int = CHRF.CHAR_ORDER , SCREAMING_SNAKE_CASE__ : int = CHRF.WORD_ORDER , SCREAMING_SNAKE_CASE__ : int = CHRF.BETA , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : bool = False , ) -> Optional[Any]: __lowerCamelCase = len(references[0] ) if any(len(SCREAMING_SNAKE_CASE__ ) != references_per_prediction for refs in references ): raise ValueError('''Sacrebleu requires the same number of references for each prediction''' ) __lowerCamelCase = [[refs[i] for refs in references] for i in range(SCREAMING_SNAKE_CASE__ )] __lowerCamelCase = CHRF(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = sb_chrf.corpus_score(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return { "score": output.score, "char_order": output.char_order, "word_order": output.word_order, "beta": output.beta, }
270
0
class _lowercase : """simple docstring""" def __init__( self : int , __lowerCamelCase : List[str] ): '''simple docstring''' lowerCamelCase__ : List[str] = val lowerCamelCase__ : Optional[Any] = None lowerCamelCase__ : List[Any] = None def lowerCAmelCase ( self : str , __lowerCamelCase : str ): '''simple docstring''' if self.val: if val < self.val: if self.left is None: lowerCamelCase__ : Dict = Node(SCREAMING_SNAKE_CASE__ ) else: self.left.insert(SCREAMING_SNAKE_CASE__ ) elif val > self.val: if self.right is None: lowerCamelCase__ : Optional[Any] = Node(SCREAMING_SNAKE_CASE__ ) else: self.right.insert(SCREAMING_SNAKE_CASE__ ) else: lowerCamelCase__ : Tuple = val def lowercase_ ( _A : Dict , _A : int ): """simple docstring""" if root: inorder(root.left , __lowerCAmelCase ) res.append(root.val ) inorder(root.right , __lowerCAmelCase ) def lowercase_ ( _A : List[Any] ): """simple docstring""" if len(__lowerCAmelCase ) == 0: return arr lowerCamelCase__ : str = Node(arr[0] ) for i in range(1 , len(__lowerCAmelCase ) ): root.insert(arr[i] ) # Traverse BST in order. lowerCamelCase__ : Optional[int] = [] inorder(__lowerCAmelCase , __lowerCAmelCase ) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
184
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : List[Any] = { "configuration_resnet": ["RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "ResNetConfig", "ResNetOnnxConfig"] } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "ResNetForImageClassification", "ResNetModel", "ResNetPreTrainedModel", "ResNetBackbone", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = [ "TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFResNetForImageClassification", "TFResNetModel", "TFResNetPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ "FlaxResNetForImageClassification", "FlaxResNetModel", "FlaxResNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_resnet import RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ResNetConfig, ResNetOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_resnet import ( RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, ResNetBackbone, ResNetForImageClassification, ResNetModel, ResNetPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_resnet import ( TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFResNetForImageClassification, TFResNetModel, TFResNetPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel, FlaxResNetPreTrainedModel else: import sys SCREAMING_SNAKE_CASE__ : Any = _LazyModule(__name__, globals()["__file__"], _import_structure)
270
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) lowerCAmelCase = { "configuration_efficientformer": [ "EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "EfficientFormerConfig", ] } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase = ["EfficientFormerImageProcessor"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase = [ "EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "EfficientFormerForImageClassification", "EfficientFormerForImageClassificationWithTeacher", "EfficientFormerModel", "EfficientFormerPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase = [ "TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TFEfficientFormerForImageClassification", "TFEfficientFormerForImageClassificationWithTeacher", "TFEfficientFormerModel", "TFEfficientFormerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_efficientformer import EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientFormerConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_efficientformer import EfficientFormerImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_efficientformer import ( EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, EfficientFormerForImageClassification, EfficientFormerForImageClassificationWithTeacher, EfficientFormerModel, EfficientFormerPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_efficientformer import ( TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TFEfficientFormerForImageClassification, TFEfficientFormerForImageClassificationWithTeacher, TFEfficientFormerModel, TFEfficientFormerPreTrainedModel, ) else: import sys lowerCAmelCase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
126
import unittest import numpy as np import requests from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: SCREAMING_SNAKE_CASE__ : str = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class lowerCAmelCase__ ( unittest.TestCase ): def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[Any]=7 , SCREAMING_SNAKE_CASE__ : List[str]=3 , SCREAMING_SNAKE_CASE__ : Tuple=18 , SCREAMING_SNAKE_CASE__ : int=30 , SCREAMING_SNAKE_CASE__ : Any=4_00 , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : str=True , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , ) -> Union[str, Any]: __lowerCamelCase = size if size is not None else {'''height''': 20, '''width''': 20} __lowerCamelCase = parent __lowerCamelCase = batch_size __lowerCamelCase = num_channels __lowerCamelCase = image_size __lowerCamelCase = min_resolution __lowerCamelCase = max_resolution __lowerCamelCase = size __lowerCamelCase = do_normalize __lowerCamelCase = do_convert_rgb __lowerCamelCase = [5_12, 10_24, 20_48, 40_96] __lowerCamelCase = patch_size if patch_size is not None else {'''height''': 16, '''width''': 16} def __A ( self : Union[str, Any] ) -> Union[str, Any]: return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def __A ( self : int ) -> Any: __lowerCamelCase = '''https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg''' __lowerCamelCase = Image.open(requests.get(SCREAMING_SNAKE_CASE__ , stream=SCREAMING_SNAKE_CASE__ ).raw ).convert('''RGB''' ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`.""" , ) @require_torch @require_vision class lowerCAmelCase__ ( __lowercase , unittest.TestCase ): a__ : Dict = PixaStructImageProcessor if is_vision_available() else None def __A ( self : Optional[Any] ) -> List[Any]: __lowerCamelCase = PixaStructImageProcessingTester(self ) @property def __A ( self : Optional[int] ) -> Optional[int]: return self.image_processor_tester.prepare_image_processor_dict() def __A ( self : Tuple ) -> Dict: __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_normalize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_convert_rgb''' ) ) def __A ( self : int ) -> str: __lowerCamelCase = self.image_processor_tester.prepare_dummy_image() __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) __lowerCamelCase = 20_48 __lowerCamelCase = image_processor(SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) ) def __A ( self : Union[str, Any] ) -> Dict: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : Dict ) -> str: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 __lowerCamelCase = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(SCREAMING_SNAKE_CASE__ ): __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches __lowerCamelCase = '''Hello''' __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ , header_text=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ , header_text=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : List[str] ) -> Any: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , numpify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , np.ndarray ) __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __A ( self : Tuple ) -> List[str]: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ , torchify=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , torch.Tensor ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason="""`Pix2StructImageProcessor` requires `torch>=1.11.0`.""" , ) @require_torch @require_vision class lowerCAmelCase__ ( __lowercase , unittest.TestCase ): a__ : Any = PixaStructImageProcessor if is_vision_available() else None def __A ( self : Union[str, Any] ) -> Optional[Any]: __lowerCamelCase = PixaStructImageProcessingTester(self , num_channels=4 ) __lowerCamelCase = 3 @property def __A ( self : List[Any] ) -> Optional[Any]: return self.image_processor_tester.prepare_image_processor_dict() def __A ( self : Union[str, Any] ) -> List[str]: __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_normalize''' ) ) self.assertTrue(hasattr(SCREAMING_SNAKE_CASE__ , '''do_convert_rgb''' ) ) def __A ( self : Optional[int] ) -> str: # Initialize image_processor __lowerCamelCase = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowerCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=SCREAMING_SNAKE_CASE__ ) for image in image_inputs: self.assertIsInstance(SCREAMING_SNAKE_CASE__ , Image.Image ) # Test not batched input __lowerCamelCase = ( (self.image_processor_tester.patch_size['''height'''] * self.image_processor_tester.patch_size['''width''']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input __lowerCamelCase = image_processor( image_inputs[0] , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched __lowerCamelCase = image_processor( SCREAMING_SNAKE_CASE__ , return_tensors='''pt''' , max_patches=SCREAMING_SNAKE_CASE__ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
270
0
"""simple docstring""" from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging _lowercase : Optional[int] = logging.get_logger(__name__) _lowercase : Optional[Any] = { "facebook/deit-base-distilled-patch16-224": ( "https://huggingface.co/facebook/deit-base-patch16-224/resolve/main/config.json" ), # See all DeiT models at https://huggingface.co/models?filter=deit } class __SCREAMING_SNAKE_CASE ( __lowercase ): '''simple docstring''' _a = """deit""" def __init__( self : str, lowerCamelCase : Dict=768, lowerCamelCase : Optional[int]=12, lowerCamelCase : Union[str, Any]=12, lowerCamelCase : Optional[Any]=3072, lowerCamelCase : Dict="gelu", lowerCamelCase : Any=0.0, lowerCamelCase : Optional[int]=0.0, lowerCamelCase : List[str]=0.02, lowerCamelCase : int=1E-12, lowerCamelCase : Optional[int]=224, lowerCamelCase : Any=16, lowerCamelCase : Any=3, lowerCamelCase : Tuple=True, lowerCamelCase : str=16, **lowerCamelCase : Any, )-> Dict: super().__init__(**SCREAMING_SNAKE_CASE__ ) lowerCamelCase__ : str =hidden_size lowerCamelCase__ : Dict =num_hidden_layers lowerCamelCase__ : str =num_attention_heads lowerCamelCase__ : Dict =intermediate_size lowerCamelCase__ : int =hidden_act lowerCamelCase__ : Union[str, Any] =hidden_dropout_prob lowerCamelCase__ : Dict =attention_probs_dropout_prob lowerCamelCase__ : List[str] =initializer_range lowerCamelCase__ : Optional[int] =layer_norm_eps lowerCamelCase__ : List[Any] =image_size lowerCamelCase__ : int =patch_size lowerCamelCase__ : Optional[int] =num_channels lowerCamelCase__ : Optional[int] =qkv_bias lowerCamelCase__ : int =encoder_stride class __SCREAMING_SNAKE_CASE ( __lowercase ): '''simple docstring''' _a = version.parse('1.11' ) @property def snake_case ( self : List[str] )-> Mapping[str, Mapping[int, str]]: return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def snake_case ( self : Dict )-> float: return 1E-4
238
import shutil import tempfile import unittest from unittest.mock import patch from transformers import ( DefaultFlowCallback, IntervalStrategy, PrinterCallback, ProgressCallback, Trainer, TrainerCallback, TrainingArguments, is_torch_available, ) from transformers.testing_utils import require_torch if is_torch_available(): from transformers.trainer import DEFAULT_CALLBACKS from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel class lowerCAmelCase__ ( __lowercase ): def __init__( self : int ) -> Optional[int]: __lowerCamelCase = [] def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> Tuple: self.events.append('''on_init_end''' ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Any: self.events.append('''on_train_begin''' ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Dict , **SCREAMING_SNAKE_CASE__ : int ) -> Any: self.events.append('''on_train_end''' ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> int: self.events.append('''on_epoch_begin''' ) def __A ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : Optional[Any] , **SCREAMING_SNAKE_CASE__ : Tuple ) -> Optional[Any]: self.events.append('''on_epoch_end''' ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : str ) -> List[Any]: self.events.append('''on_step_begin''' ) def __A ( self : Any , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Any , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: self.events.append('''on_step_end''' ) def __A ( self : int , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , **SCREAMING_SNAKE_CASE__ : List[Any] ) -> Union[str, Any]: self.events.append('''on_evaluate''' ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str , **SCREAMING_SNAKE_CASE__ : str ) -> str: self.events.append('''on_predict''' ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[int] , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Tuple: self.events.append('''on_save''' ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : List[str] ) -> List[str]: self.events.append('''on_log''' ) def __A ( self : int , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: self.events.append('''on_prediction_step''' ) @require_torch class lowerCAmelCase__ ( unittest.TestCase ): def __A ( self : Union[str, Any] ) -> Optional[Any]: __lowerCamelCase = tempfile.mkdtemp() def __A ( self : int ) -> List[str]: shutil.rmtree(self.output_dir ) def __A ( self : Tuple , SCREAMING_SNAKE_CASE__ : List[Any]=0 , SCREAMING_SNAKE_CASE__ : Any=0 , SCREAMING_SNAKE_CASE__ : List[str]=64 , SCREAMING_SNAKE_CASE__ : Optional[int]=64 , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Optional[int]=False , **SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> Union[str, Any]: # disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure # its set to False since the tests later on depend on its value. __lowerCamelCase = RegressionDataset(length=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionDataset(length=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionModelConfig(a=SCREAMING_SNAKE_CASE__ , b=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = RegressionPreTrainedModel(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = TrainingArguments(self.output_dir , disable_tqdm=SCREAMING_SNAKE_CASE__ , report_to=[] , **SCREAMING_SNAKE_CASE__ ) return Trainer( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , train_dataset=SCREAMING_SNAKE_CASE__ , eval_dataset=SCREAMING_SNAKE_CASE__ , callbacks=SCREAMING_SNAKE_CASE__ , ) def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : str ) -> Optional[int]: self.assertEqual(len(SCREAMING_SNAKE_CASE__ ) , len(SCREAMING_SNAKE_CASE__ ) ) # Order doesn't matter __lowerCamelCase = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : cb.__name__ if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cb.__class__.__name__ ) __lowerCamelCase = sorted(SCREAMING_SNAKE_CASE__ , key=lambda SCREAMING_SNAKE_CASE__ : cb.__name__ if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cb.__class__.__name__ ) for cba, cba in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(SCREAMING_SNAKE_CASE__ , cba.__class__ ) elif not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): self.assertEqual(cba.__class__ , SCREAMING_SNAKE_CASE__ ) else: self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Tuple: __lowerCamelCase = ['''on_init_end''', '''on_train_begin'''] __lowerCamelCase = 0 __lowerCamelCase = len(trainer.get_eval_dataloader() ) __lowerCamelCase = ['''on_prediction_step'''] * len(trainer.get_eval_dataloader() ) + ['''on_log''', '''on_evaluate'''] for _ in range(trainer.state.num_train_epochs ): expected_events.append('''on_epoch_begin''' ) for _ in range(SCREAMING_SNAKE_CASE__ ): step += 1 expected_events += ["on_step_begin", "on_step_end"] if step % trainer.args.logging_steps == 0: expected_events.append('''on_log''' ) if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0: expected_events += evaluation_events.copy() if step % trainer.args.save_steps == 0: expected_events.append('''on_save''' ) expected_events.append('''on_epoch_end''' ) if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH: expected_events += evaluation_events.copy() expected_events += ["on_log", "on_train_end"] return expected_events def __A ( self : Union[str, Any] ) -> int: __lowerCamelCase = self.get_trainer() __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [ProgressCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # Callbacks passed at init are added to the default callbacks __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] ) expected_callbacks.append(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback __lowerCamelCase = self.get_trainer(disable_tqdm=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [PrinterCallback] self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) def __A ( self : List[Any] ) -> str: __lowerCamelCase = DEFAULT_CALLBACKS.copy() + [ProgressCallback] __lowerCamelCase = self.get_trainer() # We can add, pop, or remove by class name trainer.remove_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.remove(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.pop_callback(SCREAMING_SNAKE_CASE__ ) self.assertEqual(cb.__class__ , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) trainer.add_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.insert(0 , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) # We can also add, pop, or remove by instance __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.callback_handler.callbacks[0] trainer.remove_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.remove(SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer() __lowerCamelCase = trainer.callback_handler.callbacks[0] __lowerCamelCase = trainer.pop_callback(SCREAMING_SNAKE_CASE__ ) self.assertEqual(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) trainer.add_callback(SCREAMING_SNAKE_CASE__ ) expected_callbacks.insert(0 , SCREAMING_SNAKE_CASE__ ) self.check_callbacks_equality(trainer.callback_handler.callbacks , SCREAMING_SNAKE_CASE__ ) def __A ( self : Union[str, Any] ) -> Any: import warnings # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested warnings.simplefilter(action='''ignore''' , category=SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # Independent log/save/eval __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , logging_steps=5 ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , save_steps=5 ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , eval_steps=5 , evaluation_strategy='''steps''' ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) __lowerCamelCase = self.get_trainer(callbacks=[MyTestTrainerCallback] , evaluation_strategy='''epoch''' ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # A bit of everything __lowerCamelCase = self.get_trainer( callbacks=[MyTestTrainerCallback] , logging_steps=3 , save_steps=10 , eval_steps=5 , evaluation_strategy='''steps''' , ) trainer.train() __lowerCamelCase = trainer.callback_handler.callbacks[-2].events self.assertEqual(SCREAMING_SNAKE_CASE__ , self.get_expected_events(SCREAMING_SNAKE_CASE__ ) ) # warning should be emitted for duplicated callbacks with patch('''transformers.trainer_callback.logger.warning''' ) as warn_mock: __lowerCamelCase = self.get_trainer( callbacks=[MyTestTrainerCallback, MyTestTrainerCallback] , ) assert str(SCREAMING_SNAKE_CASE__ ) in warn_mock.call_args[0][0]
270
0
from .glue import GlueDataset, GlueDataTrainingArguments from .language_modeling import ( LineByLineTextDataset, LineByLineWithRefDataset, LineByLineWithSOPTextDataset, TextDataset, TextDatasetForNextSentencePrediction, ) from .squad import SquadDataset, SquadDataTrainingArguments
187
import numpy as np from cva import destroyAllWindows, imread, imshow, waitKey class lowerCAmelCase__ : def __init__( self : Any , SCREAMING_SNAKE_CASE__ : List[str] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> Dict: if dst_width < 0 or dst_height < 0: raise ValueError('''Destination width/height should be > 0''' ) __lowerCamelCase = img __lowerCamelCase = img.shape[1] __lowerCamelCase = img.shape[0] __lowerCamelCase = dst_width __lowerCamelCase = dst_height __lowerCamelCase = self.src_w / self.dst_w __lowerCamelCase = self.src_h / self.dst_h __lowerCamelCase = __lowerCamelCase = ( np.ones((self.dst_h, self.dst_w, 3) , np.uinta ) * 2_55 ) def __A ( self : List[Any] ) -> str: for i in range(self.dst_h ): for j in range(self.dst_w ): __lowerCamelCase = self.img[self.get_y(SCREAMING_SNAKE_CASE__ )][self.get_x(SCREAMING_SNAKE_CASE__ )] def __A ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> int: return int(self.ratio_x * x ) def __A ( self : str , SCREAMING_SNAKE_CASE__ : int ) -> int: return int(self.ratio_y * y ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = 800, 600 SCREAMING_SNAKE_CASE__ : int = imread("image_data/lena.jpg", 1) SCREAMING_SNAKE_CASE__ : Union[str, Any] = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( F'Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}', n.output ) waitKey(0) destroyAllWindows()
270
0
import fire from transformers import AutoConfig, AutoModelForSeqaSeqLM, AutoTokenizer def __lowerCamelCase ( snake_case__ ,snake_case__ ,**snake_case__ ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(__lowerCAmelCase ,**__lowerCAmelCase ) _SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM.from_config(__lowerCAmelCase ) model.save_pretrained(__lowerCAmelCase ) AutoTokenizer.from_pretrained(__lowerCAmelCase ).save_pretrained(__lowerCAmelCase ) return model if __name__ == "__main__": fire.Fire(save_randomly_initialized_version)
306
from queue import PriorityQueue from typing import Any import numpy as np def __magic_name__ ( __lowerCAmelCase : dict , __lowerCAmelCase : str , __lowerCAmelCase : set , __lowerCAmelCase : set , __lowerCAmelCase : dict , __lowerCAmelCase : dict , __lowerCAmelCase : PriorityQueue , __lowerCAmelCase : dict , __lowerCAmelCase : float | int , ) -> float | int: for nxt, d in graph[v]: if nxt in visited_forward: continue __lowerCamelCase = cst_fwd.get(__lowerCAmelCase , np.inf ) __lowerCamelCase = cst_fwd[v] + d if new_cost_f < old_cost_f: queue.put((new_cost_f, nxt) ) __lowerCamelCase = new_cost_f __lowerCamelCase = v if nxt in visited_backward: if cst_fwd[v] + d + cst_bwd[nxt] < shortest_distance: __lowerCamelCase = cst_fwd[v] + d + cst_bwd[nxt] return shortest_distance def __magic_name__ ( __lowerCAmelCase : str , __lowerCAmelCase : str , __lowerCAmelCase : dict , __lowerCAmelCase : dict ) -> int: __lowerCamelCase = -1 __lowerCamelCase = set() __lowerCamelCase = set() __lowerCamelCase = {source: 0} __lowerCamelCase = {destination: 0} __lowerCamelCase = {source: None} __lowerCamelCase = {destination: None} __lowerCamelCase = PriorityQueue() __lowerCamelCase = PriorityQueue() __lowerCamelCase = np.inf queue_forward.put((0, source) ) queue_backward.put((0, destination) ) if source == destination: return 0 while not queue_forward.empty() and not queue_backward.empty(): __lowerCamelCase , __lowerCamelCase = queue_forward.get() visited_forward.add(__lowerCAmelCase ) __lowerCamelCase , __lowerCamelCase = queue_backward.get() visited_backward.add(__lowerCAmelCase ) __lowerCamelCase = pass_and_relaxation( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) __lowerCamelCase = pass_and_relaxation( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , ) if cst_fwd[v_fwd] + cst_bwd[v_bwd] >= shortest_distance: break if shortest_distance != np.inf: __lowerCamelCase = shortest_distance return shortest_path_distance SCREAMING_SNAKE_CASE__ : List[Any] = { "B": [["C", 1]], "C": [["D", 1]], "D": [["F", 1]], "E": [["B", 1], ["G", 2]], "F": [], "G": [["F", 1]], } SCREAMING_SNAKE_CASE__ : Optional[int] = { "B": [["E", 1]], "C": [["B", 1]], "D": [["C", 1]], "F": [["D", 1], ["G", 1]], "E": [[None, np.inf]], "G": [["E", 2]], } if __name__ == "__main__": import doctest doctest.testmod()
270
0
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool class a_ ( __lowercase ): __A = """philschmid/bart-large-cnn-samsum""" __A = ( """This is a tool that summarizes an English text. It takes an input `text` containing the text to summarize, """ """and returns a summary of the text.""" ) __A = """summarizer""" __A = AutoTokenizer __A = AutoModelForSeqaSeqLM __A = ["""text"""] __A = ["""text"""] def lowercase__ ( self : Tuple , lowercase : str ): """simple docstring""" return self.pre_processor(SCREAMING_SNAKE_CASE__ , return_tensors="pt" , truncation=SCREAMING_SNAKE_CASE__ ) def lowercase__ ( self : Any , lowercase : int ): """simple docstring""" return self.model.generate(**SCREAMING_SNAKE_CASE__ )[0] def lowercase__ ( self : Union[str, Any] , lowercase : str ): """simple docstring""" return self.pre_processor.decode(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ , clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE__ )
223
from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar SCREAMING_SNAKE_CASE__ : List[Any] = TypeVar("T") def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (position - 1) // 2 def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (2 * position) + 1 def __magic_name__ ( __lowerCAmelCase : int ) -> int: return (2 * position) + 2 class lowerCAmelCase__ ( Generic[T] ): def __init__( self : List[str] ) -> None: __lowerCamelCase = [] __lowerCamelCase = {} __lowerCamelCase = 0 def __len__( self : Optional[int] ) -> int: return self.elements def __repr__( self : Optional[int] ) -> str: return str(self.heap ) def __A ( self : Union[str, Any] ) -> bool: # Check if the priority queue is empty return self.elements == 0 def __A ( self : str , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Add an element with given priority to the queue self.heap.append((elem, weight) ) __lowerCamelCase = self.elements self.elements += 1 self._bubble_up(SCREAMING_SNAKE_CASE__ ) def __A ( self : Any ) -> T: # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) __lowerCamelCase , __lowerCamelCase = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __lowerCamelCase , __lowerCamelCase = self.heap[0] self._bubble_down(SCREAMING_SNAKE_CASE__ ) return elem def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Update the weight of the given key __lowerCamelCase = self.position_map[elem] __lowerCamelCase = (elem, weight) if position > 0: __lowerCamelCase = get_parent_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase = self.heap[parent_position] if parent_weight > weight: self._bubble_up(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: self._bubble_down(SCREAMING_SNAKE_CASE__ ) def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Place a node at the proper position (upward movement) [to be used internally # only] __lowerCamelCase = self.position_map[elem] if curr_pos == 0: return None __lowerCamelCase = get_parent_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase , __lowerCamelCase = self.heap[curr_pos] __lowerCamelCase , __lowerCamelCase = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_up(SCREAMING_SNAKE_CASE__ ) return None def __A ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Place a node at the proper position (downward movement) [to be used # internally only] __lowerCamelCase = self.position_map[elem] __lowerCamelCase , __lowerCamelCase = self.heap[curr_pos] __lowerCamelCase = get_child_left_position(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = get_child_right_position(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements and child_right_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_left_position] __lowerCamelCase , __lowerCamelCase = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) if child_left_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) else: return None if child_right_position < self.elements: __lowerCamelCase , __lowerCamelCase = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) return self._bubble_down(SCREAMING_SNAKE_CASE__ ) return None def __A ( self : List[Any] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: # Swap the nodes at the given positions __lowerCamelCase = self.heap[nodea_pos][0] __lowerCamelCase = self.heap[nodea_pos][0] __lowerCamelCase , __lowerCamelCase = ( self.heap[nodea_pos], self.heap[nodea_pos], ) __lowerCamelCase = nodea_pos __lowerCamelCase = nodea_pos class lowerCAmelCase__ ( Generic[T] ): def __init__( self : Tuple ) -> None: __lowerCamelCase = {} __lowerCamelCase = 0 def __repr__( self : Optional[int] ) -> str: return str(self.connections ) def __len__( self : List[str] ) -> int: return self.nodes def __A ( self : List[str] , SCREAMING_SNAKE_CASE__ : T ) -> None: # Add a node in the graph if it is not in the graph if node not in self.connections: __lowerCamelCase = {} self.nodes += 1 def __A ( self : Dict , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : T , SCREAMING_SNAKE_CASE__ : int ) -> None: # Add an edge between 2 nodes in the graph self.add_node(SCREAMING_SNAKE_CASE__ ) self.add_node(SCREAMING_SNAKE_CASE__ ) __lowerCamelCase = weight __lowerCamelCase = weight def __magic_name__ ( __lowerCAmelCase : GraphUndirectedWeighted[T] , ) -> tuple[dict[T, int], dict[T, T | None]]: __lowerCamelCase = {node: maxsize for node in graph.connections} __lowerCamelCase = {node: None for node in graph.connections} __lowerCamelCase = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(__lowerCAmelCase , __lowerCAmelCase ) if priority_queue.is_empty(): return dist, parent # initialization __lowerCamelCase = priority_queue.extract_min() __lowerCamelCase = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __lowerCamelCase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(__lowerCAmelCase , dist[neighbour] ) __lowerCamelCase = node # running prim's algorithm while not priority_queue.is_empty(): __lowerCamelCase = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __lowerCamelCase = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(__lowerCAmelCase , dist[neighbour] ) __lowerCamelCase = node return dist, parent
270
0
'''simple docstring''' def UpperCamelCase ( _lowerCamelCase : list , _lowerCamelCase : int = 0 ): A__ = length or len(__lowerCAmelCase ) A__ = False for i in range(length - 1 ): if list_data[i] > list_data[i + 1]: A__, A__ = list_data[i + 1], list_data[i] A__ = True return list_data if not swapped else bubble_sort(__lowerCAmelCase , length - 1 ) if __name__ == "__main__": import doctest doctest.testmod()
237
from __future__ import annotations from statistics import mean def __magic_name__ ( __lowerCAmelCase : list[int] , __lowerCAmelCase : list[int] , __lowerCAmelCase : int ) -> list[int]: __lowerCamelCase = [0] * no_of_processes __lowerCamelCase = [0] * no_of_processes # Initialize remaining_time to waiting_time. for i in range(__lowerCAmelCase ): __lowerCamelCase = burst_time[i] __lowerCamelCase = [] __lowerCamelCase = 0 __lowerCamelCase = 0 # When processes are not completed, # A process whose arrival time has passed \ # and has remaining execution time is put into the ready_process. # The shortest process in the ready_process, target_process is executed. while completed != no_of_processes: __lowerCamelCase = [] __lowerCamelCase = -1 for i in range(__lowerCAmelCase ): if (arrival_time[i] <= total_time) and (remaining_time[i] > 0): ready_process.append(__lowerCAmelCase ) if len(__lowerCAmelCase ) > 0: __lowerCamelCase = ready_process[0] for i in ready_process: if remaining_time[i] < remaining_time[target_process]: __lowerCamelCase = i total_time += burst_time[target_process] completed += 1 __lowerCamelCase = 0 __lowerCamelCase = ( total_time - arrival_time[target_process] - burst_time[target_process] ) else: total_time += 1 return waiting_time def __magic_name__ ( __lowerCAmelCase : list[int] , __lowerCAmelCase : int , __lowerCAmelCase : list[int] ) -> list[int]: __lowerCamelCase = [0] * no_of_processes for i in range(__lowerCAmelCase ): __lowerCamelCase = burst_time[i] + waiting_time[i] return turn_around_time if __name__ == "__main__": print("[TEST CASE 01]") SCREAMING_SNAKE_CASE__ : Tuple = 4 SCREAMING_SNAKE_CASE__ : Optional[int] = [2, 5, 3, 7] SCREAMING_SNAKE_CASE__ : List[str] = [0, 0, 0, 0] SCREAMING_SNAKE_CASE__ : str = calculate_waitingtime(arrival_time, burst_time, no_of_processes) SCREAMING_SNAKE_CASE__ : Union[str, Any] = calculate_turnaroundtime( burst_time, no_of_processes, waiting_time ) # Printing the Result print("PID\tBurst Time\tArrival Time\tWaiting Time\tTurnaround Time") for i, process_id in enumerate(list(range(1, 5))): print( F'{process_id}\t{burst_time[i]}\t\t\t{arrival_time[i]}\t\t\t\t' F'{waiting_time[i]}\t\t\t\t{turn_around_time[i]}' ) print(F'\nAverage waiting time = {mean(waiting_time):.5f}') print(F'Average turnaround time = {mean(turn_around_time):.5f}')
270
0
import os import re 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 lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = {"vocab_file": "spiece.model"} lowerCAmelCase__ = { "vocab_file": { "google/bigbird-roberta-base": "https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model", "google/bigbird-roberta-large": ( "https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model" ), "google/bigbird-base-trivia-itc": ( "https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model" ), } } lowerCAmelCase__ = { "google/bigbird-roberta-base": 4_0_9_6, "google/bigbird-roberta-large": 4_0_9_6, "google/bigbird-base-trivia-itc": 4_0_9_6, } class a__ ( __lowercase ): """simple docstring""" __lowerCamelCase = VOCAB_FILES_NAMES __lowerCamelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCamelCase = ["""input_ids""", """attention_mask"""] __lowerCamelCase = [] def __init__( self , lowercase , lowercase="<unk>" , lowercase="<s>" , lowercase="</s>" , lowercase="<pad>" , lowercase="[SEP]" , lowercase="[MASK]" , lowercase="[CLS]" , lowercase = None , **lowercase , ) -> None: '''simple docstring''' A__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else bos_token A__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else eos_token A__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else unk_token A__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else pad_token A__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else cls_token A__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it A__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else mask_token A__ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , sp_model_kwargs=self.sp_model_kwargs , **SCREAMING_SNAKE_CASE__ , ) A__ = vocab_file A__ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(SCREAMING_SNAKE_CASE__ ) @property def UpperCamelCase ( self ) -> Any: '''simple docstring''' return self.sp_model.get_piece_size() def UpperCamelCase ( self ) -> Dict: '''simple docstring''' A__ = {self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self ) -> str: '''simple docstring''' A__ = self.__dict__.copy() A__ = None return state def __setstate__( self , lowercase ) -> int: '''simple docstring''' 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 UpperCamelCase ( self , lowercase ) -> List[str]: '''simple docstring''' return self.sp_model.encode(SCREAMING_SNAKE_CASE__ , out_type=SCREAMING_SNAKE_CASE__ ) def UpperCamelCase ( self , lowercase ) -> List[str]: '''simple docstring''' return self.sp_model.piece_to_id(SCREAMING_SNAKE_CASE__ ) def UpperCamelCase ( self , lowercase ) -> List[Any]: '''simple docstring''' A__ = self.sp_model.IdToPiece(SCREAMING_SNAKE_CASE__ ) return token def UpperCamelCase ( self , lowercase ) -> Optional[int]: '''simple docstring''' A__ = [] A__ = "" A__ = 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(SCREAMING_SNAKE_CASE__ ) + token A__ = True A__ = [] else: current_sub_tokens.append(SCREAMING_SNAKE_CASE__ ) A__ = False out_string += self.sp_model.decode(SCREAMING_SNAKE_CASE__ ) return out_string.strip() def UpperCamelCase ( self , lowercase , lowercase = False , lowercase = None , lowercase = True , **lowercase , ) -> str: '''simple docstring''' A__ = kwargs.pop("use_source_tokenizer" , SCREAMING_SNAKE_CASE__ ) A__ = self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 A__ = [] A__ = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) A__ = [] sub_texts.append(SCREAMING_SNAKE_CASE__ ) else: current_sub_text.append(SCREAMING_SNAKE_CASE__ ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(SCREAMING_SNAKE_CASE__ ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: A__ = re.sub(R" (\[(MASK|SEP)\])" , R"\1" , " ".join(SCREAMING_SNAKE_CASE__ ) ) else: A__ = "".join(SCREAMING_SNAKE_CASE__ ) A__ = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: A__ = self.clean_up_tokenization(SCREAMING_SNAKE_CASE__ ) return clean_text else: return text def UpperCamelCase ( self , lowercase , lowercase = None ) -> Tuple[str]: '''simple docstring''' if not os.path.isdir(SCREAMING_SNAKE_CASE__ ): logger.error(F'Vocabulary path ({save_directory}) should be a directory' ) return A__ = os.path.join( SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ ) elif not os.path.isfile(self.vocab_file ): with open(SCREAMING_SNAKE_CASE__ , "wb" ) as fi: A__ = self.sp_model.serialized_model_proto() fi.write(SCREAMING_SNAKE_CASE__ ) return (out_vocab_file,) def UpperCamelCase ( self , lowercase , lowercase = None ) -> List[int]: '''simple docstring''' if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] A__ = [self.cls_token_id] A__ = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def UpperCamelCase ( self , lowercase , lowercase = None , lowercase = False ) -> List[int]: '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=SCREAMING_SNAKE_CASE__ , token_ids_a=SCREAMING_SNAKE_CASE__ , already_has_special_tokens=SCREAMING_SNAKE_CASE__ ) if token_ids_a is None: return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] return [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] + ([0] * len(SCREAMING_SNAKE_CASE__ )) + [1] def UpperCamelCase ( self , lowercase , lowercase = None ) -> List[int]: '''simple docstring''' A__ = [self.sep_token_id] A__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
68
from abc import ABC, abstractmethod from argparse import ArgumentParser class lowerCAmelCase__ ( __lowercase ): @staticmethod @abstractmethod def __A ( SCREAMING_SNAKE_CASE__ : ArgumentParser ) -> str: raise NotImplementedError() @abstractmethod def __A ( self : Optional[int] ) -> Union[str, Any]: raise NotImplementedError()
270
0