code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
def A__ (snake_case : list[list[float]] ) -> Tuple: __UpperCamelCase : list[list[float]] = [] for data in source_data: for i, el in enumerate(lowercase_ ): if len(lowercase_ ) < i + 1: data_lists.append([] ) data_lists[i].append(float(lowercase_ ) ) return data_lists def A__ (snake_case : list[list[float]] , snake_case : list[int] ) -> Tuple: __UpperCamelCase : list[list[float]] = [] for dlist, weight in zip(lowercase_ , lowercase_ ): __UpperCamelCase : int = min(lowercase_ ) __UpperCamelCase : Optional[Any] = max(lowercase_ ) __UpperCamelCase : list[float] = [] # for weight 0 score is 1 - actual score if weight == 0: for item in dlist: try: score.append(1 - ((item - mind) / (maxd - mind)) ) except ZeroDivisionError: score.append(1 ) elif weight == 1: for item in dlist: try: score.append((item - mind) / (maxd - mind) ) except ZeroDivisionError: score.append(0 ) # weight not 0 or 1 else: __UpperCamelCase : Any = F'''Invalid weight of {weight:f} provided''' raise ValueError(lowercase_ ) score_lists.append(lowercase_ ) return score_lists def A__ (snake_case : list[list[float]] ) -> Tuple: __UpperCamelCase : list[float] = [0 for i in range(len(score_lists[0] ) )] for slist in score_lists: for j, ele in enumerate(lowercase_ ): __UpperCamelCase : Dict = final_scores[j] + ele return final_scores def A__ (snake_case : list[list[float]] , snake_case : list[int] ) -> str: __UpperCamelCase : int = get_data(lowercase_ ) __UpperCamelCase : str = calculate_each_score(lowercase_ , lowercase_ ) __UpperCamelCase : Any = generate_final_scores(lowercase_ ) # append scores to source data for i, ele in enumerate(lowercase_ ): source_data[i].append(lowercase_ ) return source_data
279
"""simple docstring""" from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class snake_case ( __UpperCAmelCase , __UpperCAmelCase ): @register_to_config def __init__( self :List[str] , _lowerCamelCase :int = 7_6_8 , ): super().__init__() __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter(torch.zeros(1 , _lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.ones(1 , _lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Optional[Union[str, torch.device]] = None , _lowerCamelCase :Optional[torch.dtype] = None , ): __SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(self.mean.to(_lowerCamelCase ).to(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(self.std.to(_lowerCamelCase ).to(_lowerCamelCase ) ) return self def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Tuple = (embeds - self.mean) * 1.0 / self.std return embeds def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = (embeds * self.std) + self.mean return embeds
674
0
from dataclasses import dataclass, field from typing import Optional from transformers import AutoConfig, AutoImageProcessor, AutoTokenizer, FlaxVisionEncoderDecoderModel, HfArgumentParser @dataclass class lowerCamelCase : UpperCamelCase_ : Tuple = field( metadata={'help': 'The output directory where the model will be written.'} , ) UpperCamelCase_ : str = field( metadata={ 'help': ( 'The encoder model checkpoint for weights initialization.' 'Don\'t set if you want to train an encoder model from scratch.' ) } , ) UpperCamelCase_ : int = field( metadata={ 'help': ( 'The decoder model checkpoint for weights initialization.' 'Don\'t set if you want to train a decoder model from scratch.' ) } , ) UpperCamelCase_ : Union[str, Any] = field( default=__UpperCAmelCase , metadata={'help': 'Pretrained encoder config name or path if not the same as encoder_model_name'} ) UpperCamelCase_ : List[Any] = field( default=__UpperCAmelCase , metadata={'help': 'Pretrained decoder config name or path if not the same as decoder_model_name'} ) def a ( ) ->List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = HfArgumentParser((ModelArguments,) ) (SCREAMING_SNAKE_CASE ) = parser.parse_args_into_dataclasses() # Load pretrained model and tokenizer # Use explicit specified encoder config if model_args.encoder_config_name: SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(model_args.encoder_config_name ) # Use pretrained encoder model's config else: SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(model_args.encoder_model_name_or_path ) # Use explicit specified decoder config if model_args.decoder_config_name: SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(model_args.decoder_config_name ) # Use pretrained decoder model's config else: SCREAMING_SNAKE_CASE = AutoConfig.from_pretrained(model_args.decoder_model_name_or_path ) # necessary for `from_encoder_decoder_pretrained` when `decoder_config` is passed SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = 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=lowercase_ , decoder_config=lowercase_ , ) # GPT2 only has bos/eos tokens but not decoder_start/pad tokens SCREAMING_SNAKE_CASE = decoder_config.decoder_start_token_id SCREAMING_SNAKE_CASE = decoder_config.pad_token_id if decoder_start_token_id is None: SCREAMING_SNAKE_CASE = decoder_config.bos_token_id if pad_token_id is None: SCREAMING_SNAKE_CASE = decoder_config.eos_token_id # This is necessary to make Flax's generate() work SCREAMING_SNAKE_CASE = decoder_config.eos_token_id SCREAMING_SNAKE_CASE = decoder_start_token_id SCREAMING_SNAKE_CASE = pad_token_id SCREAMING_SNAKE_CASE = AutoImageProcessor.from_pretrained(model_args.encoder_model_name_or_path ) SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(model_args.decoder_model_name_or_path ) SCREAMING_SNAKE_CASE = 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()
201
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : int , lowercase_ : Any ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = BertConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : Optional[int] = BertForPreTraining(lowercase_ ) # Load weights from tf checkpoint load_tf_weights_in_bert(lowercase_ , lowercase_ , lowercase_ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--bert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained BERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
674
0
"""simple docstring""" import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class __UpperCAmelCase( __UpperCAmelCase ): """simple docstring""" __lowerCamelCase = ( "This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image." "It takes two arguments named `image` which should be the original image, and `label` which should be a text " "describing the elements what should be identified in the segmentation mask. The tool returns the mask." ) __lowerCamelCase = "CIDAS/clipseg-rd64-refined" __lowerCamelCase = "image_segmenter" __lowerCamelCase = CLIPSegForImageSegmentation __lowerCamelCase = ["image", "text"] __lowerCamelCase = ["image"] def __init__( self , *snake_case__ , **snake_case__ ): '''simple docstring''' requires_backends(self , ["vision"] ) super().__init__(*_lowerCamelCase , **_lowerCamelCase ) def UpperCAmelCase_ ( self , snake_case__ , snake_case__ ): '''simple docstring''' return self.pre_processor(text=[label] , images=[image] , padding=_lowerCamelCase , return_tensors="pt" ) def UpperCAmelCase_ ( self , snake_case__ ): '''simple docstring''' with torch.no_grad(): lowercase__ : List[Any]= self.model(**_lowerCamelCase ).logits return logits def UpperCAmelCase_ ( self , snake_case__ ): '''simple docstring''' lowercase__ : Optional[int]= outputs.cpu().detach().numpy() lowercase__ : str= 0 lowercase__ : str= 1 return Image.fromarray((array * 255).astype(np.uinta ) )
218
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = ( '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.''' '''It takes two arguments named `image` which should be the original image, and `label` which should be a text ''' '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.''' ) lowerCamelCase__ = '''CIDAS/clipseg-rd64-refined''' lowerCamelCase__ = '''image_segmenter''' lowerCamelCase__ = CLIPSegForImageSegmentation lowerCamelCase__ = ['''image''', '''text'''] lowerCamelCase__ = ['''image'''] def __init__( self :Dict , *_lowerCamelCase :Union[str, Any] , **_lowerCamelCase :Tuple ): requires_backends(self , ['''vision'''] ) super().__init__(*_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :"Image" , _lowerCamelCase :str ): return self.pre_processor(text=[label] , images=[image] , padding=_lowerCamelCase , return_tensors='''pt''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[int] ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = self.model(**_lowerCamelCase ).logits return logits def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy() __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : str = 1 return Image.fromarray((array * 2_5_5).astype(np.uinta ) )
674
0
def __snake_case ( _UpperCamelCase ) -> Union[str, Any]: # noqa: E741 _a = len(lowercase_ ) _a = 0 _a = [0] * n _a = [False] * n _a = [False] * n def dfs(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ): if parent == root: out_edge_count += 1 _a = True _a = at for to in l[at]: if to == parent: pass elif not visited[to]: _a = dfs(lowercase_ , lowercase_ , lowercase_ , lowercase_ ) _a = min(low[at] , low[to] ) # AP found via bridge if at < low[to]: _a = True # AP found via cycle if at == low[to]: _a = True else: _a = min(low[at] , lowercase_ ) return out_edge_count for i in range(lowercase_ ): if not visited[i]: _a = 0 _a = dfs(lowercase_ , lowercase_ , -1 , lowercase_ ) _a = out_edge_count > 1 for x in range(len(lowercase_ ) ): if is_art[x] is True: print(lowercase_ ) # Adjacency list of graph lowerCamelCase :Any = { 0: [1, 2], 1: [0, 2], 2: [0, 1, 3, 5], 3: [2, 4], 4: [3], 5: [2, 6, 8], 6: [5, 7], 7: [6, 8], 8: [5, 7], } compute_ap(data)
487
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE : Optional[int] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) __SCREAMING_SNAKE_CASE : Optional[int] = { '''do_resize''': True, '''size''': {'''height''': 1_8, '''width''': 1_8}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , _lowerCamelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , **_lowerCamelCase :List[str] ): return BertTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , **_lowerCamelCase :Optional[int] ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE : Tuple = [Image.fromarray(np.moveaxis(_lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : str = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor(do_normalize=_lowerCamelCase , padding_value=1.0 ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : Optional[int] = image_processor(_lowerCamelCase , return_tensors='''np''' ) __SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Any = self.get_image_processor() __SCREAMING_SNAKE_CASE : Any = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Optional[int] = processor(text=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = tokenizer(_lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : int = self.get_tokenizer() __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = '''lower newer''' __SCREAMING_SNAKE_CASE : int = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : int = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(_lowerCamelCase ): processor() def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Dict = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE : Tuple = processor.batch_decode(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.batch_decode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : str = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
674
0
"""simple docstring""" import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from utils_qa import postprocess_qa_predictions import transformers from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed from transformers.trainer_pt_utils import nested_concat, nested_truncate a_ = trt.Logger(trt.Logger.WARNING) a_ = absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) a_ = logging.getLogger(__name__) a_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--onnx_model_path', default=None, type=str, required=True, help='Path to ONNX model: ', ) parser.add_argument( '--output_dir', default=None, type=str, required=True, help='The output directory where the model checkpoints and predictions will be written.', ) # Other parameters parser.add_argument( '--tokenizer_name', default='', type=str, required=True, help='Pretrained tokenizer name or path if not the same as model_name', ) parser.add_argument( '--version_2_with_negative', action='store_true', help='If true, the SQuAD examples contain some that do not have an answer.', ) parser.add_argument( '--null_score_diff_threshold', type=float, default=0.0, help='If null_score - best_non_null is greater than the threshold predict null.', ) parser.add_argument( '--max_seq_length', default=3_8_4, type=int, help=( 'The maximum total input sequence length after WordPiece tokenization. Sequences ' 'longer than this will be truncated, and sequences shorter than this will be padded.' ), ) parser.add_argument( '--doc_stride', default=1_2_8, type=int, help='When splitting up a long document into chunks, how much stride to take between chunks.', ) parser.add_argument('--per_device_eval_batch_size', default=8, type=int, help='Batch size per GPU/CPU for evaluation.') parser.add_argument( '--n_best_size', default=2_0, type=int, help='The total number of n-best predictions to generate in the nbest_predictions.json output file.', ) parser.add_argument( '--max_answer_length', default=3_0, type=int, help=( 'The maximum length of an answer that can be generated. This is needed because the start ' 'and end predictions are not conditioned on one another.' ), ) parser.add_argument('--seed', type=int, default=4_2, help='random seed for initialization') parser.add_argument( '--dataset_name', type=str, default=None, required=True, help='The name of the dataset to use (via the datasets library).', ) parser.add_argument( '--dataset_config_name', type=str, default=None, help='The configuration name of the dataset to use (via the datasets library).', ) parser.add_argument( '--preprocessing_num_workers', type=int, default=4, help='A csv or a json file containing the training data.' ) parser.add_argument('--overwrite_cache', action='store_true', help='Overwrite the cached training and evaluation sets') parser.add_argument( '--fp16', action='store_true', help='Whether to use 16-bit (mixed) precision instead of 32-bit', ) parser.add_argument( '--int8', action='store_true', help='Whether to use INT8', ) a_ = parser.parse_args() if args.tokenizer_name: a_ = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) else: raise ValueError( 'You are instantiating a new tokenizer from scratch. This is not supported by this script.' 'You can do it from another script, save it, and load it from here, using --tokenizer_name.' ) logger.info('Training/evaluation parameters %s', args) a_ = args.per_device_eval_batch_size a_ = (args.eval_batch_size, args.max_seq_length) # TRT Engine properties a_ = True a_ = 'temp_engine/bert-fp32.engine' if args.fpaa: a_ = 'temp_engine/bert-fp16.engine' if args.inta: a_ = 'temp_engine/bert-int8.engine' # import ONNX file if not os.path.exists('temp_engine'): os.makedirs('temp_engine') a_ = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser( network, TRT_LOGGER ) as parser: with open(args.onnx_model_path, 'rb') as model: if not parser.parse(model.read()): for error in range(parser.num_errors): print(parser.get_error(error)) # Query input names and shapes from parsed TensorRT network a_ = [network.get_input(i) for i in range(network.num_inputs)] a_ = [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: a_ = 1 << 5_0 if STRICT_TYPES: config.set_flag(trt.BuilderFlag.STRICT_TYPES) if args.fpaa: config.set_flag(trt.BuilderFlag.FPaa) if args.inta: config.set_flag(trt.BuilderFlag.INTa) a_ = builder.create_optimization_profile() config.add_optimization_profile(profile) for i in range(len(input_names)): profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE) a_ = builder.build_engine(network, config) # serialize_engine and store in file (can be directly loaded and deserialized): with open(engine_name, 'wb') as f: f.write(engine.serialize()) def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): __lowercase : Dict = np.asarray(inputs['''input_ids'''] , dtype=np.intaa ) __lowercase : Optional[Any] = np.asarray(inputs['''attention_mask'''] , dtype=np.intaa ) __lowercase : Optional[Any] = np.asarray(inputs['''token_type_ids'''] , dtype=np.intaa ) # Copy inputs cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , lowercase_ ) # start time __lowercase : Tuple = time.time() # Run inference context.execute_async( bindings=[int(lowercase_ ) for d_inp in d_inputs] + [int(lowercase_ ), int(lowercase_ )] , stream_handle=stream.handle ) # Transfer predictions back from GPU cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) # Synchronize the stream and take time stream.synchronize() # end time __lowercase : List[str] = time.time() __lowercase : int = end_time - start_time __lowercase : int = (h_outputa, h_outputa) # print(outputs) return outputs, infer_time # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. a_ = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). if args.dataset_name is not None: # Downloading and loading a dataset from the hub. a_ = load_dataset(args.dataset_name, args.dataset_config_name) else: raise ValueError('Evaluation requires a dataset name') # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Preprocessing the datasets. # Preprocessing is slighlty different for training and evaluation. a_ = raw_datasets['validation'].column_names a_ = 'question' if 'question' in column_names else column_names[0] a_ = 'context' if 'context' in column_names else column_names[1] a_ = 'answers' if 'answers' in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). a_ = tokenizer.padding_side == 'right' if args.max_seq_length > tokenizer.model_max_length: logger.warning( F"The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the" F"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}." ) a_ = min(args.max_seq_length, tokenizer.model_max_length) def __UpperCAmelCase ( __UpperCamelCase ): __lowercase : Any = [q.lstrip() for q in examples[question_column_name]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. __lowercase : Optional[Any] = tokenizer( examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='''only_second''' if pad_on_right else '''only_first''' , max_length=lowercase_ , stride=args.doc_stride , return_overflowing_tokens=lowercase_ , return_offsets_mapping=lowercase_ , padding='''max_length''' , ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. __lowercase : Optional[int] = tokenized_examples.pop('''overflow_to_sample_mapping''' ) # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. __lowercase : Any = [] for i in range(len(tokenized_examples['''input_ids'''] ) ): # Grab the sequence corresponding to that example (to know what is the context and what is the question). __lowercase : int = tokenized_examples.sequence_ids(lowercase_ ) __lowercase : str = 1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. __lowercase : str = sample_mapping[i] tokenized_examples["example_id"].append(examples['''id'''][sample_index] ) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. __lowercase : List[str] = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples['''offset_mapping'''][i] ) ] return tokenized_examples a_ = raw_datasets['validation'] # Validation Feature Creation a_ = eval_examples.map( prepare_validation_features, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc='Running tokenizer on validation dataset', ) a_ = default_data_collator a_ = eval_dataset.remove_columns(['example_id', 'offset_mapping']) a_ = DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase="eval" ): __lowercase : Tuple = postprocess_qa_predictions( examples=lowercase_ , features=lowercase_ , predictions=lowercase_ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=lowercase_ , ) # Format the result to the format the metric expects. if args.version_2_with_negative: __lowercase : Union[str, Any] = [ {'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items() ] else: __lowercase : int = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()] __lowercase : Any = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=lowercase_ , label_ids=lowercase_ ) a_ = load_metric('squad_v2' if args.version_2_with_negative else 'squad') # Evaluation! logger.info('Loading ONNX model %s for evaluation', args.onnx_model_path) with open(engine_name, 'rb') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine( f.read() ) as engine, engine.create_execution_context() as context: # setup for TRT inferrence for i in range(len(input_names)): context.set_binding_shape(i, INPUT_SHAPE) assert context.all_binding_shapes_specified def __UpperCAmelCase ( __UpperCamelCase ): return trt.volume(engine.get_binding_shape(lowercase_ ) ) * engine.get_binding_dtype(lowercase_ ).itemsize # Allocate device memory for inputs and outputs. a_ = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer a_ = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) a_ = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) a_ = cuda.mem_alloc(h_outputa.nbytes) a_ = cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. a_ = cuda.Stream() # Evaluation logger.info('***** Running Evaluation *****') logger.info(F" Num examples = {len(eval_dataset)}") logger.info(F" Batch size = {args.per_device_eval_batch_size}") a_ = 0.0 a_ = 0 a_ = timeit.default_timer() a_ = None for step, batch in enumerate(eval_dataloader): a_ , a_ = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 a_ , a_ = outputs a_ = torch.tensor(start_logits) a_ = torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered a_ = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_0_0) a_ = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_0_0) a_ = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) a_ = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_0_0) if all_preds is not None: a_ = nested_truncate(all_preds, len(eval_dataset)) a_ = timeit.default_timer() - start_time logger.info(' Evaluation done in total %f secs (%f sec per example)', evalTime, evalTime / len(eval_dataset)) # Inference time from TRT logger.info('Average Inference Time = {:.3f} ms'.format(total_time * 1_0_0_0 / niter)) logger.info('Total Inference Time = {:.3f} ms'.format(total_time * 1_0_0_0)) logger.info('Total Number of Inference = %d', niter) a_ = post_processing_function(eval_examples, eval_dataset, all_preds) a_ = metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(F"Evaluation metrics: {eval_metric}")
76
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class snake_case : def __init__( self :Optional[int] , _lowerCamelCase :int , _lowerCamelCase :Any=2 , _lowerCamelCase :List[str]=True , _lowerCamelCase :str=False , _lowerCamelCase :Tuple=1_0 , _lowerCamelCase :str=3 , _lowerCamelCase :str=3_2 * 4 , _lowerCamelCase :Dict=3_2 * 6 , _lowerCamelCase :str=4 , _lowerCamelCase :Any=3_2 , ): __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Tuple = batch_size __SCREAMING_SNAKE_CASE : Optional[Any] = is_training __SCREAMING_SNAKE_CASE : Dict = use_auxiliary_loss __SCREAMING_SNAKE_CASE : List[str] = num_queries __SCREAMING_SNAKE_CASE : Optional[int] = num_channels __SCREAMING_SNAKE_CASE : List[Any] = min_size __SCREAMING_SNAKE_CASE : int = max_size __SCREAMING_SNAKE_CASE : Any = num_labels __SCREAMING_SNAKE_CASE : Union[str, Any] = mask_feature_size def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : str = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowerCamelCase ) > 0.5 ).float() __SCREAMING_SNAKE_CASE : Dict = (torch.rand((self.batch_size, self.num_labels) , device=_lowerCamelCase ) > 0.5).long() __SCREAMING_SNAKE_CASE : str = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=1_2_8 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Any = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = output.encoder_hidden_states __SCREAMING_SNAKE_CASE : int = output.pixel_decoder_hidden_states __SCREAMING_SNAKE_CASE : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , config.decoder_config.decoder_layers ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :str , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any]=False ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = MaskFormerModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : str = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , output_hidden_states=_lowerCamelCase ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerForInstanceSegmentation(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() def comm_check_on_output(_lowerCamelCase :Optional[Any] ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = model( pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () lowerCamelCase__ = ( {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerModelTester(self ) __SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowerCamelCase ) @unittest.skip(reason='''MaskFormer does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): pass @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' ) def SCREAMING_SNAKE_CASE_ ( self :int ): pass @unittest.skip(reason='''MaskFormer is not a generative model''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): pass @unittest.skip(reason='''MaskFormer does not use token embeddings''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): pass @require_torch_multi_gpu @unittest.skip( reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Tuple = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE : List[str] = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): for model_name in ["facebook/maskformer-swin-small-coco"]: __SCREAMING_SNAKE_CASE : Tuple = MaskFormerModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Dict = (self.model_tester.min_size,) * 2 __SCREAMING_SNAKE_CASE : Dict = { '''pixel_values''': torch.randn((2, 3, *size) , device=_lowerCamelCase ), '''mask_labels''': torch.randn((2, 1_0, *size) , device=_lowerCamelCase ), '''class_labels''': torch.zeros(2 , 1_0 , device=_lowerCamelCase ).long(), } __SCREAMING_SNAKE_CASE : Dict = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Dict = model_class(_lowerCamelCase ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = model(**_lowerCamelCase , output_attentions=_lowerCamelCase ) self.assertTrue(outputs.attentions is not None ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : List[Any] = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ).loss loss.backward() def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : Tuple = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Tuple = True __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : str = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't __SCREAMING_SNAKE_CASE : Optional[int] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : int = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_lowerCamelCase ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) _lowerCamelCase = 1e-4 def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @slow class snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self :str ): return ( MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' ) if is_vision_available() else None ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : Tuple = model(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor( [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Any = torch.tensor( [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : str = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Any = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[Any] = [ [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3], [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5], [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2], ] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : List[Any] = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [ [1.65_12e00, -5.25_72e00, -3.35_19e00], [3.61_69e-02, -5.90_25e00, -2.93_13e00], [1.07_66e-04, -7.76_30e00, -5.12_63e00], ] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor __SCREAMING_SNAKE_CASE : str = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[str] = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : int = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : int = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Any = self.default_image_processor __SCREAMING_SNAKE_CASE : int = image_processor( [np.zeros((3, 8_0_0, 1_3_3_3) ), np.zeros((3, 8_0_0, 1_3_3_3) )] , segmentation_maps=[np.zeros((3_8_4, 3_8_4) ).astype(np.floataa ), np.zeros((3_8_4, 3_8_4) ).astype(np.floataa )] , return_tensors='''pt''' , ) __SCREAMING_SNAKE_CASE : Dict = inputs['''pixel_values'''].to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = [el.to(_lowerCamelCase ) for el in inputs['''mask_labels''']] __SCREAMING_SNAKE_CASE : str = [el.to(_lowerCamelCase ) for el in inputs['''class_labels''']] with torch.no_grad(): __SCREAMING_SNAKE_CASE : int = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None )
674
0
lowercase_ : int = {} def A__ ( snake_case_ : int , snake_case_ : int , snake_case_ : int ): if late == 3 or absent == 2: return 0 # if we have no days left, and have not failed any other rules, # we have a prize string if days == 0: return 1 # No easy solution, so now we need to do the recursive calculation # First, check if the combination is already in the cache, and # if yes, return the stored value from there since we already # know the number of possible prize strings from this point on SCREAMING_SNAKE_CASE__: List[Any]= (days, absent, late) if key in cache: return cache[key] # now we calculate the three possible ways that can unfold from # this point on, depending on our attendance today # 1) if we are late (but not absent), the "absent" counter stays as # it is, but the "late" counter increases by one SCREAMING_SNAKE_CASE__: Optional[Any]= _calculate(days - 1 , lowercase_ , late + 1 ) # 2) if we are absent, the "absent" counter increases by 1, and the # "late" counter resets to 0 SCREAMING_SNAKE_CASE__: Optional[Any]= _calculate(days - 1 , absent + 1 , 0 ) # 3) if we are on time, this resets the "late" counter and keeps the # absent counter SCREAMING_SNAKE_CASE__: List[str]= _calculate(days - 1 , lowercase_ , 0 ) SCREAMING_SNAKE_CASE__: Optional[int]= state_late + state_absent + state_ontime SCREAMING_SNAKE_CASE__: Any= prizestrings return prizestrings def A__ ( snake_case_ : int = 30 ): return _calculate(lowercase_ , absent=0 , late=0 ) if __name__ == "__main__": print(solution())
64
"""simple docstring""" import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification _lowerCamelCase = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co _lowerCamelCase = '''main''' # Default branch name _lowerCamelCase = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2''' # One particular commit (not the top of `main`) _lowerCamelCase = '''aaaaaaa''' # This commit does not exist, so we should 404. _lowerCamelCase = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684''' # Sha-1 of config.json on the top of `main`, for checking purposes _lowerCamelCase = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3''' @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Welcome!''' ) yield print('''Bye!''' ) @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Bonjour!''' ) yield print('''Au revoir!''' ) class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): # If the spec is missing, importlib would not be able to import the module dynamically. assert transformers.__spec__ is not None assert importlib.util.find_spec('''transformers''' ) is not None class snake_case ( unittest.TestCase ): @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[int] ): with ContextManagers([] ): print('''Transformers are awesome!''' ) # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , '''Transformers are awesome!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): with ContextManagers([context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Welcome!\nTransformers are awesome!\nBye!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[str] ): with ContextManagers([context_fr(), context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n''' ) @require_torch def SCREAMING_SNAKE_CASE_ ( self :List[str] ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_tf def SCREAMING_SNAKE_CASE_ ( self :int ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_flax def SCREAMING_SNAKE_CASE_ ( self :Dict ): # Flax models don't have labels self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , [] )
674
0
import numpy as np import torch from torch.utils.data import DataLoader from accelerate.utils.dataclasses import DistributedType class lowerCamelCase_ : '''simple docstring''' def __init__( self , snake_case_=2 , snake_case_=3 , snake_case_=6_4 , snake_case_=None ) -> Any: '''simple docstring''' __lowercase = np.random.default_rng(_lowerCamelCase ) __lowercase = length __lowercase = rng.normal(size=(length,) ).astype(np.floataa ) __lowercase = a * self.x + b + rng.normal(scale=0.1 , size=(length,) ).astype(np.floataa ) def __len__( self ) -> Optional[Any]: '''simple docstring''' return self.length def __getitem__( self , snake_case_ ) -> str: '''simple docstring''' return {"x": self.x[i], "y": self.y[i]} class lowerCamelCase_ ( torch.nn.Module ): '''simple docstring''' def __init__( self , snake_case_=0 , snake_case_=0 , snake_case_=False ) -> List[Any]: '''simple docstring''' super().__init__() __lowercase = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __lowercase = torch.nn.Parameter(torch.tensor([2, 3] ).float() ) __lowercase = True def A ( self , snake_case_=None ) -> str: '''simple docstring''' if self.first_batch: print(F'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __lowercase = False return x * self.a[0] + self.b[0] class lowerCamelCase_ ( torch.nn.Module ): '''simple docstring''' def __init__( self , snake_case_=0 , snake_case_=0 , snake_case_=False ) -> Tuple: '''simple docstring''' super().__init__() __lowercase = torch.nn.Parameter(torch.tensor(_lowerCamelCase ).float() ) __lowercase = torch.nn.Parameter(torch.tensor(_lowerCamelCase ).float() ) __lowercase = True def A ( self , snake_case_=None ) -> List[Any]: '''simple docstring''' if self.first_batch: print(F'Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}' ) __lowercase = False return x * self.a + self.b def lowercase_ ( _UpperCamelCase , _UpperCamelCase = 16 ): '''simple docstring''' from datasets import load_dataset from transformers import AutoTokenizer __lowercase = AutoTokenizer.from_pretrained('''bert-base-cased''' ) __lowercase = {'''train''': '''tests/test_samples/MRPC/train.csv''', '''validation''': '''tests/test_samples/MRPC/dev.csv'''} __lowercase = load_dataset('''csv''' , data_files=lowercase_ ) __lowercase = datasets['''train'''].unique('''label''' ) __lowercase = {v: i for i, v in enumerate(lowercase_ )} def tokenize_function(_UpperCamelCase ): # max_length=None => use the model max length (it's actually the default) __lowercase = tokenizer( examples['''sentence1'''] , examples['''sentence2'''] , truncation=lowercase_ , max_length=lowercase_ , padding='''max_length''' ) if "label" in examples: __lowercase = [label_to_id[l] for l in examples['''label''']] return outputs # Apply the method we just defined to all the examples in all the splits of the dataset __lowercase = datasets.map( lowercase_ , batched=lowercase_ , remove_columns=['''sentence1''', '''sentence2''', '''label'''] , ) def collate_fn(_UpperCamelCase ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(lowercase_ , padding='''max_length''' , max_length=1_28 , return_tensors='''pt''' ) return tokenizer.pad(lowercase_ , padding='''longest''' , return_tensors='''pt''' ) # Instantiate dataloaders. __lowercase = DataLoader(tokenized_datasets['''train'''] , shuffle=lowercase_ , collate_fn=lowercase_ , batch_size=2 ) __lowercase = DataLoader(tokenized_datasets['''validation'''] , shuffle=lowercase_ , collate_fn=lowercase_ , batch_size=1 ) return train_dataloader, eval_dataloader
639
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class snake_case ( unittest.TestCase ): def __init__( self :List[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Tuple=7 , _lowerCamelCase :Dict=3 , _lowerCamelCase :Optional[Any]=3_0 , _lowerCamelCase :List[str]=4_0_0 , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :List[Any]=True , _lowerCamelCase :Any=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=True , _lowerCamelCase :str=1 / 2_5_5 , _lowerCamelCase :Union[str, Any]=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Dict = batch_size __SCREAMING_SNAKE_CASE : str = num_channels __SCREAMING_SNAKE_CASE : Union[str, Any] = min_resolution __SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution __SCREAMING_SNAKE_CASE : Tuple = do_resize __SCREAMING_SNAKE_CASE : Union[str, Any] = size __SCREAMING_SNAKE_CASE : int = do_normalize __SCREAMING_SNAKE_CASE : List[Any] = image_mean __SCREAMING_SNAKE_CASE : Tuple = image_std __SCREAMING_SNAKE_CASE : Dict = do_rescale __SCREAMING_SNAKE_CASE : Optional[int] = rescale_factor __SCREAMING_SNAKE_CASE : List[Any] = do_pad def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :List[Any]=False ): if not batched: __SCREAMING_SNAKE_CASE : str = image_inputs[0] if isinstance(_lowerCamelCase , Image.Image ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = image.size else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = image.shape[1], image.shape[2] if w < h: __SCREAMING_SNAKE_CASE : str = int(self.size['''shortest_edge'''] * h / w ) __SCREAMING_SNAKE_CASE : int = self.size['''shortest_edge'''] elif w > h: __SCREAMING_SNAKE_CASE : Optional[Any] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : int = int(self.size['''shortest_edge'''] * w / h ) else: __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] else: __SCREAMING_SNAKE_CASE : Optional[Any] = [] for image in image_inputs: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __SCREAMING_SNAKE_CASE : Optional[int] = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0] __SCREAMING_SNAKE_CASE : int = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = YolosImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=_lowerCamelCase ) self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2, '''longest_edge''': 8_4} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): pass def SCREAMING_SNAKE_CASE_ ( self :int ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : str = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : List[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Any ): # Initialize image_processing __SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : Optional[int] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): # Initialize image_processings __SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(do_resize=_lowerCamelCase , do_normalize=_lowerCamelCase , do_rescale=_lowerCamelCase ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a.pad(_lowerCamelCase , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a(_lowerCamelCase , return_tensors='''pt''' ) self.assertTrue( torch.allclose(encoded_images_with_method['''pixel_values'''] , encoded_images['''pixel_values'''] , atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): # prepare image and target __SCREAMING_SNAKE_CASE : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Tuple = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''image_id''': 3_9_7_6_9, '''annotations''': target} # encode them __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessor.from_pretrained('''hustvl/yolos-small''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : Optional[int] = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Dict = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify orig_size __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # prepare image, target and masks_path __SCREAMING_SNAKE_CASE : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Dict = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9_7_6_9, '''segments_info''': target} __SCREAMING_SNAKE_CASE : Optional[int] = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them __SCREAMING_SNAKE_CASE : Any = YolosImageProcessor(format='''coco_panoptic''' ) __SCREAMING_SNAKE_CASE : Dict = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : str = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Any = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Dict = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify masks __SCREAMING_SNAKE_CASE : Optional[Any] = 8_2_2_8_7_3 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _lowerCamelCase ) # verify orig_size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : Any = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
674
0
from __future__ import annotations from math import pi, sqrt def lowerCAmelCase_ ( lowercase: float , lowercase: float ) -> Union[str, Any]: '''simple docstring''' if inductance <= 0: raise ValueError('''Inductance cannot be 0 or negative''' ) elif capacitance <= 0: raise ValueError('''Capacitance cannot be 0 or negative''' ) else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ), ) if __name__ == "__main__": import doctest doctest.testmod()
271
"""simple docstring""" from __future__ import annotations def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) return len(lowercase_ ) == 9 and set(lowercase_ ) == set('''123456789''' ) def lowerCAmelCase_ ( ): '''simple docstring''' for base_num in range(9999 , 4999 , -1 ): __SCREAMING_SNAKE_CASE : List[str] = 10_0002 * base_num if is_9_pandigital(lowercase_ ): return candidate for base_num in range(333 , 99 , -1 ): __SCREAMING_SNAKE_CASE : List[Any] = 100_2003 * base_num if is_9_pandigital(lowercase_ ): return candidate return None if __name__ == "__main__": print(f'{solution() = }')
674
0
from __future__ import annotations from typing import Any class _lowerCAmelCase ( __UpperCAmelCase ): """simple docstring""" pass class _lowerCAmelCase : """simple docstring""" def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Any ): """simple docstring""" UpperCamelCase = data UpperCamelCase = None def __iter__( self : Union[str, Any] ): """simple docstring""" UpperCamelCase = self UpperCamelCase = [] while node: if node in visited: raise ContainsLoopError visited.append(_lowerCamelCase ) yield node.data UpperCamelCase = node.next_node @property def __lowerCAmelCase ( self : Any ): """simple docstring""" try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": _snake_case = Node(1) _snake_case = Node(2) _snake_case = Node(3) _snake_case = Node(4) print(root_node.has_loop) # False _snake_case = root_node.next_node print(root_node.has_loop) # True _snake_case = Node(5) _snake_case = Node(6) _snake_case = Node(5) _snake_case = Node(6) print(root_node.has_loop) # False _snake_case = Node(1) print(root_node.has_loop) # False
282
"""simple docstring""" import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Tuple = 0 def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Optional[Any] = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Dict = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : str = CLIPConfig() # Create a dummy config file with image_proceesor_type __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ).to_dict() config_dict.pop('''image_processor_type''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor(**_lowerCamelCase ) # save in new folder model_config.save_pretrained(_lowerCamelCase ) config.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) # make sure private variable is not incorrectly saved __SCREAMING_SNAKE_CASE : Tuple = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): with self.assertRaisesRegex( _lowerCamelCase , '''clip-base is not a local folder and is not a valid model identifier''' ): __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained('''clip-base''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): with self.assertRaisesRegex( _lowerCamelCase , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(_lowerCamelCase , revision='''aaaaaa''' ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with self.assertRaisesRegex( _lowerCamelCase , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase , trust_remote_code=_lowerCamelCase ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_lowerCamelCase ): AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = CustomImageProcessor.from_pretrained(_lowerCamelCase ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def SCREAMING_SNAKE_CASE_ ( self :Dict ): class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = True try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # If remote code is not set, the default is to use local __SCREAMING_SNAKE_CASE : List[str] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. __SCREAMING_SNAKE_CASE : str = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(_lowerCamelCase , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
674
0
"""simple docstring""" from collections.abc import Sequence from queue import Queue class __lowercase: '''simple docstring''' def __init__( self , __a , __a , __a , __a=None , __a=None ): __lowerCamelCase : Any = start __lowerCamelCase : List[Any] = end __lowerCamelCase : str = val __lowerCamelCase : str = (start + end) // 2 __lowerCamelCase : Any = left __lowerCamelCase : Dict = right def __repr__( self ): return f'''SegmentTreeNode(start={self.start}, end={self.end}, val={self.val})''' class __lowercase: '''simple docstring''' def __init__( self , __a , __a ): __lowerCamelCase : Optional[int] = collection __lowerCamelCase : List[str] = function if self.collection: __lowerCamelCase : List[str] = self._build_tree(0 , len(_lowerCamelCase ) - 1 ) def snake_case_ ( self , __a , __a ): self._update_tree(self.root , _lowerCamelCase , _lowerCamelCase ) def snake_case_ ( self , __a , __a ): return self._query_range(self.root , _lowerCamelCase , _lowerCamelCase ) def snake_case_ ( self , __a , __a ): if start == end: return SegmentTreeNode(_lowerCamelCase , _lowerCamelCase , self.collection[start] ) __lowerCamelCase : str = (start + end) // 2 __lowerCamelCase : str = self._build_tree(_lowerCamelCase , _lowerCamelCase ) __lowerCamelCase : int = self._build_tree(mid + 1 , _lowerCamelCase ) return SegmentTreeNode(_lowerCamelCase , _lowerCamelCase , self.fn(left.val , right.val ) , _lowerCamelCase , _lowerCamelCase ) def snake_case_ ( self , __a , __a , __a ): if node.start == i and node.end == i: __lowerCamelCase : Any = val return if i <= node.mid: self._update_tree(node.left , _lowerCamelCase , _lowerCamelCase ) else: self._update_tree(node.right , _lowerCamelCase , _lowerCamelCase ) __lowerCamelCase : str = self.fn(node.left.val , node.right.val ) def snake_case_ ( self , __a , __a , __a ): if node.start == i and node.end == j: return node.val if i <= node.mid: if j <= node.mid: # range in left child tree return self._query_range(node.left , _lowerCamelCase , _lowerCamelCase ) else: # range in left child tree and right child tree return self.fn( self._query_range(node.left , _lowerCamelCase , node.mid ) , self._query_range(node.right , node.mid + 1 , _lowerCamelCase ) , ) else: # range in right child tree return self._query_range(node.right , _lowerCamelCase , _lowerCamelCase ) def snake_case_ ( self ): if self.root is not None: __lowerCamelCase : Any = Queue() queue.put(self.root ) while not queue.empty(): __lowerCamelCase : Dict = queue.get() yield node if node.left is not None: queue.put(node.left ) if node.right is not None: queue.put(node.right ) if __name__ == "__main__": import operator for fn in [operator.add, max, min]: print('''*''' * 50) a_ : int = SegmentTree([2, 1, 5, 3, 4], fn) for node in arr.traverse(): print(node) print() arr.update(1, 5) for node in arr.traverse(): print(node) print() print(arr.query_range(3, 4)) # 7 print(arr.query_range(2, 2)) # 5 print(arr.query_range(1, 3)) # 13 print()
594
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case ( __UpperCAmelCase ): pass class snake_case : def __init__( self :List[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Any = data __SCREAMING_SNAKE_CASE : Node | None = None def __iter__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : List[str] = self __SCREAMING_SNAKE_CASE : List[str] = [] while node: if node in visited: raise ContainsLoopError visited.append(_lowerCamelCase ) yield node.data __SCREAMING_SNAKE_CASE : List[str] = node.next_node @property def SCREAMING_SNAKE_CASE_ ( self :Any ): try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": _lowerCamelCase = Node(1) _lowerCamelCase = Node(2) _lowerCamelCase = Node(3) _lowerCamelCase = Node(4) print(root_node.has_loop) # False _lowerCamelCase = root_node.next_node print(root_node.has_loop) # True _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) print(root_node.has_loop) # False _lowerCamelCase = Node(1) print(root_node.has_loop) # False
674
0
import warnings from ..trainer import Trainer from ..utils import logging __snake_case = logging.get_logger(__name__) class UpperCAmelCase ( __UpperCAmelCase ): def __init__( self : str , __magic_name__ : Optional[Any]=None , **__magic_name__ : Optional[int] ): """simple docstring""" warnings.warn( """`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` """ """instead.""" , _lowerCamelCase , ) super().__init__(args=_lowerCamelCase , **_lowerCamelCase )
386
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''roc_bert''' def __init__( self :Union[str, Any] , _lowerCamelCase :Any=3_0_5_2_2 , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Optional[Any]=1_2 , _lowerCamelCase :List[str]=1_2 , _lowerCamelCase :str=3_0_7_2 , _lowerCamelCase :Tuple="gelu" , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :List[str]=0.1 , _lowerCamelCase :Optional[int]=5_1_2 , _lowerCamelCase :Dict=2 , _lowerCamelCase :Any=0.0_2 , _lowerCamelCase :Optional[int]=1e-12 , _lowerCamelCase :str=True , _lowerCamelCase :Any=0 , _lowerCamelCase :List[str]="absolute" , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Any=True , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Union[str, Any]=9_1_0 , _lowerCamelCase :List[Any]=5_1_2 , _lowerCamelCase :Optional[int]=2_4_8_5_8 , _lowerCamelCase :Union[str, Any]=True , **_lowerCamelCase :str , ): __SCREAMING_SNAKE_CASE : List[str] = vocab_size __SCREAMING_SNAKE_CASE : int = max_position_embeddings __SCREAMING_SNAKE_CASE : List[str] = hidden_size __SCREAMING_SNAKE_CASE : str = num_hidden_layers __SCREAMING_SNAKE_CASE : int = num_attention_heads __SCREAMING_SNAKE_CASE : Any = intermediate_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_act __SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range __SCREAMING_SNAKE_CASE : Union[str, Any] = type_vocab_size __SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps __SCREAMING_SNAKE_CASE : Optional[int] = use_cache __SCREAMING_SNAKE_CASE : str = enable_pronunciation __SCREAMING_SNAKE_CASE : List[str] = enable_shape __SCREAMING_SNAKE_CASE : Tuple = pronunciation_embed_dim __SCREAMING_SNAKE_CASE : Optional[Any] = pronunciation_vocab_size __SCREAMING_SNAKE_CASE : str = shape_embed_dim __SCREAMING_SNAKE_CASE : Union[str, Any] = shape_vocab_size __SCREAMING_SNAKE_CASE : Tuple = concat_input __SCREAMING_SNAKE_CASE : Union[str, Any] = position_embedding_type __SCREAMING_SNAKE_CASE : str = classifier_dropout super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase )
674
0
import argparse import json import os import fairseq import torch from fairseq.data import Dictionary from transformers import ( UniSpeechConfig, UniSpeechForCTC, UniSpeechForPreTraining, WavaVecaFeatureExtractor, WavaVecaPhonemeCTCTokenizer, WavaVecaProcessor, logging, ) logging.set_verbosity_info() a__ = logging.get_logger(__name__) a__ = { '''post_extract_proj''': '''feature_projection.projection''', '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''', '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''', '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''', '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''', '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''', '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''', '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''', '''fc2''': '''encoder.layers.*.feed_forward.output_dense''', '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''feature_projection.layer_norm''', '''quantizer.weight_proj''': '''quantizer.weight_proj''', '''quantizer.vars''': '''quantizer.codevectors''', '''project_q''': '''project_q''', '''final_proj''': '''project_hid''', '''w2v_encoder.proj''': '''ctc_proj''', '''mask_emb''': '''masked_spec_embed''', } a__ = [ '''ctc_proj''', '''quantizer.weight_proj''', '''quantizer.codevectors''', '''project_q''', '''project_hid''', ] def A__ (snake_case : Union[str, Any] , snake_case : Tuple , snake_case : Union[str, Any] , snake_case : Any , snake_case : Optional[int] , snake_case : Any ) -> Dict: for attribute in key.split(""".""" ): if is_finetuned: if attribute in ["quantizer", "project_q", "project_hid"]: # those layers are only relevant for pretraining and should be dropped return if attribute == "ctc_proj": # we should rename `ctc_proj` to `lm_head` for fine-tuned phoneme models __UpperCamelCase : int = '''lm_head''' __UpperCamelCase : Optional[Any] = getattr(lowercase_ , lowercase_ ) if weight_type is not None: __UpperCamelCase : Any = getattr(lowercase_ , lowercase_ ).shape else: __UpperCamelCase : Tuple = hf_pointer.shape assert hf_shape == value.shape, ( F'''Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be''' F''' {value.shape} for {full_name}''' ) if weight_type == "weight": __UpperCamelCase : Dict = value elif weight_type == "weight_g": __UpperCamelCase : Optional[Any] = value elif weight_type == "weight_v": __UpperCamelCase : str = value elif weight_type == "bias": __UpperCamelCase : List[Any] = value else: __UpperCamelCase : int = value logger.info(F'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' ) def A__ (snake_case : List[Any] , snake_case : List[str] , snake_case : Optional[int] ) -> Any: __UpperCamelCase : str = [] __UpperCamelCase : Tuple = fairseq_model.state_dict() __UpperCamelCase : Optional[int] = hf_model.unispeech.feature_extractor for name, value in fairseq_dict.items(): __UpperCamelCase : List[str] = False if "conv_layers" in name: load_conv_layer( lowercase_ , lowercase_ , lowercase_ , lowercase_ , hf_model.config.feat_extract_norm == """group""" , ) __UpperCamelCase : Any = True else: for key, mapped_key in MAPPING.items(): __UpperCamelCase : Optional[Any] = '''unispeech.''' + mapped_key if mapped_key not in TOP_LEVEL_KEYS else mapped_key if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]: __UpperCamelCase : Dict = True if "*" in mapped_key: __UpperCamelCase : Tuple = name.split(lowercase_ )[0].split(""".""" )[-2] __UpperCamelCase : Optional[int] = mapped_key.replace("""*""" , lowercase_ ) if "weight_g" in name: __UpperCamelCase : Dict = '''weight_g''' elif "weight_v" in name: __UpperCamelCase : Optional[Any] = '''weight_v''' elif "bias" in name: __UpperCamelCase : int = '''bias''' elif "weight" in name: # TODO: don't match quantizer.weight_proj __UpperCamelCase : Dict = '''weight''' else: __UpperCamelCase : Tuple = None set_recursively(lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ ) continue if not is_used: unused_weights.append(lowercase_ ) logger.warning(F'''Unused weights: {unused_weights}''' ) def A__ (snake_case : Tuple , snake_case : Optional[int] , snake_case : Union[str, Any] , snake_case : str , snake_case : int ) -> Dict: __UpperCamelCase : Union[str, Any] = full_name.split("""conv_layers.""" )[-1] __UpperCamelCase : Tuple = name.split(""".""" ) __UpperCamelCase : List[Any] = int(items[0] ) __UpperCamelCase : Dict = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.''' ) __UpperCamelCase : str = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.''' ) __UpperCamelCase : Union[str, Any] = value logger.info(F'''Feat extract conv layer {layer_id} was initialized from {full_name}.''' ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( F'''{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was''' " found." ) __UpperCamelCase : List[Any] = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( F'''{full_name} has size {value.shape}, but''' F''' {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.''' ) __UpperCamelCase : Optional[int] = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(lowercase_ ) @torch.no_grad() def A__ (snake_case : List[Any] , snake_case : Any , snake_case : Union[str, Any]=None , snake_case : Optional[Any]=None , snake_case : str=True ) -> List[str]: if config_path is not None: __UpperCamelCase : Union[str, Any] = UniSpeechConfig.from_pretrained(lowercase_ ) else: __UpperCamelCase : Tuple = UniSpeechConfig() if is_finetuned: if dict_path: __UpperCamelCase : Tuple = Dictionary.load_from_json(lowercase_ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq __UpperCamelCase : List[str] = target_dict.pad_index __UpperCamelCase : Dict = target_dict.bos_index __UpperCamelCase : Optional[Any] = target_dict.eos_index __UpperCamelCase : List[Any] = len(target_dict.symbols ) __UpperCamelCase : List[str] = os.path.join(lowercase_ , """vocab.json""" ) if not os.path.isdir(lowercase_ ): logger.error("""--pytorch_dump_folder_path ({}) should be a directory""".format(lowercase_ ) ) return os.makedirs(lowercase_ , exist_ok=lowercase_ ) __UpperCamelCase : Dict = target_dict.indices # fairseq has the <pad> and <s> switched __UpperCamelCase : List[Any] = 42 __UpperCamelCase : Tuple = 43 with open(lowercase_ , """w""" , encoding="""utf-8""" ) as vocab_handle: json.dump(lowercase_ , lowercase_ ) __UpperCamelCase : List[str] = WavaVecaPhonemeCTCTokenizer( lowercase_ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="""|""" , do_lower_case=lowercase_ , ) __UpperCamelCase : str = True if config.feat_extract_norm == '''layer''' else False __UpperCamelCase : Any = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=lowercase_ , return_attention_mask=lowercase_ , ) __UpperCamelCase : Tuple = WavaVecaProcessor(feature_extractor=lowercase_ , tokenizer=lowercase_ ) processor.save_pretrained(lowercase_ ) __UpperCamelCase : List[str] = UniSpeechForCTC(lowercase_ ) else: __UpperCamelCase : Union[str, Any] = UniSpeechForPreTraining(lowercase_ ) if is_finetuned: __UpperCamelCase : Optional[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"""data""": """/""".join(dict_path.split("""/""" )[:-1] ), """w2v_path""": checkpoint_path} ) else: __UpperCamelCase : Any = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) __UpperCamelCase : Optional[Any] = model[0].eval() recursively_load_weights(lowercase_ , lowercase_ , lowercase_ ) hf_unispeech.save_pretrained(lowercase_ ) if __name__ == "__main__": a__ = argparse.ArgumentParser() parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''') parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--not_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) a__ = parser.parse_args() convert_unispeech_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, not args.not_finetuned )
279
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : Tuple , lowercase_ : Optional[Any]=True , lowercase_ : Any="pt" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''add_prefix_space''': True} if isinstance(lowercase_ , lowercase_ ) and not line.startswith(''' ''' ) else {} __SCREAMING_SNAKE_CASE : Optional[int] = padding_side return tokenizer( [line] , max_length=lowercase_ , padding='''max_length''' if pad_to_max_length else None , truncation=lowercase_ , return_tensors=lowercase_ , add_special_tokens=lowercase_ , **lowercase_ , ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : Tuple , lowercase_ : List[Any]=None , ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = input_ids.ne(lowercase_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class snake_case ( __UpperCAmelCase ): def __init__( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :Any="train" , _lowerCamelCase :str=None , _lowerCamelCase :Optional[Any]=None , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Tuple="" , ): super().__init__() __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ).joinpath(type_path + '''.source''' ) __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ).joinpath(type_path + '''.target''' ) __SCREAMING_SNAKE_CASE : Any = self.get_char_lens(self.src_file ) __SCREAMING_SNAKE_CASE : List[str] = max_source_length __SCREAMING_SNAKE_CASE : Dict = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' __SCREAMING_SNAKE_CASE : Dict = tokenizer __SCREAMING_SNAKE_CASE : Union[str, Any] = prefix if n_obs is not None: __SCREAMING_SNAKE_CASE : Any = self.src_lens[:n_obs] __SCREAMING_SNAKE_CASE : List[str] = src_lang __SCREAMING_SNAKE_CASE : str = tgt_lang def __len__( self :int ): return len(self.src_lens ) def __getitem__( self :Optional[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = index + 1 # linecache starts at 1 __SCREAMING_SNAKE_CASE : Any = self.prefix + linecache.getline(str(self.src_file ) , _lowerCamelCase ).rstrip('''\n''' ) __SCREAMING_SNAKE_CASE : Dict = linecache.getline(str(self.tgt_file ) , _lowerCamelCase ).rstrip('''\n''' ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , _lowerCamelCase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right __SCREAMING_SNAKE_CASE : Dict = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.generator if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_source_length , '''right''' ) __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_target_length , '''right''' ) __SCREAMING_SNAKE_CASE : Any = source_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Any = target_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Dict = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :Any ): return [len(_lowerCamelCase ) for x in Path(_lowerCamelCase ).open().readlines()] def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : int = torch.stack([x['''input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = torch.stack([x['''attention_mask'''] for x in batch] ) __SCREAMING_SNAKE_CASE : int = torch.stack([x['''decoder_input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : List[str] = trim_batch(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = trim_batch(_lowerCamelCase , _lowerCamelCase , attention_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch _lowerCamelCase = getLogger(__name__) def lowerCAmelCase_ ( lowercase_ : List[List] ): '''simple docstring''' return list(itertools.chain.from_iterable(lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = get_git_info() save_json(lowercase_ , os.path.join(lowercase_ , '''git_log.json''' ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Optional[int] , lowercase_ : str=4 , **lowercase_ : List[str] ): '''simple docstring''' with open(lowercase_ , '''w''' ) as f: json.dump(lowercase_ , lowercase_ , indent=lowercase_ , **lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Union[str, Any] ): '''simple docstring''' with open(lowercase_ ) as f: return json.load(lowercase_ ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = git.Repo(search_parent_directories=lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = { '''repo_id''': str(lowercase_ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : Iterable ): '''simple docstring''' return list(map(lowercase_ , lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Any ): '''simple docstring''' with open(lowercase_ , '''wb''' ) as f: return pickle.dump(lowercase_ , lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' def remove_articles(lowercase_ : Dict ): return re.sub(r'''\b(a|an|the)\b''' , ''' ''' , lowercase_ ) def white_space_fix(lowercase_ : Optional[int] ): return " ".join(text.split() ) def remove_punc(lowercase_ : Any ): __SCREAMING_SNAKE_CASE : Optional[int] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowercase_ : int ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowercase_ ) ) ) ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Tuple = Counter(lowercase_ ) & Counter(lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = sum(common.values() ) if num_same == 0: return 0 __SCREAMING_SNAKE_CASE : Any = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[int] = (2 * precision * recall) / (precision + recall) return fa def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Union[str, Any] ): '''simple docstring''' return normalize_answer(lowercase_ ) == normalize_answer(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' assert len(lowercase_ ) == len(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for hypo, pred in zip(lowercase_ , lowercase_ ): em += exact_match_score(lowercase_ , lowercase_ ) if len(lowercase_ ) > 0: em /= len(lowercase_ ) return {"em": em} def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' return model_prefix.startswith('''rag''' ) def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead __SCREAMING_SNAKE_CASE : Any = '''dropout_rate''' for p in extra_params: if getattr(lowercase_ , lowercase_ , lowercase_ ): if not hasattr(lowercase_ , lowercase_ ) and not hasattr(lowercase_ , equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(lowercase_ ) ) delattr(lowercase_ , lowercase_ ) continue __SCREAMING_SNAKE_CASE : Optional[int] = p if hasattr(lowercase_ , lowercase_ ) else equivalent_param[p] setattr(lowercase_ , lowercase_ , getattr(lowercase_ , lowercase_ ) ) delattr(lowercase_ , lowercase_ ) return hparams, config
674
0
import os from math import logaa def a ( a = "base_exp.txt" ) ->str: '''simple docstring''' SCREAMING_SNAKE_CASE = 0 SCREAMING_SNAKE_CASE = 0 for i, line in enumerate(open(os.path.join(os.path.dirname(lowercase_ ) , lowercase_ ) ) ): SCREAMING_SNAKE_CASE = list(map(lowercase_ , line.split(''',''' ) ) ) if x * logaa(lowercase_ ) > largest: SCREAMING_SNAKE_CASE = x * logaa(lowercase_ ) SCREAMING_SNAKE_CASE = i + 1 return result if __name__ == "__main__": print(solution())
201
"""simple docstring""" from collections.abc import Callable import numpy as np def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : float , lowercase_ : float , lowercase_ : float , lowercase_ : float ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = int(np.ceil((x_end - xa) / step_size ) ) __SCREAMING_SNAKE_CASE : Dict = np.zeros((n + 1,) ) __SCREAMING_SNAKE_CASE : List[Any] = ya __SCREAMING_SNAKE_CASE : Dict = xa for k in range(lowercase_ ): __SCREAMING_SNAKE_CASE : str = y[k] + step_size * ode_func(lowercase_ , y[k] ) __SCREAMING_SNAKE_CASE : int = y[k] + ( (step_size / 2) * (ode_func(lowercase_ , y[k] ) + ode_func(x + step_size , lowercase_ )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
674
0
"""simple docstring""" import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) a : Union[str, Any] = [ """cross_validation.py""", """gradient_accumulation.py""", """local_sgd.py""", """multi_process_metrics.py""", """memory.py""", """automatic_gradient_accumulation.py""", """fsdp_with_peak_mem_tracking.py""", """deepspeed_with_config_support.py""", """megatron_lm_gpt_pretraining.py""", ] class __UpperCAmelCase( unittest.TestCase ): """simple docstring""" def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ = None , snake_case__ = None ): '''simple docstring''' lowercase__ : List[str]= None lowercase__ : Optional[Any]= os.path.abspath(os.path.join("examples" , "by_feature" ) ) lowercase__ : Union[str, Any]= os.path.abspath("examples" ) for item in os.listdir(_lowerCamelCase ): if item not in EXCLUDE_EXAMPLES: lowercase__ : List[Any]= os.path.join(_lowerCamelCase , _lowerCamelCase ) if os.path.isfile(_lowerCamelCase ) and ".py" in item_path: with self.subTest( tested_script=_lowerCamelCase , feature_script=_lowerCamelCase , tested_section="main()" if parser_only else "training_function()" , ): lowercase__ : Tuple= compare_against_test( os.path.join(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) lowercase__ : Optional[Any]= '''\n'''.join(_lowerCamelCase ) if special_strings is not None: for string in special_strings: lowercase__ : List[Any]= diff.replace(_lowerCamelCase , "" ) self.assertEqual(_lowerCamelCase , "" ) def UpperCAmelCase_ ( self ): '''simple docstring''' self.one_complete_example("complete_nlp_example.py" , _lowerCamelCase ) self.one_complete_example("complete_nlp_example.py" , _lowerCamelCase ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Union[str, Any]= os.path.abspath(os.path.join("examples" , "cv_example.py" ) ) lowercase__ : Optional[int]= [ ''' ''' * 16 + '''{\n\n''', ''' ''' * 20 + '''"accuracy": eval_metric["accuracy"],\n\n''', ''' ''' * 20 + '''"f1": eval_metric["f1"],\n\n''', ''' ''' * 20 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''', ''' ''' * 20 + '''"epoch": epoch,\n\n''', ''' ''' * 16 + '''},\n\n''', ''' ''' * 16 + '''step=epoch,\n''', ''' ''' * 12, ''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''', ] self.one_complete_example("complete_cv_example.py" , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) self.one_complete_example("complete_cv_example.py" , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @mock.patch.dict(os.environ , {"TESTING_MOCKED_DATALOADERS": "1"} ) class __UpperCAmelCase( __UpperCAmelCase ): """simple docstring""" __lowerCamelCase = False @classmethod def UpperCAmelCase_ ( cls ): '''simple docstring''' super().setUpClass() lowercase__ : Dict= tempfile.mkdtemp() lowercase__ : str= os.path.join(cls._tmpdir , "default_config.yml" ) write_basic_config(save_location=cls.configPath ) lowercase__ : List[Any]= ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def UpperCAmelCase_ ( cls ): '''simple docstring''' super().tearDownClass() shutil.rmtree(cls._tmpdir ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : str= F''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , "epoch_0" ) ) ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[Any]= F''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() lowercase__ : Optional[int]= run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , "step_2" ) ) ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[int]= F''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )} '''.split() lowercase__ : Any= run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) self.assertNotIn("epoch 0:" , _lowerCamelCase ) self.assertIn("epoch 1:" , _lowerCamelCase ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[int]= F''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )} '''.split() lowercase__ : List[str]= run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) if torch.cuda.is_available(): lowercase__ : List[Any]= torch.cuda.device_count() else: lowercase__ : Optional[int]= 1 if num_processes > 1: self.assertNotIn("epoch 0:" , _lowerCamelCase ) self.assertIn("epoch 1:" , _lowerCamelCase ) else: self.assertIn("epoch 0:" , _lowerCamelCase ) self.assertIn("epoch 1:" , _lowerCamelCase ) @slow def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[Any]= ''' examples/by_feature/cross_validation.py --num_folds 2 '''.split() with mock.patch.dict(os.environ , {"TESTING_MOCKED_DATALOADERS": "0"} ): lowercase__ : Union[str, Any]= run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) lowercase__ : Any= re.findall("({.+})" , _lowerCamelCase ) lowercase__ : List[Any]= [r for r in results if '''accuracy''' in r][-1] lowercase__ : Tuple= ast.literal_eval(_lowerCamelCase ) self.assertGreaterEqual(results["accuracy"] , 0.75 ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[Any]= ['''examples/by_feature/multi_process_metrics.py'''] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def UpperCAmelCase_ ( self ): '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdir: lowercase__ : int= F''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(_lowerCamelCase , "tracking" ) ) ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Union[str, Any]= ['''examples/by_feature/gradient_accumulation.py'''] run_command(self._launch_args + testargs ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : List[Any]= ['''examples/by_feature/local_sgd.py'''] run_command(self._launch_args + testargs )
218
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable _lowerCamelCase = { '''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''], '''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXJapaneseForCausalLM''', '''GPTNeoXJapaneseLayer''', '''GPTNeoXJapaneseModel''', '''GPTNeoXJapanesePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
674
0
import gc import random import unittest import numpy as np import torch from PIL import Image from diffusers import ( DDIMScheduler, KandinskyVaaInpaintPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel, ) from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class UpperCAmelCase ( __UpperCAmelCase , unittest.TestCase ): a: Optional[int] = KandinskyVaaInpaintPipeline a: str = ["image_embeds", "negative_image_embeds", "image", "mask_image"] a: Any = [ "image_embeds", "negative_image_embeds", "image", "mask_image", ] a: Optional[Any] = [ "generator", "height", "width", "latents", "guidance_scale", "num_inference_steps", "return_dict", "guidance_scale", "num_images_per_prompt", "output_type", "return_dict", ] a: List[Any] = False @property def _A ( self: List[Any] ): return 32 @property def _A ( self: Union[str, Any] ): return 32 @property def _A ( self: Optional[int] ): return self.time_input_dim @property def _A ( self: int ): return self.time_input_dim * 4 @property def _A ( self: Union[str, Any] ): return 100 @property def _A ( self: Tuple ): torch.manual_seed(0 ) _a = { '''in_channels''': 9, # Out channels is double in channels because predicts mean and variance '''out_channels''': 8, '''addition_embed_type''': '''image''', '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''), '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''), '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''', '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2), '''layers_per_block''': 1, '''encoder_hid_dim''': self.text_embedder_hidden_size, '''encoder_hid_dim_type''': '''image_proj''', '''cross_attention_dim''': self.cross_attention_dim, '''attention_head_dim''': 4, '''resnet_time_scale_shift''': '''scale_shift''', '''class_embed_type''': None, } _a = UNetaDConditionModel(**_lowerCamelCase ) return model @property def _A ( self: Union[str, Any] ): 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 _A ( self: Optional[int] ): torch.manual_seed(0 ) _a = VQModel(**self.dummy_movq_kwargs ) return model def _A ( self: List[str] ): _a = self.dummy_unet _a = self.dummy_movq _a = DDIMScheduler( num_train_timesteps=1000 , beta_schedule='''linear''' , beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , clip_sample=_lowerCamelCase , set_alpha_to_one=_lowerCamelCase , steps_offset=1 , prediction_type='''epsilon''' , thresholding=_lowerCamelCase , ) _a = { '''unet''': unet, '''scheduler''': scheduler, '''movq''': movq, } return components def _A ( self: Union[str, Any] , __UpperCamelCase: Optional[int] , __UpperCamelCase: List[str]=0 ): _a = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(_lowerCamelCase ) ).to(_lowerCamelCase ) _a = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( _lowerCamelCase ) # create init_image _a = floats_tensor((1, 3, 64, 64) , rng=random.Random(_lowerCamelCase ) ).to(_lowerCamelCase ) _a = image.cpu().permute(0 , 2 , 3 , 1 )[0] _a = Image.fromarray(np.uinta(_lowerCamelCase ) ).convert('''RGB''' ).resize((256, 256) ) # create mask _a = np.ones((64, 64) , dtype=np.floataa ) _a = 0 if str(_lowerCamelCase ).startswith('''mps''' ): _a = torch.manual_seed(_lowerCamelCase ) else: _a = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) _a = { '''image''': init_image, '''mask_image''': mask, '''image_embeds''': image_embeds, '''negative_image_embeds''': negative_image_embeds, '''generator''': generator, '''height''': 64, '''width''': 64, '''num_inference_steps''': 2, '''guidance_scale''': 4.0, '''output_type''': '''np''', } return inputs def _A ( self: Optional[Any] ): _a = '''cpu''' _a = self.get_dummy_components() _a = self.pipeline_class(**_lowerCamelCase ) _a = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) _a = pipe(**self.get_dummy_inputs(_lowerCamelCase ) ) _a = output.images _a = pipe( **self.get_dummy_inputs(_lowerCamelCase ) , return_dict=_lowerCamelCase , )[0] _a = image[0, -3:, -3:, -1] _a = image_from_tuple[0, -3:, -3:, -1] print(f"image.shape {image.shape}" ) assert image.shape == (1, 64, 64, 3) _a = np.array( [0.5_0_7_7_5_9_0_3, 0.4_9_5_2_7_1_9_5, 0.4_8_8_2_4_5_4_3, 0.5_0_1_9_2_2_3_7, 0.4_8_6_4_4_9_0_6, 0.4_9_3_7_3_8_1_4, 0.4_7_8_0_5_9_8, 0.4_7_2_3_4_8_2_7, 0.4_8_3_2_7_8_4_8] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 ), f" expected_slice {expected_slice}, but got {image_slice.flatten()}" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 ), f" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}" def _A ( self: Any ): super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class UpperCAmelCase ( unittest.TestCase ): def _A ( self: List[str] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _A ( self: List[Any] ): _a = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinskyv22/kandinskyv22_inpaint_cat_with_hat_fp16.npy''' ) _a = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png''' ) _a = np.ones((768, 768) , dtype=np.floataa ) _a = 0 _a = '''a hat''' _a = KandinskyVaaPriorPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-prior''' , torch_dtype=torch.floataa ) pipe_prior.to(_lowerCamelCase ) _a = KandinskyVaaInpaintPipeline.from_pretrained( '''kandinsky-community/kandinsky-2-2-decoder-inpaint''' , torch_dtype=torch.floataa ) _a = pipeline.to(_lowerCamelCase ) pipeline.set_progress_bar_config(disable=_lowerCamelCase ) _a = torch.Generator(device='''cpu''' ).manual_seed(0 ) _a = pipe_prior( _lowerCamelCase , generator=_lowerCamelCase , num_inference_steps=5 , negative_prompt='''''' , ).to_tuple() _a = pipeline( image=_lowerCamelCase , mask_image=_lowerCamelCase , image_embeds=_lowerCamelCase , negative_image_embeds=_lowerCamelCase , generator=_lowerCamelCase , num_inference_steps=100 , height=768 , width=768 , output_type='''np''' , ) _a = output.images[0] assert image.shape == (768, 768, 3) assert_mean_pixel_difference(_lowerCamelCase , _lowerCamelCase )
487
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case : def __init__( self :Optional[Any] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : int = num_of_nodes __SCREAMING_SNAKE_CASE : list[list[int]] = [] __SCREAMING_SNAKE_CASE : dict[int, int] = {} def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :int ): self.m_edges.append([u_node, v_node, weight] ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :int ): if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :int ): if self.m_component[u_node] != u_node: for k in self.m_component: __SCREAMING_SNAKE_CASE : Optional[Any] = self.find_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :list[int] , _lowerCamelCase :int , _lowerCamelCase :int ): if component_size[u_node] <= component_size[v_node]: __SCREAMING_SNAKE_CASE : List[Any] = v_node component_size[v_node] += component_size[u_node] self.set_component(_lowerCamelCase ) elif component_size[u_node] >= component_size[v_node]: __SCREAMING_SNAKE_CASE : Dict = self.find_component(_lowerCamelCase ) component_size[u_node] += component_size[v_node] self.set_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = [] __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : list[Any] = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) __SCREAMING_SNAKE_CASE : str = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = edge __SCREAMING_SNAKE_CASE : Optional[Any] = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): __SCREAMING_SNAKE_CASE : Optional[Any] = [u, v, w] for edge in minimum_weight_edge: if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = edge __SCREAMING_SNAKE_CASE : Tuple = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: mst_weight += w self.union(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) print(f'''Added edge [{u} - {v}]\nAdded weight: {w}\n''' ) num_of_components -= 1 __SCREAMING_SNAKE_CASE : Optional[Any] = [-1] * self.m_num_of_nodes print(f'''The total weight of the minimal spanning tree is: {mst_weight}''' ) def lowerCAmelCase_ ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
674
0
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase , __UpperCamelCase ): __lowercase : Tuple = BertConfig.from_json_file(lowercase_ ) print(f"""Building PyTorch model from configuration: {config}""" ) __lowercase : Optional[int] = BertForPreTraining(lowercase_ ) # Load weights from tf checkpoint load_tf_weights_in_bert(lowercase_ , lowercase_ , lowercase_ ) # Save pytorch-model print(f"""Save PyTorch model to {pytorch_dump_path}""" ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.' ) parser.add_argument( '--bert_config_file', default=None, type=str, required=True, help=( 'The config json file corresponding to the pre-trained BERT model. \n' 'This specifies the model architecture.' ), ) parser.add_argument( '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) a_ = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
76
"""simple docstring""" import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : Any , lowercase_ : int=None ): '''simple docstring''' assert torch_layer.weight.shape == weight.shape, F'''{torch_layer} layer.weight does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(lowercase_ ) if bias is not None: assert torch_layer.bias.shape == bias.shape, F'''{torch_layer} layer.bias does not match''' __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Tuple , lowercase_ : int , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) __SCREAMING_SNAKE_CASE : Tuple = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = weights[0][0][0] __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(layer_norm_a[0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # lsh weights + output __SCREAMING_SNAKE_CASE : Tuple = weights[0][1] if len(lowercase_ ) < 4: set_layer_weights_in_torch_lsh(lowercase_ , torch_block.attention , lowercase_ ) else: set_layer_weights_in_torch_local(lowercase_ , torch_block.attention , lowercase_ ) # intermediate weighs __SCREAMING_SNAKE_CASE : Any = weights[2][0][1][2] # Chunked Feed Forward if len(lowercase_ ) == 4: __SCREAMING_SNAKE_CASE : List[str] = intermediate_weights[2] # layernorm 2 __SCREAMING_SNAKE_CASE : List[str] = np.asarray(intermediate_weights[0][0] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # intermediate dense __SCREAMING_SNAKE_CASE : int = np.asarray(intermediate_weights[1][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) # intermediate out __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[4][0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = torch_model.reformer # word embeds __SCREAMING_SNAKE_CASE : int = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(lowercase_ ) , ) if isinstance(weights[3] , lowercase_ ): __SCREAMING_SNAKE_CASE : int = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): __SCREAMING_SNAKE_CASE : Dict = np.asarray(weights[3][emb_idx][0] ) assert ( position_embeddings.weights[emb_idx].shape == emb_weights.shape ), F'''{position_embeddings[emb_idx]} emb does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.tensor(lowercase_ ) ) __SCREAMING_SNAKE_CASE : List[Any] = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( lowercase_ ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): __SCREAMING_SNAKE_CASE : Union[str, Any] = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(lowercase_ , lowercase_ , lowercase_ ) # output layer norm __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[7][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # output embeddings __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[9][0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : Any , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = ReformerConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : List[str] = ReformerModelWithLMHead(lowercase_ ) with open(lowercase_ , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : int = pickle.load(lowercase_ )['''weights'''] set_model_weights_in_torch(lowercase_ , lowercase_ , config.hidden_size ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--trax_model_pkl_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained Reformer model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
674
0
def A__ ( snake_case_ : str ): SCREAMING_SNAKE_CASE__: List[Any]= hex_num.strip() if not hex_num: raise ValueError('''No value was passed to the function''' ) SCREAMING_SNAKE_CASE__: Optional[int]= hex_num[0] == '''-''' if is_negative: SCREAMING_SNAKE_CASE__: Optional[int]= hex_num[1:] try: SCREAMING_SNAKE_CASE__: Union[str, Any]= int(lowercase_ , 16 ) except ValueError: raise ValueError('''Invalid value was passed to the function''' ) SCREAMING_SNAKE_CASE__: List[str]= '''''' while int_num > 0: SCREAMING_SNAKE_CASE__: Union[str, Any]= str(int_num % 2 ) + bin_str int_num >>= 1 return int(('''-''' + bin_str) if is_negative else bin_str ) if __name__ == "__main__": import doctest doctest.testmod()
64
"""simple docstring""" from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''microsoft/xprophetnet-large-wiki100-cased''': ( '''https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json''' ), } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''xlm-prophetnet''' lowerCamelCase__ = ['''past_key_values'''] lowerCamelCase__ = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self :List[str] , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[Union[str, Callable]] = "gelu" , _lowerCamelCase :Optional[int] = 3_0_5_2_2 , _lowerCamelCase :Optional[int] = 1_0_2_4 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[int] = 5_1_2 , _lowerCamelCase :Optional[float] = 0.0_2 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 2 , _lowerCamelCase :Optional[int] = 3_2 , _lowerCamelCase :Optional[int] = 1_2_8 , _lowerCamelCase :Optional[bool] = False , _lowerCamelCase :Optional[float] = 0.0 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 1 , _lowerCamelCase :Optional[int] = 2 , **_lowerCamelCase :int , ): __SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_size __SCREAMING_SNAKE_CASE : List[Any] = encoder_ffn_dim __SCREAMING_SNAKE_CASE : str = num_encoder_layers __SCREAMING_SNAKE_CASE : Optional[Any] = num_encoder_attention_heads __SCREAMING_SNAKE_CASE : str = decoder_ffn_dim __SCREAMING_SNAKE_CASE : List[Any] = num_decoder_layers __SCREAMING_SNAKE_CASE : List[str] = num_decoder_attention_heads __SCREAMING_SNAKE_CASE : Dict = max_position_embeddings __SCREAMING_SNAKE_CASE : Any = init_std # Normal(0, this parameter) __SCREAMING_SNAKE_CASE : Any = activation_function # parameters for xlmprophetnet __SCREAMING_SNAKE_CASE : List[Any] = ngram __SCREAMING_SNAKE_CASE : int = num_buckets __SCREAMING_SNAKE_CASE : List[str] = relative_max_distance __SCREAMING_SNAKE_CASE : str = disable_ngram_loss __SCREAMING_SNAKE_CASE : Optional[int] = eps # 3 Types of Dropout __SCREAMING_SNAKE_CASE : int = attention_dropout __SCREAMING_SNAKE_CASE : Optional[Any] = activation_dropout __SCREAMING_SNAKE_CASE : Dict = dropout __SCREAMING_SNAKE_CASE : Any = use_cache super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , is_encoder_decoder=_lowerCamelCase , add_cross_attention=_lowerCamelCase , decoder_start_token_id=_lowerCamelCase , **_lowerCamelCase , ) @property def SCREAMING_SNAKE_CASE_ ( self :int ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[Any] ): raise NotImplementedError( '''This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and''' ''' `num_decoder_layers`.''' )
674
0
import unittest from transformers import PegasusTokenizer, PegasusTokenizerFast 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 a : int = get_tests_dir('''fixtures/test_sentencepiece_no_bos.model''') @require_sentencepiece @require_tokenizers class lowerCamelCase_ ( __UpperCAmelCase , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase = PegasusTokenizer __UpperCAmelCase = PegasusTokenizerFast __UpperCAmelCase = True __UpperCAmelCase = True def A ( self ) -> int: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing __lowercase = PegasusTokenizer(_lowerCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def A ( self ) -> Any: '''simple docstring''' return PegasusTokenizer.from_pretrained('''google/pegasus-large''' ) def A ( self , **snake_case_ ) -> Optional[Any]: '''simple docstring''' return PegasusTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def A ( self , snake_case_ ) -> int: '''simple docstring''' return ("This is a test", "This is a test") def A ( self ) -> Dict: '''simple docstring''' __lowercase = '''</s>''' __lowercase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCamelCase ) , _lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCamelCase ) , _lowerCamelCase ) def A ( self ) -> Dict: '''simple docstring''' __lowercase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<pad>''' ) self.assertEqual(vocab_keys[1] , '''</s>''' ) self.assertEqual(vocab_keys[-1] , '''v''' ) self.assertEqual(len(_lowerCamelCase ) , 1_1_0_3 ) def A ( self ) -> Optional[int]: '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_1_0_3 ) def A ( self ) -> Tuple: '''simple docstring''' __lowercase = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __lowercase = self.tokenizer_class.from_pretrained(self.tmpdirname ) __lowercase = ( '''Let\'s see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important''' ''' </s> <pad> <pad> <pad>''' ) __lowercase = rust_tokenizer([raw_input_str] , return_tensors=_lowerCamelCase , add_special_tokens=_lowerCamelCase ).input_ids[0] __lowercase = py_tokenizer([raw_input_str] , return_tensors=_lowerCamelCase , add_special_tokens=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def A ( self ) -> Optional[Any]: '''simple docstring''' __lowercase = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word __lowercase = '''<mask_1> To ensure a <mask_2> flow of bank resolutions.''' __lowercase = [2, 4_1_3, 6_1_5, 1_1_4, 3, 1_9_7_1, 1_1_3, 1_6_7_9, 1_0_7_1_0, 1_0_7, 1] __lowercase = tokenizer([raw_input_str] , return_tensors=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def A ( self ) -> Optional[Any]: '''simple docstring''' __lowercase = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6_1_0_3 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 1_0_3 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 1_0_5 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1_0_2_4 __lowercase = '''To ensure a smooth flow of bank resolutions.''' __lowercase = [4_1_3, 6_1_5, 1_1_4, 2_2_9_1, 1_9_7_1, 1_1_3, 1_6_7_9, 1_0_7_1_0, 1_0_7, 1] __lowercase = tokenizer([raw_input_str] , return_tensors=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def A ( self ) -> int: '''simple docstring''' __lowercase = ['''This is going to be way too long.''' * 1_5_0, '''short example'''] __lowercase = ['''not super long but more than 5 tokens''', '''tiny'''] __lowercase = self._large_tokenizer(_lowerCamelCase , padding=_lowerCamelCase , truncation=_lowerCamelCase , return_tensors='''pt''' ) __lowercase = self._large_tokenizer( text_target=_lowerCamelCase , max_length=5 , padding=_lowerCamelCase , truncation=_lowerCamelCase , return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 1_0_2_4) assert batch.attention_mask.shape == (2, 1_0_2_4) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCamelCase ) == 2 # input_ids, attention_mask. @slow def A ( self ) -> Any: '''simple docstring''' __lowercase = {'''input_ids''': [[3_8_9_7_9, 1_4_3, 1_8_4_8_5, 6_0_6, 1_3_0, 2_6_6_6_9, 8_7_6_8_6, 1_2_1, 5_4_1_8_9, 1_1_2_9, 1_1_1, 2_6_6_6_9, 8_7_6_8_6, 1_2_1, 9_1_1_4, 1_4_7_8_7, 1_2_1, 1_3_2_4_9, 1_5_8, 5_9_2, 9_5_6, 1_2_1, 1_4_6_2_1, 3_1_5_7_6, 1_4_3, 6_2_6_1_3, 1_0_8, 9_6_8_8, 9_3_0, 4_3_4_3_0, 1_1_5_6_2, 6_2_6_1_3, 3_0_4, 1_0_8, 1_1_4_4_3, 8_9_7, 1_0_8, 9_3_1_4, 1_7_4_1_5, 6_3_3_9_9, 1_0_8, 1_1_4_4_3, 7_6_1_4, 1_8_3_1_6, 1_1_8, 4_2_8_4, 7_1_4_8, 1_2_4_3_0, 1_4_3, 1_4_0_0, 2_5_7_0_3, 1_5_8, 1_1_1, 4_2_8_4, 7_1_4_8, 1_1_7_7_2, 1_4_3, 2_1_2_9_7, 1_0_6_4, 1_5_8, 1_2_2, 2_0_4, 3_5_0_6, 1_7_5_4, 1_1_3_3, 1_4_7_8_7, 1_5_8_1, 1_1_5, 3_3_2_2_4, 4_4_8_2, 1_1_1, 1_3_5_5, 1_1_0, 2_9_1_7_3, 3_1_7, 5_0_8_3_3, 1_0_8, 2_0_1_4_7, 9_4_6_6_5, 1_1_1, 7_7_1_9_8, 1_0_7, 1], [1_1_0, 6_2_6_1_3, 1_1_7, 6_3_8, 1_1_2, 1_1_3_3, 1_2_1, 2_0_0_9_8, 1_3_5_5, 7_9_0_5_0, 1_3_8_7_2, 1_3_5, 1_5_9_6, 5_3_5_4_1, 1_3_5_2, 1_4_1, 1_3_0_3_9, 5_5_4_2, 1_2_4, 3_0_2, 5_1_8, 1_1_1, 2_6_8, 2_9_5_6, 1_1_5, 1_4_9, 4_4_2_7, 1_0_7, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1_3_9, 1_2_3_5, 2_7_9_9, 1_8_2_8_9, 1_7_7_8_0, 2_0_4, 1_0_9, 9_4_7_4, 1_2_9_6, 1_0_7, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_lowerCamelCase , model_name='''google/bigbird-pegasus-large-arxiv''' , revision='''ba85d0851d708441f91440d509690f1ab6353415''' , ) @require_sentencepiece @require_tokenizers class lowerCamelCase_ ( __UpperCAmelCase , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase = PegasusTokenizer __UpperCAmelCase = PegasusTokenizerFast __UpperCAmelCase = True __UpperCAmelCase = True def A ( self ) -> Dict: '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing __lowercase = PegasusTokenizer(_lowerCamelCase , offset=0 , mask_token_sent=_lowerCamelCase , mask_token='''[MASK]''' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def A ( self ) -> Optional[Any]: '''simple docstring''' return PegasusTokenizer.from_pretrained('''google/bigbird-pegasus-large-arxiv''' ) def A ( self , **snake_case_ ) -> List[str]: '''simple docstring''' return PegasusTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def A ( self , snake_case_ ) -> Dict: '''simple docstring''' return ("This is a test", "This is a test") def A ( self ) -> Dict: '''simple docstring''' __lowercase = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) __lowercase = self.tokenizer_class.from_pretrained(self.tmpdirname ) __lowercase = ( '''Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>''' ''' <pad> <pad> <pad>''' ) __lowercase = rust_tokenizer([raw_input_str] , return_tensors=_lowerCamelCase , add_special_tokens=_lowerCamelCase ).input_ids[0] __lowercase = py_tokenizer([raw_input_str] , return_tensors=_lowerCamelCase , add_special_tokens=_lowerCamelCase ).input_ids[0] self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) @require_torch def A ( self ) -> str: '''simple docstring''' __lowercase = ['''This is going to be way too long.''' * 1_0_0_0, '''short example'''] __lowercase = ['''not super long but more than 5 tokens''', '''tiny'''] __lowercase = self._large_tokenizer(_lowerCamelCase , padding=_lowerCamelCase , truncation=_lowerCamelCase , return_tensors='''pt''' ) __lowercase = self._large_tokenizer( text_target=_lowerCamelCase , max_length=5 , padding=_lowerCamelCase , truncation=_lowerCamelCase , return_tensors='''pt''' ) assert batch.input_ids.shape == (2, 4_0_9_6) assert batch.attention_mask.shape == (2, 4_0_9_6) assert targets["input_ids"].shape == (2, 5) assert len(_lowerCamelCase ) == 2 # input_ids, attention_mask. def A ( self ) -> str: '''simple docstring''' __lowercase = ( '''This is an example string that is used to test the original TF implementation against the HF''' ''' implementation''' ) __lowercase = self._large_tokenizer(_lowerCamelCase ).input_ids self.assertListEqual( _lowerCamelCase , [1_8_2, 1_1_7, 1_4_2, 5_8_7, 4_2_1_1, 1_2_0, 1_1_7, 2_6_3, 1_1_2, 8_0_4, 1_0_9, 8_5_6, 2_5_0_1_6, 3_1_3_7, 4_6_4, 1_0_9, 2_6_9_5_5, 3_1_3_7, 1] , )
639
"""simple docstring""" import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) _lowerCamelCase = [ '''cross_validation.py''', '''gradient_accumulation.py''', '''local_sgd.py''', '''multi_process_metrics.py''', '''memory.py''', '''automatic_gradient_accumulation.py''', '''fsdp_with_peak_mem_tracking.py''', '''deepspeed_with_config_support.py''', '''megatron_lm_gpt_pretraining.py''', ] class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :bool , _lowerCamelCase :str = None , _lowerCamelCase :list = None ): __SCREAMING_SNAKE_CASE : List[str] = None __SCREAMING_SNAKE_CASE : Optional[Any] = os.path.abspath(os.path.join('''examples''' , '''by_feature''' ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath('''examples''' ) for item in os.listdir(_lowerCamelCase ): if item not in EXCLUDE_EXAMPLES: __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_lowerCamelCase , _lowerCamelCase ) if os.path.isfile(_lowerCamelCase ) and ".py" in item_path: with self.subTest( tested_script=_lowerCamelCase , feature_script=_lowerCamelCase , tested_section='''main()''' if parser_only else '''training_function()''' , ): __SCREAMING_SNAKE_CASE : Tuple = compare_against_test( os.path.join(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = '''\n'''.join(_lowerCamelCase ) if special_strings is not None: for string in special_strings: __SCREAMING_SNAKE_CASE : List[Any] = diff.replace(_lowerCamelCase , '''''' ) self.assertEqual(_lowerCamelCase , '''''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath(os.path.join('''examples''' , '''cv_example.py''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = [ ''' ''' * 1_6 + '''{\n\n''', ''' ''' * 2_0 + '''"accuracy": eval_metric["accuracy"],\n\n''', ''' ''' * 2_0 + '''"f1": eval_metric["f1"],\n\n''', ''' ''' * 2_0 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''', ''' ''' * 2_0 + '''"epoch": epoch,\n\n''', ''' ''' * 1_6 + '''},\n\n''', ''' ''' * 1_6 + '''step=epoch,\n''', ''' ''' * 1_2, ''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''', ] self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = False @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().setUpClass() __SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : str = os.path.join(cls._tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) __SCREAMING_SNAKE_CASE : List[Any] = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().tearDownClass() shutil.rmtree(cls._tmpdir ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : str = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''epoch_0''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() __SCREAMING_SNAKE_CASE : Optional[int] = run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''step_2''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )} '''.split() __SCREAMING_SNAKE_CASE : Any = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )} '''.split() __SCREAMING_SNAKE_CASE : List[str] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) if torch.cuda.is_available(): __SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.device_count() else: __SCREAMING_SNAKE_CASE : Optional[int] = 1 if num_processes > 1: self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) else: self.assertIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ''' examples/by_feature/cross_validation.py --num_folds 2 '''.split() with mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''0'''} ): __SCREAMING_SNAKE_CASE : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = re.findall('''({.+})''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = [r for r in results if '''accuracy''' in r][-1] __SCREAMING_SNAKE_CASE : Tuple = ast.literal_eval(_lowerCamelCase ) self.assertGreaterEqual(results['''accuracy'''] , 0.7_5 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ['''examples/by_feature/multi_process_metrics.py'''] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with tempfile.TemporaryDirectory() as tmpdir: __SCREAMING_SNAKE_CASE : int = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(_lowerCamelCase , '''tracking''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''examples/by_feature/gradient_accumulation.py'''] run_command(self._launch_args + testargs ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = ['''examples/by_feature/local_sgd.py'''] run_command(self._launch_args + testargs )
674
0
import collections import tempfile import unittest import numpy as np from transformers.testing_utils import ( is_pt_flax_cross_test, require_flax, require_torch, require_vision, slow, torch_device, ) from transformers.utils import is_flax_available, is_torch_available, is_vision_available from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask from ..bert.test_modeling_flax_bert import FlaxBertModelTester from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester from ..vit.test_modeling_flax_vit import FlaxViTModelTester if is_flax_available(): from transformers import ( FlaxBertModel, FlaxCLIPVisionModel, FlaxVisionTextDualEncoderModel, FlaxViTModel, VisionTextDualEncoderConfig, VisionTextDualEncoderProcessor, ) from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) if is_torch_available(): import torch from transformers import VisionTextDualEncoderModel if is_vision_available(): from PIL import Image def lowerCAmelCase_ ( lowercase: Any ) -> List[Any]: '''simple docstring''' if isinstance(lowercase_ , collections.abc.Iterable ): return x return (x, x) @require_flax class __magic_name__ : """simple docstring""" def lowerCAmelCase ( self : Union[str, Any] , _lowercase : Tuple , _lowercase : Tuple ): """simple docstring""" pass def lowerCAmelCase ( self : str ): """simple docstring""" pass def lowerCAmelCase ( self : List[Any] ): """simple docstring""" pass def lowerCAmelCase ( self : Dict , _lowercase : np.ndarray , _lowercase : np.ndarray , _lowercase : float ): """simple docstring""" _UpperCamelCase: Dict = np.abs((a - b) ).max() self.assertLessEqual(_lowerCamelCase , _lowerCamelCase , f"""Difference between torch and flax is {diff} (>= {tol}).""" ) def lowerCAmelCase ( self : str , _lowercase : List[str] , _lowercase : Dict , _lowercase : Optional[int] , _lowercase : List[str] , _lowercase : int=None , **_lowercase : Union[str, Any] ): """simple docstring""" _UpperCamelCase: int = VisionTextDualEncoderConfig.from_vision_text_configs(_lowerCamelCase , _lowerCamelCase ) _UpperCamelCase: int = FlaxVisionTextDualEncoderModel(_lowerCamelCase ) _UpperCamelCase: Union[str, Any] = model(input_ids=_lowerCamelCase , pixel_values=_lowerCamelCase , attention_mask=_lowerCamelCase ) self.assertEqual(output['''text_embeds'''].shape , (input_ids.shape[0], config.projection_dim) ) self.assertEqual(output['''image_embeds'''].shape , (pixel_values.shape[0], config.projection_dim) ) def lowerCAmelCase ( self : str , _lowercase : List[str] , _lowercase : Tuple , _lowercase : List[str] , _lowercase : Dict , _lowercase : int=None , **_lowercase : int ): """simple docstring""" _UpperCamelCase: Optional[Any] = self.get_vision_text_model(_lowerCamelCase , _lowerCamelCase ) _UpperCamelCase: str = {'''vision_model''': vision_model, '''text_model''': text_model} _UpperCamelCase: Optional[int] = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_lowerCamelCase ) _UpperCamelCase: Dict = model(input_ids=_lowerCamelCase , pixel_values=_lowerCamelCase , attention_mask=_lowerCamelCase ) self.assertEqual(output['''text_embeds'''].shape , (input_ids.shape[0], model.config.projection_dim) ) self.assertEqual(output['''image_embeds'''].shape , (pixel_values.shape[0], model.config.projection_dim) ) def lowerCAmelCase ( self : Any , _lowercase : Dict , _lowercase : Optional[int] , _lowercase : Dict , _lowercase : str , _lowercase : List[Any]=None , **_lowercase : Dict ): """simple docstring""" _UpperCamelCase: Tuple = self.get_vision_text_model(_lowerCamelCase , _lowerCamelCase ) _UpperCamelCase: int = {'''vision_model''': vision_model, '''text_model''': text_model} _UpperCamelCase: Any = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_lowerCamelCase ) _UpperCamelCase: Any = model(input_ids=_lowerCamelCase , pixel_values=_lowerCamelCase , attention_mask=_lowerCamelCase ) _UpperCamelCase: Optional[Any] = output[0] with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_lowerCamelCase ) _UpperCamelCase: List[Any] = FlaxVisionTextDualEncoderModel.from_pretrained(_lowerCamelCase ) _UpperCamelCase: str = model(input_ids=_lowerCamelCase , pixel_values=_lowerCamelCase , attention_mask=_lowerCamelCase ) _UpperCamelCase: Dict = after_output[0] _UpperCamelCase: Tuple = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(_lowerCamelCase , 1E-3 ) def lowerCAmelCase ( self : Optional[int] , _lowercase : List[Any] , _lowercase : int , _lowercase : int , _lowercase : List[str] , _lowercase : List[Any]=None , **_lowercase : Tuple ): """simple docstring""" _UpperCamelCase: int = self.get_vision_text_model(_lowerCamelCase , _lowerCamelCase ) _UpperCamelCase: Dict = {'''vision_model''': vision_model, '''text_model''': text_model} _UpperCamelCase: str = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_lowerCamelCase ) _UpperCamelCase: Union[str, Any] = model( input_ids=_lowerCamelCase , pixel_values=_lowerCamelCase , attention_mask=_lowerCamelCase , output_attentions=_lowerCamelCase ) _UpperCamelCase: Optional[Any] = output.vision_model_output.attentions self.assertEqual(len(_lowerCamelCase ) , vision_config.num_hidden_layers ) # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token) _UpperCamelCase: Tuple = to_atuple(vision_model.config.image_size ) _UpperCamelCase: List[Any] = to_atuple(vision_model.config.patch_size ) _UpperCamelCase: Tuple = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) _UpperCamelCase: int = num_patches + 1 self.assertEqual(vision_attentions[0].shape[-3:] , (vision_config.num_attention_heads, seq_len, seq_len) ) _UpperCamelCase: Optional[int] = output.text_model_output.attentions self.assertEqual(len(_lowerCamelCase ) , text_config.num_hidden_layers ) self.assertEqual( text_attentions[0].shape[-3:] , (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1]) , ) def lowerCAmelCase ( self : Union[str, Any] , _lowercase : Optional[Any] , _lowercase : Any , _lowercase : int ): """simple docstring""" pt_model.to(_lowerCamelCase ) pt_model.eval() # prepare inputs _UpperCamelCase: Union[str, Any] = inputs_dict _UpperCamelCase: Tuple = {k: torch.tensor(v.tolist() ) for k, v in flax_inputs.items()} with torch.no_grad(): _UpperCamelCase: Union[str, Any] = pt_model(**_lowerCamelCase ).to_tuple() _UpperCamelCase: Optional[Any] = fx_model(**_lowerCamelCase ).to_tuple() self.assertEqual(len(_lowerCamelCase ) , len(_lowerCamelCase ) , '''Output lengths differ between Flax and PyTorch''' ) for fx_output, pt_output in zip(fx_outputs[:4] , pt_outputs[:4] ): self.assert_almost_equals(_lowerCamelCase , pt_output.numpy() , 4E-2 ) # PT -> Flax with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(_lowerCamelCase ) _UpperCamelCase: Union[str, Any] = FlaxVisionTextDualEncoderModel.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) _UpperCamelCase: Optional[Any] = fx_model_loaded(**_lowerCamelCase ).to_tuple() self.assertEqual(len(_lowerCamelCase ) , len(_lowerCamelCase ) , '''Output lengths differ between Flax and PyTorch''' ) for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4] , pt_outputs[:4] ): self.assert_almost_equals(_lowerCamelCase , pt_output.numpy() , 4E-2 ) # Flax -> PT with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(_lowerCamelCase ) _UpperCamelCase: List[Any] = VisionTextDualEncoderModel.from_pretrained(_lowerCamelCase , from_flax=_lowerCamelCase ) pt_model_loaded.to(_lowerCamelCase ) pt_model_loaded.eval() with torch.no_grad(): _UpperCamelCase: Optional[int] = pt_model_loaded(**_lowerCamelCase ).to_tuple() self.assertEqual(len(_lowerCamelCase ) , len(_lowerCamelCase ) , '''Output lengths differ between Flax and PyTorch''' ) for fx_output, pt_output_loaded in zip(fx_outputs[:4] , pt_outputs_loaded[:4] ): self.assert_almost_equals(_lowerCamelCase , pt_output_loaded.numpy() , 4E-2 ) def lowerCAmelCase ( self : Optional[int] , _lowercase : str , _lowercase : Optional[Any] , _lowercase : Dict ): """simple docstring""" _UpperCamelCase: Any = VisionTextDualEncoderConfig.from_vision_text_configs(_lowerCamelCase , _lowerCamelCase ) _UpperCamelCase: Any = VisionTextDualEncoderModel(_lowerCamelCase ) _UpperCamelCase: str = FlaxVisionTextDualEncoderModel(_lowerCamelCase ) _UpperCamelCase: List[str] = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , _lowerCamelCase ) _UpperCamelCase: str = fx_state self.check_pt_flax_equivalence(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def lowerCAmelCase ( self : Any , _lowercase : List[Any] , _lowercase : Optional[int] , _lowercase : List[Any] ): """simple docstring""" _UpperCamelCase: str = VisionTextDualEncoderConfig.from_vision_text_configs(_lowerCamelCase , _lowerCamelCase ) _UpperCamelCase: Tuple = VisionTextDualEncoderModel(_lowerCamelCase ) _UpperCamelCase: Dict = FlaxVisionTextDualEncoderModel(_lowerCamelCase ) _UpperCamelCase: Optional[Any] = load_flax_weights_in_pytorch_model(_lowerCamelCase , fx_model.params ) self.check_pt_flax_equivalence(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def lowerCAmelCase ( self : Optional[int] ): """simple docstring""" _UpperCamelCase: List[Any] = self.prepare_config_and_inputs() self.check_model_from_pretrained_configs(**_lowerCamelCase ) def lowerCAmelCase ( self : int ): """simple docstring""" _UpperCamelCase: str = self.prepare_config_and_inputs() self.check_vision_text_dual_encoder_from_pretrained(**_lowerCamelCase ) def lowerCAmelCase ( self : Any ): """simple docstring""" _UpperCamelCase: int = self.prepare_config_and_inputs() self.check_save_load(**_lowerCamelCase ) def lowerCAmelCase ( self : Tuple ): """simple docstring""" _UpperCamelCase: Dict = self.prepare_config_and_inputs() self.check_vision_text_output_attention(**_lowerCamelCase ) @is_pt_flax_cross_test def lowerCAmelCase ( self : List[Any] ): """simple docstring""" _UpperCamelCase: Union[str, Any] = self.prepare_config_and_inputs() _UpperCamelCase: Union[str, Any] = config_inputs_dict.pop('''vision_config''' ) _UpperCamelCase: Optional[int] = config_inputs_dict.pop('''text_config''' ) _UpperCamelCase: Optional[Any] = config_inputs_dict self.check_equivalence_pt_to_flax(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) self.check_equivalence_flax_to_pt(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @slow def lowerCAmelCase ( self : List[str] ): """simple docstring""" _UpperCamelCase: List[Any] = self.get_pretrained_model_and_inputs() _UpperCamelCase: List[Any] = model_a(**_lowerCamelCase ) _UpperCamelCase: List[str] = outputs[0] with tempfile.TemporaryDirectory() as tmp_dirname: model_a.save_pretrained(_lowerCamelCase ) _UpperCamelCase: Union[str, Any] = FlaxVisionTextDualEncoderModel.from_pretrained(_lowerCamelCase ) _UpperCamelCase: Union[str, Any] = model_a(**_lowerCamelCase ) _UpperCamelCase: Any = after_outputs[0] _UpperCamelCase: Union[str, Any] = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(_lowerCamelCase , 1E-5 ) @require_flax class __magic_name__ ( __UpperCAmelCase , unittest.TestCase ): """simple docstring""" def lowerCAmelCase ( self : Dict ): """simple docstring""" _UpperCamelCase: Any = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( '''hf-internal-testing/tiny-random-vit''' , '''hf-internal-testing/tiny-bert''' , vision_from_pt=_lowerCamelCase , text_from_pt=_lowerCamelCase , ) _UpperCamelCase: List[str] = 13 _UpperCamelCase: Any = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) _UpperCamelCase: Optional[int] = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) _UpperCamelCase: Optional[Any] = random_attention_mask([batch_size, 4] ) _UpperCamelCase: List[str] = {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask} return model, inputs def lowerCAmelCase ( self : List[Any] , _lowercase : Tuple , _lowercase : Optional[int] ): """simple docstring""" _UpperCamelCase: Dict = FlaxViTModel(_lowerCamelCase ) _UpperCamelCase: List[str] = FlaxBertModel(_lowerCamelCase ) return vision_model, text_model def lowerCAmelCase ( self : Any ): """simple docstring""" _UpperCamelCase: List[Any] = FlaxViTModelTester(self ) _UpperCamelCase: Dict = FlaxBertModelTester(self ) _UpperCamelCase: Tuple = vit_model_tester.prepare_config_and_inputs() _UpperCamelCase: Tuple = bert_model_tester.prepare_config_and_inputs() _UpperCamelCase: Optional[int] = vision_config_and_inputs _UpperCamelCase: Any = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_torch class __magic_name__ ( __UpperCAmelCase , unittest.TestCase ): """simple docstring""" def lowerCAmelCase ( self : Optional[int] ): """simple docstring""" _UpperCamelCase: Optional[int] = FlaxVisionTextDualEncoderModel.from_vision_text_pretrained( '''hf-internal-testing/tiny-random-clip''' , '''hf-internal-testing/tiny-bert''' , vision_from_pt=_lowerCamelCase , text_from_pt=_lowerCamelCase , ) _UpperCamelCase: Tuple = 13 _UpperCamelCase: List[str] = floats_tensor( [ batch_size, model.config.vision_config.num_channels, model.config.vision_config.image_size, model.config.vision_config.image_size, ] ) _UpperCamelCase: Union[str, Any] = ids_tensor([batch_size, 4] , model.config.text_config.vocab_size ) _UpperCamelCase: List[str] = random_attention_mask([batch_size, 4] ) _UpperCamelCase: Optional[Any] = {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask} return model, inputs def lowerCAmelCase ( self : str , _lowercase : List[str] , _lowercase : int ): """simple docstring""" _UpperCamelCase: List[Any] = FlaxCLIPVisionModel(_lowerCamelCase ) _UpperCamelCase: Any = FlaxBertModel(_lowerCamelCase ) return vision_model, text_model def lowerCAmelCase ( self : List[str] ): """simple docstring""" _UpperCamelCase: List[Any] = FlaxCLIPVisionModelTester(self ) _UpperCamelCase: int = FlaxBertModelTester(self ) _UpperCamelCase: List[str] = clip_model_tester.prepare_config_and_inputs() _UpperCamelCase: Tuple = bert_model_tester.prepare_config_and_inputs() _UpperCamelCase: Dict = vision_config_and_inputs _UpperCamelCase: Optional[Any] = text_config_and_inputs # make sure that cross attention layers are added return { "text_config": text_config, "vision_config": vision_config, "pixel_values": pixel_values, "attention_mask": attention_mask, "input_ids": input_ids, "token_type_ids": token_type_ids, } @require_flax @require_vision class __magic_name__ ( unittest.TestCase ): """simple docstring""" @slow def lowerCAmelCase ( self : Dict ): """simple docstring""" _UpperCamelCase: List[Any] = FlaxVisionTextDualEncoderModel.from_pretrained('''clip-italian/clip-italian''' , logit_scale_init_value=1.0 ) _UpperCamelCase: List[str] = VisionTextDualEncoderProcessor.from_pretrained('''clip-italian/clip-italian''' ) _UpperCamelCase: Union[str, Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) _UpperCamelCase: Union[str, Any] = processor( text=['''una foto di un gatto''', '''una foto di un cane'''] , images=_lowerCamelCase , padding=_lowerCamelCase , return_tensors='''np''' ) _UpperCamelCase: int = model(**_lowerCamelCase ) # verify the logits self.assertEqual(outputs.logits_per_image.shape , (inputs.pixel_values.shape[0], inputs.input_ids.shape[0]) ) self.assertEqual( outputs.logits_per_text.shape , (inputs.input_ids.shape[0], inputs.pixel_values.shape[0]) , ) _UpperCamelCase: Dict = np.array([[1.2284727, 0.3104122]] ) self.assertTrue(np.allclose(outputs.logits_per_image , _lowerCamelCase , atol=1E-3 ) )
271
"""simple docstring""" import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from utils_qa import postprocess_qa_predictions import transformers from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed from transformers.trainer_pt_utils import nested_concat, nested_truncate _lowerCamelCase = trt.Logger(trt.Logger.WARNING) _lowerCamelCase = absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) _lowerCamelCase = logging.getLogger(__name__) _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--onnx_model_path''', default=None, type=str, required=True, help='''Path to ONNX model: ''', ) parser.add_argument( '''--output_dir''', default=None, type=str, required=True, help='''The output directory where the model checkpoints and predictions will be written.''', ) # Other parameters parser.add_argument( '''--tokenizer_name''', default='''''', type=str, required=True, help='''Pretrained tokenizer name or path if not the same as model_name''', ) parser.add_argument( '''--version_2_with_negative''', action='''store_true''', help='''If true, the SQuAD examples contain some that do not have an answer.''', ) parser.add_argument( '''--null_score_diff_threshold''', type=float, default=0.0, help='''If null_score - best_non_null is greater than the threshold predict null.''', ) parser.add_argument( '''--max_seq_length''', default=3_84, type=int, help=( '''The maximum total input sequence length after WordPiece tokenization. Sequences ''' '''longer than this will be truncated, and sequences shorter than this will be padded.''' ), ) parser.add_argument( '''--doc_stride''', default=1_28, type=int, help='''When splitting up a long document into chunks, how much stride to take between chunks.''', ) parser.add_argument('''--per_device_eval_batch_size''', default=8, type=int, help='''Batch size per GPU/CPU for evaluation.''') parser.add_argument( '''--n_best_size''', default=20, type=int, help='''The total number of n-best predictions to generate in the nbest_predictions.json output file.''', ) parser.add_argument( '''--max_answer_length''', default=30, type=int, help=( '''The maximum length of an answer that can be generated. This is needed because the start ''' '''and end predictions are not conditioned on one another.''' ), ) parser.add_argument('''--seed''', type=int, default=42, help='''random seed for initialization''') parser.add_argument( '''--dataset_name''', type=str, default=None, required=True, help='''The name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--dataset_config_name''', type=str, default=None, help='''The configuration name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--preprocessing_num_workers''', type=int, default=4, help='''A csv or a json file containing the training data.''' ) parser.add_argument('''--overwrite_cache''', action='''store_true''', help='''Overwrite the cached training and evaluation sets''') parser.add_argument( '''--fp16''', action='''store_true''', help='''Whether to use 16-bit (mixed) precision instead of 32-bit''', ) parser.add_argument( '''--int8''', action='''store_true''', help='''Whether to use INT8''', ) _lowerCamelCase = parser.parse_args() if args.tokenizer_name: _lowerCamelCase = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) else: raise ValueError( '''You are instantiating a new tokenizer from scratch. This is not supported by this script.''' '''You can do it from another script, save it, and load it from here, using --tokenizer_name.''' ) logger.info('''Training/evaluation parameters %s''', args) _lowerCamelCase = args.per_device_eval_batch_size _lowerCamelCase = (args.eval_batch_size, args.max_seq_length) # TRT Engine properties _lowerCamelCase = True _lowerCamelCase = '''temp_engine/bert-fp32.engine''' if args.fpaa: _lowerCamelCase = '''temp_engine/bert-fp16.engine''' if args.inta: _lowerCamelCase = '''temp_engine/bert-int8.engine''' # import ONNX file if not os.path.exists('''temp_engine'''): os.makedirs('''temp_engine''') _lowerCamelCase = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser( network, TRT_LOGGER ) as parser: with open(args.onnx_model_path, '''rb''') as model: if not parser.parse(model.read()): for error in range(parser.num_errors): print(parser.get_error(error)) # Query input names and shapes from parsed TensorRT network _lowerCamelCase = [network.get_input(i) for i in range(network.num_inputs)] _lowerCamelCase = [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: _lowerCamelCase = 1 << 50 if STRICT_TYPES: config.set_flag(trt.BuilderFlag.STRICT_TYPES) if args.fpaa: config.set_flag(trt.BuilderFlag.FPaa) if args.inta: config.set_flag(trt.BuilderFlag.INTa) _lowerCamelCase = builder.create_optimization_profile() config.add_optimization_profile(profile) for i in range(len(input_names)): profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE) _lowerCamelCase = builder.build_engine(network, config) # serialize_engine and store in file (can be directly loaded and deserialized): with open(engine_name, '''wb''') as f: f.write(engine.serialize()) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Tuple , lowercase_ : Any , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = np.asarray(inputs['''input_ids'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''attention_mask'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''token_type_ids'''] , dtype=np.intaa ) # Copy inputs cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , lowercase_ ) # start time __SCREAMING_SNAKE_CASE : Tuple = time.time() # Run inference context.execute_async( bindings=[int(lowercase_ ) for d_inp in d_inputs] + [int(lowercase_ ), int(lowercase_ )] , stream_handle=stream.handle ) # Transfer predictions back from GPU cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) # Synchronize the stream and take time stream.synchronize() # end time __SCREAMING_SNAKE_CASE : List[str] = time.time() __SCREAMING_SNAKE_CASE : int = end_time - start_time __SCREAMING_SNAKE_CASE : int = (h_outputa, h_outputa) # print(outputs) return outputs, infer_time # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. _lowerCamelCase = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). if args.dataset_name is not None: # Downloading and loading a dataset from the hub. _lowerCamelCase = load_dataset(args.dataset_name, args.dataset_config_name) else: raise ValueError('''Evaluation requires a dataset name''') # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Preprocessing the datasets. # Preprocessing is slighlty different for training and evaluation. _lowerCamelCase = raw_datasets['''validation'''].column_names _lowerCamelCase = '''question''' if '''question''' in column_names else column_names[0] _lowerCamelCase = '''context''' if '''context''' in column_names else column_names[1] _lowerCamelCase = '''answers''' if '''answers''' in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). _lowerCamelCase = tokenizer.padding_side == '''right''' if args.max_seq_length > tokenizer.model_max_length: logger.warning( f'The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the' f'model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.' ) _lowerCamelCase = min(args.max_seq_length, tokenizer.model_max_length) def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = [q.lstrip() for q in examples[question_column_name]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer( examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='''only_second''' if pad_on_right else '''only_first''' , max_length=lowercase_ , stride=args.doc_stride , return_overflowing_tokens=lowercase_ , return_offsets_mapping=lowercase_ , padding='''max_length''' , ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. __SCREAMING_SNAKE_CASE : Optional[int] = tokenized_examples.pop('''overflow_to_sample_mapping''' ) # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. __SCREAMING_SNAKE_CASE : Any = [] for i in range(len(tokenized_examples['''input_ids'''] ) ): # Grab the sequence corresponding to that example (to know what is the context and what is the question). __SCREAMING_SNAKE_CASE : int = tokenized_examples.sequence_ids(lowercase_ ) __SCREAMING_SNAKE_CASE : str = 1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. __SCREAMING_SNAKE_CASE : str = sample_mapping[i] tokenized_examples["example_id"].append(examples['''id'''][sample_index] ) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. __SCREAMING_SNAKE_CASE : List[str] = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples['''offset_mapping'''][i] ) ] return tokenized_examples _lowerCamelCase = raw_datasets['''validation'''] # Validation Feature Creation _lowerCamelCase = eval_examples.map( prepare_validation_features, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc='''Running tokenizer on validation dataset''', ) _lowerCamelCase = default_data_collator _lowerCamelCase = eval_dataset.remove_columns(['''example_id''', '''offset_mapping''']) _lowerCamelCase = DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any]="eval" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = postprocess_qa_predictions( examples=lowercase_ , features=lowercase_ , predictions=lowercase_ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=lowercase_ , ) # Format the result to the format the metric expects. if args.version_2_with_negative: __SCREAMING_SNAKE_CASE : Union[str, Any] = [ {'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items() ] else: __SCREAMING_SNAKE_CASE : int = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()] __SCREAMING_SNAKE_CASE : Any = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=lowercase_ , label_ids=lowercase_ ) _lowerCamelCase = load_metric('''squad_v2''' if args.version_2_with_negative else '''squad''') # Evaluation! logger.info('''Loading ONNX model %s for evaluation''', args.onnx_model_path) with open(engine_name, '''rb''') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine( f.read() ) as engine, engine.create_execution_context() as context: # setup for TRT inferrence for i in range(len(input_names)): context.set_binding_shape(i, INPUT_SHAPE) assert context.all_binding_shapes_specified def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' return trt.volume(engine.get_binding_shape(lowercase_ ) ) * engine.get_binding_dtype(lowercase_ ).itemsize # Allocate device memory for inputs and outputs. _lowerCamelCase = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. _lowerCamelCase = cuda.Stream() # Evaluation logger.info('''***** Running Evaluation *****''') logger.info(f' Num examples = {len(eval_dataset)}') logger.info(f' Batch size = {args.per_device_eval_batch_size}') _lowerCamelCase = 0.0 _lowerCamelCase = 0 _lowerCamelCase = timeit.default_timer() _lowerCamelCase = None for step, batch in enumerate(eval_dataloader): _lowerCamelCase , _lowerCamelCase = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 _lowerCamelCase , _lowerCamelCase = outputs _lowerCamelCase = torch.tensor(start_logits) _lowerCamelCase = torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered _lowerCamelCase = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00) _lowerCamelCase = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00) _lowerCamelCase = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) _lowerCamelCase = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00) if all_preds is not None: _lowerCamelCase = nested_truncate(all_preds, len(eval_dataset)) _lowerCamelCase = timeit.default_timer() - start_time logger.info(''' Evaluation done in total %f secs (%f sec per example)''', evalTime, evalTime / len(eval_dataset)) # Inference time from TRT logger.info('''Average Inference Time = {:.3f} ms'''.format(total_time * 10_00 / niter)) logger.info('''Total Inference Time = {:.3f} ms'''.format(total_time * 10_00)) logger.info('''Total Number of Inference = %d''', niter) _lowerCamelCase = post_processing_function(eval_examples, eval_dataset, all_preds) _lowerCamelCase = metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(f'Evaluation metrics: {eval_metric}')
674
0
import shutil import tempfile import unittest from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast from transformers.testing_utils import require_sentencepiece, require_torchaudio from .test_feature_extraction_clap import floats_list @require_torchaudio @require_sentencepiece class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def __lowerCAmelCase ( self : List[Any] ): """simple docstring""" UpperCamelCase = '''laion/clap-htsat-unfused''' UpperCamelCase = tempfile.mkdtemp() def __lowerCAmelCase ( self : Tuple , **SCREAMING_SNAKE_CASE__ : List[str] ): """simple docstring""" return RobertaTokenizer.from_pretrained(self.checkpoint , **_lowerCamelCase ) def __lowerCAmelCase ( self : Union[str, Any] , **SCREAMING_SNAKE_CASE__ : Optional[int] ): """simple docstring""" return ClapFeatureExtractor.from_pretrained(self.checkpoint , **_lowerCamelCase ) def __lowerCAmelCase ( self : List[Any] ): """simple docstring""" shutil.rmtree(self.tmpdirname ) def __lowerCAmelCase ( self : Union[str, Any] ): """simple docstring""" UpperCamelCase = self.get_tokenizer() UpperCamelCase = self.get_feature_extractor() UpperCamelCase = ClapProcessor(tokenizer=_lowerCamelCase , feature_extractor=_lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) UpperCamelCase = ClapProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , _lowerCamelCase ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor.to_json_string() ) self.assertIsInstance(processor.feature_extractor , _lowerCamelCase ) def __lowerCAmelCase ( self : str ): """simple docstring""" UpperCamelCase = ClapProcessor(tokenizer=self.get_tokenizer() , feature_extractor=self.get_feature_extractor() ) processor.save_pretrained(self.tmpdirname ) UpperCamelCase = self.get_tokenizer(bos_token='(BOS)' , eos_token='(EOS)' ) UpperCamelCase = self.get_feature_extractor(do_normalize=_lowerCamelCase , padding_value=1.0 ) UpperCamelCase = ClapProcessor.from_pretrained( self.tmpdirname , bos_token='(BOS)' , eos_token='(EOS)' , do_normalize=_lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _lowerCamelCase ) self.assertEqual(processor.feature_extractor.to_json_string() , feature_extractor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.feature_extractor , _lowerCamelCase ) def __lowerCAmelCase ( self : List[Any] ): """simple docstring""" UpperCamelCase = self.get_feature_extractor() UpperCamelCase = self.get_tokenizer() UpperCamelCase = ClapProcessor(tokenizer=_lowerCamelCase , feature_extractor=_lowerCamelCase ) UpperCamelCase = floats_list((3, 10_00) ) UpperCamelCase = feature_extractor(_lowerCamelCase , return_tensors='np' ) UpperCamelCase = processor(audios=_lowerCamelCase , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __lowerCAmelCase ( self : int ): """simple docstring""" UpperCamelCase = self.get_feature_extractor() UpperCamelCase = self.get_tokenizer() UpperCamelCase = ClapProcessor(tokenizer=_lowerCamelCase , feature_extractor=_lowerCamelCase ) UpperCamelCase = '''This is a test string''' UpperCamelCase = processor(text=_lowerCamelCase ) UpperCamelCase = tokenizer(_lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __lowerCAmelCase ( self : str ): """simple docstring""" UpperCamelCase = self.get_feature_extractor() UpperCamelCase = self.get_tokenizer() UpperCamelCase = ClapProcessor(tokenizer=_lowerCamelCase , feature_extractor=_lowerCamelCase ) UpperCamelCase = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] UpperCamelCase = processor.batch_decode(_lowerCamelCase ) UpperCamelCase = tokenizer.batch_decode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def __lowerCAmelCase ( self : List[str] ): """simple docstring""" UpperCamelCase = self.get_feature_extractor() UpperCamelCase = self.get_tokenizer() UpperCamelCase = ClapProcessor(tokenizer=_lowerCamelCase , feature_extractor=_lowerCamelCase ) self.assertListEqual( processor.model_input_names[2:] , feature_extractor.model_input_names , msg='`processor` and `feature_extractor` model input names do not match' , )
282
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = TFAutoModel.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModel.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[str] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Any ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Dict ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = TFAutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = TFAutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
674
0
"""simple docstring""" import numpy as np import torch from imwatermark import WatermarkEncoder # Copied from https://github.com/Stability-AI/generative-models/blob/613af104c6b85184091d42d374fef420eddb356d/scripts/demo/streamlit_helpers.py#L66 a_ : str = 0B101100111110110010010000011110111011000110011110 # bin(x)[2:] gives bits of x as str, use int to convert them to 0/1 a_ : Optional[int] = [int(bit) for bit in bin(WATERMARK_MESSAGE)[2:]] class __lowercase: '''simple docstring''' def __init__( self ): __lowerCamelCase : Any = WATERMARK_BITS __lowerCamelCase : List[Any] = WatermarkEncoder() self.encoder.set_watermark('bits' , self.watermark ) def snake_case_ ( self , __a ): # can't encode images that are smaller than 256 if images.shape[-1] < 256: return images __lowerCamelCase : Dict = (255 * (images / 2 + 0.5)).cpu().permute(0 , 2 , 3 , 1 ).float().numpy() __lowerCamelCase : Optional[Any] = [self.encoder.encode(_lowerCamelCase , 'dwtDct' ) for image in images] __lowerCamelCase : Dict = torch.from_numpy(np.array(_lowerCamelCase ) ).permute(0 , 3 , 1 , 2 ) __lowerCamelCase : int = torch.clamp(2 * (images / 255 - 0.5) , min=-1.0 , max=1.0 ) return images
594
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'''vocab_file''': '''spiece.model'''} _lowerCamelCase = { '''vocab_file''': { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''', } } # TODO(PVP) - this should be removed in Transformers v5 _lowerCamelCase = { '''t5-small''': 5_12, '''t5-base''': 5_12, '''t5-large''': 5_12, '''t5-3b''': 5_12, '''t5-11b''': 5_12, } _lowerCamelCase = '''▁''' class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self :int , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Union[str, Any]="</s>" , _lowerCamelCase :List[Any]="<unk>" , _lowerCamelCase :Union[str, Any]="<pad>" , _lowerCamelCase :int=1_0_0 , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :Optional[Dict[str, Any]] = None , _lowerCamelCase :int=True , **_lowerCamelCase :List[Any] , ): # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: __SCREAMING_SNAKE_CASE : Union[str, Any] = [f'''<extra_id_{i}>''' for i in range(_lowerCamelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens __SCREAMING_SNAKE_CASE : Optional[int] = len(set(filter(lambda _lowerCamelCase : bool('''extra_id''' in str(_lowerCamelCase ) ) , _lowerCamelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( f'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are''' ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) if legacy: logger.warning_once( f'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to''' ''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = legacy __SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , extra_ids=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , legacy=_lowerCamelCase , **_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Tuple = vocab_file __SCREAMING_SNAKE_CASE : List[str] = extra_ids __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :str , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :int ): if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: __SCREAMING_SNAKE_CASE : Any = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' f''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this''' ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' f''' {pretrained_model_name_or_path} automatically truncating your input to''' f''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences''' f''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with''' ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , _lowerCamelCase , ) return max_model_length @property def SCREAMING_SNAKE_CASE_ ( self :Tuple ): return self.sp_model.get_piece_size() + self._extra_ids def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : str = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None , _lowerCamelCase :bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(_lowerCamelCase )) + [1] return ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1] def SCREAMING_SNAKE_CASE_ ( self :List[str] ): return list( set(filter(lambda _lowerCamelCase : bool(re.search(r'''<extra_id_\d+>''' , _lowerCamelCase ) ) is not None , self.additional_special_tokens ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return [self._convert_token_to_id(_lowerCamelCase ) for token in self.get_sentinel_tokens()] def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[int] ): if len(_lowerCamelCase ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated''' ''' eos tokens being added.''' ) return token_ids else: return token_ids + [self.eos_token_id] def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : Optional[Any] = self._add_eos_if_not_present(_lowerCamelCase ) if token_ids_a is None: return token_ids_a else: __SCREAMING_SNAKE_CASE : Union[str, Any] = self._add_eos_if_not_present(_lowerCamelCase ) return token_ids_a + token_ids_a def __getstate__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() __SCREAMING_SNAKE_CASE : List[str] = None return state def __setstate__( self :Optional[Any] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : Tuple = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __SCREAMING_SNAKE_CASE : Optional[int] = {} __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :"TextInput" , **_lowerCamelCase :str ): # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at # the beginning of the text if not self.legacy: __SCREAMING_SNAKE_CASE : Dict = SPIECE_UNDERLINE + text.replace(_lowerCamelCase , ''' ''' ) return super().tokenize(_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[Any] , **_lowerCamelCase :Dict ): if not self.legacy: __SCREAMING_SNAKE_CASE : str = text.startswith(_lowerCamelCase ) if is_first: __SCREAMING_SNAKE_CASE : str = text[1:] __SCREAMING_SNAKE_CASE : Tuple = self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) if not self.legacy and not is_first and not text.startswith(''' ''' ) and tokens[0].startswith(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[int] = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[Any] ): if token.startswith('''<extra_id_''' ): __SCREAMING_SNAKE_CASE : Tuple = re.match(r'''<extra_id_(\d+)>''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): if index < self.sp_model.get_piece_size(): __SCREAMING_SNAKE_CASE : List[Any] = self.sp_model.IdToPiece(_lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : Dict = f'''<extra_id_{self.vocab_size - 1 - index}>''' return token def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : str = [] __SCREAMING_SNAKE_CASE : Dict = '''''' __SCREAMING_SNAKE_CASE : Dict = 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(_lowerCamelCase ) + token __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : str = [] else: current_sub_tokens.append(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = False out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :str , _lowerCamelCase :Optional[str] = None ): if not os.path.isdir(_lowerCamelCase ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __SCREAMING_SNAKE_CASE : List[str] = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: __SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
674
0
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 __snake_case = logging.get_logger(__name__) __snake_case = { "google/mobilenet_v2_1.4_224": "https://huggingface.co/google/mobilenet_v2_1.4_224/resolve/main/config.json", "google/mobilenet_v2_1.0_224": "https://huggingface.co/google/mobilenet_v2_1.0_224/resolve/main/config.json", "google/mobilenet_v2_0.75_160": "https://huggingface.co/google/mobilenet_v2_0.75_160/resolve/main/config.json", "google/mobilenet_v2_0.35_96": "https://huggingface.co/google/mobilenet_v2_0.35_96/resolve/main/config.json", # See all MobileNetV2 models at https://huggingface.co/models?filter=mobilenet_v2 } class UpperCAmelCase ( __UpperCAmelCase ): lowercase = """mobilenet_v2""" def __init__( self : Any , __magic_name__ : List[str]=3 , __magic_name__ : Tuple=2_2_4 , __magic_name__ : List[Any]=1.0 , __magic_name__ : List[Any]=8 , __magic_name__ : Tuple=8 , __magic_name__ : Optional[Any]=6 , __magic_name__ : Dict=3_2 , __magic_name__ : Dict=True , __magic_name__ : Union[str, Any]=True , __magic_name__ : List[str]="relu6" , __magic_name__ : Any=True , __magic_name__ : Any=0.8 , __magic_name__ : List[str]=0.02 , __magic_name__ : Any=0.001 , __magic_name__ : Union[str, Any]=2_5_5 , **__magic_name__ : str , ): """simple docstring""" super().__init__(**_lowerCamelCase ) if depth_multiplier <= 0: raise ValueError("""depth_multiplier must be greater than zero.""" ) UpperCamelCase = num_channels UpperCamelCase = image_size UpperCamelCase = depth_multiplier UpperCamelCase = depth_divisible_by UpperCamelCase = min_depth UpperCamelCase = expand_ratio UpperCamelCase = output_stride UpperCamelCase = first_layer_is_expansion UpperCamelCase = finegrained_output UpperCamelCase = hidden_act UpperCamelCase = tf_padding UpperCamelCase = classifier_dropout_prob UpperCamelCase = initializer_range UpperCamelCase = layer_norm_eps UpperCamelCase = semantic_loss_ignore_index class UpperCAmelCase ( __UpperCAmelCase ): lowercase = version.parse("""1.11""" ) @property def lowerCamelCase_ ( self : Optional[int] ): """simple docstring""" return OrderedDict([("""pixel_values""", {0: """batch"""})] ) @property def lowerCamelCase_ ( self : Any ): """simple docstring""" if self.task == "image-classification": return OrderedDict([("""logits""", {0: """batch"""})] ) else: return OrderedDict([("""last_hidden_state""", {0: """batch"""}), ("""pooler_output""", {0: """batch"""})] ) @property def lowerCamelCase_ ( self : Optional[Any] ): """simple docstring""" return 1e-4
386
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( '''files''' , [ ['''full:README.md''', '''dataset_infos.json'''], ['''empty:README.md''', '''dataset_infos.json'''], ['''dataset_infos.json'''], ['''full:README.md'''], ] , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = tmp_path_factory.mktemp('''dset_infos_dir''' ) if "full:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''---\ndataset_info:\n dataset_size: 42\n---''' ) if "empty:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''''' ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / '''dataset_infos.json''' , '''w''' ) as f: f.write('''{"default": {"dataset_size": 42}}''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( '''dataset_info''' , [ DatasetInfo(), DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ), ] , ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : DatasetInfo ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = str(lowercase_ ) dataset_info.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = DatasetInfo.from_directory(lowercase_ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(lowercase_ , '''dataset_info.json''' ) ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo( description='''foo''' , citation='''bar''' , homepage='''https://foo.bar''' , license='''CC0''' , features=Features({'''a''': Value('''int32''' )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train''', '''num_examples''': 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , ) __SCREAMING_SNAKE_CASE : Optional[int] = dataset_info._to_yaml_dict() assert sorted(lowercase_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) __SCREAMING_SNAKE_CASE : int = yaml.safe_dump(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = yaml.safe_load(lowercase_ ) assert dataset_info_yaml_dict == reloaded def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetInfo() __SCREAMING_SNAKE_CASE : Union[str, Any] = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( '''dataset_infos_dict''' , [ DatasetInfosDict(), DatasetInfosDict({'''default''': DatasetInfo()} ), DatasetInfosDict({'''my_config_name''': DatasetInfo()} ), DatasetInfosDict( { '''default''': DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ) } ), DatasetInfosDict( { '''v1''': DatasetInfo(dataset_size=42 ), '''v2''': DatasetInfo(dataset_size=1337 ), } ), ] , ) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : DatasetInfosDict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) dataset_infos_dict.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): __SCREAMING_SNAKE_CASE : Optional[int] = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(lowercase_ , '''README.md''' ) )
674
0
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available a__ = { '''configuration_cpmant''': ['''CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CpmAntConfig'''], '''tokenization_cpmant''': ['''CpmAntTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ = [ '''CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CpmAntForCausalLM''', '''CpmAntModel''', '''CpmAntPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_cpmant import CPMANT_PRETRAINED_CONFIG_ARCHIVE_MAP, CpmAntConfig from .tokenization_cpmant import CpmAntTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_cpmant import ( CPMANT_PRETRAINED_MODEL_ARCHIVE_LIST, CpmAntForCausalLM, CpmAntModel, CpmAntPreTrainedModel, ) else: import sys a__ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
279
"""simple docstring""" from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class snake_case ( __UpperCAmelCase , __UpperCAmelCase ): @register_to_config def __init__( self :List[str] , _lowerCamelCase :int = 7_6_8 , ): super().__init__() __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter(torch.zeros(1 , _lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.ones(1 , _lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Optional[Union[str, torch.device]] = None , _lowerCamelCase :Optional[torch.dtype] = None , ): __SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(self.mean.to(_lowerCamelCase ).to(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(self.std.to(_lowerCamelCase ).to(_lowerCamelCase ) ) return self def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Tuple = (embeds - self.mean) * 1.0 / self.std return embeds def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = (embeds * self.std) + self.mean return embeds
674
0
from pathlib import Path import fire from tqdm import tqdm def a ( a="ro" , a="en" , a="wmt16" , a=None ) ->List[Any]: '''simple docstring''' try: import datasets except (ModuleNotFoundError, ImportError): raise ImportError('''run pip install datasets''' ) SCREAMING_SNAKE_CASE = F"""{src_lang}-{tgt_lang}""" print(F"""Converting {dataset}-{pair}""" ) SCREAMING_SNAKE_CASE = datasets.load_dataset(lowercase_ , lowercase_ ) if save_dir is None: SCREAMING_SNAKE_CASE = F"""{dataset}-{pair}""" SCREAMING_SNAKE_CASE = Path(lowercase_ ) save_dir.mkdir(exist_ok=lowercase_ ) for split in ds.keys(): print(F"""Splitting {split} with {ds[split].num_rows} records""" ) # to save to val.source, val.target like summary datasets SCREAMING_SNAKE_CASE = '''val''' if split == '''validation''' else split SCREAMING_SNAKE_CASE = save_dir.joinpath(F"""{fn}.source""" ) SCREAMING_SNAKE_CASE = save_dir.joinpath(F"""{fn}.target""" ) SCREAMING_SNAKE_CASE = src_path.open('''w+''' ) SCREAMING_SNAKE_CASE = tgt_path.open('''w+''' ) # reader is the bottleneck so writing one record at a time doesn't slow things down for x in tqdm(ds[split] ): SCREAMING_SNAKE_CASE = x['''translation'''] src_fp.write(ex[src_lang] + '''\n''' ) tgt_fp.write(ex[tgt_lang] + '''\n''' ) print(F"""Saved {dataset} dataset to {save_dir}""" ) if __name__ == "__main__": fire.Fire(download_wmt_dataset)
201
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : int , lowercase_ : Any ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = BertConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : Optional[int] = BertForPreTraining(lowercase_ ) # Load weights from tf checkpoint load_tf_weights_in_bert(lowercase_ , lowercase_ , lowercase_ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--bert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained BERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
674
0
"""simple docstring""" import collections import inspect import unittest from typing import Dict, List, Tuple from transformers import MaskFormerSwinConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import MaskFormerSwinBackbone from transformers.models.maskformer import MaskFormerSwinModel class __UpperCAmelCase: """simple docstring""" def __init__( self , snake_case__ , snake_case__=13 , snake_case__=32 , snake_case__=2 , snake_case__=3 , snake_case__=16 , snake_case__=[1, 2, 1] , snake_case__=[2, 2, 4] , snake_case__=2 , snake_case__=2.0 , snake_case__=True , snake_case__=0.0 , snake_case__=0.0 , snake_case__=0.1 , snake_case__="gelu" , snake_case__=False , snake_case__=True , snake_case__=0.02 , snake_case__=1e-5 , snake_case__=True , snake_case__=None , snake_case__=True , snake_case__=10 , snake_case__=8 , snake_case__=["stage1", "stage2", "stage3"] , snake_case__=[1, 2, 3] , ): '''simple docstring''' lowercase__ : Union[str, Any]= parent lowercase__ : Optional[int]= batch_size lowercase__ : Any= image_size lowercase__ : Optional[int]= patch_size lowercase__ : str= num_channels lowercase__ : List[Any]= embed_dim lowercase__ : Optional[Any]= depths lowercase__ : List[str]= num_heads lowercase__ : Union[str, Any]= window_size lowercase__ : int= mlp_ratio lowercase__ : Any= qkv_bias lowercase__ : Tuple= hidden_dropout_prob lowercase__ : Optional[int]= attention_probs_dropout_prob lowercase__ : Dict= drop_path_rate lowercase__ : Dict= hidden_act lowercase__ : Union[str, Any]= use_absolute_embeddings lowercase__ : Optional[int]= patch_norm lowercase__ : Any= layer_norm_eps lowercase__ : Union[str, Any]= initializer_range lowercase__ : Dict= is_training lowercase__ : Optional[Any]= scope lowercase__ : Union[str, Any]= use_labels lowercase__ : Optional[Any]= type_sequence_label_size lowercase__ : List[Any]= encoder_stride lowercase__ : List[str]= out_features lowercase__ : Optional[int]= out_indices def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : str= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) lowercase__ : int= None if self.use_labels: lowercase__ : Union[str, Any]= ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowercase__ : Tuple= self.get_config() return config, pixel_values, labels def UpperCAmelCase_ ( self ): '''simple docstring''' return MaskFormerSwinConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , 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 UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' lowercase__ : Union[str, Any]= MaskFormerSwinModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() lowercase__ : Tuple= model(_lowerCamelCase ) lowercase__ : List[str]= ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) lowercase__ : Optional[int]= 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 UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' lowercase__ : Any= MaskFormerSwinBackbone(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() lowercase__ : Union[str, Any]= model(_lowerCamelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [13, 16, 16, 16] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , [16, 32, 64] ) # verify ValueError with self.parent.assertRaises(_lowerCamelCase ): lowercase__ : Optional[Any]= ['''stem'''] lowercase__ : Optional[Any]= MaskFormerSwinBackbone(config=_lowerCamelCase ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Dict= self.prepare_config_and_inputs() lowercase__ : int= config_and_inputs lowercase__ : str= {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __UpperCAmelCase( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): """simple docstring""" __lowerCamelCase = ( ( MaskFormerSwinModel, MaskFormerSwinBackbone, ) if is_torch_available() else () ) __lowerCamelCase = {"feature-extraction": MaskFormerSwinModel} if is_torch_available() else {} __lowerCamelCase = False __lowerCamelCase = False __lowerCamelCase = False __lowerCamelCase = False __lowerCamelCase = False def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Tuple= MaskFormerSwinModelTester(self ) lowercase__ : str= ConfigTester(self , config_class=_lowerCamelCase , embed_dim=37 ) @require_torch_multi_gpu @unittest.skip( reason=( "`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn\'t work well with" " `nn.DataParallel`" ) ) def UpperCAmelCase_ ( self ): '''simple docstring''' pass def UpperCAmelCase_ ( self ): '''simple docstring''' self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCAmelCase_ ( self ): '''simple docstring''' return def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Tuple= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Optional[int]= self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_lowerCamelCase ) @unittest.skip("Swin does not use inputs_embeds" ) def UpperCAmelCase_ ( self ): '''simple docstring''' pass @unittest.skip("Swin does not support feedforward chunking" ) def UpperCAmelCase_ ( self ): '''simple docstring''' pass def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Dict= self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ : int= model_class(_lowerCamelCase ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowercase__ : List[str]= model.get_output_embeddings() self.assertTrue(x is None or isinstance(_lowerCamelCase , nn.Linear ) ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Union[str, Any]= self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowercase__ : Union[str, Any]= model_class(_lowerCamelCase ) lowercase__ : List[str]= inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowercase__ : Any= [*signature.parameters.keys()] lowercase__ : Any= ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) @unittest.skip(reason="MaskFormerSwin is only used as backbone and doesn\'t support output_attentions" ) def UpperCAmelCase_ ( self ): '''simple docstring''' pass @unittest.skip(reason="MaskFormerSwin is only used as an internal backbone" ) def UpperCAmelCase_ ( self ): '''simple docstring''' pass def UpperCAmelCase_ ( self , snake_case__ , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' lowercase__ : Union[str, Any]= model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() with torch.no_grad(): lowercase__ : Union[str, Any]= model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) lowercase__ : Dict= outputs.hidden_states lowercase__ : int= getattr( self.model_tester , "expected_num_hidden_layers" , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_lowerCamelCase ) , _lowerCamelCase ) # Swin has a different seq_length lowercase__ : Any= ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) lowercase__ : List[Any]= (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] , ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : List[Any]= self.model_tester.prepare_config_and_inputs_for_common() 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) ) for model_class in self.all_model_classes: lowercase__ : Union[str, Any]= True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase__ : Optional[Any]= True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Dict= self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : int= 3 lowercase__ : int= ( 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[Any]= ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) lowercase__ : Any= image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) lowercase__ : List[Any]= image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: lowercase__ : Dict= True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowercase__ : Any= True self.check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , (padded_height, padded_width) ) @unittest.skip(reason="MaskFormerSwin doesn\'t have pretrained checkpoints" ) def UpperCAmelCase_ ( self ): '''simple docstring''' pass @unittest.skip(reason="This will be fixed once MaskFormerSwin is replaced by native Swin" ) def UpperCAmelCase_ ( self ): '''simple docstring''' pass @unittest.skip(reason="This will be fixed once MaskFormerSwin is replaced by native Swin" ) def UpperCAmelCase_ ( self ): '''simple docstring''' pass def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : List[Any]= self.model_tester.prepare_config_and_inputs_for_common() def set_nan_tensor_to_zero(snake_case__ ): lowercase__ : Any= 0 return t def check_equivalence(snake_case__ , snake_case__ , snake_case__ , snake_case__={} ): with torch.no_grad(): lowercase__ : List[str]= model(**_lowerCamelCase , return_dict=_lowerCamelCase , **_lowerCamelCase ) lowercase__ : Optional[int]= model(**_lowerCamelCase , return_dict=_lowerCamelCase , **_lowerCamelCase ).to_tuple() def recursive_check(snake_case__ , snake_case__ ): if isinstance(_lowerCamelCase , (List, Tuple) ): for tuple_iterable_value, dict_iterable_value in zip(_lowerCamelCase , _lowerCamelCase ): recursive_check(_lowerCamelCase , _lowerCamelCase ) elif isinstance(_lowerCamelCase , _lowerCamelCase ): for tuple_iterable_value, dict_iterable_value in zip( tuple_object.values() , dict_object.values() ): recursive_check(_lowerCamelCase , _lowerCamelCase ) elif tuple_object is None: return else: self.assertTrue( torch.allclose( set_nan_tensor_to_zero(_lowerCamelCase ) , set_nan_tensor_to_zero(_lowerCamelCase ) , atol=1e-5 ) , msg=( "Tuple and dict output are not equal. Difference:" F''' {torch.max(torch.abs(tuple_object - dict_object ) )}. Tuple has `nan`:''' F''' {torch.isnan(_lowerCamelCase ).any()} and `inf`: {torch.isinf(_lowerCamelCase )}. Dict has''' F''' `nan`: {torch.isnan(_lowerCamelCase ).any()} and `inf`: {torch.isinf(_lowerCamelCase )}.''' ) , ) recursive_check(_lowerCamelCase , _lowerCamelCase ) for model_class in self.all_model_classes: lowercase__ : List[str]= model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() lowercase__ : List[Any]= self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) lowercase__ : str= self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) check_equivalence(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) lowercase__ : int= self._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) lowercase__ : Optional[Any]= self._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) check_equivalence(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) lowercase__ : Any= self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) lowercase__ : Tuple= self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) check_equivalence(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , {"output_hidden_states": True} ) lowercase__ : Any= self._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) lowercase__ : Union[str, Any]= self._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) check_equivalence(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , {"output_hidden_states": True} ) @require_torch class __UpperCAmelCase( unittest.TestCase , __UpperCAmelCase ): """simple docstring""" __lowerCamelCase = (MaskFormerSwinBackbone,) if is_torch_available() else () __lowerCamelCase = MaskFormerSwinConfig def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Tuple= MaskFormerSwinModelTester(self ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Dict= self.model_tester.prepare_config_and_inputs_for_common() lowercase__ : List[str]= inputs_dict['''pixel_values'''].shape[0] for backbone_class in self.all_model_classes: lowercase__ : int= backbone_class(_lowerCamelCase ) backbone.to(_lowerCamelCase ) backbone.eval() lowercase__ : Optional[int]= backbone(**_lowerCamelCase ) # Test default outputs and verify feature maps self.assertIsInstance(outputs.feature_maps , _lowerCamelCase ) self.assertTrue(len(outputs.feature_maps ) == len(backbone.channels ) ) for feature_map, n_channels in zip(outputs.feature_maps , backbone.channels ): self.assertTrue(feature_map.shape[:2] , (batch_size, n_channels) ) self.assertIsNone(outputs.hidden_states ) self.assertIsNone(outputs.attentions ) # Test output_hidden_states=True lowercase__ : str= backbone(**_lowerCamelCase , output_hidden_states=_lowerCamelCase ) self.assertIsNotNone(outputs.hidden_states ) self.assertTrue(len(outputs.hidden_states ) , len(backbone.stage_names ) ) # We skip the stem layer for hidden_states, n_channels in zip(outputs.hidden_states[1:] , backbone.channels ): for hidden_state in hidden_states: # Hidden states are in the format (batch_size, (height * width), n_channels) lowercase__ : Tuple= hidden_state.shape self.assertTrue((h_batch_size, h_n_channels) , (batch_size, n_channels) ) # Test output_attentions=True if self.has_attentions: lowercase__ : Any= backbone(**_lowerCamelCase , output_attentions=_lowerCamelCase ) self.assertIsNotNone(outputs.attentions )
218
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = ( '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.''' '''It takes two arguments named `image` which should be the original image, and `label` which should be a text ''' '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.''' ) lowerCamelCase__ = '''CIDAS/clipseg-rd64-refined''' lowerCamelCase__ = '''image_segmenter''' lowerCamelCase__ = CLIPSegForImageSegmentation lowerCamelCase__ = ['''image''', '''text'''] lowerCamelCase__ = ['''image'''] def __init__( self :Dict , *_lowerCamelCase :Union[str, Any] , **_lowerCamelCase :Tuple ): requires_backends(self , ['''vision'''] ) super().__init__(*_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :"Image" , _lowerCamelCase :str ): return self.pre_processor(text=[label] , images=[image] , padding=_lowerCamelCase , return_tensors='''pt''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[int] ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = self.model(**_lowerCamelCase ).logits return logits def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy() __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : str = 1 return Image.fromarray((array * 2_5_5).astype(np.uinta ) )
674
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCamelCase :str = logging.get_logger(__name__) lowerCamelCase :Tuple = { 'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/config.json', 'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/config.json', 'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/config.json', 'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/config.json', 'bert-base-multilingual-uncased': 'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/config.json', 'bert-base-multilingual-cased': 'https://huggingface.co/bert-base-multilingual-cased/resolve/main/config.json', 'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/config.json', 'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/config.json', 'bert-large-uncased-whole-word-masking': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/config.json' ), 'bert-large-cased-whole-word-masking': ( 'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/config.json' ), 'bert-large-uncased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/config.json' ), 'bert-large-cased-whole-word-masking-finetuned-squad': ( 'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/config.json' ), 'bert-base-cased-finetuned-mrpc': 'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/config.json', 'bert-base-german-dbmdz-cased': 'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/config.json', 'bert-base-german-dbmdz-uncased': 'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/config.json', 'cl-tohoku/bert-base-japanese': 'https://huggingface.co/cl-tohoku/bert-base-japanese/resolve/main/config.json', 'cl-tohoku/bert-base-japanese-whole-word-masking': ( 'https://huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/resolve/main/config.json' ), 'cl-tohoku/bert-base-japanese-char': ( 'https://huggingface.co/cl-tohoku/bert-base-japanese-char/resolve/main/config.json' ), 'cl-tohoku/bert-base-japanese-char-whole-word-masking': ( 'https://huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/resolve/main/config.json' ), 'TurkuNLP/bert-base-finnish-cased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/config.json' ), 'TurkuNLP/bert-base-finnish-uncased-v1': ( 'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/config.json' ), 'wietsedv/bert-base-dutch-cased': 'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/config.json', # See all BERT models at https://huggingface.co/models?filter=bert } class UpperCAmelCase ( __UpperCAmelCase ): a: List[Any] = "bert" def __init__( self: Optional[int] , __UpperCamelCase: Optional[Any]=3_0522 , __UpperCamelCase: int=768 , __UpperCamelCase: Union[str, Any]=12 , __UpperCamelCase: Any=12 , __UpperCamelCase: List[str]=3072 , __UpperCamelCase: Optional[int]="gelu" , __UpperCamelCase: List[Any]=0.1 , __UpperCamelCase: Union[str, Any]=0.1 , __UpperCamelCase: List[str]=512 , __UpperCamelCase: Union[str, Any]=2 , __UpperCamelCase: Tuple=0.0_2 , __UpperCamelCase: Any=1E-12 , __UpperCamelCase: Tuple=0 , __UpperCamelCase: List[str]="absolute" , __UpperCamelCase: Optional[int]=True , __UpperCamelCase: Optional[int]=None , **__UpperCamelCase: Optional[Any] , ): super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase ) _a = vocab_size _a = hidden_size _a = num_hidden_layers _a = num_attention_heads _a = hidden_act _a = intermediate_size _a = hidden_dropout_prob _a = attention_probs_dropout_prob _a = max_position_embeddings _a = type_vocab_size _a = initializer_range _a = layer_norm_eps _a = position_embedding_type _a = use_cache _a = classifier_dropout class UpperCAmelCase ( __UpperCAmelCase ): @property def _A ( self: Any ): if self.task == "multiple-choice": _a = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: _a = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ('''token_type_ids''', dynamic_axis), ] )
487
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE : Optional[int] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) __SCREAMING_SNAKE_CASE : Optional[int] = { '''do_resize''': True, '''size''': {'''height''': 1_8, '''width''': 1_8}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , _lowerCamelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , **_lowerCamelCase :List[str] ): return BertTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , **_lowerCamelCase :Optional[int] ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE : Tuple = [Image.fromarray(np.moveaxis(_lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : str = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor(do_normalize=_lowerCamelCase , padding_value=1.0 ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : Optional[int] = image_processor(_lowerCamelCase , return_tensors='''np''' ) __SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Any = self.get_image_processor() __SCREAMING_SNAKE_CASE : Any = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Optional[int] = processor(text=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = tokenizer(_lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : int = self.get_tokenizer() __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = '''lower newer''' __SCREAMING_SNAKE_CASE : int = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : int = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(_lowerCamelCase ): processor() def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Dict = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE : Tuple = processor.batch_decode(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.batch_decode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : str = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
674
0
"""simple docstring""" from typing import Any, Dict, Optional import torch import torch.nn.functional as F from torch import nn from ..utils import maybe_allow_in_graph from .activations import get_activation from .attention_processor import Attention from .embeddings import CombinedTimestepLabelEmbeddings @maybe_allow_in_graph class UpperCAmelCase_ ( nn.Module ): def __init__( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_=0.0 , UpperCamelCase_ = None , UpperCamelCase_ = "geglu" , UpperCamelCase_ = None , UpperCamelCase_ = False , UpperCamelCase_ = False , UpperCamelCase_ = False , UpperCamelCase_ = False , UpperCamelCase_ = True , UpperCamelCase_ = "layer_norm" , UpperCamelCase_ = False , ) -> str: super().__init__() __lowercase : Optional[Any] = only_cross_attention __lowercase : Union[str, Any] = (num_embeds_ada_norm is not None) and norm_type == '''ada_norm_zero''' __lowercase : Optional[int] = (num_embeds_ada_norm is not None) and norm_type == '''ada_norm''' if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: raise ValueError( F"""`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to""" F""" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.""" ) # Define 3 blocks. Each block has its own normalization layer. # 1. Self-Attn if self.use_ada_layer_norm: __lowercase : Union[str, Any] = AdaLayerNorm(_lowerCamelCase , _lowerCamelCase ) elif self.use_ada_layer_norm_zero: __lowercase : Any = AdaLayerNormZero(_lowerCamelCase , _lowerCamelCase ) else: __lowercase : List[Any] = nn.LayerNorm(_lowerCamelCase , elementwise_affine=_lowerCamelCase ) __lowercase : Optional[int] = Attention( query_dim=_lowerCamelCase , heads=_lowerCamelCase , dim_head=_lowerCamelCase , dropout=_lowerCamelCase , bias=_lowerCamelCase , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=_lowerCamelCase , ) # 2. Cross-Attn if cross_attention_dim is not None or double_self_attention: # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during # the second cross attention block. __lowercase : Union[str, Any] = ( AdaLayerNorm(_lowerCamelCase , _lowerCamelCase ) if self.use_ada_layer_norm else nn.LayerNorm(_lowerCamelCase , elementwise_affine=_lowerCamelCase ) ) __lowercase : int = Attention( query_dim=_lowerCamelCase , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=_lowerCamelCase , dim_head=_lowerCamelCase , dropout=_lowerCamelCase , bias=_lowerCamelCase , upcast_attention=_lowerCamelCase , ) # is self-attn if encoder_hidden_states is none else: __lowercase : Tuple = None __lowercase : List[str] = None # 3. Feed-forward __lowercase : Dict = nn.LayerNorm(_lowerCamelCase , elementwise_affine=_lowerCamelCase ) __lowercase : List[Any] = FeedForward(_lowerCamelCase , dropout=_lowerCamelCase , activation_fn=_lowerCamelCase , final_dropout=_lowerCamelCase ) # let chunk size default to None __lowercase : Optional[Any] = None __lowercase : Optional[Any] = 0 def _lowerCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ ) -> Dict: # Sets chunk feed-forward __lowercase : Union[str, Any] = chunk_size __lowercase : Any = dim def _lowerCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = None , UpperCamelCase_ = None , ) -> int: # Notice that normalization is always applied before the real computation in the following blocks. # 1. Self-Attention if self.use_ada_layer_norm: __lowercase : Optional[Any] = self.norma(_lowerCamelCase , _lowerCamelCase ) elif self.use_ada_layer_norm_zero: __lowercase : List[Any] = self.norma( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , hidden_dtype=hidden_states.dtype ) else: __lowercase : List[str] = self.norma(_lowerCamelCase ) __lowercase : int = cross_attention_kwargs if cross_attention_kwargs is not None else {} __lowercase : Optional[int] = self.attna( _lowerCamelCase , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=_lowerCamelCase , **_lowerCamelCase , ) if self.use_ada_layer_norm_zero: __lowercase : List[Any] = gate_msa.unsqueeze(1 ) * attn_output __lowercase : Tuple = attn_output + hidden_states # 2. Cross-Attention if self.attna is not None: __lowercase : int = ( self.norma(_lowerCamelCase , _lowerCamelCase ) if self.use_ada_layer_norm else self.norma(_lowerCamelCase ) ) __lowercase : int = self.attna( _lowerCamelCase , encoder_hidden_states=_lowerCamelCase , attention_mask=_lowerCamelCase , **_lowerCamelCase , ) __lowercase : Optional[int] = attn_output + hidden_states # 3. Feed-forward __lowercase : str = self.norma(_lowerCamelCase ) if self.use_ada_layer_norm_zero: __lowercase : Tuple = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] if self._chunk_size is not None: # "feed_forward_chunk_size" can be used to save memory if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0: raise ValueError( F"""`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.""" ) __lowercase : Union[str, Any] = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size __lowercase : str = torch.cat( [self.ff(_lowerCamelCase ) for hid_slice in norm_hidden_states.chunk(_lowerCamelCase , dim=self._chunk_dim )] , dim=self._chunk_dim , ) else: __lowercase : int = self.ff(_lowerCamelCase ) if self.use_ada_layer_norm_zero: __lowercase : Union[str, Any] = gate_mlp.unsqueeze(1 ) * ff_output __lowercase : Optional[int] = ff_output + hidden_states return hidden_states class UpperCAmelCase_ ( nn.Module ): def __init__( self , UpperCamelCase_ , UpperCamelCase_ = None , UpperCamelCase_ = 4 , UpperCamelCase_ = 0.0 , UpperCamelCase_ = "geglu" , UpperCamelCase_ = False , ) -> int: super().__init__() __lowercase : Optional[Any] = int(dim * mult ) __lowercase : Optional[int] = dim_out if dim_out is not None else dim if activation_fn == "gelu": __lowercase : Optional[Any] = GELU(_lowerCamelCase , _lowerCamelCase ) if activation_fn == "gelu-approximate": __lowercase : Tuple = GELU(_lowerCamelCase , _lowerCamelCase , approximate='''tanh''' ) elif activation_fn == "geglu": __lowercase : Tuple = GEGLU(_lowerCamelCase , _lowerCamelCase ) elif activation_fn == "geglu-approximate": __lowercase : Optional[Any] = ApproximateGELU(_lowerCamelCase , _lowerCamelCase ) __lowercase : Optional[int] = nn.ModuleList([] ) # project in self.net.append(_lowerCamelCase ) # project dropout self.net.append(nn.Dropout(_lowerCamelCase ) ) # project out self.net.append(nn.Linear(_lowerCamelCase , _lowerCamelCase ) ) # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout if final_dropout: self.net.append(nn.Dropout(_lowerCamelCase ) ) def _lowerCamelCase ( self , UpperCamelCase_ ) -> Optional[Any]: for module in self.net: __lowercase : Any = module(_lowerCamelCase ) return hidden_states class UpperCAmelCase_ ( nn.Module ): def __init__( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = "none" ) -> List[Any]: super().__init__() __lowercase : int = nn.Linear(_lowerCamelCase , _lowerCamelCase ) __lowercase : Optional[Any] = approximate def _lowerCamelCase ( self , UpperCamelCase_ ) -> Any: if gate.device.type != "mps": return F.gelu(_lowerCamelCase , approximate=self.approximate ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) , approximate=self.approximate ).to(dtype=gate.dtype ) def _lowerCamelCase ( self , UpperCamelCase_ ) -> Union[str, Any]: __lowercase : Union[str, Any] = self.proj(_lowerCamelCase ) __lowercase : List[str] = self.gelu(_lowerCamelCase ) return hidden_states class UpperCAmelCase_ ( nn.Module ): def __init__( self , UpperCamelCase_ , UpperCamelCase_ ) -> int: super().__init__() __lowercase : Any = nn.Linear(_lowerCamelCase , dim_out * 2 ) def _lowerCamelCase ( self , UpperCamelCase_ ) -> int: if gate.device.type != "mps": return F.gelu(_lowerCamelCase ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype ) def _lowerCamelCase ( self , UpperCamelCase_ ) -> List[Any]: __lowercase : List[Any] = self.proj(_lowerCamelCase ).chunk(2 , dim=-1 ) return hidden_states * self.gelu(_lowerCamelCase ) class UpperCAmelCase_ ( nn.Module ): def __init__( self , UpperCamelCase_ , UpperCamelCase_ ) -> Union[str, Any]: super().__init__() __lowercase : str = nn.Linear(_lowerCamelCase , _lowerCamelCase ) def _lowerCamelCase ( self , UpperCamelCase_ ) -> int: __lowercase : str = self.proj(_lowerCamelCase ) return x * torch.sigmoid(1.7_0_2 * x ) class UpperCAmelCase_ ( nn.Module ): def __init__( self , UpperCamelCase_ , UpperCamelCase_ ) -> Union[str, Any]: super().__init__() __lowercase : str = nn.Embedding(_lowerCamelCase , _lowerCamelCase ) __lowercase : Any = nn.SiLU() __lowercase : Tuple = nn.Linear(_lowerCamelCase , embedding_dim * 2 ) __lowercase : Tuple = nn.LayerNorm(_lowerCamelCase , elementwise_affine=_lowerCamelCase ) def _lowerCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ ) -> Union[str, Any]: __lowercase : Optional[int] = self.linear(self.silu(self.emb(_lowerCamelCase ) ) ) __lowercase : Tuple = torch.chunk(_lowerCamelCase , 2 ) __lowercase : List[str] = self.norm(_lowerCamelCase ) * (1 + scale) + shift return x class UpperCAmelCase_ ( nn.Module ): def __init__( self , UpperCamelCase_ , UpperCamelCase_ ) -> str: super().__init__() __lowercase : List[Any] = CombinedTimestepLabelEmbeddings(_lowerCamelCase , _lowerCamelCase ) __lowercase : int = nn.SiLU() __lowercase : Any = nn.Linear(_lowerCamelCase , 6 * embedding_dim , bias=_lowerCamelCase ) __lowercase : List[Any] = nn.LayerNorm(_lowerCamelCase , elementwise_affine=_lowerCamelCase , eps=1E-6 ) def _lowerCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_=None ) -> Tuple: __lowercase : Tuple = self.linear(self.silu(self.emb(_lowerCamelCase , _lowerCamelCase , hidden_dtype=_lowerCamelCase ) ) ) __lowercase : Union[str, Any] = emb.chunk(6 , dim=1 ) __lowercase : int = self.norm(_lowerCamelCase ) * (1 + scale_msa[:, None]) + shift_msa[:, None] return x, gate_msa, shift_mlp, scale_mlp, gate_mlp class UpperCAmelCase_ ( nn.Module ): def __init__( self , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = None , UpperCamelCase_ = 1E-5 ) -> Optional[Any]: super().__init__() __lowercase : int = num_groups __lowercase : List[str] = eps if act_fn is None: __lowercase : Tuple = None else: __lowercase : int = get_activation(_lowerCamelCase ) __lowercase : Dict = nn.Linear(_lowerCamelCase , out_dim * 2 ) def _lowerCamelCase ( self , UpperCamelCase_ , UpperCamelCase_ ) -> Tuple: if self.act: __lowercase : int = self.act(_lowerCamelCase ) __lowercase : int = self.linear(_lowerCamelCase ) __lowercase : List[Any] = emb[:, :, None, None] __lowercase : List[Any] = emb.chunk(2 , dim=1 ) __lowercase : Tuple = F.group_norm(_lowerCamelCase , self.num_groups , eps=self.eps ) __lowercase : Optional[Any] = x * (1 + scale) + shift return x
76
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class snake_case : def __init__( self :Optional[int] , _lowerCamelCase :int , _lowerCamelCase :Any=2 , _lowerCamelCase :List[str]=True , _lowerCamelCase :str=False , _lowerCamelCase :Tuple=1_0 , _lowerCamelCase :str=3 , _lowerCamelCase :str=3_2 * 4 , _lowerCamelCase :Dict=3_2 * 6 , _lowerCamelCase :str=4 , _lowerCamelCase :Any=3_2 , ): __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Tuple = batch_size __SCREAMING_SNAKE_CASE : Optional[Any] = is_training __SCREAMING_SNAKE_CASE : Dict = use_auxiliary_loss __SCREAMING_SNAKE_CASE : List[str] = num_queries __SCREAMING_SNAKE_CASE : Optional[int] = num_channels __SCREAMING_SNAKE_CASE : List[Any] = min_size __SCREAMING_SNAKE_CASE : int = max_size __SCREAMING_SNAKE_CASE : Any = num_labels __SCREAMING_SNAKE_CASE : Union[str, Any] = mask_feature_size def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : str = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowerCamelCase ) > 0.5 ).float() __SCREAMING_SNAKE_CASE : Dict = (torch.rand((self.batch_size, self.num_labels) , device=_lowerCamelCase ) > 0.5).long() __SCREAMING_SNAKE_CASE : str = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=1_2_8 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Any = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = output.encoder_hidden_states __SCREAMING_SNAKE_CASE : int = output.pixel_decoder_hidden_states __SCREAMING_SNAKE_CASE : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , config.decoder_config.decoder_layers ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :str , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any]=False ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = MaskFormerModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : str = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , output_hidden_states=_lowerCamelCase ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerForInstanceSegmentation(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() def comm_check_on_output(_lowerCamelCase :Optional[Any] ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = model( pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () lowerCamelCase__ = ( {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerModelTester(self ) __SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowerCamelCase ) @unittest.skip(reason='''MaskFormer does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): pass @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' ) def SCREAMING_SNAKE_CASE_ ( self :int ): pass @unittest.skip(reason='''MaskFormer is not a generative model''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): pass @unittest.skip(reason='''MaskFormer does not use token embeddings''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): pass @require_torch_multi_gpu @unittest.skip( reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Tuple = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE : List[str] = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): for model_name in ["facebook/maskformer-swin-small-coco"]: __SCREAMING_SNAKE_CASE : Tuple = MaskFormerModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Dict = (self.model_tester.min_size,) * 2 __SCREAMING_SNAKE_CASE : Dict = { '''pixel_values''': torch.randn((2, 3, *size) , device=_lowerCamelCase ), '''mask_labels''': torch.randn((2, 1_0, *size) , device=_lowerCamelCase ), '''class_labels''': torch.zeros(2 , 1_0 , device=_lowerCamelCase ).long(), } __SCREAMING_SNAKE_CASE : Dict = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Dict = model_class(_lowerCamelCase ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = model(**_lowerCamelCase , output_attentions=_lowerCamelCase ) self.assertTrue(outputs.attentions is not None ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : List[Any] = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ).loss loss.backward() def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : Tuple = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Tuple = True __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : str = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't __SCREAMING_SNAKE_CASE : Optional[int] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : int = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_lowerCamelCase ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) _lowerCamelCase = 1e-4 def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @slow class snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self :str ): return ( MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' ) if is_vision_available() else None ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : Tuple = model(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor( [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Any = torch.tensor( [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : str = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Any = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[Any] = [ [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3], [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5], [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2], ] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : List[Any] = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [ [1.65_12e00, -5.25_72e00, -3.35_19e00], [3.61_69e-02, -5.90_25e00, -2.93_13e00], [1.07_66e-04, -7.76_30e00, -5.12_63e00], ] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor __SCREAMING_SNAKE_CASE : str = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[str] = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : int = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : int = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Any = self.default_image_processor __SCREAMING_SNAKE_CASE : int = image_processor( [np.zeros((3, 8_0_0, 1_3_3_3) ), np.zeros((3, 8_0_0, 1_3_3_3) )] , segmentation_maps=[np.zeros((3_8_4, 3_8_4) ).astype(np.floataa ), np.zeros((3_8_4, 3_8_4) ).astype(np.floataa )] , return_tensors='''pt''' , ) __SCREAMING_SNAKE_CASE : Dict = inputs['''pixel_values'''].to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = [el.to(_lowerCamelCase ) for el in inputs['''mask_labels''']] __SCREAMING_SNAKE_CASE : str = [el.to(_lowerCamelCase ) for el in inputs['''class_labels''']] with torch.no_grad(): __SCREAMING_SNAKE_CASE : int = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None )
674
0
import unittest import numpy as np import torch from diffusers import PNDMPipeline, PNDMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class _lowerCamelCase ( unittest.TestCase ): @property def UpperCamelCase_ ( self ) -> List[Any]: torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__: str= UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''') , up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''') , ) return model def UpperCamelCase_ ( self ) -> Tuple: SCREAMING_SNAKE_CASE__: Optional[int]= self.dummy_uncond_unet SCREAMING_SNAKE_CASE__: int= PNDMScheduler() SCREAMING_SNAKE_CASE__: Optional[int]= PNDMPipeline(unet=_lowerCamelCase , scheduler=_lowerCamelCase ) pndm.to(_lowerCamelCase ) pndm.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE__: int= torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__: Optional[Any]= pndm(generator=_lowerCamelCase , num_inference_steps=20 , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE__: str= torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__: str= pndm(generator=_lowerCamelCase , num_inference_steps=20 , output_type='''numpy''' , return_dict=_lowerCamelCase )[0] SCREAMING_SNAKE_CASE__: List[str]= image[0, -3:, -3:, -1] SCREAMING_SNAKE_CASE__: Dict= image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__: Tuple= np.array([1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 @slow @require_torch class _lowerCamelCase ( unittest.TestCase ): def UpperCamelCase_ ( self ) -> List[Any]: SCREAMING_SNAKE_CASE__: List[str]= '''google/ddpm-cifar10-32''' SCREAMING_SNAKE_CASE__: Tuple= UNetaDModel.from_pretrained(_lowerCamelCase ) SCREAMING_SNAKE_CASE__: str= PNDMScheduler() SCREAMING_SNAKE_CASE__: Optional[int]= PNDMPipeline(unet=_lowerCamelCase , scheduler=_lowerCamelCase ) pndm.to(_lowerCamelCase ) pndm.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE__: int= torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__: Tuple= pndm(generator=_lowerCamelCase , output_type='''numpy''' ).images SCREAMING_SNAKE_CASE__: Dict= image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) SCREAMING_SNAKE_CASE__: Dict= np.array([0.1564, 0.14645, 0.1406, 0.14715, 0.12425, 0.14045, 0.13115, 0.12175, 0.125] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
64
"""simple docstring""" import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification _lowerCamelCase = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co _lowerCamelCase = '''main''' # Default branch name _lowerCamelCase = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2''' # One particular commit (not the top of `main`) _lowerCamelCase = '''aaaaaaa''' # This commit does not exist, so we should 404. _lowerCamelCase = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684''' # Sha-1 of config.json on the top of `main`, for checking purposes _lowerCamelCase = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3''' @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Welcome!''' ) yield print('''Bye!''' ) @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Bonjour!''' ) yield print('''Au revoir!''' ) class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): # If the spec is missing, importlib would not be able to import the module dynamically. assert transformers.__spec__ is not None assert importlib.util.find_spec('''transformers''' ) is not None class snake_case ( unittest.TestCase ): @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[int] ): with ContextManagers([] ): print('''Transformers are awesome!''' ) # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , '''Transformers are awesome!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): with ContextManagers([context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Welcome!\nTransformers are awesome!\nBye!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[str] ): with ContextManagers([context_fr(), context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n''' ) @require_torch def SCREAMING_SNAKE_CASE_ ( self :List[str] ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_tf def SCREAMING_SNAKE_CASE_ ( self :int ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_flax def SCREAMING_SNAKE_CASE_ ( self :Dict ): # Flax models don't have labels self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , [] )
674
0
def lowercase_ ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' if discount_rate < 0: raise ValueError('''Discount rate cannot be negative''' ) if not cash_flows: raise ValueError('''Cash flows list cannot be empty''' ) __lowercase = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(lowercase_ ) ) return round(lowercase_ , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
639
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class snake_case ( unittest.TestCase ): def __init__( self :List[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Tuple=7 , _lowerCamelCase :Dict=3 , _lowerCamelCase :Optional[Any]=3_0 , _lowerCamelCase :List[str]=4_0_0 , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :List[Any]=True , _lowerCamelCase :Any=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=True , _lowerCamelCase :str=1 / 2_5_5 , _lowerCamelCase :Union[str, Any]=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Dict = batch_size __SCREAMING_SNAKE_CASE : str = num_channels __SCREAMING_SNAKE_CASE : Union[str, Any] = min_resolution __SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution __SCREAMING_SNAKE_CASE : Tuple = do_resize __SCREAMING_SNAKE_CASE : Union[str, Any] = size __SCREAMING_SNAKE_CASE : int = do_normalize __SCREAMING_SNAKE_CASE : List[Any] = image_mean __SCREAMING_SNAKE_CASE : Tuple = image_std __SCREAMING_SNAKE_CASE : Dict = do_rescale __SCREAMING_SNAKE_CASE : Optional[int] = rescale_factor __SCREAMING_SNAKE_CASE : List[Any] = do_pad def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :List[Any]=False ): if not batched: __SCREAMING_SNAKE_CASE : str = image_inputs[0] if isinstance(_lowerCamelCase , Image.Image ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = image.size else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = image.shape[1], image.shape[2] if w < h: __SCREAMING_SNAKE_CASE : str = int(self.size['''shortest_edge'''] * h / w ) __SCREAMING_SNAKE_CASE : int = self.size['''shortest_edge'''] elif w > h: __SCREAMING_SNAKE_CASE : Optional[Any] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : int = int(self.size['''shortest_edge'''] * w / h ) else: __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] else: __SCREAMING_SNAKE_CASE : Optional[Any] = [] for image in image_inputs: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __SCREAMING_SNAKE_CASE : Optional[int] = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0] __SCREAMING_SNAKE_CASE : int = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = YolosImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=_lowerCamelCase ) self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2, '''longest_edge''': 8_4} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): pass def SCREAMING_SNAKE_CASE_ ( self :int ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : str = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : List[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Any ): # Initialize image_processing __SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : Optional[int] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): # Initialize image_processings __SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(do_resize=_lowerCamelCase , do_normalize=_lowerCamelCase , do_rescale=_lowerCamelCase ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a.pad(_lowerCamelCase , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a(_lowerCamelCase , return_tensors='''pt''' ) self.assertTrue( torch.allclose(encoded_images_with_method['''pixel_values'''] , encoded_images['''pixel_values'''] , atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): # prepare image and target __SCREAMING_SNAKE_CASE : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Tuple = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''image_id''': 3_9_7_6_9, '''annotations''': target} # encode them __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessor.from_pretrained('''hustvl/yolos-small''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : Optional[int] = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Dict = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify orig_size __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # prepare image, target and masks_path __SCREAMING_SNAKE_CASE : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Dict = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9_7_6_9, '''segments_info''': target} __SCREAMING_SNAKE_CASE : Optional[int] = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them __SCREAMING_SNAKE_CASE : Any = YolosImageProcessor(format='''coco_panoptic''' ) __SCREAMING_SNAKE_CASE : Dict = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : str = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Any = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Dict = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify masks __SCREAMING_SNAKE_CASE : Optional[Any] = 8_2_2_8_7_3 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _lowerCamelCase ) # verify orig_size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : Any = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
674
0
def lowerCAmelCase_ ( lowercase: str ) -> Any: '''simple docstring''' return "".join(chr(ord(lowercase_ ) - 32 ) if '''a''' <= char <= '''z''' else char for char in word ) if __name__ == "__main__": from doctest import testmod testmod()
271
"""simple docstring""" from __future__ import annotations def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) return len(lowercase_ ) == 9 and set(lowercase_ ) == set('''123456789''' ) def lowerCAmelCase_ ( ): '''simple docstring''' for base_num in range(9999 , 4999 , -1 ): __SCREAMING_SNAKE_CASE : List[str] = 10_0002 * base_num if is_9_pandigital(lowercase_ ): return candidate for base_num in range(333 , 99 , -1 ): __SCREAMING_SNAKE_CASE : List[Any] = 100_2003 * base_num if is_9_pandigital(lowercase_ ): return candidate return None if __name__ == "__main__": print(f'{solution() = }')
674
0
import importlib.metadata import warnings from copy import deepcopy from packaging import version from ..utils import logging from .import_utils import is_accelerate_available, is_bitsandbytes_available if is_bitsandbytes_available(): import bitsandbytes as bnb import torch import torch.nn as nn from ..pytorch_utils import ConvaD if is_accelerate_available(): from accelerate import init_empty_weights from accelerate.utils import find_tied_parameters _snake_case = logging.get_logger(__name__) def __lowerCamelCase ( _lowercase , _lowercase , _lowercase , _lowercase=None , _lowercase=None ) -> Optional[Any]: if "." in tensor_name: UpperCamelCase = tensor_name.split('.' ) for split in splits[:-1]: UpperCamelCase = getattr(lowercase_ , lowercase_ ) if new_module is None: raise ValueError(F'{module} has no attribute {split}.' ) UpperCamelCase = new_module UpperCamelCase = splits[-1] if tensor_name not in module._parameters and tensor_name not in module._buffers: raise ValueError(F'{module} does not have a parameter or a buffer named {tensor_name}.' ) UpperCamelCase = tensor_name in module._buffers UpperCamelCase = getattr(lowercase_ , lowercase_ ) if old_value.device == torch.device('meta' ) and device not in ["meta", torch.device('meta' )] and value is None: raise ValueError(F'{tensor_name} is on the meta device, we need a `value` to put in on {device}.' ) UpperCamelCase = False UpperCamelCase = False if is_buffer or not is_bitsandbytes_available(): UpperCamelCase = False UpperCamelCase = False else: UpperCamelCase = hasattr(bnb.nn , 'Params4bit' ) and isinstance(module._parameters[tensor_name] , bnb.nn.Paramsabit ) UpperCamelCase = isinstance(module._parameters[tensor_name] , bnb.nn.IntaParams ) if is_abit or is_abit: UpperCamelCase = module._parameters[tensor_name] if param.device.type != "cuda": if value is None: UpperCamelCase = old_value.to(lowercase_ ) elif isinstance(lowercase_ , torch.Tensor ): UpperCamelCase = value.to('cpu' ) if value.dtype == torch.inta: UpperCamelCase = version.parse(importlib.metadata.version('bitsandbytes' ) ) > version.parse( '0.37.2' ) if not is_abit_serializable: raise ValueError( 'Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. ' 'Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.' ) else: UpperCamelCase = torch.tensor(lowercase_ , device='cpu' ) # Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization. # Since weights are saved in the correct "orientation", we skip transposing when loading. if issubclass(module.source_cls , lowercase_ ) and fpaa_statistics is None: UpperCamelCase = new_value.T UpperCamelCase = old_value.__dict__ if is_abit: UpperCamelCase = bnb.nn.IntaParams(lowercase_ , requires_grad=lowercase_ , **lowercase_ ).to(lowercase_ ) elif is_abit: UpperCamelCase = bnb.nn.Paramsabit(lowercase_ , requires_grad=lowercase_ , **lowercase_ ).to(lowercase_ ) UpperCamelCase = new_value if fpaa_statistics is not None: setattr(module.weight , 'SCB' , fpaa_statistics.to(lowercase_ ) ) else: if value is None: UpperCamelCase = old_value.to(lowercase_ ) elif isinstance(lowercase_ , torch.Tensor ): UpperCamelCase = value.to(lowercase_ ) else: UpperCamelCase = torch.tensor(lowercase_ , device=lowercase_ ) if is_buffer: UpperCamelCase = new_value else: UpperCamelCase = nn.Parameter(lowercase_ , requires_grad=old_value.requires_grad ) UpperCamelCase = new_value def __lowerCamelCase ( _lowercase , _lowercase=None , _lowercase=None , _lowercase=None , _lowercase=False ) -> Optional[Any]: for name, module in model.named_children(): if current_key_name is None: UpperCamelCase = [] current_key_name.append(lowercase_ ) if (isinstance(lowercase_ , nn.Linear ) or isinstance(lowercase_ , lowercase_ )) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` if not any(key in '.'.join(lowercase_ ) for key in modules_to_not_convert ): with init_empty_weights(): if isinstance(lowercase_ , lowercase_ ): UpperCamelCase = module.weight.shape else: UpperCamelCase = module.in_features UpperCamelCase = module.out_features if quantization_config.quantization_method() == "llm_int8": UpperCamelCase = bnb.nn.LinearabitLt( lowercase_ , lowercase_ , module.bias is not None , has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight , threshold=quantization_config.llm_inta_threshold , ) UpperCamelCase = True else: if ( quantization_config.llm_inta_skip_modules is not None and name in quantization_config.llm_inta_skip_modules ): pass else: UpperCamelCase = bnb.nn.Linearabit( lowercase_ , lowercase_ , module.bias is not None , quantization_config.bnb_abit_compute_dtype , compress_statistics=quantization_config.bnb_abit_use_double_quant , quant_type=quantization_config.bnb_abit_quant_type , ) UpperCamelCase = True # Store the module class in case we need to transpose the weight later UpperCamelCase = type(lowercase_ ) # Force requires grad to False to avoid unexpected errors model._modules[name].requires_grad_(lowercase_ ) if len(list(module.children() ) ) > 0: UpperCamelCase = _replace_with_bnb_linear( lowercase_ , lowercase_ , lowercase_ , lowercase_ , has_been_replaced=lowercase_ , ) # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def __lowerCamelCase ( _lowercase , _lowercase=None , _lowercase=None , _lowercase=None ) -> Tuple: UpperCamelCase = ['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert UpperCamelCase = _replace_with_bnb_linear( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) if not has_been_replaced: logger.warning( 'You are loading your model in 8bit or 4bit but no linear modules were found in your model.' ' Please double check your model architecture, or submit an issue on github if you think this is' ' a bug.' ) return model def __lowerCamelCase ( *_lowercase , **_lowercase ) -> int: warnings.warn( '`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead' , lowercase_ , ) return replace_with_bnb_linear(*lowercase_ , **lowercase_ ) def __lowerCamelCase ( *_lowercase , **_lowercase ) -> int: warnings.warn( '`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead' , lowercase_ , ) return set_module_quantized_tensor_to_device(*lowercase_ , **lowercase_ ) def __lowerCamelCase ( _lowercase ) -> str: UpperCamelCase = deepcopy(lowercase_ ) # this has 0 cost since it is done inside `init_empty_weights` context manager` tied_model.tie_weights() UpperCamelCase = find_tied_parameters(lowercase_ ) # For compatibility with Accelerate < 0.18 if isinstance(lowercase_ , lowercase_ ): UpperCamelCase = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: UpperCamelCase = sum(lowercase_ , [] ) UpperCamelCase = len(lowercase_ ) > 0 # Check if it is a base model UpperCamelCase = not hasattr(lowercase_ , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head UpperCamelCase = list(model.named_children() ) UpperCamelCase = [list_modules[-1][0]] # add last module together with tied weights UpperCamelCase = set(lowercase_ ) - set(lowercase_ ) UpperCamelCase = list(set(lowercase_ ) ) + list(lowercase_ ) # remove ".weight" from the keys UpperCamelCase = ['''.weight''', '''.bias'''] UpperCamelCase = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: UpperCamelCase = name.replace(lowercase_ , '' ) filtered_module_names.append(lowercase_ ) return filtered_module_names
282
"""simple docstring""" import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Tuple = 0 def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Optional[Any] = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Dict = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : str = CLIPConfig() # Create a dummy config file with image_proceesor_type __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ).to_dict() config_dict.pop('''image_processor_type''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor(**_lowerCamelCase ) # save in new folder model_config.save_pretrained(_lowerCamelCase ) config.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) # make sure private variable is not incorrectly saved __SCREAMING_SNAKE_CASE : Tuple = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): with self.assertRaisesRegex( _lowerCamelCase , '''clip-base is not a local folder and is not a valid model identifier''' ): __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained('''clip-base''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): with self.assertRaisesRegex( _lowerCamelCase , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(_lowerCamelCase , revision='''aaaaaa''' ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with self.assertRaisesRegex( _lowerCamelCase , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase , trust_remote_code=_lowerCamelCase ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_lowerCamelCase ): AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = CustomImageProcessor.from_pretrained(_lowerCamelCase ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def SCREAMING_SNAKE_CASE_ ( self :Dict ): class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = True try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # If remote code is not set, the default is to use local __SCREAMING_SNAKE_CASE : List[str] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. __SCREAMING_SNAKE_CASE : str = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(_lowerCamelCase , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
674
0
"""simple docstring""" import copy import fnmatch import json import os import pickle as pkl import shutil import sys import tarfile import tempfile from collections import OrderedDict from contextlib import contextmanager from functools import partial from hashlib import shaaaa from io import BytesIO from pathlib import Path from urllib.parse import urlparse from zipfile import ZipFile, is_zipfile import cva import numpy as np import requests import wget from filelock import FileLock from PIL import Image from tqdm.auto import tqdm from yaml import Loader, dump, load try: import torch a_ : Union[str, Any] = True except ImportError: a_ : str = False try: from torch.hub import _get_torch_home a_ : List[str] = _get_torch_home() except ImportError: a_ : int = os.path.expanduser( os.getenv('''TORCH_HOME''', os.path.join(os.getenv('''XDG_CACHE_HOME''', '''~/.cache'''), '''torch''')) ) a_ : Tuple = os.path.join(torch_cache_home, '''transformers''') a_ : List[Any] = '''https://cdn.huggingface.co''' a_ : Tuple = '''https://s3.amazonaws.com/models.huggingface.co/bert''' a_ : Tuple = '''/'''.join(str(Path(__file__).resolve()).split('''/''')[:-1]) a_ : Optional[Any] = os.path.join(PATH, '''config.yaml''') a_ : Optional[Any] = os.path.join(PATH, '''attributes.txt''') a_ : List[str] = os.path.join(PATH, '''objects.txt''') a_ : Optional[int] = os.getenv('''PYTORCH_PRETRAINED_BERT_CACHE''', default_cache_path) a_ : Dict = os.getenv('''PYTORCH_TRANSFORMERS_CACHE''', PYTORCH_PRETRAINED_BERT_CACHE) a_ : Dict = os.getenv('''TRANSFORMERS_CACHE''', PYTORCH_TRANSFORMERS_CACHE) a_ : Optional[int] = '''pytorch_model.bin''' a_ : int = '''config.yaml''' def UpperCAmelCase ( A__: Optional[int]=OBJECTS , A__: Any=ATTRIBUTES ) -> str: __lowerCamelCase : Union[str, Any] = [] with open(lowercase_ ) as f: for object in f.readlines(): vg_classes.append(object.split(',' )[0].lower().strip() ) __lowerCamelCase : str = [] with open(lowercase_ ) as f: for object in f.readlines(): vg_attrs.append(object.split(',' )[0].lower().strip() ) return vg_classes, vg_attrs def UpperCAmelCase ( A__: Optional[Any] ) -> Any: __lowerCamelCase : Optional[Any] = OrderedDict() with open(lowercase_ , 'rb' ) as f: __lowerCamelCase : str = pkl.load(lowercase_ )['''model'''] for k in copy.deepcopy(list(ckp.keys() ) ): __lowerCamelCase : Union[str, Any] = ckp.pop(lowercase_ ) if isinstance(lowercase_ , np.ndarray ): __lowerCamelCase : Optional[Any] = torch.tensor(lowercase_ ) else: assert isinstance(lowercase_ , torch.tensor ), type(lowercase_ ) __lowerCamelCase : int = v return r class __lowercase: '''simple docstring''' __a : List[str] = {} def __init__( self , __a , __a = "root" , __a=0 ): __lowerCamelCase : Tuple = name __lowerCamelCase : int = level __lowerCamelCase : Any = {} for k, v in dictionary.items(): if v is None: raise ValueError() __lowerCamelCase : Optional[int] = copy.deepcopy(_lowerCamelCase ) __lowerCamelCase : str = copy.deepcopy(_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ): __lowerCamelCase : Optional[int] = Config(_lowerCamelCase , name=_lowerCamelCase , level=level + 1 ) __lowerCamelCase : Dict = v setattr(self , _lowerCamelCase , _lowerCamelCase ) __lowerCamelCase : str = d def __repr__( self ): return str(list((self._pointer.keys()) ) ) def __setattr__( self , __a , __a ): __lowerCamelCase : Optional[Any] = val __lowerCamelCase : List[str] = val __lowerCamelCase : Union[str, Any] = key.split('.' ) __lowerCamelCase : Dict = len(_lowerCamelCase ) - 1 __lowerCamelCase : str = self._pointer if len(_lowerCamelCase ) > 1: for i, l in enumerate(_lowerCamelCase ): if hasattr(self , _lowerCamelCase ) and isinstance(getattr(self , _lowerCamelCase ) , _lowerCamelCase ): setattr(getattr(self , _lowerCamelCase ) , '.'.join(levels[i:] ) , _lowerCamelCase ) if l == last_level: __lowerCamelCase : Any = val else: __lowerCamelCase : List[Any] = pointer[l] def snake_case_ ( self ): return self._pointer def snake_case_ ( self , __a , __a ): with open(f'''{file_name}''' , 'w' ) as stream: dump(_lowerCamelCase , _lowerCamelCase ) def snake_case_ ( self , __a , __a ): with open(f'''{file_name}''' , 'w' ) as stream: json.dump(_lowerCamelCase , _lowerCamelCase ) @staticmethod def snake_case_ ( __a ): with open(_lowerCamelCase ) as stream: __lowerCamelCase : int = load(_lowerCamelCase , Loader=_lowerCamelCase ) return data def __str__( self ): __lowerCamelCase : Optional[int] = ''' ''' if self._name != "root": __lowerCamelCase : List[Any] = f'''{t * (self._level-1)}{self._name}:\n''' else: __lowerCamelCase : Optional[int] = '''''' __lowerCamelCase : Union[str, Any] = self._level for i, (k, v) in enumerate(self._pointer.items() ): if isinstance(_lowerCamelCase , _lowerCamelCase ): r += f'''{t * (self._level)}{v}\n''' self._level += 1 else: r += f'''{t * (self._level)}{k}: {v} ({type(_lowerCamelCase ).__name__})\n''' __lowerCamelCase : Union[str, Any] = level return r[:-1] @classmethod def snake_case_ ( cls , __a , **__a ): __lowerCamelCase : Dict = cls.get_config_dict(_lowerCamelCase , **_lowerCamelCase ) return cls(_lowerCamelCase ) @classmethod def snake_case_ ( cls , __a , **__a ): __lowerCamelCase : Any = kwargs.pop('cache_dir' , _lowerCamelCase ) __lowerCamelCase : List[str] = kwargs.pop('force_download' , _lowerCamelCase ) __lowerCamelCase : Optional[Any] = kwargs.pop('resume_download' , _lowerCamelCase ) __lowerCamelCase : int = kwargs.pop('proxies' , _lowerCamelCase ) __lowerCamelCase : str = kwargs.pop('local_files_only' , _lowerCamelCase ) if os.path.isdir(_lowerCamelCase ): __lowerCamelCase : str = os.path.join(_lowerCamelCase , _lowerCamelCase ) elif os.path.isfile(_lowerCamelCase ) or is_remote_url(_lowerCamelCase ): __lowerCamelCase : Tuple = pretrained_model_name_or_path else: __lowerCamelCase : Dict = hf_bucket_url(_lowerCamelCase , filename=_lowerCamelCase , use_cdn=_lowerCamelCase ) try: # Load from URL or cache if already cached __lowerCamelCase : List[Any] = cached_path( _lowerCamelCase , cache_dir=_lowerCamelCase , force_download=_lowerCamelCase , proxies=_lowerCamelCase , resume_download=_lowerCamelCase , local_files_only=_lowerCamelCase , ) # Load config dict if resolved_config_file is None: raise EnvironmentError __lowerCamelCase : List[str] = Config.load_yaml(_lowerCamelCase ) except EnvironmentError: __lowerCamelCase : List[str] = '''Can\'t load config for''' raise EnvironmentError(_lowerCamelCase ) if resolved_config_file == config_file: print('loading configuration file from path' ) else: print('loading configuration file cache' ) return Config.load_yaml(_lowerCamelCase ), kwargs def UpperCAmelCase ( A__: Any ) -> str: __lowerCamelCase : Optional[Any] = torch.load('dump.pt' , map_location=in_tensor.device ) __lowerCamelCase : Optional[int] = in_tensor.numpy() __lowerCamelCase : Optional[Any] = out_tensor.numpy()[0] print(na.shape , na[0, 0, :5] ) print(na.shape , na[0, 0, :5] ) assert np.allclose(lowercase_ , lowercase_ , rtol=0.01 , atol=0.1 ), ( f'''{sum([1 for x in np.isclose(lowercase_ , lowercase_ , rtol=0.01 , atol=0.1 ).flatten() if x is False] )/len(na.flatten() )*100:.4f} %''' " element-wise mismatch" ) raise Exception('tensors are all good' ) # Hugging face functions below def UpperCAmelCase ( A__: Union[str, Any] ) -> Optional[Any]: __lowerCamelCase : str = urlparse(lowercase_ ) return parsed.scheme in ("http", "https") def UpperCAmelCase ( A__: str , A__: str , A__: str=True ) -> List[Any]: __lowerCamelCase : str = CLOUDFRONT_DISTRIB_PREFIX if use_cdn else S3_BUCKET_PREFIX __lowerCamelCase : Any = '''/''' not in model_id if legacy_format: return f'''{endpoint}/{model_id}-{filename}''' else: return f'''{endpoint}/{model_id}/{filename}''' def UpperCAmelCase ( A__: Union[str, Any] , A__: int , A__: Union[str, Any]=None , A__: Optional[int]=0 , A__: str=None , ) -> Optional[int]: __lowerCamelCase : Tuple = '''python/{}'''.format(sys.version.split()[0] ) if _torch_available: ua += "; torch/{}".format(torch.__version__ ) if isinstance(lowercase_ , lowercase_ ): ua += "; " + "; ".join('{}/{}'.format(lowercase_ , lowercase_ ) for k, v in user_agent.items() ) elif isinstance(lowercase_ , lowercase_ ): ua += "; " + user_agent __lowerCamelCase : List[Any] = {'''user-agent''': ua} if resume_size > 0: __lowerCamelCase : Optional[Any] = '''bytes=%d-''' % (resume_size,) __lowerCamelCase : Union[str, Any] = requests.get(lowercase_ , stream=lowercase_ , proxies=lowercase_ , headers=lowercase_ ) if response.status_code == 416: # Range not satisfiable return __lowerCamelCase : List[Any] = response.headers.get('Content-Length' ) __lowerCamelCase : Any = resume_size + int(lowercase_ ) if content_length is not None else None __lowerCamelCase : str = tqdm( unit='B' , unit_scale=lowercase_ , total=lowercase_ , initial=lowercase_ , desc='Downloading' , ) for chunk in response.iter_content(chunk_size=1024 ): if chunk: # filter out keep-alive new chunks progress.update(len(lowercase_ ) ) temp_file.write(lowercase_ ) progress.close() def UpperCAmelCase ( A__: Optional[int] , A__: int=None , A__: Dict=False , A__: Optional[Any]=None , A__: Any=10 , A__: List[Any]=False , A__: Optional[Any]=None , A__: Optional[Any]=False , ) -> Dict: if cache_dir is None: __lowerCamelCase : str = TRANSFORMERS_CACHE if isinstance(lowercase_ , lowercase_ ): __lowerCamelCase : Dict = str(lowercase_ ) os.makedirs(lowercase_ , exist_ok=lowercase_ ) __lowerCamelCase : Tuple = None if not local_files_only: try: __lowerCamelCase : Any = requests.head(lowercase_ , allow_redirects=lowercase_ , proxies=lowercase_ , timeout=lowercase_ ) if response.status_code == 200: __lowerCamelCase : Optional[int] = response.headers.get('ETag' ) except (EnvironmentError, requests.exceptions.Timeout): # etag is already None pass __lowerCamelCase : Optional[int] = url_to_filename(lowercase_ , lowercase_ ) # get cache path to put the file __lowerCamelCase : List[Any] = os.path.join(lowercase_ , lowercase_ ) # etag is None = we don't have a connection, or url doesn't exist, or is otherwise inaccessible. # try to get the last downloaded one if etag is None: if os.path.exists(lowercase_ ): return cache_path else: __lowerCamelCase : Union[str, Any] = [ file for file in fnmatch.filter(os.listdir(lowercase_ ) , filename + '.*' ) if not file.endswith('.json' ) and not file.endswith('.lock' ) ] if len(lowercase_ ) > 0: return os.path.join(lowercase_ , matching_files[-1] ) else: # If files cannot be found and local_files_only=True, # the models might've been found if local_files_only=False # Notify the user about that if local_files_only: raise ValueError( 'Cannot find the requested files in the cached path and outgoing traffic has been' ' disabled. To enable model look-ups and downloads online, set \'local_files_only\'' ' to False.' ) return None # From now on, etag is not None. if os.path.exists(lowercase_ ) and not force_download: return cache_path # Prevent parallel downloads of the same file with a lock. __lowerCamelCase : Dict = cache_path + '''.lock''' with FileLock(lowercase_ ): # If the download just completed while the lock was activated. if os.path.exists(lowercase_ ) and not force_download: # Even if returning early like here, the lock will be released. return cache_path if resume_download: __lowerCamelCase : List[str] = cache_path + '''.incomplete''' @contextmanager def _resumable_file_manager(): with open(lowercase_ , 'a+b' ) as f: yield f __lowerCamelCase : str = _resumable_file_manager if os.path.exists(lowercase_ ): __lowerCamelCase : Any = os.stat(lowercase_ ).st_size else: __lowerCamelCase : str = 0 else: __lowerCamelCase : List[str] = partial(tempfile.NamedTemporaryFile , dir=lowercase_ , delete=lowercase_ ) __lowerCamelCase : Union[str, Any] = 0 # Download to temporary file, then copy to cache dir once finished. # Otherwise you get corrupt cache entries if the download gets interrupted. with temp_file_manager() as temp_file: print( '%s not found in cache or force_download set to True, downloading to %s' , lowercase_ , temp_file.name , ) http_get( lowercase_ , lowercase_ , proxies=lowercase_ , resume_size=lowercase_ , user_agent=lowercase_ , ) os.replace(temp_file.name , lowercase_ ) __lowerCamelCase : List[str] = {'''url''': url, '''etag''': etag} __lowerCamelCase : Union[str, Any] = cache_path + '''.json''' with open(lowercase_ , 'w' ) as meta_file: json.dump(lowercase_ , lowercase_ ) return cache_path def UpperCAmelCase ( A__: List[str] , A__: Any=None ) -> Dict: __lowerCamelCase : Optional[Any] = url.encode('utf-8' ) __lowerCamelCase : Any = shaaaa(lowercase_ ) __lowerCamelCase : Dict = url_hash.hexdigest() if etag: __lowerCamelCase : Tuple = etag.encode('utf-8' ) __lowerCamelCase : Optional[Any] = shaaaa(lowercase_ ) filename += "." + etag_hash.hexdigest() if url.endswith('.h5' ): filename += ".h5" return filename def UpperCAmelCase ( A__: Union[str, Any] , A__: Optional[int]=None , A__: int=False , A__: Optional[Any]=None , A__: List[Any]=False , A__: Any=None , A__: Optional[int]=False , A__: Tuple=False , A__: int=False , ) -> int: if cache_dir is None: __lowerCamelCase : Optional[Any] = TRANSFORMERS_CACHE if isinstance(lowercase_ , lowercase_ ): __lowerCamelCase : Tuple = str(lowercase_ ) if isinstance(lowercase_ , lowercase_ ): __lowerCamelCase : Dict = str(lowercase_ ) if is_remote_url(lowercase_ ): # URL, so get it from the cache (downloading if necessary) __lowerCamelCase : Any = get_from_cache( lowercase_ , cache_dir=lowercase_ , force_download=lowercase_ , proxies=lowercase_ , resume_download=lowercase_ , user_agent=lowercase_ , local_files_only=lowercase_ , ) elif os.path.exists(lowercase_ ): # File, and it exists. __lowerCamelCase : List[str] = url_or_filename elif urlparse(lowercase_ ).scheme == "": # File, but it doesn't exist. raise EnvironmentError('file {} not found'.format(lowercase_ ) ) else: # Something unknown raise ValueError('unable to parse {} as a URL or as a local path'.format(lowercase_ ) ) if extract_compressed_file: if not is_zipfile(lowercase_ ) and not tarfile.is_tarfile(lowercase_ ): return output_path # Path where we extract compressed archives # We avoid '.' in dir name and add "-extracted" at the end: "./model.zip" => "./model-zip-extracted/" __lowerCamelCase : List[str] = os.path.split(lowercase_ ) __lowerCamelCase : List[Any] = output_file.replace('.' , '-' ) + '''-extracted''' __lowerCamelCase : Dict = os.path.join(lowercase_ , lowercase_ ) if os.path.isdir(lowercase_ ) and os.listdir(lowercase_ ) and not force_extract: return output_path_extracted # Prevent parallel extractions __lowerCamelCase : Dict = output_path + '''.lock''' with FileLock(lowercase_ ): shutil.rmtree(lowercase_ , ignore_errors=lowercase_ ) os.makedirs(lowercase_ ) if is_zipfile(lowercase_ ): with ZipFile(lowercase_ , 'r' ) as zip_file: zip_file.extractall(lowercase_ ) zip_file.close() elif tarfile.is_tarfile(lowercase_ ): __lowerCamelCase : Optional[Any] = tarfile.open(lowercase_ ) tar_file.extractall(lowercase_ ) tar_file.close() else: raise EnvironmentError('Archive format of {} could not be identified'.format(lowercase_ ) ) return output_path_extracted return output_path def UpperCAmelCase ( A__: Any , A__: List[str]="," ) -> Optional[int]: assert isinstance(lowercase_ , lowercase_ ) if os.path.isfile(lowercase_ ): with open(lowercase_ ) as f: __lowerCamelCase : str = eval(f.read() ) else: __lowerCamelCase : Any = requests.get(lowercase_ ) try: __lowerCamelCase : Optional[int] = requests.json() except Exception: __lowerCamelCase : Tuple = req.content.decode() assert data is not None, "could not connect" try: __lowerCamelCase : List[Any] = eval(lowercase_ ) except Exception: __lowerCamelCase : List[Any] = data.split('\n' ) req.close() return data def UpperCAmelCase ( A__: Tuple ) -> List[Any]: __lowerCamelCase : Dict = requests.get(lowercase_ ) __lowerCamelCase : str = np.array(Image.open(BytesIO(response.content ) ) ) return img def UpperCAmelCase ( A__: Tuple ) -> Union[str, Any]: __lowerCamelCase : Dict = url.split('/' )[-1] if fn not in os.listdir(os.getcwd() ): wget.download(lowercase_ ) with open(lowercase_ , 'rb' ) as stream: __lowerCamelCase : Tuple = pkl.load(lowercase_ ) __lowerCamelCase : Optional[Any] = weights.pop('model' ) __lowerCamelCase : str = {} for k, v in model.items(): __lowerCamelCase : Optional[int] = torch.from_numpy(lowercase_ ) if "running_var" in k: __lowerCamelCase : Union[str, Any] = torch.tensor([0] ) __lowerCamelCase : List[Any] = k.replace('running_var' , 'num_batches_tracked' ) __lowerCamelCase : Dict = zero return new def UpperCAmelCase ( ) -> Union[str, Any]: print(f'''{os.path.abspath(os.path.join(lowercase_ , os.pardir ) )}/demo.ipynb''' ) def UpperCAmelCase ( A__: int , A__: List[str]="RGB" ) -> Dict: assert isinstance(lowercase_ , lowercase_ ) if os.path.isfile(lowercase_ ): __lowerCamelCase : Any = cva.imread(lowercase_ ) else: __lowerCamelCase : Union[str, Any] = get_image_from_url(lowercase_ ) assert img is not None, f'''could not connect to: {im}''' __lowerCamelCase : List[str] = cva.cvtColor(lowercase_ , cva.COLOR_BGR2RGB ) if input_format == "RGB": __lowerCamelCase : List[Any] = img[:, :, ::-1] return img def UpperCAmelCase ( A__: Dict , A__: int=1 ) -> List[Any]: return (images[i : i + batch] for i in range(0 , len(lowercase_ ) , lowercase_ ))
594
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case ( __UpperCAmelCase ): pass class snake_case : def __init__( self :List[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Any = data __SCREAMING_SNAKE_CASE : Node | None = None def __iter__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : List[str] = self __SCREAMING_SNAKE_CASE : List[str] = [] while node: if node in visited: raise ContainsLoopError visited.append(_lowerCamelCase ) yield node.data __SCREAMING_SNAKE_CASE : List[str] = node.next_node @property def SCREAMING_SNAKE_CASE_ ( self :Any ): try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": _lowerCamelCase = Node(1) _lowerCamelCase = Node(2) _lowerCamelCase = Node(3) _lowerCamelCase = Node(4) print(root_node.has_loop) # False _lowerCamelCase = root_node.next_node print(root_node.has_loop) # True _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) print(root_node.has_loop) # False _lowerCamelCase = Node(1) print(root_node.has_loop) # False
674
0
import subprocess import sys from transformers import BertConfig, BertModel, BertTokenizer, pipeline from transformers.testing_utils import TestCasePlus, require_torch class UpperCAmelCase ( __UpperCAmelCase ): @require_torch def lowerCamelCase_ ( self : Tuple ): """simple docstring""" UpperCamelCase = ''' from transformers import BertConfig, BertModel, BertTokenizer, pipeline ''' UpperCamelCase = ''' mname = "hf-internal-testing/tiny-random-bert" BertConfig.from_pretrained(mname) BertModel.from_pretrained(mname) BertTokenizer.from_pretrained(mname) pipe = pipeline(task="fill-mask", model=mname) print("success") ''' UpperCamelCase = ''' import socket def offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn\'t access internet") socket.socket = offline_socket ''' # Force fetching the files so that we can use the cache UpperCamelCase = '''hf-internal-testing/tiny-random-bert''' BertConfig.from_pretrained(_lowerCamelCase ) BertModel.from_pretrained(_lowerCamelCase ) BertTokenizer.from_pretrained(_lowerCamelCase ) pipeline(task="""fill-mask""" , model=_lowerCamelCase ) # baseline - just load from_pretrained with normal network UpperCamelCase = [sys.executable, '''-c''', '''\n'''.join([load, run, mock] )] # should succeed UpperCamelCase = self.get_env() # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files UpperCamelCase = '''1''' UpperCamelCase = subprocess.run(_lowerCamelCase , env=_lowerCamelCase , check=_lowerCamelCase , capture_output=_lowerCamelCase ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("""success""" , result.stdout.decode() ) @require_torch def lowerCamelCase_ ( self : List[str] ): """simple docstring""" UpperCamelCase = ''' from transformers import BertConfig, BertModel, BertTokenizer, pipeline ''' UpperCamelCase = ''' mname = "hf-internal-testing/tiny-random-bert" BertConfig.from_pretrained(mname) BertModel.from_pretrained(mname) BertTokenizer.from_pretrained(mname) pipe = pipeline(task="fill-mask", model=mname) print("success") ''' UpperCamelCase = ''' import socket def offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet") socket.socket = offline_socket ''' # Force fetching the files so that we can use the cache UpperCamelCase = '''hf-internal-testing/tiny-random-bert''' BertConfig.from_pretrained(_lowerCamelCase ) BertModel.from_pretrained(_lowerCamelCase ) BertTokenizer.from_pretrained(_lowerCamelCase ) pipeline(task="""fill-mask""" , model=_lowerCamelCase ) # baseline - just load from_pretrained with normal network UpperCamelCase = [sys.executable, '''-c''', '''\n'''.join([load, run, mock] )] # should succeed UpperCamelCase = self.get_env() UpperCamelCase = subprocess.run(_lowerCamelCase , env=_lowerCamelCase , check=_lowerCamelCase , capture_output=_lowerCamelCase ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("""success""" , result.stdout.decode() ) @require_torch def lowerCamelCase_ ( self : List[Any] ): """simple docstring""" UpperCamelCase = ''' from transformers import BertConfig, BertModel, BertTokenizer ''' UpperCamelCase = ''' mname = "hf-internal-testing/tiny-random-bert-sharded" BertConfig.from_pretrained(mname) BertModel.from_pretrained(mname) print("success") ''' UpperCamelCase = ''' import socket def offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled") socket.socket = offline_socket ''' # baseline - just load from_pretrained with normal network UpperCamelCase = [sys.executable, '''-c''', '''\n'''.join([load, run] )] # should succeed UpperCamelCase = self.get_env() UpperCamelCase = subprocess.run(_lowerCamelCase , env=_lowerCamelCase , check=_lowerCamelCase , capture_output=_lowerCamelCase ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("""success""" , result.stdout.decode() ) # next emulate no network UpperCamelCase = [sys.executable, '''-c''', '''\n'''.join([load, mock, run] )] # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this. # env["TRANSFORMERS_OFFLINE"] = "0" # result = subprocess.run(cmd, env=env, check=False, capture_output=True) # self.assertEqual(result.returncode, 1, result.stderr) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files UpperCamelCase = '''1''' UpperCamelCase = subprocess.run(_lowerCamelCase , env=_lowerCamelCase , check=_lowerCamelCase , capture_output=_lowerCamelCase ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("""success""" , result.stdout.decode() ) @require_torch def lowerCamelCase_ ( self : Optional[Any] ): """simple docstring""" UpperCamelCase = ''' from transformers import pipeline ''' UpperCamelCase = ''' mname = "hf-internal-testing/tiny-random-bert" pipe = pipeline(model=mname) ''' UpperCamelCase = ''' import socket def offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled") socket.socket = offline_socket ''' UpperCamelCase = self.get_env() UpperCamelCase = '''1''' UpperCamelCase = [sys.executable, '''-c''', '''\n'''.join([load, mock, run] )] UpperCamelCase = subprocess.run(_lowerCamelCase , env=_lowerCamelCase , check=_lowerCamelCase , capture_output=_lowerCamelCase ) self.assertEqual(result.returncode , 1 , result.stderr ) self.assertIn( """You cannot infer task automatically within `pipeline` when using offline mode""" , result.stderr.decode().replace("""\n""" , """""" ) , ) @require_torch def lowerCamelCase_ ( self : Dict ): """simple docstring""" UpperCamelCase = ''' from transformers import AutoModel ''' UpperCamelCase = ''' mname = "hf-internal-testing/test_dynamic_model" AutoModel.from_pretrained(mname, trust_remote_code=True) print("success") ''' # baseline - just load from_pretrained with normal network UpperCamelCase = [sys.executable, '''-c''', '''\n'''.join([load, run] )] # should succeed UpperCamelCase = self.get_env() UpperCamelCase = subprocess.run(_lowerCamelCase , env=_lowerCamelCase , check=_lowerCamelCase , capture_output=_lowerCamelCase ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("""success""" , result.stdout.decode() ) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files UpperCamelCase = '''1''' UpperCamelCase = subprocess.run(_lowerCamelCase , env=_lowerCamelCase , check=_lowerCamelCase , capture_output=_lowerCamelCase ) self.assertEqual(result.returncode , 0 , result.stderr ) self.assertIn("""success""" , result.stdout.decode() )
386
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''roc_bert''' def __init__( self :Union[str, Any] , _lowerCamelCase :Any=3_0_5_2_2 , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Optional[Any]=1_2 , _lowerCamelCase :List[str]=1_2 , _lowerCamelCase :str=3_0_7_2 , _lowerCamelCase :Tuple="gelu" , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :List[str]=0.1 , _lowerCamelCase :Optional[int]=5_1_2 , _lowerCamelCase :Dict=2 , _lowerCamelCase :Any=0.0_2 , _lowerCamelCase :Optional[int]=1e-12 , _lowerCamelCase :str=True , _lowerCamelCase :Any=0 , _lowerCamelCase :List[str]="absolute" , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Any=True , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Union[str, Any]=9_1_0 , _lowerCamelCase :List[Any]=5_1_2 , _lowerCamelCase :Optional[int]=2_4_8_5_8 , _lowerCamelCase :Union[str, Any]=True , **_lowerCamelCase :str , ): __SCREAMING_SNAKE_CASE : List[str] = vocab_size __SCREAMING_SNAKE_CASE : int = max_position_embeddings __SCREAMING_SNAKE_CASE : List[str] = hidden_size __SCREAMING_SNAKE_CASE : str = num_hidden_layers __SCREAMING_SNAKE_CASE : int = num_attention_heads __SCREAMING_SNAKE_CASE : Any = intermediate_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_act __SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range __SCREAMING_SNAKE_CASE : Union[str, Any] = type_vocab_size __SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps __SCREAMING_SNAKE_CASE : Optional[int] = use_cache __SCREAMING_SNAKE_CASE : str = enable_pronunciation __SCREAMING_SNAKE_CASE : List[str] = enable_shape __SCREAMING_SNAKE_CASE : Tuple = pronunciation_embed_dim __SCREAMING_SNAKE_CASE : Optional[Any] = pronunciation_vocab_size __SCREAMING_SNAKE_CASE : str = shape_embed_dim __SCREAMING_SNAKE_CASE : Union[str, Any] = shape_vocab_size __SCREAMING_SNAKE_CASE : Tuple = concat_input __SCREAMING_SNAKE_CASE : Union[str, Any] = position_embedding_type __SCREAMING_SNAKE_CASE : str = classifier_dropout super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase )
674
0
a__ = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] a__ = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] a__ = { 0: '''Sunday''', 1: '''Monday''', 2: '''Tuesday''', 3: '''Wednesday''', 4: '''Thursday''', 5: '''Friday''', 6: '''Saturday''', } def A__ (snake_case : int , snake_case : int , snake_case : int ) -> Optional[Any]: assert len(str(lowercase_ ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: __UpperCamelCase : List[str] = year // 1_00 __UpperCamelCase : str = (5 * (century % 4) + 2) % 7 __UpperCamelCase : Dict = year % 1_00 __UpperCamelCase : List[Any] = centurian % 12 __UpperCamelCase : Union[str, Any] = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 __UpperCamelCase : List[Any] = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 4_00) == 0) else DOOMSDAY_LEAP[month - 1] ) __UpperCamelCase : Union[str, Any] = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
279
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : Tuple , lowercase_ : Optional[Any]=True , lowercase_ : Any="pt" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''add_prefix_space''': True} if isinstance(lowercase_ , lowercase_ ) and not line.startswith(''' ''' ) else {} __SCREAMING_SNAKE_CASE : Optional[int] = padding_side return tokenizer( [line] , max_length=lowercase_ , padding='''max_length''' if pad_to_max_length else None , truncation=lowercase_ , return_tensors=lowercase_ , add_special_tokens=lowercase_ , **lowercase_ , ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : Tuple , lowercase_ : List[Any]=None , ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = input_ids.ne(lowercase_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class snake_case ( __UpperCAmelCase ): def __init__( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :Any="train" , _lowerCamelCase :str=None , _lowerCamelCase :Optional[Any]=None , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Tuple="" , ): super().__init__() __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ).joinpath(type_path + '''.source''' ) __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ).joinpath(type_path + '''.target''' ) __SCREAMING_SNAKE_CASE : Any = self.get_char_lens(self.src_file ) __SCREAMING_SNAKE_CASE : List[str] = max_source_length __SCREAMING_SNAKE_CASE : Dict = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' __SCREAMING_SNAKE_CASE : Dict = tokenizer __SCREAMING_SNAKE_CASE : Union[str, Any] = prefix if n_obs is not None: __SCREAMING_SNAKE_CASE : Any = self.src_lens[:n_obs] __SCREAMING_SNAKE_CASE : List[str] = src_lang __SCREAMING_SNAKE_CASE : str = tgt_lang def __len__( self :int ): return len(self.src_lens ) def __getitem__( self :Optional[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = index + 1 # linecache starts at 1 __SCREAMING_SNAKE_CASE : Any = self.prefix + linecache.getline(str(self.src_file ) , _lowerCamelCase ).rstrip('''\n''' ) __SCREAMING_SNAKE_CASE : Dict = linecache.getline(str(self.tgt_file ) , _lowerCamelCase ).rstrip('''\n''' ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , _lowerCamelCase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right __SCREAMING_SNAKE_CASE : Dict = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.generator if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_source_length , '''right''' ) __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_target_length , '''right''' ) __SCREAMING_SNAKE_CASE : Any = source_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Any = target_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Dict = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :Any ): return [len(_lowerCamelCase ) for x in Path(_lowerCamelCase ).open().readlines()] def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : int = torch.stack([x['''input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = torch.stack([x['''attention_mask'''] for x in batch] ) __SCREAMING_SNAKE_CASE : int = torch.stack([x['''decoder_input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : List[str] = trim_batch(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = trim_batch(_lowerCamelCase , _lowerCamelCase , attention_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch _lowerCamelCase = getLogger(__name__) def lowerCAmelCase_ ( lowercase_ : List[List] ): '''simple docstring''' return list(itertools.chain.from_iterable(lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = get_git_info() save_json(lowercase_ , os.path.join(lowercase_ , '''git_log.json''' ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Optional[int] , lowercase_ : str=4 , **lowercase_ : List[str] ): '''simple docstring''' with open(lowercase_ , '''w''' ) as f: json.dump(lowercase_ , lowercase_ , indent=lowercase_ , **lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Union[str, Any] ): '''simple docstring''' with open(lowercase_ ) as f: return json.load(lowercase_ ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = git.Repo(search_parent_directories=lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = { '''repo_id''': str(lowercase_ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : Iterable ): '''simple docstring''' return list(map(lowercase_ , lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Any ): '''simple docstring''' with open(lowercase_ , '''wb''' ) as f: return pickle.dump(lowercase_ , lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' def remove_articles(lowercase_ : Dict ): return re.sub(r'''\b(a|an|the)\b''' , ''' ''' , lowercase_ ) def white_space_fix(lowercase_ : Optional[int] ): return " ".join(text.split() ) def remove_punc(lowercase_ : Any ): __SCREAMING_SNAKE_CASE : Optional[int] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowercase_ : int ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowercase_ ) ) ) ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Tuple = Counter(lowercase_ ) & Counter(lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = sum(common.values() ) if num_same == 0: return 0 __SCREAMING_SNAKE_CASE : Any = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[int] = (2 * precision * recall) / (precision + recall) return fa def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Union[str, Any] ): '''simple docstring''' return normalize_answer(lowercase_ ) == normalize_answer(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' assert len(lowercase_ ) == len(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for hypo, pred in zip(lowercase_ , lowercase_ ): em += exact_match_score(lowercase_ , lowercase_ ) if len(lowercase_ ) > 0: em /= len(lowercase_ ) return {"em": em} def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' return model_prefix.startswith('''rag''' ) def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead __SCREAMING_SNAKE_CASE : Any = '''dropout_rate''' for p in extra_params: if getattr(lowercase_ , lowercase_ , lowercase_ ): if not hasattr(lowercase_ , lowercase_ ) and not hasattr(lowercase_ , equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(lowercase_ ) ) delattr(lowercase_ , lowercase_ ) continue __SCREAMING_SNAKE_CASE : Optional[int] = p if hasattr(lowercase_ , lowercase_ ) else equivalent_param[p] setattr(lowercase_ , lowercase_ , getattr(lowercase_ , lowercase_ ) ) delattr(lowercase_ , lowercase_ ) return hparams, config
674
0
import os import shutil from pathlib import Path from typing import Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging if is_onnx_available(): import onnxruntime as ort __lowerCAmelCase = logging.get_logger(__name__) __lowerCAmelCase = { 'tensor(bool)': np.bool_, 'tensor(int8)': np.inta, 'tensor(uint8)': np.uinta, 'tensor(int16)': np.intaa, 'tensor(uint16)': np.uintaa, 'tensor(int32)': np.intaa, 'tensor(uint32)': np.uintaa, 'tensor(int64)': np.intaa, 'tensor(uint64)': np.uintaa, 'tensor(float16)': np.floataa, 'tensor(float)': np.floataa, 'tensor(double)': np.floataa, } class lowerCamelCase : def __init__( self :Tuple , lowercase :Tuple=None , **lowercase :Optional[Any] ) -> List[Any]: """simple docstring""" logger.info('''`diffusers.OnnxRuntimeModel` is experimental and might change in the future.''' ) SCREAMING_SNAKE_CASE = model SCREAMING_SNAKE_CASE = kwargs.get('''model_save_dir''' , _lowerCamelCase ) SCREAMING_SNAKE_CASE = kwargs.get('''latest_model_name''' , _lowerCamelCase ) def __call__( self :Dict , **lowercase :List[Any] ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE = {k: np.array(_lowerCamelCase ) for k, v in kwargs.items()} return self.model.run(_lowerCamelCase , _lowerCamelCase ) @staticmethod def snake_case__ ( lowercase :Union[str, Path] , lowercase :Any=None , lowercase :Any=None ) -> Tuple: """simple docstring""" if provider is None: logger.info('''No onnxruntime provider specified, using CPUExecutionProvider''' ) SCREAMING_SNAKE_CASE = '''CPUExecutionProvider''' return ort.InferenceSession(_lowerCamelCase , providers=[provider] , sess_options=_lowerCamelCase ) def snake_case__ ( self :Dict , lowercase :Union[str, Path] , lowercase :Optional[str] = None , **lowercase :List[Any] ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE = file_name if file_name is not None else ONNX_WEIGHTS_NAME SCREAMING_SNAKE_CASE = self.model_save_dir.joinpath(self.latest_model_name ) SCREAMING_SNAKE_CASE = Path(_lowerCamelCase ).joinpath(_lowerCamelCase ) try: shutil.copyfile(_lowerCamelCase , _lowerCamelCase ) except shutil.SameFileError: pass # copy external weights (for models >2GB) SCREAMING_SNAKE_CASE = self.model_save_dir.joinpath(_lowerCamelCase ) if src_path.exists(): SCREAMING_SNAKE_CASE = Path(_lowerCamelCase ).joinpath(_lowerCamelCase ) try: shutil.copyfile(_lowerCamelCase , _lowerCamelCase ) except shutil.SameFileError: pass def snake_case__ ( self :Any , lowercase :Union[str, os.PathLike] , **lowercase :Optional[int] , ) -> str: """simple docstring""" if os.path.isfile(_lowerCamelCase ): logger.error(f"""Provided path ({save_directory}) should be a directory, not a file""" ) return os.makedirs(_lowerCamelCase , exist_ok=_lowerCamelCase ) # saving model weights/files self._save_pretrained(_lowerCamelCase , **_lowerCamelCase ) @classmethod def snake_case__ ( cls :Union[str, Any] , lowercase :Union[str, Path] , lowercase :Optional[Union[bool, str, None]] = None , lowercase :Optional[Union[str, None]] = None , lowercase :bool = False , lowercase :Optional[str] = None , lowercase :Optional[str] = None , lowercase :Optional[str] = None , lowercase :Optional["ort.SessionOptions"] = None , **lowercase :Optional[int] , ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE = file_name if file_name is not None else ONNX_WEIGHTS_NAME # load model from local directory if os.path.isdir(_lowerCamelCase ): SCREAMING_SNAKE_CASE = OnnxRuntimeModel.load_model( os.path.join(_lowerCamelCase , _lowerCamelCase ) , provider=_lowerCamelCase , sess_options=_lowerCamelCase ) SCREAMING_SNAKE_CASE = Path(_lowerCamelCase ) # load model from hub else: # download model SCREAMING_SNAKE_CASE = hf_hub_download( repo_id=_lowerCamelCase , filename=_lowerCamelCase , use_auth_token=_lowerCamelCase , revision=_lowerCamelCase , cache_dir=_lowerCamelCase , force_download=_lowerCamelCase , ) SCREAMING_SNAKE_CASE = Path(_lowerCamelCase ).parent SCREAMING_SNAKE_CASE = Path(_lowerCamelCase ).name SCREAMING_SNAKE_CASE = OnnxRuntimeModel.load_model(_lowerCamelCase , provider=_lowerCamelCase , sess_options=_lowerCamelCase ) return cls(model=_lowerCamelCase , **_lowerCamelCase ) @classmethod def snake_case__ ( cls :List[Any] , lowercase :Union[str, Path] , lowercase :bool = True , lowercase :Optional[str] = None , lowercase :Optional[str] = None , **lowercase :List[str] , ) -> Any: """simple docstring""" SCREAMING_SNAKE_CASE = None if len(str(_lowerCamelCase ).split('''@''' ) ) == 2: SCREAMING_SNAKE_CASE = model_id.split('''@''' ) return cls._from_pretrained( model_id=_lowerCamelCase , revision=_lowerCamelCase , cache_dir=_lowerCamelCase , force_download=_lowerCamelCase , use_auth_token=_lowerCamelCase , **_lowerCamelCase , )
201
"""simple docstring""" from collections.abc import Callable import numpy as np def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : float , lowercase_ : float , lowercase_ : float , lowercase_ : float ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = int(np.ceil((x_end - xa) / step_size ) ) __SCREAMING_SNAKE_CASE : Dict = np.zeros((n + 1,) ) __SCREAMING_SNAKE_CASE : List[Any] = ya __SCREAMING_SNAKE_CASE : Dict = xa for k in range(lowercase_ ): __SCREAMING_SNAKE_CASE : str = y[k] + step_size * ode_func(lowercase_ , y[k] ) __SCREAMING_SNAKE_CASE : int = y[k] + ( (step_size / 2) * (ode_func(lowercase_ , y[k] ) + ode_func(x + step_size , lowercase_ )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
674
0
"""simple docstring""" from ....utils import logging a : List[Any] = logging.get_logger(__name__) class __UpperCAmelCase( __UpperCAmelCase ): """simple docstring""" def __init__( self , snake_case__ , snake_case__=None , snake_case__=2048 ): '''simple docstring''' lowercase__ : Union[str, Any]= config.__dict__ lowercase__ : Union[str, Any]= modal_hidden_size if num_labels: lowercase__ : int= num_labels
218
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable _lowerCamelCase = { '''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''], '''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXJapaneseForCausalLM''', '''GPTNeoXJapaneseLayer''', '''GPTNeoXJapaneseModel''', '''GPTNeoXJapanesePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
674
0
import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. lowerCamelCase :Dict = abspath(join(dirname(dirname(dirname(__file__))), 'src')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='ignore', category=FutureWarning) def __snake_case ( _UpperCamelCase ) -> Tuple: from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(lowercase_ ) def __snake_case ( _UpperCamelCase ) -> Any: from transformers.testing_utils import pytest_terminal_summary_main _a = terminalreporter.config.getoption('''--make-reports''' ) if make_reports: pytest_terminal_summary_main(lowercase_ , id=lowercase_ )
487
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case : def __init__( self :Optional[Any] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : int = num_of_nodes __SCREAMING_SNAKE_CASE : list[list[int]] = [] __SCREAMING_SNAKE_CASE : dict[int, int] = {} def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :int ): self.m_edges.append([u_node, v_node, weight] ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :int ): if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :int ): if self.m_component[u_node] != u_node: for k in self.m_component: __SCREAMING_SNAKE_CASE : Optional[Any] = self.find_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :list[int] , _lowerCamelCase :int , _lowerCamelCase :int ): if component_size[u_node] <= component_size[v_node]: __SCREAMING_SNAKE_CASE : List[Any] = v_node component_size[v_node] += component_size[u_node] self.set_component(_lowerCamelCase ) elif component_size[u_node] >= component_size[v_node]: __SCREAMING_SNAKE_CASE : Dict = self.find_component(_lowerCamelCase ) component_size[u_node] += component_size[v_node] self.set_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = [] __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : list[Any] = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) __SCREAMING_SNAKE_CASE : str = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = edge __SCREAMING_SNAKE_CASE : Optional[Any] = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): __SCREAMING_SNAKE_CASE : Optional[Any] = [u, v, w] for edge in minimum_weight_edge: if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = edge __SCREAMING_SNAKE_CASE : Tuple = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: mst_weight += w self.union(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) print(f'''Added edge [{u} - {v}]\nAdded weight: {w}\n''' ) num_of_components -= 1 __SCREAMING_SNAKE_CASE : Optional[Any] = [-1] * self.m_num_of_nodes print(f'''The total weight of the minimal spanning tree is: {mst_weight}''' ) def lowerCAmelCase_ ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
674
0
"""simple docstring""" a_ = 'Alexander Joslin' import operator as op from .stack import Stack def __UpperCAmelCase ( __UpperCamelCase ): __lowercase : str = {'''*''': op.mul, '''/''': op.truediv, '''+''': op.add, '''-''': op.sub} __lowercase : Stack[int] = Stack() __lowercase : Stack[str] = Stack() for i in equation: if i.isdigit(): # RULE 1 operand_stack.push(int(lowercase_ ) ) elif i in operators: # RULE 2 operator_stack.push(lowercase_ ) elif i == ")": # RULE 4 __lowercase : Any = operator_stack.peek() operator_stack.pop() __lowercase : List[Any] = operand_stack.peek() operand_stack.pop() __lowercase : Union[str, Any] = operand_stack.peek() operand_stack.pop() __lowercase : List[Any] = operators[opr](lowercase_ , lowercase_ ) operand_stack.push(lowercase_ ) # RULE 5 return operand_stack.peek() if __name__ == "__main__": a_ = '(5 + ((4 * 2) * (2 + 3)))' # answer = 45 print(F"{equation} = {dijkstras_two_stack_algorithm(equation)}")
76
"""simple docstring""" import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : Any , lowercase_ : int=None ): '''simple docstring''' assert torch_layer.weight.shape == weight.shape, F'''{torch_layer} layer.weight does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(lowercase_ ) if bias is not None: assert torch_layer.bias.shape == bias.shape, F'''{torch_layer} layer.bias does not match''' __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Tuple , lowercase_ : int , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) __SCREAMING_SNAKE_CASE : Tuple = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = weights[0][0][0] __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(layer_norm_a[0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # lsh weights + output __SCREAMING_SNAKE_CASE : Tuple = weights[0][1] if len(lowercase_ ) < 4: set_layer_weights_in_torch_lsh(lowercase_ , torch_block.attention , lowercase_ ) else: set_layer_weights_in_torch_local(lowercase_ , torch_block.attention , lowercase_ ) # intermediate weighs __SCREAMING_SNAKE_CASE : Any = weights[2][0][1][2] # Chunked Feed Forward if len(lowercase_ ) == 4: __SCREAMING_SNAKE_CASE : List[str] = intermediate_weights[2] # layernorm 2 __SCREAMING_SNAKE_CASE : List[str] = np.asarray(intermediate_weights[0][0] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # intermediate dense __SCREAMING_SNAKE_CASE : int = np.asarray(intermediate_weights[1][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) # intermediate out __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[4][0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = torch_model.reformer # word embeds __SCREAMING_SNAKE_CASE : int = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(lowercase_ ) , ) if isinstance(weights[3] , lowercase_ ): __SCREAMING_SNAKE_CASE : int = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): __SCREAMING_SNAKE_CASE : Dict = np.asarray(weights[3][emb_idx][0] ) assert ( position_embeddings.weights[emb_idx].shape == emb_weights.shape ), F'''{position_embeddings[emb_idx]} emb does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.tensor(lowercase_ ) ) __SCREAMING_SNAKE_CASE : List[Any] = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( lowercase_ ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): __SCREAMING_SNAKE_CASE : Union[str, Any] = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(lowercase_ , lowercase_ , lowercase_ ) # output layer norm __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[7][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # output embeddings __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[9][0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : Any , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = ReformerConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : List[str] = ReformerModelWithLMHead(lowercase_ ) with open(lowercase_ , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : int = pickle.load(lowercase_ )['''weights'''] set_model_weights_in_torch(lowercase_ , lowercase_ , config.hidden_size ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--trax_model_pkl_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained Reformer model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
674
0
lowercase_ : Optional[Any] = [ 'Audio', 'Array2D', 'Array3D', 'Array4D', 'Array5D', 'ClassLabel', 'Features', 'Sequence', 'Value', 'Image', 'Translation', 'TranslationVariableLanguages', ] from .audio import Audio from .features import ArrayaD, ArrayaD, ArrayaD, ArrayaD, ClassLabel, Features, Sequence, Value from .image import Image from .translation import Translation, TranslationVariableLanguages
64
"""simple docstring""" from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''microsoft/xprophetnet-large-wiki100-cased''': ( '''https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json''' ), } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''xlm-prophetnet''' lowerCamelCase__ = ['''past_key_values'''] lowerCamelCase__ = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self :List[str] , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[Union[str, Callable]] = "gelu" , _lowerCamelCase :Optional[int] = 3_0_5_2_2 , _lowerCamelCase :Optional[int] = 1_0_2_4 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[int] = 5_1_2 , _lowerCamelCase :Optional[float] = 0.0_2 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 2 , _lowerCamelCase :Optional[int] = 3_2 , _lowerCamelCase :Optional[int] = 1_2_8 , _lowerCamelCase :Optional[bool] = False , _lowerCamelCase :Optional[float] = 0.0 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 1 , _lowerCamelCase :Optional[int] = 2 , **_lowerCamelCase :int , ): __SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_size __SCREAMING_SNAKE_CASE : List[Any] = encoder_ffn_dim __SCREAMING_SNAKE_CASE : str = num_encoder_layers __SCREAMING_SNAKE_CASE : Optional[Any] = num_encoder_attention_heads __SCREAMING_SNAKE_CASE : str = decoder_ffn_dim __SCREAMING_SNAKE_CASE : List[Any] = num_decoder_layers __SCREAMING_SNAKE_CASE : List[str] = num_decoder_attention_heads __SCREAMING_SNAKE_CASE : Dict = max_position_embeddings __SCREAMING_SNAKE_CASE : Any = init_std # Normal(0, this parameter) __SCREAMING_SNAKE_CASE : Any = activation_function # parameters for xlmprophetnet __SCREAMING_SNAKE_CASE : List[Any] = ngram __SCREAMING_SNAKE_CASE : int = num_buckets __SCREAMING_SNAKE_CASE : List[str] = relative_max_distance __SCREAMING_SNAKE_CASE : str = disable_ngram_loss __SCREAMING_SNAKE_CASE : Optional[int] = eps # 3 Types of Dropout __SCREAMING_SNAKE_CASE : int = attention_dropout __SCREAMING_SNAKE_CASE : Optional[Any] = activation_dropout __SCREAMING_SNAKE_CASE : Dict = dropout __SCREAMING_SNAKE_CASE : Any = use_cache super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , is_encoder_decoder=_lowerCamelCase , add_cross_attention=_lowerCamelCase , decoder_start_token_id=_lowerCamelCase , **_lowerCamelCase , ) @property def SCREAMING_SNAKE_CASE_ ( self :int ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[Any] ): raise NotImplementedError( '''This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and''' ''' `num_decoder_layers`.''' )
674
0
import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class lowerCamelCase_ ( unittest.TestCase ): '''simple docstring''' __UpperCAmelCase = JukeboxTokenizer __UpperCAmelCase = { "artist": "Zac Brown Band", "genres": "Country", "lyrics": "I met a traveller from an antique land,\n Who said \"Two vast and trunkless legs of stone\n Stand in the desert. . . . Near them, on the sand,\n Half sunk a shattered visage lies, whose frown,\n And wrinkled lip, and sneer of cold command,\n Tell that its sculptor well those passions read\n Which yet survive, stamped on these lifeless things,\n The hand that mocked them, and the heart that fed;\n And on the pedestal, these words appear:\n My name is Ozymandias, King of Kings;\n Look on my Works, ye Mighty, and despair!\n Nothing beside remains. Round the decay\n Of that colossal Wreck, boundless and bare\n The lone and level sands stretch far away\n ", } @require_torch def A ( self ) -> str: '''simple docstring''' import torch __lowercase = JukeboxTokenizer.from_pretrained('''openai/jukebox-1b-lyrics''' ) __lowercase = tokenizer(**self.metas )['''input_ids'''] # fmt: off __lowercase = [ torch.tensor([[ 0, 0, 0, 7_1_6_9, 5_0_7, 9, 7_6, 3_9, 3_1, 4_6, 7_6, 2_7, 7_6, 4_6, 4_4, 2_7, 4_8, 3_1, 3_8, 3_8, 3_1, 4_4, 7_6, 3_2, 4_4, 4_1, 3_9, 7_6, 2_7, 4_0, 7_6, 2_7, 4_0, 4_6, 3_5, 4_3, 4_7, 3_1, 7_6, 3_8, 2_7, 4_0, 3_0, 6_4, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 2_3, 3_4, 4_1, 7_6, 4_5, 2_7, 3_5, 3_0, 7_6, 7_1, 2_0, 4_9, 4_1, 7_6, 4_8, 2_7, 4_5, 4_6, 7_6, 2_7, 4_0, 3_0, 7_6, 4_6, 4_4, 4_7, 4_0, 3_7, 3_8, 3_1, 4_5, 4_5, 7_6, 3_8, 3_1, 3_3, 4_5, 7_6, 4_1, 3_2, 7_6, 4_5, 4_6, 4_1, 4_0, 3_1, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1_9, 4_6, 2_7, 4_0, 3_0, 7_6, 3_5, 4_0, 7_6, 4_6, 3_4, 3_1, 7_6, 3_0, 3_1, 4_5, 3_1, 4_4, 4_6, 6_3, 7_6, 6_3, 7_6, 6_3, 7_6, 6_3, 7_6, 1_4, 3_1, 2_7, 4_4, 7_6, 4_6, 3_4, 3_1, 3_9, 6_4, 7_6, 4_1, 4_0, 7_6, 4_6, 3_4, 3_1, 7_6, 4_5, 2_7, 4_0, 3_0, 6_4, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 8, 2_7, 3_8, 3_2, 7_6, 4_5, 4_7, 4_0, 3_7, 7_6, 2_7, 7_6, 4_5, 3_4, 2_7, 4_6, 4_6, 3_1, 4_4, 3_1, 3_0, 7_6, 4_8, 3_5, 4_5, 2_7, 3_3, 3_1, 7_6, 3_8, 3_5, 3_1, 4_5, 6_4, 7_6, 4_9, 3_4, 4_1, 4_5, 3_1, 7_6, 3_2, 4_4, 4_1, 4_9, 4_0, 6_4, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1, 4_0, 3_0, 7_6, 4_9, 4_4, 3_5, 4_0, 3_7, 3_8, 3_1, 3_0, 7_6, 3_8, 3_5, 4_2, 6_4, 7_6, 2_7, 4_0, 3_0, 7_6, 4_5, 4_0, 3_1, 3_1, 4_4, 7_6, 4_1, 3_2, 7_6, 2_9, 4_1, 3_8, 3_0, 7_6, 2_9, 4_1, 3_9, 3_9, 2_7, 4_0, 3_0, 6_4, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 2_0, 3_1, 3_8, 3_8, 7_6, 4_6, 3_4, 2_7, 4_6, 7_6, 3_5, 4_6, 4_5, 7_6, 4_5, 2_9, 4_7, 3_8, 4_2, 4_6, 4_1, 4_4, 7_6, 4_9, 3_1, 3_8, 3_8, 7_6, 4_6, 3_4, 4_1, 4_5, 3_1, 7_6, 4_2, 2_7, 4_5, 4_5, 3_5, 4_1, 4_0, 4_5, 7_6, 4_4, 3_1, 2_7, 3_0, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 2_3, 3_4, 3_5, 2_9, 3_4, 7_6, 5_1, 3_1, 4_6, 7_6, 4_5, 4_7, 4_4, 4_8, 3_5, 4_8, 3_1, 6_4, 7_6, 4_5, 4_6, 2_7, 3_9, 4_2, 3_1, 3_0, 7_6, 4_1, 4_0, 7_6, 4_6, 3_4, 3_1, 4_5, 3_1, 7_6, 3_8, 3_5, 3_2, 3_1, 3_8, 3_1, 4_5, 4_5, 7_6, 4_6, 3_4, 3_5, 4_0, 3_3, 4_5, 6_4, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 2_0, 3_4, 3_1, 7_6, 3_4, 2_7, 4_0, 3_0, 7_6, 4_6, 3_4, 2_7, 4_6, 7_6, 3_9, 4_1, 2_9, 3_7, 3_1, 3_0, 7_6, 4_6, 3_4, 3_1, 3_9, 6_4, 7_6, 2_7, 4_0, 3_0, 7_6, 4_6, 3_4, 3_1, 7_6, 3_4, 3_1, 2_7, 4_4, 4_6, 7_6, 4_6, 3_4, 2_7, 4_6, 7_6, 3_2, 3_1, 3_0, 6_6, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1, 4_0, 3_0, 7_6, 4_1, 4_0, 7_6, 4_6, 3_4, 3_1, 7_6, 4_2, 3_1, 3_0, 3_1, 4_5, 4_6, 2_7, 3_8, 6_4, 7_6, 4_6, 3_4, 3_1, 4_5, 3_1, 7_6, 4_9, 4_1, 4_4, 3_0, 4_5, 7_6, 2_7, 4_2, 4_2, 3_1, 2_7, 4_4, 6_5, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1_3, 5_1, 7_6, 4_0, 2_7, 3_9, 3_1, 7_6, 3_5, 4_5, 7_6, 1_5, 5_2, 5_1, 3_9, 2_7, 4_0, 3_0, 3_5, 2_7, 4_5, 6_4, 7_6, 1_1, 3_5, 4_0, 3_3, 7_6, 4_1, 3_2, 7_6, 1_1, 3_5, 4_0, 3_3, 4_5, 6_6, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1_2, 4_1, 4_1, 3_7, 7_6, 4_1, 4_0, 7_6, 3_9, 5_1, 7_6, 2_3, 4_1, 4_4, 3_7, 4_5, 6_4, 7_6, 5_1, 3_1, 7_6, 1_3, 3_5, 3_3, 3_4, 4_6, 5_1, 6_4, 7_6, 2_7, 4_0, 3_0, 7_6, 3_0, 3_1, 4_5, 4_2, 2_7, 3_5, 4_4, 6_7, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1_4, 4_1, 4_6, 3_4, 3_5, 4_0, 3_3, 7_6, 2_8, 3_1, 4_5, 3_5, 3_0, 3_1, 7_6, 4_4, 3_1, 3_9, 2_7, 3_5, 4_0, 4_5, 6_3, 7_6, 1_8, 4_1, 4_7, 4_0, 3_0, 7_6, 4_6, 3_4, 3_1, 7_6, 3_0, 3_1, 2_9, 2_7, 5_1, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 1_5, 3_2, 7_6, 4_6, 3_4, 2_7, 4_6, 7_6, 2_9, 4_1, 3_8, 4_1, 4_5, 4_5, 2_7, 3_8, 7_6, 2_3, 4_4, 3_1, 2_9, 3_7, 6_4, 7_6, 2_8, 4_1, 4_7, 4_0, 3_0, 3_8, 3_1, 4_5, 4_5, 7_6, 2_7, 4_0, 3_0, 7_6, 2_8, 2_7, 4_4, 3_1, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 2_0, 3_4, 3_1, 7_6, 3_8, 4_1, 4_0, 3_1, 7_6, 2_7, 4_0, 3_0, 7_6, 3_8, 3_1, 4_8, 3_1, 3_8, 7_6, 4_5, 2_7, 4_0, 3_0, 4_5, 7_6, 4_5, 4_6, 4_4, 3_1, 4_6, 2_9, 3_4, 7_6, 3_2, 2_7, 4_4, 7_6, 2_7, 4_9, 2_7, 5_1, 7_8, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6, 7_6]] ), torch.tensor([[0, 0, 0, 1_0_6_9, 1_1]] ), torch.tensor([[0, 0, 0, 1_0_6_9, 1_1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def A ( self ) -> List[str]: '''simple docstring''' import torch __lowercase = JukeboxTokenizer.from_pretrained('''openai/jukebox-5b-lyrics''' ) __lowercase = tokenizer(**self.metas )['''input_ids'''] # fmt: off __lowercase = [ torch.tensor([[ 0, 0, 0, 1_0_6_9, 1_1, -1, -1, -1, -1, 9, 7_7, 3_9, 3_1, 4_6, 7_7, 2_7, 7_7, 4_6, 4_4, 2_7, 4_8, 3_1, 3_8, 3_8, 3_1, 4_4, 7_7, 3_2, 4_4, 4_1, 3_9, 7_7, 2_7, 4_0, 7_7, 2_7, 4_0, 4_6, 3_5, 4_3, 4_7, 3_1, 7_7, 3_8, 2_7, 4_0, 3_0, 6_4, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 2_3, 3_4, 4_1, 7_7, 4_5, 2_7, 3_5, 3_0, 7_7, 7_2, 2_0, 4_9, 4_1, 7_7, 4_8, 2_7, 4_5, 4_6, 7_7, 2_7, 4_0, 3_0, 7_7, 4_6, 4_4, 4_7, 4_0, 3_7, 3_8, 3_1, 4_5, 4_5, 7_7, 3_8, 3_1, 3_3, 4_5, 7_7, 4_1, 3_2, 7_7, 4_5, 4_6, 4_1, 4_0, 3_1, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1_9, 4_6, 2_7, 4_0, 3_0, 7_7, 3_5, 4_0, 7_7, 4_6, 3_4, 3_1, 7_7, 3_0, 3_1, 4_5, 3_1, 4_4, 4_6, 6_3, 7_7, 6_3, 7_7, 6_3, 7_7, 6_3, 7_7, 1_4, 3_1, 2_7, 4_4, 7_7, 4_6, 3_4, 3_1, 3_9, 6_4, 7_7, 4_1, 4_0, 7_7, 4_6, 3_4, 3_1, 7_7, 4_5, 2_7, 4_0, 3_0, 6_4, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 8, 2_7, 3_8, 3_2, 7_7, 4_5, 4_7, 4_0, 3_7, 7_7, 2_7, 7_7, 4_5, 3_4, 2_7, 4_6, 4_6, 3_1, 4_4, 3_1, 3_0, 7_7, 4_8, 3_5, 4_5, 2_7, 3_3, 3_1, 7_7, 3_8, 3_5, 3_1, 4_5, 6_4, 7_7, 4_9, 3_4, 4_1, 4_5, 3_1, 7_7, 3_2, 4_4, 4_1, 4_9, 4_0, 6_4, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1, 4_0, 3_0, 7_7, 4_9, 4_4, 3_5, 4_0, 3_7, 3_8, 3_1, 3_0, 7_7, 3_8, 3_5, 4_2, 6_4, 7_7, 2_7, 4_0, 3_0, 7_7, 4_5, 4_0, 3_1, 3_1, 4_4, 7_7, 4_1, 3_2, 7_7, 2_9, 4_1, 3_8, 3_0, 7_7, 2_9, 4_1, 3_9, 3_9, 2_7, 4_0, 3_0, 6_4, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 2_0, 3_1, 3_8, 3_8, 7_7, 4_6, 3_4, 2_7, 4_6, 7_7, 3_5, 4_6, 4_5, 7_7, 4_5, 2_9, 4_7, 3_8, 4_2, 4_6, 4_1, 4_4, 7_7, 4_9, 3_1, 3_8, 3_8, 7_7, 4_6, 3_4, 4_1, 4_5, 3_1, 7_7, 4_2, 2_7, 4_5, 4_5, 3_5, 4_1, 4_0, 4_5, 7_7, 4_4, 3_1, 2_7, 3_0, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 2_3, 3_4, 3_5, 2_9, 3_4, 7_7, 5_1, 3_1, 4_6, 7_7, 4_5, 4_7, 4_4, 4_8, 3_5, 4_8, 3_1, 6_4, 7_7, 4_5, 4_6, 2_7, 3_9, 4_2, 3_1, 3_0, 7_7, 4_1, 4_0, 7_7, 4_6, 3_4, 3_1, 4_5, 3_1, 7_7, 3_8, 3_5, 3_2, 3_1, 3_8, 3_1, 4_5, 4_5, 7_7, 4_6, 3_4, 3_5, 4_0, 3_3, 4_5, 6_4, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 2_0, 3_4, 3_1, 7_7, 3_4, 2_7, 4_0, 3_0, 7_7, 4_6, 3_4, 2_7, 4_6, 7_7, 3_9, 4_1, 2_9, 3_7, 3_1, 3_0, 7_7, 4_6, 3_4, 3_1, 3_9, 6_4, 7_7, 2_7, 4_0, 3_0, 7_7, 4_6, 3_4, 3_1, 7_7, 3_4, 3_1, 2_7, 4_4, 4_6, 7_7, 4_6, 3_4, 2_7, 4_6, 7_7, 3_2, 3_1, 3_0, 6_6, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1, 4_0, 3_0, 7_7, 4_1, 4_0, 7_7, 4_6, 3_4, 3_1, 7_7, 4_2, 3_1, 3_0, 3_1, 4_5, 4_6, 2_7, 3_8, 6_4, 7_7, 4_6, 3_4, 3_1, 4_5, 3_1, 7_7, 4_9, 4_1, 4_4, 3_0, 4_5, 7_7, 2_7, 4_2, 4_2, 3_1, 2_7, 4_4, 6_5, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1_3, 5_1, 7_7, 4_0, 2_7, 3_9, 3_1, 7_7, 3_5, 4_5, 7_7, 1_5, 5_2, 5_1, 3_9, 2_7, 4_0, 3_0, 3_5, 2_7, 4_5, 6_4, 7_7, 1_1, 3_5, 4_0, 3_3, 7_7, 4_1, 3_2, 7_7, 1_1, 3_5, 4_0, 3_3, 4_5, 6_6, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1_2, 4_1, 4_1, 3_7, 7_7, 4_1, 4_0, 7_7, 3_9, 5_1, 7_7, 2_3, 4_1, 4_4, 3_7, 4_5, 6_4, 7_7, 5_1, 3_1, 7_7, 1_3, 3_5, 3_3, 3_4, 4_6, 5_1, 6_4, 7_7, 2_7, 4_0, 3_0, 7_7, 3_0, 3_1, 4_5, 4_2, 2_7, 3_5, 4_4, 6_7, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1_4, 4_1, 4_6, 3_4, 3_5, 4_0, 3_3, 7_7, 2_8, 3_1, 4_5, 3_5, 3_0, 3_1, 7_7, 4_4, 3_1, 3_9, 2_7, 3_5, 4_0, 4_5, 6_3, 7_7, 1_8, 4_1, 4_7, 4_0, 3_0, 7_7, 4_6, 3_4, 3_1, 7_7, 3_0, 3_1, 2_9, 2_7, 5_1, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 1_5, 3_2, 7_7, 4_6, 3_4, 2_7, 4_6, 7_7, 2_9, 4_1, 3_8, 4_1, 4_5, 4_5, 2_7, 3_8, 7_7, 2_3, 4_4, 3_1, 2_9, 3_7, 6_4, 7_7, 2_8, 4_1, 4_7, 4_0, 3_0, 3_8, 3_1, 4_5, 4_5, 7_7, 2_7, 4_0, 3_0, 7_7, 2_8, 2_7, 4_4, 3_1, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 2_0, 3_4, 3_1, 7_7, 3_8, 4_1, 4_0, 3_1, 7_7, 2_7, 4_0, 3_0, 7_7, 3_8, 3_1, 4_8, 3_1, 3_8, 7_7, 4_5, 2_7, 4_0, 3_0, 4_5, 7_7, 4_5, 4_6, 4_4, 3_1, 4_6, 2_9, 3_4, 7_7, 3_2, 2_7, 4_4, 7_7, 2_7, 4_9, 2_7, 5_1, 7_9, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7, 7_7]] ), torch.tensor([[0, 0, 0, 1_0_6_9, 1_1, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 1_0_6_9, 1_1, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
639
"""simple docstring""" import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) _lowerCamelCase = [ '''cross_validation.py''', '''gradient_accumulation.py''', '''local_sgd.py''', '''multi_process_metrics.py''', '''memory.py''', '''automatic_gradient_accumulation.py''', '''fsdp_with_peak_mem_tracking.py''', '''deepspeed_with_config_support.py''', '''megatron_lm_gpt_pretraining.py''', ] class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :bool , _lowerCamelCase :str = None , _lowerCamelCase :list = None ): __SCREAMING_SNAKE_CASE : List[str] = None __SCREAMING_SNAKE_CASE : Optional[Any] = os.path.abspath(os.path.join('''examples''' , '''by_feature''' ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath('''examples''' ) for item in os.listdir(_lowerCamelCase ): if item not in EXCLUDE_EXAMPLES: __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_lowerCamelCase , _lowerCamelCase ) if os.path.isfile(_lowerCamelCase ) and ".py" in item_path: with self.subTest( tested_script=_lowerCamelCase , feature_script=_lowerCamelCase , tested_section='''main()''' if parser_only else '''training_function()''' , ): __SCREAMING_SNAKE_CASE : Tuple = compare_against_test( os.path.join(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = '''\n'''.join(_lowerCamelCase ) if special_strings is not None: for string in special_strings: __SCREAMING_SNAKE_CASE : List[Any] = diff.replace(_lowerCamelCase , '''''' ) self.assertEqual(_lowerCamelCase , '''''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath(os.path.join('''examples''' , '''cv_example.py''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = [ ''' ''' * 1_6 + '''{\n\n''', ''' ''' * 2_0 + '''"accuracy": eval_metric["accuracy"],\n\n''', ''' ''' * 2_0 + '''"f1": eval_metric["f1"],\n\n''', ''' ''' * 2_0 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''', ''' ''' * 2_0 + '''"epoch": epoch,\n\n''', ''' ''' * 1_6 + '''},\n\n''', ''' ''' * 1_6 + '''step=epoch,\n''', ''' ''' * 1_2, ''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''', ] self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = False @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().setUpClass() __SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : str = os.path.join(cls._tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) __SCREAMING_SNAKE_CASE : List[Any] = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().tearDownClass() shutil.rmtree(cls._tmpdir ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : str = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''epoch_0''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() __SCREAMING_SNAKE_CASE : Optional[int] = run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''step_2''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )} '''.split() __SCREAMING_SNAKE_CASE : Any = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )} '''.split() __SCREAMING_SNAKE_CASE : List[str] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) if torch.cuda.is_available(): __SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.device_count() else: __SCREAMING_SNAKE_CASE : Optional[int] = 1 if num_processes > 1: self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) else: self.assertIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ''' examples/by_feature/cross_validation.py --num_folds 2 '''.split() with mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''0'''} ): __SCREAMING_SNAKE_CASE : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = re.findall('''({.+})''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = [r for r in results if '''accuracy''' in r][-1] __SCREAMING_SNAKE_CASE : Tuple = ast.literal_eval(_lowerCamelCase ) self.assertGreaterEqual(results['''accuracy'''] , 0.7_5 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ['''examples/by_feature/multi_process_metrics.py'''] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with tempfile.TemporaryDirectory() as tmpdir: __SCREAMING_SNAKE_CASE : int = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(_lowerCamelCase , '''tracking''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''examples/by_feature/gradient_accumulation.py'''] run_command(self._launch_args + testargs ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = ['''examples/by_feature/local_sgd.py'''] run_command(self._launch_args + testargs )
674
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available UpperCAmelCase_ = { '''configuration_x_clip''': [ '''XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XCLIPConfig''', '''XCLIPTextConfig''', '''XCLIPVisionConfig''', ], '''processing_x_clip''': ['''XCLIPProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: UpperCAmelCase_ = [ '''XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XCLIPModel''', '''XCLIPPreTrainedModel''', '''XCLIPTextModel''', '''XCLIPVisionModel''', ] if TYPE_CHECKING: from .configuration_x_clip import ( XCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, XCLIPConfig, XCLIPTextConfig, XCLIPVisionConfig, ) from .processing_x_clip import XCLIPProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_x_clip import ( XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST, XCLIPModel, XCLIPPreTrainedModel, XCLIPTextModel, XCLIPVisionModel, ) else: import sys UpperCAmelCase_ = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
271
"""simple docstring""" import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from utils_qa import postprocess_qa_predictions import transformers from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed from transformers.trainer_pt_utils import nested_concat, nested_truncate _lowerCamelCase = trt.Logger(trt.Logger.WARNING) _lowerCamelCase = absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) _lowerCamelCase = logging.getLogger(__name__) _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--onnx_model_path''', default=None, type=str, required=True, help='''Path to ONNX model: ''', ) parser.add_argument( '''--output_dir''', default=None, type=str, required=True, help='''The output directory where the model checkpoints and predictions will be written.''', ) # Other parameters parser.add_argument( '''--tokenizer_name''', default='''''', type=str, required=True, help='''Pretrained tokenizer name or path if not the same as model_name''', ) parser.add_argument( '''--version_2_with_negative''', action='''store_true''', help='''If true, the SQuAD examples contain some that do not have an answer.''', ) parser.add_argument( '''--null_score_diff_threshold''', type=float, default=0.0, help='''If null_score - best_non_null is greater than the threshold predict null.''', ) parser.add_argument( '''--max_seq_length''', default=3_84, type=int, help=( '''The maximum total input sequence length after WordPiece tokenization. Sequences ''' '''longer than this will be truncated, and sequences shorter than this will be padded.''' ), ) parser.add_argument( '''--doc_stride''', default=1_28, type=int, help='''When splitting up a long document into chunks, how much stride to take between chunks.''', ) parser.add_argument('''--per_device_eval_batch_size''', default=8, type=int, help='''Batch size per GPU/CPU for evaluation.''') parser.add_argument( '''--n_best_size''', default=20, type=int, help='''The total number of n-best predictions to generate in the nbest_predictions.json output file.''', ) parser.add_argument( '''--max_answer_length''', default=30, type=int, help=( '''The maximum length of an answer that can be generated. This is needed because the start ''' '''and end predictions are not conditioned on one another.''' ), ) parser.add_argument('''--seed''', type=int, default=42, help='''random seed for initialization''') parser.add_argument( '''--dataset_name''', type=str, default=None, required=True, help='''The name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--dataset_config_name''', type=str, default=None, help='''The configuration name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--preprocessing_num_workers''', type=int, default=4, help='''A csv or a json file containing the training data.''' ) parser.add_argument('''--overwrite_cache''', action='''store_true''', help='''Overwrite the cached training and evaluation sets''') parser.add_argument( '''--fp16''', action='''store_true''', help='''Whether to use 16-bit (mixed) precision instead of 32-bit''', ) parser.add_argument( '''--int8''', action='''store_true''', help='''Whether to use INT8''', ) _lowerCamelCase = parser.parse_args() if args.tokenizer_name: _lowerCamelCase = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) else: raise ValueError( '''You are instantiating a new tokenizer from scratch. This is not supported by this script.''' '''You can do it from another script, save it, and load it from here, using --tokenizer_name.''' ) logger.info('''Training/evaluation parameters %s''', args) _lowerCamelCase = args.per_device_eval_batch_size _lowerCamelCase = (args.eval_batch_size, args.max_seq_length) # TRT Engine properties _lowerCamelCase = True _lowerCamelCase = '''temp_engine/bert-fp32.engine''' if args.fpaa: _lowerCamelCase = '''temp_engine/bert-fp16.engine''' if args.inta: _lowerCamelCase = '''temp_engine/bert-int8.engine''' # import ONNX file if not os.path.exists('''temp_engine'''): os.makedirs('''temp_engine''') _lowerCamelCase = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser( network, TRT_LOGGER ) as parser: with open(args.onnx_model_path, '''rb''') as model: if not parser.parse(model.read()): for error in range(parser.num_errors): print(parser.get_error(error)) # Query input names and shapes from parsed TensorRT network _lowerCamelCase = [network.get_input(i) for i in range(network.num_inputs)] _lowerCamelCase = [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: _lowerCamelCase = 1 << 50 if STRICT_TYPES: config.set_flag(trt.BuilderFlag.STRICT_TYPES) if args.fpaa: config.set_flag(trt.BuilderFlag.FPaa) if args.inta: config.set_flag(trt.BuilderFlag.INTa) _lowerCamelCase = builder.create_optimization_profile() config.add_optimization_profile(profile) for i in range(len(input_names)): profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE) _lowerCamelCase = builder.build_engine(network, config) # serialize_engine and store in file (can be directly loaded and deserialized): with open(engine_name, '''wb''') as f: f.write(engine.serialize()) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Tuple , lowercase_ : Any , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = np.asarray(inputs['''input_ids'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''attention_mask'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''token_type_ids'''] , dtype=np.intaa ) # Copy inputs cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , lowercase_ ) # start time __SCREAMING_SNAKE_CASE : Tuple = time.time() # Run inference context.execute_async( bindings=[int(lowercase_ ) for d_inp in d_inputs] + [int(lowercase_ ), int(lowercase_ )] , stream_handle=stream.handle ) # Transfer predictions back from GPU cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) # Synchronize the stream and take time stream.synchronize() # end time __SCREAMING_SNAKE_CASE : List[str] = time.time() __SCREAMING_SNAKE_CASE : int = end_time - start_time __SCREAMING_SNAKE_CASE : int = (h_outputa, h_outputa) # print(outputs) return outputs, infer_time # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. _lowerCamelCase = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). if args.dataset_name is not None: # Downloading and loading a dataset from the hub. _lowerCamelCase = load_dataset(args.dataset_name, args.dataset_config_name) else: raise ValueError('''Evaluation requires a dataset name''') # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Preprocessing the datasets. # Preprocessing is slighlty different for training and evaluation. _lowerCamelCase = raw_datasets['''validation'''].column_names _lowerCamelCase = '''question''' if '''question''' in column_names else column_names[0] _lowerCamelCase = '''context''' if '''context''' in column_names else column_names[1] _lowerCamelCase = '''answers''' if '''answers''' in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). _lowerCamelCase = tokenizer.padding_side == '''right''' if args.max_seq_length > tokenizer.model_max_length: logger.warning( f'The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the' f'model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.' ) _lowerCamelCase = min(args.max_seq_length, tokenizer.model_max_length) def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = [q.lstrip() for q in examples[question_column_name]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer( examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='''only_second''' if pad_on_right else '''only_first''' , max_length=lowercase_ , stride=args.doc_stride , return_overflowing_tokens=lowercase_ , return_offsets_mapping=lowercase_ , padding='''max_length''' , ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. __SCREAMING_SNAKE_CASE : Optional[int] = tokenized_examples.pop('''overflow_to_sample_mapping''' ) # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. __SCREAMING_SNAKE_CASE : Any = [] for i in range(len(tokenized_examples['''input_ids'''] ) ): # Grab the sequence corresponding to that example (to know what is the context and what is the question). __SCREAMING_SNAKE_CASE : int = tokenized_examples.sequence_ids(lowercase_ ) __SCREAMING_SNAKE_CASE : str = 1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. __SCREAMING_SNAKE_CASE : str = sample_mapping[i] tokenized_examples["example_id"].append(examples['''id'''][sample_index] ) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. __SCREAMING_SNAKE_CASE : List[str] = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples['''offset_mapping'''][i] ) ] return tokenized_examples _lowerCamelCase = raw_datasets['''validation'''] # Validation Feature Creation _lowerCamelCase = eval_examples.map( prepare_validation_features, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc='''Running tokenizer on validation dataset''', ) _lowerCamelCase = default_data_collator _lowerCamelCase = eval_dataset.remove_columns(['''example_id''', '''offset_mapping''']) _lowerCamelCase = DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any]="eval" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = postprocess_qa_predictions( examples=lowercase_ , features=lowercase_ , predictions=lowercase_ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=lowercase_ , ) # Format the result to the format the metric expects. if args.version_2_with_negative: __SCREAMING_SNAKE_CASE : Union[str, Any] = [ {'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items() ] else: __SCREAMING_SNAKE_CASE : int = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()] __SCREAMING_SNAKE_CASE : Any = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=lowercase_ , label_ids=lowercase_ ) _lowerCamelCase = load_metric('''squad_v2''' if args.version_2_with_negative else '''squad''') # Evaluation! logger.info('''Loading ONNX model %s for evaluation''', args.onnx_model_path) with open(engine_name, '''rb''') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine( f.read() ) as engine, engine.create_execution_context() as context: # setup for TRT inferrence for i in range(len(input_names)): context.set_binding_shape(i, INPUT_SHAPE) assert context.all_binding_shapes_specified def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' return trt.volume(engine.get_binding_shape(lowercase_ ) ) * engine.get_binding_dtype(lowercase_ ).itemsize # Allocate device memory for inputs and outputs. _lowerCamelCase = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. _lowerCamelCase = cuda.Stream() # Evaluation logger.info('''***** Running Evaluation *****''') logger.info(f' Num examples = {len(eval_dataset)}') logger.info(f' Batch size = {args.per_device_eval_batch_size}') _lowerCamelCase = 0.0 _lowerCamelCase = 0 _lowerCamelCase = timeit.default_timer() _lowerCamelCase = None for step, batch in enumerate(eval_dataloader): _lowerCamelCase , _lowerCamelCase = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 _lowerCamelCase , _lowerCamelCase = outputs _lowerCamelCase = torch.tensor(start_logits) _lowerCamelCase = torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered _lowerCamelCase = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00) _lowerCamelCase = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00) _lowerCamelCase = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) _lowerCamelCase = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00) if all_preds is not None: _lowerCamelCase = nested_truncate(all_preds, len(eval_dataset)) _lowerCamelCase = timeit.default_timer() - start_time logger.info(''' Evaluation done in total %f secs (%f sec per example)''', evalTime, evalTime / len(eval_dataset)) # Inference time from TRT logger.info('''Average Inference Time = {:.3f} ms'''.format(total_time * 10_00 / niter)) logger.info('''Total Inference Time = {:.3f} ms'''.format(total_time * 10_00)) logger.info('''Total Number of Inference = %d''', niter) _lowerCamelCase = post_processing_function(eval_examples, eval_dataset, all_preds) _lowerCamelCase = metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(f'Evaluation metrics: {eval_metric}')
674
0
def __lowerCamelCase ( _lowercase = 100 ) -> List[Any]: UpperCamelCase = (n * (n + 1) // 2) ** 2 UpperCamelCase = n * (n + 1) * (2 * n + 1) // 6 return sum_cubes - sum_squares if __name__ == "__main__": print(F"{solution() = }")
282
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = TFAutoModel.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModel.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[str] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Any ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Dict ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = TFAutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = TFAutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
674
0
"""simple docstring""" def UpperCAmelCase ( A__: int ) -> Any: __lowerCamelCase : int = n ** (1 / 3) return (val * val * val) == n if __name__ == "__main__": print(perfect_cube(27)) print(perfect_cube(4))
594
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'''vocab_file''': '''spiece.model'''} _lowerCamelCase = { '''vocab_file''': { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''', } } # TODO(PVP) - this should be removed in Transformers v5 _lowerCamelCase = { '''t5-small''': 5_12, '''t5-base''': 5_12, '''t5-large''': 5_12, '''t5-3b''': 5_12, '''t5-11b''': 5_12, } _lowerCamelCase = '''▁''' class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self :int , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Union[str, Any]="</s>" , _lowerCamelCase :List[Any]="<unk>" , _lowerCamelCase :Union[str, Any]="<pad>" , _lowerCamelCase :int=1_0_0 , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :Optional[Dict[str, Any]] = None , _lowerCamelCase :int=True , **_lowerCamelCase :List[Any] , ): # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: __SCREAMING_SNAKE_CASE : Union[str, Any] = [f'''<extra_id_{i}>''' for i in range(_lowerCamelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens __SCREAMING_SNAKE_CASE : Optional[int] = len(set(filter(lambda _lowerCamelCase : bool('''extra_id''' in str(_lowerCamelCase ) ) , _lowerCamelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( f'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are''' ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) if legacy: logger.warning_once( f'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to''' ''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = legacy __SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , extra_ids=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , legacy=_lowerCamelCase , **_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Tuple = vocab_file __SCREAMING_SNAKE_CASE : List[str] = extra_ids __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :str , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :int ): if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: __SCREAMING_SNAKE_CASE : Any = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' f''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this''' ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' f''' {pretrained_model_name_or_path} automatically truncating your input to''' f''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences''' f''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with''' ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , _lowerCamelCase , ) return max_model_length @property def SCREAMING_SNAKE_CASE_ ( self :Tuple ): return self.sp_model.get_piece_size() + self._extra_ids def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : str = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None , _lowerCamelCase :bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(_lowerCamelCase )) + [1] return ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1] def SCREAMING_SNAKE_CASE_ ( self :List[str] ): return list( set(filter(lambda _lowerCamelCase : bool(re.search(r'''<extra_id_\d+>''' , _lowerCamelCase ) ) is not None , self.additional_special_tokens ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return [self._convert_token_to_id(_lowerCamelCase ) for token in self.get_sentinel_tokens()] def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[int] ): if len(_lowerCamelCase ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated''' ''' eos tokens being added.''' ) return token_ids else: return token_ids + [self.eos_token_id] def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : Optional[Any] = self._add_eos_if_not_present(_lowerCamelCase ) if token_ids_a is None: return token_ids_a else: __SCREAMING_SNAKE_CASE : Union[str, Any] = self._add_eos_if_not_present(_lowerCamelCase ) return token_ids_a + token_ids_a def __getstate__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() __SCREAMING_SNAKE_CASE : List[str] = None return state def __setstate__( self :Optional[Any] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : Tuple = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __SCREAMING_SNAKE_CASE : Optional[int] = {} __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :"TextInput" , **_lowerCamelCase :str ): # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at # the beginning of the text if not self.legacy: __SCREAMING_SNAKE_CASE : Dict = SPIECE_UNDERLINE + text.replace(_lowerCamelCase , ''' ''' ) return super().tokenize(_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[Any] , **_lowerCamelCase :Dict ): if not self.legacy: __SCREAMING_SNAKE_CASE : str = text.startswith(_lowerCamelCase ) if is_first: __SCREAMING_SNAKE_CASE : str = text[1:] __SCREAMING_SNAKE_CASE : Tuple = self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) if not self.legacy and not is_first and not text.startswith(''' ''' ) and tokens[0].startswith(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[int] = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[Any] ): if token.startswith('''<extra_id_''' ): __SCREAMING_SNAKE_CASE : Tuple = re.match(r'''<extra_id_(\d+)>''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): if index < self.sp_model.get_piece_size(): __SCREAMING_SNAKE_CASE : List[Any] = self.sp_model.IdToPiece(_lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : Dict = f'''<extra_id_{self.vocab_size - 1 - index}>''' return token def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : str = [] __SCREAMING_SNAKE_CASE : Dict = '''''' __SCREAMING_SNAKE_CASE : Dict = 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(_lowerCamelCase ) + token __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : str = [] else: current_sub_tokens.append(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = False out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :str , _lowerCamelCase :Optional[str] = None ): if not os.path.isdir(_lowerCamelCase ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __SCREAMING_SNAKE_CASE : List[str] = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: __SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
674
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) __snake_case = {"configuration_xlnet": ["XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "XLNetConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = ["XLNetTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = ["XLNetTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ "XLNET_PRETRAINED_MODEL_ARCHIVE_LIST", "XLNetForMultipleChoice", "XLNetForQuestionAnswering", "XLNetForQuestionAnsweringSimple", "XLNetForSequenceClassification", "XLNetForTokenClassification", "XLNetLMHeadModel", "XLNetModel", "XLNetPreTrainedModel", "load_tf_weights_in_xlnet", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __snake_case = [ "TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST", "TFXLNetForMultipleChoice", "TFXLNetForQuestionAnsweringSimple", "TFXLNetForSequenceClassification", "TFXLNetForTokenClassification", "TFXLNetLMHeadModel", "TFXLNetMainLayer", "TFXLNetModel", "TFXLNetPreTrainedModel", ] if TYPE_CHECKING: from .configuration_xlnet import XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP, XLNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet import XLNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_xlnet_fast import XLNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_xlnet import ( XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, XLNetForMultipleChoice, XLNetForQuestionAnswering, XLNetForQuestionAnsweringSimple, XLNetForSequenceClassification, XLNetForTokenClassification, XLNetLMHeadModel, XLNetModel, XLNetPreTrainedModel, load_tf_weights_in_xlnet, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_xlnet import ( TF_XLNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFXLNetForMultipleChoice, TFXLNetForQuestionAnsweringSimple, TFXLNetForSequenceClassification, TFXLNetForTokenClassification, TFXLNetLMHeadModel, TFXLNetMainLayer, TFXLNetModel, TFXLNetPreTrainedModel, ) else: import sys __snake_case = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
386
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( '''files''' , [ ['''full:README.md''', '''dataset_infos.json'''], ['''empty:README.md''', '''dataset_infos.json'''], ['''dataset_infos.json'''], ['''full:README.md'''], ] , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = tmp_path_factory.mktemp('''dset_infos_dir''' ) if "full:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''---\ndataset_info:\n dataset_size: 42\n---''' ) if "empty:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''''' ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / '''dataset_infos.json''' , '''w''' ) as f: f.write('''{"default": {"dataset_size": 42}}''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( '''dataset_info''' , [ DatasetInfo(), DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ), ] , ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : DatasetInfo ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = str(lowercase_ ) dataset_info.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = DatasetInfo.from_directory(lowercase_ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(lowercase_ , '''dataset_info.json''' ) ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo( description='''foo''' , citation='''bar''' , homepage='''https://foo.bar''' , license='''CC0''' , features=Features({'''a''': Value('''int32''' )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train''', '''num_examples''': 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , ) __SCREAMING_SNAKE_CASE : Optional[int] = dataset_info._to_yaml_dict() assert sorted(lowercase_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) __SCREAMING_SNAKE_CASE : int = yaml.safe_dump(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = yaml.safe_load(lowercase_ ) assert dataset_info_yaml_dict == reloaded def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetInfo() __SCREAMING_SNAKE_CASE : Union[str, Any] = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( '''dataset_infos_dict''' , [ DatasetInfosDict(), DatasetInfosDict({'''default''': DatasetInfo()} ), DatasetInfosDict({'''my_config_name''': DatasetInfo()} ), DatasetInfosDict( { '''default''': DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ) } ), DatasetInfosDict( { '''v1''': DatasetInfo(dataset_size=42 ), '''v2''': DatasetInfo(dataset_size=1337 ), } ), ] , ) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : DatasetInfosDict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) dataset_infos_dict.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): __SCREAMING_SNAKE_CASE : Optional[int] = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(lowercase_ , '''README.md''' ) )
674
0
def A__ (snake_case : int ) -> Union[str, Any]: assert ( isinstance(lowercase_ , lowercase_ ) and number_of_steps > 0 ), F'''number_of_steps needs to be positive integer, your input {number_of_steps}''' if number_of_steps == 1: return 1 __UpperCamelCase : Union[str, Any] = 1, 1 for _ in range(number_of_steps - 1 ): __UpperCamelCase : Union[str, Any] = current + previous, current return current if __name__ == "__main__": import doctest doctest.testmod()
279
"""simple docstring""" from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class snake_case ( __UpperCAmelCase , __UpperCAmelCase ): @register_to_config def __init__( self :List[str] , _lowerCamelCase :int = 7_6_8 , ): super().__init__() __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter(torch.zeros(1 , _lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.ones(1 , _lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Optional[Union[str, torch.device]] = None , _lowerCamelCase :Optional[torch.dtype] = None , ): __SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(self.mean.to(_lowerCamelCase ).to(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(self.std.to(_lowerCamelCase ).to(_lowerCamelCase ) ) return self def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Tuple = (embeds - self.mean) * 1.0 / self.std return embeds def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = (embeds * self.std) + self.mean return embeds
674
0
import argparse import torch from safetensors.torch import load_file from diffusers import StableDiffusionPipeline def a ( a , a , a , a , a ) ->int: '''simple docstring''' SCREAMING_SNAKE_CASE = StableDiffusionPipeline.from_pretrained(lowercase_ , torch_dtype=torch.floataa ) # load LoRA weight from .safetensors SCREAMING_SNAKE_CASE = load_file(lowercase_ ) SCREAMING_SNAKE_CASE = [] # directly update weight in diffusers model for key in state_dict: # it is suggested to print out the key, it usually will be something like below # "lora_te_text_model_encoder_layers_0_self_attn_k_proj.lora_down.weight" # as we have set the alpha beforehand, so just skip if ".alpha" in key or key in visited: continue if "text" in key: SCREAMING_SNAKE_CASE = key.split('''.''' )[0].split(LORA_PREFIX_TEXT_ENCODER + '''_''' )[-1].split('''_''' ) SCREAMING_SNAKE_CASE = pipeline.text_encoder else: SCREAMING_SNAKE_CASE = key.split('''.''' )[0].split(LORA_PREFIX_UNET + '''_''' )[-1].split('''_''' ) SCREAMING_SNAKE_CASE = pipeline.unet # find the target layer SCREAMING_SNAKE_CASE = layer_infos.pop(0 ) while len(lowercase_ ) > -1: try: SCREAMING_SNAKE_CASE = curr_layer.__getattr__(lowercase_ ) if len(lowercase_ ) > 0: SCREAMING_SNAKE_CASE = layer_infos.pop(0 ) elif len(lowercase_ ) == 0: break except Exception: if len(lowercase_ ) > 0: temp_name += "_" + layer_infos.pop(0 ) else: SCREAMING_SNAKE_CASE = layer_infos.pop(0 ) SCREAMING_SNAKE_CASE = [] if "lora_down" in key: pair_keys.append(key.replace('''lora_down''' , '''lora_up''' ) ) pair_keys.append(lowercase_ ) else: pair_keys.append(lowercase_ ) pair_keys.append(key.replace('''lora_up''' , '''lora_down''' ) ) # update weight if len(state_dict[pair_keys[0]].shape ) == 4: SCREAMING_SNAKE_CASE = state_dict[pair_keys[0]].squeeze(3 ).squeeze(2 ).to(torch.floataa ) SCREAMING_SNAKE_CASE = state_dict[pair_keys[1]].squeeze(3 ).squeeze(2 ).to(torch.floataa ) curr_layer.weight.data += alpha * torch.mm(lowercase_ , lowercase_ ).unsqueeze(2 ).unsqueeze(3 ) else: SCREAMING_SNAKE_CASE = state_dict[pair_keys[0]].to(torch.floataa ) SCREAMING_SNAKE_CASE = state_dict[pair_keys[1]].to(torch.floataa ) curr_layer.weight.data += alpha * torch.mm(lowercase_ , lowercase_ ) # update visited list for item in pair_keys: visited.append(lowercase_ ) return pipeline if __name__ == "__main__": __lowerCAmelCase = argparse.ArgumentParser() parser.add_argument( '--base_model_path', default=None, type=str, required=True, help='Path to the base model in diffusers format.' ) parser.add_argument( '--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.' ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument( '--lora_prefix_unet', default='lora_unet', type=str, help='The prefix of UNet weight in safetensors' ) parser.add_argument( '--lora_prefix_text_encoder', default='lora_te', type=str, help='The prefix of text encoder weight in safetensors', ) parser.add_argument('--alpha', default=0.75, type=float, help='The merging ratio in W = W0 + alpha * deltaW') parser.add_argument( '--to_safetensors', action='store_true', help='Whether to store pipeline in safetensors format or not.' ) parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)') __lowerCAmelCase = parser.parse_args() __lowerCAmelCase = args.base_model_path __lowerCAmelCase = args.checkpoint_path __lowerCAmelCase = args.dump_path __lowerCAmelCase = args.lora_prefix_unet __lowerCAmelCase = args.lora_prefix_text_encoder __lowerCAmelCase = args.alpha __lowerCAmelCase = convert(base_model_path, checkpoint_path, lora_prefix_unet, lora_prefix_text_encoder, alpha) __lowerCAmelCase = pipe.to(args.device) pipe.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
201
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : int , lowercase_ : Any ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = BertConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : Optional[int] = BertForPreTraining(lowercase_ ) # Load weights from tf checkpoint load_tf_weights_in_bert(lowercase_ , lowercase_ , lowercase_ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--bert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained BERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
674
0
"""simple docstring""" import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin a : List[str] = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class __UpperCAmelCase( __UpperCAmelCase , unittest.TestCase ): """simple docstring""" __lowerCamelCase = XLNetTokenizer __lowerCamelCase = XLNetTokenizerFast __lowerCamelCase = True __lowerCamelCase = True def UpperCAmelCase_ ( self ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowercase__ : Dict= XLNetTokenizer(_lowerCamelCase , keep_accents=_lowerCamelCase ) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : int= '''<s>''' lowercase__ : List[Any]= 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_lowerCamelCase ) , _lowerCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_lowerCamelCase ) , _lowerCamelCase ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : int= list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "<eod>" ) self.assertEqual(len(_lowerCamelCase ) , 1006 ) def UpperCAmelCase_ ( self ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : List[Any]= XLNetTokenizer(_lowerCamelCase , keep_accents=_lowerCamelCase ) lowercase__ : str= tokenizer.tokenize("This is a test" ) self.assertListEqual(_lowerCamelCase , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [285, 46, 10, 170, 382] ) lowercase__ : Dict= tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( _lowerCamelCase , [ 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__ : Dict= tokenizer.convert_tokens_to_ids(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] ) lowercase__ : List[Any]= tokenizer.convert_ids_to_tokens(_lowerCamelCase ) self.assertListEqual( _lowerCamelCase , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ] , ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : List[Any]= XLNetTokenizer(_lowerCamelCase , do_lower_case=_lowerCamelCase ) lowercase__ : Union[str, Any]= tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( _lowerCamelCase , [ 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", "se", ".", ] , ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["▁he", "ll", "o"] ) def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : Union[str, Any]= XLNetTokenizer(_lowerCamelCase , do_lower_case=_lowerCamelCase ) lowercase__ : Tuple= tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( _lowerCamelCase , [ 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", "se", ".", ] , ) @slow def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : str= XLNetTokenizer.from_pretrained("xlnet-base-cased" ) lowercase__ : Tuple= tokenizer.encode("sequence builders" , add_special_tokens=_lowerCamelCase ) lowercase__ : Optional[int]= tokenizer.encode("multi-sequence build" , add_special_tokens=_lowerCamelCase ) lowercase__ : str= tokenizer.build_inputs_with_special_tokens(_lowerCamelCase ) lowercase__ : int= tokenizer.build_inputs_with_special_tokens(_lowerCamelCase , _lowerCamelCase ) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def UpperCAmelCase_ ( self ): '''simple docstring''' # fmt: off lowercase__ : Tuple= {'''input_ids''': [[17, 21442, 270, 17, 10, 14645, 318, 34, 17, 4546, 3145, 787, 13, 7752, 22018, 23, 21, 17, 4546, 3145, 787, 13, 3352, 14431, 13, 5500, 11, 1176, 580, 13, 16819, 4797, 23, 17, 10, 17135, 658, 19, 457, 7932, 13, 184, 19, 3154, 17135, 6468, 19, 1404, 12269, 19, 4229, 5356, 16264, 46, 19, 17, 20545, 10395, 9, 9, 9, 11, 28, 6421, 9531, 20729, 17, 10, 353, 17022, 11, 21, 6421, 9531, 16949, 17, 10, 11509, 753, 11, 33, 95, 2421, 7385, 956, 14431, 2626, 25, 842, 7385, 4836, 21, 1429, 2272, 9855, 3120, 161, 24738, 19, 13203, 658, 218, 787, 21, 430, 18482, 847, 2637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 22178, 27, 1064, 22, 956, 13, 11101, 1429, 5854, 24313, 18953, 40, 422, 24366, 68, 1758, 37, 10483, 14257, 31, 207, 263, 21, 203, 3773, 25, 71, 9735, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 2049, 3442, 17, 13894, 3380, 23, 95, 18, 17634, 2288, 9, 4, 3]], '''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, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=_lowerCamelCase , model_name="xlnet-base-cased" , revision="c841166438c31ec7ca9a106dee7bb312b73ae511" , )
218
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = ( '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.''' '''It takes two arguments named `image` which should be the original image, and `label` which should be a text ''' '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.''' ) lowerCamelCase__ = '''CIDAS/clipseg-rd64-refined''' lowerCamelCase__ = '''image_segmenter''' lowerCamelCase__ = CLIPSegForImageSegmentation lowerCamelCase__ = ['''image''', '''text'''] lowerCamelCase__ = ['''image'''] def __init__( self :Dict , *_lowerCamelCase :Union[str, Any] , **_lowerCamelCase :Tuple ): requires_backends(self , ['''vision'''] ) super().__init__(*_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :"Image" , _lowerCamelCase :str ): return self.pre_processor(text=[label] , images=[image] , padding=_lowerCamelCase , return_tensors='''pt''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[int] ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = self.model(**_lowerCamelCase ).logits return logits def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy() __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : str = 1 return Image.fromarray((array * 2_5_5).astype(np.uinta ) )
674
0
import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class UpperCAmelCase : def __init__( self: Any , __UpperCamelCase: List[Any] , __UpperCamelCase: int=2 , __UpperCamelCase: Tuple=8 , __UpperCamelCase: Union[str, Any]=True , __UpperCamelCase: Optional[int]=True , __UpperCamelCase: Optional[int]=True , __UpperCamelCase: List[str]=True , __UpperCamelCase: Union[str, Any]=99 , __UpperCamelCase: int=16 , __UpperCamelCase: str=5 , __UpperCamelCase: List[Any]=2 , __UpperCamelCase: int=36 , __UpperCamelCase: Optional[Any]="gelu" , __UpperCamelCase: int=0.0 , __UpperCamelCase: Union[str, Any]=0.0 , __UpperCamelCase: List[Any]=512 , __UpperCamelCase: Any=16 , __UpperCamelCase: Any=2 , __UpperCamelCase: Union[str, Any]=0.0_2 , __UpperCamelCase: Union[str, Any]=3 , __UpperCamelCase: Tuple=4 , __UpperCamelCase: Dict=None , ): _a = parent _a = batch_size _a = seq_length _a = is_training _a = use_input_mask _a = use_token_type_ids _a = use_labels _a = vocab_size _a = hidden_size _a = num_hidden_layers _a = num_attention_heads _a = intermediate_size _a = hidden_act _a = hidden_dropout_prob _a = attention_probs_dropout_prob _a = max_position_embeddings _a = type_vocab_size _a = type_sequence_label_size _a = initializer_range _a = num_labels _a = num_choices _a = scope def _A ( self: Optional[Any] ): _a = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) _a = None if self.use_input_mask: _a = random_attention_mask([self.batch_size, self.seq_length] ) _a = None if self.use_token_type_ids: _a = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) _a = None _a = None _a = None if self.use_labels: _a = ids_tensor([self.batch_size] , self.type_sequence_label_size ) _a = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) _a = ids_tensor([self.batch_size] , self.num_choices ) _a = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _A ( self: int ): return MraConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_lowerCamelCase , initializer_range=self.initializer_range , ) def _A ( self: Dict ): _a = self.get_config() _a = 300 return config def _A ( self: List[str] ): ( _a ) = self.prepare_config_and_inputs() _a = True _a = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) _a = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def _A ( self: Tuple , __UpperCamelCase: Optional[Any] , __UpperCamelCase: Optional[int] , __UpperCamelCase: Any , __UpperCamelCase: List[Any] , __UpperCamelCase: Tuple , __UpperCamelCase: List[str] , __UpperCamelCase: List[str] ): _a = MraModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() _a = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase ) _a = model(_lowerCamelCase , token_type_ids=_lowerCamelCase ) _a = model(_lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _A ( self: List[str] , __UpperCamelCase: List[Any] , __UpperCamelCase: int , __UpperCamelCase: List[Any] , __UpperCamelCase: Any , __UpperCamelCase: List[str] , __UpperCamelCase: int , __UpperCamelCase: Optional[int] , __UpperCamelCase: Any , __UpperCamelCase: str , ): _a = True _a = MraModel(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() _a = model( _lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , encoder_hidden_states=_lowerCamelCase , encoder_attention_mask=_lowerCamelCase , ) _a = model( _lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , encoder_hidden_states=_lowerCamelCase , ) _a = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _A ( self: Optional[int] , __UpperCamelCase: Optional[Any] , __UpperCamelCase: Dict , __UpperCamelCase: Union[str, Any] , __UpperCamelCase: str , __UpperCamelCase: int , __UpperCamelCase: Tuple , __UpperCamelCase: List[Any] ): _a = MraForMaskedLM(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() _a = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _A ( self: int , __UpperCamelCase: Union[str, Any] , __UpperCamelCase: int , __UpperCamelCase: Dict , __UpperCamelCase: Optional[Any] , __UpperCamelCase: Any , __UpperCamelCase: List[str] , __UpperCamelCase: List[Any] ): _a = MraForQuestionAnswering(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() _a = model( _lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , start_positions=_lowerCamelCase , end_positions=_lowerCamelCase , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _A ( self: Tuple , __UpperCamelCase: int , __UpperCamelCase: Union[str, Any] , __UpperCamelCase: Optional[Any] , __UpperCamelCase: Dict , __UpperCamelCase: List[Any] , __UpperCamelCase: str , __UpperCamelCase: Tuple ): _a = self.num_labels _a = MraForSequenceClassification(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() _a = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _A ( self: List[str] , __UpperCamelCase: str , __UpperCamelCase: List[str] , __UpperCamelCase: str , __UpperCamelCase: List[Any] , __UpperCamelCase: Any , __UpperCamelCase: Any , __UpperCamelCase: Tuple ): _a = self.num_labels _a = MraForTokenClassification(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() _a = model(_lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _A ( self: Any , __UpperCamelCase: List[str] , __UpperCamelCase: str , __UpperCamelCase: str , __UpperCamelCase: Any , __UpperCamelCase: Any , __UpperCamelCase: Union[str, Any] , __UpperCamelCase: Any ): _a = self.num_choices _a = MraForMultipleChoice(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() _a = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _a = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _a = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() _a = model( _lowerCamelCase , attention_mask=_lowerCamelCase , token_type_ids=_lowerCamelCase , labels=_lowerCamelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _A ( self: str ): _a = self.prepare_config_and_inputs() ( _a ) = config_and_inputs _a = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class UpperCAmelCase ( __UpperCAmelCase , unittest.TestCase ): a: str = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) a: Union[str, Any] = False a: List[Any] = False a: int = False a: Any = False a: Dict = () def _A ( self: int ): _a = MraModelTester(self ) _a = ConfigTester(self , config_class=_lowerCamelCase , hidden_size=37 ) def _A ( self: Any ): self.config_tester.run_common_tests() def _A ( self: Dict ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def _A ( self: List[str] ): _a = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: _a = type self.model_tester.create_and_check_model(*_lowerCamelCase ) def _A ( self: List[Any] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*_lowerCamelCase ) def _A ( self: Any ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*_lowerCamelCase ) def _A ( self: Optional[Any] ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*_lowerCamelCase ) def _A ( self: int ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*_lowerCamelCase ) def _A ( self: str ): _a = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*_lowerCamelCase ) @slow def _A ( self: Any ): for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _a = MraModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) @unittest.skip(reason='''MRA does not output attentions''' ) def _A ( self: Tuple ): return @require_torch class UpperCAmelCase ( unittest.TestCase ): @slow def _A ( self: List[Any] ): _a = MraModel.from_pretrained('''uw-madison/mra-base-512-4''' ) _a = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): _a = model(_lowerCamelCase )[0] _a = torch.Size((1, 256, 768) ) self.assertEqual(output.shape , _lowerCamelCase ) _a = torch.tensor( [[[-0.0_1_4_0, 0.0_8_3_0, -0.0_3_8_1], [0.1_5_4_6, 0.1_4_0_2, 0.0_2_2_0], [0.1_1_6_2, 0.0_8_5_1, 0.0_1_6_5]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _lowerCamelCase , atol=1E-4 ) ) @slow def _A ( self: List[Any] ): _a = MraForMaskedLM.from_pretrained('''uw-madison/mra-base-512-4''' ) _a = torch.arange(256 ).unsqueeze(0 ) with torch.no_grad(): _a = model(_lowerCamelCase )[0] _a = 5_0265 _a = torch.Size((1, 256, vocab_size) ) self.assertEqual(output.shape , _lowerCamelCase ) _a = torch.tensor( [[[9.2_5_9_5, -3.6_0_3_8, 11.8819], [9.3_8_6_9, -3.2_6_9_3, 11.0956], [11.8524, -3.4_9_3_8, 13.1210]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _lowerCamelCase , atol=1E-4 ) ) @slow def _A ( self: int ): _a = MraForMaskedLM.from_pretrained('''uw-madison/mra-base-4096-8-d3''' ) _a = torch.arange(4096 ).unsqueeze(0 ) with torch.no_grad(): _a = model(_lowerCamelCase )[0] _a = 5_0265 _a = torch.Size((1, 4096, vocab_size) ) self.assertEqual(output.shape , _lowerCamelCase ) _a = torch.tensor( [[[5.4_7_8_9, -2.3_5_6_4, 7.5_0_6_4], [7.9_0_6_7, -1.3_3_6_9, 9.9_6_6_8], [9.0_7_1_2, -1.8_1_0_6, 7.0_3_8_0]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , _lowerCamelCase , atol=1E-4 ) )
487
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE : Optional[int] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) __SCREAMING_SNAKE_CASE : Optional[int] = { '''do_resize''': True, '''size''': {'''height''': 1_8, '''width''': 1_8}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , _lowerCamelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , **_lowerCamelCase :List[str] ): return BertTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , **_lowerCamelCase :Optional[int] ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE : Tuple = [Image.fromarray(np.moveaxis(_lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : str = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor(do_normalize=_lowerCamelCase , padding_value=1.0 ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : Optional[int] = image_processor(_lowerCamelCase , return_tensors='''np''' ) __SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Any = self.get_image_processor() __SCREAMING_SNAKE_CASE : Any = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Optional[int] = processor(text=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = tokenizer(_lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : int = self.get_tokenizer() __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = '''lower newer''' __SCREAMING_SNAKE_CASE : int = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : int = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(_lowerCamelCase ): processor() def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Dict = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE : Tuple = processor.batch_decode(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.batch_decode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : str = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
674
0
"""simple docstring""" import contextlib import copy import random from typing import Any, Dict, Iterable, Optional, Union import numpy as np import torch from .utils import deprecate, is_transformers_available if is_transformers_available(): import transformers def __UpperCAmelCase ( __UpperCamelCase ): random.seed(lowercase_ ) np.random.seed(lowercase_ ) torch.manual_seed(lowercase_ ) torch.cuda.manual_seed_all(lowercase_ ) # ^^ safe to call this function even if cuda is not available class UpperCAmelCase_ : def __init__( self , UpperCamelCase_ , UpperCamelCase_ = 0.9_9_9_9 , UpperCamelCase_ = 0.0 , UpperCamelCase_ = 0 , UpperCamelCase_ = False , UpperCamelCase_ = 1.0 , UpperCamelCase_ = 2 / 3 , UpperCamelCase_ = None , UpperCamelCase_ = None , **UpperCamelCase_ , ) -> Tuple: if isinstance(_lowerCamelCase , torch.nn.Module ): __lowercase : int = ( '''Passing a `torch.nn.Module` to `ExponentialMovingAverage` is deprecated. ''' '''Please pass the parameters of the module instead.''' ) deprecate( '''passing a `torch.nn.Module` to `ExponentialMovingAverage`''' , '''1.0.0''' , _lowerCamelCase , standard_warn=_lowerCamelCase , ) __lowercase : List[Any] = parameters.parameters() # set use_ema_warmup to True if a torch.nn.Module is passed for backwards compatibility __lowercase : Optional[int] = True if kwargs.get('''max_value''' , _lowerCamelCase ) is not None: __lowercase : Tuple = '''The `max_value` argument is deprecated. Please use `decay` instead.''' deprecate('''max_value''' , '''1.0.0''' , _lowerCamelCase , standard_warn=_lowerCamelCase ) __lowercase : str = kwargs['''max_value'''] if kwargs.get('''min_value''' , _lowerCamelCase ) is not None: __lowercase : List[Any] = '''The `min_value` argument is deprecated. Please use `min_decay` instead.''' deprecate('''min_value''' , '''1.0.0''' , _lowerCamelCase , standard_warn=_lowerCamelCase ) __lowercase : Optional[Any] = kwargs['''min_value'''] __lowercase : Optional[int] = list(_lowerCamelCase ) __lowercase : int = [p.clone().detach() for p in parameters] if kwargs.get('''device''' , _lowerCamelCase ) is not None: __lowercase : Union[str, Any] = '''The `device` argument is deprecated. Please use `to` instead.''' deprecate('''device''' , '''1.0.0''' , _lowerCamelCase , standard_warn=_lowerCamelCase ) self.to(device=kwargs['''device'''] ) __lowercase : int = None __lowercase : Tuple = decay __lowercase : Any = min_decay __lowercase : Optional[int] = update_after_step __lowercase : Optional[Any] = use_ema_warmup __lowercase : str = inv_gamma __lowercase : Tuple = power __lowercase : Any = 0 __lowercase : str = None # set in `step()` __lowercase : Dict = model_cls __lowercase : List[str] = model_config @classmethod def _lowerCamelCase ( cls , UpperCamelCase_ , UpperCamelCase_ ) -> str: __lowercase : int = model_cls.load_config(_lowerCamelCase , return_unused_kwargs=_lowerCamelCase ) __lowercase : Union[str, Any] = model_cls.from_pretrained(_lowerCamelCase ) __lowercase : Tuple = cls(model.parameters() , model_cls=_lowerCamelCase , model_config=model.config ) ema_model.load_state_dict(_lowerCamelCase ) return ema_model def _lowerCamelCase ( self , UpperCamelCase_ ) -> Tuple: if self.model_cls is None: raise ValueError('''`save_pretrained` can only be used if `model_cls` was defined at __init__.''' ) if self.model_config is None: raise ValueError('''`save_pretrained` can only be used if `model_config` was defined at __init__.''' ) __lowercase : List[str] = self.model_cls.from_config(self.model_config ) __lowercase : List[str] = self.state_dict() state_dict.pop('''shadow_params''' , _lowerCamelCase ) model.register_to_config(**_lowerCamelCase ) self.copy_to(model.parameters() ) model.save_pretrained(_lowerCamelCase ) def _lowerCamelCase ( self , UpperCamelCase_ ) -> List[Any]: __lowercase : Dict = max(0 , optimization_step - self.update_after_step - 1 ) if step <= 0: return 0.0 if self.use_ema_warmup: __lowercase : List[str] = 1 - (1 + step / self.inv_gamma) ** -self.power else: __lowercase : Tuple = (1 + step) / (10 + step) __lowercase : List[Any] = min(_lowerCamelCase , self.decay ) # make sure decay is not smaller than min_decay __lowercase : Any = max(_lowerCamelCase , self.min_decay ) return cur_decay_value @torch.no_grad() def _lowerCamelCase ( self , UpperCamelCase_ ) -> Any: if isinstance(_lowerCamelCase , torch.nn.Module ): __lowercase : List[Any] = ( '''Passing a `torch.nn.Module` to `ExponentialMovingAverage.step` is deprecated. ''' '''Please pass the parameters of the module instead.''' ) deprecate( '''passing a `torch.nn.Module` to `ExponentialMovingAverage.step`''' , '''1.0.0''' , _lowerCamelCase , standard_warn=_lowerCamelCase , ) __lowercase : str = parameters.parameters() __lowercase : Union[str, Any] = list(_lowerCamelCase ) self.optimization_step += 1 # Compute the decay factor for the exponential moving average. __lowercase : Union[str, Any] = self.get_decay(self.optimization_step ) __lowercase : int = decay __lowercase : List[Any] = 1 - decay __lowercase : List[Any] = contextlib.nullcontext if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled(): import deepspeed for s_param, param in zip(self.shadow_params , _lowerCamelCase ): if is_transformers_available() and transformers.deepspeed.is_deepspeed_zeroa_enabled(): __lowercase : Any = deepspeed.zero.GatheredParameters(_lowerCamelCase , modifier_rank=_lowerCamelCase ) with context_manager(): if param.requires_grad: s_param.sub_(one_minus_decay * (s_param - param) ) else: s_param.copy_(_lowerCamelCase ) def _lowerCamelCase ( self , UpperCamelCase_ ) -> Tuple: __lowercase : Any = list(_lowerCamelCase ) for s_param, param in zip(self.shadow_params , _lowerCamelCase ): param.data.copy_(s_param.to(param.device ).data ) def _lowerCamelCase ( self , UpperCamelCase_=None , UpperCamelCase_=None ) -> Union[str, Any]: __lowercase : List[str] = [ p.to(device=_lowerCamelCase , dtype=_lowerCamelCase ) if p.is_floating_point() else p.to(device=_lowerCamelCase ) for p in self.shadow_params ] def _lowerCamelCase ( self ) -> str: return { "decay": self.decay, "min_decay": self.min_decay, "optimization_step": self.optimization_step, "update_after_step": self.update_after_step, "use_ema_warmup": self.use_ema_warmup, "inv_gamma": self.inv_gamma, "power": self.power, "shadow_params": self.shadow_params, } def _lowerCamelCase ( self , UpperCamelCase_ ) -> int: __lowercase : Tuple = [param.detach().cpu().clone() for param in parameters] def _lowerCamelCase ( self , UpperCamelCase_ ) -> Union[str, Any]: if self.temp_stored_params is None: raise RuntimeError('''This ExponentialMovingAverage has no `store()`ed weights ''' '''to `restore()`''' ) for c_param, param in zip(self.temp_stored_params , _lowerCamelCase ): param.data.copy_(c_param.data ) # Better memory-wise. __lowercase : Dict = None def _lowerCamelCase ( self , UpperCamelCase_ ) -> int: __lowercase : Optional[Any] = copy.deepcopy(_lowerCamelCase ) __lowercase : List[str] = state_dict.get('''decay''' , self.decay ) if self.decay < 0.0 or self.decay > 1.0: raise ValueError('''Decay must be between 0 and 1''' ) __lowercase : Dict = state_dict.get('''min_decay''' , self.min_decay ) if not isinstance(self.min_decay , _lowerCamelCase ): raise ValueError('''Invalid min_decay''' ) __lowercase : List[str] = state_dict.get('''optimization_step''' , self.optimization_step ) if not isinstance(self.optimization_step , _lowerCamelCase ): raise ValueError('''Invalid optimization_step''' ) __lowercase : Any = state_dict.get('''update_after_step''' , self.update_after_step ) if not isinstance(self.update_after_step , _lowerCamelCase ): raise ValueError('''Invalid update_after_step''' ) __lowercase : Union[str, Any] = state_dict.get('''use_ema_warmup''' , self.use_ema_warmup ) if not isinstance(self.use_ema_warmup , _lowerCamelCase ): raise ValueError('''Invalid use_ema_warmup''' ) __lowercase : int = state_dict.get('''inv_gamma''' , self.inv_gamma ) if not isinstance(self.inv_gamma , (float, int) ): raise ValueError('''Invalid inv_gamma''' ) __lowercase : Tuple = state_dict.get('''power''' , self.power ) if not isinstance(self.power , (float, int) ): raise ValueError('''Invalid power''' ) __lowercase : Optional[int] = state_dict.get('''shadow_params''' , _lowerCamelCase ) if shadow_params is not None: __lowercase : str = shadow_params if not isinstance(self.shadow_params , _lowerCamelCase ): raise ValueError('''shadow_params must be a list''' ) if not all(isinstance(_lowerCamelCase , torch.Tensor ) for p in self.shadow_params ): raise ValueError('''shadow_params must all be Tensors''' )
76
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class snake_case : def __init__( self :Optional[int] , _lowerCamelCase :int , _lowerCamelCase :Any=2 , _lowerCamelCase :List[str]=True , _lowerCamelCase :str=False , _lowerCamelCase :Tuple=1_0 , _lowerCamelCase :str=3 , _lowerCamelCase :str=3_2 * 4 , _lowerCamelCase :Dict=3_2 * 6 , _lowerCamelCase :str=4 , _lowerCamelCase :Any=3_2 , ): __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Tuple = batch_size __SCREAMING_SNAKE_CASE : Optional[Any] = is_training __SCREAMING_SNAKE_CASE : Dict = use_auxiliary_loss __SCREAMING_SNAKE_CASE : List[str] = num_queries __SCREAMING_SNAKE_CASE : Optional[int] = num_channels __SCREAMING_SNAKE_CASE : List[Any] = min_size __SCREAMING_SNAKE_CASE : int = max_size __SCREAMING_SNAKE_CASE : Any = num_labels __SCREAMING_SNAKE_CASE : Union[str, Any] = mask_feature_size def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : str = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowerCamelCase ) > 0.5 ).float() __SCREAMING_SNAKE_CASE : Dict = (torch.rand((self.batch_size, self.num_labels) , device=_lowerCamelCase ) > 0.5).long() __SCREAMING_SNAKE_CASE : str = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=1_2_8 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Any = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = output.encoder_hidden_states __SCREAMING_SNAKE_CASE : int = output.pixel_decoder_hidden_states __SCREAMING_SNAKE_CASE : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , config.decoder_config.decoder_layers ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :str , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any]=False ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = MaskFormerModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : str = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , output_hidden_states=_lowerCamelCase ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerForInstanceSegmentation(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() def comm_check_on_output(_lowerCamelCase :Optional[Any] ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = model( pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () lowerCamelCase__ = ( {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerModelTester(self ) __SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowerCamelCase ) @unittest.skip(reason='''MaskFormer does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): pass @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' ) def SCREAMING_SNAKE_CASE_ ( self :int ): pass @unittest.skip(reason='''MaskFormer is not a generative model''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): pass @unittest.skip(reason='''MaskFormer does not use token embeddings''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): pass @require_torch_multi_gpu @unittest.skip( reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Tuple = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE : List[str] = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): for model_name in ["facebook/maskformer-swin-small-coco"]: __SCREAMING_SNAKE_CASE : Tuple = MaskFormerModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Dict = (self.model_tester.min_size,) * 2 __SCREAMING_SNAKE_CASE : Dict = { '''pixel_values''': torch.randn((2, 3, *size) , device=_lowerCamelCase ), '''mask_labels''': torch.randn((2, 1_0, *size) , device=_lowerCamelCase ), '''class_labels''': torch.zeros(2 , 1_0 , device=_lowerCamelCase ).long(), } __SCREAMING_SNAKE_CASE : Dict = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Dict = model_class(_lowerCamelCase ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = model(**_lowerCamelCase , output_attentions=_lowerCamelCase ) self.assertTrue(outputs.attentions is not None ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : List[Any] = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ).loss loss.backward() def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : Tuple = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Tuple = True __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : str = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't __SCREAMING_SNAKE_CASE : Optional[int] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : int = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_lowerCamelCase ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) _lowerCamelCase = 1e-4 def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @slow class snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self :str ): return ( MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' ) if is_vision_available() else None ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : Tuple = model(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor( [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Any = torch.tensor( [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : str = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Any = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[Any] = [ [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3], [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5], [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2], ] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : List[Any] = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [ [1.65_12e00, -5.25_72e00, -3.35_19e00], [3.61_69e-02, -5.90_25e00, -2.93_13e00], [1.07_66e-04, -7.76_30e00, -5.12_63e00], ] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor __SCREAMING_SNAKE_CASE : str = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[str] = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : int = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : int = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Any = self.default_image_processor __SCREAMING_SNAKE_CASE : int = image_processor( [np.zeros((3, 8_0_0, 1_3_3_3) ), np.zeros((3, 8_0_0, 1_3_3_3) )] , segmentation_maps=[np.zeros((3_8_4, 3_8_4) ).astype(np.floataa ), np.zeros((3_8_4, 3_8_4) ).astype(np.floataa )] , return_tensors='''pt''' , ) __SCREAMING_SNAKE_CASE : Dict = inputs['''pixel_values'''].to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = [el.to(_lowerCamelCase ) for el in inputs['''mask_labels''']] __SCREAMING_SNAKE_CASE : str = [el.to(_lowerCamelCase ) for el in inputs['''class_labels''']] with torch.no_grad(): __SCREAMING_SNAKE_CASE : int = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None )
674
0
import unittest import numpy as np import timeout_decorator # noqa from transformers import BlenderbotConfig, is_flax_available from transformers.testing_utils import jax_device, require_flax, slow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor if is_flax_available(): import os # The slow tests are often failing with OOM error on GPU # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html lowercase_ : Optional[Any] = 'platform' import jax import jax.numpy as jnp from transformers import BlenderbotTokenizer from transformers.models.blenderbot.modeling_flax_blenderbot import ( FlaxBlenderbotForConditionalGeneration, FlaxBlenderbotModel, shift_tokens_right, ) def A__ ( snake_case_ : Dict , snake_case_ : Optional[int] , snake_case_ : Optional[int]=None , snake_case_ : List[str]=None , snake_case_ : Optional[int]=None , snake_case_ : str=None , snake_case_ : Optional[int]=None , snake_case_ : Optional[int]=None , ): if attention_mask is None: SCREAMING_SNAKE_CASE__: int= np.where(input_ids != config.pad_token_id , 1 , 0 ) if decoder_attention_mask is None: SCREAMING_SNAKE_CASE__: Any= np.where(decoder_input_ids != config.pad_token_id , 1 , 0 ) if head_mask is None: SCREAMING_SNAKE_CASE__: str= np.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: SCREAMING_SNAKE_CASE__: int= np.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: SCREAMING_SNAKE_CASE__: Any= np.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, } class _lowerCamelCase : def __init__( self , lowerCAmelCase , lowerCAmelCase=13 , lowerCAmelCase=7 , lowerCAmelCase=True , lowerCAmelCase=False , lowerCAmelCase=99 , lowerCAmelCase=16 , lowerCAmelCase=2 , lowerCAmelCase=4 , lowerCAmelCase=4 , lowerCAmelCase="gelu" , lowerCAmelCase=0.1 , lowerCAmelCase=0.1 , lowerCAmelCase=32 , lowerCAmelCase=2 , lowerCAmelCase=1 , lowerCAmelCase=0 , lowerCAmelCase=0.02 , ) -> Tuple: SCREAMING_SNAKE_CASE__: Optional[Any]= parent SCREAMING_SNAKE_CASE__: Union[str, Any]= batch_size SCREAMING_SNAKE_CASE__: Union[str, Any]= seq_length SCREAMING_SNAKE_CASE__: Optional[int]= is_training SCREAMING_SNAKE_CASE__: Tuple= use_labels SCREAMING_SNAKE_CASE__: Union[str, Any]= vocab_size SCREAMING_SNAKE_CASE__: Optional[int]= hidden_size SCREAMING_SNAKE_CASE__: List[str]= num_hidden_layers SCREAMING_SNAKE_CASE__: str= num_attention_heads SCREAMING_SNAKE_CASE__: int= intermediate_size SCREAMING_SNAKE_CASE__: Optional[int]= hidden_act SCREAMING_SNAKE_CASE__: Dict= hidden_dropout_prob SCREAMING_SNAKE_CASE__: int= attention_probs_dropout_prob SCREAMING_SNAKE_CASE__: Tuple= max_position_embeddings SCREAMING_SNAKE_CASE__: List[Any]= eos_token_id SCREAMING_SNAKE_CASE__: Optional[int]= pad_token_id SCREAMING_SNAKE_CASE__: Tuple= bos_token_id SCREAMING_SNAKE_CASE__: List[Any]= initializer_range def UpperCamelCase_ ( self ) -> Tuple: SCREAMING_SNAKE_CASE__: Optional[int]= np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size ) SCREAMING_SNAKE_CASE__: Dict= np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 ) SCREAMING_SNAKE_CASE__: int= shift_tokens_right(_lowerCamelCase , 1 , 2 ) SCREAMING_SNAKE_CASE__: Union[str, Any]= BlenderbotConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , initializer_range=self.initializer_range , use_cache=_lowerCamelCase , ) SCREAMING_SNAKE_CASE__: Optional[int]= prepare_blenderbot_inputs_dict(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) return config, inputs_dict def UpperCamelCase_ ( self ) -> Any: SCREAMING_SNAKE_CASE__: List[str]= self.prepare_config_and_inputs() return config, inputs_dict def UpperCamelCase_ ( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) -> List[Any]: SCREAMING_SNAKE_CASE__: Tuple= 20 SCREAMING_SNAKE_CASE__: List[str]= model_class_name(_lowerCamelCase ) SCREAMING_SNAKE_CASE__: Tuple= model.encode(inputs_dict['''input_ids'''] ) SCREAMING_SNAKE_CASE__: Dict= ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) SCREAMING_SNAKE_CASE__: Dict= model.init_cache(decoder_input_ids.shape[0] , _lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE__: Union[str, Any]= jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype='''i4''' ) SCREAMING_SNAKE_CASE__: List[str]= jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) SCREAMING_SNAKE_CASE__: Optional[int]= model.decode( decoder_input_ids[:, :-1] , _lowerCamelCase , decoder_attention_mask=_lowerCamelCase , past_key_values=_lowerCamelCase , decoder_position_ids=_lowerCamelCase , ) SCREAMING_SNAKE_CASE__: str= jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) SCREAMING_SNAKE_CASE__: Dict= model.decode( decoder_input_ids[:, -1:] , _lowerCamelCase , decoder_attention_mask=_lowerCamelCase , past_key_values=outputs_cache.past_key_values , decoder_position_ids=_lowerCamelCase , ) SCREAMING_SNAKE_CASE__: Dict= model.decode(_lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE__: Optional[Any]= np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=f'Max diff is {diff}' ) def UpperCamelCase_ ( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) -> str: SCREAMING_SNAKE_CASE__: Union[str, Any]= 20 SCREAMING_SNAKE_CASE__: Optional[int]= model_class_name(_lowerCamelCase ) SCREAMING_SNAKE_CASE__: Optional[int]= model.encode(inputs_dict['''input_ids'''] ) SCREAMING_SNAKE_CASE__: List[Any]= ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) SCREAMING_SNAKE_CASE__: List[Any]= jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) SCREAMING_SNAKE_CASE__: List[str]= model.init_cache(decoder_input_ids.shape[0] , _lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE__: str= jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) SCREAMING_SNAKE_CASE__: str= model.decode( decoder_input_ids[:, :-1] , _lowerCamelCase , decoder_attention_mask=_lowerCamelCase , past_key_values=_lowerCamelCase , decoder_position_ids=_lowerCamelCase , ) SCREAMING_SNAKE_CASE__: Any= jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) SCREAMING_SNAKE_CASE__: int= model.decode( decoder_input_ids[:, -1:] , _lowerCamelCase , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=_lowerCamelCase , decoder_position_ids=_lowerCamelCase , ) SCREAMING_SNAKE_CASE__: Dict= model.decode(_lowerCamelCase , _lowerCamelCase , decoder_attention_mask=_lowerCamelCase ) SCREAMING_SNAKE_CASE__: Optional[Any]= np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=f'Max diff is {diff}' ) @require_flax class _lowerCamelCase ( unittest.TestCase ): __a = 99 def UpperCamelCase_ ( self ) -> List[str]: SCREAMING_SNAKE_CASE__: Optional[int]= np.array( [ [71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 82, 2], [5, 97, 17, 39, 94, 40, 2], [76, 83, 94, 25, 70, 78, 2], [87, 59, 41, 35, 48, 66, 2], [55, 13, 16, 58, 5, 2, 1], # note padding [64, 27, 31, 51, 12, 75, 2], [52, 64, 86, 17, 83, 39, 2], [48, 61, 9, 24, 71, 82, 2], [26, 1, 60, 48, 22, 13, 2], [21, 5, 62, 28, 14, 76, 2], [45, 98, 37, 86, 59, 48, 2], [70, 70, 50, 9, 28, 0, 2], ] , dtype=np.intaa , ) SCREAMING_SNAKE_CASE__: Tuple= input_ids.shape[0] SCREAMING_SNAKE_CASE__: Optional[Any]= BlenderbotConfig( vocab_size=self.vocab_size , d_model=24 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=32 , decoder_ffn_dim=32 , max_position_embeddings=48 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size def UpperCamelCase_ ( self ) -> Optional[Any]: SCREAMING_SNAKE_CASE__: Dict= self._get_config_and_data() SCREAMING_SNAKE_CASE__: List[Any]= FlaxBlenderbotForConditionalGeneration(_lowerCamelCase ) SCREAMING_SNAKE_CASE__: Optional[Any]= lm_model(input_ids=_lowerCamelCase ) SCREAMING_SNAKE_CASE__: Optional[Any]= (batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs['''logits'''].shape , _lowerCamelCase ) def UpperCamelCase_ ( self ) -> List[Any]: SCREAMING_SNAKE_CASE__: int= BlenderbotConfig( vocab_size=self.vocab_size , d_model=14 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=8 , decoder_ffn_dim=8 , max_position_embeddings=48 , ) SCREAMING_SNAKE_CASE__: str= FlaxBlenderbotForConditionalGeneration(_lowerCamelCase ) SCREAMING_SNAKE_CASE__: Dict= np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]] , dtype=np.intaa ) SCREAMING_SNAKE_CASE__: int= np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]] , dtype=np.intaa ) SCREAMING_SNAKE_CASE__: int= lm_model(input_ids=_lowerCamelCase , decoder_input_ids=_lowerCamelCase ) SCREAMING_SNAKE_CASE__: Optional[int]= (*summary.shape, config.vocab_size) self.assertEqual(outputs['''logits'''].shape , _lowerCamelCase ) def UpperCamelCase_ ( self ) -> List[str]: SCREAMING_SNAKE_CASE__: int= np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]] , dtype=np.intaa ) SCREAMING_SNAKE_CASE__: Any= shift_tokens_right(_lowerCamelCase , 1 , 2 ) SCREAMING_SNAKE_CASE__: List[str]= np.equal(_lowerCamelCase , 1 ).astype(np.floataa ).sum() SCREAMING_SNAKE_CASE__: List[Any]= np.equal(_lowerCamelCase , 1 ).astype(np.floataa ).sum() self.assertEqual(shifted.shape , input_ids.shape ) self.assertEqual(_lowerCamelCase , n_pad_before - 1 ) self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() ) @require_flax class _lowerCamelCase ( __UpperCAmelCase , unittest.TestCase , __UpperCAmelCase ): __a = True __a = ( ( FlaxBlenderbotModel, FlaxBlenderbotForConditionalGeneration, ) if is_flax_available() else () ) __a = (FlaxBlenderbotForConditionalGeneration,) if is_flax_available() else () def UpperCamelCase_ ( self ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__: Union[str, Any]= FlaxBlenderbotModelTester(self ) def UpperCamelCase_ ( self ) -> Optional[Any]: SCREAMING_SNAKE_CASE__: List[str]= self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def UpperCamelCase_ ( self ) -> Optional[int]: SCREAMING_SNAKE_CASE__: str= self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward_with_attn_mask(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def UpperCamelCase_ ( self ) -> Optional[int]: SCREAMING_SNAKE_CASE__: List[Any]= self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): SCREAMING_SNAKE_CASE__: Optional[Any]= self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE__: str= model_class(_lowerCamelCase ) @jax.jit def encode_jitted(lowerCAmelCase , lowerCAmelCase=None , **lowerCAmelCase ): return model.encode(input_ids=_lowerCamelCase , attention_mask=_lowerCamelCase ) with self.subTest('''JIT Enabled''' ): SCREAMING_SNAKE_CASE__: Dict= encode_jitted(**_lowerCamelCase ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): SCREAMING_SNAKE_CASE__: Optional[int]= encode_jitted(**_lowerCamelCase ).to_tuple() self.assertEqual(len(_lowerCamelCase ) , len(_lowerCamelCase ) ) for jitted_output, output in zip(_lowerCamelCase , _lowerCamelCase ): self.assertEqual(jitted_output.shape , output.shape ) def UpperCamelCase_ ( self ) -> Tuple: SCREAMING_SNAKE_CASE__: List[Any]= self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): SCREAMING_SNAKE_CASE__: Optional[Any]= model_class(_lowerCamelCase ) SCREAMING_SNAKE_CASE__: Union[str, Any]= model.encode(inputs_dict['''input_ids'''] , inputs_dict['''attention_mask'''] ) SCREAMING_SNAKE_CASE__: Union[str, Any]= { '''decoder_input_ids''': inputs_dict['''decoder_input_ids'''], '''decoder_attention_mask''': inputs_dict['''decoder_attention_mask'''], '''encoder_outputs''': encoder_outputs, } @jax.jit def decode_jitted(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ): return model.decode( decoder_input_ids=_lowerCamelCase , decoder_attention_mask=_lowerCamelCase , encoder_outputs=_lowerCamelCase , ) with self.subTest('''JIT Enabled''' ): SCREAMING_SNAKE_CASE__: int= decode_jitted(**_lowerCamelCase ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): SCREAMING_SNAKE_CASE__: Optional[int]= decode_jitted(**_lowerCamelCase ).to_tuple() self.assertEqual(len(_lowerCamelCase ) , len(_lowerCamelCase ) ) for jitted_output, output in zip(_lowerCamelCase , _lowerCamelCase ): self.assertEqual(jitted_output.shape , output.shape ) @slow def UpperCamelCase_ ( self ) -> str: for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE__: Optional[int]= model_class_name.from_pretrained('''facebook/blenderbot-400M-distill''' ) # FlaxBlenderbotForSequenceClassification expects eos token in input_ids SCREAMING_SNAKE_CASE__: Union[str, Any]= np.ones((1, 1) ) * model.config.eos_token_id SCREAMING_SNAKE_CASE__: int= model(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) @unittest.skipUnless(jax_device != '''cpu''' , '''3B test too slow on CPU.''' ) @slow def UpperCamelCase_ ( self ) -> Optional[int]: SCREAMING_SNAKE_CASE__: int= {'''num_beams''': 1, '''early_stopping''': True, '''min_length''': 15, '''max_length''': 25} SCREAMING_SNAKE_CASE__: List[str]= {'''skip_special_tokens''': True, '''clean_up_tokenization_spaces''': True} SCREAMING_SNAKE_CASE__: Any= FlaxBlenderbotForConditionalGeneration.from_pretrained('''facebook/blenderbot-3B''' , from_pt=_lowerCamelCase ) SCREAMING_SNAKE_CASE__: Union[str, Any]= BlenderbotTokenizer.from_pretrained('''facebook/blenderbot-3B''' ) SCREAMING_SNAKE_CASE__: Union[str, Any]= ['''Sam'''] SCREAMING_SNAKE_CASE__: Any= tokenizer(_lowerCamelCase , return_tensors='''jax''' ) SCREAMING_SNAKE_CASE__: List[Any]= model.generate(**_lowerCamelCase , **_lowerCamelCase ) SCREAMING_SNAKE_CASE__: Union[str, Any]= '''Sam is a great name. It means "sun" in Gaelic.''' SCREAMING_SNAKE_CASE__: str= tokenizer.batch_decode(_lowerCamelCase , **_lowerCamelCase ) assert generated_txt[0].strip() == tgt_text
64
"""simple docstring""" import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification _lowerCamelCase = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co _lowerCamelCase = '''main''' # Default branch name _lowerCamelCase = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2''' # One particular commit (not the top of `main`) _lowerCamelCase = '''aaaaaaa''' # This commit does not exist, so we should 404. _lowerCamelCase = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684''' # Sha-1 of config.json on the top of `main`, for checking purposes _lowerCamelCase = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3''' @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Welcome!''' ) yield print('''Bye!''' ) @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Bonjour!''' ) yield print('''Au revoir!''' ) class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): # If the spec is missing, importlib would not be able to import the module dynamically. assert transformers.__spec__ is not None assert importlib.util.find_spec('''transformers''' ) is not None class snake_case ( unittest.TestCase ): @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[int] ): with ContextManagers([] ): print('''Transformers are awesome!''' ) # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , '''Transformers are awesome!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): with ContextManagers([context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Welcome!\nTransformers are awesome!\nBye!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[str] ): with ContextManagers([context_fr(), context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n''' ) @require_torch def SCREAMING_SNAKE_CASE_ ( self :List[str] ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_tf def SCREAMING_SNAKE_CASE_ ( self :int ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_flax def SCREAMING_SNAKE_CASE_ ( self :Dict ): # Flax models don't have labels self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , [] )
674
0
from __future__ import annotations from PIL import Image # Define glider example a : List[Any] = [ [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], ] # Define blinker example a : Tuple = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] def lowercase_ ( _UpperCamelCase ): '''simple docstring''' __lowercase = [] for i in range(len(lowercase_ ) ): __lowercase = [] for j in range(len(cells[i] ) ): # Get the number of live neighbours __lowercase = 0 if i > 0 and j > 0: neighbour_count += cells[i - 1][j - 1] if i > 0: neighbour_count += cells[i - 1][j] if i > 0 and j < len(cells[i] ) - 1: neighbour_count += cells[i - 1][j + 1] if j > 0: neighbour_count += cells[i][j - 1] if j < len(cells[i] ) - 1: neighbour_count += cells[i][j + 1] if i < len(lowercase_ ) - 1 and j > 0: neighbour_count += cells[i + 1][j - 1] if i < len(lowercase_ ) - 1: neighbour_count += cells[i + 1][j] if i < len(lowercase_ ) - 1 and j < len(cells[i] ) - 1: neighbour_count += cells[i + 1][j + 1] # Rules of the game of life (excerpt from Wikipedia): # 1. Any live cell with two or three live neighbours survives. # 2. Any dead cell with three live neighbours becomes a live cell. # 3. All other live cells die in the next generation. # Similarly, all other dead cells stay dead. __lowercase = cells[i][j] == 1 if ( (alive and 2 <= neighbour_count <= 3) or not alive and neighbour_count == 3 ): next_generation_row.append(1 ) else: next_generation_row.append(0 ) next_generation.append(lowercase_ ) return next_generation def lowercase_ ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' __lowercase = [] for _ in range(lowercase_ ): # Create output image __lowercase = Image.new('''RGB''' , (len(cells[0] ), len(lowercase_ )) ) __lowercase = img.load() # Save cells to image for x in range(len(lowercase_ ) ): for y in range(len(cells[0] ) ): __lowercase = 2_55 - cells[y][x] * 2_55 __lowercase = (colour, colour, colour) # Save image images.append(lowercase_ ) __lowercase = new_generation(lowercase_ ) return images if __name__ == "__main__": a : List[Any] = generate_images(GLIDER, 16) images[0].save('''out.gif''', save_all=True, append_images=images[1:])
639
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class snake_case ( unittest.TestCase ): def __init__( self :List[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Tuple=7 , _lowerCamelCase :Dict=3 , _lowerCamelCase :Optional[Any]=3_0 , _lowerCamelCase :List[str]=4_0_0 , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :List[Any]=True , _lowerCamelCase :Any=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=True , _lowerCamelCase :str=1 / 2_5_5 , _lowerCamelCase :Union[str, Any]=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Dict = batch_size __SCREAMING_SNAKE_CASE : str = num_channels __SCREAMING_SNAKE_CASE : Union[str, Any] = min_resolution __SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution __SCREAMING_SNAKE_CASE : Tuple = do_resize __SCREAMING_SNAKE_CASE : Union[str, Any] = size __SCREAMING_SNAKE_CASE : int = do_normalize __SCREAMING_SNAKE_CASE : List[Any] = image_mean __SCREAMING_SNAKE_CASE : Tuple = image_std __SCREAMING_SNAKE_CASE : Dict = do_rescale __SCREAMING_SNAKE_CASE : Optional[int] = rescale_factor __SCREAMING_SNAKE_CASE : List[Any] = do_pad def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :List[Any]=False ): if not batched: __SCREAMING_SNAKE_CASE : str = image_inputs[0] if isinstance(_lowerCamelCase , Image.Image ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = image.size else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = image.shape[1], image.shape[2] if w < h: __SCREAMING_SNAKE_CASE : str = int(self.size['''shortest_edge'''] * h / w ) __SCREAMING_SNAKE_CASE : int = self.size['''shortest_edge'''] elif w > h: __SCREAMING_SNAKE_CASE : Optional[Any] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : int = int(self.size['''shortest_edge'''] * w / h ) else: __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] else: __SCREAMING_SNAKE_CASE : Optional[Any] = [] for image in image_inputs: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __SCREAMING_SNAKE_CASE : Optional[int] = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0] __SCREAMING_SNAKE_CASE : int = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = YolosImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=_lowerCamelCase ) self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2, '''longest_edge''': 8_4} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): pass def SCREAMING_SNAKE_CASE_ ( self :int ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : str = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : List[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Any ): # Initialize image_processing __SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : Optional[int] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): # Initialize image_processings __SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(do_resize=_lowerCamelCase , do_normalize=_lowerCamelCase , do_rescale=_lowerCamelCase ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a.pad(_lowerCamelCase , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a(_lowerCamelCase , return_tensors='''pt''' ) self.assertTrue( torch.allclose(encoded_images_with_method['''pixel_values'''] , encoded_images['''pixel_values'''] , atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): # prepare image and target __SCREAMING_SNAKE_CASE : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Tuple = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''image_id''': 3_9_7_6_9, '''annotations''': target} # encode them __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessor.from_pretrained('''hustvl/yolos-small''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : Optional[int] = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Dict = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify orig_size __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # prepare image, target and masks_path __SCREAMING_SNAKE_CASE : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Dict = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9_7_6_9, '''segments_info''': target} __SCREAMING_SNAKE_CASE : Optional[int] = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them __SCREAMING_SNAKE_CASE : Any = YolosImageProcessor(format='''coco_panoptic''' ) __SCREAMING_SNAKE_CASE : Dict = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : str = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Any = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Dict = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify masks __SCREAMING_SNAKE_CASE : Optional[Any] = 8_2_2_8_7_3 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _lowerCamelCase ) # verify orig_size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : Any = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
674
0
import inspect import unittest from transformers import BitConfig 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, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import BitBackbone, BitForImageClassification, BitImageProcessor, BitModel from transformers.models.bit.modeling_bit import BIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class __magic_name__ : """simple docstring""" def __init__( self : Optional[int] , _lowercase : str , _lowercase : int=3 , _lowercase : List[Any]=32 , _lowercase : int=3 , _lowercase : Dict=10 , _lowercase : int=[8, 16, 32, 64] , _lowercase : List[Any]=[1, 1, 2, 1] , _lowercase : Tuple=True , _lowercase : List[str]=True , _lowercase : str="relu" , _lowercase : List[Any]=3 , _lowercase : Optional[int]=None , _lowercase : Optional[int]=["stage2", "stage3", "stage4"] , _lowercase : Optional[Any]=[2, 3, 4] , _lowercase : Tuple=1 , ): """simple docstring""" _UpperCamelCase: Dict = parent _UpperCamelCase: Union[str, Any] = batch_size _UpperCamelCase: List[Any] = image_size _UpperCamelCase: Union[str, Any] = num_channels _UpperCamelCase: Any = embeddings_size _UpperCamelCase: Any = hidden_sizes _UpperCamelCase: int = depths _UpperCamelCase: Any = is_training _UpperCamelCase: List[str] = use_labels _UpperCamelCase: Any = hidden_act _UpperCamelCase: str = num_labels _UpperCamelCase: Tuple = scope _UpperCamelCase: Union[str, Any] = len(_lowerCamelCase ) _UpperCamelCase: int = out_features _UpperCamelCase: Any = out_indices _UpperCamelCase: int = num_groups def lowerCAmelCase ( self : List[str] ): """simple docstring""" _UpperCamelCase: List[str] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _UpperCamelCase: List[str] = None if self.use_labels: _UpperCamelCase: Any = ids_tensor([self.batch_size] , self.num_labels ) _UpperCamelCase: Dict = self.get_config() return config, pixel_values, labels def lowerCAmelCase ( self : Dict ): """simple docstring""" return BitConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , out_features=self.out_features , out_indices=self.out_indices , num_groups=self.num_groups , ) def lowerCAmelCase ( self : Union[str, Any] , _lowercase : int , _lowercase : Optional[Any] , _lowercase : Tuple ): """simple docstring""" _UpperCamelCase: Optional[int] = BitModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() _UpperCamelCase: Optional[Any] = model(_lowerCamelCase ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def lowerCAmelCase ( self : str , _lowercase : Any , _lowercase : Union[str, Any] , _lowercase : int ): """simple docstring""" _UpperCamelCase: int = self.num_labels _UpperCamelCase: int = BitForImageClassification(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() _UpperCamelCase: Dict = model(_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCAmelCase ( self : Tuple , _lowercase : List[Any] , _lowercase : Union[str, Any] , _lowercase : str ): """simple docstring""" _UpperCamelCase: Tuple = BitBackbone(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() _UpperCamelCase: Any = model(_lowerCamelCase ) # 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.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None _UpperCamelCase: Tuple = None _UpperCamelCase: Tuple = BitBackbone(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() _UpperCamelCase: Tuple = model(_lowerCamelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def lowerCAmelCase ( self : Union[str, Any] ): """simple docstring""" _UpperCamelCase: Any = self.prepare_config_and_inputs() _UpperCamelCase: Tuple = config_and_inputs _UpperCamelCase: Optional[Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class __magic_name__ ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): """simple docstring""" lowerCAmelCase : str = (BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else () lowerCAmelCase : Union[str, Any] = ( {'''feature-extraction''': BitModel, '''image-classification''': BitForImageClassification} if is_torch_available() else {} ) lowerCAmelCase : Optional[Any] = False lowerCAmelCase : List[str] = False lowerCAmelCase : List[str] = False lowerCAmelCase : Union[str, Any] = False lowerCAmelCase : Tuple = False def lowerCAmelCase ( self : Optional[int] ): """simple docstring""" _UpperCamelCase: Union[str, Any] = BitModelTester(self ) _UpperCamelCase: Optional[Any] = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase ) def lowerCAmelCase ( 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 lowerCAmelCase ( self : Dict ): """simple docstring""" return @unittest.skip(reason='''Bit does not output attentions''' ) def lowerCAmelCase ( self : Dict ): """simple docstring""" pass @unittest.skip(reason='''Bit does not use inputs_embeds''' ) def lowerCAmelCase ( self : List[Any] ): """simple docstring""" pass @unittest.skip(reason='''Bit does not support input and output embeddings''' ) def lowerCAmelCase ( self : Union[str, Any] ): """simple docstring""" pass def lowerCAmelCase ( self : List[str] ): """simple docstring""" _UpperCamelCase: Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCamelCase: str = model_class(_lowerCamelCase ) _UpperCamelCase: List[str] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _UpperCamelCase: str = [*signature.parameters.keys()] _UpperCamelCase: Any = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) def lowerCAmelCase ( self : int ): """simple docstring""" _UpperCamelCase: Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def lowerCAmelCase ( self : Any ): """simple docstring""" _UpperCamelCase: str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*_lowerCamelCase ) def lowerCAmelCase ( self : Tuple ): """simple docstring""" _UpperCamelCase: Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _UpperCamelCase: List[Any] = model_class(config=_lowerCamelCase ) for name, module in model.named_modules(): if isinstance(_lowerCamelCase , (nn.BatchNormad, nn.GroupNorm) ): self.assertTrue( torch.all(module.weight == 1 ) , msg=f"""Parameter {name} of model {model_class} seems not properly initialized""" , ) self.assertTrue( torch.all(module.bias == 0 ) , msg=f"""Parameter {name} of model {model_class} seems not properly initialized""" , ) def lowerCAmelCase ( self : List[Any] ): """simple docstring""" def check_hidden_states_output(_lowercase : Optional[int] , _lowercase : Tuple , _lowercase : List[Any] ): _UpperCamelCase: Optional[int] = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() with torch.no_grad(): _UpperCamelCase: Union[str, Any] = model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) _UpperCamelCase: int = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _UpperCamelCase: Optional[Any] = self.model_tester.num_stages self.assertEqual(len(_lowerCamelCase ) , expected_num_stages + 1 ) # Bit's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) _UpperCamelCase: List[str] = self.model_tester.prepare_config_and_inputs_for_common() _UpperCamelCase: List[Any] = ['''preactivation''', '''bottleneck'''] for model_class in self.all_model_classes: for layer_type in layers_type: _UpperCamelCase: Optional[int] = layer_type _UpperCamelCase: Any = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _UpperCamelCase: Tuple = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @unittest.skip(reason='''Bit does not use feedforward chunking''' ) def lowerCAmelCase ( self : Optional[int] ): """simple docstring""" pass def lowerCAmelCase ( self : List[Any] ): """simple docstring""" _UpperCamelCase: Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase ) @slow def lowerCAmelCase ( self : Optional[Any] ): """simple docstring""" for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _UpperCamelCase: str = BitModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def lowerCAmelCase_ ( ) -> Optional[int]: '''simple docstring''' _UpperCamelCase: Union[str, Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class __magic_name__ ( unittest.TestCase ): """simple docstring""" @cached_property def lowerCAmelCase ( self : Tuple ): """simple docstring""" return ( BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def lowerCAmelCase ( self : Any ): """simple docstring""" _UpperCamelCase: Any = BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(_lowerCamelCase ) _UpperCamelCase: Tuple = self.default_image_processor _UpperCamelCase: str = prepare_img() _UpperCamelCase: Any = image_processor(images=_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) # forward pass with torch.no_grad(): _UpperCamelCase: Any = model(**_lowerCamelCase ) # verify the logits _UpperCamelCase: Optional[int] = torch.Size((1, 1_000) ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) _UpperCamelCase: Tuple = torch.tensor([[-0.6526, -0.5263, -1.4398]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowerCamelCase , atol=1E-4 ) ) @require_torch class __magic_name__ ( __UpperCAmelCase , unittest.TestCase ): """simple docstring""" lowerCAmelCase : Dict = (BitBackbone,) if is_torch_available() else () lowerCAmelCase : Optional[int] = BitConfig lowerCAmelCase : Optional[Any] = False def lowerCAmelCase ( self : str ): """simple docstring""" _UpperCamelCase: Union[str, Any] = BitModelTester(self )
271
"""simple docstring""" from __future__ import annotations def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) return len(lowercase_ ) == 9 and set(lowercase_ ) == set('''123456789''' ) def lowerCAmelCase_ ( ): '''simple docstring''' for base_num in range(9999 , 4999 , -1 ): __SCREAMING_SNAKE_CASE : List[str] = 10_0002 * base_num if is_9_pandigital(lowercase_ ): return candidate for base_num in range(333 , 99 , -1 ): __SCREAMING_SNAKE_CASE : List[Any] = 100_2003 * base_num if is_9_pandigital(lowercase_ ): return candidate return None if __name__ == "__main__": print(f'{solution() = }')
674
0
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class _lowerCAmelCase ( unittest.TestCase ): """simple docstring""" def __init__( self : List[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Tuple=7 , SCREAMING_SNAKE_CASE__ : Dict=3 , SCREAMING_SNAKE_CASE__ : Optional[Any]=30 , SCREAMING_SNAKE_CASE__ : List[str]=4_00 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , SCREAMING_SNAKE_CASE__ : List[Any]=True , SCREAMING_SNAKE_CASE__ : Any=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE__ : Dict=[0.5, 0.5, 0.5] , SCREAMING_SNAKE_CASE__ : Dict=True , SCREAMING_SNAKE_CASE__ : str=1 / 2_55 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , ): """simple docstring""" UpperCamelCase = size if size is not None else {'''shortest_edge''': 18, '''longest_edge''': 13_33} UpperCamelCase = parent UpperCamelCase = batch_size UpperCamelCase = num_channels UpperCamelCase = min_resolution UpperCamelCase = max_resolution UpperCamelCase = do_resize UpperCamelCase = size UpperCamelCase = do_normalize UpperCamelCase = image_mean UpperCamelCase = image_std UpperCamelCase = do_rescale UpperCamelCase = rescale_factor UpperCamelCase = do_pad def __lowerCAmelCase ( self : Optional[Any] ): """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def __lowerCAmelCase ( self : Tuple , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : List[Any]=False ): """simple docstring""" if not batched: UpperCamelCase = image_inputs[0] if isinstance(_lowerCamelCase , Image.Image ): UpperCamelCase = image.size else: UpperCamelCase = image.shape[1], image.shape[2] if w < h: UpperCamelCase = int(self.size['shortest_edge'] * h / w ) UpperCamelCase = self.size['''shortest_edge'''] elif w > h: UpperCamelCase = self.size['''shortest_edge'''] UpperCamelCase = int(self.size['shortest_edge'] * w / h ) else: UpperCamelCase = self.size['''shortest_edge'''] UpperCamelCase = self.size['''shortest_edge'''] else: UpperCamelCase = [] for image in image_inputs: UpperCamelCase = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) UpperCamelCase = max(_lowerCamelCase , key=lambda SCREAMING_SNAKE_CASE__ : item[0] )[0] UpperCamelCase = max(_lowerCamelCase , key=lambda SCREAMING_SNAKE_CASE__ : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class _lowerCAmelCase ( __UpperCAmelCase , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] =YolosImageProcessor if is_vision_available() else None def __lowerCAmelCase ( self : Optional[int] ): """simple docstring""" UpperCamelCase = YolosImageProcessingTester(self ) @property def __lowerCAmelCase ( self : Optional[int] ): """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowerCAmelCase ( self : Tuple ): """simple docstring""" UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , 'image_mean' ) ) self.assertTrue(hasattr(_lowerCamelCase , 'image_std' ) ) self.assertTrue(hasattr(_lowerCamelCase , 'do_normalize' ) ) self.assertTrue(hasattr(_lowerCamelCase , 'do_resize' ) ) self.assertTrue(hasattr(_lowerCamelCase , 'size' ) ) def __lowerCAmelCase ( self : Tuple ): """simple docstring""" UpperCamelCase = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 13_33} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) UpperCamelCase = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_lowerCamelCase ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) def __lowerCAmelCase ( self : List[str] ): """simple docstring""" pass def __lowerCAmelCase ( self : 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=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input UpperCamelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values UpperCamelCase = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCamelCase = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) UpperCamelCase = image_processing(_lowerCamelCase , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __lowerCAmelCase ( self : Optional[int] ): """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=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input UpperCamelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values UpperCamelCase = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCamelCase = image_processing(_lowerCamelCase , return_tensors='pt' ).pixel_values UpperCamelCase = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __lowerCAmelCase ( self : Any ): """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=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input UpperCamelCase = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values UpperCamelCase = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched UpperCamelCase = image_processing(_lowerCamelCase , return_tensors='pt' ).pixel_values UpperCamelCase = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def __lowerCAmelCase ( self : List[str] ): """simple docstring""" UpperCamelCase = self.image_processing_class(**self.image_processor_dict ) UpperCamelCase = self.image_processing_class(do_resize=_lowerCamelCase , do_normalize=_lowerCamelCase , do_rescale=_lowerCamelCase ) # create random PyTorch tensors UpperCamelCase = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors UpperCamelCase = image_processing_a.pad(_lowerCamelCase , return_tensors='pt' ) UpperCamelCase = image_processing_a(_lowerCamelCase , return_tensors='pt' ) self.assertTrue( torch.allclose(encoded_images_with_method['pixel_values'] , encoded_images['pixel_values'] , atol=1e-4 ) ) @slow def __lowerCAmelCase ( self : int ): """simple docstring""" UpperCamelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: UpperCamelCase = json.loads(f.read() ) UpperCamelCase = {'''image_id''': 3_97_69, '''annotations''': target} # encode them UpperCamelCase = YolosImageProcessor.from_pretrained('hustvl/yolos-small' ) UpperCamelCase = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors='pt' ) # verify pixel values UpperCamelCase = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , _lowerCamelCase ) UpperCamelCase = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area UpperCamelCase = torch.tensor([58_87.96_00, 1_12_50.20_61, 48_93_53.84_38, 83_71_22.75_00, 14_79_67.51_56, 16_57_32.34_38] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _lowerCamelCase ) ) # verify boxes UpperCamelCase = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _lowerCamelCase ) UpperCamelCase = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id UpperCamelCase = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _lowerCamelCase ) ) # verify is_crowd UpperCamelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _lowerCamelCase ) ) # verify class_labels UpperCamelCase = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _lowerCamelCase ) ) # verify orig_size UpperCamelCase = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _lowerCamelCase ) ) # verify size UpperCamelCase = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _lowerCamelCase ) ) @slow def __lowerCAmelCase ( self : Optional[int] ): """simple docstring""" UpperCamelCase = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: UpperCamelCase = json.loads(f.read() ) UpperCamelCase = {'''file_name''': '''000000039769.png''', '''image_id''': 3_97_69, '''segments_info''': target} UpperCamelCase = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them UpperCamelCase = YolosImageProcessor(format='coco_panoptic' ) UpperCamelCase = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors='pt' ) # verify pixel values UpperCamelCase = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , _lowerCamelCase ) UpperCamelCase = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area UpperCamelCase = torch.tensor([14_79_79.68_75, 16_55_27.04_69, 48_46_38.59_38, 1_12_92.93_75, 58_79.65_62, 76_34.11_47] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , _lowerCamelCase ) ) # verify boxes UpperCamelCase = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , _lowerCamelCase ) UpperCamelCase = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id UpperCamelCase = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , _lowerCamelCase ) ) # verify is_crowd UpperCamelCase = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , _lowerCamelCase ) ) # verify class_labels UpperCamelCase = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , _lowerCamelCase ) ) # verify masks UpperCamelCase = 82_28_73 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , _lowerCamelCase ) # verify orig_size UpperCamelCase = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , _lowerCamelCase ) ) # verify size UpperCamelCase = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , _lowerCamelCase ) )
282
"""simple docstring""" import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Tuple = 0 def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Optional[Any] = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Dict = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : str = CLIPConfig() # Create a dummy config file with image_proceesor_type __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ).to_dict() config_dict.pop('''image_processor_type''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor(**_lowerCamelCase ) # save in new folder model_config.save_pretrained(_lowerCamelCase ) config.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) # make sure private variable is not incorrectly saved __SCREAMING_SNAKE_CASE : Tuple = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): with self.assertRaisesRegex( _lowerCamelCase , '''clip-base is not a local folder and is not a valid model identifier''' ): __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained('''clip-base''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): with self.assertRaisesRegex( _lowerCamelCase , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(_lowerCamelCase , revision='''aaaaaa''' ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with self.assertRaisesRegex( _lowerCamelCase , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase , trust_remote_code=_lowerCamelCase ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_lowerCamelCase ): AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = CustomImageProcessor.from_pretrained(_lowerCamelCase ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def SCREAMING_SNAKE_CASE_ ( self :Dict ): class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = True try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # If remote code is not set, the default is to use local __SCREAMING_SNAKE_CASE : List[str] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. __SCREAMING_SNAKE_CASE : str = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(_lowerCamelCase , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
674
0
"""simple docstring""" import os import unittest from transformers import LayoutLMTokenizer, LayoutLMTokenizerFast from transformers.models.layoutlm.tokenization_layoutlm import VOCAB_FILES_NAMES from transformers.testing_utils import require_tokenizers from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers class __lowercase( __UpperCAmelCase , unittest.TestCase ): '''simple docstring''' __a : Optional[int] = LayoutLMTokenizer __a : List[str] = LayoutLMTokenizerFast __a : List[Any] = True __a : List[Any] = True def snake_case_ ( self ): super().setUp() __lowerCamelCase : Dict = [ '''[UNK]''', '''[CLS]''', '''[SEP]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''', ] __lowerCamelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) def snake_case_ ( self , **__a ): return LayoutLMTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def snake_case_ ( self , __a ): __lowerCamelCase : Optional[Any] = '''UNwant\u00E9d,running''' __lowerCamelCase : Union[str, Any] = '''unwanted, running''' return input_text, output_text def snake_case_ ( self ): __lowerCamelCase : Optional[int] = self.tokenizer_class(self.vocab_file ) __lowerCamelCase : Dict = tokenizer.tokenize('UNwant\u00E9d,running' ) self.assertListEqual(_lowerCamelCase , ['un', '##want', '##ed', ',', 'runn', '##ing'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [7, 4, 5, 10, 8, 9] ) def snake_case_ ( self ): pass
594
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case ( __UpperCAmelCase ): pass class snake_case : def __init__( self :List[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Any = data __SCREAMING_SNAKE_CASE : Node | None = None def __iter__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : List[str] = self __SCREAMING_SNAKE_CASE : List[str] = [] while node: if node in visited: raise ContainsLoopError visited.append(_lowerCamelCase ) yield node.data __SCREAMING_SNAKE_CASE : List[str] = node.next_node @property def SCREAMING_SNAKE_CASE_ ( self :Any ): try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": _lowerCamelCase = Node(1) _lowerCamelCase = Node(2) _lowerCamelCase = Node(3) _lowerCamelCase = Node(4) print(root_node.has_loop) # False _lowerCamelCase = root_node.next_node print(root_node.has_loop) # True _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) print(root_node.has_loop) # False _lowerCamelCase = Node(1) print(root_node.has_loop) # False
674
0
import fcntl import os import socket import torch import torch.distributed as dist def _lowercase ( *SCREAMING_SNAKE_CASE_ : Optional[Any] ): """simple docstring""" with open(lowercase_ , """r""" ) as fh: fcntl.flock(lowercase_ , fcntl.LOCK_EX ) try: print(*lowercase_ ) finally: fcntl.flock(lowercase_ , fcntl.LOCK_UN ) __snake_case = int(os.environ["LOCAL_RANK"]) torch.cuda.set_device(local_rank) __snake_case = torch.device("cuda", local_rank) __snake_case = socket.gethostname() __snake_case = F'''[{hostname}-{local_rank}]''' try: # test distributed dist.init_process_group("nccl") dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM) dist.barrier() # test cuda is available and can allocate memory torch.cuda.is_available() torch.ones(1).cuda(local_rank) # global rank __snake_case = dist.get_rank() __snake_case = dist.get_world_size() printflock(F'''{gpu} is OK (global rank: {rank}/{world_size})''') dist.barrier() if rank == 0: printflock(F'''pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}''') except Exception: printflock(F'''{gpu} is broken''') raise
386
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''roc_bert''' def __init__( self :Union[str, Any] , _lowerCamelCase :Any=3_0_5_2_2 , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Optional[Any]=1_2 , _lowerCamelCase :List[str]=1_2 , _lowerCamelCase :str=3_0_7_2 , _lowerCamelCase :Tuple="gelu" , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :List[str]=0.1 , _lowerCamelCase :Optional[int]=5_1_2 , _lowerCamelCase :Dict=2 , _lowerCamelCase :Any=0.0_2 , _lowerCamelCase :Optional[int]=1e-12 , _lowerCamelCase :str=True , _lowerCamelCase :Any=0 , _lowerCamelCase :List[str]="absolute" , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Any=True , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Union[str, Any]=9_1_0 , _lowerCamelCase :List[Any]=5_1_2 , _lowerCamelCase :Optional[int]=2_4_8_5_8 , _lowerCamelCase :Union[str, Any]=True , **_lowerCamelCase :str , ): __SCREAMING_SNAKE_CASE : List[str] = vocab_size __SCREAMING_SNAKE_CASE : int = max_position_embeddings __SCREAMING_SNAKE_CASE : List[str] = hidden_size __SCREAMING_SNAKE_CASE : str = num_hidden_layers __SCREAMING_SNAKE_CASE : int = num_attention_heads __SCREAMING_SNAKE_CASE : Any = intermediate_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_act __SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range __SCREAMING_SNAKE_CASE : Union[str, Any] = type_vocab_size __SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps __SCREAMING_SNAKE_CASE : Optional[int] = use_cache __SCREAMING_SNAKE_CASE : str = enable_pronunciation __SCREAMING_SNAKE_CASE : List[str] = enable_shape __SCREAMING_SNAKE_CASE : Tuple = pronunciation_embed_dim __SCREAMING_SNAKE_CASE : Optional[Any] = pronunciation_vocab_size __SCREAMING_SNAKE_CASE : str = shape_embed_dim __SCREAMING_SNAKE_CASE : Union[str, Any] = shape_vocab_size __SCREAMING_SNAKE_CASE : Tuple = concat_input __SCREAMING_SNAKE_CASE : Union[str, Any] = position_embedding_type __SCREAMING_SNAKE_CASE : str = classifier_dropout super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase )
674
0
from ..utils import DummyObject, requires_backends class SCREAMING_SNAKE_CASE_ ( metaclass=__UpperCAmelCase ): """simple docstring""" __magic_name__ : Dict = ['torch', 'scipy'] def __init__( self : Optional[int] , *lowerCAmelCase : Tuple , **lowerCAmelCase : int ) -> Dict: """simple docstring""" requires_backends(self , ["""torch""", """scipy"""] ) @classmethod def lowerCamelCase__ ( cls : int , *lowerCAmelCase : Optional[int] , **lowerCAmelCase : int ) -> Tuple: """simple docstring""" requires_backends(cls , ["""torch""", """scipy"""] ) @classmethod def lowerCamelCase__ ( cls : Any , *lowerCAmelCase : Optional[Any] , **lowerCAmelCase : Optional[int] ) -> int: """simple docstring""" requires_backends(cls , ["""torch""", """scipy"""] )
279
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : Tuple , lowercase_ : Optional[Any]=True , lowercase_ : Any="pt" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''add_prefix_space''': True} if isinstance(lowercase_ , lowercase_ ) and not line.startswith(''' ''' ) else {} __SCREAMING_SNAKE_CASE : Optional[int] = padding_side return tokenizer( [line] , max_length=lowercase_ , padding='''max_length''' if pad_to_max_length else None , truncation=lowercase_ , return_tensors=lowercase_ , add_special_tokens=lowercase_ , **lowercase_ , ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : Tuple , lowercase_ : List[Any]=None , ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = input_ids.ne(lowercase_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class snake_case ( __UpperCAmelCase ): def __init__( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :Any="train" , _lowerCamelCase :str=None , _lowerCamelCase :Optional[Any]=None , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Tuple="" , ): super().__init__() __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ).joinpath(type_path + '''.source''' ) __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ).joinpath(type_path + '''.target''' ) __SCREAMING_SNAKE_CASE : Any = self.get_char_lens(self.src_file ) __SCREAMING_SNAKE_CASE : List[str] = max_source_length __SCREAMING_SNAKE_CASE : Dict = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' __SCREAMING_SNAKE_CASE : Dict = tokenizer __SCREAMING_SNAKE_CASE : Union[str, Any] = prefix if n_obs is not None: __SCREAMING_SNAKE_CASE : Any = self.src_lens[:n_obs] __SCREAMING_SNAKE_CASE : List[str] = src_lang __SCREAMING_SNAKE_CASE : str = tgt_lang def __len__( self :int ): return len(self.src_lens ) def __getitem__( self :Optional[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = index + 1 # linecache starts at 1 __SCREAMING_SNAKE_CASE : Any = self.prefix + linecache.getline(str(self.src_file ) , _lowerCamelCase ).rstrip('''\n''' ) __SCREAMING_SNAKE_CASE : Dict = linecache.getline(str(self.tgt_file ) , _lowerCamelCase ).rstrip('''\n''' ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , _lowerCamelCase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right __SCREAMING_SNAKE_CASE : Dict = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.generator if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_source_length , '''right''' ) __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_target_length , '''right''' ) __SCREAMING_SNAKE_CASE : Any = source_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Any = target_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Dict = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :Any ): return [len(_lowerCamelCase ) for x in Path(_lowerCamelCase ).open().readlines()] def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : int = torch.stack([x['''input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = torch.stack([x['''attention_mask'''] for x in batch] ) __SCREAMING_SNAKE_CASE : int = torch.stack([x['''decoder_input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : List[str] = trim_batch(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = trim_batch(_lowerCamelCase , _lowerCamelCase , attention_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch _lowerCamelCase = getLogger(__name__) def lowerCAmelCase_ ( lowercase_ : List[List] ): '''simple docstring''' return list(itertools.chain.from_iterable(lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = get_git_info() save_json(lowercase_ , os.path.join(lowercase_ , '''git_log.json''' ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Optional[int] , lowercase_ : str=4 , **lowercase_ : List[str] ): '''simple docstring''' with open(lowercase_ , '''w''' ) as f: json.dump(lowercase_ , lowercase_ , indent=lowercase_ , **lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Union[str, Any] ): '''simple docstring''' with open(lowercase_ ) as f: return json.load(lowercase_ ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = git.Repo(search_parent_directories=lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = { '''repo_id''': str(lowercase_ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : Iterable ): '''simple docstring''' return list(map(lowercase_ , lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Any ): '''simple docstring''' with open(lowercase_ , '''wb''' ) as f: return pickle.dump(lowercase_ , lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' def remove_articles(lowercase_ : Dict ): return re.sub(r'''\b(a|an|the)\b''' , ''' ''' , lowercase_ ) def white_space_fix(lowercase_ : Optional[int] ): return " ".join(text.split() ) def remove_punc(lowercase_ : Any ): __SCREAMING_SNAKE_CASE : Optional[int] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowercase_ : int ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowercase_ ) ) ) ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Tuple = Counter(lowercase_ ) & Counter(lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = sum(common.values() ) if num_same == 0: return 0 __SCREAMING_SNAKE_CASE : Any = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[int] = (2 * precision * recall) / (precision + recall) return fa def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Union[str, Any] ): '''simple docstring''' return normalize_answer(lowercase_ ) == normalize_answer(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' assert len(lowercase_ ) == len(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for hypo, pred in zip(lowercase_ , lowercase_ ): em += exact_match_score(lowercase_ , lowercase_ ) if len(lowercase_ ) > 0: em /= len(lowercase_ ) return {"em": em} def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' return model_prefix.startswith('''rag''' ) def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead __SCREAMING_SNAKE_CASE : Any = '''dropout_rate''' for p in extra_params: if getattr(lowercase_ , lowercase_ , lowercase_ ): if not hasattr(lowercase_ , lowercase_ ) and not hasattr(lowercase_ , equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(lowercase_ ) ) delattr(lowercase_ , lowercase_ ) continue __SCREAMING_SNAKE_CASE : Optional[int] = p if hasattr(lowercase_ , lowercase_ ) else equivalent_param[p] setattr(lowercase_ , lowercase_ , getattr(lowercase_ , lowercase_ ) ) delattr(lowercase_ , lowercase_ ) return hparams, config
674
0
from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class lowerCamelCase ( __UpperCAmelCase , __UpperCAmelCase ): @register_to_config def __init__( self :List[str] , lowercase :int = 7_6_8 , ) -> Dict: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE = nn.Parameter(torch.zeros(1 , _lowerCamelCase ) ) SCREAMING_SNAKE_CASE = nn.Parameter(torch.ones(1 , _lowerCamelCase ) ) def snake_case__ ( self :Any , lowercase :Optional[Union[str, torch.device]] = None , lowercase :Optional[torch.dtype] = None , ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE = nn.Parameter(self.mean.to(_lowerCamelCase ).to(_lowerCamelCase ) ) SCREAMING_SNAKE_CASE = nn.Parameter(self.std.to(_lowerCamelCase ).to(_lowerCamelCase ) ) return self def snake_case__ ( self :int , lowercase :Tuple ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE = (embeds - self.mean) * 1.0 / self.std return embeds def snake_case__ ( self :Optional[Any] , lowercase :Optional[int] ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE = (embeds * self.std) + self.mean return embeds
201
"""simple docstring""" from collections.abc import Callable import numpy as np def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : float , lowercase_ : float , lowercase_ : float , lowercase_ : float ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = int(np.ceil((x_end - xa) / step_size ) ) __SCREAMING_SNAKE_CASE : Dict = np.zeros((n + 1,) ) __SCREAMING_SNAKE_CASE : List[Any] = ya __SCREAMING_SNAKE_CASE : Dict = xa for k in range(lowercase_ ): __SCREAMING_SNAKE_CASE : str = y[k] + step_size * ode_func(lowercase_ , y[k] ) __SCREAMING_SNAKE_CASE : int = y[k] + ( (step_size / 2) * (ode_func(lowercase_ , y[k] ) + ode_func(x + step_size , lowercase_ )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
674
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 from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices a : int = logging.get_logger(__name__) a : int = { """microsoft/resnet-50""": """https://huggingface.co/microsoft/resnet-50/blob/main/config.json""", } class __UpperCAmelCase( __UpperCAmelCase , __UpperCAmelCase ): """simple docstring""" __lowerCamelCase = "resnet" __lowerCamelCase = ["basic", "bottleneck"] def __init__( self , snake_case__=3 , snake_case__=64 , snake_case__=[256, 512, 1024, 2048] , snake_case__=[3, 4, 6, 3] , snake_case__="bottleneck" , snake_case__="relu" , snake_case__=False , snake_case__=None , snake_case__=None , **snake_case__ , ): '''simple docstring''' super().__init__(**_lowerCamelCase ) if layer_type not in self.layer_types: raise ValueError(F'''layer_type={layer_type} is not one of {','.join(self.layer_types )}''' ) lowercase__ : List[Any]= num_channels lowercase__ : List[str]= embedding_size lowercase__ : Union[str, Any]= hidden_sizes lowercase__ : List[str]= depths lowercase__ : Optional[int]= layer_type lowercase__ : Dict= hidden_act lowercase__ : int= downsample_in_first_stage lowercase__ : int= ['''stem'''] + [F'''stage{idx}''' for idx in range(1 , len(_lowerCamelCase ) + 1 )] lowercase__ : List[str]= get_aligned_output_features_output_indices( out_features=_lowerCamelCase , out_indices=_lowerCamelCase , stage_names=self.stage_names ) class __UpperCAmelCase( __UpperCAmelCase ): """simple docstring""" __lowerCamelCase = version.parse("1.11" ) @property def UpperCAmelCase_ ( self ): '''simple docstring''' return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def UpperCAmelCase_ ( self ): '''simple docstring''' return 1e-3
218
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable _lowerCamelCase = { '''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''], '''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXJapaneseForCausalLM''', '''GPTNeoXJapaneseLayer''', '''GPTNeoXJapaneseModel''', '''GPTNeoXJapanesePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
674
0
import random import timeit from functools import wraps from typing import Callable, Optional from ..configuration_utils import PretrainedConfig from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING from ..utils import is_pyanvml_available, is_tf_available, logging from .benchmark_utils import ( Benchmark, Memory, MemorySummary, measure_peak_memory_cpu, start_memory_tracing, stop_memory_tracing, ) if is_tf_available(): import tensorflow as tf from tensorflow.python.framework.errors_impl import ResourceExhaustedError from .benchmark_args_tf import TensorFlowBenchmarkArguments if is_pyanvml_available(): import pyanvml.pyanvml as nvml lowerCamelCase :str = logging.get_logger(__name__) def __snake_case ( _UpperCamelCase , _UpperCamelCase ) -> List[str]: def run_func(_UpperCamelCase ): @wraps(lowercase_ ) def run_in_eager_mode(*_UpperCamelCase , **_UpperCamelCase ): return func(*lowercase_ , **lowercase_ ) @wraps(lowercase_ ) @tf.function(experimental_compile=lowercase_ ) def run_in_graph_mode(*_UpperCamelCase , **_UpperCamelCase ): return func(*lowercase_ , **lowercase_ ) if do_eager_mode is True: if use_xla is not False: raise ValueError( '''Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`.''' ) return run_in_eager_mode else: return run_in_graph_mode return run_func def __snake_case ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) -> Optional[Any]: _a = random.Random() _a = [rng.randint(0 , vocab_size - 1 ) for i in range(batch_size * sequence_length )] return tf.constant(lowercase_ , shape=(batch_size, sequence_length) , dtype=tf.intaa ) class UpperCAmelCase ( __UpperCAmelCase ): a: int = 42 a: Union[str, Any] = 42 a: Optional[int] = "TensorFlow" @property def _A ( self: Optional[Any] ): return tf.__version__ def _A ( self: Tuple , __UpperCamelCase: str , __UpperCamelCase: int , __UpperCamelCase: int ): # initialize GPU on separate process _a = self.args.strategy if strategy is None: raise ValueError('''A device strategy has to be initialized before using TensorFlow.''' ) _a = self._prepare_inference_func(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) return self._measure_speed(_inference ) def _A ( self: Dict , __UpperCamelCase: str , __UpperCamelCase: int , __UpperCamelCase: int ): _a = self.args.strategy if strategy is None: raise ValueError('''A device strategy has to be initialized before using TensorFlow.''' ) _a = self._prepare_train_func(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) return self._measure_speed(_train ) def _A ( self: Tuple , __UpperCamelCase: str , __UpperCamelCase: int , __UpperCamelCase: int ): # initialize GPU on separate process if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , _lowerCamelCase ) _a = self.args.strategy if strategy is None: raise ValueError('''A device strategy has to be initialized before using TensorFlow.''' ) _a = self._prepare_inference_func(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) return self._measure_memory(_inference ) def _A ( self: Union[str, Any] , __UpperCamelCase: str , __UpperCamelCase: int , __UpperCamelCase: int ): if self.args.is_gpu: tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx] , _lowerCamelCase ) _a = self.args.strategy if strategy is None: raise ValueError('''A device strategy has to be initialized before using TensorFlow.''' ) _a = self._prepare_train_func(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) return self._measure_memory(_train ) def _A ( self: Optional[Any] , __UpperCamelCase: str , __UpperCamelCase: int , __UpperCamelCase: int ): _a = self.config_dict[model_name] if self.args.fpaa: raise NotImplementedError('''Mixed precision is currently not supported.''' ) _a = ( hasattr(_lowerCamelCase , '''architectures''' ) and isinstance(config.architectures , _lowerCamelCase ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: _a = '''TF''' + config.architectures[0] # prepend 'TF' for tensorflow model _a = __import__('''transformers''' , fromlist=[model_class] ) _a = getattr(_lowerCamelCase , _lowerCamelCase ) _a = model_cls(_lowerCamelCase ) except ImportError: raise ImportError( f"{model_class} does not exist. If you just want to test the pretrained model, you might want to" ''' set `--only_pretrain_model` or `args.only_pretrain_model=True`.''' ) else: _a = TF_MODEL_MAPPING[config.__class__](_lowerCamelCase ) # encoder-decoder has vocab size saved differently _a = config.vocab_size if hasattr(_lowerCamelCase , '''vocab_size''' ) else config.encoder.vocab_size _a = random_input_ids(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_decoder_forward(): return model(_lowerCamelCase , decoder_input_ids=_lowerCamelCase , training=_lowerCamelCase ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_forward(): return model(_lowerCamelCase , training=_lowerCamelCase ) _a = encoder_decoder_forward if config.is_encoder_decoder else encoder_forward return _inference def _A ( self: List[Any] , __UpperCamelCase: str , __UpperCamelCase: int , __UpperCamelCase: int ): _a = self.config_dict[model_name] if self.args.eager_mode is not False: raise ValueError('''Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`.''' ) if self.args.fpaa: raise NotImplementedError('''Mixed precision is currently not supported.''' ) _a = ( hasattr(_lowerCamelCase , '''architectures''' ) and isinstance(config.architectures , _lowerCamelCase ) and len(config.architectures ) > 0 ) if not self.args.only_pretrain_model and has_model_class_in_config: try: _a = '''TF''' + config.architectures[0] # prepend 'TF' for tensorflow model _a = __import__('''transformers''' , fromlist=[model_class] ) _a = getattr(_lowerCamelCase , _lowerCamelCase ) _a = model_cls(_lowerCamelCase ) except ImportError: raise ImportError( f"{model_class} does not exist. If you just want to test the pretrained model, you might want to" ''' set `--only_pretrain_model` or `args.only_pretrain_model=True`.''' ) else: _a = TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](_lowerCamelCase ) # encoder-decoder has vocab size saved differently _a = config.vocab_size if hasattr(_lowerCamelCase , '''vocab_size''' ) else config.encoder.vocab_size _a = random_input_ids(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_decoder_train(): _a = model(_lowerCamelCase , decoder_input_ids=_lowerCamelCase , labels=_lowerCamelCase , training=_lowerCamelCase )[0] _a = tf.gradients(_lowerCamelCase , model.trainable_variables ) return gradients @run_with_tf_optimizations(self.args.eager_mode , self.args.use_xla ) def encoder_train(): _a = model(_lowerCamelCase , labels=_lowerCamelCase , training=_lowerCamelCase )[0] _a = tf.gradients(_lowerCamelCase , model.trainable_variables ) return gradients _a = encoder_decoder_train if config.is_encoder_decoder else encoder_train return _train def _A ( self: Dict , __UpperCamelCase: Dict ): with self.args.strategy.scope(): try: if self.args.is_tpu or self.args.use_xla: # run additional 10 times to stabilize compilation for tpu logger.info('''Do inference on TPU. Running model 5 times to stabilize compilation''' ) timeit.repeat(_lowerCamelCase , repeat=1 , number=5 ) # as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average _a = timeit.repeat( _lowerCamelCase , repeat=self.args.repeat , number=10 , ) return min(_lowerCamelCase ) / 10.0 except ResourceExhaustedError as e: self.print_fn(f"Doesn\'t fit on GPU. {e}" ) def _A ( self: Any , __UpperCamelCase: Callable[[], None] ): logger.info( '''Note that TensorFlow allocates more memory than ''' '''it might need to speed up computation. ''' '''The memory reported here corresponds to the memory ''' '''reported by `nvidia-smi`, which can vary depending ''' '''on total available memory on the GPU that is used.''' ) with self.args.strategy.scope(): try: if self.args.trace_memory_line_by_line: if not self.args.eager_mode: raise ValueError( '''`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory''' ''' consumption line by line.''' ) _a = start_memory_tracing('''transformers''' ) if self.args.is_tpu: # tpu raise NotImplementedError( '''Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking''' ''' with `args.memory=False`''' ) elif self.args.is_gpu: # gpu if not is_pyanvml_available(): logger.warning( '''py3nvml not installed, we won\'t log GPU memory usage. ''' '''Install py3nvml (pip install py3nvml) to log information about GPU.''' ) _a = '''N/A''' else: logger.info( '''Measuring total GPU usage on GPU device. Make sure to not have additional processes''' ''' running on the same GPU.''' ) # init nvml nvml.nvmlInit() func() _a = nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx ) _a = nvml.nvmlDeviceGetMemoryInfo(_lowerCamelCase ) _a = meminfo.used _a = Memory(_lowerCamelCase ) # shutdown nvml nvml.nvmlShutdown() else: # cpu if self.args.trace_memory_line_by_line: logger.info( '''When enabling line by line tracing, the max peak memory for CPU is inaccurate in''' ''' TensorFlow.''' ) _a = None else: _a = measure_peak_memory_cpu(_lowerCamelCase ) _a = Memory(_lowerCamelCase ) if isinstance(_lowerCamelCase , _lowerCamelCase ) else memory_bytes if self.args.trace_memory_line_by_line: _a = stop_memory_tracing(_lowerCamelCase ) if memory is None: _a = summary.total else: _a = None return memory, summary except ResourceExhaustedError as e: self.print_fn(f"Doesn\'t fit on GPU. {e}" ) return "N/A", None
487
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case : def __init__( self :Optional[Any] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : int = num_of_nodes __SCREAMING_SNAKE_CASE : list[list[int]] = [] __SCREAMING_SNAKE_CASE : dict[int, int] = {} def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :int ): self.m_edges.append([u_node, v_node, weight] ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :int ): if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :int ): if self.m_component[u_node] != u_node: for k in self.m_component: __SCREAMING_SNAKE_CASE : Optional[Any] = self.find_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :list[int] , _lowerCamelCase :int , _lowerCamelCase :int ): if component_size[u_node] <= component_size[v_node]: __SCREAMING_SNAKE_CASE : List[Any] = v_node component_size[v_node] += component_size[u_node] self.set_component(_lowerCamelCase ) elif component_size[u_node] >= component_size[v_node]: __SCREAMING_SNAKE_CASE : Dict = self.find_component(_lowerCamelCase ) component_size[u_node] += component_size[v_node] self.set_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = [] __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : list[Any] = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) __SCREAMING_SNAKE_CASE : str = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = edge __SCREAMING_SNAKE_CASE : Optional[Any] = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): __SCREAMING_SNAKE_CASE : Optional[Any] = [u, v, w] for edge in minimum_weight_edge: if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = edge __SCREAMING_SNAKE_CASE : Tuple = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: mst_weight += w self.union(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) print(f'''Added edge [{u} - {v}]\nAdded weight: {w}\n''' ) num_of_components -= 1 __SCREAMING_SNAKE_CASE : Optional[Any] = [-1] * self.m_num_of_nodes print(f'''The total weight of the minimal spanning tree is: {mst_weight}''' ) def lowerCAmelCase_ ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
674
0
"""simple docstring""" import unittest import numpy as np from transformers.testing_utils import require_pytesseract, require_torch from transformers.utils import is_pytesseract_available, is_torch_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_pytesseract_available(): from PIL import Image from transformers import LayoutLMvaImageProcessor class UpperCAmelCase_ ( unittest.TestCase ): def __init__( self , UpperCamelCase_ , UpperCamelCase_=7 , UpperCamelCase_=3 , UpperCamelCase_=18 , UpperCamelCase_=30 , UpperCamelCase_=4_00 , UpperCamelCase_=True , UpperCamelCase_=None , UpperCamelCase_=True , ) -> List[str]: __lowercase : Any = size if size is not None else {'''height''': 18, '''width''': 18} __lowercase : List[Any] = parent __lowercase : List[Any] = batch_size __lowercase : int = num_channels __lowercase : Tuple = image_size __lowercase : Optional[int] = min_resolution __lowercase : str = max_resolution __lowercase : List[Any] = do_resize __lowercase : List[Any] = size __lowercase : List[Any] = apply_ocr def _lowerCamelCase ( self ) -> List[Any]: return {"do_resize": self.do_resize, "size": self.size, "apply_ocr": self.apply_ocr} @require_torch @require_pytesseract class UpperCAmelCase_ ( __UpperCAmelCase , unittest.TestCase ): UpperCamelCase =LayoutLMvaImageProcessor if is_pytesseract_available() else None def _lowerCamelCase ( self ) -> Any: __lowercase : Tuple = LayoutLMvaImageProcessingTester(self ) @property def _lowerCamelCase ( self ) -> Dict: return self.image_processor_tester.prepare_image_processor_dict() def _lowerCamelCase ( self ) -> List[Any]: __lowercase : Tuple = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''apply_ocr''' ) ) def _lowerCamelCase ( self ) -> List[Any]: __lowercase : Optional[int] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''height''': 18, '''width''': 18} ) __lowercase : Any = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {'''height''': 42, '''width''': 42} ) def _lowerCamelCase ( self ) -> str: pass def _lowerCamelCase ( self ) -> List[Any]: # Initialize image_processing __lowercase : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __lowercase : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __lowercase : int = image_processing(image_inputs[0] , return_tensors='''pt''' ) self.assertEqual( encoding.pixel_values.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) self.assertIsInstance(encoding.words , _lowerCamelCase ) self.assertIsInstance(encoding.boxes , _lowerCamelCase ) # Test batched __lowercase : int = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def _lowerCamelCase ( self ) -> Any: # Initialize image_processing __lowercase : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __lowercase : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __lowercase : Union[str, Any] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) # Test batched __lowercase : List[str] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def _lowerCamelCase ( self ) -> List[Any]: # Initialize image_processing __lowercase : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __lowercase : Optional[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __lowercase : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) # Test batched __lowercase : Dict = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size['''height'''], self.image_processor_tester.size['''width'''], ) , ) def _lowerCamelCase ( self ) -> Dict: # with apply_OCR = True __lowercase : Any = LayoutLMvaImageProcessor() from datasets import load_dataset __lowercase : Union[str, Any] = load_dataset('''hf-internal-testing/fixtures_docvqa''' , split='''test''' ) __lowercase : Optional[int] = Image.open(ds[0]['''file'''] ).convert('''RGB''' ) __lowercase : Any = image_processing(_lowerCamelCase , return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_24, 2_24) ) self.assertEqual(len(encoding.words ) , len(encoding.boxes ) ) # fmt: off # the words and boxes were obtained with Tesseract 4.1.1 __lowercase : Union[str, Any] = [['''11:14''', '''to''', '''11:39''', '''a.m''', '''11:39''', '''to''', '''11:44''', '''a.m.''', '''11:44''', '''a.m.''', '''to''', '''12:25''', '''p.m.''', '''12:25''', '''to''', '''12:58''', '''p.m.''', '''12:58''', '''to''', '''4:00''', '''p.m.''', '''2:00''', '''to''', '''5:00''', '''p.m.''', '''Coffee''', '''Break''', '''Coffee''', '''will''', '''be''', '''served''', '''for''', '''men''', '''and''', '''women''', '''in''', '''the''', '''lobby''', '''adjacent''', '''to''', '''exhibit''', '''area.''', '''Please''', '''move''', '''into''', '''exhibit''', '''area.''', '''(Exhibits''', '''Open)''', '''TRRF''', '''GENERAL''', '''SESSION''', '''(PART''', '''|)''', '''Presiding:''', '''Lee''', '''A.''', '''Waller''', '''TRRF''', '''Vice''', '''President''', '''“Introductory''', '''Remarks”''', '''Lee''', '''A.''', '''Waller,''', '''TRRF''', '''Vice''', '''Presi-''', '''dent''', '''Individual''', '''Interviews''', '''with''', '''TRRF''', '''Public''', '''Board''', '''Members''', '''and''', '''Sci-''', '''entific''', '''Advisory''', '''Council''', '''Mem-''', '''bers''', '''Conducted''', '''by''', '''TRRF''', '''Treasurer''', '''Philip''', '''G.''', '''Kuehn''', '''to''', '''get''', '''answers''', '''which''', '''the''', '''public''', '''refrigerated''', '''warehousing''', '''industry''', '''is''', '''looking''', '''for.''', '''Plus''', '''questions''', '''from''', '''the''', '''floor.''', '''Dr.''', '''Emil''', '''M.''', '''Mrak,''', '''University''', '''of''', '''Cal-''', '''ifornia,''', '''Chairman,''', '''TRRF''', '''Board;''', '''Sam''', '''R.''', '''Cecil,''', '''University''', '''of''', '''Georgia''', '''College''', '''of''', '''Agriculture;''', '''Dr.''', '''Stanley''', '''Charm,''', '''Tufts''', '''University''', '''School''', '''of''', '''Medicine;''', '''Dr.''', '''Robert''', '''H.''', '''Cotton,''', '''ITT''', '''Continental''', '''Baking''', '''Company;''', '''Dr.''', '''Owen''', '''Fennema,''', '''University''', '''of''', '''Wis-''', '''consin;''', '''Dr.''', '''Robert''', '''E.''', '''Hardenburg,''', '''USDA.''', '''Questions''', '''and''', '''Answers''', '''Exhibits''', '''Open''', '''Capt.''', '''Jack''', '''Stoney''', '''Room''', '''TRRF''', '''Scientific''', '''Advisory''', '''Council''', '''Meeting''', '''Ballroom''', '''Foyer''']] # noqa: E231 __lowercase : Any = [[[1_41, 57, 2_14, 69], [2_28, 58, 2_52, 69], [1_41, 75, 2_16, 88], [2_30, 79, 2_80, 88], [1_42, 2_60, 2_18, 2_73], [2_30, 2_61, 2_55, 2_73], [1_43, 2_79, 2_18, 2_90], [2_31, 2_82, 2_90, 2_91], [1_43, 3_42, 2_18, 3_54], [2_31, 3_45, 2_89, 3_55], [2_02, 3_62, 2_27, 3_73], [1_43, 3_79, 2_20, 3_92], [2_31, 3_82, 2_91, 3_94], [1_44, 7_14, 2_20, 7_26], [2_31, 7_15, 2_56, 7_26], [1_44, 7_32, 2_20, 7_45], [2_32, 7_36, 2_91, 7_47], [1_44, 7_69, 2_18, 7_82], [2_31, 7_70, 2_56, 7_82], [1_41, 7_88, 2_02, 8_01], [2_15, 7_91, 2_74, 8_04], [1_43, 8_26, 2_04, 8_38], [2_15, 8_26, 2_40, 8_38], [1_42, 8_44, 2_02, 8_57], [2_15, 8_47, 2_74, 8_59], [3_34, 57, 4_27, 69], [4_40, 57, 5_22, 69], [3_69, 75, 4_61, 88], [4_69, 75, 5_16, 88], [5_28, 76, 5_62, 88], [5_70, 76, 6_67, 88], [6_75, 75, 7_11, 87], [7_21, 79, 7_78, 88], [7_89, 75, 8_40, 88], [3_69, 97, 4_70, 1_07], [4_84, 94, 5_07, 1_06], [5_18, 94, 5_62, 1_07], [5_76, 94, 6_55, 1_10], [6_68, 94, 7_92, 1_09], [8_04, 95, 8_29, 1_07], [3_69, 1_13, 4_65, 1_25], [4_77, 1_16, 5_47, 1_25], [5_62, 1_13, 6_58, 1_25], [6_71, 1_16, 7_48, 1_25], [7_61, 1_13, 8_11, 1_25], [3_69, 1_31, 4_65, 1_43], [4_77, 1_33, 5_48, 1_43], [5_63, 1_30, 6_98, 1_45], [7_10, 1_30, 8_02, 1_46], [3_36, 1_71, 4_12, 1_83], [4_23, 1_71, 5_72, 1_83], [5_82, 1_70, 7_16, 1_84], [7_28, 1_71, 8_17, 1_87], [8_29, 1_71, 8_44, 1_86], [3_38, 1_97, 4_82, 2_12], [5_07, 1_96, 5_57, 2_09], [5_69, 1_96, 5_95, 2_08], [6_10, 1_96, 7_02, 2_09], [5_05, 2_14, 5_83, 2_26], [5_95, 2_14, 6_56, 2_27], [6_70, 2_15, 8_07, 2_27], [3_35, 2_59, 5_43, 2_74], [5_56, 2_59, 7_08, 2_72], [3_72, 2_79, 4_22, 2_91], [4_35, 2_79, 4_60, 2_91], [4_74, 2_79, 5_74, 2_92], [5_87, 2_78, 6_64, 2_91], [6_76, 2_78, 7_38, 2_91], [7_51, 2_79, 8_34, 2_91], [3_72, 2_98, 4_34, 3_10], [3_35, 3_41, 4_83, 3_54], [4_97, 3_41, 6_55, 3_54], [6_67, 3_41, 7_28, 3_54], [7_40, 3_41, 8_25, 3_54], [3_35, 3_60, 4_30, 3_72], [4_42, 3_60, 5_34, 3_72], [5_45, 3_59, 6_87, 3_72], [6_97, 3_60, 7_54, 3_72], [7_65, 3_60, 8_23, 3_73], [3_34, 3_78, 4_28, 3_91], [4_40, 3_78, 5_77, 3_94], [5_90, 3_78, 7_05, 3_91], [7_20, 3_78, 8_01, 3_91], [3_34, 3_97, 4_00, 4_09], [3_70, 4_16, 5_29, 4_29], [5_44, 4_16, 5_76, 4_32], [5_87, 4_16, 6_65, 4_28], [6_77, 4_16, 8_14, 4_29], [3_72, 4_35, 4_52, 4_50], [4_65, 4_34, 4_95, 4_47], [5_11, 4_34, 6_00, 4_47], [6_11, 4_36, 6_37, 4_47], [6_49, 4_36, 6_94, 4_51], [7_05, 4_38, 8_24, 4_47], [3_69, 4_53, 4_52, 4_66], [4_64, 4_54, 5_09, 4_66], [5_22, 4_53, 6_11, 4_69], [6_25, 4_53, 7_92, 4_69], [3_70, 4_72, 5_56, 4_88], [5_70, 4_72, 6_84, 4_87], [6_97, 4_72, 7_18, 4_85], [7_32, 4_72, 8_35, 4_88], [3_69, 4_90, 4_11, 5_03], [4_25, 4_90, 4_84, 5_03], [4_96, 4_90, 6_35, 5_06], [6_45, 4_90, 7_07, 5_03], [7_18, 4_91, 7_61, 5_03], [7_71, 4_90, 8_40, 5_03], [3_36, 5_10, 3_74, 5_21], [3_88, 5_10, 4_47, 5_22], [4_60, 5_10, 4_89, 5_21], [5_03, 5_10, 5_80, 5_22], [5_92, 5_09, 7_36, 5_25], [7_45, 5_09, 7_70, 5_22], [7_81, 5_09, 8_40, 5_22], [3_38, 5_28, 4_34, 5_41], [4_48, 5_28, 5_96, 5_41], [6_09, 5_27, 6_87, 5_40], [7_00, 5_28, 7_92, 5_41], [3_36, 5_46, 3_97, 5_59], [4_07, 5_46, 4_31, 5_59], [4_43, 5_46, 5_25, 5_60], [5_37, 5_46, 6_80, 5_62], [6_88, 5_46, 7_14, 5_59], [7_22, 5_46, 8_37, 5_62], [3_36, 5_65, 4_49, 5_81], [4_61, 5_65, 4_85, 5_77], [4_97, 5_65, 6_65, 5_81], [6_81, 5_65, 7_18, 5_77], [7_32, 5_65, 8_37, 5_80], [3_37, 5_84, 4_38, 5_97], [4_52, 5_83, 5_21, 5_96], [5_35, 5_84, 6_77, 5_99], [6_90, 5_83, 7_87, 5_96], [8_01, 5_83, 8_25, 5_96], [3_38, 6_02, 4_78, 6_15], [4_92, 6_02, 5_30, 6_14], [5_43, 6_02, 6_38, 6_15], [6_50, 6_02, 6_76, 6_14], [6_88, 6_02, 7_88, 6_15], [8_02, 6_02, 8_43, 6_14], [3_37, 6_21, 5_02, 6_33], [5_16, 6_21, 6_15, 6_37], [6_29, 6_21, 7_74, 6_36], [7_89, 6_21, 8_27, 6_33], [3_37, 6_39, 4_18, 6_52], [4_32, 6_40, 5_71, 6_53], [5_87, 6_39, 7_31, 6_55], [7_43, 6_39, 7_69, 6_52], [7_80, 6_39, 8_41, 6_52], [3_38, 6_58, 4_40, 6_73], [4_55, 6_58, 4_91, 6_70], [5_08, 6_58, 6_02, 6_71], [6_16, 6_58, 6_38, 6_70], [6_54, 6_58, 8_35, 6_74], [3_37, 6_77, 4_29, 6_89], [3_37, 7_14, 4_82, 7_26], [4_95, 7_14, 5_48, 7_26], [5_61, 7_14, 6_83, 7_26], [3_38, 7_70, 4_61, 7_82], [4_74, 7_69, 5_54, 7_85], [4_89, 7_88, 5_62, 8_03], [5_76, 7_88, 6_43, 8_01], [6_56, 7_87, 7_51, 8_04], [7_64, 7_88, 8_44, 8_01], [3_34, 8_25, 4_21, 8_38], [4_30, 8_24, 5_74, 8_38], [5_84, 8_24, 7_23, 8_41], [3_35, 8_44, 4_50, 8_57], [4_64, 8_43, 5_83, 8_60], [6_28, 8_62, 7_55, 8_75], [7_69, 8_61, 8_48, 8_78]]] # noqa: E231 # fmt: on self.assertListEqual(encoding.words , _lowerCamelCase ) self.assertListEqual(encoding.boxes , _lowerCamelCase ) # with apply_OCR = False __lowercase : Union[str, Any] = LayoutLMvaImageProcessor(apply_ocr=_lowerCamelCase ) __lowercase : Optional[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ) self.assertEqual(encoding.pixel_values.shape , (1, 3, 2_24, 2_24) )
76
"""simple docstring""" import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : Any , lowercase_ : int=None ): '''simple docstring''' assert torch_layer.weight.shape == weight.shape, F'''{torch_layer} layer.weight does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(lowercase_ ) if bias is not None: assert torch_layer.bias.shape == bias.shape, F'''{torch_layer} layer.bias does not match''' __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Tuple , lowercase_ : int , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) __SCREAMING_SNAKE_CASE : Tuple = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = weights[0][0][0] __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(layer_norm_a[0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # lsh weights + output __SCREAMING_SNAKE_CASE : Tuple = weights[0][1] if len(lowercase_ ) < 4: set_layer_weights_in_torch_lsh(lowercase_ , torch_block.attention , lowercase_ ) else: set_layer_weights_in_torch_local(lowercase_ , torch_block.attention , lowercase_ ) # intermediate weighs __SCREAMING_SNAKE_CASE : Any = weights[2][0][1][2] # Chunked Feed Forward if len(lowercase_ ) == 4: __SCREAMING_SNAKE_CASE : List[str] = intermediate_weights[2] # layernorm 2 __SCREAMING_SNAKE_CASE : List[str] = np.asarray(intermediate_weights[0][0] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # intermediate dense __SCREAMING_SNAKE_CASE : int = np.asarray(intermediate_weights[1][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) # intermediate out __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[4][0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = torch_model.reformer # word embeds __SCREAMING_SNAKE_CASE : int = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(lowercase_ ) , ) if isinstance(weights[3] , lowercase_ ): __SCREAMING_SNAKE_CASE : int = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): __SCREAMING_SNAKE_CASE : Dict = np.asarray(weights[3][emb_idx][0] ) assert ( position_embeddings.weights[emb_idx].shape == emb_weights.shape ), F'''{position_embeddings[emb_idx]} emb does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.tensor(lowercase_ ) ) __SCREAMING_SNAKE_CASE : List[Any] = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( lowercase_ ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): __SCREAMING_SNAKE_CASE : Union[str, Any] = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(lowercase_ , lowercase_ , lowercase_ ) # output layer norm __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[7][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # output embeddings __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[9][0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : Any , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = ReformerConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : List[str] = ReformerModelWithLMHead(lowercase_ ) with open(lowercase_ , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : int = pickle.load(lowercase_ )['''weights'''] set_model_weights_in_torch(lowercase_ , lowercase_ , config.hidden_size ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--trax_model_pkl_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained Reformer model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
674
0
import numpy as np import torch import tqdm from ...models.unet_ad import UNetaDModel from ...pipelines import DiffusionPipeline from ...utils import randn_tensor from ...utils.dummy_pt_objects import DDPMScheduler class _lowerCamelCase ( __UpperCAmelCase ): def __init__( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , ) -> Optional[Any]: super().__init__() SCREAMING_SNAKE_CASE__: Tuple= value_function SCREAMING_SNAKE_CASE__: List[Any]= unet SCREAMING_SNAKE_CASE__: List[str]= scheduler SCREAMING_SNAKE_CASE__: Optional[Any]= env SCREAMING_SNAKE_CASE__: int= env.get_dataset() SCREAMING_SNAKE_CASE__: Optional[int]= {} for key in self.data.keys(): try: SCREAMING_SNAKE_CASE__: Tuple= self.data[key].mean() except: # noqa: E722 pass SCREAMING_SNAKE_CASE__: str= {} for key in self.data.keys(): try: SCREAMING_SNAKE_CASE__: str= self.data[key].std() except: # noqa: E722 pass SCREAMING_SNAKE_CASE__: Tuple= env.observation_space.shape[0] SCREAMING_SNAKE_CASE__: List[Any]= env.action_space.shape[0] def UpperCamelCase_ ( self , lowerCAmelCase , lowerCAmelCase ) -> List[str]: return (x_in - self.means[key]) / self.stds[key] def UpperCamelCase_ ( self , lowerCAmelCase , lowerCAmelCase ) -> Union[str, Any]: return x_in * self.stds[key] + self.means[key] def UpperCamelCase_ ( self , lowerCAmelCase ) -> List[str]: if type(_lowerCamelCase ) is dict: return {k: self.to_torch(_lowerCamelCase ) for k, v in x_in.items()} elif torch.is_tensor(_lowerCamelCase ): return x_in.to(self.unet.device ) return torch.tensor(_lowerCamelCase , device=self.unet.device ) def UpperCamelCase_ ( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) -> Union[str, Any]: for key, val in cond.items(): SCREAMING_SNAKE_CASE__: int= val.clone() return x_in def UpperCamelCase_ ( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase ) -> Any: SCREAMING_SNAKE_CASE__: Any= x.shape[0] SCREAMING_SNAKE_CASE__: int= None for i in tqdm.tqdm(self.scheduler.timesteps ): # create batch of timesteps to pass into model SCREAMING_SNAKE_CASE__: Optional[int]= torch.full((batch_size,) , _lowerCamelCase , device=self.unet.device , dtype=torch.long ) for _ in range(_lowerCamelCase ): with torch.enable_grad(): x.requires_grad_() # permute to match dimension for pre-trained models SCREAMING_SNAKE_CASE__: str= self.value_function(x.permute(0 , 2 , 1 ) , _lowerCamelCase ).sample SCREAMING_SNAKE_CASE__: Dict= torch.autograd.grad([y.sum()] , [x] )[0] SCREAMING_SNAKE_CASE__: Optional[int]= self.scheduler._get_variance(_lowerCamelCase ) SCREAMING_SNAKE_CASE__: Optional[Any]= torch.exp(0.5 * posterior_variance ) SCREAMING_SNAKE_CASE__: Union[str, Any]= model_std * grad SCREAMING_SNAKE_CASE__: int= 0 SCREAMING_SNAKE_CASE__: Union[str, Any]= x.detach() SCREAMING_SNAKE_CASE__: Optional[Any]= x + scale * grad SCREAMING_SNAKE_CASE__: Any= self.reset_xa(_lowerCamelCase , _lowerCamelCase , self.action_dim ) SCREAMING_SNAKE_CASE__: Dict= self.unet(x.permute(0 , 2 , 1 ) , _lowerCamelCase ).sample.permute(0 , 2 , 1 ) # TODO: verify deprecation of this kwarg SCREAMING_SNAKE_CASE__: Tuple= self.scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , predict_epsilon=_lowerCamelCase )['''prev_sample'''] # apply conditions to the trajectory (set the initial state) SCREAMING_SNAKE_CASE__: str= self.reset_xa(_lowerCamelCase , _lowerCamelCase , self.action_dim ) SCREAMING_SNAKE_CASE__: Optional[Any]= self.to_torch(_lowerCamelCase ) return x, y def __call__( self , lowerCAmelCase , lowerCAmelCase=64 , lowerCAmelCase=32 , lowerCAmelCase=2 , lowerCAmelCase=0.1 ) -> Optional[Any]: # normalize the observations and create batch dimension SCREAMING_SNAKE_CASE__: Union[str, Any]= self.normalize(_lowerCamelCase , '''observations''' ) SCREAMING_SNAKE_CASE__: Dict= obs[None].repeat(_lowerCamelCase , axis=0 ) SCREAMING_SNAKE_CASE__: Optional[int]= {0: self.to_torch(_lowerCamelCase )} SCREAMING_SNAKE_CASE__: Optional[int]= (batch_size, planning_horizon, self.state_dim + self.action_dim) # generate initial noise and apply our conditions (to make the trajectories start at current state) SCREAMING_SNAKE_CASE__: Optional[int]= randn_tensor(_lowerCamelCase , device=self.unet.device ) SCREAMING_SNAKE_CASE__: Optional[Any]= self.reset_xa(_lowerCamelCase , _lowerCamelCase , self.action_dim ) SCREAMING_SNAKE_CASE__: str= self.to_torch(_lowerCamelCase ) # run the diffusion process SCREAMING_SNAKE_CASE__: Tuple= self.run_diffusion(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # sort output trajectories by value SCREAMING_SNAKE_CASE__: Optional[Any]= y.argsort(0 , descending=_lowerCamelCase ).squeeze() SCREAMING_SNAKE_CASE__: Optional[Any]= x[sorted_idx] SCREAMING_SNAKE_CASE__: Union[str, Any]= sorted_values[:, :, : self.action_dim] SCREAMING_SNAKE_CASE__: Union[str, Any]= actions.detach().cpu().numpy() SCREAMING_SNAKE_CASE__: str= self.de_normalize(_lowerCamelCase , key='''actions''' ) # select the action with the highest value if y is not None: SCREAMING_SNAKE_CASE__: Optional[int]= 0 else: # if we didn't run value guiding, select a random action SCREAMING_SNAKE_CASE__: str= np.random.randint(0 , _lowerCamelCase ) SCREAMING_SNAKE_CASE__: Tuple= denorm_actions[selected_index, 0] return denorm_actions
64
"""simple docstring""" from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''microsoft/xprophetnet-large-wiki100-cased''': ( '''https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json''' ), } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''xlm-prophetnet''' lowerCamelCase__ = ['''past_key_values'''] lowerCamelCase__ = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self :List[str] , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[Union[str, Callable]] = "gelu" , _lowerCamelCase :Optional[int] = 3_0_5_2_2 , _lowerCamelCase :Optional[int] = 1_0_2_4 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[int] = 5_1_2 , _lowerCamelCase :Optional[float] = 0.0_2 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 2 , _lowerCamelCase :Optional[int] = 3_2 , _lowerCamelCase :Optional[int] = 1_2_8 , _lowerCamelCase :Optional[bool] = False , _lowerCamelCase :Optional[float] = 0.0 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 1 , _lowerCamelCase :Optional[int] = 2 , **_lowerCamelCase :int , ): __SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_size __SCREAMING_SNAKE_CASE : List[Any] = encoder_ffn_dim __SCREAMING_SNAKE_CASE : str = num_encoder_layers __SCREAMING_SNAKE_CASE : Optional[Any] = num_encoder_attention_heads __SCREAMING_SNAKE_CASE : str = decoder_ffn_dim __SCREAMING_SNAKE_CASE : List[Any] = num_decoder_layers __SCREAMING_SNAKE_CASE : List[str] = num_decoder_attention_heads __SCREAMING_SNAKE_CASE : Dict = max_position_embeddings __SCREAMING_SNAKE_CASE : Any = init_std # Normal(0, this parameter) __SCREAMING_SNAKE_CASE : Any = activation_function # parameters for xlmprophetnet __SCREAMING_SNAKE_CASE : List[Any] = ngram __SCREAMING_SNAKE_CASE : int = num_buckets __SCREAMING_SNAKE_CASE : List[str] = relative_max_distance __SCREAMING_SNAKE_CASE : str = disable_ngram_loss __SCREAMING_SNAKE_CASE : Optional[int] = eps # 3 Types of Dropout __SCREAMING_SNAKE_CASE : int = attention_dropout __SCREAMING_SNAKE_CASE : Optional[Any] = activation_dropout __SCREAMING_SNAKE_CASE : Dict = dropout __SCREAMING_SNAKE_CASE : Any = use_cache super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , is_encoder_decoder=_lowerCamelCase , add_cross_attention=_lowerCamelCase , decoder_start_token_id=_lowerCamelCase , **_lowerCamelCase , ) @property def SCREAMING_SNAKE_CASE_ ( self :int ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[Any] ): raise NotImplementedError( '''This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and''' ''' `num_decoder_layers`.''' )
674
0
import inspect import unittest from transformers import ConvNextVaConfig from transformers.models.auto import get_values from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowerCamelCase_ : '''simple docstring''' def __init__( self , snake_case_ , snake_case_=1_3 , snake_case_=3_2 , snake_case_=3 , snake_case_=4 , snake_case_=[1_0, 2_0, 3_0, 4_0] , snake_case_=[2, 2, 3, 2] , snake_case_=True , snake_case_=True , snake_case_=3_7 , snake_case_="gelu" , snake_case_=1_0 , snake_case_=0.0_2 , snake_case_=["stage2", "stage3", "stage4"] , snake_case_=[2, 3, 4] , snake_case_=None , ) -> Tuple: '''simple docstring''' __lowercase = parent __lowercase = batch_size __lowercase = image_size __lowercase = num_channels __lowercase = num_stages __lowercase = hidden_sizes __lowercase = depths __lowercase = is_training __lowercase = use_labels __lowercase = intermediate_size __lowercase = hidden_act __lowercase = num_labels __lowercase = initializer_range __lowercase = out_features __lowercase = out_indices __lowercase = scope def A ( self ) -> Optional[int]: '''simple docstring''' __lowercase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowercase = None if self.use_labels: __lowercase = ids_tensor([self.batch_size] , self.num_labels ) __lowercase = self.get_config() return config, pixel_values, labels def A ( self ) -> Optional[Any]: '''simple docstring''' return ConvNextVaConfig( num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=_lowerCamelCase , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , ) def A ( self , snake_case_ , snake_case_ , snake_case_ ) -> Optional[Any]: '''simple docstring''' __lowercase = ConvNextVaModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __lowercase = model(_lowerCamelCase ) # expected last hidden states: B, C, H // 32, W // 32 self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 3_2, self.image_size // 3_2) , ) def A ( self , snake_case_ , snake_case_ , snake_case_ ) -> Optional[Any]: '''simple docstring''' __lowercase = ConvNextVaForImageClassification(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __lowercase = model(_lowerCamelCase , labels=_lowerCamelCase ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def A ( self , snake_case_ , snake_case_ , snake_case_ ) -> Optional[int]: '''simple docstring''' __lowercase = ConvNextVaBackbone(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __lowercase = model(_lowerCamelCase ) # verify hidden states self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) , len(config.out_features ) ) self.parent.assertListEqual(model.channels , config.hidden_sizes[1:] ) # verify backbone works with out_features=None __lowercase = None __lowercase = ConvNextVaBackbone(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __lowercase = model(_lowerCamelCase ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) , 1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) , 1 ) self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] ) def A ( self ) -> int: '''simple docstring''' __lowercase = self.prepare_config_and_inputs() __lowercase = config_and_inputs __lowercase = {'''pixel_values''': pixel_values} return config, inputs_dict def A ( self ) -> Optional[Any]: '''simple docstring''' __lowercase = self.prepare_config_and_inputs() __lowercase = config_and_inputs __lowercase = {'''pixel_values''': pixel_values, '''labels''': labels} return config, inputs_dict @require_torch class lowerCamelCase_ ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): '''simple docstring''' __UpperCAmelCase = ( ( ConvNextVaModel, ConvNextVaForImageClassification, ConvNextVaBackbone, ) if is_torch_available() else () ) __UpperCAmelCase = ( {"feature-extraction": ConvNextVaModel, "image-classification": ConvNextVaForImageClassification} if is_torch_available() else {} ) __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False __UpperCAmelCase = False def A ( self ) -> int: '''simple docstring''' __lowercase = ConvNextVaModelTester(self ) __lowercase = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase , hidden_size=3_7 ) def A ( self ) -> Dict: '''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 A ( self ) -> Tuple: '''simple docstring''' return @unittest.skip(reason='''ConvNextV2 does not use inputs_embeds''' ) def A ( self ) -> str: '''simple docstring''' pass @unittest.skip(reason='''ConvNextV2 does not support input and output embeddings''' ) def A ( self ) -> Dict: '''simple docstring''' pass @unittest.skip(reason='''ConvNextV2 does not use feedforward chunking''' ) def A ( self ) -> Any: '''simple docstring''' pass def A ( self ) -> Union[str, Any]: '''simple docstring''' if not self.model_tester.is_training: return for model_class in self.all_model_classes: __lowercase = self.model_tester.prepare_config_and_inputs_with_labels() __lowercase = True if model_class.__name__ in [ *get_values(_lowerCamelCase ), *get_values(_lowerCamelCase ), ]: continue __lowercase = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __lowercase = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) __lowercase = model(**_lowerCamelCase ).loss loss.backward() def A ( self ) -> Dict: '''simple docstring''' if not self.model_tester.is_training: return for model_class in self.all_model_classes: __lowercase = self.model_tester.prepare_config_and_inputs_with_labels() __lowercase = False __lowercase = True if ( model_class.__name__ in [*get_values(_lowerCamelCase ), *get_values(_lowerCamelCase )] or not model_class.supports_gradient_checkpointing ): continue __lowercase = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.gradient_checkpointing_enable() model.train() __lowercase = self._prepare_for_class(_lowerCamelCase , _lowerCamelCase , return_labels=_lowerCamelCase ) __lowercase = model(**_lowerCamelCase ).loss loss.backward() def A ( self ) -> Optional[int]: '''simple docstring''' __lowercase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowercase = model_class(_lowerCamelCase ) __lowercase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowercase = [*signature.parameters.keys()] __lowercase = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) def A ( self ) -> str: '''simple docstring''' __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_lowerCamelCase ) def A ( self ) -> int: '''simple docstring''' def check_hidden_states_output(snake_case_ , snake_case_ , snake_case_ ): __lowercase = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() with torch.no_grad(): __lowercase = model(**self._prepare_for_class(_lowerCamelCase , _lowerCamelCase ) ) __lowercase = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __lowercase = self.model_tester.num_stages self.assertEqual(len(_lowerCamelCase ) , expected_num_stages + 1 ) # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , ) __lowercase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowercase = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __lowercase = True check_hidden_states_output(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) def A ( self ) -> Optional[int]: '''simple docstring''' __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase ) @slow def A ( self ) -> Union[str, Any]: '''simple docstring''' for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowercase = ConvNextVaModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def lowercase_ ( ): '''simple docstring''' __lowercase = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowerCamelCase_ ( unittest.TestCase ): '''simple docstring''' @cached_property def A ( self ) -> Optional[Any]: '''simple docstring''' return AutoImageProcessor.from_pretrained('''facebook/convnextv2-tiny-1k-224''' ) if is_vision_available() else None @slow def A ( self ) -> Union[str, Any]: '''simple docstring''' __lowercase = ConvNextVaForImageClassification.from_pretrained('''facebook/convnextv2-tiny-1k-224''' ).to(_lowerCamelCase ) __lowercase = self.default_image_processor __lowercase = prepare_img() __lowercase = preprocessor(images=_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) # forward pass with torch.no_grad(): __lowercase = model(**_lowerCamelCase ) # verify the logits __lowercase = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape , _lowerCamelCase ) __lowercase = torch.tensor([0.9_9_9_6, 0.1_9_6_6, -0.4_3_8_6] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , _lowerCamelCase , atol=1e-4 ) )
639
"""simple docstring""" import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) _lowerCamelCase = [ '''cross_validation.py''', '''gradient_accumulation.py''', '''local_sgd.py''', '''multi_process_metrics.py''', '''memory.py''', '''automatic_gradient_accumulation.py''', '''fsdp_with_peak_mem_tracking.py''', '''deepspeed_with_config_support.py''', '''megatron_lm_gpt_pretraining.py''', ] class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :bool , _lowerCamelCase :str = None , _lowerCamelCase :list = None ): __SCREAMING_SNAKE_CASE : List[str] = None __SCREAMING_SNAKE_CASE : Optional[Any] = os.path.abspath(os.path.join('''examples''' , '''by_feature''' ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath('''examples''' ) for item in os.listdir(_lowerCamelCase ): if item not in EXCLUDE_EXAMPLES: __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_lowerCamelCase , _lowerCamelCase ) if os.path.isfile(_lowerCamelCase ) and ".py" in item_path: with self.subTest( tested_script=_lowerCamelCase , feature_script=_lowerCamelCase , tested_section='''main()''' if parser_only else '''training_function()''' , ): __SCREAMING_SNAKE_CASE : Tuple = compare_against_test( os.path.join(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = '''\n'''.join(_lowerCamelCase ) if special_strings is not None: for string in special_strings: __SCREAMING_SNAKE_CASE : List[Any] = diff.replace(_lowerCamelCase , '''''' ) self.assertEqual(_lowerCamelCase , '''''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath(os.path.join('''examples''' , '''cv_example.py''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = [ ''' ''' * 1_6 + '''{\n\n''', ''' ''' * 2_0 + '''"accuracy": eval_metric["accuracy"],\n\n''', ''' ''' * 2_0 + '''"f1": eval_metric["f1"],\n\n''', ''' ''' * 2_0 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''', ''' ''' * 2_0 + '''"epoch": epoch,\n\n''', ''' ''' * 1_6 + '''},\n\n''', ''' ''' * 1_6 + '''step=epoch,\n''', ''' ''' * 1_2, ''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''', ] self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = False @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().setUpClass() __SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : str = os.path.join(cls._tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) __SCREAMING_SNAKE_CASE : List[Any] = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().tearDownClass() shutil.rmtree(cls._tmpdir ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : str = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''epoch_0''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() __SCREAMING_SNAKE_CASE : Optional[int] = run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''step_2''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )} '''.split() __SCREAMING_SNAKE_CASE : Any = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )} '''.split() __SCREAMING_SNAKE_CASE : List[str] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) if torch.cuda.is_available(): __SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.device_count() else: __SCREAMING_SNAKE_CASE : Optional[int] = 1 if num_processes > 1: self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) else: self.assertIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ''' examples/by_feature/cross_validation.py --num_folds 2 '''.split() with mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''0'''} ): __SCREAMING_SNAKE_CASE : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = re.findall('''({.+})''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = [r for r in results if '''accuracy''' in r][-1] __SCREAMING_SNAKE_CASE : Tuple = ast.literal_eval(_lowerCamelCase ) self.assertGreaterEqual(results['''accuracy'''] , 0.7_5 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ['''examples/by_feature/multi_process_metrics.py'''] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with tempfile.TemporaryDirectory() as tmpdir: __SCREAMING_SNAKE_CASE : int = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(_lowerCamelCase , '''tracking''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''examples/by_feature/gradient_accumulation.py'''] run_command(self._launch_args + testargs ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = ['''examples/by_feature/local_sgd.py'''] run_command(self._launch_args + testargs )
674
0
import math from typing import Dict, Iterable, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import normalize, rescale, resize, to_channel_dimension_format from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, get_image_size, is_torch_available, is_torch_tensor, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_torch_available(): import torch if is_vision_available(): import PIL UpperCAmelCase_ = logging.get_logger(__name__) def lowerCAmelCase_ ( lowercase: np.ndarray , lowercase: Union[int, Iterable[int]] , lowercase: bool , lowercase: int ) -> Optional[int]: '''simple docstring''' def constraint_to_multiple_of(lowercase: int , lowercase: str , lowercase: Any=0 , lowercase: Any=None ): _UpperCamelCase: Tuple = round(val / multiple ) * multiple if max_val is not None and x > max_val: _UpperCamelCase: List[Any] = math.floor(val / multiple ) * multiple if x < min_val: _UpperCamelCase: List[Any] = math.ceil(val / multiple ) * multiple return x _UpperCamelCase: str = (output_size, output_size) if isinstance(lowercase_ , lowercase_ ) else output_size _UpperCamelCase: Any = get_image_size(lowercase_ ) _UpperCamelCase: Union[str, Any] = output_size # determine new height and width _UpperCamelCase: List[Any] = output_height / input_height _UpperCamelCase: int = output_width / input_width if keep_aspect_ratio: # scale as little as possible if abs(1 - scale_width ) < abs(1 - scale_height ): # fit width _UpperCamelCase: str = scale_width else: # fit height _UpperCamelCase: Union[str, Any] = scale_height _UpperCamelCase: Optional[Any] = constraint_to_multiple_of(scale_height * input_height , multiple=lowercase_ ) _UpperCamelCase: int = constraint_to_multiple_of(scale_width * input_width , multiple=lowercase_ ) return (new_height, new_width) class __magic_name__ ( __UpperCAmelCase ): """simple docstring""" lowerCAmelCase : List[str] = ['''pixel_values'''] def __init__( self : Optional[Any] , _lowercase : bool = True , _lowercase : Dict[str, int] = None , _lowercase : PILImageResampling = PILImageResampling.BILINEAR , _lowercase : bool = False , _lowercase : int = 1 , _lowercase : bool = True , _lowercase : Union[int, float] = 1 / 255 , _lowercase : bool = True , _lowercase : Optional[Union[float, List[float]]] = None , _lowercase : Optional[Union[float, List[float]]] = None , **_lowercase : List[str] , ): """simple docstring""" super().__init__(**_lowerCamelCase ) _UpperCamelCase: Dict = size if size is not None else {'''height''': 384, '''width''': 384} _UpperCamelCase: List[Any] = get_size_dict(_lowerCamelCase ) _UpperCamelCase: List[Any] = do_resize _UpperCamelCase: List[Any] = size _UpperCamelCase: str = keep_aspect_ratio _UpperCamelCase: Optional[int] = ensure_multiple_of _UpperCamelCase: int = resample _UpperCamelCase: Any = do_rescale _UpperCamelCase: int = rescale_factor _UpperCamelCase: Optional[int] = do_normalize _UpperCamelCase: Optional[int] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN _UpperCamelCase: Union[str, Any] = image_std if image_std is not None else IMAGENET_STANDARD_STD def lowerCAmelCase ( self : Union[str, Any] , _lowercase : np.ndarray , _lowercase : Dict[str, int] , _lowercase : bool = False , _lowercase : int = 1 , _lowercase : PILImageResampling = PILImageResampling.BICUBIC , _lowercase : Optional[Union[str, ChannelDimension]] = None , **_lowercase : Tuple , ): """simple docstring""" _UpperCamelCase: Optional[Any] = get_size_dict(_lowerCamelCase ) if "height" not in size or "width" not in size: raise ValueError(f"""The size dictionary must contain the keys \'height\' and \'width\'. Got {size.keys()}""" ) _UpperCamelCase: Union[str, Any] = get_resize_output_image_size( _lowerCamelCase , output_size=(size['''height'''], size['''width''']) , keep_aspect_ratio=_lowerCamelCase , multiple=_lowerCamelCase , ) return resize(_lowerCamelCase , size=_lowerCamelCase , resample=_lowerCamelCase , data_format=_lowerCamelCase , **_lowerCamelCase ) def lowerCAmelCase ( self : Union[str, Any] , _lowercase : np.ndarray , _lowercase : Union[int, float] , _lowercase : Optional[Union[str, ChannelDimension]] = None , **_lowercase : Tuple , ): """simple docstring""" return rescale(_lowerCamelCase , scale=_lowerCamelCase , data_format=_lowerCamelCase , **_lowerCamelCase ) def lowerCAmelCase ( self : Optional[Any] , _lowercase : np.ndarray , _lowercase : Union[float, List[float]] , _lowercase : Union[float, List[float]] , _lowercase : Optional[Union[str, ChannelDimension]] = None , **_lowercase : Optional[int] , ): """simple docstring""" return normalize(_lowerCamelCase , mean=_lowerCamelCase , std=_lowerCamelCase , data_format=_lowerCamelCase , **_lowerCamelCase ) def lowerCAmelCase ( self : Optional[int] , _lowercase : ImageInput , _lowercase : bool = None , _lowercase : int = None , _lowercase : bool = None , _lowercase : int = None , _lowercase : PILImageResampling = None , _lowercase : bool = None , _lowercase : float = None , _lowercase : bool = None , _lowercase : Optional[Union[float, List[float]]] = None , _lowercase : Optional[Union[float, List[float]]] = None , _lowercase : Optional[Union[str, TensorType]] = None , _lowercase : ChannelDimension = ChannelDimension.FIRST , **_lowercase : Dict , ): """simple docstring""" _UpperCamelCase: int = do_resize if do_resize is not None else self.do_resize _UpperCamelCase: int = size if size is not None else self.size _UpperCamelCase: Dict = get_size_dict(_lowerCamelCase ) _UpperCamelCase: Tuple = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio _UpperCamelCase: List[Any] = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of _UpperCamelCase: Optional[Any] = resample if resample is not None else self.resample _UpperCamelCase: Optional[Any] = do_rescale if do_rescale is not None else self.do_rescale _UpperCamelCase: Tuple = rescale_factor if rescale_factor is not None else self.rescale_factor _UpperCamelCase: str = do_normalize if do_normalize is not None else self.do_normalize _UpperCamelCase: Union[str, Any] = image_mean if image_mean is not None else self.image_mean _UpperCamelCase: List[Any] = image_std if image_std is not None else self.image_std _UpperCamelCase: Dict = make_list_of_images(_lowerCamelCase ) if not valid_images(_lowerCamelCase ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None or resample is None: raise ValueError('''Size and resample must be specified if do_resize is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('''Image mean and std must be specified if do_normalize is True.''' ) # All transformations expect numpy arrays. _UpperCamelCase: Optional[int] = [to_numpy_array(_lowerCamelCase ) for image in images] if do_resize: _UpperCamelCase: Optional[int] = [self.resize(image=_lowerCamelCase , size=_lowerCamelCase , resample=_lowerCamelCase ) for image in images] if do_rescale: _UpperCamelCase: int = [self.rescale(image=_lowerCamelCase , scale=_lowerCamelCase ) for image in images] if do_normalize: _UpperCamelCase: str = [self.normalize(image=_lowerCamelCase , mean=_lowerCamelCase , std=_lowerCamelCase ) for image in images] _UpperCamelCase: int = [to_channel_dimension_format(_lowerCamelCase , _lowerCamelCase ) for image in images] _UpperCamelCase: Tuple = {'''pixel_values''': images} return BatchFeature(data=_lowerCamelCase , tensor_type=_lowerCamelCase ) def lowerCAmelCase ( self : Dict , _lowercase : List[Any] , _lowercase : List[Tuple] = None ): """simple docstring""" _UpperCamelCase: int = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(_lowerCamelCase ) != len(_lowerCamelCase ): raise ValueError( '''Make sure that you pass in as many target sizes as the batch dimension of the logits''' ) if is_torch_tensor(_lowerCamelCase ): _UpperCamelCase: Optional[int] = target_sizes.numpy() _UpperCamelCase: Dict = [] for idx in range(len(_lowerCamelCase ) ): _UpperCamelCase: int = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='''bilinear''' , align_corners=_lowerCamelCase ) _UpperCamelCase: int = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(_lowerCamelCase ) else: _UpperCamelCase: Any = logits.argmax(dim=1 ) _UpperCamelCase: Union[str, Any] = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
271
"""simple docstring""" import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from utils_qa import postprocess_qa_predictions import transformers from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed from transformers.trainer_pt_utils import nested_concat, nested_truncate _lowerCamelCase = trt.Logger(trt.Logger.WARNING) _lowerCamelCase = absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) _lowerCamelCase = logging.getLogger(__name__) _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--onnx_model_path''', default=None, type=str, required=True, help='''Path to ONNX model: ''', ) parser.add_argument( '''--output_dir''', default=None, type=str, required=True, help='''The output directory where the model checkpoints and predictions will be written.''', ) # Other parameters parser.add_argument( '''--tokenizer_name''', default='''''', type=str, required=True, help='''Pretrained tokenizer name or path if not the same as model_name''', ) parser.add_argument( '''--version_2_with_negative''', action='''store_true''', help='''If true, the SQuAD examples contain some that do not have an answer.''', ) parser.add_argument( '''--null_score_diff_threshold''', type=float, default=0.0, help='''If null_score - best_non_null is greater than the threshold predict null.''', ) parser.add_argument( '''--max_seq_length''', default=3_84, type=int, help=( '''The maximum total input sequence length after WordPiece tokenization. Sequences ''' '''longer than this will be truncated, and sequences shorter than this will be padded.''' ), ) parser.add_argument( '''--doc_stride''', default=1_28, type=int, help='''When splitting up a long document into chunks, how much stride to take between chunks.''', ) parser.add_argument('''--per_device_eval_batch_size''', default=8, type=int, help='''Batch size per GPU/CPU for evaluation.''') parser.add_argument( '''--n_best_size''', default=20, type=int, help='''The total number of n-best predictions to generate in the nbest_predictions.json output file.''', ) parser.add_argument( '''--max_answer_length''', default=30, type=int, help=( '''The maximum length of an answer that can be generated. This is needed because the start ''' '''and end predictions are not conditioned on one another.''' ), ) parser.add_argument('''--seed''', type=int, default=42, help='''random seed for initialization''') parser.add_argument( '''--dataset_name''', type=str, default=None, required=True, help='''The name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--dataset_config_name''', type=str, default=None, help='''The configuration name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--preprocessing_num_workers''', type=int, default=4, help='''A csv or a json file containing the training data.''' ) parser.add_argument('''--overwrite_cache''', action='''store_true''', help='''Overwrite the cached training and evaluation sets''') parser.add_argument( '''--fp16''', action='''store_true''', help='''Whether to use 16-bit (mixed) precision instead of 32-bit''', ) parser.add_argument( '''--int8''', action='''store_true''', help='''Whether to use INT8''', ) _lowerCamelCase = parser.parse_args() if args.tokenizer_name: _lowerCamelCase = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) else: raise ValueError( '''You are instantiating a new tokenizer from scratch. This is not supported by this script.''' '''You can do it from another script, save it, and load it from here, using --tokenizer_name.''' ) logger.info('''Training/evaluation parameters %s''', args) _lowerCamelCase = args.per_device_eval_batch_size _lowerCamelCase = (args.eval_batch_size, args.max_seq_length) # TRT Engine properties _lowerCamelCase = True _lowerCamelCase = '''temp_engine/bert-fp32.engine''' if args.fpaa: _lowerCamelCase = '''temp_engine/bert-fp16.engine''' if args.inta: _lowerCamelCase = '''temp_engine/bert-int8.engine''' # import ONNX file if not os.path.exists('''temp_engine'''): os.makedirs('''temp_engine''') _lowerCamelCase = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser( network, TRT_LOGGER ) as parser: with open(args.onnx_model_path, '''rb''') as model: if not parser.parse(model.read()): for error in range(parser.num_errors): print(parser.get_error(error)) # Query input names and shapes from parsed TensorRT network _lowerCamelCase = [network.get_input(i) for i in range(network.num_inputs)] _lowerCamelCase = [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: _lowerCamelCase = 1 << 50 if STRICT_TYPES: config.set_flag(trt.BuilderFlag.STRICT_TYPES) if args.fpaa: config.set_flag(trt.BuilderFlag.FPaa) if args.inta: config.set_flag(trt.BuilderFlag.INTa) _lowerCamelCase = builder.create_optimization_profile() config.add_optimization_profile(profile) for i in range(len(input_names)): profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE) _lowerCamelCase = builder.build_engine(network, config) # serialize_engine and store in file (can be directly loaded and deserialized): with open(engine_name, '''wb''') as f: f.write(engine.serialize()) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Tuple , lowercase_ : Any , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = np.asarray(inputs['''input_ids'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''attention_mask'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''token_type_ids'''] , dtype=np.intaa ) # Copy inputs cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , lowercase_ ) # start time __SCREAMING_SNAKE_CASE : Tuple = time.time() # Run inference context.execute_async( bindings=[int(lowercase_ ) for d_inp in d_inputs] + [int(lowercase_ ), int(lowercase_ )] , stream_handle=stream.handle ) # Transfer predictions back from GPU cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) # Synchronize the stream and take time stream.synchronize() # end time __SCREAMING_SNAKE_CASE : List[str] = time.time() __SCREAMING_SNAKE_CASE : int = end_time - start_time __SCREAMING_SNAKE_CASE : int = (h_outputa, h_outputa) # print(outputs) return outputs, infer_time # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. _lowerCamelCase = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). if args.dataset_name is not None: # Downloading and loading a dataset from the hub. _lowerCamelCase = load_dataset(args.dataset_name, args.dataset_config_name) else: raise ValueError('''Evaluation requires a dataset name''') # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Preprocessing the datasets. # Preprocessing is slighlty different for training and evaluation. _lowerCamelCase = raw_datasets['''validation'''].column_names _lowerCamelCase = '''question''' if '''question''' in column_names else column_names[0] _lowerCamelCase = '''context''' if '''context''' in column_names else column_names[1] _lowerCamelCase = '''answers''' if '''answers''' in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). _lowerCamelCase = tokenizer.padding_side == '''right''' if args.max_seq_length > tokenizer.model_max_length: logger.warning( f'The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the' f'model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.' ) _lowerCamelCase = min(args.max_seq_length, tokenizer.model_max_length) def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = [q.lstrip() for q in examples[question_column_name]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer( examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='''only_second''' if pad_on_right else '''only_first''' , max_length=lowercase_ , stride=args.doc_stride , return_overflowing_tokens=lowercase_ , return_offsets_mapping=lowercase_ , padding='''max_length''' , ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. __SCREAMING_SNAKE_CASE : Optional[int] = tokenized_examples.pop('''overflow_to_sample_mapping''' ) # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. __SCREAMING_SNAKE_CASE : Any = [] for i in range(len(tokenized_examples['''input_ids'''] ) ): # Grab the sequence corresponding to that example (to know what is the context and what is the question). __SCREAMING_SNAKE_CASE : int = tokenized_examples.sequence_ids(lowercase_ ) __SCREAMING_SNAKE_CASE : str = 1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. __SCREAMING_SNAKE_CASE : str = sample_mapping[i] tokenized_examples["example_id"].append(examples['''id'''][sample_index] ) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. __SCREAMING_SNAKE_CASE : List[str] = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples['''offset_mapping'''][i] ) ] return tokenized_examples _lowerCamelCase = raw_datasets['''validation'''] # Validation Feature Creation _lowerCamelCase = eval_examples.map( prepare_validation_features, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc='''Running tokenizer on validation dataset''', ) _lowerCamelCase = default_data_collator _lowerCamelCase = eval_dataset.remove_columns(['''example_id''', '''offset_mapping''']) _lowerCamelCase = DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any]="eval" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = postprocess_qa_predictions( examples=lowercase_ , features=lowercase_ , predictions=lowercase_ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=lowercase_ , ) # Format the result to the format the metric expects. if args.version_2_with_negative: __SCREAMING_SNAKE_CASE : Union[str, Any] = [ {'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items() ] else: __SCREAMING_SNAKE_CASE : int = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()] __SCREAMING_SNAKE_CASE : Any = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=lowercase_ , label_ids=lowercase_ ) _lowerCamelCase = load_metric('''squad_v2''' if args.version_2_with_negative else '''squad''') # Evaluation! logger.info('''Loading ONNX model %s for evaluation''', args.onnx_model_path) with open(engine_name, '''rb''') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine( f.read() ) as engine, engine.create_execution_context() as context: # setup for TRT inferrence for i in range(len(input_names)): context.set_binding_shape(i, INPUT_SHAPE) assert context.all_binding_shapes_specified def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' return trt.volume(engine.get_binding_shape(lowercase_ ) ) * engine.get_binding_dtype(lowercase_ ).itemsize # Allocate device memory for inputs and outputs. _lowerCamelCase = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. _lowerCamelCase = cuda.Stream() # Evaluation logger.info('''***** Running Evaluation *****''') logger.info(f' Num examples = {len(eval_dataset)}') logger.info(f' Batch size = {args.per_device_eval_batch_size}') _lowerCamelCase = 0.0 _lowerCamelCase = 0 _lowerCamelCase = timeit.default_timer() _lowerCamelCase = None for step, batch in enumerate(eval_dataloader): _lowerCamelCase , _lowerCamelCase = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 _lowerCamelCase , _lowerCamelCase = outputs _lowerCamelCase = torch.tensor(start_logits) _lowerCamelCase = torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered _lowerCamelCase = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00) _lowerCamelCase = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00) _lowerCamelCase = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) _lowerCamelCase = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00) if all_preds is not None: _lowerCamelCase = nested_truncate(all_preds, len(eval_dataset)) _lowerCamelCase = timeit.default_timer() - start_time logger.info(''' Evaluation done in total %f secs (%f sec per example)''', evalTime, evalTime / len(eval_dataset)) # Inference time from TRT logger.info('''Average Inference Time = {:.3f} ms'''.format(total_time * 10_00 / niter)) logger.info('''Total Inference Time = {:.3f} ms'''.format(total_time * 10_00)) logger.info('''Total Number of Inference = %d''', niter) _lowerCamelCase = post_processing_function(eval_examples, eval_dataset, all_preds) _lowerCamelCase = metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(f'Evaluation metrics: {eval_metric}')
674
0
import copy import os from typing import TYPE_CHECKING, List, Union if TYPE_CHECKING: pass from ...configuration_utils import PretrainedConfig from ...utils import logging _snake_case = logging.get_logger(__name__) _snake_case = { '''kakaobrain/align-base''': '''https://huggingface.co/kakaobrain/align-base/resolve/main/config.json''', } class _lowerCAmelCase ( __UpperCAmelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] ="align_text_model" def __init__( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Any=3_05_22 , SCREAMING_SNAKE_CASE__ : Optional[Any]=7_68 , SCREAMING_SNAKE_CASE__ : Tuple=12 , SCREAMING_SNAKE_CASE__ : Any=12 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=30_72 , SCREAMING_SNAKE_CASE__ : Optional[Any]="gelu" , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.1 , SCREAMING_SNAKE_CASE__ : Tuple=0.1 , SCREAMING_SNAKE_CASE__ : Any=5_12 , SCREAMING_SNAKE_CASE__ : Dict=2 , SCREAMING_SNAKE_CASE__ : List[str]=0.02 , SCREAMING_SNAKE_CASE__ : Any=1e-12 , SCREAMING_SNAKE_CASE__ : Optional[int]=0 , SCREAMING_SNAKE_CASE__ : Tuple="absolute" , SCREAMING_SNAKE_CASE__ : Union[str, Any]=True , **SCREAMING_SNAKE_CASE__ : Optional[int] , ): """simple docstring""" super().__init__(**_lowerCamelCase ) UpperCamelCase = vocab_size UpperCamelCase = hidden_size UpperCamelCase = num_hidden_layers UpperCamelCase = num_attention_heads UpperCamelCase = hidden_act UpperCamelCase = intermediate_size UpperCamelCase = hidden_dropout_prob UpperCamelCase = attention_probs_dropout_prob UpperCamelCase = max_position_embeddings UpperCamelCase = type_vocab_size UpperCamelCase = initializer_range UpperCamelCase = layer_norm_eps UpperCamelCase = position_embedding_type UpperCamelCase = use_cache UpperCamelCase = pad_token_id @classmethod def __lowerCAmelCase ( cls : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, os.PathLike] , **SCREAMING_SNAKE_CASE__ : int ): """simple docstring""" cls._set_token_in_kwargs(_lowerCamelCase ) UpperCamelCase = cls.get_config_dict(_lowerCamelCase , **_lowerCamelCase ) # get the text config dict if we are loading from AlignConfig if config_dict.get('model_type' ) == "align": UpperCamelCase = config_dict['''text_config'''] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(_lowerCamelCase , **_lowerCamelCase ) class _lowerCAmelCase ( __UpperCAmelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Union[str, Any] ="align_vision_model" def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : int = 3 , SCREAMING_SNAKE_CASE__ : int = 6_00 , SCREAMING_SNAKE_CASE__ : float = 2.0 , SCREAMING_SNAKE_CASE__ : float = 3.1 , SCREAMING_SNAKE_CASE__ : int = 8 , SCREAMING_SNAKE_CASE__ : List[int] = [3, 3, 5, 3, 5, 5, 3] , SCREAMING_SNAKE_CASE__ : List[int] = [32, 16, 24, 40, 80, 1_12, 1_92] , SCREAMING_SNAKE_CASE__ : List[int] = [16, 24, 40, 80, 1_12, 1_92, 3_20] , SCREAMING_SNAKE_CASE__ : List[int] = [] , SCREAMING_SNAKE_CASE__ : List[int] = [1, 2, 2, 2, 1, 2, 1] , SCREAMING_SNAKE_CASE__ : List[int] = [1, 2, 2, 3, 3, 4, 1] , SCREAMING_SNAKE_CASE__ : List[int] = [1, 6, 6, 6, 6, 6, 6] , SCREAMING_SNAKE_CASE__ : float = 0.25 , SCREAMING_SNAKE_CASE__ : str = "swish" , SCREAMING_SNAKE_CASE__ : int = 25_60 , SCREAMING_SNAKE_CASE__ : str = "mean" , SCREAMING_SNAKE_CASE__ : float = 0.02 , SCREAMING_SNAKE_CASE__ : float = 0.001 , SCREAMING_SNAKE_CASE__ : float = 0.99 , SCREAMING_SNAKE_CASE__ : float = 0.2 , **SCREAMING_SNAKE_CASE__ : List[Any] , ): """simple docstring""" super().__init__(**_lowerCamelCase ) UpperCamelCase = num_channels UpperCamelCase = image_size UpperCamelCase = width_coefficient UpperCamelCase = depth_coefficient UpperCamelCase = depth_divisor UpperCamelCase = kernel_sizes UpperCamelCase = in_channels UpperCamelCase = out_channels UpperCamelCase = depthwise_padding UpperCamelCase = strides UpperCamelCase = num_block_repeats UpperCamelCase = expand_ratios UpperCamelCase = squeeze_expansion_ratio UpperCamelCase = hidden_act UpperCamelCase = hidden_dim UpperCamelCase = pooling_type UpperCamelCase = initializer_range UpperCamelCase = batch_norm_eps UpperCamelCase = batch_norm_momentum UpperCamelCase = drop_connect_rate UpperCamelCase = sum(_lowerCamelCase ) * 4 @classmethod def __lowerCAmelCase ( cls : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, os.PathLike] , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ): """simple docstring""" cls._set_token_in_kwargs(_lowerCamelCase ) UpperCamelCase = cls.get_config_dict(_lowerCamelCase , **_lowerCamelCase ) # get the vision config dict if we are loading from AlignConfig if config_dict.get('model_type' ) == "align": UpperCamelCase = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(_lowerCamelCase , **_lowerCamelCase ) class _lowerCAmelCase ( __UpperCAmelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] ="align" SCREAMING_SNAKE_CASE_ : str =True def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int]=None , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : List[str]=6_40 , SCREAMING_SNAKE_CASE__ : Any=1.0 , SCREAMING_SNAKE_CASE__ : Dict=0.02 , **SCREAMING_SNAKE_CASE__ : List[str] , ): """simple docstring""" super().__init__(**_lowerCamelCase ) if text_config is None: UpperCamelCase = {} logger.info('text_config is None. Initializing the AlignTextConfig with default values.' ) if vision_config is None: UpperCamelCase = {} logger.info('vision_config is None. Initializing the AlignVisionConfig with default values.' ) UpperCamelCase = AlignTextConfig(**_lowerCamelCase ) UpperCamelCase = AlignVisionConfig(**_lowerCamelCase ) UpperCamelCase = projection_dim UpperCamelCase = temperature_init_value UpperCamelCase = initializer_range @classmethod def __lowerCAmelCase ( cls : str , SCREAMING_SNAKE_CASE__ : AlignTextConfig , SCREAMING_SNAKE_CASE__ : AlignVisionConfig , **SCREAMING_SNAKE_CASE__ : Optional[int] ): """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **_lowerCamelCase ) def __lowerCAmelCase ( self : Tuple ): """simple docstring""" UpperCamelCase = copy.deepcopy(self.__dict__ ) UpperCamelCase = self.text_config.to_dict() UpperCamelCase = self.vision_config.to_dict() UpperCamelCase = self.__class__.model_type return output
282
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = TFAutoModel.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModel.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[str] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Any ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Dict ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = TFAutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = TFAutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
674
0
"""simple docstring""" import numpy as np def UpperCAmelCase ( A__: np.ndarray , A__: np.ndarray , A__: float = 1E-12 , A__: int = 100 , ) -> Tuple: assert np.shape(lowercase_ )[0] == np.shape(lowercase_ )[1] # Ensure proper dimensionality. assert np.shape(lowercase_ )[0] == np.shape(lowercase_ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(lowercase_ ) == np.iscomplexobj(lowercase_ ) __lowerCamelCase : Any = np.iscomplexobj(lowercase_ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(lowercase_ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. __lowerCamelCase : Optional[Any] = False __lowerCamelCase : Union[str, Any] = 0 __lowerCamelCase : Any = 0 __lowerCamelCase : Any = 1E12 while not convergence: # Multiple matrix by the vector. __lowerCamelCase : int = np.dot(lowercase_ , lowercase_ ) # Normalize the resulting output vector. __lowerCamelCase : int = w / np.linalg.norm(lowercase_ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __lowerCamelCase : Optional[Any] = vector.conj().T if is_complex else vector.T __lowerCamelCase : Optional[int] = np.dot(lowercase_ , np.dot(lowercase_ , lowercase_ ) ) # Check convergence. __lowerCamelCase : int = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __lowerCamelCase : Optional[int] = True __lowerCamelCase : str = lambda_ if is_complex: __lowerCamelCase : Optional[int] = np.real(lambda_ ) return lambda_, vector def UpperCAmelCase ( ) -> List[str]: __lowerCamelCase : Union[str, Any] = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) __lowerCamelCase : Optional[Any] = np.array([41, 4, 20] ) __lowerCamelCase : Dict = real_input_matrix.astype(np.complexaaa ) __lowerCamelCase : List[str] = np.triu(1j * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __lowerCamelCase : int = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __lowerCamelCase : int = real_input_matrix __lowerCamelCase : str = real_vector elif problem_type == "complex": __lowerCamelCase : Dict = complex_input_matrix __lowerCamelCase : Optional[int] = complex_vector # Our implementation. __lowerCamelCase : str = power_iteration(lowercase_ , lowercase_ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __lowerCamelCase : int = np.linalg.eigh(lowercase_ ) # Last eigenvalue is the maximum one. __lowerCamelCase : int = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __lowerCamelCase : Dict = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(lowercase_ ) - np.abs(lowercase_ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
594
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'''vocab_file''': '''spiece.model'''} _lowerCamelCase = { '''vocab_file''': { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''', } } # TODO(PVP) - this should be removed in Transformers v5 _lowerCamelCase = { '''t5-small''': 5_12, '''t5-base''': 5_12, '''t5-large''': 5_12, '''t5-3b''': 5_12, '''t5-11b''': 5_12, } _lowerCamelCase = '''▁''' class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self :int , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Union[str, Any]="</s>" , _lowerCamelCase :List[Any]="<unk>" , _lowerCamelCase :Union[str, Any]="<pad>" , _lowerCamelCase :int=1_0_0 , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :Optional[Dict[str, Any]] = None , _lowerCamelCase :int=True , **_lowerCamelCase :List[Any] , ): # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: __SCREAMING_SNAKE_CASE : Union[str, Any] = [f'''<extra_id_{i}>''' for i in range(_lowerCamelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens __SCREAMING_SNAKE_CASE : Optional[int] = len(set(filter(lambda _lowerCamelCase : bool('''extra_id''' in str(_lowerCamelCase ) ) , _lowerCamelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( f'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are''' ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) if legacy: logger.warning_once( f'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to''' ''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = legacy __SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , extra_ids=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , legacy=_lowerCamelCase , **_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Tuple = vocab_file __SCREAMING_SNAKE_CASE : List[str] = extra_ids __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :str , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :int ): if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: __SCREAMING_SNAKE_CASE : Any = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' f''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this''' ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' f''' {pretrained_model_name_or_path} automatically truncating your input to''' f''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences''' f''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with''' ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , _lowerCamelCase , ) return max_model_length @property def SCREAMING_SNAKE_CASE_ ( self :Tuple ): return self.sp_model.get_piece_size() + self._extra_ids def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : str = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None , _lowerCamelCase :bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(_lowerCamelCase )) + [1] return ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1] def SCREAMING_SNAKE_CASE_ ( self :List[str] ): return list( set(filter(lambda _lowerCamelCase : bool(re.search(r'''<extra_id_\d+>''' , _lowerCamelCase ) ) is not None , self.additional_special_tokens ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return [self._convert_token_to_id(_lowerCamelCase ) for token in self.get_sentinel_tokens()] def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[int] ): if len(_lowerCamelCase ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated''' ''' eos tokens being added.''' ) return token_ids else: return token_ids + [self.eos_token_id] def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : Optional[Any] = self._add_eos_if_not_present(_lowerCamelCase ) if token_ids_a is None: return token_ids_a else: __SCREAMING_SNAKE_CASE : Union[str, Any] = self._add_eos_if_not_present(_lowerCamelCase ) return token_ids_a + token_ids_a def __getstate__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() __SCREAMING_SNAKE_CASE : List[str] = None return state def __setstate__( self :Optional[Any] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : Tuple = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __SCREAMING_SNAKE_CASE : Optional[int] = {} __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :"TextInput" , **_lowerCamelCase :str ): # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at # the beginning of the text if not self.legacy: __SCREAMING_SNAKE_CASE : Dict = SPIECE_UNDERLINE + text.replace(_lowerCamelCase , ''' ''' ) return super().tokenize(_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[Any] , **_lowerCamelCase :Dict ): if not self.legacy: __SCREAMING_SNAKE_CASE : str = text.startswith(_lowerCamelCase ) if is_first: __SCREAMING_SNAKE_CASE : str = text[1:] __SCREAMING_SNAKE_CASE : Tuple = self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) if not self.legacy and not is_first and not text.startswith(''' ''' ) and tokens[0].startswith(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[int] = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[Any] ): if token.startswith('''<extra_id_''' ): __SCREAMING_SNAKE_CASE : Tuple = re.match(r'''<extra_id_(\d+)>''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): if index < self.sp_model.get_piece_size(): __SCREAMING_SNAKE_CASE : List[Any] = self.sp_model.IdToPiece(_lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : Dict = f'''<extra_id_{self.vocab_size - 1 - index}>''' return token def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : str = [] __SCREAMING_SNAKE_CASE : Dict = '''''' __SCREAMING_SNAKE_CASE : Dict = 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(_lowerCamelCase ) + token __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : str = [] else: current_sub_tokens.append(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = False out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :str , _lowerCamelCase :Optional[str] = None ): if not os.path.isdir(_lowerCamelCase ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __SCREAMING_SNAKE_CASE : List[str] = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: __SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
674
0
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING __snake_case = logging.get_logger(__name__) __snake_case = { "Salesforce/instruct-blip-flan-t5": "https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json", } class UpperCAmelCase ( __UpperCAmelCase ): lowercase = """instructblip_vision_model""" def __init__( self : Any , __magic_name__ : Dict=1_4_0_8 , __magic_name__ : Dict=6_1_4_4 , __magic_name__ : Any=3_9 , __magic_name__ : Dict=1_6 , __magic_name__ : Optional[Any]=2_2_4 , __magic_name__ : Optional[Any]=1_4 , __magic_name__ : List[str]="gelu" , __magic_name__ : List[Any]=1e-6 , __magic_name__ : Optional[Any]=0.0 , __magic_name__ : List[Any]=1e-10 , __magic_name__ : Tuple=True , **__magic_name__ : Any , ): """simple docstring""" super().__init__(**_lowerCamelCase ) UpperCamelCase = hidden_size UpperCamelCase = intermediate_size UpperCamelCase = num_hidden_layers UpperCamelCase = num_attention_heads UpperCamelCase = patch_size UpperCamelCase = image_size UpperCamelCase = initializer_range UpperCamelCase = attention_dropout UpperCamelCase = layer_norm_eps UpperCamelCase = hidden_act UpperCamelCase = qkv_bias @classmethod def lowerCamelCase_ ( cls : List[Any] , __magic_name__ : Union[str, os.PathLike] , **__magic_name__ : List[Any] ): """simple docstring""" cls._set_token_in_kwargs(_lowerCamelCase ) UpperCamelCase = cls.get_config_dict(_lowerCamelCase , **_lowerCamelCase ) # get the vision config dict if we are loading from InstructBlipConfig if config_dict.get("""model_type""" ) == "instructblip": UpperCamelCase = config_dict['''vision_config'''] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(_lowerCamelCase , **_lowerCamelCase ) class UpperCAmelCase ( __UpperCAmelCase ): lowercase = """instructblip_qformer""" def __init__( self : Optional[int] , __magic_name__ : Union[str, Any]=3_0_5_2_2 , __magic_name__ : List[Any]=7_6_8 , __magic_name__ : Dict=1_2 , __magic_name__ : Optional[int]=1_2 , __magic_name__ : int=3_0_7_2 , __magic_name__ : Tuple="gelu" , __magic_name__ : Optional[int]=0.1 , __magic_name__ : str=0.1 , __magic_name__ : Optional[Any]=5_1_2 , __magic_name__ : Tuple=0.02 , __magic_name__ : Optional[int]=1e-12 , __magic_name__ : Union[str, Any]=0 , __magic_name__ : Tuple="absolute" , __magic_name__ : Any=2 , __magic_name__ : int=1_4_0_8 , **__magic_name__ : str , ): """simple docstring""" super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase ) UpperCamelCase = vocab_size UpperCamelCase = hidden_size UpperCamelCase = num_hidden_layers UpperCamelCase = num_attention_heads UpperCamelCase = hidden_act UpperCamelCase = intermediate_size UpperCamelCase = hidden_dropout_prob UpperCamelCase = attention_probs_dropout_prob UpperCamelCase = max_position_embeddings UpperCamelCase = initializer_range UpperCamelCase = layer_norm_eps UpperCamelCase = position_embedding_type UpperCamelCase = cross_attention_frequency UpperCamelCase = encoder_hidden_size @classmethod def lowerCamelCase_ ( cls : str , __magic_name__ : Union[str, os.PathLike] , **__magic_name__ : Optional[int] ): """simple docstring""" cls._set_token_in_kwargs(_lowerCamelCase ) UpperCamelCase = cls.get_config_dict(_lowerCamelCase , **_lowerCamelCase ) # get the qformer config dict if we are loading from InstructBlipConfig if config_dict.get("""model_type""" ) == "instructblip": UpperCamelCase = config_dict['''qformer_config'''] if "model_type" in config_dict and hasattr(cls , """model_type""" ) and config_dict["model_type"] != cls.model_type: logger.warning( F'You are using a model of type {config_dict["model_type"]} to instantiate a model of type ' F'{cls.model_type}. This is not supported for all configurations of models and can yield errors.' ) return cls.from_dict(_lowerCamelCase , **_lowerCamelCase ) class UpperCAmelCase ( __UpperCAmelCase ): lowercase = """instructblip""" lowercase = True def __init__( self : Union[str, Any] , __magic_name__ : Union[str, Any]=None , __magic_name__ : Any=None , __magic_name__ : Optional[int]=None , __magic_name__ : Union[str, Any]=3_2 , **__magic_name__ : Dict ): """simple docstring""" super().__init__(**_lowerCamelCase ) if vision_config is None: UpperCamelCase = {} logger.info("""vision_config is None. initializing the InstructBlipVisionConfig with default values.""" ) if qformer_config is None: UpperCamelCase = {} logger.info("""qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.""" ) if text_config is None: UpperCamelCase = {} logger.info("""text_config is None. Initializing the text config with default values (`OPTConfig`).""" ) UpperCamelCase = InstructBlipVisionConfig(**_lowerCamelCase ) UpperCamelCase = InstructBlipQFormerConfig(**_lowerCamelCase ) UpperCamelCase = text_config['''model_type'''] if '''model_type''' in text_config else '''opt''' UpperCamelCase = CONFIG_MAPPING[text_model_type](**_lowerCamelCase ) UpperCamelCase = self.text_config.tie_word_embeddings UpperCamelCase = self.text_config.is_encoder_decoder UpperCamelCase = num_query_tokens UpperCamelCase = self.vision_config.hidden_size UpperCamelCase = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES UpperCamelCase = 1.0 UpperCamelCase = 0.02 @classmethod def lowerCamelCase_ ( cls : int , __magic_name__ : InstructBlipVisionConfig , __magic_name__ : InstructBlipQFormerConfig , __magic_name__ : PretrainedConfig , **__magic_name__ : Union[str, Any] , ): """simple docstring""" return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **_lowerCamelCase , ) def lowerCamelCase_ ( self : Any ): """simple docstring""" UpperCamelCase = copy.deepcopy(self.__dict__ ) UpperCamelCase = self.vision_config.to_dict() UpperCamelCase = self.qformer_config.to_dict() UpperCamelCase = self.text_config.to_dict() UpperCamelCase = self.__class__.model_type return output
386
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( '''files''' , [ ['''full:README.md''', '''dataset_infos.json'''], ['''empty:README.md''', '''dataset_infos.json'''], ['''dataset_infos.json'''], ['''full:README.md'''], ] , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = tmp_path_factory.mktemp('''dset_infos_dir''' ) if "full:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''---\ndataset_info:\n dataset_size: 42\n---''' ) if "empty:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''''' ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / '''dataset_infos.json''' , '''w''' ) as f: f.write('''{"default": {"dataset_size": 42}}''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( '''dataset_info''' , [ DatasetInfo(), DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ), ] , ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : DatasetInfo ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = str(lowercase_ ) dataset_info.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = DatasetInfo.from_directory(lowercase_ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(lowercase_ , '''dataset_info.json''' ) ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo( description='''foo''' , citation='''bar''' , homepage='''https://foo.bar''' , license='''CC0''' , features=Features({'''a''': Value('''int32''' )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train''', '''num_examples''': 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , ) __SCREAMING_SNAKE_CASE : Optional[int] = dataset_info._to_yaml_dict() assert sorted(lowercase_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) __SCREAMING_SNAKE_CASE : int = yaml.safe_dump(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = yaml.safe_load(lowercase_ ) assert dataset_info_yaml_dict == reloaded def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetInfo() __SCREAMING_SNAKE_CASE : Union[str, Any] = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( '''dataset_infos_dict''' , [ DatasetInfosDict(), DatasetInfosDict({'''default''': DatasetInfo()} ), DatasetInfosDict({'''my_config_name''': DatasetInfo()} ), DatasetInfosDict( { '''default''': DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ) } ), DatasetInfosDict( { '''v1''': DatasetInfo(dataset_size=42 ), '''v2''': DatasetInfo(dataset_size=1337 ), } ), ] , ) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : DatasetInfosDict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) dataset_infos_dict.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): __SCREAMING_SNAKE_CASE : Optional[int] = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(lowercase_ , '''README.md''' ) )
674
0
import random import unittest import numpy as np import transformers from transformers import is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax if is_flax_available(): import os import jax.numpy as jnp from jax import jit from transformers import AutoTokenizer, FlaxAutoModelForCausalLM from transformers.modeling_flax_pytorch_utils import load_flax_weights_in_pytorch_model a__ = '''0.12''' # assumed parallelism: 8 if is_torch_available(): import torch def A__ (snake_case : List[Any] , snake_case : Union[str, Any] , snake_case : Optional[int]=None ) -> Any: if rng is None: __UpperCamelCase : Dict = random.Random() __UpperCamelCase : List[str] = 1 for dim in shape: total_dims *= dim __UpperCamelCase : Tuple = [] for _ in range(lowercase_ ): values.append(rng.randint(0 , vocab_size - 1 ) ) __UpperCamelCase : Union[str, Any] = np.array(lowercase_ , dtype=jnp.intaa ).reshape(lowercase_ ) return output def A__ (snake_case : Optional[Any] , snake_case : Dict=None ) -> int: __UpperCamelCase : Optional[int] = ids_tensor(lowercase_ , vocab_size=2 , rng=lowercase_ ) # make sure that at least one token is attended to for each batch __UpperCamelCase : Tuple = 1 return attn_mask @require_flax class SCREAMING_SNAKE_CASE_ : """simple docstring""" __magic_name__ : str = None __magic_name__ : List[str] = () def lowerCamelCase__ ( self : Optional[int] ) -> Union[str, Any]: """simple docstring""" __UpperCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() # cut to half length & take max batch_size 3 __UpperCamelCase : int = 2 __UpperCamelCase : Any = inputs['''input_ids'''].shape[-1] // 2 __UpperCamelCase : Optional[Any] = inputs['''input_ids'''][:max_batch_size, :sequence_length] __UpperCamelCase : List[str] = jnp.ones_like(_lowerCamelCase ) __UpperCamelCase : Optional[Any] = attention_mask[:max_batch_size, :sequence_length] # generate max 5 tokens __UpperCamelCase : Union[str, Any] = input_ids.shape[-1] + 5 if config.eos_token_id is not None and config.pad_token_id is None: # hack to allow generate for models such as GPT2 as is done in `generate()` __UpperCamelCase : Optional[int] = config.eos_token_id return config, input_ids, attention_mask, max_length @is_pt_flax_cross_test def lowerCamelCase__ ( self : int ) -> List[Any]: """simple docstring""" __UpperCamelCase : List[Any] = self._get_input_ids_and_config() __UpperCamelCase : Dict = False __UpperCamelCase : Optional[Any] = max_length __UpperCamelCase : List[Any] = 0 for model_class in self.all_generative_model_classes: __UpperCamelCase : Optional[Any] = model_class(_lowerCamelCase ) __UpperCamelCase : List[Any] = model_class.__name__[4:] # Skip the "Flax" at the beginning __UpperCamelCase : Optional[int] = getattr(_lowerCamelCase , _lowerCamelCase ) __UpperCamelCase : Optional[Any] = pt_model_class(_lowerCamelCase ).eval() __UpperCamelCase : Any = load_flax_weights_in_pytorch_model(_lowerCamelCase , flax_model.params ) __UpperCamelCase : Any = flax_model.generate(_lowerCamelCase ).sequences __UpperCamelCase : str = pt_model.generate(torch.tensor(_lowerCamelCase , dtype=torch.long ) ) if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]: __UpperCamelCase : Optional[Any] = flax_generation_outputs[:, : pt_generation_outputs.shape[-1]] self.assertListEqual(pt_generation_outputs.numpy().tolist() , flax_generation_outputs.tolist() ) def lowerCamelCase__ ( self : List[Any] ) -> Optional[Any]: """simple docstring""" __UpperCamelCase : int = self._get_input_ids_and_config() __UpperCamelCase : List[str] = False __UpperCamelCase : Dict = max_length for model_class in self.all_generative_model_classes: __UpperCamelCase : Dict = model_class(_lowerCamelCase ) __UpperCamelCase : str = model.generate(_lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , _lowerCamelCase ) __UpperCamelCase : str = jit(model.generate ) __UpperCamelCase : List[str] = jit_generate(_lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def lowerCamelCase__ ( self : List[Any] ) -> Union[str, Any]: """simple docstring""" __UpperCamelCase : Dict = self._get_input_ids_and_config() __UpperCamelCase : Optional[Any] = True __UpperCamelCase : List[str] = max_length for model_class in self.all_generative_model_classes: __UpperCamelCase : List[Any] = model_class(_lowerCamelCase ) __UpperCamelCase : List[Any] = model.generate(_lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , _lowerCamelCase ) __UpperCamelCase : Any = jit(model.generate ) __UpperCamelCase : Any = jit_generate(_lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def lowerCamelCase__ ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" __UpperCamelCase : Optional[Any] = self._get_input_ids_and_config() __UpperCamelCase : Dict = False __UpperCamelCase : str = max_length __UpperCamelCase : List[Any] = 2 for model_class in self.all_generative_model_classes: __UpperCamelCase : List[str] = model_class(_lowerCamelCase ) __UpperCamelCase : str = model.generate(_lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , _lowerCamelCase ) __UpperCamelCase : Any = jit(model.generate ) __UpperCamelCase : Optional[int] = jit_generate(_lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def lowerCamelCase__ ( self : List[Any] ) -> int: """simple docstring""" __UpperCamelCase : Optional[int] = self._get_input_ids_and_config() __UpperCamelCase : List[Any] = False __UpperCamelCase : Optional[Any] = max_length __UpperCamelCase : Dict = 2 __UpperCamelCase : int = 2 for model_class in self.all_generative_model_classes: __UpperCamelCase : Any = model_class(_lowerCamelCase ) __UpperCamelCase : List[Any] = model.generate(_lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[0] , input_ids.shape[0] * config.num_return_sequences ) def lowerCamelCase__ ( self : List[Any] ) -> str: """simple docstring""" __UpperCamelCase : str = self._get_input_ids_and_config() __UpperCamelCase : Any = True __UpperCamelCase : int = max_length __UpperCamelCase : Dict = 0.8 __UpperCamelCase : int = 10 __UpperCamelCase : List[str] = 0.3 __UpperCamelCase : Optional[Any] = 1 __UpperCamelCase : Optional[Any] = 8 __UpperCamelCase : Optional[int] = 9 for model_class in self.all_generative_model_classes: __UpperCamelCase : List[str] = model_class(_lowerCamelCase ) __UpperCamelCase : Dict = model.generate(_lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , _lowerCamelCase ) __UpperCamelCase : Optional[int] = jit(model.generate ) __UpperCamelCase : str = jit_generate(_lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def lowerCamelCase__ ( self : Union[str, Any] ) -> int: """simple docstring""" __UpperCamelCase : Optional[int] = self._get_input_ids_and_config() __UpperCamelCase : Tuple = max_length __UpperCamelCase : Union[str, Any] = 1 __UpperCamelCase : str = 8 __UpperCamelCase : Optional[int] = 9 for model_class in self.all_generative_model_classes: __UpperCamelCase : Optional[int] = model_class(_lowerCamelCase ) __UpperCamelCase : List[str] = model.generate(_lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , _lowerCamelCase ) __UpperCamelCase : List[str] = jit(model.generate ) __UpperCamelCase : str = jit_generate(_lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def lowerCamelCase__ ( self : Dict ) -> Optional[int]: """simple docstring""" __UpperCamelCase : List[Any] = self._get_input_ids_and_config() __UpperCamelCase : List[str] = max_length __UpperCamelCase : List[Any] = 2 __UpperCamelCase : Optional[Any] = 1 __UpperCamelCase : int = 8 __UpperCamelCase : int = 9 for model_class in self.all_generative_model_classes: __UpperCamelCase : Any = model_class(_lowerCamelCase ) __UpperCamelCase : List[str] = model.generate(_lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , _lowerCamelCase ) __UpperCamelCase : Union[str, Any] = jit(model.generate ) __UpperCamelCase : Optional[int] = jit_generate(_lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def lowerCamelCase__ ( self : int ) -> Optional[Any]: """simple docstring""" __UpperCamelCase : Any = self._get_input_ids_and_config() # pad attention mask on the left __UpperCamelCase : Optional[int] = attention_mask.at[(0, 0)].set(0 ) __UpperCamelCase : Tuple = False __UpperCamelCase : Optional[Any] = max_length for model_class in self.all_generative_model_classes: __UpperCamelCase : List[str] = model_class(_lowerCamelCase ) __UpperCamelCase : Optional[Any] = model.generate(_lowerCamelCase , attention_mask=_lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , _lowerCamelCase ) __UpperCamelCase : Optional[int] = jit(model.generate ) __UpperCamelCase : Optional[Any] = jit_generate(_lowerCamelCase , attention_mask=_lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def lowerCamelCase__ ( self : Dict ) -> Dict: """simple docstring""" __UpperCamelCase : List[Any] = self._get_input_ids_and_config() # pad attention mask on the left __UpperCamelCase : List[Any] = attention_mask.at[(0, 0)].set(0 ) __UpperCamelCase : List[str] = True __UpperCamelCase : List[str] = max_length for model_class in self.all_generative_model_classes: __UpperCamelCase : List[Any] = model_class(_lowerCamelCase ) __UpperCamelCase : Optional[Any] = model.generate(_lowerCamelCase , attention_mask=_lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , _lowerCamelCase ) __UpperCamelCase : int = jit(model.generate ) __UpperCamelCase : List[str] = jit_generate(_lowerCamelCase , attention_mask=_lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def lowerCamelCase__ ( self : int ) -> Union[str, Any]: """simple docstring""" __UpperCamelCase : Tuple = self._get_input_ids_and_config() # pad attention mask on the left __UpperCamelCase : Dict = attention_mask.at[(0, 0)].set(0 ) __UpperCamelCase : Tuple = 2 __UpperCamelCase : Tuple = max_length for model_class in self.all_generative_model_classes: __UpperCamelCase : List[Any] = model_class(_lowerCamelCase ) __UpperCamelCase : int = model.generate(_lowerCamelCase , attention_mask=_lowerCamelCase ).sequences self.assertEqual(generation_outputs.shape[-1] , _lowerCamelCase ) __UpperCamelCase : int = jit(model.generate ) __UpperCamelCase : Optional[Any] = jit_generate(_lowerCamelCase , attention_mask=_lowerCamelCase ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) @require_flax class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): """simple docstring""" def lowerCamelCase__ ( self : str ) -> Optional[int]: """simple docstring""" __UpperCamelCase : Any = AutoTokenizer.from_pretrained("""hf-internal-testing/tiny-bert""" ) __UpperCamelCase : Dict = FlaxAutoModelForCausalLM.from_pretrained("""hf-internal-testing/tiny-bert-flax-only""" ) __UpperCamelCase : Dict = '''Hello world''' __UpperCamelCase : int = tokenizer(_lowerCamelCase , return_tensors="""np""" ).input_ids # typos are quickly detected (the correct argument is `do_sample`) with self.assertRaisesRegex(_lowerCamelCase , """do_samples""" ): model.generate(_lowerCamelCase , do_samples=_lowerCamelCase ) # arbitrary arguments that will not be used anywhere are also not accepted with self.assertRaisesRegex(_lowerCamelCase , """foo""" ): __UpperCamelCase : int = {'''foo''': '''bar'''} model.generate(_lowerCamelCase , **_lowerCamelCase )
279
"""simple docstring""" from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class snake_case ( __UpperCAmelCase , __UpperCAmelCase ): @register_to_config def __init__( self :List[str] , _lowerCamelCase :int = 7_6_8 , ): super().__init__() __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter(torch.zeros(1 , _lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.ones(1 , _lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Optional[Union[str, torch.device]] = None , _lowerCamelCase :Optional[torch.dtype] = None , ): __SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(self.mean.to(_lowerCamelCase ).to(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(self.std.to(_lowerCamelCase ).to(_lowerCamelCase ) ) return self def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Tuple = (embeds - self.mean) * 1.0 / self.std return embeds def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = (embeds * self.std) + self.mean return embeds
674
0
import os import sys import unittest __lowerCAmelCase = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, 'utils')) import check_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402 # Align TRANSFORMERS_PATH in check_dummies with the current path __lowerCAmelCase = os.path.join(git_repo_path, 'src', 'transformers') __lowerCAmelCase = '\n{0} = None\n' __lowerCAmelCase = '\nclass {0}(metaclass=DummyObject):\n _backends = {1}\n\n def __init__(self, *args, **kwargs):\n requires_backends(self, {1})\n' __lowerCAmelCase = '\ndef {0}(*args, **kwargs):\n requires_backends({0}, {1})\n' class lowerCamelCase ( unittest.TestCase ): def snake_case__ ( self :List[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE = find_backend(''' _import_structure["models.albert"].append("AlbertTokenizerFast")''' ) self.assertIsNone(_lowerCamelCase ) SCREAMING_SNAKE_CASE = find_backend(''' if not is_tokenizers_available():''' ) self.assertEqual(_lowerCamelCase , '''tokenizers''' ) SCREAMING_SNAKE_CASE = find_backend(''' if not is_tensorflow_text_available():''' ) self.assertEqual(_lowerCamelCase , '''tensorflow_text''' ) SCREAMING_SNAKE_CASE = find_backend(''' if not (is_sentencepiece_available() and is_tokenizers_available()):''' ) self.assertEqual(_lowerCamelCase , '''sentencepiece_and_tokenizers''' ) SCREAMING_SNAKE_CASE = find_backend( ''' if not (is_sentencepiece_available() and is_tensorflow_text_available()):''' ) self.assertEqual(_lowerCamelCase , '''sentencepiece_and_tensorflow_text''' ) SCREAMING_SNAKE_CASE = find_backend( ''' if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):''' ) self.assertEqual(_lowerCamelCase , '''sentencepiece_and_tokenizers_and_vision''' ) def snake_case__ ( self :int ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE = read_init() # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects self.assertIn('''torch''' , _lowerCamelCase ) self.assertIn('''tensorflow_text''' , _lowerCamelCase ) self.assertIn('''sentencepiece_and_tokenizers''' , _lowerCamelCase ) # Likewise, we can't assert on the exact content of a key self.assertIn('''BertModel''' , objects['''torch'''] ) self.assertIn('''TFBertModel''' , objects['''tf'''] ) self.assertIn('''FlaxBertModel''' , objects['''flax'''] ) self.assertIn('''BertModel''' , objects['''torch'''] ) self.assertIn('''TFBertTokenizer''' , objects['''tensorflow_text'''] ) self.assertIn('''convert_slow_tokenizer''' , objects['''sentencepiece_and_tokenizers'''] ) def snake_case__ ( self :Any ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE = create_dummy_object('''CONSTANT''' , '''\'torch\'''' ) self.assertEqual(_lowerCamelCase , '''\nCONSTANT = None\n''' ) SCREAMING_SNAKE_CASE = create_dummy_object('''function''' , '''\'torch\'''' ) self.assertEqual( _lowerCamelCase , '''\ndef function(*args, **kwargs):\n requires_backends(function, \'torch\')\n''' ) SCREAMING_SNAKE_CASE = ''' class FakeClass(metaclass=DummyObject): _backends = \'torch\' def __init__(self, *args, **kwargs): requires_backends(self, \'torch\') ''' SCREAMING_SNAKE_CASE = create_dummy_object('''FakeClass''' , '''\'torch\'''' ) self.assertEqual(_lowerCamelCase , _lowerCamelCase ) def snake_case__ ( self :Union[str, Any] ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE = '''# This file is autogenerated by the command `make fix-copies`, do not edit. from ..utils import DummyObject, requires_backends CONSTANT = None def function(*args, **kwargs): requires_backends(function, ["torch"]) class FakeClass(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"]) ''' SCREAMING_SNAKE_CASE = create_dummy_files({'''torch''': ['''CONSTANT''', '''function''', '''FakeClass''']} ) self.assertEqual(dummy_files['''torch'''] , _lowerCamelCase )
201
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : int , lowercase_ : Any ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = BertConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : Optional[int] = BertForPreTraining(lowercase_ ) # Load weights from tf checkpoint load_tf_weights_in_bert(lowercase_ , lowercase_ , lowercase_ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--bert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained BERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
674
0
"""simple docstring""" from typing import List, Optional, TypeVar from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .info import DatasetInfo from .iterable_dataset import IterableDataset, _concatenate_iterable_datasets, _interleave_iterable_datasets from .splits import NamedSplit from .utils import logging from .utils.py_utils import Literal a : List[str] = logging.get_logger(__name__) a : Optional[Any] = TypeVar("""DatasetType""", Dataset, IterableDataset) def lowercase__(A , A = None , A = None , A = None , A = None , A = "first_exhausted" , ) ->List[str]: """simple docstring""" from .arrow_dataset import Dataset from .iterable_dataset import IterableDataset if not datasets: raise ValueError("Unable to interleave an empty list of datasets." ) for i, dataset in enumerate(lowercase_ ): if not isinstance(lowercase_ , (Dataset, IterableDataset) ): if isinstance(lowercase_ , (DatasetDict, IterableDatasetDict) ): if not dataset: raise ValueError( f'''Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} ''' "is an empty dataset dictionary." ) raise ValueError( f'''Dataset at position {i} has at least one split: {list(lowercase_ )}\n''' f'''Please pick one to interleave with the other datasets, for example: dataset[\'{next(iter(lowercase_ ) )}\']''' ) raise ValueError( f'''Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(lowercase_ ).__name__}.''' ) if i == 0: lowercase__ : List[str]= ( (Dataset, IterableDataset) if isinstance(lowercase_ , lowercase_ ) else (IterableDataset, Dataset) ) elif not isinstance(lowercase_ , lowercase_ ): raise ValueError( f'''Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects.''' ) if stopping_strategy not in ["first_exhausted", "all_exhausted"]: raise ValueError(f'''{stopping_strategy} is not supported. Please enter a valid stopping_strategy.''' ) if dataset_type is Dataset: return _interleave_map_style_datasets( lowercase_ , lowercase_ , lowercase_ , info=lowercase_ , split=lowercase_ , stopping_strategy=lowercase_ ) else: return _interleave_iterable_datasets( lowercase_ , lowercase_ , lowercase_ , info=lowercase_ , split=lowercase_ , stopping_strategy=lowercase_ ) def lowercase__(A , A = None , A = None , A = 0 , ) ->List[str]: """simple docstring""" if not dsets: raise ValueError("Unable to concatenate an empty list of datasets." ) for i, dataset in enumerate(lowercase_ ): if not isinstance(lowercase_ , (Dataset, IterableDataset) ): if isinstance(lowercase_ , (DatasetDict, IterableDatasetDict) ): if not dataset: raise ValueError( f'''Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} ''' "is an empty dataset dictionary." ) raise ValueError( f'''Dataset at position {i} has at least one split: {list(lowercase_ )}\n''' f'''Please pick one to interleave with the other datasets, for example: dataset[\'{next(iter(lowercase_ ) )}\']''' ) raise ValueError( f'''Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(lowercase_ ).__name__}.''' ) if i == 0: lowercase__ : Optional[Any]= ( (Dataset, IterableDataset) if isinstance(lowercase_ , lowercase_ ) else (IterableDataset, Dataset) ) elif not isinstance(lowercase_ , lowercase_ ): raise ValueError( f'''Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects.''' ) if dataset_type is Dataset: return _concatenate_map_style_datasets(lowercase_ , info=lowercase_ , split=lowercase_ , axis=lowercase_ ) else: return _concatenate_iterable_datasets(lowercase_ , info=lowercase_ , split=lowercase_ , axis=lowercase_ )
218
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = ( '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.''' '''It takes two arguments named `image` which should be the original image, and `label` which should be a text ''' '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.''' ) lowerCamelCase__ = '''CIDAS/clipseg-rd64-refined''' lowerCamelCase__ = '''image_segmenter''' lowerCamelCase__ = CLIPSegForImageSegmentation lowerCamelCase__ = ['''image''', '''text'''] lowerCamelCase__ = ['''image'''] def __init__( self :Dict , *_lowerCamelCase :Union[str, Any] , **_lowerCamelCase :Tuple ): requires_backends(self , ['''vision'''] ) super().__init__(*_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :"Image" , _lowerCamelCase :str ): return self.pre_processor(text=[label] , images=[image] , padding=_lowerCamelCase , return_tensors='''pt''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[int] ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = self.model(**_lowerCamelCase ).logits return logits def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy() __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : str = 1 return Image.fromarray((array * 2_5_5).astype(np.uinta ) )
674
0
import os import unittest from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer from ...test_tokenization_common import TokenizerTesterMixin class UpperCAmelCase ( __UpperCAmelCase , unittest.TestCase ): a: Union[str, Any] = TransfoXLTokenizer a: Union[str, Any] = False a: Optional[int] = False def _A ( self: List[str] ): super().setUp() _a = [ '''<unk>''', '''[CLS]''', '''[SEP]''', '''want''', '''unwanted''', '''wa''', '''un''', '''running''', ''',''', '''low''', '''l''', ] _a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) def _A ( self: Tuple , **__UpperCamelCase: Dict ): _a = True return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def _A ( self: Optional[int] , __UpperCamelCase: int ): _a = '''<unk> UNwanted , running''' _a = '''<unk> unwanted, running''' return input_text, output_text def _A ( self: Union[str, Any] ): _a = TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=_lowerCamelCase ) _a = tokenizer.tokenize('''<unk> UNwanted , running''' ) self.assertListEqual(_lowerCamelCase , ['''<unk>''', '''unwanted''', ''',''', '''running'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [0, 4, 8, 7] ) def _A ( self: Optional[Any] ): _a = TransfoXLTokenizer(lower_case=_lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo ! how \n Are yoU ? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] ) def _A ( self: List[str] ): _a = TransfoXLTokenizer(lower_case=_lowerCamelCase ) self.assertListEqual( tokenizer.tokenize(''' \tHeLLo ! how \n Are yoU ? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] ) def _A ( self: List[Any] ): _a = TransfoXLTokenizer(lower_case=_lowerCamelCase ) _a = '''Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?''' _a = [ '''Hello''', '''(''', '''bracket''', ''')''', '''and''', '''side''', '''@-@''', '''scrolled''', '''[''', '''and''', ''']''', '''Henry''', '''\'s''', '''$''', '''5''', '''@,@''', '''000''', '''with''', '''3''', '''@.@''', '''34''', '''m''', '''.''', '''What''', '''\'s''', '''up''', '''!''', '''?''', ] self.assertListEqual(tokenizer.tokenize(_lowerCamelCase ) , _lowerCamelCase ) self.assertEqual(tokenizer.convert_tokens_to_string(_lowerCamelCase ) , _lowerCamelCase ) def _A ( self: Optional[int] ): _a = self.get_tokenizer() _a = len(_lowerCamelCase ) tokenizer.add_tokens(['''new1''', '''new2'''] ) tokenizer.move_added_token('''new1''' , 1 ) # Check that moved token is not copied (duplicate) self.assertEqual(len(_lowerCamelCase ) , original_len + 2 ) # Check that token is moved to specified id self.assertEqual(tokenizer.encode('''new1''' ) , [1] ) self.assertEqual(tokenizer.decode([1] ) , '''new1''' )
487
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE : Optional[int] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) __SCREAMING_SNAKE_CASE : Optional[int] = { '''do_resize''': True, '''size''': {'''height''': 1_8, '''width''': 1_8}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , _lowerCamelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , **_lowerCamelCase :List[str] ): return BertTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , **_lowerCamelCase :Optional[int] ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE : Tuple = [Image.fromarray(np.moveaxis(_lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : str = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor(do_normalize=_lowerCamelCase , padding_value=1.0 ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : Optional[int] = image_processor(_lowerCamelCase , return_tensors='''np''' ) __SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Any = self.get_image_processor() __SCREAMING_SNAKE_CASE : Any = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Optional[int] = processor(text=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = tokenizer(_lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : int = self.get_tokenizer() __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = '''lower newer''' __SCREAMING_SNAKE_CASE : int = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : int = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(_lowerCamelCase ): processor() def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Dict = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE : Tuple = processor.batch_decode(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.batch_decode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : str = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
674
0
"""simple docstring""" import inspect import os import unittest from dataclasses import dataclass import torch from accelerate import Accelerator, DistributedDataParallelKwargs, GradScalerKwargs from accelerate.state import AcceleratorState from accelerate.test_utils import execute_subprocess_async, require_cuda, require_multi_gpu from accelerate.utils import KwargsHandler @dataclass class UpperCAmelCase_ ( __UpperCAmelCase ): UpperCamelCase =0 UpperCamelCase =False UpperCamelCase =3.0 class UpperCAmelCase_ ( unittest.TestCase ): def _lowerCamelCase ( self ) -> Union[str, Any]: # If no defaults are changed, `to_kwargs` returns an empty dict. self.assertDictEqual(MockClass().to_kwargs() , {} ) self.assertDictEqual(MockClass(a=2 ).to_kwargs() , {'''a''': 2} ) self.assertDictEqual(MockClass(a=2 , b=_lowerCamelCase ).to_kwargs() , {'''a''': 2, '''b''': True} ) self.assertDictEqual(MockClass(a=2 , c=2.2_5 ).to_kwargs() , {'''a''': 2, '''c''': 2.2_5} ) @require_cuda def _lowerCamelCase ( self ) -> List[Any]: # If no defaults are changed, `to_kwargs` returns an empty dict. __lowercase : str = GradScalerKwargs(init_scale=10_24 , growth_factor=2 ) AcceleratorState._reset_state() __lowercase : List[Any] = Accelerator(mixed_precision='''fp16''' , kwargs_handlers=[scaler_handler] ) print(accelerator.use_fpaa ) __lowercase : Union[str, Any] = accelerator.scaler # Check the kwargs have been applied self.assertEqual(scaler._init_scale , 10_24.0 ) self.assertEqual(scaler._growth_factor , 2.0 ) # Check the other values are at the default self.assertEqual(scaler._backoff_factor , 0.5 ) self.assertEqual(scaler._growth_interval , 20_00 ) self.assertEqual(scaler._enabled , _lowerCamelCase ) @require_multi_gpu def _lowerCamelCase ( self ) -> str: __lowercase : str = ['''torchrun''', F"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__ )] execute_subprocess_async(_lowerCamelCase , env=os.environ.copy() ) if __name__ == "__main__": a_ = DistributedDataParallelKwargs(bucket_cap_mb=1_5, find_unused_parameters=True) a_ = Accelerator(kwargs_handlers=[ddp_scaler]) a_ = torch.nn.Linear(1_0_0, 2_0_0) a_ = accelerator.prepare(model) # Check the values changed in kwargs a_ = '' a_ = model.bucket_bytes_cap // (1_0_2_4 * 1_0_2_4) if observed_bucket_cap_map != 1_5: error_msg += F"Kwargs badly passed, should have `15` but found {observed_bucket_cap_map}.\n" if model.find_unused_parameters is not True: error_msg += F"Kwargs badly passed, should have `True` but found {model.find_unused_parameters}.\n" # Check the values of the defaults if model.dim != 0: error_msg += F"Default value not respected, should have `0` but found {model.dim}.\n" if model.broadcast_buffers is not True: error_msg += F"Default value not respected, should have `True` but found {model.broadcast_buffers}.\n" if model.gradient_as_bucket_view is not False: error_msg += F"Default value not respected, should have `False` but found {model.gradient_as_bucket_view}.\n" # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
76
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class snake_case : def __init__( self :Optional[int] , _lowerCamelCase :int , _lowerCamelCase :Any=2 , _lowerCamelCase :List[str]=True , _lowerCamelCase :str=False , _lowerCamelCase :Tuple=1_0 , _lowerCamelCase :str=3 , _lowerCamelCase :str=3_2 * 4 , _lowerCamelCase :Dict=3_2 * 6 , _lowerCamelCase :str=4 , _lowerCamelCase :Any=3_2 , ): __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Tuple = batch_size __SCREAMING_SNAKE_CASE : Optional[Any] = is_training __SCREAMING_SNAKE_CASE : Dict = use_auxiliary_loss __SCREAMING_SNAKE_CASE : List[str] = num_queries __SCREAMING_SNAKE_CASE : Optional[int] = num_channels __SCREAMING_SNAKE_CASE : List[Any] = min_size __SCREAMING_SNAKE_CASE : int = max_size __SCREAMING_SNAKE_CASE : Any = num_labels __SCREAMING_SNAKE_CASE : Union[str, Any] = mask_feature_size def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : str = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowerCamelCase ) > 0.5 ).float() __SCREAMING_SNAKE_CASE : Dict = (torch.rand((self.batch_size, self.num_labels) , device=_lowerCamelCase ) > 0.5).long() __SCREAMING_SNAKE_CASE : str = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=1_2_8 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Any = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = output.encoder_hidden_states __SCREAMING_SNAKE_CASE : int = output.pixel_decoder_hidden_states __SCREAMING_SNAKE_CASE : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , config.decoder_config.decoder_layers ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :str , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any]=False ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = MaskFormerModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : str = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , output_hidden_states=_lowerCamelCase ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerForInstanceSegmentation(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() def comm_check_on_output(_lowerCamelCase :Optional[Any] ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = model( pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () lowerCamelCase__ = ( {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerModelTester(self ) __SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowerCamelCase ) @unittest.skip(reason='''MaskFormer does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): pass @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' ) def SCREAMING_SNAKE_CASE_ ( self :int ): pass @unittest.skip(reason='''MaskFormer is not a generative model''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): pass @unittest.skip(reason='''MaskFormer does not use token embeddings''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): pass @require_torch_multi_gpu @unittest.skip( reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Tuple = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE : List[str] = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): for model_name in ["facebook/maskformer-swin-small-coco"]: __SCREAMING_SNAKE_CASE : Tuple = MaskFormerModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Dict = (self.model_tester.min_size,) * 2 __SCREAMING_SNAKE_CASE : Dict = { '''pixel_values''': torch.randn((2, 3, *size) , device=_lowerCamelCase ), '''mask_labels''': torch.randn((2, 1_0, *size) , device=_lowerCamelCase ), '''class_labels''': torch.zeros(2 , 1_0 , device=_lowerCamelCase ).long(), } __SCREAMING_SNAKE_CASE : Dict = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Dict = model_class(_lowerCamelCase ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = model(**_lowerCamelCase , output_attentions=_lowerCamelCase ) self.assertTrue(outputs.attentions is not None ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : List[Any] = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ).loss loss.backward() def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : Tuple = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Tuple = True __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : str = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't __SCREAMING_SNAKE_CASE : Optional[int] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : int = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_lowerCamelCase ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) _lowerCamelCase = 1e-4 def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @slow class snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self :str ): return ( MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' ) if is_vision_available() else None ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : Tuple = model(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor( [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Any = torch.tensor( [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : str = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Any = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[Any] = [ [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3], [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5], [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2], ] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : List[Any] = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [ [1.65_12e00, -5.25_72e00, -3.35_19e00], [3.61_69e-02, -5.90_25e00, -2.93_13e00], [1.07_66e-04, -7.76_30e00, -5.12_63e00], ] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor __SCREAMING_SNAKE_CASE : str = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[str] = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : int = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : int = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Any = self.default_image_processor __SCREAMING_SNAKE_CASE : int = image_processor( [np.zeros((3, 8_0_0, 1_3_3_3) ), np.zeros((3, 8_0_0, 1_3_3_3) )] , segmentation_maps=[np.zeros((3_8_4, 3_8_4) ).astype(np.floataa ), np.zeros((3_8_4, 3_8_4) ).astype(np.floataa )] , return_tensors='''pt''' , ) __SCREAMING_SNAKE_CASE : Dict = inputs['''pixel_values'''].to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = [el.to(_lowerCamelCase ) for el in inputs['''mask_labels''']] __SCREAMING_SNAKE_CASE : str = [el.to(_lowerCamelCase ) for el in inputs['''class_labels''']] with torch.no_grad(): __SCREAMING_SNAKE_CASE : int = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None )
674
0
from sklearn.metrics import fa_score, matthews_corrcoef import datasets from .record_evaluation import evaluate as evaluate_record lowercase_ : List[str] = '\\n@article{wang2019superglue,\n title={SuperGLUE: A Stickier Benchmark for General-Purpose Language Understanding Systems},\n author={Wang, Alex and Pruksachatkun, Yada and Nangia, Nikita and Singh, Amanpreet and Michael, Julian and Hill, Felix and Levy, Omer and Bowman, Samuel R},\n journal={arXiv preprint arXiv:1905.00537},\n year={2019}\n}\n' lowercase_ : Tuple = '\\nSuperGLUE (https://super.gluebenchmark.com/) is a new benchmark styled after\nGLUE with a new set of more difficult language understanding tasks, improved\nresources, and a new public leaderboard.\n' lowercase_ : Any = '\nCompute SuperGLUE evaluation metric associated to each SuperGLUE dataset.\nArgs:\n predictions: list of predictions to score. Depending on the SuperGlUE subset:\n - for \'record\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'prediction_text\': the predicted answer text\n - for \'multirc\': list of question-answer dictionaries with the following keys:\n - \'idx\': index of the question-answer pair as specified by the dataset\n - \'prediction\': the predicted answer label\n - otherwise: list of predicted labels\n references: list of reference labels. Depending on the SuperGLUE subset:\n - for \'record\': list of question-answers dictionaries with the following keys:\n - \'idx\': index of the question as specified by the dataset\n - \'answers\': list of possible answers\n - otherwise: list of reference labels\nReturns: depending on the SuperGLUE subset:\n - for \'record\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1\': F1 score\n - for \'multirc\':\n - \'exact_match\': Exact match between answer and gold answer\n - \'f1_m\': Per-question macro-F1 score\n - \'f1_a\': Average F1 score over all answers\n - for \'axb\':\n \'matthews_correlation\': Matthew Correlation\n - for \'cb\':\n - \'accuracy\': Accuracy\n - \'f1\': F1 score\n - for all others:\n - \'accuracy\': Accuracy\nExamples:\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'copa\') # any of ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'cb\')\n >>> predictions = [0, 1]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'accuracy\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'record\')\n >>> predictions = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'prediction_text\': \'answer\'}]\n >>> references = [{\'idx\': {\'passage\': 0, \'query\': 0}, \'answers\': [\'answer\', \'another_answer\']}]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'multirc\')\n >>> predictions = [{\'idx\': {\'answer\': 0, \'paragraph\': 0, \'question\': 0}, \'prediction\': 0}, {\'idx\': {\'answer\': 1, \'paragraph\': 2, \'question\': 3}, \'prediction\': 1}]\n >>> references = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 1.0, \'f1_m\': 1.0, \'f1_a\': 1.0}\n\n >>> super_glue_metric = datasets.load_metric(\'super_glue\', \'axb\')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = super_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'matthews_correlation\': 1.0}\n' def A__ ( snake_case_ : Optional[Any] , snake_case_ : List[Any] ): return float((preds == labels).mean() ) def A__ ( snake_case_ : int , snake_case_ : int , snake_case_ : List[Any]="binary" ): SCREAMING_SNAKE_CASE__: Tuple= simple_accuracy(lowercase_ , lowercase_ ) SCREAMING_SNAKE_CASE__: str= float(fa_score(y_true=lowercase_ , y_pred=lowercase_ , average=lowercase_ ) ) return { "accuracy": acc, "f1": fa, } def A__ ( snake_case_ : str , snake_case_ : Union[str, Any] ): SCREAMING_SNAKE_CASE__: Optional[Any]= {} for id_pred, label in zip(lowercase_ , lowercase_ ): SCREAMING_SNAKE_CASE__: Optional[Any]= F'{id_pred["idx"]["paragraph"]}-{id_pred["idx"]["question"]}' SCREAMING_SNAKE_CASE__: str= id_pred['''prediction'''] if question_id in question_map: question_map[question_id].append((pred, label) ) else: SCREAMING_SNAKE_CASE__: Dict= [(pred, label)] SCREAMING_SNAKE_CASE__: int= [], [] for question, preds_labels in question_map.items(): SCREAMING_SNAKE_CASE__: Tuple= zip(*lowercase_ ) SCREAMING_SNAKE_CASE__: List[str]= fa_score(y_true=lowercase_ , y_pred=lowercase_ , average='''macro''' ) fas.append(lowercase_ ) SCREAMING_SNAKE_CASE__: Optional[Any]= int(sum(pred == label for pred, label in preds_labels ) == len(lowercase_ ) ) ems.append(lowercase_ ) SCREAMING_SNAKE_CASE__: Optional[int]= float(sum(lowercase_ ) / len(lowercase_ ) ) SCREAMING_SNAKE_CASE__: List[str]= sum(lowercase_ ) / len(lowercase_ ) SCREAMING_SNAKE_CASE__: List[Any]= float(fa_score(y_true=lowercase_ , y_pred=[id_pred['''prediction'''] for id_pred in ids_preds] ) ) return {"exact_match": em, "f1_m": fa_m, "f1_a": fa_a} @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _lowerCamelCase ( datasets.Metric ): def UpperCamelCase_ ( self ) -> List[str]: if self.config_name not in [ "boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg", ]: raise KeyError( '''You should supply a configuration name selected in ''' '''["boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg",]''' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(self._get_feature_types() ) , codebase_urls=[] , reference_urls=[] , format='''numpy''' if not self.config_name == '''record''' and not self.config_name == '''multirc''' else None , ) def UpperCamelCase_ ( self ) -> Optional[Any]: if self.config_name == "record": return { "predictions": { "idx": { "passage": datasets.Value('''int64''' ), "query": datasets.Value('''int64''' ), }, "prediction_text": datasets.Value('''string''' ), }, "references": { "idx": { "passage": datasets.Value('''int64''' ), "query": datasets.Value('''int64''' ), }, "answers": datasets.Sequence(datasets.Value('''string''' ) ), }, } elif self.config_name == "multirc": return { "predictions": { "idx": { "answer": datasets.Value('''int64''' ), "paragraph": datasets.Value('''int64''' ), "question": datasets.Value('''int64''' ), }, "prediction": datasets.Value('''int64''' ), }, "references": datasets.Value('''int64''' ), } else: return { "predictions": datasets.Value('''int64''' ), "references": datasets.Value('''int64''' ), } def UpperCamelCase_ ( self , lowerCAmelCase , lowerCAmelCase ) -> List[str]: if self.config_name == "axb": return {"matthews_correlation": matthews_corrcoef(_lowerCamelCase , _lowerCamelCase )} elif self.config_name == "cb": return acc_and_fa(_lowerCamelCase , _lowerCamelCase , fa_avg='''macro''' ) elif self.config_name == "record": SCREAMING_SNAKE_CASE__: Optional[int]= [ { '''qas''': [ {'''id''': ref['''idx''']['''query'''], '''answers''': [{'''text''': ans} for ans in ref['''answers''']]} for ref in references ] } ] SCREAMING_SNAKE_CASE__: Dict= {pred['''idx''']['''query''']: pred['''prediction_text'''] for pred in predictions} return evaluate_record(_lowerCamelCase , _lowerCamelCase )[0] elif self.config_name == "multirc": return evaluate_multirc(_lowerCamelCase , _lowerCamelCase ) elif self.config_name in ["copa", "rte", "wic", "wsc", "wsc.fixed", "boolq", "axg"]: return {"accuracy": simple_accuracy(_lowerCamelCase , _lowerCamelCase )} else: raise KeyError( '''You should supply a configuration name selected in ''' '''["boolq", "cb", "copa", "multirc", "record", "rte", "wic", "wsc", "wsc.fixed", "axb", "axg",]''' )
64
"""simple docstring""" import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification _lowerCamelCase = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co _lowerCamelCase = '''main''' # Default branch name _lowerCamelCase = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2''' # One particular commit (not the top of `main`) _lowerCamelCase = '''aaaaaaa''' # This commit does not exist, so we should 404. _lowerCamelCase = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684''' # Sha-1 of config.json on the top of `main`, for checking purposes _lowerCamelCase = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3''' @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Welcome!''' ) yield print('''Bye!''' ) @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Bonjour!''' ) yield print('''Au revoir!''' ) class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): # If the spec is missing, importlib would not be able to import the module dynamically. assert transformers.__spec__ is not None assert importlib.util.find_spec('''transformers''' ) is not None class snake_case ( unittest.TestCase ): @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[int] ): with ContextManagers([] ): print('''Transformers are awesome!''' ) # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , '''Transformers are awesome!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): with ContextManagers([context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Welcome!\nTransformers are awesome!\nBye!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[str] ): with ContextManagers([context_fr(), context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n''' ) @require_torch def SCREAMING_SNAKE_CASE_ ( self :List[str] ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_tf def SCREAMING_SNAKE_CASE_ ( self :int ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_flax def SCREAMING_SNAKE_CASE_ ( self :Dict ): # Flax models don't have labels self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , [] )
674
0
import math import sys def lowercase_ ( _UpperCamelCase ): '''simple docstring''' __lowercase = '''''' try: with open(lowercase_ , '''rb''' ) as binary_file: __lowercase = binary_file.read() for dat in data: __lowercase = F'{dat:08b}' result += curr_byte return result except OSError: print('''File not accessible''' ) sys.exit() def lowercase_ ( _UpperCamelCase ): '''simple docstring''' __lowercase = {'''0''': '''0''', '''1''': '''1'''} __lowercase = '''''', '''''' __lowercase = len(lowercase_ ) for i in range(len(lowercase_ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue __lowercase = lexicon[curr_string] result += last_match_id __lowercase = last_match_id + '''0''' if math.loga(lowercase_ ).is_integer(): __lowercase = {} for curr_key in list(lowercase_ ): __lowercase = lexicon.pop(lowercase_ ) __lowercase = new_lex __lowercase = last_match_id + '''1''' index += 1 __lowercase = '''''' return result def lowercase_ ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' __lowercase = 8 try: with open(lowercase_ , '''wb''' ) as opened_file: __lowercase = [ to_write[i : i + byte_length] for i in range(0 , len(lowercase_ ) , lowercase_ ) ] if len(result_byte_array[-1] ) % byte_length == 0: result_byte_array.append('''10000000''' ) else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1] ) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(lowercase_ , 2 ).to_bytes(1 , byteorder='''big''' ) ) except OSError: print('''File not accessible''' ) sys.exit() def lowercase_ ( _UpperCamelCase ): '''simple docstring''' __lowercase = 0 for letter in data_bits: if letter == "1": break counter += 1 __lowercase = data_bits[counter:] __lowercase = data_bits[counter + 1 :] return data_bits def lowercase_ ( _UpperCamelCase , _UpperCamelCase ): '''simple docstring''' __lowercase = read_file_binary(lowercase_ ) __lowercase = remove_prefix(lowercase_ ) __lowercase = decompress_data(lowercase_ ) write_file_binary(lowercase_ , lowercase_ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
639
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class snake_case ( unittest.TestCase ): def __init__( self :List[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Tuple=7 , _lowerCamelCase :Dict=3 , _lowerCamelCase :Optional[Any]=3_0 , _lowerCamelCase :List[str]=4_0_0 , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :List[Any]=True , _lowerCamelCase :Any=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=True , _lowerCamelCase :str=1 / 2_5_5 , _lowerCamelCase :Union[str, Any]=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Dict = batch_size __SCREAMING_SNAKE_CASE : str = num_channels __SCREAMING_SNAKE_CASE : Union[str, Any] = min_resolution __SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution __SCREAMING_SNAKE_CASE : Tuple = do_resize __SCREAMING_SNAKE_CASE : Union[str, Any] = size __SCREAMING_SNAKE_CASE : int = do_normalize __SCREAMING_SNAKE_CASE : List[Any] = image_mean __SCREAMING_SNAKE_CASE : Tuple = image_std __SCREAMING_SNAKE_CASE : Dict = do_rescale __SCREAMING_SNAKE_CASE : Optional[int] = rescale_factor __SCREAMING_SNAKE_CASE : List[Any] = do_pad def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :List[Any]=False ): if not batched: __SCREAMING_SNAKE_CASE : str = image_inputs[0] if isinstance(_lowerCamelCase , Image.Image ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = image.size else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = image.shape[1], image.shape[2] if w < h: __SCREAMING_SNAKE_CASE : str = int(self.size['''shortest_edge'''] * h / w ) __SCREAMING_SNAKE_CASE : int = self.size['''shortest_edge'''] elif w > h: __SCREAMING_SNAKE_CASE : Optional[Any] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : int = int(self.size['''shortest_edge'''] * w / h ) else: __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] else: __SCREAMING_SNAKE_CASE : Optional[Any] = [] for image in image_inputs: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __SCREAMING_SNAKE_CASE : Optional[int] = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0] __SCREAMING_SNAKE_CASE : int = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = YolosImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=_lowerCamelCase ) self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2, '''longest_edge''': 8_4} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): pass def SCREAMING_SNAKE_CASE_ ( self :int ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : str = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : List[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Any ): # Initialize image_processing __SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : Optional[int] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): # Initialize image_processings __SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(do_resize=_lowerCamelCase , do_normalize=_lowerCamelCase , do_rescale=_lowerCamelCase ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a.pad(_lowerCamelCase , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a(_lowerCamelCase , return_tensors='''pt''' ) self.assertTrue( torch.allclose(encoded_images_with_method['''pixel_values'''] , encoded_images['''pixel_values'''] , atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): # prepare image and target __SCREAMING_SNAKE_CASE : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Tuple = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''image_id''': 3_9_7_6_9, '''annotations''': target} # encode them __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessor.from_pretrained('''hustvl/yolos-small''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : Optional[int] = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Dict = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify orig_size __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # prepare image, target and masks_path __SCREAMING_SNAKE_CASE : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Dict = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9_7_6_9, '''segments_info''': target} __SCREAMING_SNAKE_CASE : Optional[int] = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them __SCREAMING_SNAKE_CASE : Any = YolosImageProcessor(format='''coco_panoptic''' ) __SCREAMING_SNAKE_CASE : Dict = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : str = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Any = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Dict = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify masks __SCREAMING_SNAKE_CASE : Optional[Any] = 8_2_2_8_7_3 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _lowerCamelCase ) # verify orig_size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : Any = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
674
0
from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase_ = logging.get_logger(__name__) UpperCAmelCase_ = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class __magic_name__ ( __UpperCAmelCase ): """simple docstring""" lowerCAmelCase : Optional[int] = '''roc_bert''' def __init__( self : Union[str, Any] , _lowercase : Any=30_522 , _lowercase : str=768 , _lowercase : Optional[Any]=12 , _lowercase : List[str]=12 , _lowercase : str=3_072 , _lowercase : Tuple="gelu" , _lowercase : List[Any]=0.1 , _lowercase : List[str]=0.1 , _lowercase : Optional[int]=512 , _lowercase : Dict=2 , _lowercase : Any=0.02 , _lowercase : Optional[int]=1E-12 , _lowercase : str=True , _lowercase : Any=0 , _lowercase : List[str]="absolute" , _lowercase : List[Any]=None , _lowercase : Any=True , _lowercase : Union[str, Any]=True , _lowercase : str=768 , _lowercase : Union[str, Any]=910 , _lowercase : List[Any]=512 , _lowercase : Optional[int]=24_858 , _lowercase : Union[str, Any]=True , **_lowercase : str , ): """simple docstring""" _UpperCamelCase: List[str] = vocab_size _UpperCamelCase: int = max_position_embeddings _UpperCamelCase: List[str] = hidden_size _UpperCamelCase: str = num_hidden_layers _UpperCamelCase: int = num_attention_heads _UpperCamelCase: Any = intermediate_size _UpperCamelCase: Optional[int] = hidden_act _UpperCamelCase: List[Any] = hidden_dropout_prob _UpperCamelCase: Optional[Any] = attention_probs_dropout_prob _UpperCamelCase: Union[str, Any] = initializer_range _UpperCamelCase: Union[str, Any] = type_vocab_size _UpperCamelCase: List[str] = layer_norm_eps _UpperCamelCase: Optional[int] = use_cache _UpperCamelCase: str = enable_pronunciation _UpperCamelCase: List[str] = enable_shape _UpperCamelCase: Tuple = pronunciation_embed_dim _UpperCamelCase: Optional[Any] = pronunciation_vocab_size _UpperCamelCase: str = shape_embed_dim _UpperCamelCase: Union[str, Any] = shape_vocab_size _UpperCamelCase: Tuple = concat_input _UpperCamelCase: Union[str, Any] = position_embedding_type _UpperCamelCase: str = classifier_dropout super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase )
271
"""simple docstring""" from __future__ import annotations def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) return len(lowercase_ ) == 9 and set(lowercase_ ) == set('''123456789''' ) def lowerCAmelCase_ ( ): '''simple docstring''' for base_num in range(9999 , 4999 , -1 ): __SCREAMING_SNAKE_CASE : List[str] = 10_0002 * base_num if is_9_pandigital(lowercase_ ): return candidate for base_num in range(333 , 99 , -1 ): __SCREAMING_SNAKE_CASE : List[Any] = 100_2003 * base_num if is_9_pandigital(lowercase_ ): return candidate return None if __name__ == "__main__": print(f'{solution() = }')
674
0
import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDict from datasets.iterable_dataset import IterableDataset from datasets.load import dataset_module_factory, import_main_class from datasets.utils.file_utils import cached_path _snake_case = [ {'''dataset''': '''wikipedia''', '''config_name''': '''20220301.de'''}, {'''dataset''': '''wikipedia''', '''config_name''': '''20220301.en'''}, {'''dataset''': '''wikipedia''', '''config_name''': '''20220301.fr'''}, {'''dataset''': '''wikipedia''', '''config_name''': '''20220301.frr'''}, {'''dataset''': '''wikipedia''', '''config_name''': '''20220301.it'''}, {'''dataset''': '''wikipedia''', '''config_name''': '''20220301.simple'''}, {'''dataset''': '''snli''', '''config_name''': '''plain_text'''}, {'''dataset''': '''eli5''', '''config_name''': '''LFQA_reddit'''}, {'''dataset''': '''wiki40b''', '''config_name''': '''en'''}, {'''dataset''': '''wiki_dpr''', '''config_name''': '''psgs_w100.nq.compressed'''}, {'''dataset''': '''wiki_dpr''', '''config_name''': '''psgs_w100.nq.no_index'''}, {'''dataset''': '''wiki_dpr''', '''config_name''': '''psgs_w100.multiset.no_index'''}, {'''dataset''': '''natural_questions''', '''config_name''': '''default'''}, ] def __lowerCamelCase ( _lowercase=True ) -> Optional[int]: if with_config: return [ { "testcase_name": d["dataset"] + "/" + d["config_name"], "dataset": d["dataset"], "config_name": d["config_name"], } for d in DATASETS_ON_HF_GCP ] else: return [ {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP} ] @parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=__UpperCAmelCase ) ) class _lowerCAmelCase ( __UpperCAmelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : str =None SCREAMING_SNAKE_CASE_ : Optional[Any] =None def __lowerCAmelCase ( self : Dict , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Tuple ): """simple docstring""" with TemporaryDirectory() as tmp_dir: UpperCamelCase = dataset_module_factory(_lowerCamelCase , cache_dir=_lowerCamelCase ) UpperCamelCase = import_main_class(dataset_module.module_path , dataset=_lowerCamelCase ) UpperCamelCase = builder_cls( cache_dir=_lowerCamelCase , config_name=_lowerCamelCase , hash=dataset_module.hash , ) UpperCamelCase = '''/'''.join( [ HF_GCP_BASE_URL, builder_instance._relative_data_dir(with_hash=_lowerCamelCase ).replace(os.sep , '/' ), config.DATASET_INFO_FILENAME, ] ) UpperCamelCase = cached_path(_lowerCamelCase , cache_dir=_lowerCamelCase ) self.assertTrue(os.path.exists(_lowerCamelCase ) ) @pytest.mark.integration def __lowerCamelCase ( _lowercase ) -> Optional[Any]: UpperCamelCase = tmp_path_factory.mktemp('test_hf_gcp' ) / '''test_wikipedia_simple''' UpperCamelCase = dataset_module_factory('wikipedia' , cache_dir=lowercase_ ) UpperCamelCase = import_main_class(dataset_module.module_path ) UpperCamelCase = builder_cls( cache_dir=lowercase_ , config_name='20220301.frr' , hash=dataset_module.hash , ) # use the HF cloud storage, not the original download_and_prepare that uses apache-beam UpperCamelCase = None builder_instance.download_and_prepare() UpperCamelCase = builder_instance.as_dataset() assert ds @pytest.mark.integration def __lowerCamelCase ( _lowercase ) -> str: UpperCamelCase = dataset_module_factory('wikipedia' , cache_dir=lowercase_ ) UpperCamelCase = import_main_class(dataset_module.module_path , dataset=lowercase_ ) UpperCamelCase = builder_cls( cache_dir=lowercase_ , config_name='20220301.frr' , hash=dataset_module.hash , ) UpperCamelCase = builder_instance.as_streaming_dataset() assert ds assert isinstance(lowercase_ , lowercase_ ) assert "train" in ds assert isinstance(ds['train'] , lowercase_ ) assert next(iter(ds['train'] ) )
282
"""simple docstring""" import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Tuple = 0 def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Optional[Any] = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Dict = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : str = CLIPConfig() # Create a dummy config file with image_proceesor_type __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ).to_dict() config_dict.pop('''image_processor_type''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor(**_lowerCamelCase ) # save in new folder model_config.save_pretrained(_lowerCamelCase ) config.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) # make sure private variable is not incorrectly saved __SCREAMING_SNAKE_CASE : Tuple = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): with self.assertRaisesRegex( _lowerCamelCase , '''clip-base is not a local folder and is not a valid model identifier''' ): __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained('''clip-base''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): with self.assertRaisesRegex( _lowerCamelCase , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(_lowerCamelCase , revision='''aaaaaa''' ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with self.assertRaisesRegex( _lowerCamelCase , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase , trust_remote_code=_lowerCamelCase ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_lowerCamelCase ): AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = CustomImageProcessor.from_pretrained(_lowerCamelCase ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def SCREAMING_SNAKE_CASE_ ( self :Dict ): class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = True try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # If remote code is not set, the default is to use local __SCREAMING_SNAKE_CASE : List[str] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. __SCREAMING_SNAKE_CASE : str = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(_lowerCamelCase , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
674
0
"""simple docstring""" import unittest import numpy as np from transformers import BertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_flax_available(): from transformers.models.bert.modeling_flax_bert import ( FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForNextSentencePrediction, FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertModel, ) class __lowercase( unittest.TestCase ): '''simple docstring''' def __init__( self , __a , __a=13 , __a=7 , __a=True , __a=True , __a=True , __a=True , __a=99 , __a=32 , __a=5 , __a=4 , __a=37 , __a="gelu" , __a=0.1 , __a=0.1 , __a=512 , __a=16 , __a=2 , __a=0.02 , __a=4 , ): __lowerCamelCase : List[Any] = parent __lowerCamelCase : int = batch_size __lowerCamelCase : int = seq_length __lowerCamelCase : Optional[int] = is_training __lowerCamelCase : List[Any] = use_attention_mask __lowerCamelCase : List[Any] = use_token_type_ids __lowerCamelCase : List[str] = use_labels __lowerCamelCase : Optional[Any] = vocab_size __lowerCamelCase : Union[str, Any] = hidden_size __lowerCamelCase : Any = num_hidden_layers __lowerCamelCase : str = num_attention_heads __lowerCamelCase : str = intermediate_size __lowerCamelCase : List[str] = hidden_act __lowerCamelCase : Tuple = hidden_dropout_prob __lowerCamelCase : Any = attention_probs_dropout_prob __lowerCamelCase : Union[str, Any] = max_position_embeddings __lowerCamelCase : str = type_vocab_size __lowerCamelCase : Union[str, Any] = type_sequence_label_size __lowerCamelCase : Any = initializer_range __lowerCamelCase : int = num_choices def snake_case_ ( self ): __lowerCamelCase : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCamelCase : Union[str, Any] = None if self.use_attention_mask: __lowerCamelCase : Optional[int] = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCamelCase : Optional[Any] = None if self.use_token_type_ids: __lowerCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowerCamelCase : Any = BertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=_lowerCamelCase , initializer_range=self.initializer_range , ) return config, input_ids, token_type_ids, attention_mask def snake_case_ ( self ): __lowerCamelCase : int = self.prepare_config_and_inputs() __lowerCamelCase : Optional[int] = config_and_inputs __lowerCamelCase : Any = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask} return config, inputs_dict def snake_case_ ( self ): __lowerCamelCase : Any = self.prepare_config_and_inputs() __lowerCamelCase : Union[str, Any] = config_and_inputs __lowerCamelCase : int = True __lowerCamelCase : Tuple = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) __lowerCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, attention_mask, encoder_hidden_states, encoder_attention_mask, ) @require_flax class __lowercase( __UpperCAmelCase , unittest.TestCase ): '''simple docstring''' __a : Optional[Any] = True __a : Dict = ( ( FlaxBertModel, FlaxBertForPreTraining, FlaxBertForMaskedLM, FlaxBertForMultipleChoice, FlaxBertForQuestionAnswering, FlaxBertForNextSentencePrediction, FlaxBertForSequenceClassification, FlaxBertForTokenClassification, FlaxBertForQuestionAnswering, ) if is_flax_available() else () ) def snake_case_ ( self ): __lowerCamelCase : Union[str, Any] = FlaxBertModelTester(self ) @slow def snake_case_ ( self ): # Only check this for base model, not necessary for all model classes. # This will also help speed-up tests. __lowerCamelCase : int = FlaxBertModel.from_pretrained('bert-base-cased' ) __lowerCamelCase : Tuple = model(np.ones((1, 1) ) ) self.assertIsNotNone(_lowerCamelCase )
594
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case ( __UpperCAmelCase ): pass class snake_case : def __init__( self :List[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Any = data __SCREAMING_SNAKE_CASE : Node | None = None def __iter__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : List[str] = self __SCREAMING_SNAKE_CASE : List[str] = [] while node: if node in visited: raise ContainsLoopError visited.append(_lowerCamelCase ) yield node.data __SCREAMING_SNAKE_CASE : List[str] = node.next_node @property def SCREAMING_SNAKE_CASE_ ( self :Any ): try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": _lowerCamelCase = Node(1) _lowerCamelCase = Node(2) _lowerCamelCase = Node(3) _lowerCamelCase = Node(4) print(root_node.has_loop) # False _lowerCamelCase = root_node.next_node print(root_node.has_loop) # True _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) print(root_node.has_loop) # False _lowerCamelCase = Node(1) print(root_node.has_loop) # False
674
0
def _lowercase ( SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Optional[int] ): """simple docstring""" UpperCamelCase = '''''' for i in table: res += inp[i - 1] return res def _lowercase ( SCREAMING_SNAKE_CASE_ : str ): """simple docstring""" return data[1:] + data[0] def _lowercase ( SCREAMING_SNAKE_CASE_ : Optional[int] , SCREAMING_SNAKE_CASE_ : List[Any] ): """simple docstring""" UpperCamelCase = '''''' for i in range(len(lowercase_ ) ): if a[i] == b[i]: res += "0" else: res += "1" return res def _lowercase ( SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : Optional[Any] ): """simple docstring""" UpperCamelCase = int("""0b""" + data[0] + data[-1] , 2 ) UpperCamelCase = int("""0b""" + data[1:3] , 2 ) return bin(s[row][col] )[2:] def _lowercase ( SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Optional[Any] , SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Any ): """simple docstring""" UpperCamelCase = message[:4] UpperCamelCase = message[4:] UpperCamelCase = apply_table(lowercase_ , lowercase_ ) UpperCamelCase = xor(lowercase_ , lowercase_ ) UpperCamelCase = apply_sbox(lowercase_ , temp[:4] ) # noqa: E741 UpperCamelCase = apply_sbox(lowercase_ , temp[4:] ) UpperCamelCase = '''0''' * (2 - len(lowercase_ )) + l # noqa: E741 UpperCamelCase = '''0''' * (2 - len(lowercase_ )) + r UpperCamelCase = apply_table(l + r , lowercase_ ) UpperCamelCase = xor(lowercase_ , lowercase_ ) return temp + right if __name__ == "__main__": __snake_case = input("Enter 10 bit key: ") __snake_case = input("Enter 8 bit message: ") __snake_case = [6, 3, 7, 4, 8, 5, 10, 9] __snake_case = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6] __snake_case = [2, 4, 3, 1] __snake_case = [2, 6, 3, 1, 4, 8, 5, 7] __snake_case = [4, 1, 3, 5, 7, 2, 8, 6] __snake_case = [4, 1, 2, 3, 2, 3, 4, 1] __snake_case = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]] __snake_case = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]] # key generation __snake_case = apply_table(key, paa_table) __snake_case = temp[:5] __snake_case = temp[5:] __snake_case = left_shift(left) __snake_case = left_shift(right) __snake_case = apply_table(left + right, pa_table) __snake_case = left_shift(left) __snake_case = left_shift(right) __snake_case = left_shift(left) __snake_case = left_shift(right) __snake_case = apply_table(left + right, pa_table) # encryption __snake_case = apply_table(message, IP) __snake_case = function(expansion, sa, sa, keya, temp) __snake_case = temp[4:] + temp[:4] __snake_case = function(expansion, sa, sa, keya, temp) __snake_case = apply_table(temp, IP_inv) print("Cipher text is:", CT) # decryption __snake_case = apply_table(CT, IP) __snake_case = function(expansion, sa, sa, keya, temp) __snake_case = temp[4:] + temp[:4] __snake_case = function(expansion, sa, sa, keya, temp) __snake_case = apply_table(temp, IP_inv) print("Plain text after decypting is:", PT)
386
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''roc_bert''' def __init__( self :Union[str, Any] , _lowerCamelCase :Any=3_0_5_2_2 , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Optional[Any]=1_2 , _lowerCamelCase :List[str]=1_2 , _lowerCamelCase :str=3_0_7_2 , _lowerCamelCase :Tuple="gelu" , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :List[str]=0.1 , _lowerCamelCase :Optional[int]=5_1_2 , _lowerCamelCase :Dict=2 , _lowerCamelCase :Any=0.0_2 , _lowerCamelCase :Optional[int]=1e-12 , _lowerCamelCase :str=True , _lowerCamelCase :Any=0 , _lowerCamelCase :List[str]="absolute" , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Any=True , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Union[str, Any]=9_1_0 , _lowerCamelCase :List[Any]=5_1_2 , _lowerCamelCase :Optional[int]=2_4_8_5_8 , _lowerCamelCase :Union[str, Any]=True , **_lowerCamelCase :str , ): __SCREAMING_SNAKE_CASE : List[str] = vocab_size __SCREAMING_SNAKE_CASE : int = max_position_embeddings __SCREAMING_SNAKE_CASE : List[str] = hidden_size __SCREAMING_SNAKE_CASE : str = num_hidden_layers __SCREAMING_SNAKE_CASE : int = num_attention_heads __SCREAMING_SNAKE_CASE : Any = intermediate_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_act __SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range __SCREAMING_SNAKE_CASE : Union[str, Any] = type_vocab_size __SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps __SCREAMING_SNAKE_CASE : Optional[int] = use_cache __SCREAMING_SNAKE_CASE : str = enable_pronunciation __SCREAMING_SNAKE_CASE : List[str] = enable_shape __SCREAMING_SNAKE_CASE : Tuple = pronunciation_embed_dim __SCREAMING_SNAKE_CASE : Optional[Any] = pronunciation_vocab_size __SCREAMING_SNAKE_CASE : str = shape_embed_dim __SCREAMING_SNAKE_CASE : Union[str, Any] = shape_vocab_size __SCREAMING_SNAKE_CASE : Tuple = concat_input __SCREAMING_SNAKE_CASE : Union[str, Any] = position_embedding_type __SCREAMING_SNAKE_CASE : str = classifier_dropout super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase )
674
0
import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DetrImageProcessor class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): """simple docstring""" def __init__( self : Optional[int] , lowerCAmelCase : Any , lowerCAmelCase : Dict=7 , lowerCAmelCase : Tuple=3 , lowerCAmelCase : List[Any]=30 , lowerCAmelCase : List[str]=400 , lowerCAmelCase : Any=True , lowerCAmelCase : str=None , lowerCAmelCase : List[Any]=True , lowerCAmelCase : List[Any]=1 / 255 , lowerCAmelCase : Dict=True , lowerCAmelCase : Any=[0.5, 0.5, 0.5] , lowerCAmelCase : int=[0.5, 0.5, 0.5] , lowerCAmelCase : Union[str, Any]=True , ) -> Optional[int]: """simple docstring""" __UpperCamelCase : str = size if size is not None else {'''shortest_edge''': 18, '''longest_edge''': 1333} __UpperCamelCase : Dict = parent __UpperCamelCase : Dict = batch_size __UpperCamelCase : int = num_channels __UpperCamelCase : int = min_resolution __UpperCamelCase : int = max_resolution __UpperCamelCase : Optional[int] = do_resize __UpperCamelCase : List[str] = size __UpperCamelCase : Dict = do_rescale __UpperCamelCase : List[str] = rescale_factor __UpperCamelCase : Tuple = do_normalize __UpperCamelCase : List[Any] = image_mean __UpperCamelCase : str = image_std __UpperCamelCase : List[str] = do_pad def lowerCamelCase__ ( self : str ) -> List[Any]: """simple docstring""" return { "do_resize": self.do_resize, "size": self.size, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_pad": self.do_pad, } def lowerCamelCase__ ( self : Optional[Any] , lowerCAmelCase : int , lowerCAmelCase : Union[str, Any]=False ) -> int: """simple docstring""" if not batched: __UpperCamelCase : Optional[int] = image_inputs[0] if isinstance(_lowerCamelCase , Image.Image ): __UpperCamelCase : Tuple = image.size else: __UpperCamelCase : Any = image.shape[1], image.shape[2] if w < h: __UpperCamelCase : Optional[int] = int(self.size["""shortest_edge"""] * h / w ) __UpperCamelCase : Dict = self.size['''shortest_edge'''] elif w > h: __UpperCamelCase : Tuple = self.size['''shortest_edge'''] __UpperCamelCase : Optional[Any] = int(self.size["""shortest_edge"""] * w / h ) else: __UpperCamelCase : List[str] = self.size['''shortest_edge'''] __UpperCamelCase : List[Any] = self.size['''shortest_edge'''] else: __UpperCamelCase : Optional[int] = [] for image in image_inputs: __UpperCamelCase : Optional[int] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __UpperCamelCase : Optional[int] = max(_lowerCamelCase , key=lambda lowerCAmelCase : item[0] )[0] __UpperCamelCase : Any = max(_lowerCamelCase , key=lambda lowerCAmelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class SCREAMING_SNAKE_CASE_ ( __UpperCAmelCase , unittest.TestCase ): """simple docstring""" __magic_name__ : Tuple = DetrImageProcessor if is_vision_available() else None def lowerCamelCase__ ( self : Optional[Any] ) -> Optional[Any]: """simple docstring""" __UpperCamelCase : Tuple = DetrImageProcessingTester(self ) @property def lowerCamelCase__ ( self : Union[str, Any] ) -> List[str]: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def lowerCamelCase__ ( self : Union[str, Any] ) -> Optional[Any]: """simple docstring""" __UpperCamelCase : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , """image_mean""" ) ) self.assertTrue(hasattr(_lowerCamelCase , """image_std""" ) ) self.assertTrue(hasattr(_lowerCamelCase , """do_normalize""" ) ) self.assertTrue(hasattr(_lowerCamelCase , """do_rescale""" ) ) self.assertTrue(hasattr(_lowerCamelCase , """rescale_factor""" ) ) self.assertTrue(hasattr(_lowerCamelCase , """do_resize""" ) ) self.assertTrue(hasattr(_lowerCamelCase , """size""" ) ) self.assertTrue(hasattr(_lowerCamelCase , """do_pad""" ) ) def lowerCamelCase__ ( self : int ) -> Dict: """simple docstring""" __UpperCamelCase : int = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""shortest_edge""": 18, """longest_edge""": 1333} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) __UpperCamelCase : int = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=_lowerCamelCase ) self.assertEqual(image_processor.size , {"""shortest_edge""": 42, """longest_edge""": 84} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) def lowerCamelCase__ ( self : Dict ) -> Tuple: """simple docstring""" pass def lowerCamelCase__ ( self : Optional[int] ) -> List[str]: """simple docstring""" __UpperCamelCase : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __UpperCamelCase : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __UpperCamelCase : Any = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values __UpperCamelCase : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __UpperCamelCase : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) __UpperCamelCase : Union[str, Any] = image_processing(_lowerCamelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def lowerCamelCase__ ( self : int ) -> List[Any]: """simple docstring""" __UpperCamelCase : int = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __UpperCamelCase : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __UpperCamelCase : List[str] = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values __UpperCamelCase : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __UpperCamelCase : int = image_processing(_lowerCamelCase , return_tensors="""pt""" ).pixel_values __UpperCamelCase : Optional[int] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def lowerCamelCase__ ( self : str ) -> Optional[Any]: """simple docstring""" __UpperCamelCase : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __UpperCamelCase : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __UpperCamelCase : Dict = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values __UpperCamelCase : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __UpperCamelCase : Tuple = image_processing(_lowerCamelCase , return_tensors="""pt""" ).pixel_values __UpperCamelCase : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def lowerCamelCase__ ( self : Union[str, Any] ) -> Tuple: """simple docstring""" __UpperCamelCase : Union[str, Any] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) with open("""./tests/fixtures/tests_samples/COCO/coco_annotations.txt""" , """r""" ) as f: __UpperCamelCase : Tuple = json.loads(f.read() ) __UpperCamelCase : Any = {'''image_id''': 39769, '''annotations''': target} # encode them __UpperCamelCase : str = DetrImageProcessor.from_pretrained("""facebook/detr-resnet-50""" ) __UpperCamelCase : List[Any] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors="""pt""" ) # verify pixel values __UpperCamelCase : Optional[int] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["""pixel_values"""].shape , _lowerCamelCase ) __UpperCamelCase : int = torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , _lowerCamelCase , atol=1E-4 ) ) # verify area __UpperCamelCase : Optional[int] = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , _lowerCamelCase ) ) # verify boxes __UpperCamelCase : str = torch.Size([6, 4] ) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , _lowerCamelCase ) __UpperCamelCase : List[str] = torch.tensor([0.55_03, 0.27_65, 0.06_04, 0.22_15] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , _lowerCamelCase , atol=1E-3 ) ) # verify image_id __UpperCamelCase : str = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , _lowerCamelCase ) ) # verify is_crowd __UpperCamelCase : List[str] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , _lowerCamelCase ) ) # verify class_labels __UpperCamelCase : List[str] = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , _lowerCamelCase ) ) # verify orig_size __UpperCamelCase : Dict = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , _lowerCamelCase ) ) # verify size __UpperCamelCase : int = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , _lowerCamelCase ) ) @slow def lowerCamelCase__ ( self : List[str] ) -> Optional[int]: """simple docstring""" __UpperCamelCase : Dict = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) with open("""./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt""" , """r""" ) as f: __UpperCamelCase : int = json.loads(f.read() ) __UpperCamelCase : Dict = {'''file_name''': '''000000039769.png''', '''image_id''': 39769, '''segments_info''': target} __UpperCamelCase : Tuple = pathlib.Path("""./tests/fixtures/tests_samples/COCO/coco_panoptic""" ) # encode them __UpperCamelCase : Any = DetrImageProcessor.from_pretrained("""facebook/detr-resnet-50-panoptic""" ) __UpperCamelCase : Union[str, Any] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors="""pt""" ) # verify pixel values __UpperCamelCase : Optional[Any] = torch.Size([1, 3, 800, 1066] ) self.assertEqual(encoding["""pixel_values"""].shape , _lowerCamelCase ) __UpperCamelCase : Any = torch.tensor([0.27_96, 0.31_38, 0.34_81] ) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , _lowerCamelCase , atol=1E-4 ) ) # verify area __UpperCamelCase : Tuple = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , _lowerCamelCase ) ) # verify boxes __UpperCamelCase : Tuple = torch.Size([6, 4] ) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , _lowerCamelCase ) __UpperCamelCase : Union[str, Any] = torch.tensor([0.26_25, 0.54_37, 0.46_88, 0.86_25] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , _lowerCamelCase , atol=1E-3 ) ) # verify image_id __UpperCamelCase : Dict = torch.tensor([39769] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , _lowerCamelCase ) ) # verify is_crowd __UpperCamelCase : Tuple = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , _lowerCamelCase ) ) # verify class_labels __UpperCamelCase : str = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , _lowerCamelCase ) ) # verify masks __UpperCamelCase : Union[str, Any] = 822873 self.assertEqual(encoding["""labels"""][0]["""masks"""].sum().item() , _lowerCamelCase ) # verify orig_size __UpperCamelCase : List[Any] = torch.tensor([480, 640] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , _lowerCamelCase ) ) # verify size __UpperCamelCase : str = torch.tensor([800, 1066] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , _lowerCamelCase ) )
279
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : Tuple , lowercase_ : Optional[Any]=True , lowercase_ : Any="pt" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''add_prefix_space''': True} if isinstance(lowercase_ , lowercase_ ) and not line.startswith(''' ''' ) else {} __SCREAMING_SNAKE_CASE : Optional[int] = padding_side return tokenizer( [line] , max_length=lowercase_ , padding='''max_length''' if pad_to_max_length else None , truncation=lowercase_ , return_tensors=lowercase_ , add_special_tokens=lowercase_ , **lowercase_ , ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : Tuple , lowercase_ : List[Any]=None , ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = input_ids.ne(lowercase_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class snake_case ( __UpperCAmelCase ): def __init__( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :Any="train" , _lowerCamelCase :str=None , _lowerCamelCase :Optional[Any]=None , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Tuple="" , ): super().__init__() __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ).joinpath(type_path + '''.source''' ) __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ).joinpath(type_path + '''.target''' ) __SCREAMING_SNAKE_CASE : Any = self.get_char_lens(self.src_file ) __SCREAMING_SNAKE_CASE : List[str] = max_source_length __SCREAMING_SNAKE_CASE : Dict = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' __SCREAMING_SNAKE_CASE : Dict = tokenizer __SCREAMING_SNAKE_CASE : Union[str, Any] = prefix if n_obs is not None: __SCREAMING_SNAKE_CASE : Any = self.src_lens[:n_obs] __SCREAMING_SNAKE_CASE : List[str] = src_lang __SCREAMING_SNAKE_CASE : str = tgt_lang def __len__( self :int ): return len(self.src_lens ) def __getitem__( self :Optional[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = index + 1 # linecache starts at 1 __SCREAMING_SNAKE_CASE : Any = self.prefix + linecache.getline(str(self.src_file ) , _lowerCamelCase ).rstrip('''\n''' ) __SCREAMING_SNAKE_CASE : Dict = linecache.getline(str(self.tgt_file ) , _lowerCamelCase ).rstrip('''\n''' ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , _lowerCamelCase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right __SCREAMING_SNAKE_CASE : Dict = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.generator if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_source_length , '''right''' ) __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_target_length , '''right''' ) __SCREAMING_SNAKE_CASE : Any = source_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Any = target_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Dict = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :Any ): return [len(_lowerCamelCase ) for x in Path(_lowerCamelCase ).open().readlines()] def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : int = torch.stack([x['''input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = torch.stack([x['''attention_mask'''] for x in batch] ) __SCREAMING_SNAKE_CASE : int = torch.stack([x['''decoder_input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : List[str] = trim_batch(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = trim_batch(_lowerCamelCase , _lowerCamelCase , attention_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch _lowerCamelCase = getLogger(__name__) def lowerCAmelCase_ ( lowercase_ : List[List] ): '''simple docstring''' return list(itertools.chain.from_iterable(lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = get_git_info() save_json(lowercase_ , os.path.join(lowercase_ , '''git_log.json''' ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Optional[int] , lowercase_ : str=4 , **lowercase_ : List[str] ): '''simple docstring''' with open(lowercase_ , '''w''' ) as f: json.dump(lowercase_ , lowercase_ , indent=lowercase_ , **lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Union[str, Any] ): '''simple docstring''' with open(lowercase_ ) as f: return json.load(lowercase_ ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = git.Repo(search_parent_directories=lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = { '''repo_id''': str(lowercase_ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : Iterable ): '''simple docstring''' return list(map(lowercase_ , lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Any ): '''simple docstring''' with open(lowercase_ , '''wb''' ) as f: return pickle.dump(lowercase_ , lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' def remove_articles(lowercase_ : Dict ): return re.sub(r'''\b(a|an|the)\b''' , ''' ''' , lowercase_ ) def white_space_fix(lowercase_ : Optional[int] ): return " ".join(text.split() ) def remove_punc(lowercase_ : Any ): __SCREAMING_SNAKE_CASE : Optional[int] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowercase_ : int ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowercase_ ) ) ) ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Tuple = Counter(lowercase_ ) & Counter(lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = sum(common.values() ) if num_same == 0: return 0 __SCREAMING_SNAKE_CASE : Any = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[int] = (2 * precision * recall) / (precision + recall) return fa def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Union[str, Any] ): '''simple docstring''' return normalize_answer(lowercase_ ) == normalize_answer(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' assert len(lowercase_ ) == len(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for hypo, pred in zip(lowercase_ , lowercase_ ): em += exact_match_score(lowercase_ , lowercase_ ) if len(lowercase_ ) > 0: em /= len(lowercase_ ) return {"em": em} def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' return model_prefix.startswith('''rag''' ) def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead __SCREAMING_SNAKE_CASE : Any = '''dropout_rate''' for p in extra_params: if getattr(lowercase_ , lowercase_ , lowercase_ ): if not hasattr(lowercase_ , lowercase_ ) and not hasattr(lowercase_ , equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(lowercase_ ) ) delattr(lowercase_ , lowercase_ ) continue __SCREAMING_SNAKE_CASE : Optional[int] = p if hasattr(lowercase_ , lowercase_ ) else equivalent_param[p] setattr(lowercase_ , lowercase_ , getattr(lowercase_ , lowercase_ ) ) delattr(lowercase_ , lowercase_ ) return hparams, config
674
0
import logging import os from logging import ( CRITICAL, # NOQA DEBUG, # NOQA ERROR, # NOQA FATAL, # NOQA INFO, # NOQA NOTSET, # NOQA WARN, # NOQA WARNING, # NOQA ) from typing import Optional from tqdm import auto as tqdm_lib __lowerCAmelCase = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL, } __lowerCAmelCase = logging.WARNING def a ( ) ->Any: '''simple docstring''' SCREAMING_SNAKE_CASE = os.getenv('''DATASETS_VERBOSITY''' , lowercase_ ) if env_level_str: if env_level_str in log_levels: return log_levels[env_level_str] else: logging.getLogger().warning( F"""Unknown option DATASETS_VERBOSITY={env_level_str}, """ F"""has to be one of: { ", ".join(log_levels.keys() ) }""" ) return _default_log_level def a ( ) ->Dict: '''simple docstring''' return __name__.split('''.''' )[0] def a ( ) ->Any: '''simple docstring''' return logging.getLogger(_get_library_name() ) def a ( ) ->str: '''simple docstring''' SCREAMING_SNAKE_CASE = _get_library_root_logger() library_root_logger.setLevel(_get_default_logging_level() ) def a ( ) ->int: '''simple docstring''' SCREAMING_SNAKE_CASE = _get_library_root_logger() library_root_logger.setLevel(logging.NOTSET ) def a ( a = None ) ->Any: '''simple docstring''' if name is None: SCREAMING_SNAKE_CASE = _get_library_name() return logging.getLogger(lowercase_ ) def a ( ) ->int: '''simple docstring''' return _get_library_root_logger().getEffectiveLevel() def a ( a ) ->List[Any]: '''simple docstring''' _get_library_root_logger().setLevel(lowercase_ ) def a ( ) ->List[str]: '''simple docstring''' return set_verbosity(lowercase_ ) def a ( ) ->Union[str, Any]: '''simple docstring''' return set_verbosity(lowercase_ ) def a ( ) ->Any: '''simple docstring''' return set_verbosity(lowercase_ ) def a ( ) ->str: '''simple docstring''' return set_verbosity(lowercase_ ) def a ( ) ->Optional[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = False def a ( ) ->Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = True # Configure the library root logger at the module level (singleton-like) _configure_library_root_logger() class lowerCamelCase : def __init__( self :str , *lowercase :List[Any] , **lowercase :Any ) -> Union[str, Any]: # pylint: disable=unused-argument """simple docstring""" SCREAMING_SNAKE_CASE = args[0] if args else None def __iter__( self :Union[str, Any] ) -> Optional[int]: """simple docstring""" return iter(self._iterator ) def __getattr__( self :Union[str, Any] , lowercase :Optional[Any] ) -> Optional[int]: """simple docstring""" def empty_fn(*lowercase :List[Any] , **lowercase :Dict ): # pylint: disable=unused-argument return return empty_fn def __enter__( self :List[Any] ) -> Union[str, Any]: """simple docstring""" return self def __exit__( self :List[str] , lowercase :Optional[Any] , lowercase :Union[str, Any] , lowercase :Tuple ) -> Any: """simple docstring""" return __lowerCAmelCase = True class lowerCamelCase : def __call__( self :Dict , *lowercase :Union[str, Any] , lowercase :str=False , **lowercase :Optional[int] ) -> Tuple: """simple docstring""" if _tqdm_active and not disable: return tqdm_lib.tqdm(*_lowerCamelCase , **_lowerCamelCase ) else: return EmptyTqdm(*_lowerCamelCase , **_lowerCamelCase ) def snake_case__ ( self :int , *lowercase :List[Any] , **lowercase :Optional[int] ) -> int: """simple docstring""" SCREAMING_SNAKE_CASE = None if _tqdm_active: return tqdm_lib.tqdm.set_lock(*_lowerCamelCase , **_lowerCamelCase ) def snake_case__ ( self :int ) -> List[str]: """simple docstring""" if _tqdm_active: return tqdm_lib.tqdm.get_lock() __lowerCAmelCase = _tqdm_cls() def a ( ) ->List[Any]: '''simple docstring''' global _tqdm_active return bool(_tqdm_active ) def a ( ) ->Any: '''simple docstring''' global _tqdm_active SCREAMING_SNAKE_CASE = True def a ( ) ->List[str]: '''simple docstring''' global _tqdm_active SCREAMING_SNAKE_CASE = False
201
"""simple docstring""" from collections.abc import Callable import numpy as np def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : float , lowercase_ : float , lowercase_ : float , lowercase_ : float ): '''simple docstring''' __SCREAMING_SNAKE_CASE : int = int(np.ceil((x_end - xa) / step_size ) ) __SCREAMING_SNAKE_CASE : Dict = np.zeros((n + 1,) ) __SCREAMING_SNAKE_CASE : List[Any] = ya __SCREAMING_SNAKE_CASE : Dict = xa for k in range(lowercase_ ): __SCREAMING_SNAKE_CASE : str = y[k] + step_size * ode_func(lowercase_ , y[k] ) __SCREAMING_SNAKE_CASE : int = y[k] + ( (step_size / 2) * (ode_func(lowercase_ , y[k] ) + ode_func(x + step_size , lowercase_ )) ) x += step_size return y if __name__ == "__main__": import doctest doctest.testmod()
674
0
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging a : Union[str, Any] = logging.get_logger(__name__) a : Any = {"""vocab_file""": """spiece.model"""} a : Optional[int] = { """vocab_file""": { """t5-small""": """https://huggingface.co/t5-small/resolve/main/spiece.model""", """t5-base""": """https://huggingface.co/t5-base/resolve/main/spiece.model""", """t5-large""": """https://huggingface.co/t5-large/resolve/main/spiece.model""", """t5-3b""": """https://huggingface.co/t5-3b/resolve/main/spiece.model""", """t5-11b""": """https://huggingface.co/t5-11b/resolve/main/spiece.model""", } } # TODO(PVP) - this should be removed in Transformers v5 a : Any = { """t5-small""": 512, """t5-base""": 512, """t5-large""": 512, """t5-3b""": 512, """t5-11b""": 512, } a : List[str] = """▁""" class __UpperCAmelCase( __UpperCAmelCase ): """simple docstring""" __lowerCamelCase = VOCAB_FILES_NAMES __lowerCamelCase = PRETRAINED_VOCAB_FILES_MAP __lowerCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __lowerCamelCase = ["input_ids", "attention_mask"] def __init__( self , snake_case__ , snake_case__="</s>" , snake_case__="<unk>" , snake_case__="<pad>" , snake_case__=100 , snake_case__=None , snake_case__ = None , snake_case__=True , **snake_case__ , ): '''simple docstring''' # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: lowercase__ : Union[str, Any]= [F'''<extra_id_{i}>''' for i in range(_lowerCamelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens lowercase__ : Optional[int]= len(set(filter(lambda snake_case__ : bool("extra_id" in str(_lowerCamelCase ) ) , _lowerCamelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( F'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are''' " provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids" " tokens" ) if legacy: logger.warning_once( F'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to''' " read the related pull request available at https://github.com/huggingface/transformers/pull/24565" ) lowercase__ : Optional[Any]= legacy lowercase__ : Optional[int]= {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , extra_ids=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , legacy=_lowerCamelCase , **_lowerCamelCase , ) lowercase__ : Tuple= vocab_file lowercase__ : List[str]= extra_ids lowercase__ : Optional[int]= spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) @staticmethod def UpperCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: lowercase__ : Any= TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( "This tokenizer was incorrectly instantiated with a model max length of" F''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this''' " behavior is kept to avoid breaking backwards compatibility when padding/encoding with" " `truncation is True`.\n- Be aware that you SHOULD NOT rely on" F''' {pretrained_model_name_or_path} automatically truncating your input to''' F''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences''' F''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with''' " `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please" " instantiate this tokenizer with `model_max_length` set to your preferred value." , _lowerCamelCase , ) return max_model_length @property def UpperCAmelCase_ ( self ): '''simple docstring''' return self.sp_model.get_piece_size() + self._extra_ids def UpperCAmelCase_ ( self ): '''simple docstring''' lowercase__ : str= {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCAmelCase_ ( self , snake_case__ , snake_case__ = None , snake_case__ = False ): '''simple docstring''' if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(_lowerCamelCase )) + [1] return ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1] def UpperCAmelCase_ ( self ): '''simple docstring''' return list( set(filter(lambda snake_case__ : bool(re.search(r"<extra_id_\d+>" , _lowerCamelCase ) ) is not None , self.additional_special_tokens ) ) ) def UpperCAmelCase_ ( self ): '''simple docstring''' return [self._convert_token_to_id(_lowerCamelCase ) for token in self.get_sentinel_tokens()] def UpperCAmelCase_ ( self , snake_case__ ): '''simple docstring''' if len(_lowerCamelCase ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( F'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated''' " eos tokens being added." ) return token_ids else: return token_ids + [self.eos_token_id] def UpperCAmelCase_ ( self , snake_case__ , snake_case__ = None ): '''simple docstring''' lowercase__ : List[str]= [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def UpperCAmelCase_ ( self , snake_case__ , snake_case__ = None ): '''simple docstring''' lowercase__ : Optional[Any]= self._add_eos_if_not_present(_lowerCamelCase ) if token_ids_a is None: return token_ids_a else: lowercase__ : Union[str, Any]= self._add_eos_if_not_present(_lowerCamelCase ) return token_ids_a + token_ids_a def __getstate__( self ): '''simple docstring''' lowercase__ : Any= self.__dict__.copy() lowercase__ : List[str]= None return state def __setstate__( self , snake_case__ ): '''simple docstring''' lowercase__ : Tuple= d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): lowercase__ : Optional[int]= {} lowercase__ : Optional[int]= spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCAmelCase_ ( self , snake_case__ , **snake_case__ ): '''simple docstring''' # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at # the beginning of the text if not self.legacy: lowercase__ : Dict= SPIECE_UNDERLINE + text.replace(_lowerCamelCase , " " ) return super().tokenize(_lowerCamelCase , **_lowerCamelCase ) def UpperCAmelCase_ ( self , snake_case__ , **snake_case__ ): '''simple docstring''' if not self.legacy: lowercase__ : str= text.startswith(_lowerCamelCase ) if is_first: lowercase__ : str= text[1:] lowercase__ : Tuple= self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) if not self.legacy and not is_first and not text.startswith(" " ) and tokens[0].startswith(_lowerCamelCase ): lowercase__ : Optional[int]= ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def UpperCAmelCase_ ( self , snake_case__ ): '''simple docstring''' if token.startswith("<extra_id_" ): lowercase__ : Tuple= re.match(r"<extra_id_(\d+)>" , _lowerCamelCase ) lowercase__ : Union[str, Any]= int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(_lowerCamelCase ) def UpperCAmelCase_ ( self , snake_case__ ): '''simple docstring''' if index < self.sp_model.get_piece_size(): lowercase__ : List[Any]= self.sp_model.IdToPiece(_lowerCamelCase ) else: lowercase__ : Dict= F'''<extra_id_{self.vocab_size - 1 - index}>''' return token def UpperCAmelCase_ ( self , snake_case__ ): '''simple docstring''' lowercase__ : str= [] lowercase__ : Dict= '''''' lowercase__ : Dict= 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(_lowerCamelCase ) + token lowercase__ : List[str]= True lowercase__ : str= [] else: current_sub_tokens.append(_lowerCamelCase ) lowercase__ : int= False out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def UpperCAmelCase_ ( self , snake_case__ , snake_case__ = None ): '''simple docstring''' if not os.path.isdir(_lowerCamelCase ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowercase__ : List[str]= os.path.join( _lowerCamelCase , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , "wb" ) as fi: lowercase__ : Any= self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
218
"""simple docstring""" from typing import TYPE_CHECKING from ...file_utils import _LazyModule, is_torch_available from ...utils import OptionalDependencyNotAvailable _lowerCamelCase = { '''configuration_gpt_neox_japanese''': ['''GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTNeoXJapaneseConfig'''], '''tokenization_gpt_neox_japanese''': ['''GPTNeoXJapaneseTokenizer'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase = [ '''GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GPTNeoXJapaneseForCausalLM''', '''GPTNeoXJapaneseLayer''', '''GPTNeoXJapaneseModel''', '''GPTNeoXJapanesePreTrainedModel''', ] if TYPE_CHECKING: from .configuration_gpt_neox_japanese import GPT_NEOX_JAPANESE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTNeoXJapaneseConfig from .tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_gpt_neox_japanese import ( GPT_NEOX_JAPANESE_PRETRAINED_MODEL_ARCHIVE_LIST, GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseLayer, GPTNeoXJapaneseModel, GPTNeoXJapanesePreTrainedModel, ) else: import sys _lowerCamelCase = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
674
0
import tempfile import unittest import numpy as np from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import BertConfig, is_flax_available from transformers.testing_utils import TOKEN, USER, is_staging_test, require_flax if is_flax_available(): import os from flax.core.frozen_dict import unfreeze from flax.traverse_util import flatten_dict from transformers import FlaxBertModel lowerCamelCase :Any = '0.12' # assumed parallelism: 8 @require_flax @is_staging_test class UpperCAmelCase ( unittest.TestCase ): @classmethod def _A ( cls: Union[str, Any] ): _a = TOKEN HfFolder.save_token(_lowerCamelCase ) @classmethod def _A ( cls: int ): try: delete_repo(token=cls._token , repo_id='''test-model-flax''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-model-flax-org''' ) except HTTPError: pass def _A ( self: List[str] ): _a = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) _a = FlaxBertModel(_lowerCamelCase ) model.push_to_hub('''test-model-flax''' , use_auth_token=self._token ) _a = FlaxBertModel.from_pretrained(f"{USER}/test-model-flax" ) _a = flatten_dict(unfreeze(model.params ) ) _a = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): _a = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(_lowerCamelCase , 1E-3 , msg=f"{key} not identical" ) # Reset repo delete_repo(token=self._token , repo_id='''test-model-flax''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(_lowerCamelCase , repo_id='''test-model-flax''' , push_to_hub=_lowerCamelCase , use_auth_token=self._token ) _a = FlaxBertModel.from_pretrained(f"{USER}/test-model-flax" ) _a = flatten_dict(unfreeze(model.params ) ) _a = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): _a = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(_lowerCamelCase , 1E-3 , msg=f"{key} not identical" ) def _A ( self: Any ): _a = BertConfig( vocab_size=99 , hidden_size=32 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=37 ) _a = FlaxBertModel(_lowerCamelCase ) model.push_to_hub('''valid_org/test-model-flax-org''' , use_auth_token=self._token ) _a = FlaxBertModel.from_pretrained('''valid_org/test-model-flax-org''' ) _a = flatten_dict(unfreeze(model.params ) ) _a = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): _a = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(_lowerCamelCase , 1E-3 , msg=f"{key} not identical" ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-model-flax-org''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained( _lowerCamelCase , repo_id='''valid_org/test-model-flax-org''' , push_to_hub=_lowerCamelCase , use_auth_token=self._token ) _a = FlaxBertModel.from_pretrained('''valid_org/test-model-flax-org''' ) _a = flatten_dict(unfreeze(model.params ) ) _a = flatten_dict(unfreeze(new_model.params ) ) for key in base_params.keys(): _a = (base_params[key] - new_params[key]).sum().item() self.assertLessEqual(_lowerCamelCase , 1E-3 , msg=f"{key} not identical" ) def __snake_case ( _UpperCamelCase , _UpperCamelCase ) -> Optional[int]: _a = True _a = flatten_dict(modela.params ) _a = flatten_dict(modela.params ) for key in flat_params_a.keys(): if np.sum(np.abs(flat_params_a[key] - flat_params_a[key] ) ) > 1E-4: _a = False return models_are_equal @require_flax class UpperCAmelCase ( unittest.TestCase ): def _A ( self: Optional[Any] ): _a = BertConfig.from_pretrained('''hf-internal-testing/tiny-bert-flax-only''' ) _a = FlaxBertModel(_lowerCamelCase ) _a = '''bert''' with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(_lowerCamelCase , _lowerCamelCase ) ) with self.assertRaises(_lowerCamelCase ): _a = FlaxBertModel.from_pretrained(_lowerCamelCase ) _a = FlaxBertModel.from_pretrained(_lowerCamelCase , subfolder=_lowerCamelCase ) self.assertTrue(check_models_equal(_lowerCamelCase , _lowerCamelCase ) ) def _A ( self: List[Any] ): _a = BertConfig.from_pretrained('''hf-internal-testing/tiny-bert-flax-only''' ) _a = FlaxBertModel(_lowerCamelCase ) _a = '''bert''' with tempfile.TemporaryDirectory() as tmp_dir: model.save_pretrained(os.path.join(_lowerCamelCase , _lowerCamelCase ) , max_shard_size='''10KB''' ) with self.assertRaises(_lowerCamelCase ): _a = FlaxBertModel.from_pretrained(_lowerCamelCase ) _a = FlaxBertModel.from_pretrained(_lowerCamelCase , subfolder=_lowerCamelCase ) self.assertTrue(check_models_equal(_lowerCamelCase , _lowerCamelCase ) ) def _A ( self: List[str] ): _a = '''bert''' _a = '''hf-internal-testing/tiny-random-bert-subfolder''' with self.assertRaises(_lowerCamelCase ): _a = FlaxBertModel.from_pretrained(_lowerCamelCase ) _a = FlaxBertModel.from_pretrained(_lowerCamelCase , subfolder=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def _A ( self: Optional[Any] ): _a = '''bert''' _a = '''hf-internal-testing/tiny-random-bert-sharded-subfolder''' with self.assertRaises(_lowerCamelCase ): _a = FlaxBertModel.from_pretrained(_lowerCamelCase ) _a = FlaxBertModel.from_pretrained(_lowerCamelCase , subfolder=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase )
487
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case : def __init__( self :Optional[Any] , _lowerCamelCase :int ): __SCREAMING_SNAKE_CASE : int = num_of_nodes __SCREAMING_SNAKE_CASE : list[list[int]] = [] __SCREAMING_SNAKE_CASE : dict[int, int] = {} def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :int , _lowerCamelCase :int ): self.m_edges.append([u_node, v_node, weight] ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :int ): if self.m_component[u_node] == u_node: return u_node return self.find_component(self.m_component[u_node] ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :int ): if self.m_component[u_node] != u_node: for k in self.m_component: __SCREAMING_SNAKE_CASE : Optional[Any] = self.find_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :list[int] , _lowerCamelCase :int , _lowerCamelCase :int ): if component_size[u_node] <= component_size[v_node]: __SCREAMING_SNAKE_CASE : List[Any] = v_node component_size[v_node] += component_size[u_node] self.set_component(_lowerCamelCase ) elif component_size[u_node] >= component_size[v_node]: __SCREAMING_SNAKE_CASE : Dict = self.find_component(_lowerCamelCase ) component_size[u_node] += component_size[v_node] self.set_component(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = [] __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : list[Any] = [-1] * self.m_num_of_nodes # A list of components (initialized to all of the nodes) for node in range(self.m_num_of_nodes ): self.m_component.update({node: node} ) component_size.append(1 ) __SCREAMING_SNAKE_CASE : str = self.m_num_of_nodes while num_of_components > 1: for edge in self.m_edges: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = edge __SCREAMING_SNAKE_CASE : Optional[Any] = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: for component in (u_component, v_component): if ( minimum_weight_edge[component] == -1 or minimum_weight_edge[component][2] > w ): __SCREAMING_SNAKE_CASE : Optional[Any] = [u, v, w] for edge in minimum_weight_edge: if isinstance(_lowerCamelCase , _lowerCamelCase ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = edge __SCREAMING_SNAKE_CASE : Tuple = self.m_component[u] __SCREAMING_SNAKE_CASE : int = self.m_component[v] if u_component != v_component: mst_weight += w self.union(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) print(f'''Added edge [{u} - {v}]\nAdded weight: {w}\n''' ) num_of_components -= 1 __SCREAMING_SNAKE_CASE : Optional[Any] = [-1] * self.m_num_of_nodes print(f'''The total weight of the minimal spanning tree is: {mst_weight}''' ) def lowerCAmelCase_ ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
674
0
"""simple docstring""" def __UpperCAmelCase ( __UpperCamelCase ): assert isinstance(lowercase_ , lowercase_ ), f"""The input value of [n={number}] is not an integer""" if number == 1: return 2 elif number < 1: __lowercase : Union[str, Any] = f"""The input value of [n={number}] has to be > 0""" raise ValueError(lowercase_ ) else: __lowercase : Tuple = sylvester(number - 1 ) __lowercase : Any = num - 1 __lowercase : Tuple = num return lower * upper + 1 if __name__ == "__main__": print(F"The 8th number in Sylvester\'s sequence: {sylvester(8)}")
76
"""simple docstring""" import argparse import pickle import numpy as np import torch from torch import nn from transformers import ReformerConfig, ReformerModelWithLMHead from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : Any , lowercase_ : int=None ): '''simple docstring''' assert torch_layer.weight.shape == weight.shape, F'''{torch_layer} layer.weight does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(lowercase_ ) if bias is not None: assert torch_layer.bias.shape == bias.shape, F'''{torch_layer} layer.bias does not match''' __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Tuple , lowercase_ : int , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Optional[int] = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) set_param( torch_layer.self_attention.query_key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(weights[1] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(weights[2] ) __SCREAMING_SNAKE_CASE : Tuple = np.asarray(weights[3] ) set_param( torch_layer.self_attention.query , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.key , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.self_attention.value , torch.tensor(lowercase_ ).transpose(1 , 2 ).contiguous().view(-1 , lowercase_ ) , ) set_param( torch_layer.output.dense , torch.tensor(lowercase_ ).view(-1 , lowercase_ ).contiguous().transpose(0 , 1 ) , ) def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = weights[0][0][0] __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(layer_norm_a[0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(layer_norm_a[1] ) set_param( torch_block.attention.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # lsh weights + output __SCREAMING_SNAKE_CASE : Tuple = weights[0][1] if len(lowercase_ ) < 4: set_layer_weights_in_torch_lsh(lowercase_ , torch_block.attention , lowercase_ ) else: set_layer_weights_in_torch_local(lowercase_ , torch_block.attention , lowercase_ ) # intermediate weighs __SCREAMING_SNAKE_CASE : Any = weights[2][0][1][2] # Chunked Feed Forward if len(lowercase_ ) == 4: __SCREAMING_SNAKE_CASE : List[str] = intermediate_weights[2] # layernorm 2 __SCREAMING_SNAKE_CASE : List[str] = np.asarray(intermediate_weights[0][0] ) __SCREAMING_SNAKE_CASE : Union[str, Any] = np.asarray(intermediate_weights[0][1] ) set_param( torch_block.feed_forward.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # intermediate dense __SCREAMING_SNAKE_CASE : int = np.asarray(intermediate_weights[1][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[1][1] ) set_param( torch_block.feed_forward.dense.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) # intermediate out __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(intermediate_weights[4][0] ) __SCREAMING_SNAKE_CASE : Any = np.asarray(intermediate_weights[4][1] ) set_param( torch_block.feed_forward.output.dense , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Optional[Any] , lowercase_ : Optional[Any] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = torch_model.reformer # word embeds __SCREAMING_SNAKE_CASE : int = np.asarray(weights[1] ) set_param( torch_model_reformer.embeddings.word_embeddings , torch.tensor(lowercase_ ) , ) if isinstance(weights[3] , lowercase_ ): __SCREAMING_SNAKE_CASE : int = torch_model_reformer.embeddings.position_embeddings for emb_idx in range(len(position_embeddings.weights ) ): __SCREAMING_SNAKE_CASE : Dict = np.asarray(weights[3][emb_idx][0] ) assert ( position_embeddings.weights[emb_idx].shape == emb_weights.shape ), F'''{position_embeddings[emb_idx]} emb does not match''' __SCREAMING_SNAKE_CASE : str = nn.Parameter(torch.tensor(lowercase_ ) ) __SCREAMING_SNAKE_CASE : List[Any] = weights[5] assert len(torch_model_reformer.encoder.layers ) * 4 == len( lowercase_ ), "HF and trax model do not have the same number of layers" for layer_idx, layer in enumerate(torch_model_reformer.encoder.layers ): __SCREAMING_SNAKE_CASE : Union[str, Any] = trax_layer_weights[4 * layer_idx : 4 * (layer_idx + 1)] set_block_weights_in_torch(lowercase_ , lowercase_ , lowercase_ ) # output layer norm __SCREAMING_SNAKE_CASE : List[str] = np.asarray(weights[7][0] ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[7][1] ) set_param( torch_model_reformer.encoder.layer_norm , torch.tensor(lowercase_ ) , torch.tensor(lowercase_ ) , ) # output embeddings __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(weights[9][0] ) __SCREAMING_SNAKE_CASE : List[Any] = np.asarray(weights[9][1] ) set_param( torch_model.lm_head.decoder , torch.tensor(lowercase_ ).transpose(0 , 1 ).contiguous() , torch.tensor(lowercase_ ) , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : Any , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = ReformerConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : List[str] = ReformerModelWithLMHead(lowercase_ ) with open(lowercase_ , '''rb''' ) as f: __SCREAMING_SNAKE_CASE : int = pickle.load(lowercase_ )['''weights'''] set_model_weights_in_torch(lowercase_ , lowercase_ , config.hidden_size ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--trax_model_pkl_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained Reformer model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase = parser.parse_args() convert_trax_checkpoint_to_pytorch(args.trax_model_pkl_path, args.config_file, args.pytorch_dump_path)
674
0
from __future__ import annotations import os from typing import Any import requests lowercase_ : List[Any] = 'https://api.github.com' # https://docs.github.com/en/free-pro-team@latest/rest/reference/users#get-the-authenticated-user lowercase_ : Dict = BASE_URL + '/user' # https://github.com/settings/tokens lowercase_ : Optional[int] = os.environ.get('USER_TOKEN', '') def A__ ( snake_case_ : str ): SCREAMING_SNAKE_CASE__: Tuple= { '''Authorization''': F'token {auth_token}', '''Accept''': '''application/vnd.github.v3+json''', } return requests.get(lowercase_ , headers=lowercase_ ).json() if __name__ == "__main__": # pragma: no cover if USER_TOKEN: for key, value in fetch_github_info(USER_TOKEN).items(): print(f'''{key}: {value}''') else: raise ValueError('\'USER_TOKEN\' field cannot be empty.')
64
"""simple docstring""" from typing import Callable, Optional, Union from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''microsoft/xprophetnet-large-wiki100-cased''': ( '''https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased/resolve/main/config.json''' ), } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''xlm-prophetnet''' lowerCamelCase__ = ['''past_key_values'''] lowerCamelCase__ = { '''num_attention_heads''': '''num_encoder_attention_heads''', } def __init__( self :List[str] , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[Union[str, Callable]] = "gelu" , _lowerCamelCase :Optional[int] = 3_0_5_2_2 , _lowerCamelCase :Optional[int] = 1_0_2_4 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[int] = 4_0_9_6 , _lowerCamelCase :Optional[int] = 1_2 , _lowerCamelCase :Optional[int] = 1_6 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[float] = 0.1 , _lowerCamelCase :Optional[int] = 5_1_2 , _lowerCamelCase :Optional[float] = 0.0_2 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 2 , _lowerCamelCase :Optional[int] = 3_2 , _lowerCamelCase :Optional[int] = 1_2_8 , _lowerCamelCase :Optional[bool] = False , _lowerCamelCase :Optional[float] = 0.0 , _lowerCamelCase :Optional[bool] = True , _lowerCamelCase :Optional[int] = 0 , _lowerCamelCase :Optional[int] = 1 , _lowerCamelCase :Optional[int] = 2 , **_lowerCamelCase :int , ): __SCREAMING_SNAKE_CASE : Union[str, Any] = vocab_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_size __SCREAMING_SNAKE_CASE : List[Any] = encoder_ffn_dim __SCREAMING_SNAKE_CASE : str = num_encoder_layers __SCREAMING_SNAKE_CASE : Optional[Any] = num_encoder_attention_heads __SCREAMING_SNAKE_CASE : str = decoder_ffn_dim __SCREAMING_SNAKE_CASE : List[Any] = num_decoder_layers __SCREAMING_SNAKE_CASE : List[str] = num_decoder_attention_heads __SCREAMING_SNAKE_CASE : Dict = max_position_embeddings __SCREAMING_SNAKE_CASE : Any = init_std # Normal(0, this parameter) __SCREAMING_SNAKE_CASE : Any = activation_function # parameters for xlmprophetnet __SCREAMING_SNAKE_CASE : List[Any] = ngram __SCREAMING_SNAKE_CASE : int = num_buckets __SCREAMING_SNAKE_CASE : List[str] = relative_max_distance __SCREAMING_SNAKE_CASE : str = disable_ngram_loss __SCREAMING_SNAKE_CASE : Optional[int] = eps # 3 Types of Dropout __SCREAMING_SNAKE_CASE : int = attention_dropout __SCREAMING_SNAKE_CASE : Optional[Any] = activation_dropout __SCREAMING_SNAKE_CASE : Dict = dropout __SCREAMING_SNAKE_CASE : Any = use_cache super().__init__( pad_token_id=_lowerCamelCase , bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , is_encoder_decoder=_lowerCamelCase , add_cross_attention=_lowerCamelCase , decoder_start_token_id=_lowerCamelCase , **_lowerCamelCase , ) @property def SCREAMING_SNAKE_CASE_ ( self :int ): return self.num_encoder_layers + self.num_decoder_layers @num_hidden_layers.setter def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[Any] ): raise NotImplementedError( '''This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and''' ''' `num_decoder_layers`.''' )
674
0
import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class lowerCamelCase_ ( unittest.TestCase ): '''simple docstring''' def A ( self ) -> List[Any]: '''simple docstring''' __lowercase = 0 def A ( self ) -> List[Any]: '''simple docstring''' __lowercase = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def A ( self ) -> Tuple: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: __lowercase = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __lowercase = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __lowercase = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def A ( self ) -> List[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: __lowercase = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __lowercase = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __lowercase = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def A ( self ) -> Optional[Any]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: __lowercase = CLIPConfig() # Create a dummy config file with image_proceesor_type __lowercase = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __lowercase = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally __lowercase = AutoImageProcessor.from_pretrained(_lowerCamelCase ).to_dict() config_dict.pop('''image_processor_type''' ) __lowercase = CLIPImageProcessor(**_lowerCamelCase ) # save in new folder model_config.save_pretrained(_lowerCamelCase ) config.save_pretrained(_lowerCamelCase ) __lowercase = AutoImageProcessor.from_pretrained(_lowerCamelCase ) # make sure private variable is not incorrectly saved __lowercase = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def A ( self ) -> List[str]: '''simple docstring''' with tempfile.TemporaryDirectory() as tmpdirname: __lowercase = Path(_lowerCamelCase ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) __lowercase = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def A ( self ) -> List[str]: '''simple docstring''' with self.assertRaisesRegex( _lowerCamelCase , '''clip-base is not a local folder and is not a valid model identifier''' ): __lowercase = AutoImageProcessor.from_pretrained('''clip-base''' ) def A ( self ) -> List[str]: '''simple docstring''' with self.assertRaisesRegex( _lowerCamelCase , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): __lowercase = AutoImageProcessor.from_pretrained(_lowerCamelCase , revision='''aaaaaa''' ) def A ( self ) -> Any: '''simple docstring''' with self.assertRaisesRegex( _lowerCamelCase , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): __lowercase = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def A ( self ) -> Any: '''simple docstring''' with self.assertRaises(_lowerCamelCase ): __lowercase = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(_lowerCamelCase ): __lowercase = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) __lowercase = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __lowercase = AutoImageProcessor.from_pretrained(_lowerCamelCase , trust_remote_code=_lowerCamelCase ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def A ( self ) -> Union[str, Any]: '''simple docstring''' try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_lowerCamelCase ): AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: __lowercase = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __lowercase = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __lowercase = CustomImageProcessor.from_pretrained(_lowerCamelCase ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __lowercase = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def A ( self ) -> Optional[int]: '''simple docstring''' class lowerCamelCase_ ( __UpperCAmelCase ): '''simple docstring''' __UpperCAmelCase = True try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # If remote code is not set, the default is to use local __lowercase = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. __lowercase = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub __lowercase = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(_lowerCamelCase , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
639
"""simple docstring""" import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) _lowerCamelCase = [ '''cross_validation.py''', '''gradient_accumulation.py''', '''local_sgd.py''', '''multi_process_metrics.py''', '''memory.py''', '''automatic_gradient_accumulation.py''', '''fsdp_with_peak_mem_tracking.py''', '''deepspeed_with_config_support.py''', '''megatron_lm_gpt_pretraining.py''', ] class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :str , _lowerCamelCase :bool , _lowerCamelCase :str = None , _lowerCamelCase :list = None ): __SCREAMING_SNAKE_CASE : List[str] = None __SCREAMING_SNAKE_CASE : Optional[Any] = os.path.abspath(os.path.join('''examples''' , '''by_feature''' ) ) __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath('''examples''' ) for item in os.listdir(_lowerCamelCase ): if item not in EXCLUDE_EXAMPLES: __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(_lowerCamelCase , _lowerCamelCase ) if os.path.isfile(_lowerCamelCase ) and ".py" in item_path: with self.subTest( tested_script=_lowerCamelCase , feature_script=_lowerCamelCase , tested_section='''main()''' if parser_only else '''training_function()''' , ): __SCREAMING_SNAKE_CASE : Tuple = compare_against_test( os.path.join(_lowerCamelCase , _lowerCamelCase ) , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = '''\n'''.join(_lowerCamelCase ) if special_strings is not None: for string in special_strings: __SCREAMING_SNAKE_CASE : List[Any] = diff.replace(_lowerCamelCase , '''''' ) self.assertEqual(_lowerCamelCase , '''''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) self.one_complete_example('''complete_nlp_example.py''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = os.path.abspath(os.path.join('''examples''' , '''cv_example.py''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = [ ''' ''' * 1_6 + '''{\n\n''', ''' ''' * 2_0 + '''"accuracy": eval_metric["accuracy"],\n\n''', ''' ''' * 2_0 + '''"f1": eval_metric["f1"],\n\n''', ''' ''' * 2_0 + '''"train_loss": total_loss.item() / len(train_dataloader),\n\n''', ''' ''' * 2_0 + '''"epoch": epoch,\n\n''', ''' ''' * 1_6 + '''},\n\n''', ''' ''' * 1_6 + '''step=epoch,\n''', ''' ''' * 1_2, ''' ''' * 8 + '''for step, batch in enumerate(active_dataloader):\n''', ] self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) self.one_complete_example('''complete_cv_example.py''' , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) @mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''1'''} ) class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = False @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().setUpClass() __SCREAMING_SNAKE_CASE : Dict = tempfile.mkdtemp() __SCREAMING_SNAKE_CASE : str = os.path.join(cls._tmpdir , '''default_config.yml''' ) write_basic_config(save_location=cls.configPath ) __SCREAMING_SNAKE_CASE : List[Any] = ['''accelerate''', '''launch''', '''--config_file''', cls.configPath] @classmethod def SCREAMING_SNAKE_CASE_ ( cls :Dict ): super().tearDownClass() shutil.rmtree(cls._tmpdir ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : str = f''' examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''epoch_0''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Optional[Any] = f''' examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} '''.split() __SCREAMING_SNAKE_CASE : Optional[int] = run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , '''step_2''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'epoch_0' )} '''.split() __SCREAMING_SNAKE_CASE : Any = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Optional[int] = f''' examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , 'step_2' )} '''.split() __SCREAMING_SNAKE_CASE : List[str] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) if torch.cuda.is_available(): __SCREAMING_SNAKE_CASE : List[Any] = torch.cuda.device_count() else: __SCREAMING_SNAKE_CASE : Optional[int] = 1 if num_processes > 1: self.assertNotIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) else: self.assertIn('''epoch 0:''' , _lowerCamelCase ) self.assertIn('''epoch 1:''' , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ''' examples/by_feature/cross_validation.py --num_folds 2 '''.split() with mock.patch.dict(os.environ , {'''TESTING_MOCKED_DATALOADERS''': '''0'''} ): __SCREAMING_SNAKE_CASE : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = re.findall('''({.+})''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = [r for r in results if '''accuracy''' in r][-1] __SCREAMING_SNAKE_CASE : Tuple = ast.literal_eval(_lowerCamelCase ) self.assertGreaterEqual(results['''accuracy'''] , 0.7_5 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = ['''examples/by_feature/multi_process_metrics.py'''] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {'''WANDB_MODE''': '''offline'''} ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with tempfile.TemporaryDirectory() as tmpdir: __SCREAMING_SNAKE_CASE : int = f''' examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} '''.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(_lowerCamelCase , '''tracking''' ) ) ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = ['''examples/by_feature/gradient_accumulation.py'''] run_command(self._launch_args + testargs ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = ['''examples/by_feature/local_sgd.py'''] run_command(self._launch_args + testargs )
674
0
import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class __magic_name__ ( unittest.TestCase ): """simple docstring""" def lowerCAmelCase ( self : str ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() @property def lowerCAmelCase ( self : List[Any] ): """simple docstring""" torch.manual_seed(0 ) _UpperCamelCase: List[str] = UNetaDModel( sample_size=(32, 64) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('''AttnDownBlock2D''', '''DownBlock2D''') , up_block_types=('''UpBlock2D''', '''AttnUpBlock2D''') , ) return model @property def lowerCAmelCase ( self : Any ): """simple docstring""" torch.manual_seed(0 ) _UpperCamelCase: str = UNetaDConditionModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('''CrossAttnDownBlock2D''', '''DownBlock2D''') , up_block_types=('''UpBlock2D''', '''CrossAttnUpBlock2D''') , cross_attention_dim=10 , ) return model @property def lowerCAmelCase ( self : Any ): """simple docstring""" torch.manual_seed(0 ) _UpperCamelCase: Tuple = AutoencoderKL( sample_size=(128, 64) , in_channels=1 , out_channels=1 , latent_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('''DownEncoderBlock2D''', '''DownEncoderBlock2D''') , up_block_types=('''UpDecoderBlock2D''', '''UpDecoderBlock2D''') , ) _UpperCamelCase: List[str] = UNetaDModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(128, 128) , down_block_types=('''AttnDownBlock2D''', '''DownBlock2D''') , up_block_types=('''UpBlock2D''', '''AttnUpBlock2D''') , ) return vqvae, unet @slow def lowerCAmelCase ( self : Tuple ): """simple docstring""" _UpperCamelCase: str = '''cpu''' # ensure determinism for the device-dependent torch.Generator _UpperCamelCase: Tuple = Mel( x_res=self.dummy_unet.config.sample_size[1] , y_res=self.dummy_unet.config.sample_size[0] , ) _UpperCamelCase: List[str] = DDPMScheduler() _UpperCamelCase: Optional[int] = AudioDiffusionPipeline(vqvae=_lowerCamelCase , unet=self.dummy_unet , mel=_lowerCamelCase , scheduler=_lowerCamelCase ) _UpperCamelCase: int = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) _UpperCamelCase: int = torch.Generator(device=_lowerCamelCase ).manual_seed(42 ) _UpperCamelCase: Optional[int] = pipe(generator=_lowerCamelCase , steps=4 ) _UpperCamelCase: Tuple = output.audios[0] _UpperCamelCase: List[Any] = output.images[0] _UpperCamelCase: Optional[Any] = torch.Generator(device=_lowerCamelCase ).manual_seed(42 ) _UpperCamelCase: int = pipe(generator=_lowerCamelCase , steps=4 , return_dict=_lowerCamelCase ) _UpperCamelCase: List[str] = output[0][0] assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length) assert ( image.height == self.dummy_unet.config.sample_size[0] and image.width == self.dummy_unet.config.sample_size[1] ) _UpperCamelCase: List[Any] = np.frombuffer(image.tobytes() , dtype='''uint8''' )[:10] _UpperCamelCase: int = np.frombuffer(image_from_tuple.tobytes() , dtype='''uint8''' )[:10] _UpperCamelCase: str = np.array([69, 255, 255, 255, 0, 0, 77, 181, 12, 127] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() == 0 _UpperCamelCase: Dict = Mel( x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1] , y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0] , ) _UpperCamelCase: List[Any] = DDIMScheduler() _UpperCamelCase: str = self.dummy_vqvae_and_unet _UpperCamelCase: List[str] = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=dummy_vqvae_and_unet[1] , mel=_lowerCamelCase , scheduler=_lowerCamelCase ) _UpperCamelCase: Tuple = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) np.random.seed(0 ) _UpperCamelCase: int = np.random.uniform(-1 , 1 , ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,) ) _UpperCamelCase: Union[str, Any] = torch.Generator(device=_lowerCamelCase ).manual_seed(42 ) _UpperCamelCase: Tuple = pipe(raw_audio=_lowerCamelCase , generator=_lowerCamelCase , start_step=5 , steps=10 ) _UpperCamelCase: Any = output.images[0] assert ( image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0] and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1] ) _UpperCamelCase: Any = np.frombuffer(image.tobytes() , dtype='''uint8''' )[:10] _UpperCamelCase: Union[str, Any] = np.array([120, 117, 110, 109, 138, 167, 138, 148, 132, 121] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 _UpperCamelCase: Optional[Any] = self.dummy_unet_condition _UpperCamelCase: Dict = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=_lowerCamelCase , mel=_lowerCamelCase , scheduler=_lowerCamelCase ) _UpperCamelCase: List[str] = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) np.random.seed(0 ) _UpperCamelCase: Optional[int] = torch.rand((1, 1, 10) ) _UpperCamelCase: Union[str, Any] = pipe(generator=_lowerCamelCase , encoding=_lowerCamelCase ) _UpperCamelCase: Optional[int] = output.images[0] _UpperCamelCase: List[Any] = np.frombuffer(image.tobytes() , dtype='''uint8''' )[:10] _UpperCamelCase: List[str] = np.array([107, 103, 120, 127, 142, 122, 113, 122, 97, 111] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 @slow @require_torch_gpu class __magic_name__ ( unittest.TestCase ): """simple docstring""" def lowerCAmelCase ( self : Optional[int] ): """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCAmelCase ( self : List[str] ): """simple docstring""" _UpperCamelCase: str = torch_device _UpperCamelCase: Union[str, Any] = DiffusionPipeline.from_pretrained('''teticio/audio-diffusion-ddim-256''' ) _UpperCamelCase: int = pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) _UpperCamelCase: Optional[int] = torch.Generator(device=_lowerCamelCase ).manual_seed(42 ) _UpperCamelCase: Optional[int] = pipe(generator=_lowerCamelCase ) _UpperCamelCase: Optional[Any] = output.audios[0] _UpperCamelCase: Union[str, Any] = output.images[0] assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length) assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1] _UpperCamelCase: Dict = np.frombuffer(image.tobytes() , dtype='''uint8''' )[:10] _UpperCamelCase: Any = np.array([151, 167, 154, 144, 122, 134, 121, 105, 70, 26] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
271
"""simple docstring""" import argparse import logging import os import time import timeit import datasets import numpy as np import pycuda.autoinit # noqa: F401 import pycuda.driver as cuda import tensorrt as trt import torch from absl import logging as absl_logging from accelerate import Accelerator from datasets import load_dataset, load_metric from torch.utils.data import DataLoader from utils_qa import postprocess_qa_predictions import transformers from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed from transformers.trainer_pt_utils import nested_concat, nested_truncate _lowerCamelCase = trt.Logger(trt.Logger.WARNING) _lowerCamelCase = absl_logging.get_absl_logger() absl_logger.setLevel(logging.WARNING) _lowerCamelCase = logging.getLogger(__name__) _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--onnx_model_path''', default=None, type=str, required=True, help='''Path to ONNX model: ''', ) parser.add_argument( '''--output_dir''', default=None, type=str, required=True, help='''The output directory where the model checkpoints and predictions will be written.''', ) # Other parameters parser.add_argument( '''--tokenizer_name''', default='''''', type=str, required=True, help='''Pretrained tokenizer name or path if not the same as model_name''', ) parser.add_argument( '''--version_2_with_negative''', action='''store_true''', help='''If true, the SQuAD examples contain some that do not have an answer.''', ) parser.add_argument( '''--null_score_diff_threshold''', type=float, default=0.0, help='''If null_score - best_non_null is greater than the threshold predict null.''', ) parser.add_argument( '''--max_seq_length''', default=3_84, type=int, help=( '''The maximum total input sequence length after WordPiece tokenization. Sequences ''' '''longer than this will be truncated, and sequences shorter than this will be padded.''' ), ) parser.add_argument( '''--doc_stride''', default=1_28, type=int, help='''When splitting up a long document into chunks, how much stride to take between chunks.''', ) parser.add_argument('''--per_device_eval_batch_size''', default=8, type=int, help='''Batch size per GPU/CPU for evaluation.''') parser.add_argument( '''--n_best_size''', default=20, type=int, help='''The total number of n-best predictions to generate in the nbest_predictions.json output file.''', ) parser.add_argument( '''--max_answer_length''', default=30, type=int, help=( '''The maximum length of an answer that can be generated. This is needed because the start ''' '''and end predictions are not conditioned on one another.''' ), ) parser.add_argument('''--seed''', type=int, default=42, help='''random seed for initialization''') parser.add_argument( '''--dataset_name''', type=str, default=None, required=True, help='''The name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--dataset_config_name''', type=str, default=None, help='''The configuration name of the dataset to use (via the datasets library).''', ) parser.add_argument( '''--preprocessing_num_workers''', type=int, default=4, help='''A csv or a json file containing the training data.''' ) parser.add_argument('''--overwrite_cache''', action='''store_true''', help='''Overwrite the cached training and evaluation sets''') parser.add_argument( '''--fp16''', action='''store_true''', help='''Whether to use 16-bit (mixed) precision instead of 32-bit''', ) parser.add_argument( '''--int8''', action='''store_true''', help='''Whether to use INT8''', ) _lowerCamelCase = parser.parse_args() if args.tokenizer_name: _lowerCamelCase = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True) else: raise ValueError( '''You are instantiating a new tokenizer from scratch. This is not supported by this script.''' '''You can do it from another script, save it, and load it from here, using --tokenizer_name.''' ) logger.info('''Training/evaluation parameters %s''', args) _lowerCamelCase = args.per_device_eval_batch_size _lowerCamelCase = (args.eval_batch_size, args.max_seq_length) # TRT Engine properties _lowerCamelCase = True _lowerCamelCase = '''temp_engine/bert-fp32.engine''' if args.fpaa: _lowerCamelCase = '''temp_engine/bert-fp16.engine''' if args.inta: _lowerCamelCase = '''temp_engine/bert-int8.engine''' # import ONNX file if not os.path.exists('''temp_engine'''): os.makedirs('''temp_engine''') _lowerCamelCase = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH) with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser( network, TRT_LOGGER ) as parser: with open(args.onnx_model_path, '''rb''') as model: if not parser.parse(model.read()): for error in range(parser.num_errors): print(parser.get_error(error)) # Query input names and shapes from parsed TensorRT network _lowerCamelCase = [network.get_input(i) for i in range(network.num_inputs)] _lowerCamelCase = [_input.name for _input in network_inputs] # ex: ["actual_input1"] with builder.create_builder_config() as config: _lowerCamelCase = 1 << 50 if STRICT_TYPES: config.set_flag(trt.BuilderFlag.STRICT_TYPES) if args.fpaa: config.set_flag(trt.BuilderFlag.FPaa) if args.inta: config.set_flag(trt.BuilderFlag.INTa) _lowerCamelCase = builder.create_optimization_profile() config.add_optimization_profile(profile) for i in range(len(input_names)): profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE) _lowerCamelCase = builder.build_engine(network, config) # serialize_engine and store in file (can be directly loaded and deserialized): with open(engine_name, '''wb''') as f: f.write(engine.serialize()) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : Tuple , lowercase_ : List[Any] , lowercase_ : List[Any] , lowercase_ : str , lowercase_ : Tuple , lowercase_ : Any , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = np.asarray(inputs['''input_ids'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''attention_mask'''] , dtype=np.intaa ) __SCREAMING_SNAKE_CASE : Optional[Any] = np.asarray(inputs['''token_type_ids'''] , dtype=np.intaa ) # Copy inputs cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , lowercase_ ) cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , lowercase_ ) # start time __SCREAMING_SNAKE_CASE : Tuple = time.time() # Run inference context.execute_async( bindings=[int(lowercase_ ) for d_inp in d_inputs] + [int(lowercase_ ), int(lowercase_ )] , stream_handle=stream.handle ) # Transfer predictions back from GPU cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) cuda.memcpy_dtoh_async(lowercase_ , lowercase_ , lowercase_ ) # Synchronize the stream and take time stream.synchronize() # end time __SCREAMING_SNAKE_CASE : List[str] = time.time() __SCREAMING_SNAKE_CASE : int = end_time - start_time __SCREAMING_SNAKE_CASE : int = (h_outputa, h_outputa) # print(outputs) return outputs, infer_time # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. _lowerCamelCase = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''', datefmt='''%m/%d/%Y %H:%M:%S''', level=logging.INFO, ) # Setup logging, we only want one process per machine to log things on the screen. # accelerator.is_local_main_process is only True for one process per machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed) # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ # (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called # 'text' is found. You can easily tweak this behavior (see below). if args.dataset_name is not None: # Downloading and loading a dataset from the hub. _lowerCamelCase = load_dataset(args.dataset_name, args.dataset_config_name) else: raise ValueError('''Evaluation requires a dataset name''') # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at # https://huggingface.co/docs/datasets/loading_datasets.html. # Preprocessing the datasets. # Preprocessing is slighlty different for training and evaluation. _lowerCamelCase = raw_datasets['''validation'''].column_names _lowerCamelCase = '''question''' if '''question''' in column_names else column_names[0] _lowerCamelCase = '''context''' if '''context''' in column_names else column_names[1] _lowerCamelCase = '''answers''' if '''answers''' in column_names else column_names[2] # Padding side determines if we do (question|context) or (context|question). _lowerCamelCase = tokenizer.padding_side == '''right''' if args.max_seq_length > tokenizer.model_max_length: logger.warning( f'The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the' f'model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.' ) _lowerCamelCase = min(args.max_seq_length, tokenizer.model_max_length) def lowerCAmelCase_ ( lowercase_ : Tuple ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = [q.lstrip() for q in examples[question_column_name]] # Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results # in one example possible giving several features when a context is long, each of those features having a # context that overlaps a bit the context of the previous feature. __SCREAMING_SNAKE_CASE : Optional[Any] = tokenizer( examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation='''only_second''' if pad_on_right else '''only_first''' , max_length=lowercase_ , stride=args.doc_stride , return_overflowing_tokens=lowercase_ , return_offsets_mapping=lowercase_ , padding='''max_length''' , ) # Since one example might give us several features if it has a long context, we need a map from a feature to # its corresponding example. This key gives us just that. __SCREAMING_SNAKE_CASE : Optional[int] = tokenized_examples.pop('''overflow_to_sample_mapping''' ) # For evaluation, we will need to convert our predictions to substrings of the context, so we keep the # corresponding example_id and we will store the offset mappings. __SCREAMING_SNAKE_CASE : Any = [] for i in range(len(tokenized_examples['''input_ids'''] ) ): # Grab the sequence corresponding to that example (to know what is the context and what is the question). __SCREAMING_SNAKE_CASE : int = tokenized_examples.sequence_ids(lowercase_ ) __SCREAMING_SNAKE_CASE : str = 1 if pad_on_right else 0 # One example can give several spans, this is the index of the example containing this span of text. __SCREAMING_SNAKE_CASE : str = sample_mapping[i] tokenized_examples["example_id"].append(examples['''id'''][sample_index] ) # Set to None the offset_mapping that are not part of the context so it's easy to determine if a token # position is part of the context or not. __SCREAMING_SNAKE_CASE : List[str] = [ (o if sequence_ids[k] == context_index else None) for k, o in enumerate(tokenized_examples['''offset_mapping'''][i] ) ] return tokenized_examples _lowerCamelCase = raw_datasets['''validation'''] # Validation Feature Creation _lowerCamelCase = eval_examples.map( prepare_validation_features, batched=True, num_proc=args.preprocessing_num_workers, remove_columns=column_names, load_from_cache_file=not args.overwrite_cache, desc='''Running tokenizer on validation dataset''', ) _lowerCamelCase = default_data_collator _lowerCamelCase = eval_dataset.remove_columns(['''example_id''', '''offset_mapping''']) _lowerCamelCase = DataLoader( eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size ) def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : Union[str, Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any]="eval" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = postprocess_qa_predictions( examples=lowercase_ , features=lowercase_ , predictions=lowercase_ , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=lowercase_ , ) # Format the result to the format the metric expects. if args.version_2_with_negative: __SCREAMING_SNAKE_CASE : Union[str, Any] = [ {'''id''': k, '''prediction_text''': v, '''no_answer_probability''': 0.0} for k, v in predictions.items() ] else: __SCREAMING_SNAKE_CASE : int = [{'''id''': k, '''prediction_text''': v} for k, v in predictions.items()] __SCREAMING_SNAKE_CASE : Any = [{'''id''': ex['''id'''], '''answers''': ex[answer_column_name]} for ex in examples] return EvalPrediction(predictions=lowercase_ , label_ids=lowercase_ ) _lowerCamelCase = load_metric('''squad_v2''' if args.version_2_with_negative else '''squad''') # Evaluation! logger.info('''Loading ONNX model %s for evaluation''', args.onnx_model_path) with open(engine_name, '''rb''') as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine( f.read() ) as engine, engine.create_execution_context() as context: # setup for TRT inferrence for i in range(len(input_names)): context.set_binding_shape(i, INPUT_SHAPE) assert context.all_binding_shapes_specified def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' return trt.volume(engine.get_binding_shape(lowercase_ ) ) * engine.get_binding_dtype(lowercase_ ).itemsize # Allocate device memory for inputs and outputs. _lowerCamelCase = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)] # Allocate output buffer _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa) _lowerCamelCase = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) _lowerCamelCase = cuda.mem_alloc(h_outputa.nbytes) # Create a stream in which to copy inputs/outputs and run inference. _lowerCamelCase = cuda.Stream() # Evaluation logger.info('''***** Running Evaluation *****''') logger.info(f' Num examples = {len(eval_dataset)}') logger.info(f' Batch size = {args.per_device_eval_batch_size}') _lowerCamelCase = 0.0 _lowerCamelCase = 0 _lowerCamelCase = timeit.default_timer() _lowerCamelCase = None for step, batch in enumerate(eval_dataloader): _lowerCamelCase , _lowerCamelCase = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream) total_time += infer_time niter += 1 _lowerCamelCase , _lowerCamelCase = outputs _lowerCamelCase = torch.tensor(start_logits) _lowerCamelCase = torch.tensor(end_logits) # necessary to pad predictions and labels for being gathered _lowerCamelCase = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-1_00) _lowerCamelCase = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-1_00) _lowerCamelCase = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy()) _lowerCamelCase = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-1_00) if all_preds is not None: _lowerCamelCase = nested_truncate(all_preds, len(eval_dataset)) _lowerCamelCase = timeit.default_timer() - start_time logger.info(''' Evaluation done in total %f secs (%f sec per example)''', evalTime, evalTime / len(eval_dataset)) # Inference time from TRT logger.info('''Average Inference Time = {:.3f} ms'''.format(total_time * 10_00 / niter)) logger.info('''Total Inference Time = {:.3f} ms'''.format(total_time * 10_00)) logger.info('''Total Number of Inference = %d''', niter) _lowerCamelCase = post_processing_function(eval_examples, eval_dataset, all_preds) _lowerCamelCase = metric.compute(predictions=prediction.predictions, references=prediction.label_ids) logger.info(f'Evaluation metrics: {eval_metric}')
674
0
from datasets.utils.patching import _PatchedModuleObj, patch_submodule from . import _test_patching def __lowerCamelCase ( ) -> str: import os as original_os from os import path as original_path from os import rename as original_rename from os.path import dirname as original_dirname from os.path import join as original_join assert _test_patching.os is original_os assert _test_patching.path is original_path assert _test_patching.join is original_join assert _test_patching.renamed_os is original_os assert _test_patching.renamed_path is original_path assert _test_patching.renamed_join is original_join UpperCamelCase = '''__test_patch_submodule_mock__''' with patch_submodule(_test_patching , 'os.path.join' , lowercase_ ): # Every way to access os.path.join must be patched, and the rest must stay untouched # check os.path.join assert isinstance(_test_patching.os , _PatchedModuleObj ) assert isinstance(_test_patching.os.path , _PatchedModuleObj ) assert _test_patching.os.path.join is mock # check path.join assert isinstance(_test_patching.path , _PatchedModuleObj ) assert _test_patching.path.join is mock # check join assert _test_patching.join is mock # check that the other attributes are untouched assert _test_patching.os.rename is original_rename assert _test_patching.path.dirname is original_dirname assert _test_patching.os.path.dirname is original_dirname # Even renamed modules or objects must be patched # check renamed_os.path.join assert isinstance(_test_patching.renamed_os , _PatchedModuleObj ) assert isinstance(_test_patching.renamed_os.path , _PatchedModuleObj ) assert _test_patching.renamed_os.path.join is mock # check renamed_path.join assert isinstance(_test_patching.renamed_path , _PatchedModuleObj ) assert _test_patching.renamed_path.join is mock # check renamed_join assert _test_patching.renamed_join is mock # check that the other attributes are untouched assert _test_patching.renamed_os.rename is original_rename assert _test_patching.renamed_path.dirname is original_dirname assert _test_patching.renamed_os.path.dirname is original_dirname # check that everthing is back to normal when the patch is over assert _test_patching.os is original_os assert _test_patching.path is original_path assert _test_patching.join is original_join assert _test_patching.renamed_os is original_os assert _test_patching.renamed_path is original_path assert _test_patching.renamed_join is original_join def __lowerCamelCase ( ) -> Optional[int]: assert _test_patching.open is open UpperCamelCase = '''__test_patch_submodule_builtin_mock__''' # _test_patching has "open" in its globals assert _test_patching.open is open with patch_submodule(_test_patching , 'open' , lowercase_ ): assert _test_patching.open is mock # check that everthing is back to normal when the patch is over assert _test_patching.open is open def __lowerCamelCase ( ) -> Dict: UpperCamelCase = '''__test_patch_submodule_missing_mock__''' with patch_submodule(_test_patching , 'pandas.read_csv' , lowercase_ ): pass def __lowerCamelCase ( ) -> Any: UpperCamelCase = '''__test_patch_submodule_missing_builtin_mock__''' # _test_patching doesn't have "len" in its globals assert getattr(_test_patching , 'len' , lowercase_ ) is None with patch_submodule(_test_patching , 'len' , lowercase_ ): assert _test_patching.len is mock assert _test_patching.len is len def __lowerCamelCase ( ) -> Optional[Any]: UpperCamelCase = '''__test_patch_submodule_start_and_stop_mock__''' UpperCamelCase = patch_submodule(_test_patching , 'open' , lowercase_ ) assert _test_patching.open is open patch.start() assert _test_patching.open is mock patch.stop() assert _test_patching.open is open def __lowerCamelCase ( ) -> Optional[Any]: from os import rename as original_rename from os.path import dirname as original_dirname from os.path import join as original_join UpperCamelCase = '''__test_patch_submodule_successive_join__''' UpperCamelCase = '''__test_patch_submodule_successive_dirname__''' UpperCamelCase = '''__test_patch_submodule_successive_rename__''' assert _test_patching.os.path.join is original_join assert _test_patching.os.path.dirname is original_dirname assert _test_patching.os.rename is original_rename with patch_submodule(_test_patching , 'os.path.join' , lowercase_ ): with patch_submodule(_test_patching , 'os.rename' , lowercase_ ): with patch_submodule(_test_patching , 'os.path.dirname' , lowercase_ ): assert _test_patching.os.path.join is mock_join assert _test_patching.os.path.dirname is mock_dirname assert _test_patching.os.rename is mock_rename # try another order with patch_submodule(_test_patching , 'os.rename' , lowercase_ ): with patch_submodule(_test_patching , 'os.path.join' , lowercase_ ): with patch_submodule(_test_patching , 'os.path.dirname' , lowercase_ ): assert _test_patching.os.path.join is mock_join assert _test_patching.os.path.dirname is mock_dirname assert _test_patching.os.rename is mock_rename assert _test_patching.os.path.join is original_join assert _test_patching.os.path.dirname is original_dirname assert _test_patching.os.rename is original_rename def __lowerCamelCase ( ) -> Any: UpperCamelCase = '''__test_patch_submodule_doesnt_exist_mock__''' with patch_submodule(_test_patching , '__module_that_doesn_exist__.__attribute_that_doesn_exist__' , lowercase_ ): pass with patch_submodule(_test_patching , 'os.__attribute_that_doesn_exist__' , lowercase_ ): pass
282
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class snake_case ( unittest.TestCase ): @slow def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = TFAutoModel.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModel.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : List[str] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForPreTraining.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Any ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Optional[int] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = TFAutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForCausalLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForCausalLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Dict ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelForMaskedLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForMaskedLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : str = TFAutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = AutoModelForSeqaSeqLM.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = AutoModelForSeqaSeqLM.from_pretrained( _lowerCamelCase , output_loading_info=_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = TFAutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoModelForSequenceClassification.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: __SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = TFAutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = AutoModelForQuestionAnswering.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Tuple = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Tuple = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_pt=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 ) __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoModelWithLMHead.from_pretrained(_lowerCamelCase , from_tf=_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) self.assertEqual(model.num_parameters() , 1_4_4_1_0 ) self.assertEqual(model.num_parameters(only_trainable=_lowerCamelCase ) , 1_4_4_1_0 )
674
0
"""simple docstring""" import argparse import OmegaConf import torch from diffusers import DDIMScheduler, LDMPipeline, UNetLDMModel, VQModel def UpperCAmelCase ( A__: List[Any] , A__: Optional[int] , A__: List[Any] ) -> int: __lowerCamelCase : Any = OmegaConf.load(lowercase_ ) __lowerCamelCase : List[str] = torch.load(lowercase_ , map_location='cpu' )['''model'''] __lowerCamelCase : List[str] = list(state_dict.keys() ) # extract state_dict for VQVAE __lowerCamelCase : Union[str, Any] = {} __lowerCamelCase : List[Any] = '''first_stage_model.''' for key in keys: if key.startswith(lowercase_ ): __lowerCamelCase : Union[str, Any] = state_dict[key] # extract state_dict for UNetLDM __lowerCamelCase : List[Any] = {} __lowerCamelCase : List[str] = '''model.diffusion_model.''' for key in keys: if key.startswith(lowercase_ ): __lowerCamelCase : Optional[int] = state_dict[key] __lowerCamelCase : Dict = config.model.params.first_stage_config.params __lowerCamelCase : Union[str, Any] = config.model.params.unet_config.params __lowerCamelCase : Optional[Any] = VQModel(**lowercase_ ).eval() vqvae.load_state_dict(lowercase_ ) __lowerCamelCase : Dict = UNetLDMModel(**lowercase_ ).eval() unet.load_state_dict(lowercase_ ) __lowerCamelCase : Union[str, Any] = DDIMScheduler( timesteps=config.model.params.timesteps , beta_schedule='scaled_linear' , beta_start=config.model.params.linear_start , beta_end=config.model.params.linear_end , clip_sample=lowercase_ , ) __lowerCamelCase : Tuple = LDMPipeline(lowercase_ , lowercase_ , lowercase_ ) pipeline.save_pretrained(lowercase_ ) if __name__ == "__main__": a_ : Union[str, Any] = argparse.ArgumentParser() parser.add_argument('''--checkpoint_path''', type=str, required=True) parser.add_argument('''--config_path''', type=str, required=True) parser.add_argument('''--output_path''', type=str, required=True) a_ : int = parser.parse_args() convert_ldm_original(args.checkpoint_path, args.config_path, args.output_path)
594
"""simple docstring""" import os import re import warnings from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer if TYPE_CHECKING: from ...tokenization_utils_base import TextInput from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = {'''vocab_file''': '''spiece.model'''} _lowerCamelCase = { '''vocab_file''': { '''t5-small''': '''https://huggingface.co/t5-small/resolve/main/spiece.model''', '''t5-base''': '''https://huggingface.co/t5-base/resolve/main/spiece.model''', '''t5-large''': '''https://huggingface.co/t5-large/resolve/main/spiece.model''', '''t5-3b''': '''https://huggingface.co/t5-3b/resolve/main/spiece.model''', '''t5-11b''': '''https://huggingface.co/t5-11b/resolve/main/spiece.model''', } } # TODO(PVP) - this should be removed in Transformers v5 _lowerCamelCase = { '''t5-small''': 5_12, '''t5-base''': 5_12, '''t5-large''': 5_12, '''t5-3b''': 5_12, '''t5-11b''': 5_12, } _lowerCamelCase = '''▁''' class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = VOCAB_FILES_NAMES lowerCamelCase__ = PRETRAINED_VOCAB_FILES_MAP lowerCamelCase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowerCamelCase__ = ['''input_ids''', '''attention_mask'''] def __init__( self :int , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Union[str, Any]="</s>" , _lowerCamelCase :List[Any]="<unk>" , _lowerCamelCase :Union[str, Any]="<pad>" , _lowerCamelCase :int=1_0_0 , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :Optional[Dict[str, Any]] = None , _lowerCamelCase :int=True , **_lowerCamelCase :List[Any] , ): # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: __SCREAMING_SNAKE_CASE : Union[str, Any] = [f'''<extra_id_{i}>''' for i in range(_lowerCamelCase )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens __SCREAMING_SNAKE_CASE : Optional[int] = len(set(filter(lambda _lowerCamelCase : bool('''extra_id''' in str(_lowerCamelCase ) ) , _lowerCamelCase ) ) ) if extra_tokens != extra_ids: raise ValueError( f'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are''' ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids''' ''' tokens''' ) if legacy: logger.warning_once( f'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to''' ''' read the related pull request available at https://github.com/huggingface/transformers/pull/24565''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = legacy __SCREAMING_SNAKE_CASE : Optional[int] = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=_lowerCamelCase , unk_token=_lowerCamelCase , pad_token=_lowerCamelCase , extra_ids=_lowerCamelCase , additional_special_tokens=_lowerCamelCase , sp_model_kwargs=self.sp_model_kwargs , legacy=_lowerCamelCase , **_lowerCamelCase , ) __SCREAMING_SNAKE_CASE : Tuple = vocab_file __SCREAMING_SNAKE_CASE : List[str] = extra_ids __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(_lowerCamelCase ) @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :str , _lowerCamelCase :Union[str, Any] , _lowerCamelCase :int ): if pretrained_model_name_or_path in TaTokenizer.max_model_input_sizes: __SCREAMING_SNAKE_CASE : Any = TaTokenizer.max_model_input_sizes[pretrained_model_name_or_path] if init_max_model_length is not None and init_max_model_length != max_model_length: return init_max_model_length elif init_max_model_length is None: warnings.warn( '''This tokenizer was incorrectly instantiated with a model max length of''' f''' {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this''' ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with''' ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on''' f''' {pretrained_model_name_or_path} automatically truncating your input to''' f''' {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences''' f''' longer than {deprecated_max_model_length} you can either instantiate this tokenizer with''' ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please''' ''' instantiate this tokenizer with `model_max_length` set to your preferred value.''' , _lowerCamelCase , ) return max_model_length @property def SCREAMING_SNAKE_CASE_ ( self :Tuple ): return self.sp_model.get_piece_size() + self._extra_ids def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : str = {self.convert_ids_to_tokens(_lowerCamelCase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None , _lowerCamelCase :bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_lowerCamelCase , token_ids_a=_lowerCamelCase , already_has_special_tokens=_lowerCamelCase ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(_lowerCamelCase )) + [1] return ([0] * len(_lowerCamelCase )) + [1] + ([0] * len(_lowerCamelCase )) + [1] def SCREAMING_SNAKE_CASE_ ( self :List[str] ): return list( set(filter(lambda _lowerCamelCase : bool(re.search(r'''<extra_id_\d+>''' , _lowerCamelCase ) ) is not None , self.additional_special_tokens ) ) ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return [self._convert_token_to_id(_lowerCamelCase ) for token in self.get_sentinel_tokens()] def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :List[int] ): if len(_lowerCamelCase ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated''' ''' eos tokens being added.''' ) return token_ids else: return token_ids + [self.eos_token_id] def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def SCREAMING_SNAKE_CASE_ ( self :List[Any] , _lowerCamelCase :List[int] , _lowerCamelCase :Optional[List[int]] = None ): __SCREAMING_SNAKE_CASE : Optional[Any] = self._add_eos_if_not_present(_lowerCamelCase ) if token_ids_a is None: return token_ids_a else: __SCREAMING_SNAKE_CASE : Union[str, Any] = self._add_eos_if_not_present(_lowerCamelCase ) return token_ids_a + token_ids_a def __getstate__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Any = self.__dict__.copy() __SCREAMING_SNAKE_CASE : List[str] = None return state def __setstate__( self :Optional[Any] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : Tuple = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): __SCREAMING_SNAKE_CASE : Optional[int] = {} __SCREAMING_SNAKE_CASE : Optional[int] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :"TextInput" , **_lowerCamelCase :str ): # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at # the beginning of the text if not self.legacy: __SCREAMING_SNAKE_CASE : Dict = SPIECE_UNDERLINE + text.replace(_lowerCamelCase , ''' ''' ) return super().tokenize(_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :List[Any] , **_lowerCamelCase :Dict ): if not self.legacy: __SCREAMING_SNAKE_CASE : str = text.startswith(_lowerCamelCase ) if is_first: __SCREAMING_SNAKE_CASE : str = text[1:] __SCREAMING_SNAKE_CASE : Tuple = self.sp_model.encode(_lowerCamelCase , out_type=_lowerCamelCase ) if not self.legacy and not is_first and not text.startswith(''' ''' ) and tokens[0].startswith(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[int] = ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:] return tokens def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[Any] ): if token.startswith('''<extra_id_''' ): __SCREAMING_SNAKE_CASE : Tuple = re.match(r'''<extra_id_(\d+)>''' , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = int(match.group(1 ) ) return self.vocab_size - num - 1 return self.sp_model.piece_to_id(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): if index < self.sp_model.get_piece_size(): __SCREAMING_SNAKE_CASE : List[Any] = self.sp_model.IdToPiece(_lowerCamelCase ) else: __SCREAMING_SNAKE_CASE : Dict = f'''<extra_id_{self.vocab_size - 1 - index}>''' return token def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : str = [] __SCREAMING_SNAKE_CASE : Dict = '''''' __SCREAMING_SNAKE_CASE : Dict = 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(_lowerCamelCase ) + token __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : str = [] else: current_sub_tokens.append(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = False out_string += self.sp_model.decode(_lowerCamelCase ) return out_string.strip() def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :str , _lowerCamelCase :Optional[str] = None ): if not os.path.isdir(_lowerCamelCase ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __SCREAMING_SNAKE_CASE : List[str] = os.path.join( _lowerCamelCase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(_lowerCamelCase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , _lowerCamelCase ) elif not os.path.isfile(self.vocab_file ): with open(_lowerCamelCase , '''wb''' ) as fi: __SCREAMING_SNAKE_CASE : Any = self.sp_model.serialized_model_proto() fi.write(_lowerCamelCase ) return (out_vocab_file,)
674
0
from __future__ import annotations from collections import deque from collections.abc import Sequence from dataclasses import dataclass from typing import Any @dataclass class UpperCAmelCase : lowercase = 4_2 lowercase = None lowercase = None def _lowercase ( ): """simple docstring""" UpperCamelCase = Node(1 ) UpperCamelCase = Node(2 ) UpperCamelCase = Node(3 ) UpperCamelCase = Node(4 ) UpperCamelCase = Node(5 ) return tree def _lowercase ( SCREAMING_SNAKE_CASE_ : Node | None ): """simple docstring""" return [root.data, *preorder(root.left ), *preorder(root.right )] if root else [] def _lowercase ( SCREAMING_SNAKE_CASE_ : Node | None ): """simple docstring""" return postorder(root.left ) + postorder(root.right ) + [root.data] if root else [] def _lowercase ( SCREAMING_SNAKE_CASE_ : Node | None ): """simple docstring""" return [*inorder(root.left ), root.data, *inorder(root.right )] if root else [] def _lowercase ( SCREAMING_SNAKE_CASE_ : Node | None ): """simple docstring""" return (max(height(root.left ) , height(root.right ) ) + 1) if root else 0 def _lowercase ( SCREAMING_SNAKE_CASE_ : Node | None ): """simple docstring""" UpperCamelCase = [] if root is None: return output UpperCamelCase = deque([root] ) while process_queue: UpperCamelCase = process_queue.popleft() output.append(node.data ) if node.left: process_queue.append(node.left ) if node.right: process_queue.append(node.right ) return output def _lowercase ( SCREAMING_SNAKE_CASE_ : Node | None , SCREAMING_SNAKE_CASE_ : int ): """simple docstring""" UpperCamelCase = [] def populate_output(SCREAMING_SNAKE_CASE_ : Node | None , SCREAMING_SNAKE_CASE_ : int ) -> None: if not root: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.left , level - 1 ) populate_output(root.right , level - 1 ) populate_output(lowercase_ , lowercase_ ) return output def _lowercase ( SCREAMING_SNAKE_CASE_ : Node | None , SCREAMING_SNAKE_CASE_ : int ): """simple docstring""" UpperCamelCase = [] def populate_output(SCREAMING_SNAKE_CASE_ : Node | None , SCREAMING_SNAKE_CASE_ : int ) -> None: if root is None: return if level == 1: output.append(root.data ) elif level > 1: populate_output(root.right , level - 1 ) populate_output(root.left , level - 1 ) populate_output(lowercase_ , lowercase_ ) return output def _lowercase ( SCREAMING_SNAKE_CASE_ : Node | None ): """simple docstring""" if root is None: return [] UpperCamelCase = [] UpperCamelCase = 0 UpperCamelCase = height(lowercase_ ) for h in range(1 , height_tree + 1 ): if not flag: output.append(get_nodes_from_left_to_right(lowercase_ , lowercase_ ) ) UpperCamelCase = 1 else: output.append(get_nodes_from_right_to_left(lowercase_ , lowercase_ ) ) UpperCamelCase = 0 return output def _lowercase ( ): # Main function for testing. """simple docstring""" UpperCamelCase = make_tree() print(f'In-order Traversal: {inorder(lowercase_ )}' ) print(f'Pre-order Traversal: {preorder(lowercase_ )}' ) print(f'Post-order Traversal: {postorder(lowercase_ )}' , """\n""" ) print(f'Height of Tree: {height(lowercase_ )}' , """\n""" ) print("""Complete Level Order Traversal: """ ) print(level_order(lowercase_ ) , """\n""" ) print("""Level-wise order Traversal: """ ) for level in range(1 , height(lowercase_ ) + 1 ): print(f'Level {level}:' , get_nodes_from_left_to_right(lowercase_ , level=lowercase_ ) ) print("""\nZigZag order Traversal: """ ) print(zigzag(lowercase_ ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
386
"""simple docstring""" import os import pytest import yaml from datasets.features.features import Features, Value from datasets.info import DatasetInfo, DatasetInfosDict @pytest.mark.parametrize( '''files''' , [ ['''full:README.md''', '''dataset_infos.json'''], ['''empty:README.md''', '''dataset_infos.json'''], ['''dataset_infos.json'''], ['''full:README.md'''], ] , ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = tmp_path_factory.mktemp('''dset_infos_dir''' ) if "full:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''---\ndataset_info:\n dataset_size: 42\n---''' ) if "empty:README.md" in files: with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f: f.write('''''' ) # we want to support dataset_infos.json for backward compatibility if "dataset_infos.json" in files: with open(dataset_infos_dir / '''dataset_infos.json''' , '''w''' ) as f: f.write('''{"default": {"dataset_size": 42}}''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) assert dataset_infos assert dataset_infos["default"].dataset_size == 42 @pytest.mark.parametrize( '''dataset_info''' , [ DatasetInfo(), DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ), ] , ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : DatasetInfo ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[str] = str(lowercase_ ) dataset_info.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Dict = DatasetInfo.from_directory(lowercase_ ) assert dataset_info == reloaded assert os.path.exists(os.path.join(lowercase_ , '''dataset_info.json''' ) ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo( description='''foo''' , citation='''bar''' , homepage='''https://foo.bar''' , license='''CC0''' , features=Features({'''a''': Value('''int32''' )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train''', '''num_examples''': 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , ) __SCREAMING_SNAKE_CASE : Optional[int] = dataset_info._to_yaml_dict() assert sorted(lowercase_ ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML ) for key in DatasetInfo._INCLUDED_INFO_IN_YAML: assert key in dataset_info_yaml_dict assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) ) __SCREAMING_SNAKE_CASE : int = yaml.safe_dump(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = yaml.safe_load(lowercase_ ) assert dataset_info_yaml_dict == reloaded def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = DatasetInfo() __SCREAMING_SNAKE_CASE : Union[str, Any] = dataset_info._to_yaml_dict() assert dataset_info_yaml_dict == {} @pytest.mark.parametrize( '''dataset_infos_dict''' , [ DatasetInfosDict(), DatasetInfosDict({'''default''': DatasetInfo()} ), DatasetInfosDict({'''my_config_name''': DatasetInfo()} ), DatasetInfosDict( { '''default''': DatasetInfo( description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ) } ), DatasetInfosDict( { '''v1''': DatasetInfo(dataset_size=42 ), '''v2''': DatasetInfo(dataset_size=1337 ), } ), ] , ) def lowerCAmelCase_ ( lowercase_ : List[Any] , lowercase_ : DatasetInfosDict ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) dataset_infos_dict.write_to_directory(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[Any] = DatasetInfosDict.from_directory(lowercase_ ) # the config_name of the dataset_infos_dict take over the attribute for config_name, dataset_info in dataset_infos_dict.items(): __SCREAMING_SNAKE_CASE : Optional[int] = config_name # the yaml representation doesn't include fields like description or citation # so we just test that we can recover what we can from the yaml __SCREAMING_SNAKE_CASE : Tuple = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() ) assert dataset_infos_dict == reloaded if dataset_infos_dict: assert os.path.exists(os.path.join(lowercase_ , '''README.md''' ) )
674
0
import tempfile import torch from diffusers import IPNDMScheduler from .test_schedulers import SchedulerCommonTest class SCREAMING_SNAKE_CASE_ ( __UpperCAmelCase ): """simple docstring""" __magic_name__ : Any = (IPNDMScheduler,) __magic_name__ : List[Any] = (('num_inference_steps', 50),) def lowerCamelCase__ ( self : Optional[int] , **lowerCAmelCase : Tuple ) -> Optional[int]: """simple docstring""" __UpperCamelCase : Union[str, Any] = {'''num_train_timesteps''': 1000} config.update(**_lowerCamelCase ) return config def lowerCamelCase__ ( self : List[Any] , lowerCAmelCase : List[Any]=0 , **lowerCAmelCase : Union[str, Any] ) -> List[Any]: """simple docstring""" __UpperCamelCase : int = dict(self.forward_default_kwargs ) __UpperCamelCase : List[Any] = kwargs.pop("""num_inference_steps""" , _lowerCamelCase ) __UpperCamelCase : Optional[int] = self.dummy_sample __UpperCamelCase : Optional[int] = 0.1 * sample __UpperCamelCase : Optional[Any] = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: __UpperCamelCase : List[str] = self.get_scheduler_config(**_lowerCamelCase ) __UpperCamelCase : Optional[Any] = scheduler_class(**_lowerCamelCase ) scheduler.set_timesteps(_lowerCamelCase ) # copy over dummy past residuals __UpperCamelCase : Union[str, Any] = dummy_past_residuals[:] if time_step is None: __UpperCamelCase : Tuple = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(_lowerCamelCase ) __UpperCamelCase : Any = scheduler_class.from_pretrained(_lowerCamelCase ) new_scheduler.set_timesteps(_lowerCamelCase ) # copy over dummy past residuals __UpperCamelCase : Any = dummy_past_residuals[:] __UpperCamelCase : List[Any] = scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample __UpperCamelCase : Optional[Any] = new_scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" __UpperCamelCase : Any = scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample __UpperCamelCase : Tuple = new_scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def lowerCamelCase__ ( self : List[str] ) -> List[str]: """simple docstring""" pass def lowerCamelCase__ ( self : Any , lowerCAmelCase : Any=0 , **lowerCAmelCase : List[str] ) -> Union[str, Any]: """simple docstring""" __UpperCamelCase : Optional[int] = dict(self.forward_default_kwargs ) __UpperCamelCase : Any = kwargs.pop("""num_inference_steps""" , _lowerCamelCase ) __UpperCamelCase : Tuple = self.dummy_sample __UpperCamelCase : List[Any] = 0.1 * sample __UpperCamelCase : Optional[Any] = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] for scheduler_class in self.scheduler_classes: __UpperCamelCase : Dict = self.get_scheduler_config() __UpperCamelCase : int = scheduler_class(**_lowerCamelCase ) scheduler.set_timesteps(_lowerCamelCase ) # copy over dummy past residuals (must be after setting timesteps) __UpperCamelCase : Any = dummy_past_residuals[:] if time_step is None: __UpperCamelCase : str = scheduler.timesteps[len(scheduler.timesteps ) // 2] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(_lowerCamelCase ) __UpperCamelCase : List[str] = scheduler_class.from_pretrained(_lowerCamelCase ) # copy over dummy past residuals new_scheduler.set_timesteps(_lowerCamelCase ) # copy over dummy past residual (must be after setting timesteps) __UpperCamelCase : Any = dummy_past_residuals[:] __UpperCamelCase : Union[str, Any] = scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample __UpperCamelCase : Union[str, Any] = new_scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" __UpperCamelCase : int = scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample __UpperCamelCase : Dict = new_scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def lowerCamelCase__ ( self : Dict , **lowerCAmelCase : Optional[Any] ) -> Union[str, Any]: """simple docstring""" __UpperCamelCase : List[Any] = self.scheduler_classes[0] __UpperCamelCase : Optional[int] = self.get_scheduler_config(**_lowerCamelCase ) __UpperCamelCase : Tuple = scheduler_class(**_lowerCamelCase ) __UpperCamelCase : Union[str, Any] = 10 __UpperCamelCase : Any = self.dummy_model() __UpperCamelCase : Optional[int] = self.dummy_sample_deter scheduler.set_timesteps(_lowerCamelCase ) for i, t in enumerate(scheduler.timesteps ): __UpperCamelCase : Union[str, Any] = model(_lowerCamelCase , _lowerCamelCase ) __UpperCamelCase : List[Any] = scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ).prev_sample for i, t in enumerate(scheduler.timesteps ): __UpperCamelCase : Union[str, Any] = model(_lowerCamelCase , _lowerCamelCase ) __UpperCamelCase : str = scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ).prev_sample return sample def lowerCamelCase__ ( self : Dict ) -> Optional[Any]: """simple docstring""" __UpperCamelCase : Optional[int] = dict(self.forward_default_kwargs ) __UpperCamelCase : int = kwargs.pop("""num_inference_steps""" , _lowerCamelCase ) for scheduler_class in self.scheduler_classes: __UpperCamelCase : List[Any] = self.get_scheduler_config() __UpperCamelCase : str = scheduler_class(**_lowerCamelCase ) __UpperCamelCase : str = self.dummy_sample __UpperCamelCase : Dict = 0.1 * sample if num_inference_steps is not None and hasattr(_lowerCamelCase , """set_timesteps""" ): scheduler.set_timesteps(_lowerCamelCase ) elif num_inference_steps is not None and not hasattr(_lowerCamelCase , """set_timesteps""" ): __UpperCamelCase : str = num_inference_steps # copy over dummy past residuals (must be done after set_timesteps) __UpperCamelCase : List[str] = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05] __UpperCamelCase : Dict = dummy_past_residuals[:] __UpperCamelCase : Any = scheduler.timesteps[5] __UpperCamelCase : Optional[int] = scheduler.timesteps[6] __UpperCamelCase : List[str] = scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample __UpperCamelCase : Dict = scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) __UpperCamelCase : List[Any] = scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample __UpperCamelCase : Dict = scheduler.step(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , **_lowerCamelCase ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def lowerCamelCase__ ( self : Optional[int] ) -> Tuple: """simple docstring""" for timesteps in [100, 1000]: self.check_over_configs(num_train_timesteps=_lowerCamelCase , time_step=_lowerCamelCase ) def lowerCamelCase__ ( self : Tuple ) -> Any: """simple docstring""" for t, num_inference_steps in zip([1, 5, 10] , [10, 50, 100] ): self.check_over_forward(num_inference_steps=_lowerCamelCase , time_step=_lowerCamelCase ) def lowerCamelCase__ ( self : Optional[int] ) -> Tuple: """simple docstring""" __UpperCamelCase : Dict = self.full_loop() __UpperCamelCase : Dict = torch.mean(torch.abs(_lowerCamelCase ) ) assert abs(result_mean.item() - 2540529 ) < 10
279
"""simple docstring""" from typing import Optional, Union import torch from torch import nn from ...configuration_utils import ConfigMixin, register_to_config from ...models.modeling_utils import ModelMixin class snake_case ( __UpperCAmelCase , __UpperCAmelCase ): @register_to_config def __init__( self :List[str] , _lowerCamelCase :int = 7_6_8 , ): super().__init__() __SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter(torch.zeros(1 , _lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : List[Any] = nn.Parameter(torch.ones(1 , _lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any , _lowerCamelCase :Optional[Union[str, torch.device]] = None , _lowerCamelCase :Optional[torch.dtype] = None , ): __SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter(self.mean.to(_lowerCamelCase ).to(_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Tuple = nn.Parameter(self.std.to(_lowerCamelCase ).to(_lowerCamelCase ) ) return self def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Tuple = (embeds - self.mean) * 1.0 / self.std return embeds def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = (embeds * self.std) + self.mean return embeds
674
0
import tempfile import numpy as np import torch from transformers import AutoTokenizer, TaEncoderModel from diffusers import DDPMScheduler, UNetaDConditionModel from diffusers.models.attention_processor import AttnAddedKVProcessor from diffusers.pipelines.deepfloyd_if import IFWatermarker from diffusers.utils.testing_utils import torch_device from ..test_pipelines_common import to_np class lowerCamelCase : def snake_case__ ( self :Any ) -> Dict: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = TaEncoderModel.from_pretrained('''hf-internal-testing/tiny-random-t5''' ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-t5''' ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = UNetaDConditionModel( sample_size=3_2 , layers_per_block=1 , block_out_channels=[3_2, 6_4] , down_block_types=[ '''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D''', ] , mid_block_type='''UNetMidBlock2DSimpleCrossAttn''' , up_block_types=['''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''] , in_channels=3 , out_channels=6 , cross_attention_dim=3_2 , encoder_hid_dim=3_2 , attention_head_dim=8 , addition_embed_type='''text''' , addition_embed_type_num_heads=2 , cross_attention_norm='''group_norm''' , resnet_time_scale_shift='''scale_shift''' , act_fn='''gelu''' , ) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = DDPMScheduler( num_train_timesteps=1_0_0_0 , beta_schedule='''squaredcos_cap_v2''' , beta_start=0.00_01 , beta_end=0.02 , thresholding=_lowerCamelCase , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type='''epsilon''' , variance_type='''learned_range''' , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def snake_case__ ( self :Tuple ) -> Union[str, Any]: """simple docstring""" torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = TaEncoderModel.from_pretrained('''hf-internal-testing/tiny-random-t5''' ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-t5''' ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = UNetaDConditionModel( sample_size=3_2 , layers_per_block=[1, 2] , block_out_channels=[3_2, 6_4] , down_block_types=[ '''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D''', ] , mid_block_type='''UNetMidBlock2DSimpleCrossAttn''' , up_block_types=['''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''] , in_channels=6 , out_channels=6 , cross_attention_dim=3_2 , encoder_hid_dim=3_2 , attention_head_dim=8 , addition_embed_type='''text''' , addition_embed_type_num_heads=2 , cross_attention_norm='''group_norm''' , resnet_time_scale_shift='''scale_shift''' , act_fn='''gelu''' , class_embed_type='''timestep''' , mid_block_scale_factor=1.4_14 , time_embedding_act_fn='''gelu''' , time_embedding_dim=3_2 , ) unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = DDPMScheduler( num_train_timesteps=1_0_0_0 , beta_schedule='''squaredcos_cap_v2''' , beta_start=0.00_01 , beta_end=0.02 , thresholding=_lowerCamelCase , dynamic_thresholding_ratio=0.95 , sample_max_value=1.0 , prediction_type='''epsilon''' , variance_type='''learned_range''' , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = DDPMScheduler( num_train_timesteps=1_0_0_0 , beta_schedule='''squaredcos_cap_v2''' , beta_start=0.00_01 , beta_end=0.02 , ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE = IFWatermarker() return { "text_encoder": text_encoder, "tokenizer": tokenizer, "unet": unet, "scheduler": scheduler, "image_noising_scheduler": image_noising_scheduler, "watermarker": watermarker, "safety_checker": None, "feature_extractor": None, } def snake_case__ ( self :Optional[Any] ) -> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**_lowerCamelCase ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(_lowerCamelCase ) SCREAMING_SNAKE_CASE = inputs['''prompt'''] SCREAMING_SNAKE_CASE = inputs['''generator'''] SCREAMING_SNAKE_CASE = inputs['''num_inference_steps'''] SCREAMING_SNAKE_CASE = inputs['''output_type'''] if "image" in inputs: SCREAMING_SNAKE_CASE = inputs['''image'''] else: SCREAMING_SNAKE_CASE = None if "mask_image" in inputs: SCREAMING_SNAKE_CASE = inputs['''mask_image'''] else: SCREAMING_SNAKE_CASE = None if "original_image" in inputs: SCREAMING_SNAKE_CASE = inputs['''original_image'''] else: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = pipe.encode_prompt(_lowerCamelCase ) # inputs with prompt converted to embeddings SCREAMING_SNAKE_CASE = { '''prompt_embeds''': prompt_embeds, '''negative_prompt_embeds''': negative_prompt_embeds, '''generator''': generator, '''num_inference_steps''': num_inference_steps, '''output_type''': output_type, } if image is not None: SCREAMING_SNAKE_CASE = image if mask_image is not None: SCREAMING_SNAKE_CASE = mask_image if original_image is not None: SCREAMING_SNAKE_CASE = original_image # set all optional components to None for optional_component in pipe._optional_components: setattr(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase ) SCREAMING_SNAKE_CASE = pipe(**_lowerCamelCase )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(_lowerCamelCase ) SCREAMING_SNAKE_CASE = self.pipeline_class.from_pretrained(_lowerCamelCase ) pipe_loaded.to(_lowerCamelCase ) pipe_loaded.set_progress_bar_config(disable=_lowerCamelCase ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests for optional_component in pipe._optional_components: self.assertTrue( getattr(_lowerCamelCase , _lowerCamelCase ) is None , f"""`{optional_component}` did not stay set to None after loading.""" , ) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(_lowerCamelCase ) SCREAMING_SNAKE_CASE = inputs['''generator'''] SCREAMING_SNAKE_CASE = inputs['''num_inference_steps'''] SCREAMING_SNAKE_CASE = inputs['''output_type'''] # inputs with prompt converted to embeddings SCREAMING_SNAKE_CASE = { '''prompt_embeds''': prompt_embeds, '''negative_prompt_embeds''': negative_prompt_embeds, '''generator''': generator, '''num_inference_steps''': num_inference_steps, '''output_type''': output_type, } if image is not None: SCREAMING_SNAKE_CASE = image if mask_image is not None: SCREAMING_SNAKE_CASE = mask_image if original_image is not None: SCREAMING_SNAKE_CASE = original_image SCREAMING_SNAKE_CASE = pipe_loaded(**_lowerCamelCase )[0] SCREAMING_SNAKE_CASE = np.abs(to_np(_lowerCamelCase ) - to_np(_lowerCamelCase ) ).max() self.assertLess(_lowerCamelCase , 1e-4 ) def snake_case__ ( self :int ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE = self.get_dummy_components() SCREAMING_SNAKE_CASE = self.pipeline_class(**_lowerCamelCase ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) SCREAMING_SNAKE_CASE = self.get_dummy_inputs(_lowerCamelCase ) SCREAMING_SNAKE_CASE = pipe(**_lowerCamelCase )[0] with tempfile.TemporaryDirectory() as tmpdir: pipe.save_pretrained(_lowerCamelCase ) SCREAMING_SNAKE_CASE = self.pipeline_class.from_pretrained(_lowerCamelCase ) pipe_loaded.to(_lowerCamelCase ) pipe_loaded.set_progress_bar_config(disable=_lowerCamelCase ) pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor() ) # For reproducibility tests SCREAMING_SNAKE_CASE = self.get_dummy_inputs(_lowerCamelCase ) SCREAMING_SNAKE_CASE = pipe_loaded(**_lowerCamelCase )[0] SCREAMING_SNAKE_CASE = np.abs(to_np(_lowerCamelCase ) - to_np(_lowerCamelCase ) ).max() self.assertLess(_lowerCamelCase , 1e-4 )
201
"""simple docstring""" import argparse import torch from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase_ ( lowercase_ : Dict , lowercase_ : int , lowercase_ : Any ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Tuple = BertConfig.from_json_file(lowercase_ ) print(F'''Building PyTorch model from configuration: {config}''' ) __SCREAMING_SNAKE_CASE : Optional[int] = BertForPreTraining(lowercase_ ) # Load weights from tf checkpoint load_tf_weights_in_bert(lowercase_ , lowercase_ , lowercase_ ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) torch.save(model.state_dict() , lowercase_ ) if __name__ == "__main__": _lowerCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--tf_checkpoint_path''', default=None, type=str, required=True, help='''Path to the TensorFlow checkpoint path.''' ) parser.add_argument( '''--bert_config_file''', default=None, type=str, required=True, help=( '''The config json file corresponding to the pre-trained BERT model. \n''' '''This specifies the model architecture.''' ), ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) _lowerCamelCase = parser.parse_args() convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
674
0
"""simple docstring""" def lowercase__(A ) ->str: """simple docstring""" lowercase__ : Dict= int(lowercase_ ) if decimal in (0, 1): # Exit cases for the recursion return str(lowercase_ ) lowercase__ : List[Any]= divmod(lowercase_ , 2 ) return binary_recursive(lowercase_ ) + str(lowercase_ ) def lowercase__(A ) ->List[str]: """simple docstring""" lowercase__ : int= str(lowercase_ ).strip() if not number: raise ValueError("No input value was provided" ) lowercase__ : Union[str, Any]= '''-''' if number.startswith("-" ) else '''''' lowercase__ : str= number.lstrip("-" ) if not number.isnumeric(): raise ValueError("Input value is not an integer" ) return f'''{negative}0b{binary_recursive(int(lowercase_ ) )}''' if __name__ == "__main__": from doctest import testmod testmod()
218
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np import torch from ..models.clipseg import CLIPSegForImageSegmentation from ..utils import is_vision_available, requires_backends from .base import PipelineTool if is_vision_available(): from PIL import Image class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = ( '''This is a tool that creates a segmentation mask of an image according to a label. It cannot create an image.''' '''It takes two arguments named `image` which should be the original image, and `label` which should be a text ''' '''describing the elements what should be identified in the segmentation mask. The tool returns the mask.''' ) lowerCamelCase__ = '''CIDAS/clipseg-rd64-refined''' lowerCamelCase__ = '''image_segmenter''' lowerCamelCase__ = CLIPSegForImageSegmentation lowerCamelCase__ = ['''image''', '''text'''] lowerCamelCase__ = ['''image'''] def __init__( self :Dict , *_lowerCamelCase :Union[str, Any] , **_lowerCamelCase :Tuple ): requires_backends(self , ['''vision'''] ) super().__init__(*_lowerCamelCase , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :"Image" , _lowerCamelCase :str ): return self.pre_processor(text=[label] , images=[image] , padding=_lowerCamelCase , return_tensors='''pt''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] , _lowerCamelCase :Optional[int] ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = self.model(**_lowerCamelCase ).logits return logits def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Tuple ): __SCREAMING_SNAKE_CASE : Optional[int] = outputs.cpu().detach().numpy() __SCREAMING_SNAKE_CASE : str = 0 __SCREAMING_SNAKE_CASE : str = 1 return Image.fromarray((array * 2_5_5).astype(np.uinta ) )
674
0
import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def __snake_case ( _UpperCamelCase ) -> Optional[Any]: _a = args.pruning_method _a = args.threshold _a = args.model_name_or_path.rstrip('''/''' ) _a = args.target_model_path print(f"Load fine-pruned model from {model_name_or_path}" ) _a = torch.load(os.path.join(lowercase_ , '''pytorch_model.bin''' ) ) _a = {} for name, tensor in model.items(): if "embeddings" in name or "LayerNorm" in name or "pooler" in name: _a = tensor print(f"Copied layer {name}" ) elif "classifier" in name or "qa_output" in name: _a = tensor print(f"Copied layer {name}" ) elif "bias" in name: _a = tensor print(f"Copied layer {name}" ) else: if pruning_method == "magnitude": _a = MagnitudeBinarizer.apply(inputs=lowercase_ , threshold=lowercase_ ) _a = tensor * mask print(f"Pruned layer {name}" ) elif pruning_method == "topK": if "mask_scores" in name: continue _a = name[:-6] _a = model[f"{prefix_}mask_scores"] _a = TopKBinarizer.apply(lowercase_ , lowercase_ ) _a = tensor * mask print(f"Pruned layer {name}" ) elif pruning_method == "sigmoied_threshold": if "mask_scores" in name: continue _a = name[:-6] _a = model[f"{prefix_}mask_scores"] _a = ThresholdBinarizer.apply(lowercase_ , lowercase_ , lowercase_ ) _a = tensor * mask print(f"Pruned layer {name}" ) elif pruning_method == "l0": if "mask_scores" in name: continue _a = name[:-6] _a = model[f"{prefix_}mask_scores"] _a = -0.1, 1.1 _a = torch.sigmoid(lowercase_ ) _a = s * (r - l) + l _a = s_bar.clamp(min=0.0 , max=1.0 ) _a = tensor * mask print(f"Pruned layer {name}" ) else: raise ValueError('''Unknown pruning method''' ) if target_model_path is None: _a = os.path.join( os.path.dirname(lowercase_ ) , f"bertarized_{os.path.basename(lowercase_ )}" ) if not os.path.isdir(lowercase_ ): shutil.copytree(lowercase_ , lowercase_ ) print(f"\nCreated folder {target_model_path}" ) torch.save(lowercase_ , os.path.join(lowercase_ , '''pytorch_model.bin''' ) ) print('''\nPruned model saved! See you later!''' ) if __name__ == "__main__": lowerCamelCase :Any = argparse.ArgumentParser() parser.add_argument( '--pruning_method', choices=['l0', 'magnitude', 'topK', 'sigmoied_threshold'], type=str, required=True, help=( 'Pruning Method (l0 = L0 regularization, magnitude = Magnitude pruning, topK = Movement pruning,' ' sigmoied_threshold = Soft movement pruning)' ), ) parser.add_argument( '--threshold', type=float, required=False, help=( 'For `magnitude` and `topK`, it is the level of remaining weights (in %) in the fine-pruned model.' 'For `sigmoied_threshold`, it is the threshold \tau against which the (sigmoied) scores are compared.' 'Not needed for `l0`' ), ) parser.add_argument( '--model_name_or_path', type=str, required=True, help='Folder containing the model that was previously fine-pruned', ) parser.add_argument( '--target_model_path', default=None, type=str, required=False, help='Folder containing the model that was previously fine-pruned', ) lowerCamelCase :int = parser.parse_args() main(args)
487
"""simple docstring""" import json import os import shutil import tempfile import unittest import numpy as np from transformers import BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer from transformers.testing_utils import require_tokenizers, require_vision from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor @require_tokenizers @require_vision class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp() # fmt: off __SCREAMING_SNAKE_CASE : Optional[int] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest'''] # fmt: on __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer: vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) ) __SCREAMING_SNAKE_CASE : Optional[int] = { '''do_resize''': True, '''size''': {'''height''': 1_8, '''width''': 1_8}, '''do_normalize''': True, '''image_mean''': [0.5, 0.5, 0.5], '''image_std''': [0.5, 0.5, 0.5], } __SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , _lowerCamelCase ) with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp: json.dump(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , **_lowerCamelCase :List[str] ): return BertTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] , **_lowerCamelCase :Optional[int] ): return ViTImageProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): shutil.rmtree(self.tmpdirname ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Union[str, Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )] __SCREAMING_SNAKE_CASE : Tuple = [Image.fromarray(np.moveaxis(_lowerCamelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : str = VisionTextDualEncoderProcessor( tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) __SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' ) __SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor(do_normalize=_lowerCamelCase , padding_value=1.0 ) __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained( self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_lowerCamelCase , padding_value=1.0 ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor() __SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : Optional[int] = image_processor(_lowerCamelCase , return_tensors='''np''' ) __SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , return_tensors='''np''' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : Any = self.get_image_processor() __SCREAMING_SNAKE_CASE : Any = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Optional[int] = processor(text=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = tokenizer(_lowerCamelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : int = self.get_tokenizer() __SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = '''lower newer''' __SCREAMING_SNAKE_CASE : int = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : int = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] ) # test if it raises when no input is passed with self.assertRaises(_lowerCamelCase ): processor() def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Dict = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] __SCREAMING_SNAKE_CASE : Tuple = processor.batch_decode(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = tokenizer.batch_decode(_lowerCamelCase ) self.assertListEqual(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : str = self.get_image_processor() __SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer() __SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = '''lower newer''' __SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs() __SCREAMING_SNAKE_CASE : str = processor(text=_lowerCamelCase , images=_lowerCamelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
674
0
"""simple docstring""" from __future__ import annotations import string from itertools import cycle, product from pathlib import Path a_ = ( string.ascii_letters + string.digits + string.punctuation + string.whitespace ) a_ = [ord(letter) for letter in string.ascii_lowercase] a_ = {ord(char) for char in VALID_CHARS} a_ = ['the', 'be', 'to', 'of', 'and', 'in', 'that', 'have'] def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase ): __lowercase : str = "" __lowercase : int __lowercase : int __lowercase : int for keychar, cipherchar in zip(cycle(lowercase_ ) , lowercase_ ): __lowercase : List[str] = cipherchar ^ keychar if decodedchar not in VALID_INTS: return None decoded += chr(lowercase_ ) return decoded def __UpperCAmelCase ( __UpperCamelCase ): __lowercase : list[str] = [] for key in product(lowercase_ , repeat=3 ): __lowercase : List[Any] = try_key(lowercase_ , lowercase_ ) if encoded is not None: possibles.append(lowercase_ ) return possibles def __UpperCAmelCase ( __UpperCamelCase , __UpperCamelCase ): return [possible for possible in possibles if common_word in possible.lower()] def __UpperCAmelCase ( __UpperCamelCase = "p059_cipher.txt" ): __lowercase : list[int] __lowercase : list[str] __lowercase : str __lowercase : str __lowercase : str = Path(lowercase_ ).parent.joinpath(lowercase_ ).read_text(encoding='''utf-8''' ) __lowercase : Optional[Any] = [int(lowercase_ ) for number in data.strip().split(''',''' )] __lowercase : Optional[int] = filter_valid_chars(lowercase_ ) for common_word in COMMON_WORDS: __lowercase : Union[str, Any] = filter_common_word(lowercase_ , lowercase_ ) if len(lowercase_ ) == 1: break __lowercase : List[str] = possibles[0] return sum(ord(lowercase_ ) for char in decoded_text ) if __name__ == "__main__": print(F"{solution() = }")
76
"""simple docstring""" import inspect import unittest import numpy as np from tests.test_modeling_common import floats_tensor from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel if is_vision_available(): from transformers import MaskFormerImageProcessor if is_vision_available(): from PIL import Image class snake_case : def __init__( self :Optional[int] , _lowerCamelCase :int , _lowerCamelCase :Any=2 , _lowerCamelCase :List[str]=True , _lowerCamelCase :str=False , _lowerCamelCase :Tuple=1_0 , _lowerCamelCase :str=3 , _lowerCamelCase :str=3_2 * 4 , _lowerCamelCase :Dict=3_2 * 6 , _lowerCamelCase :str=4 , _lowerCamelCase :Any=3_2 , ): __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Tuple = batch_size __SCREAMING_SNAKE_CASE : Optional[Any] = is_training __SCREAMING_SNAKE_CASE : Dict = use_auxiliary_loss __SCREAMING_SNAKE_CASE : List[str] = num_queries __SCREAMING_SNAKE_CASE : Optional[int] = num_channels __SCREAMING_SNAKE_CASE : List[Any] = min_size __SCREAMING_SNAKE_CASE : int = max_size __SCREAMING_SNAKE_CASE : Any = num_labels __SCREAMING_SNAKE_CASE : Union[str, Any] = mask_feature_size def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : str = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.ones([self.batch_size, self.min_size, self.max_size] , device=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=_lowerCamelCase ) > 0.5 ).float() __SCREAMING_SNAKE_CASE : Dict = (torch.rand((self.batch_size, self.num_labels) , device=_lowerCamelCase ) > 0.5).long() __SCREAMING_SNAKE_CASE : str = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): return MaskFormerConfig.from_backbone_and_decoder_configs( backbone_config=SwinConfig( depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig( decoder_ffn_dim=1_2_8 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , ) def SCREAMING_SNAKE_CASE_ ( self :str ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Any = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask} return config, inputs_dict def SCREAMING_SNAKE_CASE_ ( self :int , _lowerCamelCase :int , _lowerCamelCase :Optional[int] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = output.encoder_hidden_states __SCREAMING_SNAKE_CASE : int = output.pixel_decoder_hidden_states __SCREAMING_SNAKE_CASE : Optional[int] = output.transformer_decoder_hidden_states self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(_lowerCamelCase ) , config.decoder_config.decoder_layers ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :str , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any]=False ): with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = MaskFormerModel(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() __SCREAMING_SNAKE_CASE : str = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , output_hidden_states=_lowerCamelCase ) # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the # encoder and pixel decoder self.parent.assertEqual( output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , ) # let's ensure the other two hidden state exists self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(output.encoder_last_hidden_state is not None ) if output_hidden_states: self.check_output_hidden_state(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Optional[int] , _lowerCamelCase :Optional[Any] , _lowerCamelCase :List[str] , _lowerCamelCase :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerForInstanceSegmentation(config=_lowerCamelCase ) model.to(_lowerCamelCase ) model.eval() def comm_check_on_output(_lowerCamelCase :Optional[Any] ): # let's still check that all the required stuff is there self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None ) self.parent.assertTrue(result.encoder_last_hidden_state is not None ) # okay, now we need to check the logits shape # due to the encoder compression, masks have a //4 spatial size self.parent.assertEqual( result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , ) # + 1 for null class self.parent.assertEqual( result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[str] = model(pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = model(_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = model( pixel_values=_lowerCamelCase , pixel_mask=_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) comm_check_on_output(_lowerCamelCase ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class snake_case ( __UpperCAmelCase , __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () lowerCamelCase__ = ( {'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False lowerCamelCase__ = False def SCREAMING_SNAKE_CASE_ ( self :Dict ): __SCREAMING_SNAKE_CASE : Optional[Any] = MaskFormerModelTester(self ) __SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=_lowerCamelCase , has_text_modality=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowerCamelCase ) @unittest.skip(reason='''MaskFormer does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): pass @unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''' ) def SCREAMING_SNAKE_CASE_ ( self :int ): pass @unittest.skip(reason='''MaskFormer is not a generative model''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): pass @unittest.skip(reason='''MaskFormer does not use token embeddings''' ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): pass @require_torch_multi_gpu @unittest.skip( reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): pass def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Tuple = model_class(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __SCREAMING_SNAKE_CASE : List[str] = [*signature.parameters.keys()] __SCREAMING_SNAKE_CASE : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , _lowerCamelCase ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): for model_name in ["facebook/maskformer-swin-small-coco"]: __SCREAMING_SNAKE_CASE : Tuple = MaskFormerModel.from_pretrained(_lowerCamelCase ) self.assertIsNotNone(_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : Dict = (self.model_tester.min_size,) * 2 __SCREAMING_SNAKE_CASE : Dict = { '''pixel_values''': torch.randn((2, 3, *size) , device=_lowerCamelCase ), '''mask_labels''': torch.randn((2, 1_0, *size) , device=_lowerCamelCase ), '''class_labels''': torch.zeros(2 , 1_0 , device=_lowerCamelCase ).long(), } __SCREAMING_SNAKE_CASE : Dict = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[Any] = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(_lowerCamelCase , **_lowerCamelCase , output_hidden_states=_lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __SCREAMING_SNAKE_CASE : Dict = model_class(_lowerCamelCase ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Optional[int] = model(**_lowerCamelCase , output_attentions=_lowerCamelCase ) self.assertTrue(outputs.attentions is not None ) def SCREAMING_SNAKE_CASE_ ( self :Dict ): if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : List[Any] = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : int = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Any = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ).loss loss.backward() def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # only MaskFormerForInstanceSegmentation has the loss __SCREAMING_SNAKE_CASE : Tuple = self.all_model_classes[1] __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() __SCREAMING_SNAKE_CASE : Tuple = True __SCREAMING_SNAKE_CASE : List[str] = True __SCREAMING_SNAKE_CASE : Any = model_class(_lowerCamelCase ) model.to(_lowerCamelCase ) model.train() __SCREAMING_SNAKE_CASE : Optional[int] = model(_lowerCamelCase , mask_labels=_lowerCamelCase , class_labels=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : str = outputs.pixel_decoder_hidden_states[0] pixel_decoder_hidden_states.retain_grad() # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't __SCREAMING_SNAKE_CASE : Optional[int] = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() __SCREAMING_SNAKE_CASE : int = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=_lowerCamelCase ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) _lowerCamelCase = 1e-4 def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : List[Any] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_vision @slow class snake_case ( unittest.TestCase ): @cached_property def SCREAMING_SNAKE_CASE_ ( self :str ): return ( MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''' ) if is_vision_available() else None ) def SCREAMING_SNAKE_CASE_ ( self :List[Any] ): __SCREAMING_SNAKE_CASE : Union[str, Any] = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : Tuple = model(**_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor( [[-0.0_4_8_2, 0.9_2_2_8, 0.4_9_5_1], [-0.2_5_4_7, 0.8_0_1_7, 0.8_5_2_7], [-0.0_0_6_9, 0.3_3_8_5, -0.0_0_8_9]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Any = torch.tensor( [[-0.8_4_2_2, -0.8_4_3_4, -0.9_7_1_8], [-1.0_1_4_4, -0.5_5_6_5, -0.4_1_9_5], [-1.0_0_3_8, -0.4_4_8_4, -0.1_9_6_1]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) __SCREAMING_SNAKE_CASE : Optional[int] = torch.tensor( [[0.2_8_5_2, -0.0_1_5_9, 0.9_7_3_5], [0.6_2_5_4, 0.1_8_5_8, 0.8_5_2_9], [-0.0_6_8_0, -0.4_1_1_6, 1.8_4_1_3]] ).to(_lowerCamelCase ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = self.default_image_processor __SCREAMING_SNAKE_CASE : Tuple = prepare_img() __SCREAMING_SNAKE_CASE : str = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : str = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Any = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[Any] = [ [-1.3_7_3_7_1_2_4, -1.7_7_2_4_9_3_7, -1.9_3_6_4_2_3_3], [-1.5_9_7_7_2_8_1, -1.9_8_6_7_9_3_9, -2.1_5_2_3_6_9_5], [-1.5_7_9_5_3_9_8, -1.9_2_6_9_8_3_2, -2.0_9_3_9_4_2], ] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : List[Any] = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [ [1.65_12e00, -5.25_72e00, -3.35_19e00], [3.61_69e-02, -5.90_25e00, -2.93_13e00], [1.07_66e-04, -7.76_30e00, -5.12_63e00], ] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Tuple = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Tuple = self.default_image_processor __SCREAMING_SNAKE_CASE : str = prepare_img() __SCREAMING_SNAKE_CASE : List[Any] = image_processor(_lowerCamelCase , return_tensors='''pt''' ).to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[Any] = inputs['''pixel_values'''].shape # check size is divisible by 32 self.assertTrue((inputs_shape[-1] % 3_2) == 0 and (inputs_shape[-2] % 3_2) == 0 ) # check size self.assertEqual(_lowerCamelCase , (1, 3, 8_0_0, 1_0_8_8) ) with torch.no_grad(): __SCREAMING_SNAKE_CASE : List[Any] = model(**_lowerCamelCase ) # masks_queries_logits __SCREAMING_SNAKE_CASE : Union[str, Any] = outputs.masks_queries_logits self.assertEqual( masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , ) __SCREAMING_SNAKE_CASE : List[str] = [[-0.9_0_4_6, -2.6_3_6_6, -4.6_0_6_2], [-3.4_1_7_9, -5.7_8_9_0, -8.8_0_5_7], [-4.9_1_7_9, -7.6_5_6_0, -1_0.7_7_1_1]] __SCREAMING_SNAKE_CASE : Any = torch.tensor(_lowerCamelCase ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) # class_queries_logits __SCREAMING_SNAKE_CASE : int = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor( [[4.7_1_8_8, -3.2_5_8_5, -2.8_8_5_7], [6.6_8_7_1, -2.9_1_8_1, -1.2_4_8_7], [7.2_4_4_9, -2.2_7_6_4, -2.1_8_7_4]] ).to(_lowerCamelCase ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , _lowerCamelCase , atol=_lowerCamelCase ) ) def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : int = ( MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''' ) .to(_lowerCamelCase ) .eval() ) __SCREAMING_SNAKE_CASE : Any = self.default_image_processor __SCREAMING_SNAKE_CASE : int = image_processor( [np.zeros((3, 8_0_0, 1_3_3_3) ), np.zeros((3, 8_0_0, 1_3_3_3) )] , segmentation_maps=[np.zeros((3_8_4, 3_8_4) ).astype(np.floataa ), np.zeros((3_8_4, 3_8_4) ).astype(np.floataa )] , return_tensors='''pt''' , ) __SCREAMING_SNAKE_CASE : Dict = inputs['''pixel_values'''].to(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = [el.to(_lowerCamelCase ) for el in inputs['''mask_labels''']] __SCREAMING_SNAKE_CASE : str = [el.to(_lowerCamelCase ) for el in inputs['''class_labels''']] with torch.no_grad(): __SCREAMING_SNAKE_CASE : int = model(**_lowerCamelCase ) self.assertTrue(outputs.loss is not None )
674
0
from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo lowercase_ : Tuple = '\\n@misc{wu2016googles,\n title={Google\'s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},\n author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey\n and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin\n Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto\n Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and\n Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes\n and Jeffrey Dean},\n year={2016},\n eprint={1609.08144},\n archivePrefix={arXiv},\n primaryClass={cs.CL}\n}\n' lowercase_ : Optional[Any] = '\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe \'GLEU score\'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore\'s range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n' lowercase_ : Optional[Any] = '\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n predictions (list of str): list of translations to score.\n Each translation should be tokenized into a list of tokens.\n references (list of list of str): list of lists of references for each translation.\n Each reference should be tokenized into a list of tokens.\n min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n \'google_bleu\': google_bleu score\n\nExamples:\n Example 1:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results["google_bleu"], 2))\n 0.44\n\n Example 2:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n >>> print(round(results["google_bleu"], 2))\n 0.61\n\n Example 3:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n >>> print(round(results["google_bleu"], 2))\n 0.53\n\n Example 4:\n >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',\n ... \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']\n >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',\n ... \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',\n ... \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']\n >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',\n ... \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',\n ... \'heed\', \'the\', \'cat\', \'commands\']\n >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',\n ... \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',\n ... \'of\', \'the\', \'cat\']\n\n >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',\n ... \'interested\', \'in\', \'world\', \'history\']\n >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',\n ... \'because\', \'he\', \'read\', \'the\', \'book\']\n\n >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n >>> hypotheses = [hyp1, hyp2]\n >>> google_bleu = datasets.load_metric("google_bleu")\n >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n >>> print(round(results["google_bleu"], 2))\n 0.4\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class _lowerCamelCase ( datasets.Metric ): def UpperCamelCase_ ( self ) -> int: return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': datasets.Sequence(datasets.Value('''string''' , id='''token''' ) , id='''sequence''' ), '''references''': datasets.Sequence( datasets.Sequence(datasets.Value('''string''' , id='''token''' ) , id='''sequence''' ) , id='''references''' ), } ) , ) def UpperCamelCase_ ( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = 1 , lowerCAmelCase = 4 , ) -> int: return { "google_bleu": gleu_score.corpus_gleu( list_of_references=_lowerCamelCase , hypotheses=_lowerCamelCase , min_len=_lowerCamelCase , max_len=_lowerCamelCase ) }
64
"""simple docstring""" import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification _lowerCamelCase = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co _lowerCamelCase = '''main''' # Default branch name _lowerCamelCase = '''f2c752cfc5c0ab6f4bdec59acea69eefbee381c2''' # One particular commit (not the top of `main`) _lowerCamelCase = '''aaaaaaa''' # This commit does not exist, so we should 404. _lowerCamelCase = '''d9e9f15bc825e4b2c9249e9578f884bbcb5e3684''' # Sha-1 of config.json on the top of `main`, for checking purposes _lowerCamelCase = '''4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3''' @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Welcome!''' ) yield print('''Bye!''' ) @contextlib.contextmanager def lowerCAmelCase_ ( ): '''simple docstring''' print('''Bonjour!''' ) yield print('''Au revoir!''' ) class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): # If the spec is missing, importlib would not be able to import the module dynamically. assert transformers.__spec__ is not None assert importlib.util.find_spec('''transformers''' ) is not None class snake_case ( unittest.TestCase ): @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :Optional[int] ): with ContextManagers([] ): print('''Transformers are awesome!''' ) # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , '''Transformers are awesome!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :str , _lowerCamelCase :Optional[int] ): with ContextManagers([context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Welcome!\nTransformers are awesome!\nBye!\n''' ) @unittest.mock.patch('''sys.stdout''' , new_callable=io.StringIO ) def SCREAMING_SNAKE_CASE_ ( self :Dict , _lowerCamelCase :List[str] ): with ContextManagers([context_fr(), context_en()] ): print('''Transformers are awesome!''' ) # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , '''Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n''' ) @require_torch def SCREAMING_SNAKE_CASE_ ( self :List[str] ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_tf def SCREAMING_SNAKE_CASE_ ( self :int ): self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels''', '''next_sentence_label'''] ) self.assertEqual(find_labels(_lowerCamelCase ) , ['''start_positions''', '''end_positions'''] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , ['''labels'''] ) @require_flax def SCREAMING_SNAKE_CASE_ ( self :Dict ): # Flax models don't have labels self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) self.assertEqual(find_labels(_lowerCamelCase ) , [] ) class snake_case ( __UpperCAmelCase ): pass self.assertEqual(find_labels(_lowerCamelCase ) , [] )
674
0
from ...configuration_utils import PretrainedConfig from ...utils import logging a : Tuple = logging.get_logger(__name__) a : List[str] = { '''abeja/gpt-neox-japanese-2.7b''': '''https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/config.json''', } class lowerCamelCase_ ( __UpperCAmelCase ): '''simple docstring''' __UpperCAmelCase = "gpt_neox_japanese" def __init__( self , snake_case_=3_2_0_0_0 , snake_case_=2_5_6_0 , snake_case_=3_2 , snake_case_=3_2 , snake_case_=4 , snake_case_="gelu" , snake_case_=1.0_0 , snake_case_=1_0_0_0_0 , snake_case_=2_0_4_8 , snake_case_=0.0_2 , snake_case_=1e-5 , snake_case_=True , snake_case_=3_1_9_9_6 , snake_case_=3_1_9_9_9 , snake_case_=0.1 , snake_case_=0.0 , **snake_case_ , ) -> int: '''simple docstring''' super().__init__(bos_token_id=_lowerCamelCase , eos_token_id=_lowerCamelCase , **_lowerCamelCase ) __lowercase = vocab_size __lowercase = max_position_embeddings __lowercase = hidden_size __lowercase = num_hidden_layers __lowercase = num_attention_heads __lowercase = intermediate_multiple_size __lowercase = hidden_act __lowercase = rotary_pct __lowercase = rotary_emb_base __lowercase = initializer_range __lowercase = layer_norm_eps __lowercase = use_cache __lowercase = attention_dropout __lowercase = hidden_dropout
639
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class snake_case ( unittest.TestCase ): def __init__( self :List[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Tuple=7 , _lowerCamelCase :Dict=3 , _lowerCamelCase :Optional[Any]=3_0 , _lowerCamelCase :List[str]=4_0_0 , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :Union[str, Any]=None , _lowerCamelCase :List[Any]=True , _lowerCamelCase :Any=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=[0.5, 0.5, 0.5] , _lowerCamelCase :Dict=True , _lowerCamelCase :str=1 / 2_5_5 , _lowerCamelCase :Union[str, Any]=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p __SCREAMING_SNAKE_CASE : Optional[Any] = size if size is not None else {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} __SCREAMING_SNAKE_CASE : List[str] = parent __SCREAMING_SNAKE_CASE : Dict = batch_size __SCREAMING_SNAKE_CASE : str = num_channels __SCREAMING_SNAKE_CASE : Union[str, Any] = min_resolution __SCREAMING_SNAKE_CASE : Union[str, Any] = max_resolution __SCREAMING_SNAKE_CASE : Tuple = do_resize __SCREAMING_SNAKE_CASE : Union[str, Any] = size __SCREAMING_SNAKE_CASE : int = do_normalize __SCREAMING_SNAKE_CASE : List[Any] = image_mean __SCREAMING_SNAKE_CASE : Tuple = image_std __SCREAMING_SNAKE_CASE : Dict = do_rescale __SCREAMING_SNAKE_CASE : Optional[int] = rescale_factor __SCREAMING_SNAKE_CASE : List[Any] = do_pad def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE_ ( self :Tuple , _lowerCamelCase :Dict , _lowerCamelCase :List[Any]=False ): if not batched: __SCREAMING_SNAKE_CASE : str = image_inputs[0] if isinstance(_lowerCamelCase , Image.Image ): __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[int] = image.size else: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = image.shape[1], image.shape[2] if w < h: __SCREAMING_SNAKE_CASE : str = int(self.size['''shortest_edge'''] * h / w ) __SCREAMING_SNAKE_CASE : int = self.size['''shortest_edge'''] elif w > h: __SCREAMING_SNAKE_CASE : Optional[Any] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : int = int(self.size['''shortest_edge'''] * w / h ) else: __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] __SCREAMING_SNAKE_CASE : List[str] = self.size['''shortest_edge'''] else: __SCREAMING_SNAKE_CASE : Optional[Any] = [] for image in image_inputs: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) __SCREAMING_SNAKE_CASE : Optional[int] = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[0] )[0] __SCREAMING_SNAKE_CASE : int = max(_lowerCamelCase , key=lambda _lowerCamelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class snake_case ( __UpperCAmelCase , unittest.TestCase ): lowerCamelCase__ = YolosImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Any = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_lowerCamelCase , '''image_mean''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''image_std''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_normalize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''do_resize''' ) ) self.assertTrue(hasattr(_lowerCamelCase , '''size''' ) ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): __SCREAMING_SNAKE_CASE : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''shortest_edge''': 1_8, '''longest_edge''': 1_3_3_3} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=_lowerCamelCase ) self.assertEqual(image_processor.size , {'''shortest_edge''': 4_2, '''longest_edge''': 8_4} ) self.assertEqual(image_processor.do_pad , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): pass def SCREAMING_SNAKE_CASE_ ( self :int ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __SCREAMING_SNAKE_CASE : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , Image.Image ) # Test not batched input __SCREAMING_SNAKE_CASE : str = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Dict = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Tuple = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Initialize image_processing __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __SCREAMING_SNAKE_CASE : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , numpify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , np.ndarray ) # Test not batched input __SCREAMING_SNAKE_CASE : Dict = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[str] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : List[Any] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :Any ): # Initialize image_processing __SCREAMING_SNAKE_CASE : str = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : Any = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test not batched input __SCREAMING_SNAKE_CASE : List[str] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Optional[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched __SCREAMING_SNAKE_CASE : Optional[int] = image_processing(_lowerCamelCase , return_tensors='''pt''' ).pixel_values __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : List[Any] = self.image_processor_tester.get_expected_values(_lowerCamelCase , batched=_lowerCamelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): # Initialize image_processings __SCREAMING_SNAKE_CASE : Dict = self.image_processing_class(**self.image_processor_dict ) __SCREAMING_SNAKE_CASE : Tuple = self.image_processing_class(do_resize=_lowerCamelCase , do_normalize=_lowerCamelCase , do_rescale=_lowerCamelCase ) # create random PyTorch tensors __SCREAMING_SNAKE_CASE : int = prepare_image_inputs(self.image_processor_tester , equal_resolution=_lowerCamelCase , torchify=_lowerCamelCase ) for image in image_inputs: self.assertIsInstance(_lowerCamelCase , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a.pad(_lowerCamelCase , return_tensors='''pt''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = image_processing_a(_lowerCamelCase , return_tensors='''pt''' ) self.assertTrue( torch.allclose(encoded_images_with_method['''pixel_values'''] , encoded_images['''pixel_values'''] , atol=1e-4 ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :int ): # prepare image and target __SCREAMING_SNAKE_CASE : Tuple = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Tuple = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''image_id''': 3_9_7_6_9, '''annotations''': target} # encode them __SCREAMING_SNAKE_CASE : List[Any] = YolosImageProcessor.from_pretrained('''hustvl/yolos-small''' ) __SCREAMING_SNAKE_CASE : Optional[Any] = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : Optional[int] = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([5_8_8_7.9_6_0_0, 1_1_2_5_0.2_0_6_1, 4_8_9_3_5_3.8_4_3_8, 8_3_7_1_2_2.7_5_0_0, 1_4_7_9_6_7.5_1_5_6, 1_6_5_7_3_2.3_4_3_8] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : Any = torch.tensor([0.5_5_0_3, 0.2_7_6_5, 0.0_6_0_4, 0.2_2_1_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : str = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Dict = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify orig_size __SCREAMING_SNAKE_CASE : Union[str, Any] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) ) @slow def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # prepare image, target and masks_path __SCREAMING_SNAKE_CASE : List[str] = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) with open('''./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt''' , '''r''' ) as f: __SCREAMING_SNAKE_CASE : Union[str, Any] = json.loads(f.read() ) __SCREAMING_SNAKE_CASE : Dict = {'''file_name''': '''000000039769.png''', '''image_id''': 3_9_7_6_9, '''segments_info''': target} __SCREAMING_SNAKE_CASE : Optional[int] = pathlib.Path('''./tests/fixtures/tests_samples/COCO/coco_panoptic''' ) # encode them __SCREAMING_SNAKE_CASE : Any = YolosImageProcessor(format='''coco_panoptic''' ) __SCREAMING_SNAKE_CASE : Dict = image_processing(images=_lowerCamelCase , annotations=_lowerCamelCase , masks_path=_lowerCamelCase , return_tensors='''pt''' ) # verify pixel values __SCREAMING_SNAKE_CASE : str = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding['''pixel_values'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : str = torch.tensor([0.2_7_9_6, 0.3_1_3_8, 0.3_4_8_1] ) self.assertTrue(torch.allclose(encoding['''pixel_values'''][0, 0, 0, :3] , _lowerCamelCase , atol=1e-4 ) ) # verify area __SCREAMING_SNAKE_CASE : Any = torch.tensor([1_4_7_9_7_9.6_8_7_5, 1_6_5_5_2_7.0_4_6_9, 4_8_4_6_3_8.5_9_3_8, 1_1_2_9_2.9_3_7_5, 5_8_7_9.6_5_6_2, 7_6_3_4.1_1_4_7] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''area'''] , _lowerCamelCase ) ) # verify boxes __SCREAMING_SNAKE_CASE : List[str] = torch.Size([6, 4] ) self.assertEqual(encoding['''labels'''][0]['''boxes'''].shape , _lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = torch.tensor([0.2_6_2_5, 0.5_4_3_7, 0.4_6_8_8, 0.8_6_2_5] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''boxes'''][0] , _lowerCamelCase , atol=1e-3 ) ) # verify image_id __SCREAMING_SNAKE_CASE : Dict = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''image_id'''] , _lowerCamelCase ) ) # verify is_crowd __SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''iscrowd'''] , _lowerCamelCase ) ) # verify class_labels __SCREAMING_SNAKE_CASE : Optional[Any] = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''class_labels'''] , _lowerCamelCase ) ) # verify masks __SCREAMING_SNAKE_CASE : Optional[Any] = 8_2_2_8_7_3 self.assertEqual(encoding['''labels'''][0]['''masks'''].sum().item() , _lowerCamelCase ) # verify orig_size __SCREAMING_SNAKE_CASE : List[str] = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''orig_size'''] , _lowerCamelCase ) ) # verify size __SCREAMING_SNAKE_CASE : Any = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding['''labels'''][0]['''size'''] , _lowerCamelCase ) )
674
0
from __future__ import annotations from collections import namedtuple def lowerCAmelCase_ ( lowercase: float , lowercase: float , lowercase: float ) -> Union[str, Any]: '''simple docstring''' _UpperCamelCase: List[Any] = namedtuple('''result''' , '''name value''' ) if (voltage, current, power).count(0 ) != 1: raise ValueError('''Only one argument must be 0''' ) elif power < 0: raise ValueError( '''Power cannot be negative in any electrical/electronics system''' ) elif voltage == 0: return result('''voltage''' , power / current ) elif current == 0: return result('''current''' , power / voltage ) elif power == 0: return result('''power''' , float(round(abs(voltage * current ) , 2 ) ) ) else: raise ValueError('''Exactly one argument must be 0''' ) if __name__ == "__main__": import doctest doctest.testmod()
271
"""simple docstring""" from __future__ import annotations def lowerCAmelCase_ ( lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = str(lowercase_ ) return len(lowercase_ ) == 9 and set(lowercase_ ) == set('''123456789''' ) def lowerCAmelCase_ ( ): '''simple docstring''' for base_num in range(9999 , 4999 , -1 ): __SCREAMING_SNAKE_CASE : List[str] = 10_0002 * base_num if is_9_pandigital(lowercase_ ): return candidate for base_num in range(333 , 99 , -1 ): __SCREAMING_SNAKE_CASE : List[Any] = 100_2003 * base_num if is_9_pandigital(lowercase_ ): return candidate return None if __name__ == "__main__": print(f'{solution() = }')
674
0
def __lowerCamelCase ( _lowercase , _lowercase , _lowercase , _lowercase ) -> List[Any]: if graph[path[curr_ind - 1]][next_ver] == 0: return False # 2. Validate that next vertex is not already in path return not any(vertex == next_ver for vertex in path ) def __lowerCamelCase ( _lowercase , _lowercase , _lowercase ) -> str: if curr_ind == len(lowercase_ ): # return whether path exists between current and starting vertices return graph[path[curr_ind - 1]][path[0]] == 1 # Recursive Step for next_ver in range(0 , len(lowercase_ ) ): if valid_connection(lowercase_ , lowercase_ , lowercase_ , lowercase_ ): # Insert current vertex into path as next transition UpperCamelCase = next_ver # Validate created path if util_hamilton_cycle(lowercase_ , lowercase_ , curr_ind + 1 ): return True # Backtrack UpperCamelCase = -1 return False def __lowerCamelCase ( _lowercase , _lowercase = 0 ) -> int: UpperCamelCase = [-1] * (len(lowercase_ ) + 1) # initialize start and end of path with starting index UpperCamelCase = start_index # evaluate and if we find answer return path either return empty array return path if util_hamilton_cycle(lowercase_ , lowercase_ , 1 ) else []
282
"""simple docstring""" import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE_ ( self :int ): __SCREAMING_SNAKE_CASE : Tuple = 0 def SCREAMING_SNAKE_CASE_ ( self :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained('''openai/clip-vit-base-patch32''' ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Optional[Any] = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Dict = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Union[str, Any] = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :int ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : str = CLIPConfig() # Create a dummy config file with image_proceesor_type __SCREAMING_SNAKE_CASE : Tuple = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained(_lowerCamelCase ).to_dict() config_dict.pop('''image_processor_type''' ) __SCREAMING_SNAKE_CASE : Union[str, Any] = CLIPImageProcessor(**_lowerCamelCase ) # save in new folder model_config.save_pretrained(_lowerCamelCase ) config.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) # make sure private variable is not incorrectly saved __SCREAMING_SNAKE_CASE : Tuple = json.loads(config.to_json_string() ) self.assertTrue('''_processor_class''' not in dict_as_saved ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' json.dump( {'''image_processor_type''': '''CLIPImageProcessor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) def SCREAMING_SNAKE_CASE_ ( self :Optional[int] ): with self.assertRaisesRegex( _lowerCamelCase , '''clip-base is not a local folder and is not a valid model identifier''' ): __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained('''clip-base''' ) def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ): with self.assertRaisesRegex( _lowerCamelCase , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained(_lowerCamelCase , revision='''aaaaaa''' ) def SCREAMING_SNAKE_CASE_ ( self :List[str] ): with self.assertRaisesRegex( _lowerCamelCase , '''hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json.''' , ): __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained('''hf-internal-testing/config-no-model''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Union[str, Any] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(_lowerCamelCase ): __SCREAMING_SNAKE_CASE : Optional[Any] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : int = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase , trust_remote_code=_lowerCamelCase ) self.assertEqual(reloaded_image_processor.__class__.__name__ , '''NewImageProcessor''' ) def SCREAMING_SNAKE_CASE_ ( self :Tuple ): try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(_lowerCamelCase ): AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) with tempfile.TemporaryDirectory() as tmpdirname: __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''preprocessor_config.json''' __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ) / '''config.json''' json.dump( {'''feature_extractor_type''': '''CLIPFeatureExtractor''', '''processor_class''': '''CLIPProcessor'''} , open(_lowerCamelCase , '''w''' ) , ) json.dump({'''model_type''': '''clip'''} , open(_lowerCamelCase , '''w''' ) ) __SCREAMING_SNAKE_CASE : Optional[int] = CustomImageProcessor.from_pretrained(_lowerCamelCase ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Tuple = AutoImageProcessor.from_pretrained(_lowerCamelCase ) self.assertIsInstance(_lowerCamelCase , _lowerCamelCase ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def SCREAMING_SNAKE_CASE_ ( self :Dict ): class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = True try: AutoConfig.register('''custom''' , _lowerCamelCase ) AutoImageProcessor.register(_lowerCamelCase , _lowerCamelCase ) # If remote code is not set, the default is to use local __SCREAMING_SNAKE_CASE : List[str] = AutoImageProcessor.from_pretrained('''hf-internal-testing/test_dynamic_image_processor''' ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. __SCREAMING_SNAKE_CASE : str = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub __SCREAMING_SNAKE_CASE : Optional[int] = AutoImageProcessor.from_pretrained( '''hf-internal-testing/test_dynamic_image_processor''' , trust_remote_code=_lowerCamelCase ) self.assertEqual(image_processor.__class__.__name__ , '''NewImageProcessor''' ) self.assertTrue(not hasattr(_lowerCamelCase , '''is_local''' ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
674
0
"""simple docstring""" import unittest import numpy as np import torch from diffusers import DDIMPipeline, DDIMScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class __lowercase( __UpperCAmelCase , unittest.TestCase ): '''simple docstring''' __a : Tuple = DDIMPipeline __a : int = UNCONDITIONAL_IMAGE_GENERATION_PARAMS __a : List[Any] = PipelineTesterMixin.required_optional_params - { 'num_images_per_prompt', 'latents', 'callback', 'callback_steps', } __a : List[Any] = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS __a : Optional[int] = False def snake_case_ ( self ): torch.manual_seed(0 ) __lowerCamelCase : Optional[int] = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=('DownBlock2D', 'AttnDownBlock2D') , up_block_types=('AttnUpBlock2D', 'UpBlock2D') , ) __lowerCamelCase : List[Any] = DDIMScheduler() __lowerCamelCase : Optional[int] = {'''unet''': unet, '''scheduler''': scheduler} return components def snake_case_ ( self , __a , __a=0 ): if str(_lowerCamelCase ).startswith('mps' ): __lowerCamelCase : Tuple = torch.manual_seed(_lowerCamelCase ) else: __lowerCamelCase : List[str] = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase ) __lowerCamelCase : Optional[int] = { '''batch_size''': 1, '''generator''': generator, '''num_inference_steps''': 2, '''output_type''': '''numpy''', } return inputs def snake_case_ ( self ): __lowerCamelCase : str = '''cpu''' __lowerCamelCase : List[str] = self.get_dummy_components() __lowerCamelCase : int = self.pipeline_class(**_lowerCamelCase ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __lowerCamelCase : List[Any] = self.get_dummy_inputs(_lowerCamelCase ) __lowerCamelCase : Any = pipe(**_lowerCamelCase ).images __lowerCamelCase : List[Any] = image[0, -3:, -3:, -1] self.assertEqual(image.shape , (1, 32, 32, 3) ) __lowerCamelCase : Any = np.array( [1.000E00, 5.717E-01, 4.717E-01, 1.000E00, 0.000E00, 1.000E00, 3.000E-04, 0.000E00, 9.000E-04] ) __lowerCamelCase : Any = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(_lowerCamelCase , 1E-3 ) def snake_case_ ( self ): super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3 ) def snake_case_ ( self ): super().test_save_load_local(expected_max_difference=3E-3 ) def snake_case_ ( self ): super().test_save_load_optional_components(expected_max_difference=3E-3 ) def snake_case_ ( self ): super().test_inference_batch_single_identical(expected_max_diff=3E-3 ) @slow @require_torch_gpu class __lowercase( unittest.TestCase ): '''simple docstring''' def snake_case_ ( self ): __lowerCamelCase : Union[str, Any] = '''google/ddpm-cifar10-32''' __lowerCamelCase : Any = UNetaDModel.from_pretrained(_lowerCamelCase ) __lowerCamelCase : Dict = DDIMScheduler() __lowerCamelCase : Dict = DDIMPipeline(unet=_lowerCamelCase , scheduler=_lowerCamelCase ) ddim.to(_lowerCamelCase ) ddim.set_progress_bar_config(disable=_lowerCamelCase ) __lowerCamelCase : Dict = torch.manual_seed(0 ) __lowerCamelCase : str = ddim(generator=_lowerCamelCase , eta=0.0 , output_type='numpy' ).images __lowerCamelCase : Tuple = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) __lowerCamelCase : int = np.array([0.1_723, 0.1_617, 0.1_600, 0.1_626, 0.1_497, 0.1_513, 0.1_505, 0.1_442, 0.1_453] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def snake_case_ ( self ): __lowerCamelCase : List[str] = '''google/ddpm-ema-bedroom-256''' __lowerCamelCase : str = UNetaDModel.from_pretrained(_lowerCamelCase ) __lowerCamelCase : Union[str, Any] = DDIMScheduler.from_pretrained(_lowerCamelCase ) __lowerCamelCase : Union[str, Any] = DDIMPipeline(unet=_lowerCamelCase , scheduler=_lowerCamelCase ) ddpm.to(_lowerCamelCase ) ddpm.set_progress_bar_config(disable=_lowerCamelCase ) __lowerCamelCase : Any = torch.manual_seed(0 ) __lowerCamelCase : Optional[int] = ddpm(generator=_lowerCamelCase , output_type='numpy' ).images __lowerCamelCase : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) __lowerCamelCase : List[Any] = np.array([0.0_060, 0.0_201, 0.0_344, 0.0_024, 0.0_018, 0.0_002, 0.0_022, 0.0_000, 0.0_069] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
594
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case ( __UpperCAmelCase ): pass class snake_case : def __init__( self :List[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Any = data __SCREAMING_SNAKE_CASE : Node | None = None def __iter__( self :Union[str, Any] ): __SCREAMING_SNAKE_CASE : List[str] = self __SCREAMING_SNAKE_CASE : List[str] = [] while node: if node in visited: raise ContainsLoopError visited.append(_lowerCamelCase ) yield node.data __SCREAMING_SNAKE_CASE : List[str] = node.next_node @property def SCREAMING_SNAKE_CASE_ ( self :Any ): try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": _lowerCamelCase = Node(1) _lowerCamelCase = Node(2) _lowerCamelCase = Node(3) _lowerCamelCase = Node(4) print(root_node.has_loop) # False _lowerCamelCase = root_node.next_node print(root_node.has_loop) # True _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) _lowerCamelCase = Node(5) _lowerCamelCase = Node(6) print(root_node.has_loop) # False _lowerCamelCase = Node(1) print(root_node.has_loop) # False
674
0
def _lowercase ( SCREAMING_SNAKE_CASE_ : int = 50 ): """simple docstring""" UpperCamelCase = [1] * (length + 1) for row_length in range(length + 1 ): for tile_length in range(2 , 5 ): for tile_start in range(row_length - tile_length + 1 ): ways_number[row_length] += ways_number[ row_length - tile_start - tile_length ] return ways_number[length] if __name__ == "__main__": print(F'''{solution() = }''')
386
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCamelCase = logging.get_logger(__name__) _lowerCamelCase = { '''weiweishi/roc-bert-base-zh''': '''https://huggingface.co/weiweishi/roc-bert-base-zh/resolve/main/config.json''', } class snake_case ( __UpperCAmelCase ): lowerCamelCase__ = '''roc_bert''' def __init__( self :Union[str, Any] , _lowerCamelCase :Any=3_0_5_2_2 , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Optional[Any]=1_2 , _lowerCamelCase :List[str]=1_2 , _lowerCamelCase :str=3_0_7_2 , _lowerCamelCase :Tuple="gelu" , _lowerCamelCase :List[Any]=0.1 , _lowerCamelCase :List[str]=0.1 , _lowerCamelCase :Optional[int]=5_1_2 , _lowerCamelCase :Dict=2 , _lowerCamelCase :Any=0.0_2 , _lowerCamelCase :Optional[int]=1e-12 , _lowerCamelCase :str=True , _lowerCamelCase :Any=0 , _lowerCamelCase :List[str]="absolute" , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Any=True , _lowerCamelCase :Union[str, Any]=True , _lowerCamelCase :str=7_6_8 , _lowerCamelCase :Union[str, Any]=9_1_0 , _lowerCamelCase :List[Any]=5_1_2 , _lowerCamelCase :Optional[int]=2_4_8_5_8 , _lowerCamelCase :Union[str, Any]=True , **_lowerCamelCase :str , ): __SCREAMING_SNAKE_CASE : List[str] = vocab_size __SCREAMING_SNAKE_CASE : int = max_position_embeddings __SCREAMING_SNAKE_CASE : List[str] = hidden_size __SCREAMING_SNAKE_CASE : str = num_hidden_layers __SCREAMING_SNAKE_CASE : int = num_attention_heads __SCREAMING_SNAKE_CASE : Any = intermediate_size __SCREAMING_SNAKE_CASE : Optional[int] = hidden_act __SCREAMING_SNAKE_CASE : List[Any] = hidden_dropout_prob __SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range __SCREAMING_SNAKE_CASE : Union[str, Any] = type_vocab_size __SCREAMING_SNAKE_CASE : List[str] = layer_norm_eps __SCREAMING_SNAKE_CASE : Optional[int] = use_cache __SCREAMING_SNAKE_CASE : str = enable_pronunciation __SCREAMING_SNAKE_CASE : List[str] = enable_shape __SCREAMING_SNAKE_CASE : Tuple = pronunciation_embed_dim __SCREAMING_SNAKE_CASE : Optional[Any] = pronunciation_vocab_size __SCREAMING_SNAKE_CASE : str = shape_embed_dim __SCREAMING_SNAKE_CASE : Union[str, Any] = shape_vocab_size __SCREAMING_SNAKE_CASE : Tuple = concat_input __SCREAMING_SNAKE_CASE : Union[str, Any] = position_embedding_type __SCREAMING_SNAKE_CASE : str = classifier_dropout super().__init__(pad_token_id=_lowerCamelCase , **_lowerCamelCase )
674
0
import gc import tempfile import unittest import numpy as np import torch from diffusers import VersatileDiffusionPipeline from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device a__ = False class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): """simple docstring""" pass @nightly @require_torch_gpu class SCREAMING_SNAKE_CASE_ ( unittest.TestCase ): """simple docstring""" def lowerCamelCase__ ( self : int ) -> str: """simple docstring""" super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase__ ( self : int ) -> Tuple: """simple docstring""" __UpperCamelCase : int = VersatileDiffusionPipeline.from_pretrained("""shi-labs/versatile-diffusion""" , torch_dtype=torch.floataa ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __UpperCamelCase : Dict = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg""" ) __UpperCamelCase : List[str] = torch.manual_seed(0 ) __UpperCamelCase : Union[str, Any] = pipe.dual_guided( prompt="""first prompt""" , image=_lowerCamelCase , text_to_image_strength=0.75 , generator=_lowerCamelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type="""numpy""" , ).images with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(_lowerCamelCase ) __UpperCamelCase : List[Any] = VersatileDiffusionPipeline.from_pretrained(_lowerCamelCase , torch_dtype=torch.floataa ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __UpperCamelCase : List[str] = generator.manual_seed(0 ) __UpperCamelCase : int = pipe.dual_guided( prompt="""first prompt""" , image=_lowerCamelCase , text_to_image_strength=0.75 , generator=_lowerCamelCase , guidance_scale=7.5 , num_inference_steps=2 , output_type="""numpy""" , ).images assert np.abs(image - new_image ).sum() < 1E-5, "Models don't have the same forward pass" def lowerCamelCase__ ( self : int ) -> Tuple: """simple docstring""" __UpperCamelCase : Tuple = VersatileDiffusionPipeline.from_pretrained("""shi-labs/versatile-diffusion""" , torch_dtype=torch.floataa ) pipe.to(_lowerCamelCase ) pipe.set_progress_bar_config(disable=_lowerCamelCase ) __UpperCamelCase : int = '''cyberpunk 2077''' __UpperCamelCase : Any = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg""" ) __UpperCamelCase : str = torch.manual_seed(0 ) __UpperCamelCase : Dict = pipe.dual_guided( prompt=_lowerCamelCase , image=_lowerCamelCase , text_to_image_strength=0.75 , generator=_lowerCamelCase , guidance_scale=7.5 , num_inference_steps=50 , output_type="""numpy""" , ).images __UpperCamelCase : List[Any] = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) __UpperCamelCase : List[str] = np.array([0.14_48, 0.16_19, 0.17_41, 0.10_86, 0.11_47, 0.11_28, 0.11_99, 0.11_65, 0.10_01] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1 __UpperCamelCase : List[str] = '''A painting of a squirrel eating a burger ''' __UpperCamelCase : str = torch.manual_seed(0 ) __UpperCamelCase : Dict = pipe.text_to_image( prompt=_lowerCamelCase , generator=_lowerCamelCase , guidance_scale=7.5 , num_inference_steps=50 , output_type="""numpy""" ).images __UpperCamelCase : Any = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) __UpperCamelCase : List[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-1 __UpperCamelCase : str = pipe.image_variation(_lowerCamelCase , generator=_lowerCamelCase , output_type="""numpy""" ).images __UpperCamelCase : List[Any] = image[0, 253:256, 253:256, -1] assert image.shape == (1, 512, 512, 3) __UpperCamelCase : Tuple = np.array([0.30_76, 0.31_23, 0.32_84, 0.37_82, 0.37_70, 0.38_94, 0.42_97, 0.43_31, 0.44_56] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-1
279
"""simple docstring""" import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] , lowercase_ : Dict , lowercase_ : Tuple , lowercase_ : Optional[Any]=True , lowercase_ : Any="pt" ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Union[str, Any] = {'''add_prefix_space''': True} if isinstance(lowercase_ , lowercase_ ) and not line.startswith(''' ''' ) else {} __SCREAMING_SNAKE_CASE : Optional[int] = padding_side return tokenizer( [line] , max_length=lowercase_ , padding='''max_length''' if pad_to_max_length else None , truncation=lowercase_ , return_tensors=lowercase_ , add_special_tokens=lowercase_ , **lowercase_ , ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : Tuple , lowercase_ : List[Any]=None , ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Dict = input_ids.ne(lowercase_ ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class snake_case ( __UpperCAmelCase ): def __init__( self :Optional[Any] , _lowerCamelCase :Dict , _lowerCamelCase :Any , _lowerCamelCase :Optional[Any] , _lowerCamelCase :Tuple , _lowerCamelCase :Any="train" , _lowerCamelCase :str=None , _lowerCamelCase :Optional[Any]=None , _lowerCamelCase :List[Any]=None , _lowerCamelCase :Tuple="" , ): super().__init__() __SCREAMING_SNAKE_CASE : Dict = Path(_lowerCamelCase ).joinpath(type_path + '''.source''' ) __SCREAMING_SNAKE_CASE : Any = Path(_lowerCamelCase ).joinpath(type_path + '''.target''' ) __SCREAMING_SNAKE_CASE : Any = self.get_char_lens(self.src_file ) __SCREAMING_SNAKE_CASE : List[str] = max_source_length __SCREAMING_SNAKE_CASE : Dict = max_target_length assert min(self.src_lens ) > 0, f'''found empty line in {self.src_file}''' __SCREAMING_SNAKE_CASE : Dict = tokenizer __SCREAMING_SNAKE_CASE : Union[str, Any] = prefix if n_obs is not None: __SCREAMING_SNAKE_CASE : Any = self.src_lens[:n_obs] __SCREAMING_SNAKE_CASE : List[str] = src_lang __SCREAMING_SNAKE_CASE : str = tgt_lang def __len__( self :int ): return len(self.src_lens ) def __getitem__( self :Optional[Any] , _lowerCamelCase :Any ): __SCREAMING_SNAKE_CASE : Optional[Any] = index + 1 # linecache starts at 1 __SCREAMING_SNAKE_CASE : Any = self.prefix + linecache.getline(str(self.src_file ) , _lowerCamelCase ).rstrip('''\n''' ) __SCREAMING_SNAKE_CASE : Dict = linecache.getline(str(self.tgt_file ) , _lowerCamelCase ).rstrip('''\n''' ) assert source_line, f'''empty source line for index {index}''' assert tgt_line, f'''empty tgt line for index {index}''' # Need to add eos token manually for T5 if isinstance(self.tokenizer , _lowerCamelCase ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right __SCREAMING_SNAKE_CASE : Dict = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer ) __SCREAMING_SNAKE_CASE : Optional[Any] = self.tokenizer.generator if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_source_length , '''right''' ) __SCREAMING_SNAKE_CASE : Dict = encode_line(_lowerCamelCase , _lowerCamelCase , self.max_target_length , '''right''' ) __SCREAMING_SNAKE_CASE : Any = source_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Any = target_inputs['''input_ids'''].squeeze() __SCREAMING_SNAKE_CASE : Dict = source_inputs['''attention_mask'''].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def SCREAMING_SNAKE_CASE_ ( _lowerCamelCase :Any ): return [len(_lowerCamelCase ) for x in Path(_lowerCamelCase ).open().readlines()] def SCREAMING_SNAKE_CASE_ ( self :List[str] , _lowerCamelCase :List[str] ): __SCREAMING_SNAKE_CASE : int = torch.stack([x['''input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = torch.stack([x['''attention_mask'''] for x in batch] ) __SCREAMING_SNAKE_CASE : int = torch.stack([x['''decoder_input_ids'''] for x in batch] ) __SCREAMING_SNAKE_CASE : str = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : Union[str, Any] = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , _lowerCamelCase ) else self.tokenizer.pad_token_id ) __SCREAMING_SNAKE_CASE : List[str] = trim_batch(_lowerCamelCase , _lowerCamelCase ) __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : Any = trim_batch(_lowerCamelCase , _lowerCamelCase , attention_mask=_lowerCamelCase ) __SCREAMING_SNAKE_CASE : Dict = { '''input_ids''': source_ids, '''attention_mask''': source_mask, '''decoder_input_ids''': y, } return batch _lowerCamelCase = getLogger(__name__) def lowerCAmelCase_ ( lowercase_ : List[List] ): '''simple docstring''' return list(itertools.chain.from_iterable(lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = get_git_info() save_json(lowercase_ , os.path.join(lowercase_ , '''git_log.json''' ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Optional[int] , lowercase_ : str=4 , **lowercase_ : List[str] ): '''simple docstring''' with open(lowercase_ , '''w''' ) as f: json.dump(lowercase_ , lowercase_ , indent=lowercase_ , **lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Union[str, Any] ): '''simple docstring''' with open(lowercase_ ) as f: return json.load(lowercase_ ) def lowerCAmelCase_ ( ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = git.Repo(search_parent_directories=lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = { '''repo_id''': str(lowercase_ ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), '''hostname''': str(socket.gethostname() ), } return repo_infos def lowerCAmelCase_ ( lowercase_ : Callable , lowercase_ : Iterable ): '''simple docstring''' return list(map(lowercase_ , lowercase_ ) ) def lowerCAmelCase_ ( lowercase_ : Any , lowercase_ : Any ): '''simple docstring''' with open(lowercase_ , '''wb''' ) as f: return pickle.dump(lowercase_ , lowercase_ ) def lowerCAmelCase_ ( lowercase_ : Any ): '''simple docstring''' def remove_articles(lowercase_ : Dict ): return re.sub(r'''\b(a|an|the)\b''' , ''' ''' , lowercase_ ) def white_space_fix(lowercase_ : Optional[int] ): return " ".join(text.split() ) def remove_punc(lowercase_ : Any ): __SCREAMING_SNAKE_CASE : Optional[int] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowercase_ : int ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowercase_ ) ) ) ) def lowerCAmelCase_ ( lowercase_ : Optional[int] , lowercase_ : int ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Any = normalize_answer(lowercase_ ).split() __SCREAMING_SNAKE_CASE : Tuple = Counter(lowercase_ ) & Counter(lowercase_ ) __SCREAMING_SNAKE_CASE : Tuple = sum(common.values() ) if num_same == 0: return 0 __SCREAMING_SNAKE_CASE : Any = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : List[str] = 1.0 * num_same / len(lowercase_ ) __SCREAMING_SNAKE_CASE : Optional[int] = (2 * precision * recall) / (precision + recall) return fa def lowerCAmelCase_ ( lowercase_ : str , lowercase_ : Union[str, Any] ): '''simple docstring''' return normalize_answer(lowercase_ ) == normalize_answer(lowercase_ ) def lowerCAmelCase_ ( lowercase_ : List[str] , lowercase_ : List[str] ): '''simple docstring''' assert len(lowercase_ ) == len(lowercase_ ) __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for hypo, pred in zip(lowercase_ , lowercase_ ): em += exact_match_score(lowercase_ , lowercase_ ) if len(lowercase_ ) > 0: em /= len(lowercase_ ) return {"em": em} def lowerCAmelCase_ ( lowercase_ : str ): '''simple docstring''' return model_prefix.startswith('''rag''' ) def lowerCAmelCase_ ( lowercase_ : Optional[Any] , lowercase_ : Tuple , lowercase_ : Optional[int] ): '''simple docstring''' __SCREAMING_SNAKE_CASE : Optional[int] = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead __SCREAMING_SNAKE_CASE : Any = '''dropout_rate''' for p in extra_params: if getattr(lowercase_ , lowercase_ , lowercase_ ): if not hasattr(lowercase_ , lowercase_ ) and not hasattr(lowercase_ , equivalent_param[p] ): logger.info('''config doesn\'t have a `{}` attribute'''.format(lowercase_ ) ) delattr(lowercase_ , lowercase_ ) continue __SCREAMING_SNAKE_CASE : Optional[int] = p if hasattr(lowercase_ , lowercase_ ) else equivalent_param[p] setattr(lowercase_ , lowercase_ , getattr(lowercase_ , lowercase_ ) ) delattr(lowercase_ , lowercase_ ) return hparams, config
674
0