code
stringlengths
81
54k
code_codestyle
int64
0
721
style_context
stringlengths
91
41.9k
style_context_codestyle
int64
0
699
label
int64
0
1
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Any = { "google/fnet-base": "https://huggingface.co/google/fnet-base/resolve/main/config.json", "google/fnet-large": "https://huggingface.co/google/fnet-large/resolve/main/config.json" # See all FNet models at https://huggingface.co/models?filter=fnet } class snake_case ( UpperCamelCase_ ): lowercase_ = 'fnet' def __init__( self : Optional[Any] , a_ : List[str]=3_2000 , a_ : Dict=768 , a_ : int=12 , a_ : List[Any]=3072 , a_ : List[str]="gelu_new" , a_ : List[Any]=0.1 , a_ : str=512 , a_ : str=4 , a_ : List[str]=0.02 , a_ : Optional[Any]=1e-1_2 , a_ : int=False , a_ : Optional[int]=512 , a_ : Optional[int]=3 , a_ : List[str]=1 , a_ : Any=2 , **a_ : Optional[Any] , )-> Any: """simple docstring""" super().__init__(pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : str = vocab_size SCREAMING_SNAKE_CASE__ : Tuple = max_position_embeddings SCREAMING_SNAKE_CASE__ : Any = hidden_size SCREAMING_SNAKE_CASE__ : Any = num_hidden_layers SCREAMING_SNAKE_CASE__ : int = intermediate_size SCREAMING_SNAKE_CASE__ : List[str] = hidden_act SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = initializer_range SCREAMING_SNAKE_CASE__ : str = type_vocab_size SCREAMING_SNAKE_CASE__ : Tuple = layer_norm_eps SCREAMING_SNAKE_CASE__ : List[Any] = use_tpu_fourier_optimizations SCREAMING_SNAKE_CASE__ : Optional[Any] = tpu_short_seq_length
720
import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def _a ( lowercase__ : int ): '''simple docstring''' if is_torch_version('<' , '2.0.0' ) or not hasattr(lowercase__ , '_dynamo' ): return False return isinstance(lowercase__ , torch._dynamo.eval_frame.OptimizedModule ) def _a ( lowercase__ : Optional[Any] , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) SCREAMING_SNAKE_CASE__ : Dict = is_compiled_module(lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : Tuple = model SCREAMING_SNAKE_CASE__ : int = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : Any = model.module if not keep_fpaa_wrapper: SCREAMING_SNAKE_CASE__ : List[Any] = getattr(lowercase__ , 'forward' ) SCREAMING_SNAKE_CASE__ : str = model.__dict__.pop('_original_forward' , lowercase__ ) if original_forward is not None: while hasattr(lowercase__ , '__wrapped__' ): SCREAMING_SNAKE_CASE__ : Dict = forward.__wrapped__ if forward == original_forward: break SCREAMING_SNAKE_CASE__ : Dict = forward if getattr(lowercase__ , '_converted_to_transformer_engine' , lowercase__ ): convert_model(lowercase__ , to_transformer_engine=lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : List[Any] = model SCREAMING_SNAKE_CASE__ : Optional[Any] = compiled_model return model def _a ( ): '''simple docstring''' PartialState().wait_for_everyone() def _a ( lowercase__ : str , lowercase__ : Optional[Any] ): '''simple docstring''' if PartialState().distributed_type == DistributedType.TPU: xm.save(lowercase__ , lowercase__ ) elif PartialState().local_process_index == 0: torch.save(lowercase__ , lowercase__ ) @contextmanager def _a ( **lowercase__ : str ): '''simple docstring''' for key, value in kwargs.items(): SCREAMING_SNAKE_CASE__ : int = str(lowercase__ ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if not hasattr(lowercase__ , '__qualname__' ) and not hasattr(lowercase__ , '__name__' ): SCREAMING_SNAKE_CASE__ : Any = getattr(lowercase__ , '__class__' , lowercase__ ) if hasattr(lowercase__ , '__qualname__' ): return obj.__qualname__ if hasattr(lowercase__ , '__name__' ): return obj.__name__ return str(lowercase__ ) def _a ( lowercase__ : List[str] , lowercase__ : List[Any] ): '''simple docstring''' for key, value in source.items(): if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : List[str] = destination.setdefault(lowercase__ , {} ) merge_dicts(lowercase__ , lowercase__ ) else: SCREAMING_SNAKE_CASE__ : List[Any] = value return destination def _a ( lowercase__ : int = None ): '''simple docstring''' if port is None: SCREAMING_SNAKE_CASE__ : int = 2_95_00 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(('localhost', port) ) == 0
636
0
from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class snake_case ( nn.Module ): def __init__( self : str , a_ : int = 16 , a_ : int = 88 , a_ : Optional[int] = None , a_ : int = 1 , a_ : float = 0.0 , a_ : int = 32 , a_ : Optional[int] = None , a_ : bool = False , a_ : Optional[int] = None , a_ : Optional[int] = None , a_ : str = "geglu" , a_ : Optional[int] = None , )-> Optional[Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Optional[Any] = nn.ModuleList( [ TransformeraDModel( num_attention_heads=a_ , attention_head_dim=a_ , in_channels=a_ , num_layers=a_ , dropout=a_ , norm_num_groups=a_ , cross_attention_dim=a_ , attention_bias=a_ , sample_size=a_ , num_vector_embeds=a_ , activation_fn=a_ , num_embeds_ada_norm=a_ , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference SCREAMING_SNAKE_CASE__ : Optional[int] = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` SCREAMING_SNAKE_CASE__ : str = [77, 257] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` SCREAMING_SNAKE_CASE__ : str = [1, 0] def __lowercase( self : Dict , a_ : Tuple , a_ : List[Any] , a_ : int=None , a_ : Dict=None , a_ : int=None , a_ : bool = True , )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = hidden_states SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : Any = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens SCREAMING_SNAKE_CASE__ : List[str] = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] SCREAMING_SNAKE_CASE__ : Tuple = self.transformer_index_for_condition[i] SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.transformers[transformer_index]( a_ , encoder_hidden_states=a_ , timestep=a_ , cross_attention_kwargs=a_ , return_dict=a_ , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] SCREAMING_SNAKE_CASE__ : Dict = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) SCREAMING_SNAKE_CASE__ : Optional[int] = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=a_ )
721
from __future__ import annotations def _a ( lowercase__ : list[int | float] , lowercase__ : int , lowercase__ : int ): '''simple docstring''' if len(lowercase__ ) == 0: raise ValueError('find_max() arg is an empty sequence' ) if ( left >= len(lowercase__ ) or left < -len(lowercase__ ) or right >= len(lowercase__ ) or right < -len(lowercase__ ) ): raise IndexError('list index out of range' ) if left == right: return nums[left] SCREAMING_SNAKE_CASE__ : Union[str, Any] = (left + right) >> 1 # the middle SCREAMING_SNAKE_CASE__ : int = find_max(lowercase__ , lowercase__ , lowercase__ ) # find max in range[left, mid] SCREAMING_SNAKE_CASE__ : Tuple = find_max(lowercase__ , mid + 1 , lowercase__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
636
0
import itertools import os import random import tempfile import unittest import numpy as np from transformers import TvltFeatureExtractor, is_datasets_available from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch if is_datasets_available(): from datasets import load_dataset SCREAMING_SNAKE_CASE__ : Dict = random.Random() def _a ( lowercase__ : Any , lowercase__ : Tuple=1.0 , lowercase__ : int=None , lowercase__ : int=None ): '''simple docstring''' if rng is None: SCREAMING_SNAKE_CASE__ : int = global_rng SCREAMING_SNAKE_CASE__ : Tuple = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class snake_case ( unittest.TestCase ): def __init__( self : Any , a_ : str , a_ : int=7 , a_ : str=400 , a_ : Any=2000 , a_ : List[str]=2048 , a_ : Optional[Any]=128 , a_ : Union[str, Any]=1 , a_ : Dict=512 , a_ : Dict=30 , a_ : Tuple=4_4100 , )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Optional[Any] = batch_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = min_seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = max_seq_length SCREAMING_SNAKE_CASE__ : List[str] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE__ : Any = spectrogram_length SCREAMING_SNAKE_CASE__ : Dict = feature_size SCREAMING_SNAKE_CASE__ : Tuple = num_audio_channels SCREAMING_SNAKE_CASE__ : Any = hop_length SCREAMING_SNAKE_CASE__ : int = chunk_length SCREAMING_SNAKE_CASE__ : Dict = sampling_rate def __lowercase( self : int )-> int: """simple docstring""" return { "spectrogram_length": self.spectrogram_length, "feature_size": self.feature_size, "num_audio_channels": self.num_audio_channels, "hop_length": self.hop_length, "chunk_length": self.chunk_length, "sampling_rate": self.sampling_rate, } def __lowercase( self : int , a_ : Any=False , a_ : Union[str, Any]=False )-> str: """simple docstring""" def _flatten(a_ : Optional[Any] ): return list(itertools.chain(*a_ ) ) if equal_length: SCREAMING_SNAKE_CASE__ : List[str] = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Optional[int] = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : int = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = TvltFeatureExtractor def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = TvltFeatureExtractionTester(self ) def __lowercase( self : Optional[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(a_ , 'spectrogram_length' ) ) self.assertTrue(hasattr(a_ , 'feature_size' ) ) self.assertTrue(hasattr(a_ , 'num_audio_channels' ) ) self.assertTrue(hasattr(a_ , 'hop_length' ) ) self.assertTrue(hasattr(a_ , 'chunk_length' ) ) self.assertTrue(hasattr(a_ , 'sampling_rate' ) ) def __lowercase( self : int )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE__ : Any = feat_extract_first.save_pretrained(a_ )[0] check_json_file_has_correct_format(a_ ) SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE__ : str = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE__ : Dict = dict_first.pop('mel_filters' ) SCREAMING_SNAKE_CASE__ : Tuple = dict_second.pop('mel_filters' ) self.assertTrue(np.allclose(a_ , a_ ) ) self.assertEqual(a_ , a_ ) def __lowercase( self : List[str] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE__ : str = os.path.join(a_ , 'feat_extract.json' ) feat_extract_first.to_json_file(a_ ) SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class.from_json_file(a_ ) SCREAMING_SNAKE_CASE__ : int = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE__ : int = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE__ : Any = dict_first.pop('mel_filters' ) SCREAMING_SNAKE_CASE__ : Any = dict_second.pop('mel_filters' ) self.assertTrue(np.allclose(a_ , a_ ) ) self.assertEqual(a_ , a_ ) def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feature_extraction_class(**self.feat_extract_dict ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Dict = [np.asarray(a_ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor(np_speech_inputs[0] , return_tensors='np' , sampling_rate=4_4100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = feature_extractor(a_ , return_tensors='np' , sampling_rate=4_4100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test audio masking SCREAMING_SNAKE_CASE__ : List[Any] = feature_extractor( a_ , return_tensors='np' , sampling_rate=4_4100 , mask_audio=a_ ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE__ : Any = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE__ : List[str] = np.asarray(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = feature_extractor(a_ , return_tensors='np' , sampling_rate=4_4100 ).audio_values self.assertTrue(encoded_audios.ndim == 4 ) self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size ) self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length ) self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels ) def __lowercase( self : Any , a_ : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation' ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE__ : Optional[int] = ds.sort('id' ).select(range(a_ ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def __lowercase( self : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : Any = TvltFeatureExtractor() SCREAMING_SNAKE_CASE__ : List[Any] = feature_extractor(a_ , return_tensors='pt' ).audio_values self.assertEquals(audio_values.shape , (1, 1, 192, 128) ) SCREAMING_SNAKE_CASE__ : Dict = torch.tensor([[-0.3032, -0.2708], [-0.4434, -0.4007]] ) self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] , a_ , atol=1e-4 ) )
700
# Copyright 2023 The HuggingFace 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 torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def _a ( lowercase__ : Any ): '''simple docstring''' return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def _a ( lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = gather(lowercase__ ) assert gathered_tensor.tolist() == list(range(1 , state.num_processes**2 + 1 ) ) def _a ( lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [state.process_index] SCREAMING_SNAKE_CASE__ : Any = gather_object(lowercase__ ) assert len(lowercase__ ) == state.num_processes, f'''{gathered_obj}, {len(lowercase__ )} != {state.num_processes}''' assert gathered_obj == list(range(state.num_processes ) ), f'''{gathered_obj} != {list(range(state.num_processes ) )}''' def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = broadcast(lowercase__ ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 , state.num_processes + 1 ) ) def _a ( lowercase__ : int ): '''simple docstring''' if state.is_main_process: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.arange(state.num_processes + 1 ).to(state.device ) else: SCREAMING_SNAKE_CASE__ : List[Any] = torch.arange(state.num_processes ).to(state.device ) SCREAMING_SNAKE_CASE__ : Any = pad_across_processes(lowercase__ ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0 , state.num_processes ) ) + [0] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : List[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = reduce(lowercase__ , 'sum' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : Any = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = reduce(lowercase__ , 'mean' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' main() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = PartialState() state.print(f'''State: {state}''' ) state.print('testing gather' ) test_gather(lowercase__ ) state.print('testing gather_object' ) test_gather_object(lowercase__ ) state.print('testing broadcast' ) test_broadcast(lowercase__ ) state.print('testing pad_across_processes' ) test_pad_across_processes(lowercase__ ) state.print('testing reduce_sum' ) test_reduce_sum(lowercase__ ) state.print('testing reduce_mean' ) test_reduce_mean(lowercase__ ) if __name__ == "__main__": main()
636
0
import os from pathlib import Path import numpy as np import pytest from pack_dataset import pack_data_dir from parameterized import parameterized from save_len_file import save_len_file from torch.utils.data import DataLoader from transformers import AutoTokenizer from transformers.models.mbart.modeling_mbart import shift_tokens_right from transformers.testing_utils import TestCasePlus, slow from utils import FAIRSEQ_AVAILABLE, DistributedSortishSampler, LegacySeqaSeqDataset, SeqaSeqDataset SCREAMING_SNAKE_CASE__ : int = "bert-base-cased" SCREAMING_SNAKE_CASE__ : List[Any] = "google/pegasus-xsum" SCREAMING_SNAKE_CASE__ : Union[str, Any] = [" Sam ate lunch today.", "Sams lunch ingredients."] SCREAMING_SNAKE_CASE__ : Any = ["A very interesting story about what I ate for lunch.", "Avocado, celery, turkey, coffee"] SCREAMING_SNAKE_CASE__ : str = "patrickvonplaten/t5-tiny-random" SCREAMING_SNAKE_CASE__ : Tuple = "sshleifer/bart-tiny-random" SCREAMING_SNAKE_CASE__ : Any = "sshleifer/tiny-mbart" SCREAMING_SNAKE_CASE__ : Optional[Any] = "sshleifer/tiny-marian-en-de" def _a ( lowercase__ : Path , lowercase__ : list ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = '\n'.join(lowercase__ ) Path(lowercase__ ).open('w' ).writelines(lowercase__ ) def _a ( lowercase__ : List[Any] ) -> Optional[int]: '''simple docstring''' for split in ["train", "val", "test"]: _dump_articles(os.path.join(lowercase__ , f'''{split}.source''' ) , lowercase__ ) _dump_articles(os.path.join(lowercase__ , f'''{split}.target''' ) , lowercase__ ) return tmp_dir class snake_case ( UpperCamelCase_ ): @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) @slow def __lowercase( self : Optional[Any] , a_ : Optional[int] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = AutoTokenizer.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) SCREAMING_SNAKE_CASE__ : int = max(len(tokenizer.encode(a_ ) ) for a in ARTICLES ) SCREAMING_SNAKE_CASE__ : str = max(len(tokenizer.encode(a_ ) ) for a in SUMMARIES ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 4 SCREAMING_SNAKE_CASE__ : Dict = 8 assert max_len_target > max_src_len # Will be truncated assert max_len_source > max_src_len # Will be truncated SCREAMING_SNAKE_CASE__ : Optional[int] = 'ro_RO', 'de_DE' # ignored for all but mbart, but never causes error. SCREAMING_SNAKE_CASE__ : Optional[int] = SeqaSeqDataset( a_ , data_dir=a_ , type_path='train' , max_source_length=a_ , max_target_length=a_ , src_lang=a_ , tgt_lang=a_ , ) SCREAMING_SNAKE_CASE__ : Any = DataLoader(a_ , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert isinstance(a_ , a_ ) assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_src_len # show that targets are the same len assert batch["labels"].shape[1] == max_tgt_len if tok_name != MBART_TINY: continue # check language codes in correct place SCREAMING_SNAKE_CASE__ : Tuple = shift_tokens_right(batch['labels'] , tokenizer.pad_token_id ) assert batch["decoder_input_ids"][0, 0].item() == tokenizer.lang_code_to_id[tgt_lang] assert batch["decoder_input_ids"][0, -1].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -2].item() == tokenizer.eos_token_id assert batch["input_ids"][0, -1].item() == tokenizer.lang_code_to_id[src_lang] break # No need to test every batch @parameterized.expand([BART_TINY, BERT_BASE_CASED] ) def __lowercase( self : Union[str, Any] , a_ : List[str] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = AutoTokenizer.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : int = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) SCREAMING_SNAKE_CASE__ : Any = max(len(tokenizer.encode(a_ ) ) for a in ARTICLES ) SCREAMING_SNAKE_CASE__ : Any = max(len(tokenizer.encode(a_ ) ) for a in SUMMARIES ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 4 SCREAMING_SNAKE_CASE__ : str = LegacySeqaSeqDataset( a_ , data_dir=a_ , type_path='train' , max_source_length=20 , max_target_length=a_ , ) SCREAMING_SNAKE_CASE__ : List[Any] = DataLoader(a_ , batch_size=2 , collate_fn=train_dataset.collate_fn ) for batch in dataloader: assert batch["attention_mask"].shape == batch["input_ids"].shape # show that articles were trimmed. assert batch["input_ids"].shape[1] == max_len_source assert 20 >= batch["input_ids"].shape[1] # trimmed significantly # show that targets were truncated assert batch["labels"].shape[1] == trunc_target # Truncated assert max_len_target > trunc_target # Truncated break # No need to test every batch def __lowercase( self : Optional[int] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = AutoTokenizer.from_pretrained('facebook/mbart-large-cc25' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) SCREAMING_SNAKE_CASE__ : Any = tmp_dir.joinpath('train.source' ).open().readlines() SCREAMING_SNAKE_CASE__ : Optional[int] = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) ) pack_data_dir(a_ , a_ , 128 , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = {x.name for x in tmp_dir.iterdir()} SCREAMING_SNAKE_CASE__ : Dict = {x.name for x in save_dir.iterdir()} SCREAMING_SNAKE_CASE__ : List[Any] = save_dir.joinpath('train.source' ).open().readlines() # orig: [' Sam ate lunch today.\n', 'Sams lunch ingredients.'] # desired_packed: [' Sam ate lunch today.\n Sams lunch ingredients.'] assert len(a_ ) < len(a_ ) assert len(a_ ) == 1 assert len(packed_examples[0] ) == sum(len(a_ ) for x in orig_examples ) assert orig_paths == new_paths @pytest.mark.skipif(not FAIRSEQ_AVAILABLE , reason='This test requires fairseq' ) def __lowercase( self : int )-> Union[str, Any]: """simple docstring""" if not FAIRSEQ_AVAILABLE: return SCREAMING_SNAKE_CASE__ : List[Any] = self._get_dataset(max_len=64 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 64 SCREAMING_SNAKE_CASE__ : int = ds.make_dynamic_sampler(a_ , required_batch_size_multiple=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = [len(a_ ) for x in batch_sampler] assert len(set(a_ ) ) > 1 # it's not dynamic batch size if every batch is the same length assert sum(a_ ) == len(a_ ) # no dropped or added examples SCREAMING_SNAKE_CASE__ : Union[str, Any] = DataLoader(a_ , batch_sampler=a_ , collate_fn=ds.collate_fn , num_workers=2 ) SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : List[Any] = [] for batch in data_loader: SCREAMING_SNAKE_CASE__ : List[Any] = batch['input_ids'].shape SCREAMING_SNAKE_CASE__ : int = src_shape[0] assert bs % required_batch_size_multiple == 0 or bs < required_batch_size_multiple SCREAMING_SNAKE_CASE__ : Any = np.product(batch['input_ids'].shape ) num_src_per_batch.append(a_ ) if num_src_tokens > (max_tokens * 1.1): failures.append(a_ ) assert num_src_per_batch[0] == max(a_ ) if failures: raise AssertionError(F'''too many tokens in {len(a_ )} batches''' ) def __lowercase( self : Dict )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self._get_dataset(max_len=512 ) SCREAMING_SNAKE_CASE__ : int = 2 SCREAMING_SNAKE_CASE__ : List[Any] = ds.make_sortish_sampler(a_ , shuffle=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = DataLoader(a_ , batch_size=a_ , collate_fn=ds.collate_fn , num_workers=2 ) SCREAMING_SNAKE_CASE__ : List[str] = DataLoader(a_ , batch_size=a_ , collate_fn=ds.collate_fn , num_workers=2 , sampler=a_ ) SCREAMING_SNAKE_CASE__ : str = tokenizer.pad_token_id def count_pad_tokens(a_ : int , a_ : Dict="input_ids" ): return [batch[k].eq(a_ ).sum().item() for batch in data_loader] assert sum(count_pad_tokens(a_ , k='labels' ) ) < sum(count_pad_tokens(a_ , k='labels' ) ) assert sum(count_pad_tokens(a_ ) ) < sum(count_pad_tokens(a_ ) ) assert len(a_ ) == len(a_ ) def __lowercase( self : Optional[Any] , a_ : Union[str, Any]=1000 , a_ : Tuple=128 )-> Optional[int]: """simple docstring""" if os.getenv('USE_REAL_DATA' , a_ ): SCREAMING_SNAKE_CASE__ : Tuple = 'examples/seq2seq/wmt_en_ro' SCREAMING_SNAKE_CASE__ : Tuple = max_len * 2 * 64 if not Path(a_ ).joinpath('train.len' ).exists(): save_len_file(a_ , a_ ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = 'examples/seq2seq/test_data/wmt_en_ro' SCREAMING_SNAKE_CASE__ : Optional[Any] = max_len * 4 save_len_file(a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = AutoTokenizer.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = SeqaSeqDataset( a_ , data_dir=a_ , type_path='train' , max_source_length=a_ , max_target_length=a_ , n_obs=a_ , ) return ds, max_tokens, tokenizer def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self._get_dataset() SCREAMING_SNAKE_CASE__ : Union[str, Any] = set(DistributedSortishSampler(a_ , 256 , num_replicas=2 , rank=0 , add_extra_examples=a_ ) ) SCREAMING_SNAKE_CASE__ : Any = set(DistributedSortishSampler(a_ , 256 , num_replicas=2 , rank=1 , add_extra_examples=a_ ) ) assert idsa.intersection(a_ ) == set() @parameterized.expand( [ MBART_TINY, MARIAN_TINY, T5_TINY, BART_TINY, PEGASUS_XSUM, ] , ) def __lowercase( self : Union[str, Any] , a_ : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = AutoTokenizer.from_pretrained(a_ , use_fast=a_ ) if tok_name == MBART_TINY: SCREAMING_SNAKE_CASE__ : Any = SeqaSeqDataset( a_ , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path='train' , max_source_length=4 , max_target_length=8 , src_lang='EN' , tgt_lang='FR' , ) SCREAMING_SNAKE_CASE__ : Optional[int] = train_dataset.dataset_kwargs assert "src_lang" in kwargs and "tgt_lang" in kwargs else: SCREAMING_SNAKE_CASE__ : Optional[int] = SeqaSeqDataset( a_ , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path='train' , max_source_length=4 , max_target_length=8 , ) SCREAMING_SNAKE_CASE__ : Tuple = train_dataset.dataset_kwargs assert "add_prefix_space" not in kwargs if tok_name != BART_TINY else "add_prefix_space" in kwargs assert len(a_ ) == 1 if tok_name == BART_TINY else len(a_ ) == 0
701
import unittest import numpy as np import requests from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: SCREAMING_SNAKE_CASE__ : Any = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[int] , a_ : Dict=7 , a_ : Any=3 , a_ : Any=18 , a_ : int=30 , a_ : int=400 , a_ : List[Any]=None , a_ : int=True , a_ : int=True , a_ : Dict=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = size if size is not None else {'height': 20, 'width': 20} SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : Any = num_channels SCREAMING_SNAKE_CASE__ : Optional[Any] = image_size SCREAMING_SNAKE_CASE__ : List[str] = min_resolution SCREAMING_SNAKE_CASE__ : Dict = max_resolution SCREAMING_SNAKE_CASE__ : List[Any] = size SCREAMING_SNAKE_CASE__ : Tuple = do_normalize SCREAMING_SNAKE_CASE__ : Optional[Any] = do_convert_rgb SCREAMING_SNAKE_CASE__ : List[str] = [512, 1024, 2048, 4096] SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size if patch_size is not None else {'height': 16, 'width': 16} def __lowercase( self : Optional[Any] )-> str: """simple docstring""" return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def __lowercase( self : Dict )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg' SCREAMING_SNAKE_CASE__ : str = Image.open(requests.get(a_ , stream=a_ ).raw ).convert('RGB' ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PixaStructImageProcessor if is_vision_available() else None def __lowercase( self : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = PixaStructImageProcessingTester(self ) @property def __lowercase( self : Dict )-> Tuple: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , 'do_normalize' ) ) self.assertTrue(hasattr(a_ , 'do_convert_rgb' ) ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.image_processor_tester.prepare_dummy_image() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) SCREAMING_SNAKE_CASE__ : List[Any] = 2048 SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(a_ , return_tensors='pt' , max_patches=a_ ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) ) def __lowercase( self : Any )-> Tuple: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : List[str] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Tuple = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : Any )-> Any: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 SCREAMING_SNAKE_CASE__ : int = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(a_ ): SCREAMING_SNAKE_CASE__ : Dict = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches SCREAMING_SNAKE_CASE__ : List[Any] = 'Hello' SCREAMING_SNAKE_CASE__ : List[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ , header_text=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Any = image_processor( a_ , return_tensors='pt' , max_patches=a_ , header_text=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , numpify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , np.ndarray ) SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : str = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : int = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , torchify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE__ : Any = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PixaStructImageProcessor if is_vision_available() else None def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = PixaStructImageProcessingTester(self , num_channels=4 ) SCREAMING_SNAKE_CASE__ : Dict = 3 @property def __lowercase( self : Any )-> Any: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowercase( self : Dict )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , 'do_normalize' ) ) self.assertTrue(hasattr(a_ , 'do_convert_rgb' ) ) def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : Dict = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Tuple = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
636
0
def _a ( lowercase__ : Tuple , lowercase__ : int , lowercase__ : List[Any]=False ): '''simple docstring''' if isinstance(lowercase__ , lowercase__ ) and isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : List[Any] = len(set_a.intersection(lowercase__ ) ) if alternative_union: SCREAMING_SNAKE_CASE__ : int = len(lowercase__ ) + len(lowercase__ ) else: SCREAMING_SNAKE_CASE__ : Tuple = len(set_a.union(lowercase__ ) ) return intersection / union if isinstance(lowercase__ , (list, tuple) ) and isinstance(lowercase__ , (list, tuple) ): SCREAMING_SNAKE_CASE__ : Any = [element for element in set_a if element in set_b] if alternative_union: SCREAMING_SNAKE_CASE__ : Optional[Any] = len(lowercase__ ) + len(lowercase__ ) return len(lowercase__ ) / union else: SCREAMING_SNAKE_CASE__ : Any = set_a + [element for element in set_b if element not in set_a] return len(lowercase__ ) / len(lowercase__ ) return len(lowercase__ ) / len(lowercase__ ) return None if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : List[Any] = {"a", "b", "c", "d", "e"} SCREAMING_SNAKE_CASE__ : Tuple = {"c", "d", "e", "f", "h", "i"} print(jaccard_similarity(set_a, set_b))
702
import heapq as hq import math from collections.abc import Iterator class snake_case : def __init__( self : str , a_ : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = str(id_ ) SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} # {vertex:distance} def __lt__( self : int , a_ : Tuple )-> Union[str, Any]: """simple docstring""" return self.key < other.key def __repr__( self : Any )-> Dict: """simple docstring""" return self.id def __lowercase( self : Optional[Any] , a_ : int )-> List[str]: """simple docstring""" self.neighbors.append(a_ ) def __lowercase( self : int , a_ : int , a_ : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = weight def _a ( lowercase__ : Optional[Any] , lowercase__ : Union[str, Any] , lowercase__ : Tuple , lowercase__ : Dict ): '''simple docstring''' graph[a - 1].add_neighbor(graph[b - 1] ) graph[b - 1].add_neighbor(graph[a - 1] ) # add the edges: graph[a - 1].add_edge(graph[b - 1] , lowercase__ ) graph[b - 1].add_edge(graph[a - 1] , lowercase__ ) def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] for u in graph: SCREAMING_SNAKE_CASE__ : Dict = math.inf SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = 0 SCREAMING_SNAKE_CASE__ : int = graph[:] while q: SCREAMING_SNAKE_CASE__ : Optional[Any] = min(lowercase__ ) q.remove(lowercase__ ) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : int = u SCREAMING_SNAKE_CASE__ : Any = u.edges[v.id] for i in range(1 , len(lowercase__ ) ): a.append((int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) ) return a def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' for u in graph: SCREAMING_SNAKE_CASE__ : List[str] = math.inf SCREAMING_SNAKE_CASE__ : int = None SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : Tuple = list(lowercase__ ) hq.heapify(lowercase__ ) while h: SCREAMING_SNAKE_CASE__ : Optional[int] = hq.heappop(lowercase__ ) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : List[str] = u SCREAMING_SNAKE_CASE__ : Dict = u.edges[v.id] hq.heapify(lowercase__ ) for i in range(1 , len(lowercase__ ) ): yield (int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) def _a ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
636
0
def _a ( lowercase__ : Optional[Any] , lowercase__ : Any , lowercase__ : List[str] , lowercase__ : str , lowercase__ : Dict , lowercase__ : Union[str, Any] ): '''simple docstring''' if index == r: for j in range(lowercase__ ): print(data[j] , end=' ' ) print(' ' ) return # When no more elements are there to put in data[] if i >= n: return # current is included, put next at next location SCREAMING_SNAKE_CASE__ : int = arr[i] combination_util(lowercase__ , lowercase__ , lowercase__ , index + 1 , lowercase__ , i + 1 ) # current is excluded, replace it with # next (Note that i+1 is passed, but # index is not changed) combination_util(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , i + 1 ) # The main function that prints all combinations # of size r in arr[] of size n. This function # mainly uses combinationUtil() def _a ( lowercase__ : List[str] , lowercase__ : List[str] , lowercase__ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = [0] * r # Print all combination using temporary array 'data[]' combination_util(lowercase__ , lowercase__ , lowercase__ , 0 , lowercase__ , 0 ) if __name__ == "__main__": # Driver code to check the function above SCREAMING_SNAKE_CASE__ : List[Any] = [10, 20, 30, 40, 50] print_combination(arr, len(arr), 3) # This code is contributed by Ambuj sahu
703
def _a ( lowercase__ : int , lowercase__ : int ): '''simple docstring''' return int((input_a, input_a).count(0 ) != 0 ) def _a ( ): '''simple docstring''' assert nand_gate(0 , 0 ) == 1 assert nand_gate(0 , 1 ) == 1 assert nand_gate(1 , 0 ) == 1 assert nand_gate(1 , 1 ) == 0 if __name__ == "__main__": print(nand_gate(0, 0)) print(nand_gate(0, 1)) print(nand_gate(1, 0)) print(nand_gate(1, 1))
636
0
# Copyright 2023 The HuggingFace 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 torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def _a ( lowercase__ : Any ): '''simple docstring''' return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def _a ( lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = gather(lowercase__ ) assert gathered_tensor.tolist() == list(range(1 , state.num_processes**2 + 1 ) ) def _a ( lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [state.process_index] SCREAMING_SNAKE_CASE__ : Any = gather_object(lowercase__ ) assert len(lowercase__ ) == state.num_processes, f'''{gathered_obj}, {len(lowercase__ )} != {state.num_processes}''' assert gathered_obj == list(range(state.num_processes ) ), f'''{gathered_obj} != {list(range(state.num_processes ) )}''' def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = broadcast(lowercase__ ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 , state.num_processes + 1 ) ) def _a ( lowercase__ : int ): '''simple docstring''' if state.is_main_process: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.arange(state.num_processes + 1 ).to(state.device ) else: SCREAMING_SNAKE_CASE__ : List[Any] = torch.arange(state.num_processes ).to(state.device ) SCREAMING_SNAKE_CASE__ : Any = pad_across_processes(lowercase__ ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0 , state.num_processes ) ) + [0] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : List[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = reduce(lowercase__ , 'sum' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : Any = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = reduce(lowercase__ , 'mean' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' main() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = PartialState() state.print(f'''State: {state}''' ) state.print('testing gather' ) test_gather(lowercase__ ) state.print('testing gather_object' ) test_gather_object(lowercase__ ) state.print('testing broadcast' ) test_broadcast(lowercase__ ) state.print('testing pad_across_processes' ) test_pad_across_processes(lowercase__ ) state.print('testing reduce_sum' ) test_reduce_sum(lowercase__ ) state.print('testing reduce_mean' ) test_reduce_mean(lowercase__ ) if __name__ == "__main__": main()
704
from math import factorial, radians def _a ( lowercase__ : float , lowercase__ : int = 18 , lowercase__ : int = 10 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0) # Converting from degrees to radians SCREAMING_SNAKE_CASE__ : int = radians(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = angle_in_radians SCREAMING_SNAKE_CASE__ : Optional[int] = 3 SCREAMING_SNAKE_CASE__ : Optional[int] = -1 for _ in range(lowercase__ ): result += (b * (angle_in_radians**a)) / factorial(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(lowercase__ , lowercase__ ) if __name__ == "__main__": __import__("doctest").testmod()
636
0
from ..utils import DummyObject, requires_backends class snake_case ( metaclass=UpperCamelCase_ ): lowercase_ = ['onnx'] def __init__( self : str , *a_ : Tuple , **a_ : Dict )-> Union[str, Any]: """simple docstring""" requires_backends(self , ['onnx'] ) @classmethod def __lowercase( cls : Any , *a_ : List[Any] , **a_ : int )-> Optional[int]: """simple docstring""" requires_backends(cls , ['onnx'] ) @classmethod def __lowercase( cls : List[Any] , *a_ : int , **a_ : List[str] )-> List[str]: """simple docstring""" requires_backends(cls , ['onnx'] )
705
import math def _a ( lowercase__ : int ): '''simple docstring''' assert isinstance(lowercase__ , lowercase__ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False SCREAMING_SNAKE_CASE__ : Tuple = range(3 , int(math.sqrt(lowercase__ ) + 1 ) , 2 ) return not any(not number % i for i in odd_numbers ) def _a ( lowercase__ : List[str] , lowercase__ : Any=1 , **lowercase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = factor * value SCREAMING_SNAKE_CASE__ : Dict = value while not is_prime(lowercase__ ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1 , **lowercase__ ) return value
636
0
import doctest import glob import importlib import inspect import os import re from contextlib import contextmanager from functools import wraps from unittest.mock import patch import numpy as np import pytest from absl.testing import parameterized import datasets from datasets import load_metric from .utils import for_all_test_methods, local, slow # mark all tests as integration SCREAMING_SNAKE_CASE__ : Optional[Any] = pytest.mark.integration SCREAMING_SNAKE_CASE__ : int = {"comet"} SCREAMING_SNAKE_CASE__ : Optional[int] = importlib.util.find_spec("fairseq") is not None SCREAMING_SNAKE_CASE__ : List[str] = {"code_eval"} SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.name == "nt" SCREAMING_SNAKE_CASE__ : Optional[Any] = {"bertscore", "frugalscore", "perplexity"} SCREAMING_SNAKE_CASE__ : Tuple = importlib.util.find_spec("transformers") is not None def _a ( lowercase__ : Union[str, Any] ): '''simple docstring''' @wraps(lowercase__ ) def wrapper(self : Any , lowercase__ : List[Any] ): if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ: self.skipTest('"test requires Fairseq"' ) else: test_case(self , lowercase__ ) return wrapper def _a ( lowercase__ : Tuple ): '''simple docstring''' @wraps(lowercase__ ) def wrapper(self : Optional[Any] , lowercase__ : int ): if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS: self.skipTest('"test requires transformers"' ) else: test_case(self , lowercase__ ) return wrapper def _a ( lowercase__ : str ): '''simple docstring''' @wraps(lowercase__ ) def wrapper(self : Any , lowercase__ : Dict ): if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS: self.skipTest('"test not supported on Windows"' ) else: test_case(self , lowercase__ ) return wrapper def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = [metric_dir.split(os.sep )[-2] for metric_dir in glob.glob('./metrics/*/' )] return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"] # gleu is unfinished @parameterized.named_parameters(get_local_metric_names() ) @for_all_test_methods( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) @local class snake_case ( parameterized.TestCase ): lowercase_ = {} lowercase_ = None @pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning' ) @pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning' ) def __lowercase( self : List[Any] , a_ : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = '[...]' SCREAMING_SNAKE_CASE__ : List[Any] = importlib.import_module( datasets.load.metric_module_factory(os.path.join('metrics' , a_ ) ).module_path ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = datasets.load.import_main_class(metric_module.__name__ , dataset=a_ ) # check parameters SCREAMING_SNAKE_CASE__ : List[str] = inspect.signature(metric._compute ).parameters self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values() ) ) # no **kwargs # run doctest with self.patch_intensive_calls(a_ , metric_module.__name__ ): with self.use_local_metrics(): try: SCREAMING_SNAKE_CASE__ : Optional[int] = doctest.testmod(a_ , verbose=a_ , raise_on_error=a_ ) except doctest.UnexpectedException as e: raise e.exc_info[1] # raise the exception that doctest caught self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @slow def __lowercase( self : int , a_ : Tuple )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = '[...]' SCREAMING_SNAKE_CASE__ : str = importlib.import_module( datasets.load.metric_module_factory(os.path.join('metrics' , a_ ) ).module_path ) # run doctest with self.use_local_metrics(): SCREAMING_SNAKE_CASE__ : List[Any] = doctest.testmod(a_ , verbose=a_ , raise_on_error=a_ ) self.assertEqual(results.failed , 0 ) self.assertGreater(results.attempted , 1 ) @contextmanager def __lowercase( self : List[Any] , a_ : Optional[Any] , a_ : Tuple )-> Union[str, Any]: """simple docstring""" if metric_name in self.INTENSIVE_CALLS_PATCHER: with self.INTENSIVE_CALLS_PATCHER[metric_name](a_ ): yield else: yield @contextmanager def __lowercase( self : List[str] )-> Tuple: """simple docstring""" def load_local_metric(a_ : Any , *a_ : str , **a_ : Optional[int] ): return load_metric(os.path.join('metrics' , a_ ) , *a_ , **a_ ) with patch('datasets.load_metric' ) as mock_load_metric: SCREAMING_SNAKE_CASE__ : Tuple = load_local_metric yield @classmethod def __lowercase( cls : Optional[int] , a_ : List[str] )-> List[str]: """simple docstring""" def wrapper(a_ : str ): SCREAMING_SNAKE_CASE__ : Optional[int] = contextmanager(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = patcher return patcher return wrapper @LocalMetricTest.register_intensive_calls_patcher('bleurt' ) def _a ( lowercase__ : str ): '''simple docstring''' import tensorflow.compat.va as tf from bleurt.score import Predictor tf.flags.DEFINE_string('sv' , '' , '' ) # handle pytest cli flags class snake_case ( UpperCamelCase_ ): def __lowercase( self : Any , a_ : Optional[Any] )-> str: """simple docstring""" assert len(input_dict['input_ids'] ) == 2 return np.array([1.03, 1.04] ) # mock predict_fn which is supposed to do a forward pass with a bleurt model with patch('bleurt.score._create_predictor' ) as mock_create_predictor: SCREAMING_SNAKE_CASE__ : int = MockedPredictor() yield @LocalMetricTest.register_intensive_calls_patcher('bertscore' ) def _a ( lowercase__ : Dict ): '''simple docstring''' import torch def bert_cos_score_idf(lowercase__ : Optional[Any] , lowercase__ : Dict , *lowercase__ : Dict , **lowercase__ : List[str] ): return torch.tensor([[1.0, 1.0, 1.0]] * len(lowercase__ ) ) # mock get_model which is supposed to do download a bert model # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model with patch('bert_score.scorer.get_model' ), patch( 'bert_score.scorer.bert_cos_score_idf' ) as mock_bert_cos_score_idf: SCREAMING_SNAKE_CASE__ : Optional[int] = bert_cos_score_idf yield @LocalMetricTest.register_intensive_calls_patcher('comet' ) def _a ( lowercase__ : int ): '''simple docstring''' def load_from_checkpoint(lowercase__ : Optional[int] ): class snake_case : def __lowercase( self : Tuple , a_ : List[str] , *a_ : Optional[Any] , **a_ : str )-> Optional[Any]: """simple docstring""" assert len(a_ ) == 2 SCREAMING_SNAKE_CASE__ : Any = [0.19, 0.92] return scores, sum(a_ ) / len(a_ ) return Model() # mock load_from_checkpoint which is supposed to do download a bert model # mock load_from_checkpoint which is supposed to do download a bert model with patch('comet.download_model' ) as mock_download_model: SCREAMING_SNAKE_CASE__ : Tuple = None with patch('comet.load_from_checkpoint' ) as mock_load_from_checkpoint: SCREAMING_SNAKE_CASE__ : List[str] = load_from_checkpoint yield def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = load_metric(os.path.join('metrics' , 'seqeval' ) ) SCREAMING_SNAKE_CASE__ : int = 'ERROR' SCREAMING_SNAKE_CASE__ : str = f'''Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}''' with pytest.raises(lowercase__ , match=re.escape(lowercase__ ) ): metric.compute(predictions=[] , references=[] , scheme=lowercase__ )
706
import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class snake_case : def __init__( self : str , a_ : List[str] , a_ : Tuple=13 , a_ : Dict=30 , a_ : Optional[int]=2 , a_ : Tuple=3 , a_ : Dict=True , a_ : int=True , a_ : Optional[Any]=32 , a_ : List[str]=5 , a_ : Any=4 , a_ : Dict=37 , a_ : Dict="gelu" , a_ : int=0.1 , a_ : Optional[Any]=0.1 , a_ : Any=10 , a_ : List[str]=0.02 , a_ : Any=3 , a_ : List[str]=None , a_ : Optional[int]=2 , )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = parent SCREAMING_SNAKE_CASE__ : int = batch_size SCREAMING_SNAKE_CASE__ : int = image_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE__ : Optional[int] = num_channels SCREAMING_SNAKE_CASE__ : int = is_training SCREAMING_SNAKE_CASE__ : List[Any] = use_labels SCREAMING_SNAKE_CASE__ : str = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = scope SCREAMING_SNAKE_CASE__ : str = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) SCREAMING_SNAKE_CASE__ : Optional[int] = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_patches + 2 def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE__ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_config() return config, pixel_values, labels def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=a_ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __lowercase( self : List[str] , a_ : List[str] , a_ : Optional[Any] , a_ : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = DeiTModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : List[str] , a_ : List[str] , a_ : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = DeiTForMaskedImageModeling(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Optional[int] = 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = DeiTForMaskedImageModeling(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : int = model(a_ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowercase( self : List[str] , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : int = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : List[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Dict = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) lowercase_ = ( { 'feature-extraction': DeiTModel, 'image-classification': (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = DeiTModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , has_text_modality=a_ , hidden_size=37 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='DeiT does not use inputs_embeds' ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" pass def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a_ , nn.Linear ) ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[str] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : int = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*a_ ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) def __lowercase( self : str , a_ : str , a_ : Tuple , a_ : Union[str, Any]=False )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = super()._prepare_for_class(a_ , a_ , return_labels=a_ ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[Any] = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(a_ ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE__ : Tuple = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : List[Any] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = True for model_class in self.all_model_classes: if model_class in get_values(a_ ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) model.gradient_checkpointing_enable() model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[str] = [ {'title': 'multi_label_classification', 'num_labels': 2, 'dtype': torch.float}, {'title': 'single_label_classification', 'num_labels': 1, 'dtype': torch.long}, {'title': 'regression', 'num_labels': 1, 'dtype': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(a_ ), *get_values(a_ ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'''Testing {model_class} with {problem_type['title']}''' ): SCREAMING_SNAKE_CASE__ : int = problem_type['title'] SCREAMING_SNAKE_CASE__ : Tuple = problem_type['num_labels'] SCREAMING_SNAKE_CASE__ : str = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs['labels'].unsqueeze(1 ).repeat(1 , problem_type['num_labels'] ) SCREAMING_SNAKE_CASE__ : Any = inputs['labels'].to(problem_type['dtype'] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=a_ ) as warning_list: SCREAMING_SNAKE_CASE__ : str = model(**a_ ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( F'''Something is going wrong in the regression problem: intercepted {w.message}''' ) loss.backward() @slow def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = DeiTModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : int )-> Dict: """simple docstring""" return ( DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224' ) if is_vision_available() else None ) @slow def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = DeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224' ).to( a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : List[Any] = prepare_img() SCREAMING_SNAKE_CASE__ : List[str] = image_processor(images=a_ , return_tensors='pt' ).to(a_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(**a_ ) # verify the logits SCREAMING_SNAKE_CASE__ : int = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor([-1.0266, 0.1912, -1.2861] ).to(a_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a_ , atol=1e-4 ) ) @slow @require_accelerate @require_torch_gpu def __lowercase( self : Tuple )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = DeiTModel.from_pretrained( 'facebook/deit-base-distilled-patch16-224' , torch_dtype=torch.floataa , device_map='auto' ) SCREAMING_SNAKE_CASE__ : Dict = self.default_image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = prepare_img() SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(images=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = inputs.pixel_values.to(a_ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ )
636
0
def _a ( lowercase__ : int = 10**9 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = 1 SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Optional[int] = 0 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : Any = 0 while perimeter <= max_perimeter: perimeters_sum += perimeter prev_value += 2 * value value += prev_value SCREAMING_SNAKE_CASE__ : Tuple = 2 * value + 2 if i % 2 == 0 else 2 * value - 2 i += 1 return perimeters_sum if __name__ == "__main__": print(F"""{solution() = }""")
707
import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case : def __init__( self : List[Any] , a_ : Dict , a_ : Any=13 , a_ : Any=7 , a_ : Tuple=True , a_ : Tuple=True , a_ : Optional[int]=False , a_ : Dict=True , a_ : Optional[Any]=99 , a_ : Any=32 , a_ : Dict=5 , a_ : Tuple=4 , a_ : List[str]=37 , a_ : Union[str, Any]="gelu" , a_ : Dict=0.1 , a_ : Tuple=0.1 , a_ : List[str]=512 , a_ : List[str]=16 , a_ : List[str]=2 , a_ : Optional[int]=0.02 , a_ : List[str]=3 , a_ : Union[str, Any]=4 , a_ : Optional[Any]=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Dict = batch_size SCREAMING_SNAKE_CASE__ : Dict = seq_length SCREAMING_SNAKE_CASE__ : Optional[Any] = is_training SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_input_mask SCREAMING_SNAKE_CASE__ : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : Any = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = initializer_range SCREAMING_SNAKE_CASE__ : List[Any] = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : str = scope def __lowercase( self : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Tuple = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : str = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : List[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase( self : Dict )-> Tuple: """simple docstring""" return BioGptConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a_ , initializer_range=self.initializer_range , ) def __lowercase( self : Any , a_ : str , a_ : Tuple , a_ : Dict , a_ : Optional[int] , a_ : List[Any] , a_ : Union[str, Any] , a_ : Tuple )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = BioGptModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : Union[str, Any] , a_ : Optional[int] , a_ : Tuple , a_ : Optional[Any] , a_ : int , a_ : Optional[int] , a_ : int , a_ : str , a_ : Optional[Any] , )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = BioGptForCausalLM(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowercase( self : Tuple , a_ : Optional[int] , a_ : Union[str, Any] , a_ : Any , a_ : Any , a_ : Optional[int] , *a_ : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(config=a_ ) model.to(a_ ) model.eval() # create attention mask SCREAMING_SNAKE_CASE__ : Any = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.seq_length // 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 # first forward pass SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ).to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids SCREAMING_SNAKE_CASE__ : str = ids_tensor((1,) , a_ ).item() + 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = random_other_next_tokens # append to next input_ids and attn_mask SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Dict = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=a_ )] , dim=1 , ) # get two different outputs SCREAMING_SNAKE_CASE__ : str = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , past_key_values=a_ , attention_mask=a_ )['last_hidden_state'] # select random slice SCREAMING_SNAKE_CASE__ : Any = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : List[str] = output_from_no_past[:, -1, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : List[str] = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : str , a_ : List[Any] , a_ : str , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Optional[Any] , *a_ : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel(config=a_ ).to(a_ ).eval() SCREAMING_SNAKE_CASE__ : Dict = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) # first forward pass SCREAMING_SNAKE_CASE__ : Any = model(a_ , attention_mask=a_ , use_cache=a_ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : int = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) SCREAMING_SNAKE_CASE__ : int = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , attention_mask=a_ , past_key_values=a_ )[ 'last_hidden_state' ] # select random slice SCREAMING_SNAKE_CASE__ : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : Any = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : Optional[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Any , a_ : List[str] , a_ : Optional[int] , a_ : Any , a_ : Tuple , a_ : Any , *a_ : List[Any] , a_ : Union[str, Any]=False )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = BioGptForCausalLM(a_ ) model.to(a_ ) if gradient_checkpointing: model.gradient_checkpointing_enable() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , labels=a_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def __lowercase( self : Union[str, Any] , a_ : List[str] , *a_ : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def __lowercase( self : Dict , a_ : Tuple , a_ : Tuple , a_ : List[str] , a_ : Any , a_ : str , *a_ : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.num_labels SCREAMING_SNAKE_CASE__ : str = BioGptForTokenClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ , attention_mask=a_ , token_type_ids=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowercase( self : Any )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) lowercase_ = (BioGptForCausalLM,) if is_torch_available() else () lowercase_ = ( { 'feature-extraction': BioGptModel, 'text-classification': BioGptForSequenceClassification, 'text-generation': BioGptForCausalLM, 'token-classification': BioGptForTokenClassification, 'zero-shot': BioGptForSequenceClassification, } if is_torch_available() else {} ) lowercase_ = False def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , hidden_size=37 ) def __lowercase( self : Tuple )-> int: """simple docstring""" self.config_tester.run_common_tests() def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : Union[str, Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE__ : List[str] = type self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : int )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*a_ ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*a_ , gradient_checkpointing=a_ ) def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*a_ ) def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*a_ ) def __lowercase( self : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*a_ ) @slow def __lowercase( self : List[str] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = 'left' # Define PAD Token = EOS Token = 50256 SCREAMING_SNAKE_CASE__ : Any = tokenizer.eos_token SCREAMING_SNAKE_CASE__ : Tuple = model.config.eos_token_id # use different length sentences to test batching SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ 'Hello, my dog is a little', 'Today, I', ] SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer(a_ , return_tensors='pt' , padding=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = inputs['input_ids'].to(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = model.generate( input_ids=a_ , attention_mask=inputs['attention_mask'].to(a_ ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer(sentences[0] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = model.generate(input_ids=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = inputs_non_padded.shape[-1] - inputs['attention_mask'][-1].long().sum().cpu().item() SCREAMING_SNAKE_CASE__ : Dict = tokenizer(sentences[1] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.generate(input_ids=a_ , max_length=model.config.max_length - num_paddings ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.batch_decode(a_ , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.decode(output_non_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = [ 'Hello, my dog is a little bit bigger than a little bit.', 'Today, I have a good idea of how to use the information', ] self.assertListEqual(a_ , a_ ) self.assertListEqual(a_ , [non_padded_sentence, padded_sentence] ) @slow def __lowercase( self : Any )-> List[Any]: """simple docstring""" for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] = 3 SCREAMING_SNAKE_CASE__ : List[Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : int = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : str = 3 SCREAMING_SNAKE_CASE__ : Any = 'multi_label_classification' SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Any = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class snake_case ( unittest.TestCase ): @slow def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([[2, 4805, 9, 656, 21]] ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ )[0] SCREAMING_SNAKE_CASE__ : List[str] = 4_2384 SCREAMING_SNAKE_CASE__ : Dict = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , a_ ) SCREAMING_SNAKE_CASE__ : int = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , a_ , atol=1e-4 ) ) @slow def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer('COVID-19 is' , return_tensors='pt' ).to(a_ ) SCREAMING_SNAKE_CASE__ : int = model.generate( **a_ , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=a_ , ) SCREAMING_SNAKE_CASE__ : int = tokenizer.decode(output_ids[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( 'COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the' ' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and' ' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),' ' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and' ' more than 800,000 deaths.' ) self.assertEqual(a_ , a_ )
636
0
from collections import OrderedDict from typing import Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...feature_extraction_utils import FeatureExtractionMixin from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType, logging SCREAMING_SNAKE_CASE__ : Optional[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "deepmind/language-perceiver": "https://huggingface.co/deepmind/language-perceiver/resolve/main/config.json", # See all Perceiver models at https://huggingface.co/models?filter=perceiver } class snake_case ( UpperCamelCase_ ): lowercase_ = 'perceiver' def __init__( self : Tuple , a_ : int=256 , a_ : Dict=1280 , a_ : Optional[int]=768 , a_ : Union[str, Any]=1 , a_ : Optional[Any]=26 , a_ : Union[str, Any]=8 , a_ : Dict=8 , a_ : Union[str, Any]=None , a_ : Tuple=None , a_ : List[Any]="kv" , a_ : Dict=1 , a_ : Union[str, Any]=1 , a_ : Tuple="gelu" , a_ : Any=0.1 , a_ : Tuple=0.02 , a_ : Dict=1e-1_2 , a_ : Tuple=True , a_ : List[Any]=262 , a_ : Any=2048 , a_ : Optional[int]=56 , a_ : Dict=[368, 496] , a_ : List[Any]=16 , a_ : int=1920 , a_ : Tuple=16 , a_ : Optional[int]=[1, 16, 224, 224] , **a_ : str , )-> int: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : str = num_latents SCREAMING_SNAKE_CASE__ : Optional[int] = d_latents SCREAMING_SNAKE_CASE__ : Union[str, Any] = d_model SCREAMING_SNAKE_CASE__ : Any = num_blocks SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_self_attends_per_block SCREAMING_SNAKE_CASE__ : Tuple = num_self_attention_heads SCREAMING_SNAKE_CASE__ : int = num_cross_attention_heads SCREAMING_SNAKE_CASE__ : Optional[Any] = qk_channels SCREAMING_SNAKE_CASE__ : Tuple = v_channels SCREAMING_SNAKE_CASE__ : str = cross_attention_shape_for_attention SCREAMING_SNAKE_CASE__ : Union[str, Any] = self_attention_widening_factor SCREAMING_SNAKE_CASE__ : str = cross_attention_widening_factor SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : List[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[int] = initializer_range SCREAMING_SNAKE_CASE__ : Optional[int] = layer_norm_eps SCREAMING_SNAKE_CASE__ : Dict = use_query_residual # masked language modeling attributes SCREAMING_SNAKE_CASE__ : Dict = vocab_size SCREAMING_SNAKE_CASE__ : List[Any] = max_position_embeddings # image classification attributes SCREAMING_SNAKE_CASE__ : str = image_size # flow attributes SCREAMING_SNAKE_CASE__ : int = train_size # multimodal autoencoding attributes SCREAMING_SNAKE_CASE__ : Optional[int] = num_frames SCREAMING_SNAKE_CASE__ : int = audio_samples_per_frame SCREAMING_SNAKE_CASE__ : int = samples_per_patch SCREAMING_SNAKE_CASE__ : List[str] = output_shape class snake_case ( UpperCamelCase_ ): @property def __lowercase( self : str )-> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE__ : Union[str, Any] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: SCREAMING_SNAKE_CASE__ : Any = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('inputs', dynamic_axis), ('attention_mask', dynamic_axis), ] ) @property def __lowercase( self : Tuple )-> float: """simple docstring""" return 1e-4 def __lowercase( self : List[str] , a_ : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , a_ : int = -1 , a_ : int = -1 , a_ : int = -1 , a_ : bool = False , a_ : Optional[TensorType] = None , a_ : int = 3 , a_ : int = 40 , a_ : int = 40 , )-> Mapping[str, Any]: """simple docstring""" # copied from `transformers.onnx.config.OnnxConfig` and slightly altered/simplified if isinstance(a_ , a_ ): # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX SCREAMING_SNAKE_CASE__ : Union[str, Any] = compute_effective_axis_dimension( a_ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX SCREAMING_SNAKE_CASE__ : Union[str, Any] = preprocessor.num_special_tokens_to_add(a_ ) SCREAMING_SNAKE_CASE__ : str = compute_effective_axis_dimension( a_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=a_ ) # Generate dummy inputs according to compute batch and sequence SCREAMING_SNAKE_CASE__ : Dict = [' '.join(['a'] ) * seq_length] * batch_size SCREAMING_SNAKE_CASE__ : Any = dict(preprocessor(a_ , return_tensors=a_ ) ) SCREAMING_SNAKE_CASE__ : int = inputs.pop('input_ids' ) return inputs elif isinstance(a_ , a_ ) and preprocessor.model_input_names[0] == "pixel_values": # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX SCREAMING_SNAKE_CASE__ : Union[str, Any] = compute_effective_axis_dimension(a_ , fixed_dimension=OnnxConfig.default_fixed_batch ) SCREAMING_SNAKE_CASE__ : List[str] = self._generate_dummy_images(a_ , a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = dict(preprocessor(images=a_ , return_tensors=a_ ) ) SCREAMING_SNAKE_CASE__ : int = inputs.pop('pixel_values' ) return inputs else: raise ValueError( 'Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor.' )
708
import itertools import random import unittest import numpy as np from transformers import BatchFeature, SpeechTaFeatureExtractor from transformers.testing_utils import require_torch from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : Optional[Any] = random.Random() def _a ( lowercase__ : List[str] , lowercase__ : List[Any]=1.0 , lowercase__ : Optional[int]=None , lowercase__ : List[str]=None ): '''simple docstring''' if rng is None: SCREAMING_SNAKE_CASE__ : Optional[int] = global_rng SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[Any] , a_ : Union[str, Any]=7 , a_ : Any=400 , a_ : List[Any]=2000 , a_ : Tuple=1 , a_ : Optional[int]=0.0 , a_ : Optional[Any]=1_6000 , a_ : str=True , a_ : Union[str, Any]=80 , a_ : Dict=16 , a_ : Tuple=64 , a_ : Any="hann_window" , a_ : Union[str, Any]=80 , a_ : List[Any]=7600 , a_ : Optional[Any]=1e-1_0 , a_ : Dict=True , )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = parent SCREAMING_SNAKE_CASE__ : List[Any] = batch_size SCREAMING_SNAKE_CASE__ : str = min_seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = max_seq_length SCREAMING_SNAKE_CASE__ : str = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE__ : int = feature_size SCREAMING_SNAKE_CASE__ : str = padding_value SCREAMING_SNAKE_CASE__ : Any = sampling_rate SCREAMING_SNAKE_CASE__ : Optional[int] = do_normalize SCREAMING_SNAKE_CASE__ : int = num_mel_bins SCREAMING_SNAKE_CASE__ : int = hop_length SCREAMING_SNAKE_CASE__ : str = win_length SCREAMING_SNAKE_CASE__ : Optional[Any] = win_function SCREAMING_SNAKE_CASE__ : List[str] = fmin SCREAMING_SNAKE_CASE__ : Dict = fmax SCREAMING_SNAKE_CASE__ : int = mel_floor SCREAMING_SNAKE_CASE__ : Tuple = return_attention_mask def __lowercase( self : Dict )-> Dict: """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "do_normalize": self.do_normalize, "num_mel_bins": self.num_mel_bins, "hop_length": self.hop_length, "win_length": self.win_length, "win_function": self.win_function, "fmin": self.fmin, "fmax": self.fmax, "mel_floor": self.mel_floor, "return_attention_mask": self.return_attention_mask, } def __lowercase( self : List[Any] , a_ : str=False , a_ : List[Any]=False )-> Optional[Any]: """simple docstring""" def _flatten(a_ : int ): return list(itertools.chain(*a_ ) ) if equal_length: SCREAMING_SNAKE_CASE__ : Tuple = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Optional[int] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : int = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs def __lowercase( self : Any , a_ : int=False , a_ : Any=False )-> Union[str, Any]: """simple docstring""" if equal_length: SCREAMING_SNAKE_CASE__ : str = [floats_list((self.max_seq_length, self.num_mel_bins) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Tuple = [ floats_list((x, self.num_mel_bins) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : List[str] = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs @require_torch class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = SpeechTaFeatureExtractor def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SpeechTaFeatureExtractionTester(self ) def __lowercase( self : Any , a_ : Optional[int] )-> List[str]: """simple docstring""" self.assertTrue(np.all(np.mean(a_ , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(a_ , axis=0 ) - 1 ) < 1e-3 ) ) def __lowercase( self : Tuple )-> Dict: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : str = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = [np.asarray(a_ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Dict = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Tuple = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : str = feat_extract(a_ , padding=a_ , max_length=a_ , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self.assertTrue(input_values[0][800:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self.assertTrue(input_values[0][1000:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : List[Any] = range(800 , 1400 , 200 ) SCREAMING_SNAKE_CASE__ : int = [floats_list((1, x) )[0] for x in lengths] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , max_length=a_ , padding=a_ ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : int )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='max_length' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def __lowercase( self : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : List[str] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1000) ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : str = feat_extract( a_ , truncation=a_ , max_length=2000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1200) ) def __lowercase( self : Any )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.rand(100 ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : int = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: SCREAMING_SNAKE_CASE__ : Any = feature_extractor.pad([{'input_values': inputs}] , return_tensors='np' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor.pad([{'input_values': inputs}] , return_tensors='pt' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Dict = [np.asarray(a_ ) for speech_input in speech_inputs] # Test feature size SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(audio_target=a_ , padding=a_ , return_tensors='np' ).input_values self.assertTrue(input_values.ndim == 3 ) self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins ) # Test not batched input SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : int = feature_extractor(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE__ : List[str] = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE__ : List[str] = np.asarray(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : str = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Dict )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(a_ ) == len(a_ ) for x, y in zip(a_ , processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} , tensor_type='np' ) SCREAMING_SNAKE_CASE__ : List[Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : int = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} , tensor_type='pt' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : Optional[Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : Tuple )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Dict = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : str = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : List[Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.pad(a_ , padding='longest' , return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Any = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , a_ ) def __lowercase( self : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Tuple = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : str = min(a_ ) SCREAMING_SNAKE_CASE__ : Any = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : int = feat_extract.pad( a_ , padding='max_length' , max_length=a_ , truncation=a_ , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] ) def __lowercase( self : Optional[int] , a_ : List[str] )-> Any: """simple docstring""" from datasets import load_dataset SCREAMING_SNAKE_CASE__ : int = load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation' ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE__ : List[Any] = ds.sort('id' ).select(range(a_ ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def __lowercase( self : List[str] )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor( [2.3_8_0_4e-0_3, 2.0_7_5_2e-0_3, 1.9_8_3_6e-0_3, 2.1_0_5_7e-0_3, 1.6_1_7_4e-0_3, 3.0_5_1_8e-0_4, 9.1_5_5_3e-0_5, 3.3_5_6_9e-0_4, 9.7_6_5_6e-0_4, 1.8_3_1_1e-0_3, 2.0_1_4_2e-0_3, 2.1_0_5_7e-0_3, 1.7_3_9_5e-0_3, 4.5_7_7_6e-0_4, -3.9_6_7_3e-0_4, 4.5_7_7_6e-0_4, 1.0_0_7_1e-0_3, 9.1_5_5_3e-0_5, 4.8_8_2_8e-0_4, 1.1_5_9_7e-0_3, 7.3_2_4_2e-0_4, 9.4_6_0_4e-0_4, 1.8_0_0_5e-0_3, 1.8_3_1_1e-0_3, 8.8_5_0_1e-0_4, 4.2_7_2_5e-0_4, 4.8_8_2_8e-0_4, 7.3_2_4_2e-0_4, 1.0_9_8_6e-0_3, 2.1_0_5_7e-0_3] ) # fmt: on SCREAMING_SNAKE_CASE__ : List[str] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : List[str] = feature_extractor(a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 9_3680) ) self.assertTrue(torch.allclose(input_values[0, :30] , a_ , atol=1e-6 ) ) def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor( [-2.6870, -3.0104, -3.1356, -3.5352, -3.0044, -3.0353, -3.4719, -3.6777, -3.1520, -2.9435, -2.6553, -2.8795, -2.9944, -2.5921, -3.0279, -3.0386, -3.0864, -3.1291, -3.2353, -2.7444, -2.6831, -2.7287, -3.1761, -3.1571, -3.2726, -3.0582, -3.1007, -3.4533, -3.4695, -3.0998] ) # fmt: on SCREAMING_SNAKE_CASE__ : Optional[Any] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : int = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : str = feature_extractor(audio_target=a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 366, 80) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , a_ , atol=1e-4 ) )
636
0
from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : str = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Any = { "EleutherAI/gpt-neox-20b": "https://huggingface.co/EleutherAI/gpt-neox-20b/resolve/main/config.json", # See all GPTNeoX models at https://huggingface.co/models?filter=gpt_neox } class snake_case ( UpperCamelCase_ ): lowercase_ = 'gpt_neox' def __init__( self : Any , a_ : Optional[int]=5_0432 , a_ : int=6144 , a_ : List[str]=44 , a_ : int=64 , a_ : str=2_4576 , a_ : Dict="gelu" , a_ : Any=0.25 , a_ : Any=1_0000 , a_ : Tuple=0.0 , a_ : str=0.0 , a_ : int=0.1 , a_ : List[Any]=2048 , a_ : List[Any]=0.02 , a_ : Dict=1e-5 , a_ : Optional[int]=True , a_ : Optional[int]=0 , a_ : Any=2 , a_ : int=False , a_ : Tuple=True , a_ : Dict=None , **a_ : List[Any] , )-> Tuple: """simple docstring""" super().__init__(bos_token_id=a_ , eos_token_id=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = vocab_size SCREAMING_SNAKE_CASE__ : List[str] = max_position_embeddings SCREAMING_SNAKE_CASE__ : int = hidden_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Tuple = intermediate_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : Any = rotary_pct SCREAMING_SNAKE_CASE__ : Optional[int] = rotary_emb_base SCREAMING_SNAKE_CASE__ : Any = attention_dropout SCREAMING_SNAKE_CASE__ : List[str] = hidden_dropout SCREAMING_SNAKE_CASE__ : Optional[int] = classifier_dropout SCREAMING_SNAKE_CASE__ : Dict = initializer_range SCREAMING_SNAKE_CASE__ : Optional[Any] = layer_norm_eps SCREAMING_SNAKE_CASE__ : int = use_cache SCREAMING_SNAKE_CASE__ : Tuple = tie_word_embeddings SCREAMING_SNAKE_CASE__ : List[str] = use_parallel_residual SCREAMING_SNAKE_CASE__ : List[Any] = rope_scaling self._rope_scaling_validation() if self.hidden_size % self.num_attention_heads != 0: raise ValueError( 'The hidden size is not divisble by the number of attention heads! Make sure to update them!' ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" if self.rope_scaling is None: return if not isinstance(self.rope_scaling , a_ ) or len(self.rope_scaling ) != 2: raise ValueError( '`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, ' F'''got {self.rope_scaling}''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.rope_scaling.get('type' , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.rope_scaling.get('factor' , a_ ) if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]: raise ValueError( F'''`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}''' ) if rope_scaling_factor is None or not isinstance(a_ , a_ ) or rope_scaling_factor <= 1.0: raise ValueError(F'''`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}''' )
709
import math import sys def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = '' try: with open(lowercase__ , 'rb' ) as binary_file: SCREAMING_SNAKE_CASE__ : Tuple = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Tuple = f'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible' ) sys.exit() def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = '', '' SCREAMING_SNAKE_CASE__ : Tuple = len(lowercase__ ) for i in range(len(lowercase__ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : int = lexicon[curr_string] result += last_match_id SCREAMING_SNAKE_CASE__ : str = last_match_id + '0' if math.loga(lowercase__ ).is_integer(): SCREAMING_SNAKE_CASE__ : List[str] = {} for curr_key in list(lowercase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = new_lex SCREAMING_SNAKE_CASE__ : Any = last_match_id + '1' index += 1 SCREAMING_SNAKE_CASE__ : Tuple = '' return result def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = 8 try: with open(lowercase__ , 'wb' ) as opened_file: SCREAMING_SNAKE_CASE__ : Dict = [ 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 _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 0 for letter in data_bits: if letter == "1": break counter += 1 SCREAMING_SNAKE_CASE__ : Optional[int] = data_bits[counter:] SCREAMING_SNAKE_CASE__ : int = data_bits[counter + 1 :] return data_bits def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = read_file_binary(lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = remove_prefix(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = decompress_data(lowercase__ ) write_file_binary(lowercase__ , lowercase__ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
636
0
def _a ( lowercase__ : int , lowercase__ : int ): '''simple docstring''' return int((input_a, input_a).count(0 ) != 0 ) def _a ( ): '''simple docstring''' assert nand_gate(0 , 0 ) == 1 assert nand_gate(0 , 1 ) == 1 assert nand_gate(1 , 0 ) == 1 assert nand_gate(1 , 1 ) == 0 if __name__ == "__main__": print(nand_gate(0, 0)) print(nand_gate(0, 1)) print(nand_gate(1, 0)) print(nand_gate(1, 1))
710
def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : List[Any] = set({'(', '[', '{'} ) SCREAMING_SNAKE_CASE__ : Optional[int] = set({')', ']', '}'} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'{': '}', '[': ']', '(': ')'} for i in range(len(lowercase__ ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(lowercase__ ) == 0 or (len(lowercase__ ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(lowercase__ ) == 0 def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = input('Enter sequence of brackets: ' ) if is_balanced(lowercase__ ): print(lowercase__ , 'is balanced' ) else: print(lowercase__ , 'is not balanced' ) if __name__ == "__main__": main()
636
0
SCREAMING_SNAKE_CASE__ : int = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = input('Enter message: ' ) SCREAMING_SNAKE_CASE__ : Tuple = input('Enter key [alphanumeric]: ' ) SCREAMING_SNAKE_CASE__ : str = input('Encrypt/Decrypt [e/d]: ' ) if mode.lower().startswith('e' ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'encrypt' SCREAMING_SNAKE_CASE__ : int = encrypt_message(lowercase__ , lowercase__ ) elif mode.lower().startswith('d' ): SCREAMING_SNAKE_CASE__ : Optional[int] = 'decrypt' SCREAMING_SNAKE_CASE__ : Optional[int] = decrypt_message(lowercase__ , lowercase__ ) print(f'''\n{mode.title()}ed message:''' ) print(lowercase__ ) def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' return translate_message(lowercase__ , lowercase__ , 'encrypt' ) def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' return translate_message(lowercase__ , lowercase__ , 'decrypt' ) def _a ( lowercase__ : str , lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = key.upper() for symbol in message: SCREAMING_SNAKE_CASE__ : Tuple = LETTERS.find(symbol.upper() ) if num != -1: if mode == "encrypt": num += LETTERS.find(key[key_index] ) elif mode == "decrypt": num -= LETTERS.find(key[key_index] ) num %= len(lowercase__ ) if symbol.isupper(): translated.append(LETTERS[num] ) elif symbol.islower(): translated.append(LETTERS[num].lower() ) key_index += 1 if key_index == len(lowercase__ ): SCREAMING_SNAKE_CASE__ : Dict = 0 else: translated.append(lowercase__ ) return "".join(lowercase__ ) if __name__ == "__main__": main()
711
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 SCREAMING_SNAKE_CASE__ : List[Any] = get_tests_dir("fixtures/test_sentencepiece_no_bos.model") @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : int )-> List[Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : List[Any] = PegasusTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def __lowercase( self : Any , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Union[str, Any] , a_ : List[Any] )-> Optional[int]: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : Optional[int] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = '</s>' SCREAMING_SNAKE_CASE__ : Any = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : Dict )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = 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(a_ ) , 1103 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( '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>' ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word SCREAMING_SNAKE_CASE__ : Any = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 SCREAMING_SNAKE_CASE__ : int = 'To ensure a smooth flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ['This is going to be way too long.' * 150, 'short example'] SCREAMING_SNAKE_CASE__ : int = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. @slow def __lowercase( self : Any )-> str: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Optional[int] = {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 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], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 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=a_ , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Any )-> Union[str, Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Optional[int] = PegasusTokenizer(a_ , offset=0 , mask_token_sent=a_ , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> List[str]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def __lowercase( self : List[str] , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Optional[Any] , a_ : Tuple )-> str: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE__ : str = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : str = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) @require_torch def __lowercase( self : List[str] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = ['This is going to be way too long.' * 1000, 'short example'] SCREAMING_SNAKE_CASE__ : Optional[int] = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : str = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._large_tokenizer(a_ ).input_ids self.assertListEqual( a_ , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
636
0
import copy from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING SCREAMING_SNAKE_CASE__ : List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Optional[int] = { "ut/deta": "https://huggingface.co/ut/deta/resolve/main/config.json", } class snake_case ( UpperCamelCase_ ): lowercase_ = 'deta' lowercase_ = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : List[str] , a_ : Tuple=None , a_ : Any=900 , a_ : Tuple=2048 , a_ : Union[str, Any]=6 , a_ : List[str]=2048 , a_ : int=8 , a_ : Tuple=6 , a_ : List[Any]=1024 , a_ : Dict=8 , a_ : Any=0.0 , a_ : Union[str, Any]=True , a_ : List[Any]="relu" , a_ : Optional[Any]=256 , a_ : Any=0.1 , a_ : str=0.0 , a_ : Union[str, Any]=0.0 , a_ : Tuple=0.02 , a_ : Union[str, Any]=1.0 , a_ : Tuple=True , a_ : Dict=False , a_ : int="sine" , a_ : str=5 , a_ : Any=4 , a_ : int=4 , a_ : List[Any]=True , a_ : List[Any]=300 , a_ : Dict=True , a_ : str=True , a_ : Optional[int]=1 , a_ : str=5 , a_ : Tuple=2 , a_ : List[Any]=1 , a_ : Dict=1 , a_ : Any=5 , a_ : Any=2 , a_ : Optional[int]=0.1 , a_ : str=0.25 , **a_ : Optional[int] , )-> List[Any]: """simple docstring""" if backbone_config is None: logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = CONFIG_MAPPING['resnet'](out_features=['stage2', 'stage3', 'stage4'] ) else: if isinstance(a_ , a_ ): SCREAMING_SNAKE_CASE__ : Optional[int] = backbone_config.pop('model_type' ) SCREAMING_SNAKE_CASE__ : List[Any] = CONFIG_MAPPING[backbone_model_type] SCREAMING_SNAKE_CASE__ : Dict = config_class.from_dict(a_ ) SCREAMING_SNAKE_CASE__ : Dict = backbone_config SCREAMING_SNAKE_CASE__ : Optional[int] = num_queries SCREAMING_SNAKE_CASE__ : Optional[int] = max_position_embeddings SCREAMING_SNAKE_CASE__ : str = d_model SCREAMING_SNAKE_CASE__ : Any = encoder_ffn_dim SCREAMING_SNAKE_CASE__ : Optional[int] = encoder_layers SCREAMING_SNAKE_CASE__ : Dict = encoder_attention_heads SCREAMING_SNAKE_CASE__ : Any = decoder_ffn_dim SCREAMING_SNAKE_CASE__ : List[str] = decoder_layers SCREAMING_SNAKE_CASE__ : List[str] = decoder_attention_heads SCREAMING_SNAKE_CASE__ : Any = dropout SCREAMING_SNAKE_CASE__ : str = attention_dropout SCREAMING_SNAKE_CASE__ : Any = activation_dropout SCREAMING_SNAKE_CASE__ : Any = activation_function SCREAMING_SNAKE_CASE__ : Dict = init_std SCREAMING_SNAKE_CASE__ : Any = init_xavier_std SCREAMING_SNAKE_CASE__ : Optional[int] = encoder_layerdrop SCREAMING_SNAKE_CASE__ : Optional[Any] = auxiliary_loss SCREAMING_SNAKE_CASE__ : Dict = position_embedding_type # deformable attributes SCREAMING_SNAKE_CASE__ : str = num_feature_levels SCREAMING_SNAKE_CASE__ : str = encoder_n_points SCREAMING_SNAKE_CASE__ : Any = decoder_n_points SCREAMING_SNAKE_CASE__ : Optional[int] = two_stage SCREAMING_SNAKE_CASE__ : Dict = two_stage_num_proposals SCREAMING_SNAKE_CASE__ : List[str] = with_box_refine SCREAMING_SNAKE_CASE__ : Any = assign_first_stage if two_stage is True and with_box_refine is False: raise ValueError('If two_stage is True, with_box_refine must be True.' ) # Hungarian matcher SCREAMING_SNAKE_CASE__ : Optional[Any] = class_cost SCREAMING_SNAKE_CASE__ : Dict = bbox_cost SCREAMING_SNAKE_CASE__ : Dict = giou_cost # Loss coefficients SCREAMING_SNAKE_CASE__ : Union[str, Any] = mask_loss_coefficient SCREAMING_SNAKE_CASE__ : str = dice_loss_coefficient SCREAMING_SNAKE_CASE__ : str = bbox_loss_coefficient SCREAMING_SNAKE_CASE__ : Optional[Any] = giou_loss_coefficient SCREAMING_SNAKE_CASE__ : int = eos_coefficient SCREAMING_SNAKE_CASE__ : int = focal_alpha super().__init__(is_encoder_decoder=a_ , **a_ ) @property def __lowercase( self : Optional[Any] )-> int: """simple docstring""" return self.encoder_attention_heads @property def __lowercase( self : str )-> int: """simple docstring""" return self.d_model def __lowercase( self : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.backbone_config.to_dict() SCREAMING_SNAKE_CASE__ : Optional[int] = self.__class__.model_type return output
712
def _a ( lowercase__ : int = 1_00_00_00 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , lowercase__ ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
636
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 SCREAMING_SNAKE_CASE__ : Optional[Any] = "0.12" # assumed parallelism: 8 if is_torch_available(): import torch def _a ( lowercase__ : Optional[Any] , lowercase__ : Tuple , lowercase__ : List[str]=None ): '''simple docstring''' if rng is None: SCREAMING_SNAKE_CASE__ : Optional[int] = random.Random() SCREAMING_SNAKE_CASE__ : Optional[Any] = 1 for dim in shape: total_dims *= dim SCREAMING_SNAKE_CASE__ : Tuple = [] for _ in range(lowercase__ ): values.append(rng.randint(0 , vocab_size - 1 ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.array(lowercase__ , dtype=jnp.intaa ).reshape(lowercase__ ) return output def _a ( lowercase__ : Optional[Any] , lowercase__ : int=None ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = ids_tensor(lowercase__ , vocab_size=2 , rng=lowercase__ ) # make sure that at least one token is attended to for each batch SCREAMING_SNAKE_CASE__ : List[Any] = 1 return attn_mask @require_flax class snake_case : lowercase_ = None lowercase_ = () def __lowercase( self : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs_for_common() # cut to half length & take max batch_size 3 SCREAMING_SNAKE_CASE__ : str = 2 SCREAMING_SNAKE_CASE__ : int = inputs['input_ids'].shape[-1] // 2 SCREAMING_SNAKE_CASE__ : Any = inputs['input_ids'][:max_batch_size, :sequence_length] SCREAMING_SNAKE_CASE__ : Optional[Any] = jnp.ones_like(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = attention_mask[:max_batch_size, :sequence_length] # generate max 5 tokens SCREAMING_SNAKE_CASE__ : 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()` SCREAMING_SNAKE_CASE__ : Tuple = config.eos_token_id return config, input_ids, attention_mask, max_length @is_pt_flax_cross_test def __lowercase( self : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._get_input_ids_and_config() SCREAMING_SNAKE_CASE__ : int = False SCREAMING_SNAKE_CASE__ : str = max_length SCREAMING_SNAKE_CASE__ : Dict = 0 for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE__ : Any = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = model_class.__name__[4:] # Skip the "Flax" at the beginning SCREAMING_SNAKE_CASE__ : Optional[Any] = getattr(a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = pt_model_class(a_ ).eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = load_flax_weights_in_pytorch_model(a_ , flax_model.params ) SCREAMING_SNAKE_CASE__ : Dict = flax_model.generate(a_ ).sequences SCREAMING_SNAKE_CASE__ : str = pt_model.generate(torch.tensor(a_ , dtype=torch.long ) ) if flax_generation_outputs.shape[-1] > pt_generation_outputs.shape[-1]: SCREAMING_SNAKE_CASE__ : List[Any] = flax_generation_outputs[:, : pt_generation_outputs.shape[-1]] self.assertListEqual(pt_generation_outputs.numpy().tolist() , flax_generation_outputs.tolist() ) def __lowercase( self : Optional[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self._get_input_ids_and_config() SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : str = max_length for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE__ : Optional[Any] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : str = model.generate(a_ ).sequences self.assertEqual(generation_outputs.shape[-1] , a_ ) SCREAMING_SNAKE_CASE__ : List[str] = jit(model.generate ) SCREAMING_SNAKE_CASE__ : Dict = jit_generate(a_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __lowercase( self : Tuple )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self._get_input_ids_and_config() SCREAMING_SNAKE_CASE__ : List[str] = True SCREAMING_SNAKE_CASE__ : str = max_length for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE__ : List[str] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.generate(a_ ).sequences self.assertEqual(generation_outputs.shape[-1] , a_ ) SCREAMING_SNAKE_CASE__ : Any = jit(model.generate ) SCREAMING_SNAKE_CASE__ : str = jit_generate(a_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __lowercase( self : int )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self._get_input_ids_and_config() SCREAMING_SNAKE_CASE__ : int = False SCREAMING_SNAKE_CASE__ : str = max_length SCREAMING_SNAKE_CASE__ : Any = 2 for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE__ : Dict = model_class(a_ ) SCREAMING_SNAKE_CASE__ : str = model.generate(a_ ).sequences self.assertEqual(generation_outputs.shape[-1] , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = jit(model.generate ) SCREAMING_SNAKE_CASE__ : Tuple = jit_generate(a_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self._get_input_ids_and_config() SCREAMING_SNAKE_CASE__ : Any = False SCREAMING_SNAKE_CASE__ : Union[str, Any] = max_length SCREAMING_SNAKE_CASE__ : Tuple = 2 SCREAMING_SNAKE_CASE__ : Tuple = 2 for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Dict = model.generate(a_ ).sequences self.assertEqual(generation_outputs.shape[0] , input_ids.shape[0] * config.num_return_sequences ) def __lowercase( self : Any )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self._get_input_ids_and_config() SCREAMING_SNAKE_CASE__ : str = True SCREAMING_SNAKE_CASE__ : int = max_length SCREAMING_SNAKE_CASE__ : List[str] = 0.8 SCREAMING_SNAKE_CASE__ : Tuple = 10 SCREAMING_SNAKE_CASE__ : str = 0.3 SCREAMING_SNAKE_CASE__ : Optional[Any] = 1 SCREAMING_SNAKE_CASE__ : Any = 8 SCREAMING_SNAKE_CASE__ : Dict = 9 for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE__ : Optional[Any] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model.generate(a_ ).sequences self.assertEqual(generation_outputs.shape[-1] , a_ ) SCREAMING_SNAKE_CASE__ : Any = jit(model.generate ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = jit_generate(a_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __lowercase( self : Dict )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self._get_input_ids_and_config() SCREAMING_SNAKE_CASE__ : Union[str, Any] = max_length SCREAMING_SNAKE_CASE__ : Tuple = 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = 8 SCREAMING_SNAKE_CASE__ : str = 9 for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE__ : Dict = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Dict = model.generate(a_ ).sequences self.assertEqual(generation_outputs.shape[-1] , a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = jit(model.generate ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jit_generate(a_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self._get_input_ids_and_config() SCREAMING_SNAKE_CASE__ : List[Any] = max_length SCREAMING_SNAKE_CASE__ : Tuple = 2 SCREAMING_SNAKE_CASE__ : List[Any] = 1 SCREAMING_SNAKE_CASE__ : Any = 8 SCREAMING_SNAKE_CASE__ : Optional[int] = 9 for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = model.generate(a_ ).sequences self.assertEqual(generation_outputs.shape[-1] , a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jit(model.generate ) SCREAMING_SNAKE_CASE__ : int = jit_generate(a_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self._get_input_ids_and_config() # pad attention mask on the left SCREAMING_SNAKE_CASE__ : List[str] = attention_mask.at[(0, 0)].set(0 ) SCREAMING_SNAKE_CASE__ : Any = False SCREAMING_SNAKE_CASE__ : Optional[int] = max_length for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE__ : str = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model.generate(a_ , attention_mask=a_ ).sequences self.assertEqual(generation_outputs.shape[-1] , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = jit(model.generate ) SCREAMING_SNAKE_CASE__ : Tuple = jit_generate(a_ , attention_mask=a_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __lowercase( self : List[str] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self._get_input_ids_and_config() # pad attention mask on the left SCREAMING_SNAKE_CASE__ : List[Any] = attention_mask.at[(0, 0)].set(0 ) SCREAMING_SNAKE_CASE__ : List[str] = True SCREAMING_SNAKE_CASE__ : Dict = max_length for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE__ : Dict = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = model.generate(a_ , attention_mask=a_ ).sequences self.assertEqual(generation_outputs.shape[-1] , a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jit(model.generate ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = jit_generate(a_ , attention_mask=a_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) def __lowercase( self : Any )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self._get_input_ids_and_config() # pad attention mask on the left SCREAMING_SNAKE_CASE__ : List[str] = attention_mask.at[(0, 0)].set(0 ) SCREAMING_SNAKE_CASE__ : Any = 2 SCREAMING_SNAKE_CASE__ : List[Any] = max_length for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE__ : Tuple = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Any = model.generate(a_ , attention_mask=a_ ).sequences self.assertEqual(generation_outputs.shape[-1] , a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = jit(model.generate ) SCREAMING_SNAKE_CASE__ : Dict = jit_generate(a_ , attention_mask=a_ ).sequences self.assertListEqual(generation_outputs.tolist() , jit_generation_outputs.tolist() ) @require_flax class snake_case ( unittest.TestCase ): def __lowercase( self : Optional[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-bert' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = FlaxAutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-bert-flax-only' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 'Hello world' SCREAMING_SNAKE_CASE__ : List[str] = tokenizer(a_ , return_tensors='np' ).input_ids # typos are quickly detected (the correct argument is `do_sample`) with self.assertRaisesRegex(a_ , 'do_samples' ): model.generate(a_ , do_samples=a_ ) # arbitrary arguments that will not be used anywhere are also not accepted with self.assertRaisesRegex(a_ , 'foo' ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'foo': 'bar'} model.generate(a_ , **a_ )
713
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) def _a ( lowercase__ : Union[str, Any] , lowercase__ : Union[str, Any]=False , lowercase__ : str=False , lowercase__ : Dict=False ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''transformer.blocks.{i}.norm1.weight''', f'''vilt.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm1.bias''', f'''vilt.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.weight''', f'''vilt.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.bias''', f'''vilt.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.weight''', f'''vilt.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.bias''', f'''vilt.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.mlp.fc1.weight''', f'''vilt.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc1.bias''', f'''vilt.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.weight''', f'''vilt.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.bias''', f'''vilt.encoder.layer.{i}.output.dense.bias''') ) # embeddings rename_keys.extend( [ # text embeddings ('text_embeddings.word_embeddings.weight', 'vilt.embeddings.text_embeddings.word_embeddings.weight'), ( 'text_embeddings.position_embeddings.weight', 'vilt.embeddings.text_embeddings.position_embeddings.weight', ), ('text_embeddings.position_ids', 'vilt.embeddings.text_embeddings.position_ids'), ( 'text_embeddings.token_type_embeddings.weight', 'vilt.embeddings.text_embeddings.token_type_embeddings.weight', ), ('text_embeddings.LayerNorm.weight', 'vilt.embeddings.text_embeddings.LayerNorm.weight'), ('text_embeddings.LayerNorm.bias', 'vilt.embeddings.text_embeddings.LayerNorm.bias'), # patch embeddings ('transformer.cls_token', 'vilt.embeddings.cls_token'), ('transformer.patch_embed.proj.weight', 'vilt.embeddings.patch_embeddings.projection.weight'), ('transformer.patch_embed.proj.bias', 'vilt.embeddings.patch_embeddings.projection.bias'), ('transformer.pos_embed', 'vilt.embeddings.position_embeddings'), # token type embeddings ('token_type_embeddings.weight', 'vilt.embeddings.token_type_embeddings.weight'), ] ) # final layernorm + pooler rename_keys.extend( [ ('transformer.norm.weight', 'vilt.layernorm.weight'), ('transformer.norm.bias', 'vilt.layernorm.bias'), ('pooler.dense.weight', 'vilt.pooler.dense.weight'), ('pooler.dense.bias', 'vilt.pooler.dense.bias'), ] ) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ('vqa_classifier.0.weight', 'classifier.0.weight'), ('vqa_classifier.0.bias', 'classifier.0.bias'), ('vqa_classifier.1.weight', 'classifier.1.weight'), ('vqa_classifier.1.bias', 'classifier.1.bias'), ('vqa_classifier.3.weight', 'classifier.3.weight'), ('vqa_classifier.3.bias', 'classifier.3.bias'), ] ) elif nlvr_model: # classification head rename_keys.extend( [ ('nlvr2_classifier.0.weight', 'classifier.0.weight'), ('nlvr2_classifier.0.bias', 'classifier.0.bias'), ('nlvr2_classifier.1.weight', 'classifier.1.weight'), ('nlvr2_classifier.1.bias', 'classifier.1.bias'), ('nlvr2_classifier.3.weight', 'classifier.3.weight'), ('nlvr2_classifier.3.bias', 'classifier.3.bias'), ] ) else: pass return rename_keys def _a ( lowercase__ : List[str] , lowercase__ : Dict ): '''simple docstring''' for i in range(config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ : Dict = 'vilt.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[-config.hidden_size :] def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) def _a ( lowercase__ : int , lowercase__ : int , lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = dct.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = val @torch.no_grad() def _a ( lowercase__ : Dict , lowercase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = ViltConfig(image_size=3_84 , patch_size=32 , tie_word_embeddings=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = False SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : str = False if "vqa" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : str = 31_29 SCREAMING_SNAKE_CASE__ : Optional[Any] = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : int = 'vqa2-id2label.json' SCREAMING_SNAKE_CASE__ : str = json.load(open(hf_hub_download(lowercase__ , lowercase__ , repo_type='dataset' ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = idalabel SCREAMING_SNAKE_CASE__ : str = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : List[str] = ViltForQuestionAnswering(lowercase__ ) elif "nlvr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = True SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Dict = {0: 'False', 1: 'True'} SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in config.idalabel.items()} SCREAMING_SNAKE_CASE__ : Tuple = 3 SCREAMING_SNAKE_CASE__ : int = ViltForImagesAndTextClassification(lowercase__ ) elif "irtr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : str = ViltForImageAndTextRetrieval(lowercase__ ) elif "mlm_itm" in checkpoint_url: SCREAMING_SNAKE_CASE__ : int = True SCREAMING_SNAKE_CASE__ : Optional[int] = ViltForMaskedLM(lowercase__ ) else: raise ValueError('Unknown model type' ) # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE__ : Any = torch.hub.load_state_dict_from_url(lowercase__ , map_location='cpu' )['state_dict'] SCREAMING_SNAKE_CASE__ : Any = create_rename_keys(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) for src, dest in rename_keys: rename_key(lowercase__ , lowercase__ , lowercase__ ) read_in_q_k_v(lowercase__ , lowercase__ ) if mlm_model or irtr_model: SCREAMING_SNAKE_CASE__ : Any = ['itm_score.fc.weight', 'itm_score.fc.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) # load state dict into HuggingFace model model.eval() if mlm_model: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model.load_state_dict(lowercase__ , strict=lowercase__ ) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(lowercase__ ) # Define processor SCREAMING_SNAKE_CASE__ : str = ViltImageProcessor(size=3_84 ) SCREAMING_SNAKE_CASE__ : List[Any] = BertTokenizer.from_pretrained('bert-base-uncased' ) SCREAMING_SNAKE_CASE__ : List[Any] = ViltProcessor(lowercase__ , lowercase__ ) # Forward pass on example inputs (image + text) if nlvr_model: SCREAMING_SNAKE_CASE__ : List[str] = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Any = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'The left image contains twice the number of dogs as the right image, and at least two dogs in total are' ' standing.' ) SCREAMING_SNAKE_CASE__ : List[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[str] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[Any] = model( input_ids=encoding_a.input_ids , pixel_values=encoding_a.pixel_values , pixel_values_a=encoding_a.pixel_values , ) else: SCREAMING_SNAKE_CASE__ : Tuple = Image.open(requests.get('http://images.cocodataset.org/val2017/000000039769.jpg' , stream=lowercase__ ).raw ) if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'a bunch of [MASK] laying on a [MASK].' else: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'How many cats are there?' SCREAMING_SNAKE_CASE__ : Optional[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = model(**lowercase__ ) # Verify outputs if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Size([1, 11, 3_05_22] ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([-12.5061, -12.5123, -12.5174] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify masked token prediction equals "cats" SCREAMING_SNAKE_CASE__ : Union[str, Any] = outputs.logits[0, 4, :].argmax(-1 ).item() assert tokenizer.decode([predicted_id] ) == "cats" elif vqa_model: SCREAMING_SNAKE_CASE__ : str = torch.Size([1, 31_29] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([-15.9495, -18.1472, -10.3041] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify vqa prediction equals "2" SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(-1 ).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.Size([1, 2] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([-2.8721, 2.1291] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape Path(lowercase__ ).mkdir(exist_ok=lowercase__ ) print(f'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase__ ) processor.save_pretrained(lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt", type=str, help="URL of the checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
636
0
def _a ( lowercase__ : Tuple , lowercase__ : str , lowercase__ : str , lowercase__ : Dict ): '''simple docstring''' if height >= 1: move_tower(height - 1 , lowercase__ , lowercase__ , lowercase__ ) move_disk(lowercase__ , lowercase__ ) move_tower(height - 1 , lowercase__ , lowercase__ , lowercase__ ) def _a ( lowercase__ : Tuple , lowercase__ : Tuple ): '''simple docstring''' print('moving disk from' , lowercase__ , 'to' , lowercase__ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = int(input('Height of hanoi: ' ).strip() ) move_tower(lowercase__ , 'A' , 'B' , 'C' ) if __name__ == "__main__": main()
714
from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class snake_case : lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def __lowercase( self : Dict )-> Tuple: """simple docstring""" return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def __lowercase( self : Dict )-> Union[str, Any]: """simple docstring""" return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def __lowercase( self : Tuple )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = torch.arange(self.height * self.width ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.stack( [ pixel_indices % self.width, torch.div(a_ , self.width , rounding_mode='trunc' ), ] , axis=1 , ) return coords @property def __lowercase( self : Any )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.shape SCREAMING_SNAKE_CASE__ : Tuple = int(np.prod(a_ ) ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_coords() SCREAMING_SNAKE_CASE__ : Dict = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) SCREAMING_SNAKE_CASE__ : Any = self.get_camera_rays(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = rays.view(a_ , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def __lowercase( self : Optional[Any] , a_ : torch.Tensor )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] SCREAMING_SNAKE_CASE__ : str = coords.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : List[Any] = self.resolution() SCREAMING_SNAKE_CASE__ : str = self.fov() SCREAMING_SNAKE_CASE__ : Any = (flat.float() / (res - 1)) * 2 - 1 SCREAMING_SNAKE_CASE__ : Any = fracs * torch.tan(fov / 2 ) SCREAMING_SNAKE_CASE__ : List[str] = fracs.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : str = ( self.z.view(a_ , 1 , 3 ) + self.x.view(a_ , 1 , 3 ) * fracs[:, :, :1] + self.y.view(a_ , 1 , 3 ) * fracs[:, :, 1:] ) SCREAMING_SNAKE_CASE__ : Tuple = directions / directions.norm(dim=-1 , keepdim=a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.stack( [ torch.broadcast_to(self.origin.view(a_ , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(a_ , *a_ , 2 , 3 ) def __lowercase( self : Optional[int] , a_ : int , a_ : int )-> "DifferentiableProjectiveCamera": """simple docstring""" assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=a_ , height=a_ , x_fov=self.x_fov , y_fov=self.y_fov , ) def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.sin(lowercase__ ), np.cos(lowercase__ ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) SCREAMING_SNAKE_CASE__ : Tuple = -z * 4 SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.cos(lowercase__ ), -np.sin(lowercase__ ), 0.0] ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.cross(lowercase__ , lowercase__ ) origins.append(lowercase__ ) xs.append(lowercase__ ) ys.append(lowercase__ ) zs.append(lowercase__ ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , x=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , y=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , z=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , width=lowercase__ , height=lowercase__ , x_fov=0.7 , y_fov=0.7 , shape=(1, len(lowercase__ )) , )
636
0
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD torch.set_grad_enabled(False) def _a ( lowercase__ : Optional[int] , lowercase__ : List[str]=False ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''module.blocks.{i}.norm1.weight''', f'''vit.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''module.blocks.{i}.norm1.bias''', f'''vit.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (f'''module.blocks.{i}.attn.proj.weight''', f'''vit.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append((f'''module.blocks.{i}.attn.proj.bias''', f'''vit.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''module.blocks.{i}.norm2.weight''', f'''vit.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''module.blocks.{i}.norm2.bias''', f'''vit.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append((f'''module.blocks.{i}.mlp.fc1.weight''', f'''vit.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''module.blocks.{i}.mlp.fc1.bias''', f'''vit.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''module.blocks.{i}.mlp.fc2.weight''', f'''vit.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''module.blocks.{i}.mlp.fc2.bias''', f'''vit.encoder.layer.{i}.output.dense.bias''') ) # projection layer + position embeddings rename_keys.extend( [ ('module.cls_token', 'vit.embeddings.cls_token'), ('module.patch_embed.proj.weight', 'vit.embeddings.patch_embeddings.projection.weight'), ('module.patch_embed.proj.bias', 'vit.embeddings.patch_embeddings.projection.bias'), ('module.pos_embed', 'vit.embeddings.position_embeddings'), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ('module.norm.weight', 'layernorm.weight'), ('module.norm.bias', 'layernorm.bias'), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" SCREAMING_SNAKE_CASE__ : Any = [(pair[0], pair[1][4:]) if pair[1].startswith('vit' ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ('norm.weight', 'vit.layernorm.weight'), ('norm.bias', 'vit.layernorm.bias'), ('head.weight', 'classifier.weight'), ('head.bias', 'classifier.bias'), ] ) return rename_keys def _a ( lowercase__ : int , lowercase__ : Optional[Any] , lowercase__ : Optional[Any]=False ): '''simple docstring''' for i in range(config.num_hidden_layers ): if base_model: SCREAMING_SNAKE_CASE__ : Any = '' else: SCREAMING_SNAKE_CASE__ : List[str] = 'vit.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(f'''module.blocks.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(f'''module.blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE__ : str = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias[-config.hidden_size :] def _a ( lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) def _a ( lowercase__ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = [ 'module.fc.fc1.weight', 'module.fc.fc1.bias', 'module.fc.bn1.weight', 'module.fc.bn1.bias', 'module.fc.bn1.running_mean', 'module.fc.bn1.running_var', 'module.fc.bn1.num_batches_tracked', 'module.fc.fc2.weight', 'module.fc.fc2.bias', 'module.fc.bn2.weight', 'module.fc.bn2.bias', 'module.fc.bn2.running_mean', 'module.fc.bn2.running_var', 'module.fc.bn2.num_batches_tracked', 'module.fc.fc3.weight', 'module.fc.fc3.bias', ] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) def _a ( lowercase__ : str , lowercase__ : Optional[int] , lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = dct.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = val def _a ( lowercase__ : List[str] , lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = ViTMSNConfig() SCREAMING_SNAKE_CASE__ : int = 10_00 SCREAMING_SNAKE_CASE__ : Optional[int] = 'datasets/huggingface/label-files' SCREAMING_SNAKE_CASE__ : Any = 'imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE__ : Any = json.load(open(hf_hub_download(lowercase__ , lowercase__ ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Optional[int] = idalabel SCREAMING_SNAKE_CASE__ : Tuple = {v: k for k, v in idalabel.items()} if "s16" in checkpoint_url: SCREAMING_SNAKE_CASE__ : int = 3_84 SCREAMING_SNAKE_CASE__ : List[str] = 15_36 SCREAMING_SNAKE_CASE__ : Optional[int] = 6 elif "l16" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = 10_24 SCREAMING_SNAKE_CASE__ : List[str] = 40_96 SCREAMING_SNAKE_CASE__ : Optional[int] = 24 SCREAMING_SNAKE_CASE__ : int = 16 SCREAMING_SNAKE_CASE__ : Tuple = 0.1 elif "b4" in checkpoint_url: SCREAMING_SNAKE_CASE__ : List[Any] = 4 elif "l7" in checkpoint_url: SCREAMING_SNAKE_CASE__ : int = 7 SCREAMING_SNAKE_CASE__ : List[str] = 10_24 SCREAMING_SNAKE_CASE__ : Any = 40_96 SCREAMING_SNAKE_CASE__ : Dict = 24 SCREAMING_SNAKE_CASE__ : Tuple = 16 SCREAMING_SNAKE_CASE__ : int = 0.1 SCREAMING_SNAKE_CASE__ : Optional[int] = ViTMSNModel(lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = torch.hub.load_state_dict_from_url(lowercase__ , map_location='cpu' )['target_encoder'] SCREAMING_SNAKE_CASE__ : Tuple = ViTImageProcessor(size=config.image_size ) remove_projection_head(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = create_rename_keys(lowercase__ , base_model=lowercase__ ) for src, dest in rename_keys: rename_key(lowercase__ , lowercase__ , lowercase__ ) read_in_q_k_v(lowercase__ , lowercase__ , base_model=lowercase__ ) model.load_state_dict(lowercase__ ) model.eval() SCREAMING_SNAKE_CASE__ : str = 'http://images.cocodataset.org/val2017/000000039769.jpg' SCREAMING_SNAKE_CASE__ : str = Image.open(requests.get(lowercase__ , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Dict = ViTImageProcessor( size=config.image_size , image_mean=lowercase__ , image_std=lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = image_processor(images=lowercase__ , return_tensors='pt' ) # forward pass torch.manual_seed(2 ) SCREAMING_SNAKE_CASE__ : str = model(**lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = outputs.last_hidden_state # The following Colab Notebook was used to generate these outputs: # https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb if "s16" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Dict = torch.tensor([[-1.0915, -1.4876, -1.1809]] ) elif "b16" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([[14.2889, -18.9045, 11.7281]] ) elif "l16" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Any = torch.tensor([[41.5028, -22.8681, 45.6475]] ) elif "b4" in checkpoint_url: SCREAMING_SNAKE_CASE__ : str = torch.tensor([[-4.3868, 5.2932, -0.4137]] ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([[-0.1792, -0.6465, 2.4263]] ) # verify logits assert torch.allclose(last_hidden_state[:, 0, :3] , lowercase__ , atol=1E-4 ) print(f'''Saving model to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase__ ) print(f'''Saving image processor to {pytorch_dump_folder_path}''' ) image_processor.save_pretrained(lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : List[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar", type=str, help="URL of the checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
715
import requests SCREAMING_SNAKE_CASE__ : int = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page['articles'] , 1 ): print(f'''{i}.) {article['title']}''' ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
636
0
import operator as op def _a ( lowercase__ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : List[Any] = lambda lowercase__ , lowercase__ : int(x / y ) # noqa: E731 integer division operation SCREAMING_SNAKE_CASE__ : Optional[Any] = { '^': op.pow, '*': op.mul, '/': div, '+': op.add, '-': op.sub, } # operators & their respective operation # print table header print('Symbol'.center(8 ) , 'Action'.center(12 ) , 'Stack' , sep=' | ' ) print('-' * (30 + len(lowercase__ )) ) for x in post_fix: if x.isdigit(): # if x in digit stack.append(lowercase__ ) # append x to stack # output in tabular format print(x.rjust(8 ) , ('push(' + x + ')').ljust(12 ) , ','.join(lowercase__ ) , sep=' | ' ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = stack.pop() # pop stack # output in tabular format print(''.rjust(8 ) , ('pop(' + b + ')').ljust(12 ) , ','.join(lowercase__ ) , sep=' | ' ) SCREAMING_SNAKE_CASE__ : Dict = stack.pop() # pop stack # output in tabular format print(''.rjust(8 ) , ('pop(' + a + ')').ljust(12 ) , ','.join(lowercase__ ) , sep=' | ' ) stack.append( str(opr[x](int(lowercase__ ) , int(lowercase__ ) ) ) ) # evaluate the 2 values popped from stack & push result to stack # output in tabular format print( x.rjust(8 ) , ('push(' + a + x + b + ')').ljust(12 ) , ','.join(lowercase__ ) , sep=' | ' , ) return int(stack[0] ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Optional[Any] = input("\n\nEnter a Postfix Equation (space separated) = ").split(" ") print("\n\tResult = ", solve(Postfix))
716
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : Tuple = logging.get_logger() @dataclass class snake_case : lowercase_ = 42 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) def __lowercase( self : Dict , a_ : Dict , a_ : Tensor , a_ : Tensor )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = len(list(m.modules() ) ) == 1 or isinstance(a_ , nn.Convad ) or isinstance(a_ , nn.BatchNormad ) if has_not_submodules: self.traced.append(a_ ) def __call__( self : Tuple , a_ : Tensor )-> Any: """simple docstring""" for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(a_ ) [x.remove() for x in self.handles] return self @property def __lowercase( self : Tuple )-> int: """simple docstring""" # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda a_ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class snake_case : lowercase_ = 42 lowercase_ = 42 lowercase_ = 1 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = True def __call__( self : List[Any] , a_ : Tensor )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = Tracker(self.dest )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : Optional[int] = Tracker(self.src )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : List[str] = list(filter(lambda a_ : type(a_ ) not in self.src_skip , a_ ) ) SCREAMING_SNAKE_CASE__ : Dict = list(filter(lambda a_ : type(a_ ) not in self.dest_skip , a_ ) ) if len(a_ ) != len(a_ ) and self.raise_if_mismatch: raise Exception( F'''Numbers of operations are different. Source module has {len(a_ )} operations while''' F''' destination module has {len(a_ )}.''' ) for dest_m, src_m in zip(a_ , a_ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F'''Transfered from={src_m} to={dest_m}''' ) class snake_case ( nn.Module ): def __init__( self : List[Any] , a_ : nn.Module )-> Dict: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : List[Tuple[str, nn.Module]] = [] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), F'''Unexpected layer name {k}''' SCREAMING_SNAKE_CASE__ : Optional[Any] = len(a_ ) + 1 feature_blocks.append((F'''res{block_index}''', v) ) SCREAMING_SNAKE_CASE__ : Any = nn.ModuleDict(a_ ) def __lowercase( self : Tuple , a_ : Tensor )-> Dict: """simple docstring""" return get_trunk_forward_outputs( a_ , out_feat_keys=a_ , feature_blocks=self._feature_blocks , ) class snake_case ( UpperCamelCase_ ): def __lowercase( self : Optional[Any] , a_ : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Union[str, Any] , a_ : str )-> Callable[[], Tuple[nn.Module, Dict]]: """simple docstring""" # default to timm! if x not in self: SCREAMING_SNAKE_CASE__ : Any = self.convert_name_to_timm(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = partial(lambda: (timm.create_model(a_ , pretrained=a_ ).eval(), None) ) else: SCREAMING_SNAKE_CASE__ : List[str] = super().__getitem__(a_ ) return val class snake_case ( UpperCamelCase_ ): def __getitem__( self : Any , a_ : str )-> Callable[[], nn.Module]: """simple docstring""" if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE__ : Any = RegNetModel else: SCREAMING_SNAKE_CASE__ : Any = RegNetForImageClassification return val def _a ( lowercase__ : Any , lowercase__ : Optional[Any] , lowercase__ : List[Tuple[str, str]] ): '''simple docstring''' for from_key, to_key in keys: SCREAMING_SNAKE_CASE__ : Tuple = from_state_dict[from_key].clone() print(f'''Copied key={from_key} to={to_key}''' ) return to_state_dict def _a ( lowercase__ : str , lowercase__ : Callable[[], nn.Module] , lowercase__ : Callable[[], nn.Module] , lowercase__ : RegNetConfig , lowercase__ : Path , lowercase__ : bool = True , ): '''simple docstring''' print(f'''Converting {name}...''' ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = from_model_func() SCREAMING_SNAKE_CASE__ : int = our_model_func(lowercase__ ).eval() SCREAMING_SNAKE_CASE__ : List[Any] = ModuleTransfer(src=lowercase__ , dest=lowercase__ , raise_if_mismatch=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.randn((1, 3, 2_24, 2_24) ) module_transfer(lowercase__ ) if from_state_dict is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : int = [('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')] SCREAMING_SNAKE_CASE__ : Optional[Any] = manually_copy_vissl_head(lowercase__ , our_model.state_dict() , lowercase__ ) our_model.load_state_dict(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = our_model(lowercase__ , output_hidden_states=lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = ( our_outputs.logits if isinstance(lowercase__ , lowercase__ ) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE__ : List[Any] = from_model(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = from_output[-1] if type(lowercase__ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : List[Any] = our_outputs.hidden_states[-1] assert torch.allclose(lowercase__ , lowercase__ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add model' , use_temp_dir=lowercase__ , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 2_24 if 'seer' not in name else 3_84 # we can use the convnext one SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' , size=lowercase__ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add image processor' , use_temp_dir=lowercase__ , ) print(f'''Pushed {name}''' ) def _a ( lowercase__ : Path , lowercase__ : str = None , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = 'imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE__ : Tuple = 10_00 SCREAMING_SNAKE_CASE__ : Tuple = (1, num_labels) SCREAMING_SNAKE_CASE__ : str = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE__ : List[str] = json.load(open(cached_download(hf_hub_url(lowercase__ , lowercase__ , repo_type='dataset' ) ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : str = idalabel SCREAMING_SNAKE_CASE__ : Tuple = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Any = partial(lowercase__ , num_labels=lowercase__ , idalabel=lowercase__ , labelaid=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = { 'regnet-x-002': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 , layer_type='x' ), 'regnet-x-004': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 1_60, 3_84] , groups_width=16 , layer_type='x' ), 'regnet-x-006': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 2_40, 5_28] , groups_width=24 , layer_type='x' ), 'regnet-x-008': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 1_28, 2_88, 6_72] , groups_width=16 , layer_type='x' ), 'regnet-x-016': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 1_68, 4_08, 9_12] , groups_width=24 , layer_type='x' ), 'regnet-x-032': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 1_92, 4_32, 10_08] , groups_width=48 , layer_type='x' ), 'regnet-x-040': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 2_40, 5_60, 13_60] , groups_width=40 , layer_type='x' ), 'regnet-x-064': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 3_92, 7_84, 16_24] , groups_width=56 , layer_type='x' ), 'regnet-x-080': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 2_40, 7_20, 19_20] , groups_width=1_20 , layer_type='x' ), 'regnet-x-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 , layer_type='x' ), 'regnet-x-160': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[2_56, 5_12, 8_96, 20_48] , groups_width=1_28 , layer_type='x' ), 'regnet-x-320': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[3_36, 6_72, 13_44, 25_20] , groups_width=1_68 , layer_type='x' ), # y variant 'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 ), 'regnet-y-004': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 1_04, 2_08, 4_40] , groups_width=8 ), 'regnet-y-006': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 1_12, 2_56, 6_08] , groups_width=16 ), 'regnet-y-008': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 1_28, 3_20, 7_68] , groups_width=16 ), 'regnet-y-016': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 1_20, 3_36, 8_88] , groups_width=24 ), 'regnet-y-032': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 2_16, 5_76, 15_12] , groups_width=24 ), 'regnet-y-040': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[1_28, 1_92, 5_12, 10_88] , groups_width=64 ), 'regnet-y-064': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[1_44, 2_88, 5_76, 12_96] , groups_width=72 ), 'regnet-y-080': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 4_48, 8_96, 20_16] , groups_width=56 ), 'regnet-y-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 ), 'regnet-y-160': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[2_24, 4_48, 12_32, 30_24] , groups_width=1_12 ), 'regnet-y-320': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer': RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer': RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), # finetuned on imagenet 'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), } SCREAMING_SNAKE_CASE__ : List[Any] = NameToOurModelFuncMap() SCREAMING_SNAKE_CASE__ : Dict = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowercase__ : str , lowercase__ : Callable[[], nn.Module] ) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(lowercase__ , model_dir=str(lowercase__ ) , map_location='cpu' ) SCREAMING_SNAKE_CASE__ : Tuple = model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE__ : str = files['classy_state_dict']['base_model']['model'] SCREAMING_SNAKE_CASE__ : str = model_state_dict['trunk'] model.load_state_dict(lowercase__ ) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : int = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) # IN1K finetuned SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) if model_name: convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , lowercase__ , lowercase__ , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , lowercase__ , lowercase__ , lowercase__ , ) return config, expected_shape if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : Path = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
636
0
'''simple docstring''' from __future__ import annotations def _a ( lowercase__ : list[int | float] , lowercase__ : int , lowercase__ : int ): '''simple docstring''' if len(lowercase__ ) == 0: raise ValueError('find_max() arg is an empty sequence' ) if ( left >= len(lowercase__ ) or left < -len(lowercase__ ) or right >= len(lowercase__ ) or right < -len(lowercase__ ) ): raise IndexError('list index out of range' ) if left == right: return nums[left] SCREAMING_SNAKE_CASE__ : Union[str, Any] = (left + right) >> 1 # the middle SCREAMING_SNAKE_CASE__ : int = find_max(lowercase__ , lowercase__ , lowercase__ ) # find max in range[left, mid] SCREAMING_SNAKE_CASE__ : Tuple = find_max(lowercase__ , mid + 1 , lowercase__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
717
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'OwlViTImageProcessor' lowercase_ = ('CLIPTokenizer', 'CLIPTokenizerFast') def __init__( self : List[str] , a_ : List[Any]=None , a_ : str=None , **a_ : Any )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop('feature_extractor' ) SCREAMING_SNAKE_CASE__ : List[str] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(a_ , a_ ) def __call__( self : Any , a_ : Optional[int]=None , a_ : Tuple=None , a_ : List[Any]=None , a_ : Tuple="max_length" , a_ : str="np" , **a_ : Any )-> int: """simple docstring""" if text is None and query_images is None and images is None: raise ValueError( 'You have to specify at least one text or query image or image. All three cannot be none.' ) if text is not None: if isinstance(a_ , a_ ) or (isinstance(a_ , a_ ) and not isinstance(text[0] , a_ )): SCREAMING_SNAKE_CASE__ : Tuple = [self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ )] elif isinstance(a_ , a_ ) and isinstance(text[0] , a_ ): SCREAMING_SNAKE_CASE__ : Any = [] # Maximum number of queries across batch SCREAMING_SNAKE_CASE__ : str = max([len(a_ ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(a_ ) != max_num_queries: SCREAMING_SNAKE_CASE__ : Tuple = t + [' '] * (max_num_queries - len(a_ )) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ ) encodings.append(a_ ) else: raise TypeError('Input text should be a string, a list of strings or a nested list of strings' ) if return_tensors == "np": SCREAMING_SNAKE_CASE__ : Dict = np.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : List[Any] = np.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jnp.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : int = torch.cat([encoding['input_ids'] for encoding in encodings] , dim=0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([encoding['attention_mask'] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf SCREAMING_SNAKE_CASE__ : str = tf.stack([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Dict = tf.stack([encoding['attention_mask'] for encoding in encodings] , axis=0 ) else: raise ValueError('Target return tensor type could not be returned' ) SCREAMING_SNAKE_CASE__ : Optional[int] = BatchEncoding() SCREAMING_SNAKE_CASE__ : List[str] = input_ids SCREAMING_SNAKE_CASE__ : Tuple = attention_mask if query_images is not None: SCREAMING_SNAKE_CASE__ : Any = BatchEncoding() SCREAMING_SNAKE_CASE__ : Dict = self.image_processor( a_ , return_tensors=a_ , **a_ ).pixel_values SCREAMING_SNAKE_CASE__ : Dict = query_pixel_values if images is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ : Dict = image_features.pixel_values return encoding elif query_images is not None and images is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def __lowercase( self : str , *a_ : List[str] , **a_ : int )-> List[Any]: """simple docstring""" return self.image_processor.post_process(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : List[str] , **a_ : str )-> Union[str, Any]: """simple docstring""" return self.image_processor.post_process_object_detection(*a_ , **a_ ) def __lowercase( self : Optional[Any] , *a_ : str , **a_ : Dict )-> Optional[int]: """simple docstring""" return self.image_processor.post_process_image_guided_detection(*a_ , **a_ ) def __lowercase( self : Optional[int] , *a_ : Tuple , **a_ : Tuple )-> Optional[Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : Tuple , **a_ : Tuple )-> List[str]: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property def __lowercase( self : Tuple )-> Any: """simple docstring""" warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , a_ , ) return self.image_processor_class @property def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , a_ , ) return self.image_processor
636
0
import math import torch from torch import nn from ..configuration_utils import ConfigMixin, register_to_config from .attention_processor import Attention from .embeddings import get_timestep_embedding from .modeling_utils import ModelMixin class snake_case ( UpperCamelCase_ , UpperCamelCase_ ): @register_to_config def __init__( self : Tuple , a_ : int = 128 , a_ : int = 256 , a_ : float = 2000.0 , a_ : int = 768 , a_ : int = 12 , a_ : int = 12 , a_ : int = 64 , a_ : int = 2048 , a_ : float = 0.1 , )-> Dict: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Union[str, Any] = nn.Sequential( nn.Linear(a_ , d_model * 4 , bias=a_ ) , nn.SiLU() , nn.Linear(d_model * 4 , d_model * 4 , bias=a_ ) , nn.SiLU() , ) SCREAMING_SNAKE_CASE__ : Any = nn.Embedding(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Optional[Any] = nn.Linear(a_ , a_ , bias=a_ ) SCREAMING_SNAKE_CASE__ : int = nn.Dropout(p=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = nn.ModuleList() for lyr_num in range(a_ ): # FiLM conditional T5 decoder SCREAMING_SNAKE_CASE__ : Optional[int] = DecoderLayer(d_model=a_ , d_kv=a_ , num_heads=a_ , d_ff=a_ , dropout_rate=a_ ) self.decoders.append(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = TaLayerNorm(a_ ) SCREAMING_SNAKE_CASE__ : Any = nn.Dropout(p=a_ ) SCREAMING_SNAKE_CASE__ : str = nn.Linear(a_ , a_ , bias=a_ ) def __lowercase( self : Dict , a_ : List[str] , a_ : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = torch.mul(query_input.unsqueeze(-1 ) , key_input.unsqueeze(-2 ) ) return mask.unsqueeze(-3 ) def __lowercase( self : Optional[int] , a_ : int , a_ : Optional[Any] , a_ : Tuple )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = decoder_input_tokens.shape assert decoder_noise_time.shape == (batch,) # decoder_noise_time is in [0, 1), so rescale to expected timing range. SCREAMING_SNAKE_CASE__ : Dict = get_timestep_embedding( decoder_noise_time * self.config.max_decoder_noise_time , embedding_dim=self.config.d_model , max_period=self.config.max_decoder_noise_time , ).to(dtype=self.dtype ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.conditioning_emb(a_ ).unsqueeze(1 ) assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4) SCREAMING_SNAKE_CASE__ : Tuple = decoder_input_tokens.shape[1] # If we want to use relative positions for audio context, we can just offset # this sequence by the length of encodings_and_masks. SCREAMING_SNAKE_CASE__ : List[Any] = torch.broadcast_to( torch.arange(a_ , device=decoder_input_tokens.device ) , (batch, seq_length) , ) SCREAMING_SNAKE_CASE__ : str = self.position_encoding(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = self.continuous_inputs_projection(a_ ) inputs += position_encodings SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.dropout(a_ ) # decoder: No padding present. SCREAMING_SNAKE_CASE__ : Optional[int] = torch.ones( decoder_input_tokens.shape[:2] , device=decoder_input_tokens.device , dtype=inputs.dtype ) # Translate encoding masks to encoder-decoder masks. SCREAMING_SNAKE_CASE__ : Union[str, Any] = [(x, self.encoder_decoder_mask(a_ , a_ )) for x, y in encodings_and_masks] # cross attend style: concat encodings SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([x[0] for x in encodings_and_encdec_masks] , dim=1 ) SCREAMING_SNAKE_CASE__ : Dict = torch.cat([x[1] for x in encodings_and_encdec_masks] , dim=-1 ) for lyr in self.decoders: SCREAMING_SNAKE_CASE__ : Union[str, Any] = lyr( a_ , conditioning_emb=a_ , encoder_hidden_states=a_ , encoder_attention_mask=a_ , )[0] SCREAMING_SNAKE_CASE__ : Tuple = self.decoder_norm(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.post_dropout(a_ ) SCREAMING_SNAKE_CASE__ : Any = self.spec_out(a_ ) return spec_out class snake_case ( nn.Module ): def __init__( self : int , a_ : Any , a_ : int , a_ : Optional[int] , a_ : int , a_ : int , a_ : str=1e-6 )-> Any: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Optional[int] = nn.ModuleList() # cond self attention: layer 0 self.layer.append( TaLayerSelfAttentionCond(d_model=a_ , d_kv=a_ , num_heads=a_ , dropout_rate=a_ ) ) # cross attention: layer 1 self.layer.append( TaLayerCrossAttention( d_model=a_ , d_kv=a_ , num_heads=a_ , dropout_rate=a_ , layer_norm_epsilon=a_ , ) ) # Film Cond MLP + dropout: last layer self.layer.append( TaLayerFFCond(d_model=a_ , d_ff=a_ , dropout_rate=a_ , layer_norm_epsilon=a_ ) ) def __lowercase( self : Tuple , a_ : Union[str, Any] , a_ : Tuple=None , a_ : int=None , a_ : List[Any]=None , a_ : Any=None , a_ : Any=None , )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.layer[0]( a_ , conditioning_emb=a_ , attention_mask=a_ , ) if encoder_hidden_states is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.where(encoder_attention_mask > 0 , 0 , -1e1_0 ).to( encoder_hidden_states.dtype ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.layer[1]( a_ , key_value_states=a_ , attention_mask=a_ , ) # Apply Film Conditional Feed Forward layer SCREAMING_SNAKE_CASE__ : List[Any] = self.layer[-1](a_ , a_ ) return (hidden_states,) class snake_case ( nn.Module ): def __init__( self : Union[str, Any] , a_ : Tuple , a_ : Dict , a_ : Union[str, Any] , a_ : int )-> str: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Union[str, Any] = TaLayerNorm(a_ ) SCREAMING_SNAKE_CASE__ : Any = TaFiLMLayer(in_features=d_model * 4 , out_features=a_ ) SCREAMING_SNAKE_CASE__ : str = Attention(query_dim=a_ , heads=a_ , dim_head=a_ , out_bias=a_ , scale_qk=a_ ) SCREAMING_SNAKE_CASE__ : Dict = nn.Dropout(a_ ) def __lowercase( self : Optional[Any] , a_ : List[str] , a_ : str=None , a_ : Tuple=None , )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.layer_norm(a_ ) if conditioning_emb is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.FiLMLayer(a_ , a_ ) # Self-attention block SCREAMING_SNAKE_CASE__ : str = self.attention(a_ ) SCREAMING_SNAKE_CASE__ : int = hidden_states + self.dropout(a_ ) return hidden_states class snake_case ( nn.Module ): def __init__( self : List[Any] , a_ : str , a_ : int , a_ : str , a_ : Union[str, Any] , a_ : Optional[int] )-> Union[str, Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Dict = Attention(query_dim=a_ , heads=a_ , dim_head=a_ , out_bias=a_ , scale_qk=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = TaLayerNorm(a_ , eps=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = nn.Dropout(a_ ) def __lowercase( self : List[Any] , a_ : Dict , a_ : List[str]=None , a_ : Tuple=None , )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.layer_norm(a_ ) SCREAMING_SNAKE_CASE__ : int = self.attention( a_ , encoder_hidden_states=a_ , attention_mask=attention_mask.squeeze(1 ) , ) SCREAMING_SNAKE_CASE__ : List[Any] = hidden_states + self.dropout(a_ ) return layer_output class snake_case ( nn.Module ): def __init__( self : List[str] , a_ : str , a_ : List[Any] , a_ : List[Any] , a_ : Any )-> Optional[int]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Optional[Any] = TaDenseGatedActDense(d_model=a_ , d_ff=a_ , dropout_rate=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = TaFiLMLayer(in_features=d_model * 4 , out_features=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = TaLayerNorm(a_ , eps=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = nn.Dropout(a_ ) def __lowercase( self : Tuple , a_ : Dict , a_ : Any=None )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.layer_norm(a_ ) if conditioning_emb is not None: SCREAMING_SNAKE_CASE__ : Dict = self.film(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.DenseReluDense(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_states + self.dropout(a_ ) return hidden_states class snake_case ( nn.Module ): def __init__( self : Optional[Any] , a_ : Tuple , a_ : int , a_ : Optional[int] )-> List[str]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Optional[int] = nn.Linear(a_ , a_ , bias=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = nn.Linear(a_ , a_ , bias=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = nn.Linear(a_ , a_ , bias=a_ ) SCREAMING_SNAKE_CASE__ : Any = nn.Dropout(a_ ) SCREAMING_SNAKE_CASE__ : Any = NewGELUActivation() def __lowercase( self : Optional[Any] , a_ : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.act(self.wi_a(a_ ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.wi_a(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = hidden_gelu * hidden_linear SCREAMING_SNAKE_CASE__ : List[str] = self.dropout(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.wo(a_ ) return hidden_states class snake_case ( nn.Module ): def __init__( self : str , a_ : Union[str, Any] , a_ : Optional[int]=1e-6 )-> Any: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : List[Any] = nn.Parameter(torch.ones(a_ ) ) SCREAMING_SNAKE_CASE__ : List[str] = eps def __lowercase( self : Union[str, Any] , a_ : int )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = hidden_states.to(torch.floataa ).pow(2 ).mean(-1 , keepdim=a_ ) SCREAMING_SNAKE_CASE__ : str = hidden_states * torch.rsqrt(variance + self.variance_epsilon ) # convert into half-precision if necessary if self.weight.dtype in [torch.floataa, torch.bfloataa]: SCREAMING_SNAKE_CASE__ : List[str] = hidden_states.to(self.weight.dtype ) return self.weight * hidden_states class snake_case ( nn.Module ): def __lowercase( self : Optional[Any] , a_ : torch.Tensor )-> torch.Tensor: """simple docstring""" return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi ) * (input + 0.04_4715 * torch.pow(a_ , 3.0 )) )) class snake_case ( nn.Module ): def __init__( self : Union[str, Any] , a_ : Tuple , a_ : Tuple )-> List[str]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : List[Any] = nn.Linear(a_ , out_features * 2 , bias=a_ ) def __lowercase( self : int , a_ : List[Any] , a_ : Dict )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.scale_bias(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.chunk(a_ , 2 , -1 ) SCREAMING_SNAKE_CASE__ : int = x * (1 + scale) + shift return x
718
class snake_case ( UpperCamelCase_ ): pass class snake_case ( UpperCamelCase_ ): pass class snake_case : def __init__( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [ [], [], [], ] def __lowercase( self : int , a_ : int , a_ : int )-> None: """simple docstring""" try: if len(self.queues[priority] ) >= 100: raise OverflowError('Maximum queue size is 100' ) self.queues[priority].append(a_ ) except IndexError: raise ValueError('Valid priorities are 0, 1, and 2' ) def __lowercase( self : int )-> int: """simple docstring""" for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError('All queues are empty' ) def __str__( self : Any )-> str: """simple docstring""" return "\n".join(F'''Priority {i}: {q}''' for i, q in enumerate(self.queues ) ) class snake_case : def __init__( self : Union[str, Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [] def __lowercase( self : List[str] , a_ : int )-> None: """simple docstring""" if len(self.queue ) == 100: raise OverFlowError('Maximum queue size is 100' ) self.queue.append(a_ ) def __lowercase( self : int )-> int: """simple docstring""" if not self.queue: raise UnderFlowError('The queue is empty' ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = min(self.queue ) self.queue.remove(a_ ) return data def __str__( self : List[str] )-> str: """simple docstring""" return str(self.queue ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 1_00 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 1_28 ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(1_00 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(1_28 ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
636
0
from math import ceil def _a ( lowercase__ : int = 10_01 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 1 for i in range(1 , int(ceil(n / 2.0 ) ) ): SCREAMING_SNAKE_CASE__ : List[Any] = 2 * i + 1 SCREAMING_SNAKE_CASE__ : Tuple = 2 * i SCREAMING_SNAKE_CASE__ : List[str] = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: SCREAMING_SNAKE_CASE__ : Optional[int] = int(sys.argv[1]) print(solution(n)) except ValueError: print("Invalid entry - please enter a number")
719
from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def _a ( lowercase__ : List[str] ): '''simple docstring''' if not is_accelerate_available(): return method SCREAMING_SNAKE_CASE__ : str = version.parse(accelerate.__version__ ).base_version if version.parse(lowercase__ ) < version.parse('0.17.0' ): return method def wrapper(self : Optional[int] , *lowercase__ : int , **lowercase__ : Tuple ): if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ): self._hf_hook.pre_forward(self ) return method(self , *lowercase__ , **lowercase__ ) return wrapper
636
0
from typing import Dict, List, Optional, Tuple, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, flip_channel_order, get_resize_output_image_size, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_torch_available, is_torch_tensor, is_vision_available, logging if is_vision_available(): import PIL if is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : Any = logging.get_logger(__name__) class snake_case ( UpperCamelCase_ ): lowercase_ = ['pixel_values'] def __init__( self : List[Any] , a_ : bool = True , a_ : Dict[str, int] = None , a_ : PILImageResampling = PILImageResampling.BILINEAR , a_ : bool = True , a_ : Union[int, float] = 1 / 255 , a_ : bool = True , a_ : Dict[str, int] = None , a_ : bool = True , **a_ : Any , )-> None: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = size if size is not None else {'shortest_edge': 224} SCREAMING_SNAKE_CASE__ : List[Any] = get_size_dict(a_ , default_to_square=a_ ) SCREAMING_SNAKE_CASE__ : int = crop_size if crop_size is not None else {'height': 256, 'width': 256} SCREAMING_SNAKE_CASE__ : Optional[int] = get_size_dict(a_ , param_name='crop_size' ) SCREAMING_SNAKE_CASE__ : Any = do_resize SCREAMING_SNAKE_CASE__ : Any = size SCREAMING_SNAKE_CASE__ : int = resample SCREAMING_SNAKE_CASE__ : Union[str, Any] = do_rescale SCREAMING_SNAKE_CASE__ : List[Any] = rescale_factor SCREAMING_SNAKE_CASE__ : Tuple = do_center_crop SCREAMING_SNAKE_CASE__ : Dict = crop_size SCREAMING_SNAKE_CASE__ : str = do_flip_channel_order def __lowercase( self : str , a_ : np.ndarray , a_ : Dict[str, int] , a_ : PILImageResampling = PIL.Image.BILINEAR , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : List[str] , )-> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = get_size_dict(a_ , default_to_square=a_ ) if "shortest_edge" not in size: raise ValueError(F'''The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_resize_output_image_size(a_ , size=size['shortest_edge'] , default_to_square=a_ ) return resize(a_ , size=a_ , resample=a_ , data_format=a_ , **a_ ) def __lowercase( self : int , a_ : np.ndarray , a_ : Dict[str, int] , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : List[Any] , )-> np.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = get_size_dict(a_ ) if "height" not in size or "width" not in size: raise ValueError(F'''The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}''' ) return center_crop(a_ , size=(size['height'], size['width']) , data_format=a_ , **a_ ) def __lowercase( self : Optional[int] , a_ : np.ndarray , a_ : Union[int, float] , a_ : Optional[Union[str, ChannelDimension]] = None , **a_ : List[Any] , )-> Tuple: """simple docstring""" return rescale(a_ , scale=a_ , data_format=a_ , **a_ ) def __lowercase( self : str , a_ : np.ndarray , a_ : Optional[Union[str, ChannelDimension]] = None )-> np.ndarray: """simple docstring""" return flip_channel_order(a_ , data_format=a_ ) def __lowercase( self : List[Any] , a_ : ImageInput , a_ : bool = None , a_ : Dict[str, int] = None , a_ : PILImageResampling = None , a_ : bool = None , a_ : float = None , a_ : bool = None , a_ : Dict[str, int] = None , a_ : bool = None , a_ : Optional[Union[str, TensorType]] = None , a_ : ChannelDimension = ChannelDimension.FIRST , **a_ : Union[str, Any] , )-> PIL.Image.Image: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE__ : List[Any] = resample if resample is not None else self.resample SCREAMING_SNAKE_CASE__ : List[str] = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE__ : Dict = rescale_factor if rescale_factor is not None else self.rescale_factor SCREAMING_SNAKE_CASE__ : Optional[int] = do_center_crop if do_center_crop is not None else self.do_center_crop SCREAMING_SNAKE_CASE__ : Tuple = ( do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order ) SCREAMING_SNAKE_CASE__ : Dict = size if size is not None else self.size SCREAMING_SNAKE_CASE__ : Optional[int] = get_size_dict(a_ , default_to_square=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = crop_size if crop_size is not None else self.crop_size SCREAMING_SNAKE_CASE__ : Optional[int] = get_size_dict(a_ , param_name='crop_size' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = make_list_of_images(a_ ) if not valid_images(a_ ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None: raise ValueError('Size must be specified if do_resize is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE__ : Tuple = [to_numpy_array(a_ ) for image in images] if do_resize: SCREAMING_SNAKE_CASE__ : Optional[int] = [self.resize(image=a_ , size=a_ , resample=a_ ) for image in images] if do_center_crop: SCREAMING_SNAKE_CASE__ : Tuple = [self.center_crop(image=a_ , size=a_ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE__ : List[Any] = [self.rescale(image=a_ , scale=a_ ) for image in images] # the pretrained checkpoints assume images are BGR, not RGB if do_flip_channel_order: SCREAMING_SNAKE_CASE__ : str = [self.flip_channel_order(image=a_ ) for image in images] SCREAMING_SNAKE_CASE__ : List[str] = [to_channel_dimension_format(a_ , a_ ) for image in images] SCREAMING_SNAKE_CASE__ : Tuple = {'pixel_values': images} return BatchFeature(data=a_ , tensor_type=a_ ) def __lowercase( self : List[Any] , a_ : Optional[Any] , a_ : List[Tuple] = None )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = outputs.logits # Resize logits and compute semantic segmentation maps if target_sizes is not None: if len(a_ ) != len(a_ ): raise ValueError( 'Make sure that you pass in as many target sizes as the batch dimension of the logits' ) if is_torch_tensor(a_ ): SCREAMING_SNAKE_CASE__ : Optional[int] = target_sizes.numpy() SCREAMING_SNAKE_CASE__ : Dict = [] for idx in range(len(a_ ) ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.nn.functional.interpolate( logits[idx].unsqueeze(dim=0 ) , size=target_sizes[idx] , mode='bilinear' , align_corners=a_ ) SCREAMING_SNAKE_CASE__ : str = resized_logits[0].argmax(dim=0 ) semantic_segmentation.append(a_ ) else: SCREAMING_SNAKE_CASE__ : List[str] = logits.argmax(dim=1 ) SCREAMING_SNAKE_CASE__ : str = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0] )] return semantic_segmentation
720
import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def _a ( lowercase__ : int ): '''simple docstring''' if is_torch_version('<' , '2.0.0' ) or not hasattr(lowercase__ , '_dynamo' ): return False return isinstance(lowercase__ , torch._dynamo.eval_frame.OptimizedModule ) def _a ( lowercase__ : Optional[Any] , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) SCREAMING_SNAKE_CASE__ : Dict = is_compiled_module(lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : Tuple = model SCREAMING_SNAKE_CASE__ : int = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : Any = model.module if not keep_fpaa_wrapper: SCREAMING_SNAKE_CASE__ : List[Any] = getattr(lowercase__ , 'forward' ) SCREAMING_SNAKE_CASE__ : str = model.__dict__.pop('_original_forward' , lowercase__ ) if original_forward is not None: while hasattr(lowercase__ , '__wrapped__' ): SCREAMING_SNAKE_CASE__ : Dict = forward.__wrapped__ if forward == original_forward: break SCREAMING_SNAKE_CASE__ : Dict = forward if getattr(lowercase__ , '_converted_to_transformer_engine' , lowercase__ ): convert_model(lowercase__ , to_transformer_engine=lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : List[Any] = model SCREAMING_SNAKE_CASE__ : Optional[Any] = compiled_model return model def _a ( ): '''simple docstring''' PartialState().wait_for_everyone() def _a ( lowercase__ : str , lowercase__ : Optional[Any] ): '''simple docstring''' if PartialState().distributed_type == DistributedType.TPU: xm.save(lowercase__ , lowercase__ ) elif PartialState().local_process_index == 0: torch.save(lowercase__ , lowercase__ ) @contextmanager def _a ( **lowercase__ : str ): '''simple docstring''' for key, value in kwargs.items(): SCREAMING_SNAKE_CASE__ : int = str(lowercase__ ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if not hasattr(lowercase__ , '__qualname__' ) and not hasattr(lowercase__ , '__name__' ): SCREAMING_SNAKE_CASE__ : Any = getattr(lowercase__ , '__class__' , lowercase__ ) if hasattr(lowercase__ , '__qualname__' ): return obj.__qualname__ if hasattr(lowercase__ , '__name__' ): return obj.__name__ return str(lowercase__ ) def _a ( lowercase__ : List[str] , lowercase__ : List[Any] ): '''simple docstring''' for key, value in source.items(): if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : List[str] = destination.setdefault(lowercase__ , {} ) merge_dicts(lowercase__ , lowercase__ ) else: SCREAMING_SNAKE_CASE__ : List[Any] = value return destination def _a ( lowercase__ : int = None ): '''simple docstring''' if port is None: SCREAMING_SNAKE_CASE__ : int = 2_95_00 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(('localhost', port) ) == 0
636
0
import os from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch from torch import nn from ...models.controlnet import ControlNetModel, ControlNetOutput from ...models.modeling_utils import ModelMixin from ...utils import logging SCREAMING_SNAKE_CASE__ : List[str] = logging.get_logger(__name__) class snake_case ( UpperCamelCase_ ): def __init__( self : Optional[int] , a_ : Union[List[ControlNetModel], Tuple[ControlNetModel]] )-> int: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : List[str] = nn.ModuleList(a_ ) def __lowercase( self : Tuple , a_ : torch.FloatTensor , a_ : Union[torch.Tensor, float, int] , a_ : torch.Tensor , a_ : List[torch.tensor] , a_ : List[float] , a_ : Optional[torch.Tensor] = None , a_ : Optional[torch.Tensor] = None , a_ : Optional[torch.Tensor] = None , a_ : Optional[Dict[str, Any]] = None , a_ : bool = False , a_ : bool = True , )-> Union[ControlNetOutput, Tuple]: """simple docstring""" for i, (image, scale, controlnet) in enumerate(zip(a_ , a_ , self.nets ) ): SCREAMING_SNAKE_CASE__ : str = controlnet( a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , a_ , ) # merge samples if i == 0: SCREAMING_SNAKE_CASE__ : Optional[int] = down_samples, mid_sample else: SCREAMING_SNAKE_CASE__ : List[str] = [ samples_prev + samples_curr for samples_prev, samples_curr in zip(a_ , a_ ) ] mid_block_res_sample += mid_sample return down_block_res_samples, mid_block_res_sample def __lowercase( self : Optional[Any] , a_ : Union[str, os.PathLike] , a_ : bool = True , a_ : Callable = None , a_ : bool = False , a_ : Optional[str] = None , )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = 0 SCREAMING_SNAKE_CASE__ : int = save_directory for controlnet in self.nets: controlnet.save_pretrained( a_ , is_main_process=a_ , save_function=a_ , safe_serialization=a_ , variant=a_ , ) idx += 1 SCREAMING_SNAKE_CASE__ : List[str] = model_path_to_save + F'''_{idx}''' @classmethod def __lowercase( cls : str , a_ : Optional[Union[str, os.PathLike]] , **a_ : Optional[int] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : List[str] = [] # load controlnet and append to list until no controlnet directory exists anymore # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained` # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ... SCREAMING_SNAKE_CASE__ : Union[str, Any] = pretrained_model_path while os.path.isdir(a_ ): SCREAMING_SNAKE_CASE__ : Optional[Any] = ControlNetModel.from_pretrained(a_ , **a_ ) controlnets.append(a_ ) idx += 1 SCREAMING_SNAKE_CASE__ : Tuple = pretrained_model_path + F'''_{idx}''' logger.info(F'''{len(a_ )} controlnets loaded from {pretrained_model_path}.''' ) if len(a_ ) == 0: raise ValueError( F'''No ControlNets found under {os.path.dirname(a_ )}. Expected at least {pretrained_model_path + '_0'}.''' ) return cls(a_ )
721
from __future__ import annotations def _a ( lowercase__ : list[int | float] , lowercase__ : int , lowercase__ : int ): '''simple docstring''' if len(lowercase__ ) == 0: raise ValueError('find_max() arg is an empty sequence' ) if ( left >= len(lowercase__ ) or left < -len(lowercase__ ) or right >= len(lowercase__ ) or right < -len(lowercase__ ) ): raise IndexError('list index out of range' ) if left == right: return nums[left] SCREAMING_SNAKE_CASE__ : Union[str, Any] = (left + right) >> 1 # the middle SCREAMING_SNAKE_CASE__ : int = find_max(lowercase__ , lowercase__ , lowercase__ ) # find max in range[left, mid] SCREAMING_SNAKE_CASE__ : Tuple = find_max(lowercase__ , mid + 1 , lowercase__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
636
0
import pickle import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, XLMRobertaTokenizer, XLMRobertaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE__ : str = get_tests_dir("fixtures/test_sentencepiece.model") @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = XLMRobertaTokenizer lowercase_ = XLMRobertaTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Any )-> str: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Tuple = XLMRobertaTokenizer(a_ , keep_accents=a_ ) tokenizer.save_pretrained(self.tmpdirname ) def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = '<pad>' SCREAMING_SNAKE_CASE__ : Dict = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : int )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(a_ ) , 1002 ) def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1002 ) def __lowercase( self : Any )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = XLMRobertaTokenizer(a_ , keep_accents=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer.tokenize('This is a test' ) self.assertListEqual(a_ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(a_ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( a_ , [ 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', 'é', '.', ] , ) SCREAMING_SNAKE_CASE__ : int = tokenizer.convert_tokens_to_ids(a_ ) self.assertListEqual( a_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] # ^ unk: 2 + 1 = 3 unk: 2 + 1 = 3 ^ ] , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer.convert_ids_to_tokens(a_ ) self.assertListEqual( a_ , [ 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 __lowercase( self : Tuple )-> Optional[int]: """simple docstring""" if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return SCREAMING_SNAKE_CASE__ : Union[str, Any] = (self.rust_tokenizer_class, 'hf-internal-testing/tiny-xlm-roberta', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.rust_tokenizer_class.from_pretrained(a_ , **a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.tokenizer_class.from_pretrained(a_ , **a_ ) SCREAMING_SNAKE_CASE__ : List[str] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Any = tokenizer_r.save_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer_p.save_pretrained(a_ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) SCREAMING_SNAKE_CASE__ : List[str] = tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(a_ , a_ ) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer_r.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer_p.from_pretrained(a_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(a_ , a_ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(a_ ) # Save tokenizer rust, legacy_format=True SCREAMING_SNAKE_CASE__ : Tuple = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Any = tokenizer_r.save_pretrained(a_ , legacy_format=a_ ) SCREAMING_SNAKE_CASE__ : str = tokenizer_p.save_pretrained(a_ ) # Checks it save with the same files self.assertSequenceEqual(a_ , a_ ) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer_r.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : int = tokenizer_p.from_pretrained(a_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(a_ , a_ ) ) shutil.rmtree(a_ ) # Save tokenizer rust, legacy_format=False SCREAMING_SNAKE_CASE__ : Tuple = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer_r.save_pretrained(a_ , legacy_format=a_ ) SCREAMING_SNAKE_CASE__ : int = tokenizer_p.save_pretrained(a_ ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer_r.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer_p.from_pretrained(a_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(a_ , a_ ) ) shutil.rmtree(a_ ) @cached_property def __lowercase( self : Optional[int] )-> Union[str, Any]: """simple docstring""" return XLMRobertaTokenizer.from_pretrained('xlm-roberta-base' ) def __lowercase( self : int )-> Optional[int]: """simple docstring""" with tempfile.NamedTemporaryFile() as f: shutil.copyfile(a_ , f.name ) SCREAMING_SNAKE_CASE__ : int = XLMRobertaTokenizer(f.name , keep_accents=a_ ) SCREAMING_SNAKE_CASE__ : Dict = pickle.dumps(a_ ) pickle.loads(a_ ) def __lowercase( self : Union[str, Any] )-> Dict: """simple docstring""" if not self.test_rust_tokenizer: return SCREAMING_SNAKE_CASE__ : int = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : List[Any] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : List[Any] = 'I was born in 92000, and this is falsé.' SCREAMING_SNAKE_CASE__ : int = tokenizer.tokenize(a_ ) SCREAMING_SNAKE_CASE__ : int = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer.encode(a_ , add_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : int = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.encode(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) @slow def __lowercase( self : int )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 'Hello World!' SCREAMING_SNAKE_CASE__ : List[Any] = [0, 3_5378, 6661, 38, 2] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(a_ , self.big_tokenizer.encode(a_ ) ) @slow def __lowercase( self : List[str] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = ( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth' ) SCREAMING_SNAKE_CASE__ : List[str] = [ 0, 3293, 83, 10, 4552, 4989, 7986, 678, 10, 5915, 111, 17_9459, 12_4850, 4, 6044, 237, 12, 6, 5, 6, 4, 6780, 705, 15, 1388, 44, 378, 1_0114, 711, 152, 20, 6, 5, 2_2376, 642, 1221, 1_5190, 3_4153, 450, 5608, 959, 1119, 5_7702, 136, 186, 47, 1098, 2_9367, 47, # 4426, # What fairseq tokenizes from "<unk>": "_<" # 3678, # What fairseq tokenizes from "<unk>": "unk" # 2740, # What fairseq tokenizes from "<unk>": ">" 3, # What we tokenize from "<unk>": "<unk>" 6, # Residue from the tokenization: an extra sentencepiece underline 4, 6044, 237, 6284, 5_0901, 528, 31, 90, 34, 927, 2, ] # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.large has same tokenizer # xlmr.eval() # xlmr.encode(symbols) self.assertListEqual(a_ , self.big_tokenizer.encode(a_ ) ) @slow def __lowercase( self : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = {'input_ids': [[0, 1_1062, 8_2772, 7, 15, 8_2772, 538, 5_1529, 237, 1_7198, 1290, 206, 9, 21_5175, 1314, 136, 1_7198, 1290, 206, 9, 5_6359, 42, 12_2009, 9, 1_6466, 16, 8_7344, 4537, 9, 4717, 7_8381, 6, 15_9958, 7, 15, 2_4480, 618, 4, 527, 2_2693, 5428, 4, 2777, 2_4480, 9874, 4, 4_3523, 594, 4, 803, 1_8392, 3_3189, 18, 4, 4_3523, 2_4447, 1_2399, 100, 2_4955, 8_3658, 9626, 14_4057, 15, 839, 2_2335, 16, 136, 2_4955, 8_3658, 8_3479, 15, 3_9102, 724, 16, 678, 645, 2789, 1328, 4589, 42, 12_2009, 11_5774, 23, 805, 1328, 4_6876, 7, 136, 5_3894, 1940, 4_2227, 4_1159, 1_7721, 823, 425, 4, 2_7512, 9_8722, 206, 136, 5531, 4970, 919, 1_7336, 5, 2], [0, 2_0080, 618, 83, 8_2775, 47, 479, 9, 1517, 73, 5_3894, 333, 8_0581, 11_0117, 1_8811, 5256, 1295, 51, 15_2526, 297, 7986, 390, 12_4416, 538, 3_5431, 214, 98, 1_5044, 2_5737, 136, 7108, 4_3701, 23, 756, 13_5355, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 581, 6_3773, 11_9455, 6, 14_7797, 8_8203, 7, 645, 70, 21, 3285, 1_0269, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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], [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]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a_ , model_name='xlm-roberta-base' , revision='d9d8a8ea5eb94b1c6654ae9249df7793cd2933d3' , )
700
# Copyright 2023 The HuggingFace 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 torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def _a ( lowercase__ : Any ): '''simple docstring''' return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def _a ( lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = gather(lowercase__ ) assert gathered_tensor.tolist() == list(range(1 , state.num_processes**2 + 1 ) ) def _a ( lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [state.process_index] SCREAMING_SNAKE_CASE__ : Any = gather_object(lowercase__ ) assert len(lowercase__ ) == state.num_processes, f'''{gathered_obj}, {len(lowercase__ )} != {state.num_processes}''' assert gathered_obj == list(range(state.num_processes ) ), f'''{gathered_obj} != {list(range(state.num_processes ) )}''' def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = broadcast(lowercase__ ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 , state.num_processes + 1 ) ) def _a ( lowercase__ : int ): '''simple docstring''' if state.is_main_process: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.arange(state.num_processes + 1 ).to(state.device ) else: SCREAMING_SNAKE_CASE__ : List[Any] = torch.arange(state.num_processes ).to(state.device ) SCREAMING_SNAKE_CASE__ : Any = pad_across_processes(lowercase__ ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0 , state.num_processes ) ) + [0] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : List[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = reduce(lowercase__ , 'sum' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : Any = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = reduce(lowercase__ , 'mean' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' main() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = PartialState() state.print(f'''State: {state}''' ) state.print('testing gather' ) test_gather(lowercase__ ) state.print('testing gather_object' ) test_gather_object(lowercase__ ) state.print('testing broadcast' ) test_broadcast(lowercase__ ) state.print('testing pad_across_processes' ) test_pad_across_processes(lowercase__ ) state.print('testing reduce_sum' ) test_reduce_sum(lowercase__ ) state.print('testing reduce_mean' ) test_reduce_mean(lowercase__ ) if __name__ == "__main__": main()
636
0
def _a ( lowercase__ : int , lowercase__ : int ) -> Tuple: '''simple docstring''' if a < 0 or b < 0: raise ValueError('the value of both inputs must be positive' ) SCREAMING_SNAKE_CASE__ : int = str(bin(lowercase__ ) )[2:] # remove the leading "0b" SCREAMING_SNAKE_CASE__ : Union[str, Any] = str(bin(lowercase__ ) )[2:] SCREAMING_SNAKE_CASE__ : List[Any] = max(len(lowercase__ ) , len(lowercase__ ) ) return "0b" + "".join( str(int('1' in (char_a, char_b) ) ) for char_a, char_b in zip(a_binary.zfill(lowercase__ ) , b_binary.zfill(lowercase__ ) ) ) if __name__ == "__main__": import doctest doctest.testmod()
701
import unittest import numpy as np import requests from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: SCREAMING_SNAKE_CASE__ : Any = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[int] , a_ : Dict=7 , a_ : Any=3 , a_ : Any=18 , a_ : int=30 , a_ : int=400 , a_ : List[Any]=None , a_ : int=True , a_ : int=True , a_ : Dict=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = size if size is not None else {'height': 20, 'width': 20} SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : Any = num_channels SCREAMING_SNAKE_CASE__ : Optional[Any] = image_size SCREAMING_SNAKE_CASE__ : List[str] = min_resolution SCREAMING_SNAKE_CASE__ : Dict = max_resolution SCREAMING_SNAKE_CASE__ : List[Any] = size SCREAMING_SNAKE_CASE__ : Tuple = do_normalize SCREAMING_SNAKE_CASE__ : Optional[Any] = do_convert_rgb SCREAMING_SNAKE_CASE__ : List[str] = [512, 1024, 2048, 4096] SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size if patch_size is not None else {'height': 16, 'width': 16} def __lowercase( self : Optional[Any] )-> str: """simple docstring""" return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def __lowercase( self : Dict )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg' SCREAMING_SNAKE_CASE__ : str = Image.open(requests.get(a_ , stream=a_ ).raw ).convert('RGB' ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PixaStructImageProcessor if is_vision_available() else None def __lowercase( self : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = PixaStructImageProcessingTester(self ) @property def __lowercase( self : Dict )-> Tuple: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , 'do_normalize' ) ) self.assertTrue(hasattr(a_ , 'do_convert_rgb' ) ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.image_processor_tester.prepare_dummy_image() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) SCREAMING_SNAKE_CASE__ : List[Any] = 2048 SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(a_ , return_tensors='pt' , max_patches=a_ ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) ) def __lowercase( self : Any )-> Tuple: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : List[str] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Tuple = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : Any )-> Any: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 SCREAMING_SNAKE_CASE__ : int = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(a_ ): SCREAMING_SNAKE_CASE__ : Dict = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches SCREAMING_SNAKE_CASE__ : List[Any] = 'Hello' SCREAMING_SNAKE_CASE__ : List[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ , header_text=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Any = image_processor( a_ , return_tensors='pt' , max_patches=a_ , header_text=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , numpify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , np.ndarray ) SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : str = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : int = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , torchify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE__ : Any = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PixaStructImageProcessor if is_vision_available() else None def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = PixaStructImageProcessingTester(self , num_channels=4 ) SCREAMING_SNAKE_CASE__ : Dict = 3 @property def __lowercase( self : Any )-> Any: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowercase( self : Dict )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , 'do_normalize' ) ) self.assertTrue(hasattr(a_ , 'do_convert_rgb' ) ) def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : Dict = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Tuple = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
636
0
import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "RUCAIBox/mvp": "https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json", } class snake_case ( UpperCamelCase_ ): lowercase_ = 'mvp' lowercase_ = ['past_key_values'] lowercase_ = {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'} def __init__( self : List[Any] , a_ : Dict=5_0267 , a_ : Tuple=1024 , a_ : Dict=12 , a_ : str=4096 , a_ : List[Any]=16 , a_ : Optional[Any]=12 , a_ : Optional[int]=4096 , a_ : str=16 , a_ : int=0.0 , a_ : Dict=0.0 , a_ : List[Any]="gelu" , a_ : List[str]=1024 , a_ : Any=0.1 , a_ : List[Any]=0.0 , a_ : Dict=0.0 , a_ : Union[str, Any]=0.02 , a_ : Union[str, Any]=0.0 , a_ : Optional[Any]=False , a_ : Tuple=True , a_ : Optional[Any]=1 , a_ : Dict=0 , a_ : str=2 , a_ : Dict=True , a_ : str=2 , a_ : Optional[int]=2 , a_ : Any=False , a_ : Optional[Any]=100 , a_ : int=800 , **a_ : Union[str, Any] , )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = vocab_size SCREAMING_SNAKE_CASE__ : List[str] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[Any] = d_model SCREAMING_SNAKE_CASE__ : List[str] = encoder_ffn_dim SCREAMING_SNAKE_CASE__ : int = encoder_layers SCREAMING_SNAKE_CASE__ : Dict = encoder_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = decoder_ffn_dim SCREAMING_SNAKE_CASE__ : Union[str, Any] = decoder_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = decoder_attention_heads SCREAMING_SNAKE_CASE__ : Tuple = dropout SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_dropout SCREAMING_SNAKE_CASE__ : List[str] = activation_dropout SCREAMING_SNAKE_CASE__ : Optional[Any] = activation_function SCREAMING_SNAKE_CASE__ : List[str] = init_std SCREAMING_SNAKE_CASE__ : Optional[int] = encoder_layerdrop SCREAMING_SNAKE_CASE__ : Optional[Any] = decoder_layerdrop SCREAMING_SNAKE_CASE__ : Optional[Any] = classifier_dropout SCREAMING_SNAKE_CASE__ : List[Any] = use_cache SCREAMING_SNAKE_CASE__ : List[Any] = encoder_layers SCREAMING_SNAKE_CASE__ : List[Any] = scale_embedding # scale factor will be sqrt(d_model) if True SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_prompt SCREAMING_SNAKE_CASE__ : Any = prompt_length SCREAMING_SNAKE_CASE__ : int = prompt_mid_dim super().__init__( pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , is_encoder_decoder=a_ , decoder_start_token_id=a_ , forced_eos_token_id=a_ , **a_ , ) if self.forced_bos_token_id is None and kwargs.get('force_bos_token_to_be_generated' , a_ ): SCREAMING_SNAKE_CASE__ : Any = self.bos_token_id warnings.warn( F'''Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. ''' 'The config can simply be saved and uploaded again to be fixed.' )
702
import heapq as hq import math from collections.abc import Iterator class snake_case : def __init__( self : str , a_ : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = str(id_ ) SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} # {vertex:distance} def __lt__( self : int , a_ : Tuple )-> Union[str, Any]: """simple docstring""" return self.key < other.key def __repr__( self : Any )-> Dict: """simple docstring""" return self.id def __lowercase( self : Optional[Any] , a_ : int )-> List[str]: """simple docstring""" self.neighbors.append(a_ ) def __lowercase( self : int , a_ : int , a_ : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = weight def _a ( lowercase__ : Optional[Any] , lowercase__ : Union[str, Any] , lowercase__ : Tuple , lowercase__ : Dict ): '''simple docstring''' graph[a - 1].add_neighbor(graph[b - 1] ) graph[b - 1].add_neighbor(graph[a - 1] ) # add the edges: graph[a - 1].add_edge(graph[b - 1] , lowercase__ ) graph[b - 1].add_edge(graph[a - 1] , lowercase__ ) def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] for u in graph: SCREAMING_SNAKE_CASE__ : Dict = math.inf SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = 0 SCREAMING_SNAKE_CASE__ : int = graph[:] while q: SCREAMING_SNAKE_CASE__ : Optional[Any] = min(lowercase__ ) q.remove(lowercase__ ) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : int = u SCREAMING_SNAKE_CASE__ : Any = u.edges[v.id] for i in range(1 , len(lowercase__ ) ): a.append((int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) ) return a def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' for u in graph: SCREAMING_SNAKE_CASE__ : List[str] = math.inf SCREAMING_SNAKE_CASE__ : int = None SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : Tuple = list(lowercase__ ) hq.heapify(lowercase__ ) while h: SCREAMING_SNAKE_CASE__ : Optional[int] = hq.heappop(lowercase__ ) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : List[str] = u SCREAMING_SNAKE_CASE__ : Dict = u.edges[v.id] hq.heapify(lowercase__ ) for i in range(1 , len(lowercase__ ) ): yield (int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) def _a ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
636
0
import warnings from ...utils import logging from .image_processing_videomae import VideoMAEImageProcessor SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) class snake_case ( UpperCamelCase_ ): def __init__( self : List[Any] , *a_ : Optional[int] , **a_ : Optional[Any] )-> None: """simple docstring""" warnings.warn( 'The class VideoMAEFeatureExtractor is deprecated and will be removed in version 5 of Transformers.' ' Please use VideoMAEImageProcessor instead.' , a_ , ) super().__init__(*a_ , **a_ )
703
def _a ( lowercase__ : int , lowercase__ : int ): '''simple docstring''' return int((input_a, input_a).count(0 ) != 0 ) def _a ( ): '''simple docstring''' assert nand_gate(0 , 0 ) == 1 assert nand_gate(0 , 1 ) == 1 assert nand_gate(1 , 0 ) == 1 assert nand_gate(1 , 1 ) == 0 if __name__ == "__main__": print(nand_gate(0, 0)) print(nand_gate(0, 1)) print(nand_gate(1, 0)) print(nand_gate(1, 1))
636
0
def _a ( lowercase__ : int ): '''simple docstring''' if number < 0: raise ValueError('number must not be negative' ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
704
from math import factorial, radians def _a ( lowercase__ : float , lowercase__ : int = 18 , lowercase__ : int = 10 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0) # Converting from degrees to radians SCREAMING_SNAKE_CASE__ : int = radians(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = angle_in_radians SCREAMING_SNAKE_CASE__ : Optional[int] = 3 SCREAMING_SNAKE_CASE__ : Optional[int] = -1 for _ in range(lowercase__ ): result += (b * (angle_in_radians**a)) / factorial(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(lowercase__ , lowercase__ ) if __name__ == "__main__": __import__("doctest").testmod()
636
0
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available SCREAMING_SNAKE_CASE__ : str = { "configuration_timesformer": ["TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP", "TimesformerConfig"], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : int = [ "TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST", "TimesformerModel", "TimesformerForVideoClassification", "TimesformerPreTrainedModel", ] if TYPE_CHECKING: from .configuration_timesformer import TIMESFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, TimesformerConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_timesformer import ( TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, TimesformerForVideoClassification, TimesformerModel, TimesformerPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : Union[str, Any] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
705
import math def _a ( lowercase__ : int ): '''simple docstring''' assert isinstance(lowercase__ , lowercase__ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False SCREAMING_SNAKE_CASE__ : Tuple = range(3 , int(math.sqrt(lowercase__ ) + 1 ) , 2 ) return not any(not number % i for i in odd_numbers ) def _a ( lowercase__ : List[str] , lowercase__ : Any=1 , **lowercase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = factor * value SCREAMING_SNAKE_CASE__ : Dict = value while not is_prime(lowercase__ ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1 , **lowercase__ ) return value
636
0
from __future__ import annotations def _a ( lowercase__ : int , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : list[list[int]] = [] create_all_state(1 , lowercase__ , lowercase__ , [] , lowercase__ ) return result def _a ( lowercase__ : int , lowercase__ : int , lowercase__ : int , lowercase__ : list[int] , lowercase__ : list[list[int]] , ): '''simple docstring''' if level == 0: total_list.append(current_list[:] ) return for i in range(lowercase__ , total_number - level + 2 ): current_list.append(lowercase__ ) create_all_state(i + 1 , lowercase__ , level - 1 , lowercase__ , lowercase__ ) current_list.pop() def _a ( lowercase__ : list[list[int]] ): '''simple docstring''' for i in total_list: print(*lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Union[str, Any] = 4 SCREAMING_SNAKE_CASE__ : Dict = 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = generate_all_combinations(n, k) print_all_state(total_list)
706
import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class snake_case : def __init__( self : str , a_ : List[str] , a_ : Tuple=13 , a_ : Dict=30 , a_ : Optional[int]=2 , a_ : Tuple=3 , a_ : Dict=True , a_ : int=True , a_ : Optional[Any]=32 , a_ : List[str]=5 , a_ : Any=4 , a_ : Dict=37 , a_ : Dict="gelu" , a_ : int=0.1 , a_ : Optional[Any]=0.1 , a_ : Any=10 , a_ : List[str]=0.02 , a_ : Any=3 , a_ : List[str]=None , a_ : Optional[int]=2 , )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = parent SCREAMING_SNAKE_CASE__ : int = batch_size SCREAMING_SNAKE_CASE__ : int = image_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE__ : Optional[int] = num_channels SCREAMING_SNAKE_CASE__ : int = is_training SCREAMING_SNAKE_CASE__ : List[Any] = use_labels SCREAMING_SNAKE_CASE__ : str = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = scope SCREAMING_SNAKE_CASE__ : str = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) SCREAMING_SNAKE_CASE__ : Optional[int] = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_patches + 2 def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE__ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_config() return config, pixel_values, labels def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=a_ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __lowercase( self : List[str] , a_ : List[str] , a_ : Optional[Any] , a_ : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = DeiTModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : List[str] , a_ : List[str] , a_ : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = DeiTForMaskedImageModeling(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Optional[int] = 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = DeiTForMaskedImageModeling(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : int = model(a_ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowercase( self : List[str] , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : int = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : List[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Dict = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) lowercase_ = ( { 'feature-extraction': DeiTModel, 'image-classification': (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = DeiTModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , has_text_modality=a_ , hidden_size=37 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='DeiT does not use inputs_embeds' ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" pass def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a_ , nn.Linear ) ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[str] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : int = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*a_ ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) def __lowercase( self : str , a_ : str , a_ : Tuple , a_ : Union[str, Any]=False )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = super()._prepare_for_class(a_ , a_ , return_labels=a_ ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[Any] = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(a_ ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE__ : Tuple = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : List[Any] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = True for model_class in self.all_model_classes: if model_class in get_values(a_ ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) model.gradient_checkpointing_enable() model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[str] = [ {'title': 'multi_label_classification', 'num_labels': 2, 'dtype': torch.float}, {'title': 'single_label_classification', 'num_labels': 1, 'dtype': torch.long}, {'title': 'regression', 'num_labels': 1, 'dtype': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(a_ ), *get_values(a_ ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'''Testing {model_class} with {problem_type['title']}''' ): SCREAMING_SNAKE_CASE__ : int = problem_type['title'] SCREAMING_SNAKE_CASE__ : Tuple = problem_type['num_labels'] SCREAMING_SNAKE_CASE__ : str = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs['labels'].unsqueeze(1 ).repeat(1 , problem_type['num_labels'] ) SCREAMING_SNAKE_CASE__ : Any = inputs['labels'].to(problem_type['dtype'] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=a_ ) as warning_list: SCREAMING_SNAKE_CASE__ : str = model(**a_ ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( F'''Something is going wrong in the regression problem: intercepted {w.message}''' ) loss.backward() @slow def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = DeiTModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : int )-> Dict: """simple docstring""" return ( DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224' ) if is_vision_available() else None ) @slow def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = DeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224' ).to( a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : List[Any] = prepare_img() SCREAMING_SNAKE_CASE__ : List[str] = image_processor(images=a_ , return_tensors='pt' ).to(a_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(**a_ ) # verify the logits SCREAMING_SNAKE_CASE__ : int = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor([-1.0266, 0.1912, -1.2861] ).to(a_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a_ , atol=1e-4 ) ) @slow @require_accelerate @require_torch_gpu def __lowercase( self : Tuple )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = DeiTModel.from_pretrained( 'facebook/deit-base-distilled-patch16-224' , torch_dtype=torch.floataa , device_map='auto' ) SCREAMING_SNAKE_CASE__ : Dict = self.default_image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = prepare_img() SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(images=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = inputs.pixel_values.to(a_ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ )
636
0
import json import os from typing import Optional import numpy as np from ...feature_extraction_utils import BatchFeature from ...processing_utils import ProcessorMixin from ...utils import logging from ...utils.hub import get_file_from_repo from ..auto import AutoTokenizer SCREAMING_SNAKE_CASE__ : Union[str, Any] = logging.get_logger(__name__) class snake_case ( UpperCamelCase_ ): lowercase_ = 'AutoTokenizer' lowercase_ = ['tokenizer'] lowercase_ = { 'semantic_prompt': 1, 'coarse_prompt': 2, 'fine_prompt': 2, } def __init__( self : Union[str, Any] , a_ : List[Any] , a_ : Dict=None )-> Any: """simple docstring""" super().__init__(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = speaker_embeddings @classmethod def __lowercase( cls : List[str] , a_ : Union[str, Any] , a_ : Any="speaker_embeddings_path.json" , **a_ : int )-> List[str]: """simple docstring""" if speaker_embeddings_dict_path is not None: SCREAMING_SNAKE_CASE__ : Dict = get_file_from_repo( a_ , a_ , subfolder=kwargs.pop('subfolder' , a_ ) , cache_dir=kwargs.pop('cache_dir' , a_ ) , force_download=kwargs.pop('force_download' , a_ ) , proxies=kwargs.pop('proxies' , a_ ) , resume_download=kwargs.pop('resume_download' , a_ ) , local_files_only=kwargs.pop('local_files_only' , a_ ) , use_auth_token=kwargs.pop('use_auth_token' , a_ ) , revision=kwargs.pop('revision' , a_ ) , ) if speaker_embeddings_path is None: logger.warning( F'''`{os.path.join(a_ , a_ )}` does not exists , no preloaded speaker embeddings will be used - Make sure to provide a correct path to the json dictionnary if wanted, otherwise set `speaker_embeddings_dict_path=None`.''' ) SCREAMING_SNAKE_CASE__ : int = None else: with open(a_ ) as speaker_embeddings_json: SCREAMING_SNAKE_CASE__ : Union[str, Any] = json.load(a_ ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = None SCREAMING_SNAKE_CASE__ : Tuple = AutoTokenizer.from_pretrained(a_ , **a_ ) return cls(tokenizer=a_ , speaker_embeddings=a_ ) def __lowercase( self : Optional[Any] , a_ : Tuple , a_ : Dict="speaker_embeddings_path.json" , a_ : int="speaker_embeddings" , a_ : bool = False , **a_ : Tuple , )-> Optional[Any]: """simple docstring""" if self.speaker_embeddings is not None: os.makedirs(os.path.join(a_ , a_ , 'v2' ) , exist_ok=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = {} SCREAMING_SNAKE_CASE__ : List[Any] = save_directory for prompt_key in self.speaker_embeddings: if prompt_key != "repo_or_path": SCREAMING_SNAKE_CASE__ : Optional[Any] = self._load_voice_preset(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = {} for key in self.speaker_embeddings[prompt_key]: np.save( os.path.join( embeddings_dict['repo_or_path'] , a_ , F'''{prompt_key}_{key}''' ) , voice_preset[key] , allow_pickle=a_ , ) SCREAMING_SNAKE_CASE__ : int = os.path.join(a_ , F'''{prompt_key}_{key}.npy''' ) SCREAMING_SNAKE_CASE__ : str = tmp_dict with open(os.path.join(a_ , a_ ) , 'w' ) as fp: json.dump(a_ , a_ ) super().save_pretrained(a_ , a_ , **a_ ) def __lowercase( self : List[Any] , a_ : str = None , **a_ : Optional[int] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.speaker_embeddings[voice_preset] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]: if key not in voice_preset_paths: raise ValueError( F'''Voice preset unrecognized, missing {key} as a key in self.speaker_embeddings[{voice_preset}].''' ) SCREAMING_SNAKE_CASE__ : Tuple = get_file_from_repo( self.speaker_embeddings.get('repo_or_path' , '/' ) , voice_preset_paths[key] , subfolder=kwargs.pop('subfolder' , a_ ) , cache_dir=kwargs.pop('cache_dir' , a_ ) , force_download=kwargs.pop('force_download' , a_ ) , proxies=kwargs.pop('proxies' , a_ ) , resume_download=kwargs.pop('resume_download' , a_ ) , local_files_only=kwargs.pop('local_files_only' , a_ ) , use_auth_token=kwargs.pop('use_auth_token' , a_ ) , revision=kwargs.pop('revision' , a_ ) , ) if path is None: raise ValueError( F'''`{os.path.join(self.speaker_embeddings.get('repo_or_path' , '/' ) , voice_preset_paths[key] )}` does not exists , no preloaded voice preset will be used - Make sure to provide correct paths to the {voice_preset} embeddings.''' ) SCREAMING_SNAKE_CASE__ : Tuple = np.load(a_ ) return voice_preset_dict def __lowercase( self : List[Any] , a_ : Optional[dict] = None )-> List[str]: """simple docstring""" for key in ["semantic_prompt", "coarse_prompt", "fine_prompt"]: if key not in voice_preset: raise ValueError(F'''Voice preset unrecognized, missing {key} as a key.''' ) if not isinstance(voice_preset[key] , np.ndarray ): raise ValueError(F'''{key} voice preset must be a {str(self.preset_shape[key] )}D ndarray.''' ) if len(voice_preset[key].shape ) != self.preset_shape[key]: raise ValueError(F'''{key} voice preset must be a {str(self.preset_shape[key] )}D ndarray.''' ) def __call__( self : Optional[Any] , a_ : Dict=None , a_ : Optional[Any]=None , a_ : Tuple="pt" , a_ : Union[str, Any]=256 , a_ : str=False , a_ : List[Any]=True , a_ : int=False , **a_ : List[str] , )-> Optional[Any]: """simple docstring""" if voice_preset is not None and not isinstance(a_ , a_ ): if ( isinstance(a_ , a_ ) and self.speaker_embeddings is not None and voice_preset in self.speaker_embeddings ): SCREAMING_SNAKE_CASE__ : int = self._load_voice_preset(a_ ) else: if isinstance(a_ , a_ ) and not voice_preset.endswith('.npz' ): SCREAMING_SNAKE_CASE__ : int = voice_preset + '.npz' SCREAMING_SNAKE_CASE__ : Tuple = np.load(a_ ) if voice_preset is not None: self._validate_voice_preset_dict(a_ , **a_ ) SCREAMING_SNAKE_CASE__ : str = BatchFeature(data=a_ , tensor_type=a_ ) SCREAMING_SNAKE_CASE__ : Any = self.tokenizer( a_ , return_tensors=a_ , padding='max_length' , max_length=a_ , return_attention_mask=a_ , return_token_type_ids=a_ , add_special_tokens=a_ , **a_ , ) if voice_preset is not None: SCREAMING_SNAKE_CASE__ : Dict = voice_preset return encoded_text
707
import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case : def __init__( self : List[Any] , a_ : Dict , a_ : Any=13 , a_ : Any=7 , a_ : Tuple=True , a_ : Tuple=True , a_ : Optional[int]=False , a_ : Dict=True , a_ : Optional[Any]=99 , a_ : Any=32 , a_ : Dict=5 , a_ : Tuple=4 , a_ : List[str]=37 , a_ : Union[str, Any]="gelu" , a_ : Dict=0.1 , a_ : Tuple=0.1 , a_ : List[str]=512 , a_ : List[str]=16 , a_ : List[str]=2 , a_ : Optional[int]=0.02 , a_ : List[str]=3 , a_ : Union[str, Any]=4 , a_ : Optional[Any]=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Dict = batch_size SCREAMING_SNAKE_CASE__ : Dict = seq_length SCREAMING_SNAKE_CASE__ : Optional[Any] = is_training SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_input_mask SCREAMING_SNAKE_CASE__ : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : Any = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = initializer_range SCREAMING_SNAKE_CASE__ : List[Any] = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : str = scope def __lowercase( self : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Tuple = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : str = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : List[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase( self : Dict )-> Tuple: """simple docstring""" return BioGptConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a_ , initializer_range=self.initializer_range , ) def __lowercase( self : Any , a_ : str , a_ : Tuple , a_ : Dict , a_ : Optional[int] , a_ : List[Any] , a_ : Union[str, Any] , a_ : Tuple )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = BioGptModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : Union[str, Any] , a_ : Optional[int] , a_ : Tuple , a_ : Optional[Any] , a_ : int , a_ : Optional[int] , a_ : int , a_ : str , a_ : Optional[Any] , )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = BioGptForCausalLM(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowercase( self : Tuple , a_ : Optional[int] , a_ : Union[str, Any] , a_ : Any , a_ : Any , a_ : Optional[int] , *a_ : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(config=a_ ) model.to(a_ ) model.eval() # create attention mask SCREAMING_SNAKE_CASE__ : Any = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.seq_length // 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 # first forward pass SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ).to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids SCREAMING_SNAKE_CASE__ : str = ids_tensor((1,) , a_ ).item() + 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = random_other_next_tokens # append to next input_ids and attn_mask SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Dict = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=a_ )] , dim=1 , ) # get two different outputs SCREAMING_SNAKE_CASE__ : str = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , past_key_values=a_ , attention_mask=a_ )['last_hidden_state'] # select random slice SCREAMING_SNAKE_CASE__ : Any = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : List[str] = output_from_no_past[:, -1, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : List[str] = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : str , a_ : List[Any] , a_ : str , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Optional[Any] , *a_ : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel(config=a_ ).to(a_ ).eval() SCREAMING_SNAKE_CASE__ : Dict = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) # first forward pass SCREAMING_SNAKE_CASE__ : Any = model(a_ , attention_mask=a_ , use_cache=a_ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : int = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) SCREAMING_SNAKE_CASE__ : int = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , attention_mask=a_ , past_key_values=a_ )[ 'last_hidden_state' ] # select random slice SCREAMING_SNAKE_CASE__ : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : Any = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : Optional[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Any , a_ : List[str] , a_ : Optional[int] , a_ : Any , a_ : Tuple , a_ : Any , *a_ : List[Any] , a_ : Union[str, Any]=False )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = BioGptForCausalLM(a_ ) model.to(a_ ) if gradient_checkpointing: model.gradient_checkpointing_enable() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , labels=a_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def __lowercase( self : Union[str, Any] , a_ : List[str] , *a_ : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def __lowercase( self : Dict , a_ : Tuple , a_ : Tuple , a_ : List[str] , a_ : Any , a_ : str , *a_ : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.num_labels SCREAMING_SNAKE_CASE__ : str = BioGptForTokenClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ , attention_mask=a_ , token_type_ids=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowercase( self : Any )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) lowercase_ = (BioGptForCausalLM,) if is_torch_available() else () lowercase_ = ( { 'feature-extraction': BioGptModel, 'text-classification': BioGptForSequenceClassification, 'text-generation': BioGptForCausalLM, 'token-classification': BioGptForTokenClassification, 'zero-shot': BioGptForSequenceClassification, } if is_torch_available() else {} ) lowercase_ = False def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , hidden_size=37 ) def __lowercase( self : Tuple )-> int: """simple docstring""" self.config_tester.run_common_tests() def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : Union[str, Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE__ : List[str] = type self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : int )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*a_ ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*a_ , gradient_checkpointing=a_ ) def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*a_ ) def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*a_ ) def __lowercase( self : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*a_ ) @slow def __lowercase( self : List[str] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = 'left' # Define PAD Token = EOS Token = 50256 SCREAMING_SNAKE_CASE__ : Any = tokenizer.eos_token SCREAMING_SNAKE_CASE__ : Tuple = model.config.eos_token_id # use different length sentences to test batching SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ 'Hello, my dog is a little', 'Today, I', ] SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer(a_ , return_tensors='pt' , padding=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = inputs['input_ids'].to(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = model.generate( input_ids=a_ , attention_mask=inputs['attention_mask'].to(a_ ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer(sentences[0] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = model.generate(input_ids=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = inputs_non_padded.shape[-1] - inputs['attention_mask'][-1].long().sum().cpu().item() SCREAMING_SNAKE_CASE__ : Dict = tokenizer(sentences[1] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.generate(input_ids=a_ , max_length=model.config.max_length - num_paddings ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.batch_decode(a_ , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.decode(output_non_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = [ 'Hello, my dog is a little bit bigger than a little bit.', 'Today, I have a good idea of how to use the information', ] self.assertListEqual(a_ , a_ ) self.assertListEqual(a_ , [non_padded_sentence, padded_sentence] ) @slow def __lowercase( self : Any )-> List[Any]: """simple docstring""" for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] = 3 SCREAMING_SNAKE_CASE__ : List[Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : int = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : str = 3 SCREAMING_SNAKE_CASE__ : Any = 'multi_label_classification' SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Any = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class snake_case ( unittest.TestCase ): @slow def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([[2, 4805, 9, 656, 21]] ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ )[0] SCREAMING_SNAKE_CASE__ : List[str] = 4_2384 SCREAMING_SNAKE_CASE__ : Dict = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , a_ ) SCREAMING_SNAKE_CASE__ : int = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , a_ , atol=1e-4 ) ) @slow def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer('COVID-19 is' , return_tensors='pt' ).to(a_ ) SCREAMING_SNAKE_CASE__ : int = model.generate( **a_ , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=a_ , ) SCREAMING_SNAKE_CASE__ : int = tokenizer.decode(output_ids[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( 'COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the' ' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and' ' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),' ' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and' ' more than 800,000 deaths.' ) self.assertEqual(a_ , a_ )
636
0
import unittest from transformers import AutoTokenizer, NystromformerConfig, 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, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, NystromformerModel, ) from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case : def __init__( self : List[str] , a_ : Optional[Any] , a_ : Union[str, Any]=13 , a_ : str=7 , a_ : List[str]=True , a_ : Tuple=True , a_ : str=True , a_ : Optional[Any]=True , a_ : List[str]=99 , a_ : List[str]=32 , a_ : Tuple=5 , a_ : Optional[int]=4 , a_ : List[Any]=37 , a_ : Any="gelu" , a_ : int=0.1 , a_ : str=0.1 , a_ : Optional[Any]=512 , a_ : Dict=16 , a_ : Tuple=2 , a_ : List[Any]=0.02 , a_ : Optional[int]=3 , a_ : List[str]=4 , a_ : List[str]=None , )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = parent SCREAMING_SNAKE_CASE__ : str = batch_size SCREAMING_SNAKE_CASE__ : int = seq_length SCREAMING_SNAKE_CASE__ : str = is_training SCREAMING_SNAKE_CASE__ : List[str] = use_input_mask SCREAMING_SNAKE_CASE__ : int = use_token_type_ids SCREAMING_SNAKE_CASE__ : str = use_labels SCREAMING_SNAKE_CASE__ : Any = vocab_size SCREAMING_SNAKE_CASE__ : int = hidden_size SCREAMING_SNAKE_CASE__ : Dict = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Union[str, Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Any = max_position_embeddings SCREAMING_SNAKE_CASE__ : List[str] = type_vocab_size SCREAMING_SNAKE_CASE__ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Any = initializer_range SCREAMING_SNAKE_CASE__ : int = num_labels SCREAMING_SNAKE_CASE__ : List[Any] = num_choices SCREAMING_SNAKE_CASE__ : Dict = scope def __lowercase( self : int )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : str = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : Dict = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Optional[int] = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Any = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : List[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" return NystromformerConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a_ , initializer_range=self.initializer_range , ) def __lowercase( self : int , a_ : str , a_ : Any , a_ : Dict , a_ : Tuple , a_ : List[str] , a_ : int , a_ : str )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = NystromformerModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : int = model(a_ , attention_mask=a_ , token_type_ids=a_ ) SCREAMING_SNAKE_CASE__ : str = model(a_ , token_type_ids=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : Union[str, Any] , a_ : int , a_ : Optional[int] , a_ : List[Any] , a_ : Union[str, Any] , a_ : Any , a_ : Any , a_ : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = NystromformerForMaskedLM(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : str = model(a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowercase( self : Dict , a_ : int , a_ : List[str] , a_ : Any , a_ : Union[str, Any] , a_ : str , a_ : int , a_ : Optional[int] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = NystromformerForQuestionAnswering(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] = model( a_ , attention_mask=a_ , token_type_ids=a_ , start_positions=a_ , end_positions=a_ , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def __lowercase( self : Dict , a_ : int , a_ : Tuple , a_ : int , a_ : Tuple , a_ : Dict , a_ : int , a_ : Optional[int] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.num_labels SCREAMING_SNAKE_CASE__ : Union[str, Any] = NystromformerForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Any = model(a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def __lowercase( self : List[Any] , a_ : List[Any] , a_ : int , a_ : List[Any] , a_ : int , a_ : Union[str, Any] , a_ : List[str] , a_ : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.num_labels SCREAMING_SNAKE_CASE__ : int = NystromformerForTokenClassification(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowercase( self : Union[str, Any] , a_ : Any , a_ : Union[str, Any] , a_ : Optional[Any] , a_ : str , a_ : Any , a_ : Dict , a_ : int )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.num_choices SCREAMING_SNAKE_CASE__ : Dict = NystromformerForMultipleChoice(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : str = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : List[str] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : Dict = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() SCREAMING_SNAKE_CASE__ : int = model( a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def __lowercase( self : Dict )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.prepare_config_and_inputs() ( SCREAMING_SNAKE_CASE__ ) : Optional[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : List[str] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( ( NystromformerModel, NystromformerForMaskedLM, NystromformerForMultipleChoice, NystromformerForQuestionAnswering, NystromformerForSequenceClassification, NystromformerForTokenClassification, ) if is_torch_available() else () ) lowercase_ = ( { 'feature-extraction': NystromformerModel, 'fill-mask': NystromformerForMaskedLM, 'question-answering': NystromformerForQuestionAnswering, 'text-classification': NystromformerForSequenceClassification, 'token-classification': NystromformerForTokenClassification, 'zero-shot': NystromformerForSequenceClassification, } if is_torch_available() else {} ) lowercase_ = False lowercase_ = False def __lowercase( self : Optional[int] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = NystromformerModelTester(self ) SCREAMING_SNAKE_CASE__ : List[str] = ConfigTester(self , config_class=a_ , hidden_size=37 ) def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" self.config_tester.run_common_tests() def __lowercase( self : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[str] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE__ : Tuple = type self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[str] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*a_ ) def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*a_ ) def __lowercase( self : Tuple )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*a_ ) def __lowercase( self : List[str] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*a_ ) def __lowercase( self : List[str] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*a_ ) @slow def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Dict = NystromformerModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) @require_torch class snake_case ( unittest.TestCase ): @slow def __lowercase( self : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = NystromformerModel.from_pretrained('uw-madison/nystromformer-512' ) SCREAMING_SNAKE_CASE__ : Dict = torch.tensor([[0, 1, 2, 3, 4, 5]] ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(a_ )[0] SCREAMING_SNAKE_CASE__ : str = torch.Size((1, 6, 768) ) self.assertEqual(output.shape , a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.tensor( [[[-0.4532, -0.0936, 0.5137], [-0.2676, 0.0628, 0.6186], [-0.3629, -0.1726, 0.4716]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , a_ , atol=1e-4 ) ) @slow def __lowercase( self : List[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = 'the [MASK] of Belgium is Brussels' SCREAMING_SNAKE_CASE__ : Optional[Any] = AutoTokenizer.from_pretrained('uw-madison/nystromformer-512' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = NystromformerForMaskedLM.from_pretrained('uw-madison/nystromformer-512' ) SCREAMING_SNAKE_CASE__ : str = tokenizer(a_ , return_tensors='pt' ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : str = model(encoding.input_ids ).logits SCREAMING_SNAKE_CASE__ : Union[str, Any] = token_logits[:, 2, :].argmax(-1 )[0] self.assertEqual(tokenizer.decode(a_ ) , 'capital' )
708
import itertools import random import unittest import numpy as np from transformers import BatchFeature, SpeechTaFeatureExtractor from transformers.testing_utils import require_torch from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : Optional[Any] = random.Random() def _a ( lowercase__ : List[str] , lowercase__ : List[Any]=1.0 , lowercase__ : Optional[int]=None , lowercase__ : List[str]=None ): '''simple docstring''' if rng is None: SCREAMING_SNAKE_CASE__ : Optional[int] = global_rng SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[Any] , a_ : Union[str, Any]=7 , a_ : Any=400 , a_ : List[Any]=2000 , a_ : Tuple=1 , a_ : Optional[int]=0.0 , a_ : Optional[Any]=1_6000 , a_ : str=True , a_ : Union[str, Any]=80 , a_ : Dict=16 , a_ : Tuple=64 , a_ : Any="hann_window" , a_ : Union[str, Any]=80 , a_ : List[Any]=7600 , a_ : Optional[Any]=1e-1_0 , a_ : Dict=True , )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = parent SCREAMING_SNAKE_CASE__ : List[Any] = batch_size SCREAMING_SNAKE_CASE__ : str = min_seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = max_seq_length SCREAMING_SNAKE_CASE__ : str = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE__ : int = feature_size SCREAMING_SNAKE_CASE__ : str = padding_value SCREAMING_SNAKE_CASE__ : Any = sampling_rate SCREAMING_SNAKE_CASE__ : Optional[int] = do_normalize SCREAMING_SNAKE_CASE__ : int = num_mel_bins SCREAMING_SNAKE_CASE__ : int = hop_length SCREAMING_SNAKE_CASE__ : str = win_length SCREAMING_SNAKE_CASE__ : Optional[Any] = win_function SCREAMING_SNAKE_CASE__ : List[str] = fmin SCREAMING_SNAKE_CASE__ : Dict = fmax SCREAMING_SNAKE_CASE__ : int = mel_floor SCREAMING_SNAKE_CASE__ : Tuple = return_attention_mask def __lowercase( self : Dict )-> Dict: """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "do_normalize": self.do_normalize, "num_mel_bins": self.num_mel_bins, "hop_length": self.hop_length, "win_length": self.win_length, "win_function": self.win_function, "fmin": self.fmin, "fmax": self.fmax, "mel_floor": self.mel_floor, "return_attention_mask": self.return_attention_mask, } def __lowercase( self : List[Any] , a_ : str=False , a_ : List[Any]=False )-> Optional[Any]: """simple docstring""" def _flatten(a_ : int ): return list(itertools.chain(*a_ ) ) if equal_length: SCREAMING_SNAKE_CASE__ : Tuple = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Optional[int] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : int = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs def __lowercase( self : Any , a_ : int=False , a_ : Any=False )-> Union[str, Any]: """simple docstring""" if equal_length: SCREAMING_SNAKE_CASE__ : str = [floats_list((self.max_seq_length, self.num_mel_bins) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Tuple = [ floats_list((x, self.num_mel_bins) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : List[str] = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs @require_torch class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = SpeechTaFeatureExtractor def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SpeechTaFeatureExtractionTester(self ) def __lowercase( self : Any , a_ : Optional[int] )-> List[str]: """simple docstring""" self.assertTrue(np.all(np.mean(a_ , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(a_ , axis=0 ) - 1 ) < 1e-3 ) ) def __lowercase( self : Tuple )-> Dict: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : str = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = [np.asarray(a_ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Dict = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Tuple = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : str = feat_extract(a_ , padding=a_ , max_length=a_ , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self.assertTrue(input_values[0][800:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self.assertTrue(input_values[0][1000:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : List[Any] = range(800 , 1400 , 200 ) SCREAMING_SNAKE_CASE__ : int = [floats_list((1, x) )[0] for x in lengths] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , max_length=a_ , padding=a_ ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : int )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='max_length' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def __lowercase( self : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : List[str] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1000) ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : str = feat_extract( a_ , truncation=a_ , max_length=2000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1200) ) def __lowercase( self : Any )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.rand(100 ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : int = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: SCREAMING_SNAKE_CASE__ : Any = feature_extractor.pad([{'input_values': inputs}] , return_tensors='np' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor.pad([{'input_values': inputs}] , return_tensors='pt' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Dict = [np.asarray(a_ ) for speech_input in speech_inputs] # Test feature size SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(audio_target=a_ , padding=a_ , return_tensors='np' ).input_values self.assertTrue(input_values.ndim == 3 ) self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins ) # Test not batched input SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : int = feature_extractor(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE__ : List[str] = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE__ : List[str] = np.asarray(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : str = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Dict )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(a_ ) == len(a_ ) for x, y in zip(a_ , processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} , tensor_type='np' ) SCREAMING_SNAKE_CASE__ : List[Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : int = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} , tensor_type='pt' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : Optional[Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : Tuple )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Dict = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : str = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : List[Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.pad(a_ , padding='longest' , return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Any = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , a_ ) def __lowercase( self : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Tuple = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : str = min(a_ ) SCREAMING_SNAKE_CASE__ : Any = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : int = feat_extract.pad( a_ , padding='max_length' , max_length=a_ , truncation=a_ , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] ) def __lowercase( self : Optional[int] , a_ : List[str] )-> Any: """simple docstring""" from datasets import load_dataset SCREAMING_SNAKE_CASE__ : int = load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation' ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE__ : List[Any] = ds.sort('id' ).select(range(a_ ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def __lowercase( self : List[str] )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor( [2.3_8_0_4e-0_3, 2.0_7_5_2e-0_3, 1.9_8_3_6e-0_3, 2.1_0_5_7e-0_3, 1.6_1_7_4e-0_3, 3.0_5_1_8e-0_4, 9.1_5_5_3e-0_5, 3.3_5_6_9e-0_4, 9.7_6_5_6e-0_4, 1.8_3_1_1e-0_3, 2.0_1_4_2e-0_3, 2.1_0_5_7e-0_3, 1.7_3_9_5e-0_3, 4.5_7_7_6e-0_4, -3.9_6_7_3e-0_4, 4.5_7_7_6e-0_4, 1.0_0_7_1e-0_3, 9.1_5_5_3e-0_5, 4.8_8_2_8e-0_4, 1.1_5_9_7e-0_3, 7.3_2_4_2e-0_4, 9.4_6_0_4e-0_4, 1.8_0_0_5e-0_3, 1.8_3_1_1e-0_3, 8.8_5_0_1e-0_4, 4.2_7_2_5e-0_4, 4.8_8_2_8e-0_4, 7.3_2_4_2e-0_4, 1.0_9_8_6e-0_3, 2.1_0_5_7e-0_3] ) # fmt: on SCREAMING_SNAKE_CASE__ : List[str] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : List[str] = feature_extractor(a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 9_3680) ) self.assertTrue(torch.allclose(input_values[0, :30] , a_ , atol=1e-6 ) ) def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor( [-2.6870, -3.0104, -3.1356, -3.5352, -3.0044, -3.0353, -3.4719, -3.6777, -3.1520, -2.9435, -2.6553, -2.8795, -2.9944, -2.5921, -3.0279, -3.0386, -3.0864, -3.1291, -3.2353, -2.7444, -2.6831, -2.7287, -3.1761, -3.1571, -3.2726, -3.0582, -3.1007, -3.4533, -3.4695, -3.0998] ) # fmt: on SCREAMING_SNAKE_CASE__ : Optional[Any] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : int = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : str = feature_extractor(audio_target=a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 366, 80) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , a_ , atol=1e-4 ) )
636
0
import re import string from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets SCREAMING_SNAKE_CASE__ : Any = "\n@inproceedings{xu-etal-2016-optimizing,\n title = {Optimizing Statistical Machine Translation for Text Simplification},\n authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris},\n journal = {Transactions of the Association for Computational Linguistics},\n volume = {4},\n year={2016},\n url = {https://www.aclweb.org/anthology/Q16-1029},\n pages = {401--415\n},\n@inproceedings{post-2018-call,\n title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n author = \"Post, Matt\",\n booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n month = oct,\n year = \"2018\",\n address = \"Belgium, Brussels\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W18-6319\",\n pages = \"186--191\",\n}\n" SCREAMING_SNAKE_CASE__ : Dict = "\\nWIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU\nIt can be used to evaluate the quality of machine-generated texts.\n" SCREAMING_SNAKE_CASE__ : int = "\nCalculates sari score (between 0 and 100) given a list of source and predicted\nsentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score.\nArgs:\n sources: list of source sentences where each sentence should be a string.\n predictions: list of predicted sentences where each sentence should be a string.\n references: list of lists of reference sentences where each sentence should be a string.\nReturns:\n sari: sari score\n sacrebleu: sacrebleu score\n exact: exact score\n\nExamples:\n >>> sources=[\"About 95 species are currently accepted .\"]\n >>> predictions=[\"About 95 you now get in .\"]\n >>> references=[[\"About 95 species are currently known .\"]]\n >>> wiki_split = datasets.load_metric(\"wiki_split\")\n >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references)\n >>> print(results)\n {'sari': 21.805555555555557, 'sacrebleu': 14.535768424205482, 'exact': 0.0}\n" def _a ( lowercase__ : str ): '''simple docstring''' def remove_articles(lowercase__ : str ): SCREAMING_SNAKE_CASE__ : str = re.compile(r'\b(a|an|the)\b' , re.UNICODE ) return re.sub(lowercase__ , ' ' , lowercase__ ) def white_space_fix(lowercase__ : Dict ): return " ".join(text.split() ) def remove_punc(lowercase__ : Any ): SCREAMING_SNAKE_CASE__ : List[Any] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(lowercase__ : List[Any] ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(lowercase__ ) ) ) ) def _a ( lowercase__ : Dict , lowercase__ : Optional[Any] ): '''simple docstring''' return int(normalize_answer(lowercase__ ) == normalize_answer(lowercase__ ) ) def _a ( lowercase__ : Optional[Any] , lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [any(compute_exact(lowercase__ , lowercase__ ) for ref in refs ) for pred, refs in zip(lowercase__ , lowercase__ )] return (sum(lowercase__ ) / len(lowercase__ )) * 1_00 def _a ( lowercase__ : Union[str, Any] , lowercase__ : int , lowercase__ : Any , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = [rgram for rgrams in rgramslist for rgram in rgrams] SCREAMING_SNAKE_CASE__ : List[Any] = Counter(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = Counter(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = Counter() for sgram, scount in sgramcounter.items(): SCREAMING_SNAKE_CASE__ : Optional[Any] = scount * numref SCREAMING_SNAKE_CASE__ : int = Counter(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = Counter() for cgram, ccount in cgramcounter.items(): SCREAMING_SNAKE_CASE__ : Dict = ccount * numref # KEEP SCREAMING_SNAKE_CASE__ : str = sgramcounter_rep & cgramcounter_rep SCREAMING_SNAKE_CASE__ : Any = keepgramcounter_rep & rgramcounter SCREAMING_SNAKE_CASE__ : Dict = sgramcounter_rep & rgramcounter SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : Dict = 0 for keepgram in keepgramcountergood_rep: keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscorea += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1 SCREAMING_SNAKE_CASE__ : List[Any] = 1 if len(lowercase__ ) > 0: SCREAMING_SNAKE_CASE__ : int = keeptmpscorea / len(lowercase__ ) if len(lowercase__ ) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) SCREAMING_SNAKE_CASE__ : Any = keeptmpscorea / sum(keepgramcounterall_rep.values() ) SCREAMING_SNAKE_CASE__ : str = 0 if keepscore_precision > 0 or keepscore_recall > 0: SCREAMING_SNAKE_CASE__ : int = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION SCREAMING_SNAKE_CASE__ : Any = sgramcounter_rep - cgramcounter_rep SCREAMING_SNAKE_CASE__ : Optional[int] = delgramcounter_rep - rgramcounter SCREAMING_SNAKE_CASE__ : int = sgramcounter_rep - rgramcounter SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 0 for delgram in delgramcountergood_rep: deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. SCREAMING_SNAKE_CASE__ : str = 1 if len(lowercase__ ) > 0: SCREAMING_SNAKE_CASE__ : int = deltmpscorea / len(lowercase__ ) # ADDITION SCREAMING_SNAKE_CASE__ : Tuple = set(lowercase__ ) - set(lowercase__ ) SCREAMING_SNAKE_CASE__ : int = set(lowercase__ ) & set(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = set(lowercase__ ) - set(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. SCREAMING_SNAKE_CASE__ : Optional[Any] = 1 SCREAMING_SNAKE_CASE__ : List[Any] = 1 if len(lowercase__ ) > 0: SCREAMING_SNAKE_CASE__ : str = addtmpscore / len(lowercase__ ) if len(lowercase__ ) > 0: SCREAMING_SNAKE_CASE__ : Optional[Any] = addtmpscore / len(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 if addscore_precision > 0 or addscore_recall > 0: SCREAMING_SNAKE_CASE__ : Tuple = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def _a ( lowercase__ : Dict , lowercase__ : Any , lowercase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = len(lowercase__ ) SCREAMING_SNAKE_CASE__ : int = ssent.split(' ' ) SCREAMING_SNAKE_CASE__ : List[str] = csent.split(' ' ) SCREAMING_SNAKE_CASE__ : int = [] SCREAMING_SNAKE_CASE__ : Optional[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : List[str] = [] SCREAMING_SNAKE_CASE__ : Dict = [] SCREAMING_SNAKE_CASE__ : int = [] SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : str = [] for rsent in rsents: SCREAMING_SNAKE_CASE__ : List[Any] = rsent.split(' ' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] SCREAMING_SNAKE_CASE__ : str = [] SCREAMING_SNAKE_CASE__ : int = [] ragramslist.append(lowercase__ ) for i in range(0 , len(lowercase__ ) - 1 ): if i < len(lowercase__ ) - 1: SCREAMING_SNAKE_CASE__ : List[str] = ragrams[i] + ' ' + ragrams[i + 1] ragrams.append(lowercase__ ) if i < len(lowercase__ ) - 2: SCREAMING_SNAKE_CASE__ : Dict = ragrams[i] + ' ' + ragrams[i + 1] + ' ' + ragrams[i + 2] ragrams.append(lowercase__ ) if i < len(lowercase__ ) - 3: SCREAMING_SNAKE_CASE__ : Optional[Any] = ragrams[i] + ' ' + ragrams[i + 1] + ' ' + ragrams[i + 2] + ' ' + ragrams[i + 3] ragrams.append(lowercase__ ) ragramslist.append(lowercase__ ) ragramslist.append(lowercase__ ) ragramslist.append(lowercase__ ) for i in range(0 , len(lowercase__ ) - 1 ): if i < len(lowercase__ ) - 1: SCREAMING_SNAKE_CASE__ : Union[str, Any] = sagrams[i] + ' ' + sagrams[i + 1] sagrams.append(lowercase__ ) if i < len(lowercase__ ) - 2: SCREAMING_SNAKE_CASE__ : Dict = sagrams[i] + ' ' + sagrams[i + 1] + ' ' + sagrams[i + 2] sagrams.append(lowercase__ ) if i < len(lowercase__ ) - 3: SCREAMING_SNAKE_CASE__ : str = sagrams[i] + ' ' + sagrams[i + 1] + ' ' + sagrams[i + 2] + ' ' + sagrams[i + 3] sagrams.append(lowercase__ ) for i in range(0 , len(lowercase__ ) - 1 ): if i < len(lowercase__ ) - 1: SCREAMING_SNAKE_CASE__ : List[str] = cagrams[i] + ' ' + cagrams[i + 1] cagrams.append(lowercase__ ) if i < len(lowercase__ ) - 2: SCREAMING_SNAKE_CASE__ : Optional[int] = cagrams[i] + ' ' + cagrams[i + 1] + ' ' + cagrams[i + 2] cagrams.append(lowercase__ ) if i < len(lowercase__ ) - 3: SCREAMING_SNAKE_CASE__ : Optional[int] = cagrams[i] + ' ' + cagrams[i + 1] + ' ' + cagrams[i + 2] + ' ' + cagrams[i + 3] cagrams.append(lowercase__ ) (SCREAMING_SNAKE_CASE__) : Tuple = SARIngram(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) (SCREAMING_SNAKE_CASE__) : int = SARIngram(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) (SCREAMING_SNAKE_CASE__) : Tuple = SARIngram(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) (SCREAMING_SNAKE_CASE__) : Tuple = SARIngram(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = sum([keepascore, keepascore, keepascore, keepascore] ) / 4 SCREAMING_SNAKE_CASE__ : Optional[int] = sum([delascore, delascore, delascore, delascore] ) / 4 SCREAMING_SNAKE_CASE__ : List[Any] = sum([addascore, addascore, addascore, addascore] ) / 4 SCREAMING_SNAKE_CASE__ : str = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def _a ( lowercase__ : Tuple , lowercase__ : bool = True , lowercase__ : str = "13a" , lowercase__ : bool = True ): '''simple docstring''' if lowercase: SCREAMING_SNAKE_CASE__ : Union[str, Any] = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__ ).major >= 2: SCREAMING_SNAKE_CASE__ : Optional[int] = sacrebleu.metrics.bleu._get_tokenizer(lowercase__ )()(lowercase__ ) else: SCREAMING_SNAKE_CASE__ : Dict = sacrebleu.TOKENIZERS[tokenizer]()(lowercase__ ) elif tokenizer == "moses": SCREAMING_SNAKE_CASE__ : str = sacremoses.MosesTokenizer().tokenize(lowercase__ , return_str=lowercase__ , escape=lowercase__ ) elif tokenizer == "penn": SCREAMING_SNAKE_CASE__ : List[Any] = sacremoses.MosesTokenizer().penn_tokenize(lowercase__ , return_str=lowercase__ ) else: SCREAMING_SNAKE_CASE__ : List[Any] = sentence if not return_str: SCREAMING_SNAKE_CASE__ : Optional[Any] = normalized_sent.split() return normalized_sent def _a ( lowercase__ : Optional[Any] , lowercase__ : Optional[Any] , lowercase__ : Optional[Any] ): '''simple docstring''' if not (len(lowercase__ ) == len(lowercase__ ) == len(lowercase__ )): raise ValueError('Sources length must match predictions and references lengths.' ) SCREAMING_SNAKE_CASE__ : List[Any] = 0 for src, pred, refs in zip(lowercase__ , lowercase__ , lowercase__ ): sari_score += SARIsent(normalize(lowercase__ ) , normalize(lowercase__ ) , [normalize(lowercase__ ) for sent in refs] ) SCREAMING_SNAKE_CASE__ : Dict = sari_score / len(lowercase__ ) return 1_00 * sari_score def _a ( lowercase__ : str , lowercase__ : str , lowercase__ : Any="exp" , lowercase__ : Any=None , lowercase__ : List[str]=False , lowercase__ : Tuple=False , lowercase__ : List[str]=False , ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = len(references[0] ) if any(len(lowercase__ ) != references_per_prediction for refs in references ): raise ValueError('Sacrebleu requires the same number of references for each prediction' ) SCREAMING_SNAKE_CASE__ : Optional[int] = [[refs[i] for refs in references] for i in range(lowercase__ )] SCREAMING_SNAKE_CASE__ : Optional[Any] = sacrebleu.corpus_bleu( lowercase__ , lowercase__ , smooth_method=lowercase__ , smooth_value=lowercase__ , force=lowercase__ , lowercase=lowercase__ , use_effective_order=lowercase__ , ) return output.score @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): def __lowercase( self : int )-> List[str]: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence' ), 'references': datasets.Sequence(datasets.Value('string' , id='sequence' ) , id='references' ), } ) , codebase_urls=[ 'https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py', 'https://github.com/cocoxu/simplification/blob/master/SARI.py', 'https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py', 'https://github.com/mjpost/sacreBLEU', ] , reference_urls=[ 'https://www.aclweb.org/anthology/Q16-1029.pdf', 'https://github.com/mjpost/sacreBLEU', 'https://en.wikipedia.org/wiki/BLEU', 'https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213', ] , ) def __lowercase( self : int , a_ : Dict , a_ : Dict , a_ : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = {} result.update({'sari': compute_sari(sources=a_ , predictions=a_ , references=a_ )} ) result.update({'sacrebleu': compute_sacrebleu(predictions=a_ , references=a_ )} ) result.update({'exact': compute_em(predictions=a_ , references=a_ )} ) return result
709
import math import sys def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = '' try: with open(lowercase__ , 'rb' ) as binary_file: SCREAMING_SNAKE_CASE__ : Tuple = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Tuple = f'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible' ) sys.exit() def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = '', '' SCREAMING_SNAKE_CASE__ : Tuple = len(lowercase__ ) for i in range(len(lowercase__ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : int = lexicon[curr_string] result += last_match_id SCREAMING_SNAKE_CASE__ : str = last_match_id + '0' if math.loga(lowercase__ ).is_integer(): SCREAMING_SNAKE_CASE__ : List[str] = {} for curr_key in list(lowercase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = new_lex SCREAMING_SNAKE_CASE__ : Any = last_match_id + '1' index += 1 SCREAMING_SNAKE_CASE__ : Tuple = '' return result def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = 8 try: with open(lowercase__ , 'wb' ) as opened_file: SCREAMING_SNAKE_CASE__ : Dict = [ 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 _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 0 for letter in data_bits: if letter == "1": break counter += 1 SCREAMING_SNAKE_CASE__ : Optional[int] = data_bits[counter:] SCREAMING_SNAKE_CASE__ : int = data_bits[counter + 1 :] return data_bits def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = read_file_binary(lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = remove_prefix(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = decompress_data(lowercase__ ) write_file_binary(lowercase__ , lowercase__ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
636
0
import warnings from contextlib import contextmanager from ...processing_utils import ProcessorMixin class snake_case ( UpperCamelCase_ ): lowercase_ = 'Speech2TextFeatureExtractor' lowercase_ = 'Speech2TextTokenizer' def __init__( self : Union[str, Any] , a_ : Optional[int] , a_ : Any )-> List[str]: """simple docstring""" super().__init__(a_ , a_ ) SCREAMING_SNAKE_CASE__ : int = self.feature_extractor SCREAMING_SNAKE_CASE__ : Dict = False def __call__( self : Tuple , *a_ : Optional[Any] , **a_ : Dict )-> Optional[int]: """simple docstring""" # For backward compatibility if self._in_target_context_manager: return self.current_processor(*a_ , **a_ ) if "raw_speech" in kwargs: warnings.warn('Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.' ) SCREAMING_SNAKE_CASE__ : Any = kwargs.pop('raw_speech' ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = kwargs.pop('audio' , a_ ) SCREAMING_SNAKE_CASE__ : int = kwargs.pop('sampling_rate' , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = kwargs.pop('text' , a_ ) if len(a_ ) > 0: SCREAMING_SNAKE_CASE__ : Optional[Any] = args[0] SCREAMING_SNAKE_CASE__ : List[Any] = args[1:] if audio is None and text is None: raise ValueError('You need to specify either an `audio` or `text` input to process.' ) if audio is not None: SCREAMING_SNAKE_CASE__ : int = self.feature_extractor(a_ , *a_ , sampling_rate=a_ , **a_ ) if text is not None: SCREAMING_SNAKE_CASE__ : Any = self.tokenizer(a_ , **a_ ) if text is None: return inputs elif audio is None: return encodings else: SCREAMING_SNAKE_CASE__ : List[str] = encodings['input_ids'] return inputs def __lowercase( self : int , *a_ : List[Any] , **a_ : str )-> Union[str, Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Optional[int] , *a_ : Tuple , **a_ : str )-> Union[str, Any]: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @contextmanager def __lowercase( self : Dict )-> List[Any]: """simple docstring""" warnings.warn( '`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your ' 'labels by using the argument `text` of the regular `__call__` method (either in the same call as ' 'your audio inputs, or in a separate call.' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Optional[int] = self.tokenizer yield SCREAMING_SNAKE_CASE__ : Dict = self.feature_extractor SCREAMING_SNAKE_CASE__ : Optional[int] = False
710
def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : List[Any] = set({'(', '[', '{'} ) SCREAMING_SNAKE_CASE__ : Optional[int] = set({')', ']', '}'} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'{': '}', '[': ']', '(': ')'} for i in range(len(lowercase__ ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(lowercase__ ) == 0 or (len(lowercase__ ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(lowercase__ ) == 0 def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = input('Enter sequence of brackets: ' ) if is_balanced(lowercase__ ): print(lowercase__ , 'is balanced' ) else: print(lowercase__ , 'is not balanced' ) if __name__ == "__main__": main()
636
0
import contextlib from multiprocessing import Pool, RLock from tqdm.auto import tqdm from ..utils import experimental, logging SCREAMING_SNAKE_CASE__ : Any = logging.get_logger(__name__) class snake_case : lowercase_ = None @experimental def _a ( lowercase__ : Any , lowercase__ : str , lowercase__ : Dict , lowercase__ : Any , lowercase__ : Union[str, Any] , lowercase__ : str , lowercase__ : Optional[Any] ): '''simple docstring''' if ParallelBackendConfig.backend_name is None: return _map_with_multiprocessing_pool( lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) return _map_with_joblib(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) def _a ( lowercase__ : Optional[int] , lowercase__ : Optional[Any] , lowercase__ : Union[str, Any] , lowercase__ : int , lowercase__ : Union[str, Any] , lowercase__ : str , lowercase__ : List[str] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = num_proc if num_proc <= len(lowercase__ ) else len(lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = [] # We organize the splits ourselve (contiguous splits) for index in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : Any = len(lowercase__ ) // num_proc SCREAMING_SNAKE_CASE__ : Any = len(lowercase__ ) % num_proc SCREAMING_SNAKE_CASE__ : Dict = div * index + min(lowercase__ , lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = start + div + (1 if index < mod else 0) split_kwds.append((function, iterable[start:end], types, index, disable_tqdm, desc) ) if len(lowercase__ ) != sum(len(i[1] ) for i in split_kwds ): raise ValueError( f'''Error dividing inputs iterable among processes. ''' f'''Total number of objects {len(lowercase__ )}, ''' f'''length: {sum(len(i[1] ) for i in split_kwds )}''' ) logger.info( f'''Spawning {num_proc} processes for {len(lowercase__ )} objects in slices of {[len(i[1] ) for i in split_kwds]}''' ) SCREAMING_SNAKE_CASE__ : int = None, None if not disable_tqdm: SCREAMING_SNAKE_CASE__ : Union[str, Any] = (RLock(),), tqdm.set_lock with Pool(lowercase__ , initargs=lowercase__ , initializer=lowercase__ ) as pool: SCREAMING_SNAKE_CASE__ : Any = pool.map(lowercase__ , lowercase__ ) logger.info(f'''Finished {num_proc} processes''' ) SCREAMING_SNAKE_CASE__ : List[Any] = [obj for proc_res in mapped for obj in proc_res] logger.info(f'''Unpacked {len(lowercase__ )} objects''' ) return mapped def _a ( lowercase__ : Dict , lowercase__ : List[str] , lowercase__ : List[Any] , lowercase__ : Any , lowercase__ : Tuple , lowercase__ : Optional[int] , lowercase__ : str ): '''simple docstring''' import joblib with joblib.parallel_backend(ParallelBackendConfig.backend_name , n_jobs=lowercase__ ): return joblib.Parallel()( joblib.delayed(lowercase__ )((function, obj, types, None, True, None) ) for obj in iterable ) @experimental @contextlib.contextmanager def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = backend_name if backend_name == "spark": from joblibspark import register_spark register_spark() # TODO: call create_cache_and_write_probe if "download" in steps # TODO: raise NotImplementedError when Dataset.map etc is called try: yield finally: SCREAMING_SNAKE_CASE__ : Tuple = None
711
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 SCREAMING_SNAKE_CASE__ : List[Any] = get_tests_dir("fixtures/test_sentencepiece_no_bos.model") @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : int )-> List[Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : List[Any] = PegasusTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def __lowercase( self : Any , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Union[str, Any] , a_ : List[Any] )-> Optional[int]: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : Optional[int] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = '</s>' SCREAMING_SNAKE_CASE__ : Any = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : Dict )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = 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(a_ ) , 1103 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( '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>' ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word SCREAMING_SNAKE_CASE__ : Any = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 SCREAMING_SNAKE_CASE__ : int = 'To ensure a smooth flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ['This is going to be way too long.' * 150, 'short example'] SCREAMING_SNAKE_CASE__ : int = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. @slow def __lowercase( self : Any )-> str: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Optional[int] = {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 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], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 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=a_ , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Any )-> Union[str, Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Optional[int] = PegasusTokenizer(a_ , offset=0 , mask_token_sent=a_ , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> List[str]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def __lowercase( self : List[str] , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Optional[Any] , a_ : Tuple )-> str: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE__ : str = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : str = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) @require_torch def __lowercase( self : List[str] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = ['This is going to be way too long.' * 1000, 'short example'] SCREAMING_SNAKE_CASE__ : Optional[int] = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : str = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._large_tokenizer(a_ ).input_ids self.assertListEqual( a_ , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
636
0
import requests SCREAMING_SNAKE_CASE__ : int = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page['articles'] , 1 ): print(f'''{i}.) {article['title']}''' ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
712
def _a ( lowercase__ : int = 1_00_00_00 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , lowercase__ ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
636
0
import json import os import shutil import tempfile import unittest import numpy as np import pytest from transformers import BertTokenizer, BertTokenizerFast from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES from transformers.testing_utils import require_vision from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available if is_vision_available(): from PIL import Image from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor @require_vision class snake_case ( unittest.TestCase ): def __lowercase( self : int )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = tempfile.mkdtemp() SCREAMING_SNAKE_CASE__ : List[str] = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', '的', '价', '格', '是', '15', '便', 'alex', '##andra', ',', '。', '-', 't', 'shirt', ] SCREAMING_SNAKE_CASE__ : int = 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__ : List[Any] = { 'do_resize': True, 'size': {'height': 224, 'width': 224}, 'do_center_crop': True, 'crop_size': {'height': 18, 'width': 18}, 'do_normalize': True, 'image_mean': [0.4814_5466, 0.457_8275, 0.4082_1073], 'image_std': [0.2686_2954, 0.2613_0258, 0.2757_7711], 'do_convert_rgb': True, } SCREAMING_SNAKE_CASE__ : List[str] = os.path.join(self.tmpdirname , a_ ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(a_ , a_ ) def __lowercase( self : Dict , **a_ : int )-> Optional[int]: """simple docstring""" return BertTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : List[str] , **a_ : int )-> int: """simple docstring""" return BertTokenizerFast.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : str , **a_ : Any )-> Optional[Any]: """simple docstring""" return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" shutil.rmtree(self.tmpdirname ) def __lowercase( self : Optional[int] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE__ : List[Any] = [Image.fromarray(np.moveaxis(a_ , 0 , -1 ) ) for x in image_inputs] return image_inputs def __lowercase( self : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : str = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE__ : List[Any] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Optional[int] = ChineseCLIPProcessor(tokenizer=a_ , image_processor=a_ ) processor_slow.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = ChineseCLIPProcessor(tokenizer=a_ , image_processor=a_ ) processor_fast.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Dict = ChineseCLIPProcessor.from_pretrained(self.tmpdirname ) self.assertEqual(processor_slow.tokenizer.get_vocab() , tokenizer_slow.get_vocab() ) self.assertEqual(processor_fast.tokenizer.get_vocab() , tokenizer_fast.get_vocab() ) self.assertEqual(tokenizer_slow.get_vocab() , tokenizer_fast.get_vocab() ) self.assertIsInstance(processor_slow.tokenizer , a_ ) self.assertIsInstance(processor_fast.tokenizer , a_ ) self.assertEqual(processor_slow.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertEqual(processor_fast.image_processor.to_json_string() , image_processor.to_json_string() ) self.assertIsInstance(processor_slow.image_processor , a_ ) self.assertIsInstance(processor_fast.image_processor , a_ ) def __lowercase( self : str )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_tokenizer(cls_token='(CLS)' , sep_token='(SEP)' ) SCREAMING_SNAKE_CASE__ : str = self.get_image_processor(do_normalize=a_ ) SCREAMING_SNAKE_CASE__ : int = ChineseCLIPProcessor.from_pretrained( self.tmpdirname , cls_token='(CLS)' , sep_token='(SEP)' , do_normalize=a_ ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , a_ ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , a_ ) def __lowercase( self : List[str] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : List[str] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Dict = ChineseCLIPProcessor(tokenizer=a_ , image_processor=a_ ) SCREAMING_SNAKE_CASE__ : List[str] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : List[Any] = image_processor(a_ , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Any = processor(images=a_ , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1e-2 ) def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Any = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Union[str, Any] = ChineseCLIPProcessor(tokenizer=a_ , image_processor=a_ ) SCREAMING_SNAKE_CASE__ : Any = 'Alexandra,T-shirt的价格是15便士。' SCREAMING_SNAKE_CASE__ : int = processor(text=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer(a_ ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def __lowercase( self : Dict )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Optional[int] = ChineseCLIPProcessor(tokenizer=a_ , image_processor=a_ ) SCREAMING_SNAKE_CASE__ : Dict = 'Alexandra,T-shirt的价格是15便士。' SCREAMING_SNAKE_CASE__ : List[Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : Union[str, Any] = processor(text=a_ , images=a_ ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'token_type_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(a_ ): processor() def __lowercase( self : Tuple )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.get_image_processor() SCREAMING_SNAKE_CASE__ : str = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : Any = ChineseCLIPProcessor(tokenizer=a_ , image_processor=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE__ : Tuple = processor.batch_decode(a_ ) SCREAMING_SNAKE_CASE__ : str = tokenizer.batch_decode(a_ ) self.assertListEqual(a_ , a_ ) def __lowercase( self : Optional[int] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.get_image_processor() SCREAMING_SNAKE_CASE__ : Dict = self.get_tokenizer() SCREAMING_SNAKE_CASE__ : List[Any] = ChineseCLIPProcessor(tokenizer=a_ , image_processor=a_ ) SCREAMING_SNAKE_CASE__ : Any = 'Alexandra,T-shirt的价格是15便士。' SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_image_inputs() SCREAMING_SNAKE_CASE__ : int = processor(text=a_ , images=a_ ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
713
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) def _a ( lowercase__ : Union[str, Any] , lowercase__ : Union[str, Any]=False , lowercase__ : str=False , lowercase__ : Dict=False ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''transformer.blocks.{i}.norm1.weight''', f'''vilt.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm1.bias''', f'''vilt.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.weight''', f'''vilt.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.bias''', f'''vilt.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.weight''', f'''vilt.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.bias''', f'''vilt.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.mlp.fc1.weight''', f'''vilt.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc1.bias''', f'''vilt.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.weight''', f'''vilt.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.bias''', f'''vilt.encoder.layer.{i}.output.dense.bias''') ) # embeddings rename_keys.extend( [ # text embeddings ('text_embeddings.word_embeddings.weight', 'vilt.embeddings.text_embeddings.word_embeddings.weight'), ( 'text_embeddings.position_embeddings.weight', 'vilt.embeddings.text_embeddings.position_embeddings.weight', ), ('text_embeddings.position_ids', 'vilt.embeddings.text_embeddings.position_ids'), ( 'text_embeddings.token_type_embeddings.weight', 'vilt.embeddings.text_embeddings.token_type_embeddings.weight', ), ('text_embeddings.LayerNorm.weight', 'vilt.embeddings.text_embeddings.LayerNorm.weight'), ('text_embeddings.LayerNorm.bias', 'vilt.embeddings.text_embeddings.LayerNorm.bias'), # patch embeddings ('transformer.cls_token', 'vilt.embeddings.cls_token'), ('transformer.patch_embed.proj.weight', 'vilt.embeddings.patch_embeddings.projection.weight'), ('transformer.patch_embed.proj.bias', 'vilt.embeddings.patch_embeddings.projection.bias'), ('transformer.pos_embed', 'vilt.embeddings.position_embeddings'), # token type embeddings ('token_type_embeddings.weight', 'vilt.embeddings.token_type_embeddings.weight'), ] ) # final layernorm + pooler rename_keys.extend( [ ('transformer.norm.weight', 'vilt.layernorm.weight'), ('transformer.norm.bias', 'vilt.layernorm.bias'), ('pooler.dense.weight', 'vilt.pooler.dense.weight'), ('pooler.dense.bias', 'vilt.pooler.dense.bias'), ] ) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ('vqa_classifier.0.weight', 'classifier.0.weight'), ('vqa_classifier.0.bias', 'classifier.0.bias'), ('vqa_classifier.1.weight', 'classifier.1.weight'), ('vqa_classifier.1.bias', 'classifier.1.bias'), ('vqa_classifier.3.weight', 'classifier.3.weight'), ('vqa_classifier.3.bias', 'classifier.3.bias'), ] ) elif nlvr_model: # classification head rename_keys.extend( [ ('nlvr2_classifier.0.weight', 'classifier.0.weight'), ('nlvr2_classifier.0.bias', 'classifier.0.bias'), ('nlvr2_classifier.1.weight', 'classifier.1.weight'), ('nlvr2_classifier.1.bias', 'classifier.1.bias'), ('nlvr2_classifier.3.weight', 'classifier.3.weight'), ('nlvr2_classifier.3.bias', 'classifier.3.bias'), ] ) else: pass return rename_keys def _a ( lowercase__ : List[str] , lowercase__ : Dict ): '''simple docstring''' for i in range(config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ : Dict = 'vilt.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[-config.hidden_size :] def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) def _a ( lowercase__ : int , lowercase__ : int , lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = dct.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = val @torch.no_grad() def _a ( lowercase__ : Dict , lowercase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = ViltConfig(image_size=3_84 , patch_size=32 , tie_word_embeddings=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = False SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : str = False if "vqa" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : str = 31_29 SCREAMING_SNAKE_CASE__ : Optional[Any] = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : int = 'vqa2-id2label.json' SCREAMING_SNAKE_CASE__ : str = json.load(open(hf_hub_download(lowercase__ , lowercase__ , repo_type='dataset' ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = idalabel SCREAMING_SNAKE_CASE__ : str = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : List[str] = ViltForQuestionAnswering(lowercase__ ) elif "nlvr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = True SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Dict = {0: 'False', 1: 'True'} SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in config.idalabel.items()} SCREAMING_SNAKE_CASE__ : Tuple = 3 SCREAMING_SNAKE_CASE__ : int = ViltForImagesAndTextClassification(lowercase__ ) elif "irtr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : str = ViltForImageAndTextRetrieval(lowercase__ ) elif "mlm_itm" in checkpoint_url: SCREAMING_SNAKE_CASE__ : int = True SCREAMING_SNAKE_CASE__ : Optional[int] = ViltForMaskedLM(lowercase__ ) else: raise ValueError('Unknown model type' ) # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE__ : Any = torch.hub.load_state_dict_from_url(lowercase__ , map_location='cpu' )['state_dict'] SCREAMING_SNAKE_CASE__ : Any = create_rename_keys(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) for src, dest in rename_keys: rename_key(lowercase__ , lowercase__ , lowercase__ ) read_in_q_k_v(lowercase__ , lowercase__ ) if mlm_model or irtr_model: SCREAMING_SNAKE_CASE__ : Any = ['itm_score.fc.weight', 'itm_score.fc.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) # load state dict into HuggingFace model model.eval() if mlm_model: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model.load_state_dict(lowercase__ , strict=lowercase__ ) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(lowercase__ ) # Define processor SCREAMING_SNAKE_CASE__ : str = ViltImageProcessor(size=3_84 ) SCREAMING_SNAKE_CASE__ : List[Any] = BertTokenizer.from_pretrained('bert-base-uncased' ) SCREAMING_SNAKE_CASE__ : List[Any] = ViltProcessor(lowercase__ , lowercase__ ) # Forward pass on example inputs (image + text) if nlvr_model: SCREAMING_SNAKE_CASE__ : List[str] = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Any = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'The left image contains twice the number of dogs as the right image, and at least two dogs in total are' ' standing.' ) SCREAMING_SNAKE_CASE__ : List[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[str] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[Any] = model( input_ids=encoding_a.input_ids , pixel_values=encoding_a.pixel_values , pixel_values_a=encoding_a.pixel_values , ) else: SCREAMING_SNAKE_CASE__ : Tuple = Image.open(requests.get('http://images.cocodataset.org/val2017/000000039769.jpg' , stream=lowercase__ ).raw ) if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'a bunch of [MASK] laying on a [MASK].' else: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'How many cats are there?' SCREAMING_SNAKE_CASE__ : Optional[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = model(**lowercase__ ) # Verify outputs if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Size([1, 11, 3_05_22] ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([-12.5061, -12.5123, -12.5174] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify masked token prediction equals "cats" SCREAMING_SNAKE_CASE__ : Union[str, Any] = outputs.logits[0, 4, :].argmax(-1 ).item() assert tokenizer.decode([predicted_id] ) == "cats" elif vqa_model: SCREAMING_SNAKE_CASE__ : str = torch.Size([1, 31_29] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([-15.9495, -18.1472, -10.3041] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify vqa prediction equals "2" SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(-1 ).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.Size([1, 2] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([-2.8721, 2.1291] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape Path(lowercase__ ).mkdir(exist_ok=lowercase__ ) print(f'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase__ ) processor.save_pretrained(lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt", type=str, help="URL of the checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
636
0
import argparse import json import os import sys import tempfile import unittest from argparse import Namespace from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import List, Literal, Optional import yaml from transformers import HfArgumentParser, TrainingArguments from transformers.hf_argparser import make_choice_type_function, string_to_bool # Since Python 3.10, we can use the builtin `|` operator for Union types # See PEP 604: https://peps.python.org/pep-0604 SCREAMING_SNAKE_CASE__ : Optional[int] = sys.version_info >= (3, 10) def _a ( lowercase__ : Any=None , lowercase__ : Tuple=None ): '''simple docstring''' return field(default_factory=lambda: default , metadata=lowercase__ ) @dataclass class snake_case : lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 @dataclass class snake_case : lowercase_ = 42 lowercase_ = field(default='toto' , metadata={'help': 'help message'} ) @dataclass class snake_case : lowercase_ = False lowercase_ = True lowercase_ = None class snake_case ( UpperCamelCase_ ): lowercase_ = 'titi' lowercase_ = 'toto' class snake_case ( UpperCamelCase_ ): lowercase_ = 'titi' lowercase_ = 'toto' lowercase_ = 42 @dataclass class snake_case : lowercase_ = 'toto' def __lowercase( self : List[str] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = BasicEnum(self.foo ) @dataclass class snake_case : lowercase_ = 'toto' def __lowercase( self : Any )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = MixedTypeEnum(self.foo ) @dataclass class snake_case : lowercase_ = None lowercase_ = field(default=UpperCamelCase_ , metadata={'help': 'help message'} ) lowercase_ = None lowercase_ = list_field(default=[] ) lowercase_ = list_field(default=[] ) @dataclass class snake_case : lowercase_ = list_field(default=[] ) lowercase_ = list_field(default=[1, 2, 3] ) lowercase_ = list_field(default=['Hallo', 'Bonjour', 'Hello'] ) lowercase_ = list_field(default=[0.1, 0.2, 0.3] ) @dataclass class snake_case : lowercase_ = field() lowercase_ = field() lowercase_ = field() def __lowercase( self : Optional[int] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = BasicEnum(self.required_enum ) @dataclass class snake_case : lowercase_ = 42 lowercase_ = field() lowercase_ = None lowercase_ = field(default='toto' , metadata={'help': 'help message'} ) lowercase_ = list_field(default=['Hallo', 'Bonjour', 'Hello'] ) if is_python_no_less_than_3_10: @dataclass class snake_case : lowercase_ = False lowercase_ = True lowercase_ = None @dataclass class snake_case : lowercase_ = None lowercase_ = field(default=UpperCamelCase_ , metadata={'help': 'help message'} ) lowercase_ = None lowercase_ = list_field(default=[] ) lowercase_ = list_field(default=[] ) class snake_case ( unittest.TestCase ): def __lowercase( self : int , a_ : argparse.ArgumentParser , a_ : argparse.ArgumentParser )-> Tuple: """simple docstring""" self.assertEqual(len(a._actions ) , len(b._actions ) ) for x, y in zip(a._actions , b._actions ): SCREAMING_SNAKE_CASE__ : List[str] = {k: v for k, v in vars(a_ ).items() if k != 'container'} SCREAMING_SNAKE_CASE__ : Dict = {k: v for k, v in vars(a_ ).items() if k != 'container'} # Choices with mixed type have custom function as "type" # So we need to compare results directly for equality if xx.get('choices' , a_ ) and yy.get('choices' , a_ ): for expected_choice in yy["choices"] + xx["choices"]: self.assertEqual(xx['type'](a_ ) , yy['type'](a_ ) ) del xx["type"], yy["type"] self.assertEqual(a_ , a_ ) def __lowercase( self : int )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = HfArgumentParser(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = argparse.ArgumentParser() expected.add_argument('--foo' , type=a_ , required=a_ ) expected.add_argument('--bar' , type=a_ , required=a_ ) expected.add_argument('--baz' , type=a_ , required=a_ ) expected.add_argument('--flag' , type=a_ , default=a_ , const=a_ , nargs='?' ) self.argparsersEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = ['--foo', '1', '--baz', 'quux', '--bar', '0.5'] (SCREAMING_SNAKE_CASE__ ) : Tuple = parser.parse_args_into_dataclasses(a_ , look_for_args_file=a_ ) self.assertFalse(example.flag ) def __lowercase( self : Dict )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = HfArgumentParser(a_ ) SCREAMING_SNAKE_CASE__ : Dict = argparse.ArgumentParser() expected.add_argument('--foo' , default=42 , type=a_ ) expected.add_argument('--baz' , default='toto' , type=a_ , help='help message' ) self.argparsersEqual(a_ , a_ ) def __lowercase( self : List[Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = argparse.ArgumentParser() expected.add_argument('--foo' , type=a_ , default=a_ , const=a_ , nargs='?' ) expected.add_argument('--baz' , type=a_ , default=a_ , const=a_ , nargs='?' ) # A boolean no_* argument always has to come after its "default: True" regular counter-part # and its default must be set to False expected.add_argument('--no_baz' , action='store_false' , default=a_ , dest='baz' ) expected.add_argument('--opt' , type=a_ , default=a_ ) SCREAMING_SNAKE_CASE__ : str = [WithDefaultBoolExample] if is_python_no_less_than_3_10: dataclass_types.append(a_ ) for dataclass_type in dataclass_types: SCREAMING_SNAKE_CASE__ : Union[str, Any] = HfArgumentParser(a_ ) self.argparsersEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = parser.parse_args([] ) self.assertEqual(a_ , Namespace(foo=a_ , baz=a_ , opt=a_ ) ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args(['--foo', '--no_baz'] ) self.assertEqual(a_ , Namespace(foo=a_ , baz=a_ , opt=a_ ) ) SCREAMING_SNAKE_CASE__ : Dict = parser.parse_args(['--foo', '--baz'] ) self.assertEqual(a_ , Namespace(foo=a_ , baz=a_ , opt=a_ ) ) SCREAMING_SNAKE_CASE__ : List[str] = parser.parse_args(['--foo', 'True', '--baz', 'True', '--opt', 'True'] ) self.assertEqual(a_ , Namespace(foo=a_ , baz=a_ , opt=a_ ) ) SCREAMING_SNAKE_CASE__ : Dict = parser.parse_args(['--foo', 'False', '--baz', 'False', '--opt', 'False'] ) self.assertEqual(a_ , Namespace(foo=a_ , baz=a_ , opt=a_ ) ) def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = HfArgumentParser(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = argparse.ArgumentParser() expected.add_argument( '--foo' , default='toto' , choices=['titi', 'toto', 42] , type=make_choice_type_function(['titi', 'toto', 42] ) , ) self.argparsersEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = parser.parse_args([] ) self.assertEqual(args.foo , 'toto' ) SCREAMING_SNAKE_CASE__ : List[str] = parser.parse_args_into_dataclasses([] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.toto ) SCREAMING_SNAKE_CASE__ : Tuple = parser.parse_args(['--foo', 'titi'] ) self.assertEqual(args.foo , 'titi' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = parser.parse_args_into_dataclasses(['--foo', 'titi'] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.titi ) SCREAMING_SNAKE_CASE__ : str = parser.parse_args(['--foo', '42'] ) self.assertEqual(args.foo , 42 ) SCREAMING_SNAKE_CASE__ : str = parser.parse_args_into_dataclasses(['--foo', '42'] )[0] self.assertEqual(enum_ex.foo , MixedTypeEnum.fourtytwo ) def __lowercase( self : Union[str, Any] )-> Union[str, Any]: """simple docstring""" @dataclass class snake_case : lowercase_ = 'toto' SCREAMING_SNAKE_CASE__ : Tuple = HfArgumentParser(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = argparse.ArgumentParser() expected.add_argument( '--foo' , default='toto' , choices=('titi', 'toto', 42) , type=make_choice_type_function(['titi', 'toto', 42] ) , ) self.argparsersEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args([] ) self.assertEqual(args.foo , 'toto' ) SCREAMING_SNAKE_CASE__ : int = parser.parse_args(['--foo', 'titi'] ) self.assertEqual(args.foo , 'titi' ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args(['--foo', '42'] ) self.assertEqual(args.foo , 42 ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = HfArgumentParser(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = argparse.ArgumentParser() expected.add_argument('--foo_int' , nargs='+' , default=[] , type=a_ ) expected.add_argument('--bar_int' , nargs='+' , default=[1, 2, 3] , type=a_ ) expected.add_argument('--foo_str' , nargs='+' , default=['Hallo', 'Bonjour', 'Hello'] , type=a_ ) expected.add_argument('--foo_float' , nargs='+' , default=[0.1, 0.2, 0.3] , type=a_ ) self.argparsersEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : int = parser.parse_args([] ) self.assertEqual( a_ , Namespace(foo_int=[] , bar_int=[1, 2, 3] , foo_str=['Hallo', 'Bonjour', 'Hello'] , foo_float=[0.1, 0.2, 0.3] ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = parser.parse_args('--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7'.split() ) self.assertEqual(a_ , Namespace(foo_int=[1] , bar_int=[2, 3] , foo_str=['a', 'b', 'c'] , foo_float=[0.1, 0.7] ) ) def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = argparse.ArgumentParser() expected.add_argument('--foo' , default=a_ , type=a_ ) expected.add_argument('--bar' , default=a_ , type=a_ , help='help message' ) expected.add_argument('--baz' , default=a_ , type=a_ ) expected.add_argument('--ces' , nargs='+' , default=[] , type=a_ ) expected.add_argument('--des' , nargs='+' , default=[] , type=a_ ) SCREAMING_SNAKE_CASE__ : int = [OptionalExample] if is_python_no_less_than_3_10: dataclass_types.append(a_ ) for dataclass_type in dataclass_types: SCREAMING_SNAKE_CASE__ : Dict = HfArgumentParser(a_ ) self.argparsersEqual(a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args([] ) self.assertEqual(a_ , Namespace(foo=a_ , bar=a_ , baz=a_ , ces=[] , des=[] ) ) SCREAMING_SNAKE_CASE__ : str = parser.parse_args('--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3'.split() ) self.assertEqual(a_ , Namespace(foo=12 , bar=3.14 , baz='42' , ces=['a', 'b', 'c'] , des=[1, 2, 3] ) ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = HfArgumentParser(a_ ) SCREAMING_SNAKE_CASE__ : Dict = argparse.ArgumentParser() expected.add_argument('--required_list' , nargs='+' , type=a_ , required=a_ ) expected.add_argument('--required_str' , type=a_ , required=a_ ) expected.add_argument( '--required_enum' , type=make_choice_type_function(['titi', 'toto'] ) , choices=['titi', 'toto'] , required=a_ , ) self.argparsersEqual(a_ , a_ ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = HfArgumentParser(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = argparse.ArgumentParser() expected.add_argument('--foo' , type=a_ , required=a_ ) expected.add_argument( '--required_enum' , type=make_choice_type_function(['titi', 'toto'] ) , choices=['titi', 'toto'] , required=a_ , ) expected.add_argument('--opt' , type=a_ , default=a_ ) expected.add_argument('--baz' , default='toto' , type=a_ , help='help message' ) expected.add_argument('--foo_str' , nargs='+' , default=['Hallo', 'Bonjour', 'Hello'] , type=a_ ) self.argparsersEqual(a_ , a_ ) def __lowercase( self : Tuple )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = HfArgumentParser(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = { 'foo': 12, 'bar': 3.14, 'baz': '42', 'flag': True, } SCREAMING_SNAKE_CASE__ : Tuple = parser.parse_dict(a_ )[0] SCREAMING_SNAKE_CASE__ : Dict = BasicExample(**a_ ) self.assertEqual(a_ , a_ ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = HfArgumentParser(a_ ) SCREAMING_SNAKE_CASE__ : Dict = { 'foo': 12, 'bar': 3.14, 'baz': '42', 'flag': True, 'extra': 42, } self.assertRaises(a_ , parser.parse_dict , a_ , allow_extra_keys=a_ ) def __lowercase( self : int )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = HfArgumentParser(a_ ) SCREAMING_SNAKE_CASE__ : str = { 'foo': 12, 'bar': 3.14, 'baz': '42', 'flag': True, } with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE__ : Union[str, Any] = os.path.join(a_ , 'temp_json' ) os.mkdir(a_ ) with open(temp_local_path + '.json' , 'w+' ) as f: json.dump(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = parser.parse_yaml_file(Path(temp_local_path + '.json' ) )[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = BasicExample(**a_ ) self.assertEqual(a_ , a_ ) def __lowercase( self : List[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = HfArgumentParser(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = { 'foo': 12, 'bar': 3.14, 'baz': '42', 'flag': True, } with tempfile.TemporaryDirectory() as tmp_dir: SCREAMING_SNAKE_CASE__ : Any = os.path.join(a_ , 'temp_yaml' ) os.mkdir(a_ ) with open(temp_local_path + '.yaml' , 'w+' ) as f: yaml.dump(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Any = parser.parse_yaml_file(Path(temp_local_path + '.yaml' ) )[0] SCREAMING_SNAKE_CASE__ : List[str] = BasicExample(**a_ ) self.assertEqual(a_ , a_ ) def __lowercase( self : Tuple )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = HfArgumentParser(a_ ) self.assertIsNotNone(a_ )
714
from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class snake_case : lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def __lowercase( self : Dict )-> Tuple: """simple docstring""" return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def __lowercase( self : Dict )-> Union[str, Any]: """simple docstring""" return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def __lowercase( self : Tuple )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = torch.arange(self.height * self.width ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.stack( [ pixel_indices % self.width, torch.div(a_ , self.width , rounding_mode='trunc' ), ] , axis=1 , ) return coords @property def __lowercase( self : Any )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.shape SCREAMING_SNAKE_CASE__ : Tuple = int(np.prod(a_ ) ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_coords() SCREAMING_SNAKE_CASE__ : Dict = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) SCREAMING_SNAKE_CASE__ : Any = self.get_camera_rays(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = rays.view(a_ , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def __lowercase( self : Optional[Any] , a_ : torch.Tensor )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] SCREAMING_SNAKE_CASE__ : str = coords.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : List[Any] = self.resolution() SCREAMING_SNAKE_CASE__ : str = self.fov() SCREAMING_SNAKE_CASE__ : Any = (flat.float() / (res - 1)) * 2 - 1 SCREAMING_SNAKE_CASE__ : Any = fracs * torch.tan(fov / 2 ) SCREAMING_SNAKE_CASE__ : List[str] = fracs.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : str = ( self.z.view(a_ , 1 , 3 ) + self.x.view(a_ , 1 , 3 ) * fracs[:, :, :1] + self.y.view(a_ , 1 , 3 ) * fracs[:, :, 1:] ) SCREAMING_SNAKE_CASE__ : Tuple = directions / directions.norm(dim=-1 , keepdim=a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.stack( [ torch.broadcast_to(self.origin.view(a_ , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(a_ , *a_ , 2 , 3 ) def __lowercase( self : Optional[int] , a_ : int , a_ : int )-> "DifferentiableProjectiveCamera": """simple docstring""" assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=a_ , height=a_ , x_fov=self.x_fov , y_fov=self.y_fov , ) def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.sin(lowercase__ ), np.cos(lowercase__ ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) SCREAMING_SNAKE_CASE__ : Tuple = -z * 4 SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.cos(lowercase__ ), -np.sin(lowercase__ ), 0.0] ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.cross(lowercase__ , lowercase__ ) origins.append(lowercase__ ) xs.append(lowercase__ ) ys.append(lowercase__ ) zs.append(lowercase__ ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , x=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , y=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , z=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , width=lowercase__ , height=lowercase__ , x_fov=0.7 , y_fov=0.7 , shape=(1, len(lowercase__ )) , )
636
0
import unittest from transformers import MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING, is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class snake_case : @staticmethod def __lowercase( *a_ : List[str] , **a_ : str )-> str: """simple docstring""" pass @is_pipeline_test @require_torch @require_vision class snake_case ( unittest.TestCase ): lowercase_ = MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING def __lowercase( self : Dict , a_ : Dict , a_ : Optional[int] , a_ : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = pipeline('visual-question-answering' , model='hf-internal-testing/tiny-vilt-random-vqa' ) SCREAMING_SNAKE_CASE__ : List[str] = [ { 'image': Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ), 'question': 'How many cats are there?', }, { 'image': './tests/fixtures/tests_samples/COCO/000000039769.png', 'question': 'How many cats are there?', }, ] return vqa_pipeline, examples def __lowercase( self : List[Any] , a_ : Any , a_ : Tuple )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = vqa_pipeline(a_ , top_k=1 ) self.assertEqual( a_ , [ [{'score': ANY(a_ ), 'answer': ANY(a_ )}], [{'score': ANY(a_ ), 'answer': ANY(a_ )}], ] , ) @require_torch def __lowercase( self : List[Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = pipeline('visual-question-answering' , model='hf-internal-testing/tiny-vilt-random-vqa' ) SCREAMING_SNAKE_CASE__ : Any = './tests/fixtures/tests_samples/COCO/000000039769.png' SCREAMING_SNAKE_CASE__ : str = 'How many cats are there?' SCREAMING_SNAKE_CASE__ : str = vqa_pipeline(image=a_ , question='How many cats are there?' , top_k=2 ) self.assertEqual( a_ , [{'score': ANY(a_ ), 'answer': ANY(a_ )}, {'score': ANY(a_ ), 'answer': ANY(a_ )}] ) SCREAMING_SNAKE_CASE__ : List[str] = vqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( a_ , [{'score': ANY(a_ ), 'answer': ANY(a_ )}, {'score': ANY(a_ ), 'answer': ANY(a_ )}] ) @slow @require_torch def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = pipeline('visual-question-answering' , model='dandelin/vilt-b32-finetuned-vqa' ) SCREAMING_SNAKE_CASE__ : Optional[int] = './tests/fixtures/tests_samples/COCO/000000039769.png' SCREAMING_SNAKE_CASE__ : Dict = 'How many cats are there?' SCREAMING_SNAKE_CASE__ : Union[str, Any] = vqa_pipeline(image=a_ , question=a_ , top_k=2 ) self.assertEqual( nested_simplify(a_ , decimals=4 ) , [{'score': 0.8799, 'answer': '2'}, {'score': 0.296, 'answer': '1'}] ) SCREAMING_SNAKE_CASE__ : List[Any] = vqa_pipeline({'image': image, 'question': question} , top_k=2 ) self.assertEqual( nested_simplify(a_ , decimals=4 ) , [{'score': 0.8799, 'answer': '2'}, {'score': 0.296, 'answer': '1'}] ) SCREAMING_SNAKE_CASE__ : int = vqa_pipeline( [{'image': image, 'question': question}, {'image': image, 'question': question}] , top_k=2 ) self.assertEqual( nested_simplify(a_ , decimals=4 ) , [[{'score': 0.8799, 'answer': '2'}, {'score': 0.296, 'answer': '1'}]] * 2 , ) @require_tf @unittest.skip('Visual question answering not implemented in TF' ) def __lowercase( self : List[str] )-> Optional[int]: """simple docstring""" pass
715
import requests SCREAMING_SNAKE_CASE__ : int = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page['articles'] , 1 ): print(f'''{i}.) {article['title']}''' ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
636
0
from collections import OrderedDict from typing import TYPE_CHECKING, Any, Mapping, Optional from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...utils import logging if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType SCREAMING_SNAKE_CASE__ : Optional[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Optional[int] = { "microsoft/layoutlmv3-base": "https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json", } class snake_case ( UpperCamelCase_ ): lowercase_ = 'layoutlmv3' def __init__( self : Dict , a_ : List[Any]=5_0265 , a_ : Optional[int]=768 , a_ : List[Any]=12 , a_ : Any=12 , a_ : List[str]=3072 , a_ : int="gelu" , a_ : Any=0.1 , a_ : int=0.1 , a_ : Optional[Any]=512 , a_ : Any=2 , a_ : Optional[int]=0.02 , a_ : Tuple=1e-5 , a_ : Any=1 , a_ : Tuple=0 , a_ : Union[str, Any]=2 , a_ : List[Any]=1024 , a_ : Dict=128 , a_ : Tuple=128 , a_ : int=True , a_ : Optional[Any]=32 , a_ : List[Any]=128 , a_ : Union[str, Any]=64 , a_ : Tuple=256 , a_ : Union[str, Any]=True , a_ : Optional[Any]=True , a_ : List[Any]=True , a_ : List[str]=224 , a_ : Union[str, Any]=3 , a_ : Dict=16 , a_ : Tuple=None , **a_ : str , )-> Optional[int]: """simple docstring""" super().__init__( 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_ , initializer_range=a_ , layer_norm_eps=a_ , pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , **a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = max_ad_position_embeddings SCREAMING_SNAKE_CASE__ : List[str] = coordinate_size SCREAMING_SNAKE_CASE__ : Optional[int] = shape_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = has_relative_attention_bias SCREAMING_SNAKE_CASE__ : str = rel_pos_bins SCREAMING_SNAKE_CASE__ : Optional[Any] = max_rel_pos SCREAMING_SNAKE_CASE__ : Any = has_spatial_attention_bias SCREAMING_SNAKE_CASE__ : Tuple = rel_ad_pos_bins SCREAMING_SNAKE_CASE__ : int = max_rel_ad_pos SCREAMING_SNAKE_CASE__ : Optional[int] = text_embed SCREAMING_SNAKE_CASE__ : Optional[int] = visual_embed SCREAMING_SNAKE_CASE__ : Any = input_size SCREAMING_SNAKE_CASE__ : Tuple = num_channels SCREAMING_SNAKE_CASE__ : List[str] = patch_size SCREAMING_SNAKE_CASE__ : int = classifier_dropout class snake_case ( UpperCamelCase_ ): lowercase_ = version.parse('1.12' ) @property def __lowercase( self : int )-> Mapping[str, Mapping[int, str]]: """simple docstring""" # The order of inputs is different for question answering and sequence classification if self.task in ["question-answering", "sequence-classification"]: return OrderedDict( [ ('input_ids', {0: 'batch', 1: 'sequence'}), ('attention_mask', {0: 'batch', 1: 'sequence'}), ('bbox', {0: 'batch', 1: 'sequence'}), ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ] ) else: return OrderedDict( [ ('input_ids', {0: 'batch', 1: 'sequence'}), ('bbox', {0: 'batch', 1: 'sequence'}), ('attention_mask', {0: 'batch', 1: 'sequence'}), ('pixel_values', {0: 'batch', 1: 'num_channels'}), ] ) @property def __lowercase( self : Union[str, Any] )-> float: """simple docstring""" return 1e-5 @property def __lowercase( self : Optional[int] )-> int: """simple docstring""" return 12 def __lowercase( self : Optional[int] , a_ : "ProcessorMixin" , a_ : int = -1 , a_ : int = -1 , a_ : bool = False , a_ : Optional["TensorType"] = None , a_ : int = 3 , a_ : int = 40 , a_ : int = 40 , )-> Mapping[str, Any]: """simple docstring""" setattr(processor.image_processor , 'apply_ocr' , a_ ) # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX SCREAMING_SNAKE_CASE__ : Tuple = compute_effective_axis_dimension( a_ , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX SCREAMING_SNAKE_CASE__ : Dict = processor.tokenizer.num_special_tokens_to_add(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = compute_effective_axis_dimension( a_ , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=a_ ) # Generate dummy inputs according to compute batch and sequence SCREAMING_SNAKE_CASE__ : List[str] = [[' '.join([processor.tokenizer.unk_token] ) * seq_length]] * batch_size # Generate dummy bounding boxes SCREAMING_SNAKE_CASE__ : Union[str, Any] = [[[48, 84, 73, 128]]] * batch_size # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch) SCREAMING_SNAKE_CASE__ : List[str] = self._generate_dummy_images(a_ , a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = dict( processor( a_ , text=a_ , boxes=a_ , return_tensors=a_ , ) ) return inputs
716
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : Tuple = logging.get_logger() @dataclass class snake_case : lowercase_ = 42 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) def __lowercase( self : Dict , a_ : Dict , a_ : Tensor , a_ : Tensor )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = len(list(m.modules() ) ) == 1 or isinstance(a_ , nn.Convad ) or isinstance(a_ , nn.BatchNormad ) if has_not_submodules: self.traced.append(a_ ) def __call__( self : Tuple , a_ : Tensor )-> Any: """simple docstring""" for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(a_ ) [x.remove() for x in self.handles] return self @property def __lowercase( self : Tuple )-> int: """simple docstring""" # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda a_ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class snake_case : lowercase_ = 42 lowercase_ = 42 lowercase_ = 1 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = True def __call__( self : List[Any] , a_ : Tensor )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = Tracker(self.dest )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : Optional[int] = Tracker(self.src )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : List[str] = list(filter(lambda a_ : type(a_ ) not in self.src_skip , a_ ) ) SCREAMING_SNAKE_CASE__ : Dict = list(filter(lambda a_ : type(a_ ) not in self.dest_skip , a_ ) ) if len(a_ ) != len(a_ ) and self.raise_if_mismatch: raise Exception( F'''Numbers of operations are different. Source module has {len(a_ )} operations while''' F''' destination module has {len(a_ )}.''' ) for dest_m, src_m in zip(a_ , a_ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F'''Transfered from={src_m} to={dest_m}''' ) class snake_case ( nn.Module ): def __init__( self : List[Any] , a_ : nn.Module )-> Dict: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : List[Tuple[str, nn.Module]] = [] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), F'''Unexpected layer name {k}''' SCREAMING_SNAKE_CASE__ : Optional[Any] = len(a_ ) + 1 feature_blocks.append((F'''res{block_index}''', v) ) SCREAMING_SNAKE_CASE__ : Any = nn.ModuleDict(a_ ) def __lowercase( self : Tuple , a_ : Tensor )-> Dict: """simple docstring""" return get_trunk_forward_outputs( a_ , out_feat_keys=a_ , feature_blocks=self._feature_blocks , ) class snake_case ( UpperCamelCase_ ): def __lowercase( self : Optional[Any] , a_ : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Union[str, Any] , a_ : str )-> Callable[[], Tuple[nn.Module, Dict]]: """simple docstring""" # default to timm! if x not in self: SCREAMING_SNAKE_CASE__ : Any = self.convert_name_to_timm(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = partial(lambda: (timm.create_model(a_ , pretrained=a_ ).eval(), None) ) else: SCREAMING_SNAKE_CASE__ : List[str] = super().__getitem__(a_ ) return val class snake_case ( UpperCamelCase_ ): def __getitem__( self : Any , a_ : str )-> Callable[[], nn.Module]: """simple docstring""" if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE__ : Any = RegNetModel else: SCREAMING_SNAKE_CASE__ : Any = RegNetForImageClassification return val def _a ( lowercase__ : Any , lowercase__ : Optional[Any] , lowercase__ : List[Tuple[str, str]] ): '''simple docstring''' for from_key, to_key in keys: SCREAMING_SNAKE_CASE__ : Tuple = from_state_dict[from_key].clone() print(f'''Copied key={from_key} to={to_key}''' ) return to_state_dict def _a ( lowercase__ : str , lowercase__ : Callable[[], nn.Module] , lowercase__ : Callable[[], nn.Module] , lowercase__ : RegNetConfig , lowercase__ : Path , lowercase__ : bool = True , ): '''simple docstring''' print(f'''Converting {name}...''' ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = from_model_func() SCREAMING_SNAKE_CASE__ : int = our_model_func(lowercase__ ).eval() SCREAMING_SNAKE_CASE__ : List[Any] = ModuleTransfer(src=lowercase__ , dest=lowercase__ , raise_if_mismatch=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.randn((1, 3, 2_24, 2_24) ) module_transfer(lowercase__ ) if from_state_dict is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : int = [('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')] SCREAMING_SNAKE_CASE__ : Optional[Any] = manually_copy_vissl_head(lowercase__ , our_model.state_dict() , lowercase__ ) our_model.load_state_dict(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = our_model(lowercase__ , output_hidden_states=lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = ( our_outputs.logits if isinstance(lowercase__ , lowercase__ ) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE__ : List[Any] = from_model(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = from_output[-1] if type(lowercase__ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : List[Any] = our_outputs.hidden_states[-1] assert torch.allclose(lowercase__ , lowercase__ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add model' , use_temp_dir=lowercase__ , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 2_24 if 'seer' not in name else 3_84 # we can use the convnext one SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' , size=lowercase__ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add image processor' , use_temp_dir=lowercase__ , ) print(f'''Pushed {name}''' ) def _a ( lowercase__ : Path , lowercase__ : str = None , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = 'imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE__ : Tuple = 10_00 SCREAMING_SNAKE_CASE__ : Tuple = (1, num_labels) SCREAMING_SNAKE_CASE__ : str = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE__ : List[str] = json.load(open(cached_download(hf_hub_url(lowercase__ , lowercase__ , repo_type='dataset' ) ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : str = idalabel SCREAMING_SNAKE_CASE__ : Tuple = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Any = partial(lowercase__ , num_labels=lowercase__ , idalabel=lowercase__ , labelaid=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = { 'regnet-x-002': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 , layer_type='x' ), 'regnet-x-004': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 1_60, 3_84] , groups_width=16 , layer_type='x' ), 'regnet-x-006': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 2_40, 5_28] , groups_width=24 , layer_type='x' ), 'regnet-x-008': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 1_28, 2_88, 6_72] , groups_width=16 , layer_type='x' ), 'regnet-x-016': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 1_68, 4_08, 9_12] , groups_width=24 , layer_type='x' ), 'regnet-x-032': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 1_92, 4_32, 10_08] , groups_width=48 , layer_type='x' ), 'regnet-x-040': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 2_40, 5_60, 13_60] , groups_width=40 , layer_type='x' ), 'regnet-x-064': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 3_92, 7_84, 16_24] , groups_width=56 , layer_type='x' ), 'regnet-x-080': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 2_40, 7_20, 19_20] , groups_width=1_20 , layer_type='x' ), 'regnet-x-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 , layer_type='x' ), 'regnet-x-160': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[2_56, 5_12, 8_96, 20_48] , groups_width=1_28 , layer_type='x' ), 'regnet-x-320': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[3_36, 6_72, 13_44, 25_20] , groups_width=1_68 , layer_type='x' ), # y variant 'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 ), 'regnet-y-004': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 1_04, 2_08, 4_40] , groups_width=8 ), 'regnet-y-006': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 1_12, 2_56, 6_08] , groups_width=16 ), 'regnet-y-008': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 1_28, 3_20, 7_68] , groups_width=16 ), 'regnet-y-016': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 1_20, 3_36, 8_88] , groups_width=24 ), 'regnet-y-032': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 2_16, 5_76, 15_12] , groups_width=24 ), 'regnet-y-040': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[1_28, 1_92, 5_12, 10_88] , groups_width=64 ), 'regnet-y-064': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[1_44, 2_88, 5_76, 12_96] , groups_width=72 ), 'regnet-y-080': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 4_48, 8_96, 20_16] , groups_width=56 ), 'regnet-y-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 ), 'regnet-y-160': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[2_24, 4_48, 12_32, 30_24] , groups_width=1_12 ), 'regnet-y-320': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer': RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer': RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), # finetuned on imagenet 'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), } SCREAMING_SNAKE_CASE__ : List[Any] = NameToOurModelFuncMap() SCREAMING_SNAKE_CASE__ : Dict = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowercase__ : str , lowercase__ : Callable[[], nn.Module] ) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(lowercase__ , model_dir=str(lowercase__ ) , map_location='cpu' ) SCREAMING_SNAKE_CASE__ : Tuple = model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE__ : str = files['classy_state_dict']['base_model']['model'] SCREAMING_SNAKE_CASE__ : str = model_state_dict['trunk'] model.load_state_dict(lowercase__ ) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : int = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) # IN1K finetuned SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) if model_name: convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , lowercase__ , lowercase__ , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , lowercase__ , lowercase__ , lowercase__ , ) return config, expected_shape if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : Path = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
636
0
'''simple docstring''' import unittest from transformers import AutoTokenizer, FalconConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( FalconForCausalLM, FalconForQuestionAnswering, FalconForSequenceClassification, FalconForTokenClassification, FalconModel, ) class snake_case : def __init__( self : Any , a_ : int , a_ : Union[str, Any]=3 , a_ : int=7 , a_ : List[Any]=True , a_ : Dict=True , a_ : Union[str, Any]=False , a_ : List[str]=True , a_ : int=99 , a_ : Any=32 , a_ : Tuple=5 , a_ : List[Any]=4 , a_ : str=37 , a_ : int="gelu" , a_ : Any=0.1 , a_ : Optional[Any]=0.1 , a_ : int=512 , a_ : str=16 , a_ : List[str]=2 , a_ : Dict=0.02 , a_ : str=3 , a_ : Optional[Any]=4 , a_ : Optional[Any]=None , )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = parent SCREAMING_SNAKE_CASE__ : Any = batch_size SCREAMING_SNAKE_CASE__ : Dict = seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = is_training SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_input_mask SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_token_type_ids SCREAMING_SNAKE_CASE__ : Dict = use_labels SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE__ : List[Any] = hidden_size SCREAMING_SNAKE_CASE__ : List[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : int = intermediate_size SCREAMING_SNAKE_CASE__ : Dict = hidden_act SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : str = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Any = max_position_embeddings SCREAMING_SNAKE_CASE__ : Union[str, Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : Dict = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Optional[Any] = initializer_range SCREAMING_SNAKE_CASE__ : List[Any] = num_labels SCREAMING_SNAKE_CASE__ : Tuple = num_choices SCREAMING_SNAKE_CASE__ : Tuple = scope def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : List[Any] = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : List[Any] = None SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : Tuple = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase( self : List[Any] )-> Dict: """simple docstring""" return FalconConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a_ , initializer_range=self.initializer_range , pad_token_id=1 , new_decoder_architecture=a_ , ) def __lowercase( self : int , a_ : Tuple , a_ : List[Any] , a_ : str , a_ : str , a_ : Dict , a_ : List[Any] , a_ : Any )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = FalconModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ , attention_mask=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : Tuple , a_ : Optional[Any] , a_ : Tuple , a_ : Any , a_ : Tuple , a_ : Optional[int] , a_ : Optional[int] , a_ : int , a_ : Union[str, Any] , a_ : Dict , )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = True SCREAMING_SNAKE_CASE__ : Optional[int] = FalconModel(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model( a_ , attention_mask=a_ , encoder_hidden_states=a_ , encoder_attention_mask=a_ , ) SCREAMING_SNAKE_CASE__ : Any = model( a_ , attention_mask=a_ , encoder_hidden_states=a_ , ) SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , attention_mask=a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : Optional[Any] , a_ : List[Any] , a_ : Optional[int] , a_ : int , a_ : Dict , a_ : Optional[int] , a_ : Tuple , a_ : Optional[Any] , a_ : Tuple , a_ : List[str] , )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = FalconForCausalLM(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowercase( self : Any , a_ : Optional[Any] , a_ : List[str] , a_ : Union[str, Any] , a_ : Any , a_ : Dict , a_ : Any , a_ : Dict , a_ : List[str] , a_ : Optional[Any] , )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : List[Any] = FalconForCausalLM(config=a_ ) model.to(a_ ) model.eval() # first forward pass SCREAMING_SNAKE_CASE__ : Dict = model( a_ , attention_mask=a_ , encoder_hidden_states=a_ , encoder_attention_mask=a_ , use_cache=a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Dict = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE__ : Any = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : Tuple = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([input_mask, next_mask] , dim=-1 ) SCREAMING_SNAKE_CASE__ : List[Any] = model( a_ , attention_mask=a_ , encoder_hidden_states=a_ , encoder_attention_mask=a_ , output_hidden_states=a_ , )['hidden_states'][0] SCREAMING_SNAKE_CASE__ : List[str] = model( a_ , attention_mask=a_ , encoder_hidden_states=a_ , encoder_attention_mask=a_ , past_key_values=a_ , output_hidden_states=a_ , )['hidden_states'][0] # select random slice SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : Dict = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : Union[str, Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.prepare_config_and_inputs() ( SCREAMING_SNAKE_CASE__ ) : Dict = config_and_inputs SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( ( FalconModel, FalconForCausalLM, FalconForSequenceClassification, FalconForTokenClassification, FalconForQuestionAnswering, ) if is_torch_available() else () ) lowercase_ = (FalconForCausalLM,) if is_torch_available() else () lowercase_ = ( { 'feature-extraction': FalconModel, 'text-classification': FalconForSequenceClassification, 'text-generation': FalconForCausalLM, 'question-answering': FalconForQuestionAnswering, 'token-classification': FalconForTokenClassification, 'zero-shot': FalconForSequenceClassification, } if is_torch_available() else {} ) lowercase_ = False lowercase_ = False def __lowercase( self : Tuple )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = FalconModelTester(self ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ConfigTester(self , config_class=a_ , hidden_size=37 ) def __lowercase( self : int )-> Optional[int]: """simple docstring""" self.config_tester.run_common_tests() def __lowercase( self : List[str] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() for alibi in [True, False]: SCREAMING_SNAKE_CASE__ : Union[str, Any] = alibi self.model_tester.create_and_check_model(a_ , *a_ ) def __lowercase( self : int )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : int = 3 SCREAMING_SNAKE_CASE__ : Optional[int] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : List[Any] = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Any = FalconForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[int] = 3 SCREAMING_SNAKE_CASE__ : Optional[Any] = 'single_label_classification' SCREAMING_SNAKE_CASE__ : Tuple = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : str = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Any = FalconForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Any = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Optional[Any] = FalconForCausalLM(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , use_cache=a_ ) SCREAMING_SNAKE_CASE__ : str = input_ids.shape[0] SCREAMING_SNAKE_CASE__ : Optional[int] = model._convert_to_rw_cache(result.past_key_values ) SCREAMING_SNAKE_CASE__ : Tuple = model._convert_cache_to_standard_format(a_ , a_ ) for layer in range(len(a_ ) ): for tensor_idx in range(2 ): self.assertTrue(rw_cache[layer][tensor_idx].ndim == 3 ) self.assertTrue(result.past_key_values[layer][tensor_idx].ndim == 4 ) self.assertTrue( torch.all(result.past_key_values[layer][tensor_idx] == standard_cache[layer][tensor_idx] ) ) def __lowercase( self : int )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Union[str, Any] = 3 SCREAMING_SNAKE_CASE__ : Tuple = 'multi_label_classification' SCREAMING_SNAKE_CASE__ : int = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : int = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : Any = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) SCREAMING_SNAKE_CASE__ : Any = FalconForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __lowercase( self : Tuple )-> Optional[int]: """simple docstring""" # Falcon can have different numbers of KV-heads than the number of query heads, so we need # to override this test to use the right head counts. for model_class in self.all_generative_model_classes: SCREAMING_SNAKE_CASE__ : Any = self.model_tester.prepare_config_and_inputs_for_common() # If it doesn't support cache, pass the test if not hasattr(a_ , 'use_cache' ): return SCREAMING_SNAKE_CASE__ : List[Any] = model_class(a_ ).to(a_ ) if "use_cache" not in inputs: SCREAMING_SNAKE_CASE__ : str = True SCREAMING_SNAKE_CASE__ : List[Any] = model(**a_ ) # If "past_key_values" is not returned, pass the test (e.g. RWKV uses a different cache name and format) if "past_key_values" not in outputs: return SCREAMING_SNAKE_CASE__ : Any = ( getattr(a_ , 'decoder_layers' , a_ ) or getattr(a_ , 'num_decoder_layers' , a_ ) or config.num_hidden_layers ) SCREAMING_SNAKE_CASE__ : Dict = getattr(a_ , 'num_kv_heads' , config.num_attention_heads ) SCREAMING_SNAKE_CASE__ : List[Any] = getattr(a_ , 'd_model' , config.hidden_size ) SCREAMING_SNAKE_CASE__ : List[str] = embed_dim // num_attention_heads SCREAMING_SNAKE_CASE__ : int = outputs['past_key_values'] self.assertEqual(len(a_ ) , a_ ) SCREAMING_SNAKE_CASE__ : Dict = inputs['input_ids'].shape for i in range(a_ ): if config.new_decoder_architecture: SCREAMING_SNAKE_CASE__ : Optional[int] = config.num_attention_heads elif config.multi_query: SCREAMING_SNAKE_CASE__ : Dict = 1 self.assertEqual(len(past_kv[0] ) , 2 ) # K V for the decoder = 2 self.assertEqual( past_kv[i][0].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) ) self.assertEqual( past_kv[i][1].shape , (batch_size, num_attention_heads, seq_length, per_head_embed_dim) ) @require_torch class snake_case ( unittest.TestCase ): @slow def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = AutoTokenizer.from_pretrained('Rocketknight1/falcon-rw-1b' ) SCREAMING_SNAKE_CASE__ : Tuple = FalconForCausalLM.from_pretrained('Rocketknight1/falcon-rw-1b' ) model.eval() model.to(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer('My favorite food is' , return_tensors='pt' ).to(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( 'My favorite food is pizza. I love it so much that I have a pizza party every year for my birthday.' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model.generate(**a_ , do_sample=a_ , max_new_tokens=19 ) SCREAMING_SNAKE_CASE__ : str = tokenizer.batch_decode(a_ )[0] self.assertEqual(a_ , a_ ) @slow def __lowercase( self : Optional[int] )-> int: """simple docstring""" # The big models are way too big for the CI, so we use tiny random models that resemble their # architectures but with much smaller and fewer layers for repo in ["Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b"]: SCREAMING_SNAKE_CASE__ : Optional[Any] = AutoTokenizer.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Dict = FalconForCausalLM.from_pretrained(a_ ) model.eval() model.to(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = tokenizer('My favorite food is' , return_tensors='pt' ).to(a_ ) # We just test that these run without errors - the models are randomly initialized # and so the actual text outputs will be garbage model.generate(**a_ , do_sample=a_ , max_new_tokens=4 ) model.generate(**a_ , do_sample=a_ , max_new_tokens=4 ) model.generate(**a_ , num_beams=2 , max_new_tokens=4 ) @slow def __lowercase( self : List[Any] )-> Dict: """simple docstring""" # The big models are way too big for the CI, so we use tiny random models that resemble their # architectures but with much smaller and fewer layers with torch.no_grad(): for repo in [ "Rocketknight1/falcon-rw-1b", "Rocketknight1/tiny-random-falcon-7b", "Rocketknight1/tiny-random-falcon-40b", ]: SCREAMING_SNAKE_CASE__ : List[Any] = AutoTokenizer.from_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = FalconForCausalLM.from_pretrained(a_ ) model.eval() model.to(device=a_ ) SCREAMING_SNAKE_CASE__ : Any = tokenizer('My favorite food is' , return_tensors='pt' ).to(a_ ) # Test results are the same with and without cache SCREAMING_SNAKE_CASE__ : Dict = model.generate(**a_ , do_sample=a_ , max_new_tokens=20 , use_cache=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = model.generate(**a_ , do_sample=a_ , max_new_tokens=20 , use_cache=a_ ) self.assertTrue((outputs_cache - outputs_no_cache).sum().item() == 0 )
717
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'OwlViTImageProcessor' lowercase_ = ('CLIPTokenizer', 'CLIPTokenizerFast') def __init__( self : List[str] , a_ : List[Any]=None , a_ : str=None , **a_ : Any )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop('feature_extractor' ) SCREAMING_SNAKE_CASE__ : List[str] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(a_ , a_ ) def __call__( self : Any , a_ : Optional[int]=None , a_ : Tuple=None , a_ : List[Any]=None , a_ : Tuple="max_length" , a_ : str="np" , **a_ : Any )-> int: """simple docstring""" if text is None and query_images is None and images is None: raise ValueError( 'You have to specify at least one text or query image or image. All three cannot be none.' ) if text is not None: if isinstance(a_ , a_ ) or (isinstance(a_ , a_ ) and not isinstance(text[0] , a_ )): SCREAMING_SNAKE_CASE__ : Tuple = [self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ )] elif isinstance(a_ , a_ ) and isinstance(text[0] , a_ ): SCREAMING_SNAKE_CASE__ : Any = [] # Maximum number of queries across batch SCREAMING_SNAKE_CASE__ : str = max([len(a_ ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(a_ ) != max_num_queries: SCREAMING_SNAKE_CASE__ : Tuple = t + [' '] * (max_num_queries - len(a_ )) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ ) encodings.append(a_ ) else: raise TypeError('Input text should be a string, a list of strings or a nested list of strings' ) if return_tensors == "np": SCREAMING_SNAKE_CASE__ : Dict = np.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : List[Any] = np.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jnp.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : int = torch.cat([encoding['input_ids'] for encoding in encodings] , dim=0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([encoding['attention_mask'] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf SCREAMING_SNAKE_CASE__ : str = tf.stack([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Dict = tf.stack([encoding['attention_mask'] for encoding in encodings] , axis=0 ) else: raise ValueError('Target return tensor type could not be returned' ) SCREAMING_SNAKE_CASE__ : Optional[int] = BatchEncoding() SCREAMING_SNAKE_CASE__ : List[str] = input_ids SCREAMING_SNAKE_CASE__ : Tuple = attention_mask if query_images is not None: SCREAMING_SNAKE_CASE__ : Any = BatchEncoding() SCREAMING_SNAKE_CASE__ : Dict = self.image_processor( a_ , return_tensors=a_ , **a_ ).pixel_values SCREAMING_SNAKE_CASE__ : Dict = query_pixel_values if images is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ : Dict = image_features.pixel_values return encoding elif query_images is not None and images is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def __lowercase( self : str , *a_ : List[str] , **a_ : int )-> List[Any]: """simple docstring""" return self.image_processor.post_process(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : List[str] , **a_ : str )-> Union[str, Any]: """simple docstring""" return self.image_processor.post_process_object_detection(*a_ , **a_ ) def __lowercase( self : Optional[Any] , *a_ : str , **a_ : Dict )-> Optional[int]: """simple docstring""" return self.image_processor.post_process_image_guided_detection(*a_ , **a_ ) def __lowercase( self : Optional[int] , *a_ : Tuple , **a_ : Tuple )-> Optional[Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : Tuple , **a_ : Tuple )-> List[str]: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property def __lowercase( self : Tuple )-> Any: """simple docstring""" warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , a_ , ) return self.image_processor_class @property def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , a_ , ) return self.image_processor
636
0
from __future__ import annotations class snake_case : def __init__( self : Any , a_ : int )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = data SCREAMING_SNAKE_CASE__ : Node | None = None SCREAMING_SNAKE_CASE__ : Node | None = None def _a ( lowercase__ : Node | None ): # In Order traversal of the tree '''simple docstring''' if tree: display(tree.left ) print(tree.data ) display(tree.right ) def _a ( lowercase__ : Node | None ): '''simple docstring''' return 1 + max(depth_of_tree(tree.left ) , depth_of_tree(tree.right ) ) if tree else 0 def _a ( lowercase__ : Node ): '''simple docstring''' if not tree: return True if tree.left and tree.right: return is_full_binary_tree(tree.left ) and is_full_binary_tree(tree.right ) else: return not tree.left and not tree.right def _a ( ): # Main function for testing. '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = Node(1 ) SCREAMING_SNAKE_CASE__ : Any = Node(2 ) SCREAMING_SNAKE_CASE__ : str = Node(3 ) SCREAMING_SNAKE_CASE__ : int = Node(4 ) SCREAMING_SNAKE_CASE__ : Optional[int] = Node(5 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = Node(6 ) SCREAMING_SNAKE_CASE__ : Dict = Node(7 ) SCREAMING_SNAKE_CASE__ : List[str] = Node(8 ) SCREAMING_SNAKE_CASE__ : int = Node(9 ) print(is_full_binary_tree(lowercase__ ) ) print(depth_of_tree(lowercase__ ) ) print('Tree is: ' ) display(lowercase__ ) if __name__ == "__main__": main()
718
class snake_case ( UpperCamelCase_ ): pass class snake_case ( UpperCamelCase_ ): pass class snake_case : def __init__( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [ [], [], [], ] def __lowercase( self : int , a_ : int , a_ : int )-> None: """simple docstring""" try: if len(self.queues[priority] ) >= 100: raise OverflowError('Maximum queue size is 100' ) self.queues[priority].append(a_ ) except IndexError: raise ValueError('Valid priorities are 0, 1, and 2' ) def __lowercase( self : int )-> int: """simple docstring""" for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError('All queues are empty' ) def __str__( self : Any )-> str: """simple docstring""" return "\n".join(F'''Priority {i}: {q}''' for i, q in enumerate(self.queues ) ) class snake_case : def __init__( self : Union[str, Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [] def __lowercase( self : List[str] , a_ : int )-> None: """simple docstring""" if len(self.queue ) == 100: raise OverFlowError('Maximum queue size is 100' ) self.queue.append(a_ ) def __lowercase( self : int )-> int: """simple docstring""" if not self.queue: raise UnderFlowError('The queue is empty' ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = min(self.queue ) self.queue.remove(a_ ) return data def __str__( self : List[str] )-> str: """simple docstring""" return str(self.queue ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 1_00 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 1_28 ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(1_00 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(1_28 ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
636
0
from __future__ import annotations from collections.abc import Iterator class snake_case : def __init__( self : Union[str, Any] , a_ : int )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = value SCREAMING_SNAKE_CASE__ : Node | None = None SCREAMING_SNAKE_CASE__ : Node | None = None class snake_case : def __init__( self : Any , a_ : Node )-> None: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = tree def __lowercase( self : List[str] , a_ : Node | None )-> int: """simple docstring""" if node is None: return 0 return node.value + ( self.depth_first_search(node.left ) + self.depth_first_search(node.right ) ) def __iter__( self : Any )-> Iterator[int]: """simple docstring""" yield self.depth_first_search(self.tree ) if __name__ == "__main__": import doctest doctest.testmod()
719
from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def _a ( lowercase__ : List[str] ): '''simple docstring''' if not is_accelerate_available(): return method SCREAMING_SNAKE_CASE__ : str = version.parse(accelerate.__version__ ).base_version if version.parse(lowercase__ ) < version.parse('0.17.0' ): return method def wrapper(self : Optional[int] , *lowercase__ : int , **lowercase__ : Tuple ): if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ): self._hf_hook.pre_forward(self ) return method(self , *lowercase__ , **lowercase__ ) return wrapper
636
0
import argparse import json import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from torchvision import transforms from transformers import BitImageProcessor, FocalNetConfig, FocalNetForImageClassification from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = [2, 2, 6, 2] if 'tiny' in model_name else [2, 2, 18, 2] SCREAMING_SNAKE_CASE__ : Any = True if 'large' in model_name or 'huge' in model_name else False SCREAMING_SNAKE_CASE__ : List[Any] = True if 'large' in model_name or 'huge' in model_name else False SCREAMING_SNAKE_CASE__ : Any = True if 'large' in model_name or 'huge' in model_name else False if "large" in model_name or "xlarge" in model_name or "huge" in model_name: if "fl3" in model_name: SCREAMING_SNAKE_CASE__ : int = [3, 3, 3, 3] SCREAMING_SNAKE_CASE__ : Optional[int] = [5, 5, 5, 5] elif "fl4" in model_name: SCREAMING_SNAKE_CASE__ : Optional[int] = [4, 4, 4, 4] SCREAMING_SNAKE_CASE__ : Tuple = [3, 3, 3, 3] if "tiny" in model_name or "small" in model_name or "base" in model_name: SCREAMING_SNAKE_CASE__ : List[str] = [3, 3, 3, 3] if "lrf" in model_name: SCREAMING_SNAKE_CASE__ : Dict = [3, 3, 3, 3] else: SCREAMING_SNAKE_CASE__ : Tuple = [2, 2, 2, 2] if "tiny" in model_name: SCREAMING_SNAKE_CASE__ : Tuple = 96 elif "small" in model_name: SCREAMING_SNAKE_CASE__ : Tuple = 96 elif "base" in model_name: SCREAMING_SNAKE_CASE__ : Any = 1_28 elif "large" in model_name: SCREAMING_SNAKE_CASE__ : List[Any] = 1_92 elif "xlarge" in model_name: SCREAMING_SNAKE_CASE__ : str = 2_56 elif "huge" in model_name: SCREAMING_SNAKE_CASE__ : Dict = 3_52 # set label information SCREAMING_SNAKE_CASE__ : Dict = 'huggingface/label-files' if "large" in model_name or "huge" in model_name: SCREAMING_SNAKE_CASE__ : str = 'imagenet-22k-id2label.json' else: SCREAMING_SNAKE_CASE__ : str = 'imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE__ : Union[str, Any] = json.load(open(hf_hub_download(lowercase__ , lowercase__ , repo_type='dataset' ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Tuple = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : List[Any] = FocalNetConfig( embed_dim=lowercase__ , depths=lowercase__ , focal_levels=lowercase__ , focal_windows=lowercase__ , use_conv_embed=lowercase__ , idalabel=lowercase__ , labelaid=lowercase__ , use_post_layernorm=lowercase__ , use_layerscale=lowercase__ , ) return config def _a ( lowercase__ : List[Any] ): '''simple docstring''' if "patch_embed.proj" in name: SCREAMING_SNAKE_CASE__ : List[str] = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: SCREAMING_SNAKE_CASE__ : Union[str, Any] = name.replace('patch_embed.norm' , 'embeddings.norm' ) if "layers" in name: SCREAMING_SNAKE_CASE__ : List[str] = 'encoder.' + name if "encoder.layers" in name: SCREAMING_SNAKE_CASE__ : Optional[Any] = name.replace('encoder.layers' , 'encoder.stages' ) if "downsample.proj" in name: SCREAMING_SNAKE_CASE__ : List[Any] = name.replace('downsample.proj' , 'downsample.projection' ) if "blocks" in name: SCREAMING_SNAKE_CASE__ : Tuple = name.replace('blocks' , 'layers' ) if "modulation.f.weight" in name or "modulation.f.bias" in name: SCREAMING_SNAKE_CASE__ : List[str] = name.replace('modulation.f' , 'modulation.projection_in' ) if "modulation.h.weight" in name or "modulation.h.bias" in name: SCREAMING_SNAKE_CASE__ : Dict = name.replace('modulation.h' , 'modulation.projection_context' ) if "modulation.proj.weight" in name or "modulation.proj.bias" in name: SCREAMING_SNAKE_CASE__ : Optional[Any] = name.replace('modulation.proj' , 'modulation.projection_out' ) if name == "norm.weight": SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'layernorm.weight' if name == "norm.bias": SCREAMING_SNAKE_CASE__ : int = 'layernorm.bias' if "head" in name: SCREAMING_SNAKE_CASE__ : int = name.replace('head' , 'classifier' ) else: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'focalnet.' + name return name def _a ( lowercase__ : Optional[int] , lowercase__ : Union[str, Any] , lowercase__ : Any=False ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = { 'focalnet-tiny': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_srf.pth', 'focalnet-tiny-lrf': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_tiny_lrf.pth', 'focalnet-small': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_srf.pth', 'focalnet-small-lrf': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_small_lrf.pth', 'focalnet-base': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_srf.pth', 'focalnet-base-lrf': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_base_lrf.pth', 'focalnet-large-lrf-fl3': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384.pth', 'focalnet-large-lrf-fl4': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_large_lrf_384_fl4.pth', 'focalnet-xlarge-lrf-fl3': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384.pth', 'focalnet-xlarge-lrf-fl4': 'https://projects4jw.blob.core.windows.net/focalnet/release/classification/focalnet_xlarge_lrf_384_fl4.pth', } # fmt: on SCREAMING_SNAKE_CASE__ : List[str] = model_name_to_url[model_name] print('Checkpoint URL: ' , lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.hub.load_state_dict_from_url(lowercase__ , map_location='cpu' )['model'] # rename keys for key in state_dict.copy().keys(): SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = val SCREAMING_SNAKE_CASE__ : Optional[int] = get_focalnet_config(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = FocalNetForImageClassification(lowercase__ ) model.eval() # load state dict model.load_state_dict(lowercase__ ) # verify conversion SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'http://images.cocodataset.org/val2017/000000039769.jpg' SCREAMING_SNAKE_CASE__ : int = BitImageProcessor( do_resize=lowercase__ , size={'shortest_edge': 2_56} , resample=PILImageResampling.BILINEAR , do_center_crop=lowercase__ , crop_size=2_24 , do_normalize=lowercase__ , image_mean=lowercase__ , image_std=lowercase__ , ) SCREAMING_SNAKE_CASE__ : Tuple = Image.open(requests.get(lowercase__ , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Any = processor(images=lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = transforms.Compose( [ transforms.Resize(2_56 ), transforms.CenterCrop(2_24 ), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] ), ] ) SCREAMING_SNAKE_CASE__ : int = image_transforms(lowercase__ ).unsqueeze(0 ) # verify pixel_values assert torch.allclose(inputs.pixel_values , lowercase__ , atol=1E-4 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(**lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = outputs.logits.argmax(-1 ).item() print('Predicted class:' , model.config.idalabel[predicted_class_idx] ) print('First values of logits:' , outputs.logits[0, :3] ) if model_name == "focalnet-tiny": SCREAMING_SNAKE_CASE__ : Any = torch.tensor([0.2166, -0.4368, 0.2191] ) elif model_name == "focalnet-tiny-lrf": SCREAMING_SNAKE_CASE__ : int = torch.tensor([1.1669, 0.0125, -0.1695] ) elif model_name == "focalnet-small": SCREAMING_SNAKE_CASE__ : int = torch.tensor([0.4917, -0.0430, 0.1341] ) elif model_name == "focalnet-small-lrf": SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor([-0.2588, -0.5342, -0.2331] ) elif model_name == "focalnet-base": SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([-0.1655, -0.4090, -0.1730] ) elif model_name == "focalnet-base-lrf": SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([0.5306, -0.0483, -0.3928] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) print('Looks ok!' ) if pytorch_dump_folder_path is not None: print(f'''Saving model and processor of {model_name} to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase__ ) processor.save_pretrained(lowercase__ ) if push_to_hub: print(f'''Pushing model and processor of {model_name} to the hub...''' ) model.push_to_hub(f'''{model_name}''' ) processor.push_to_hub(f'''{model_name}''' ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default="focalnet-tiny", type=str, help="Name of the FocalNet model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) parser.add_argument( "--push_to_hub", action="store_true", help="Whether to push the model and processor to the hub.", ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() convert_focalnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
720
import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def _a ( lowercase__ : int ): '''simple docstring''' if is_torch_version('<' , '2.0.0' ) or not hasattr(lowercase__ , '_dynamo' ): return False return isinstance(lowercase__ , torch._dynamo.eval_frame.OptimizedModule ) def _a ( lowercase__ : Optional[Any] , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) SCREAMING_SNAKE_CASE__ : Dict = is_compiled_module(lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : Tuple = model SCREAMING_SNAKE_CASE__ : int = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : Any = model.module if not keep_fpaa_wrapper: SCREAMING_SNAKE_CASE__ : List[Any] = getattr(lowercase__ , 'forward' ) SCREAMING_SNAKE_CASE__ : str = model.__dict__.pop('_original_forward' , lowercase__ ) if original_forward is not None: while hasattr(lowercase__ , '__wrapped__' ): SCREAMING_SNAKE_CASE__ : Dict = forward.__wrapped__ if forward == original_forward: break SCREAMING_SNAKE_CASE__ : Dict = forward if getattr(lowercase__ , '_converted_to_transformer_engine' , lowercase__ ): convert_model(lowercase__ , to_transformer_engine=lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : List[Any] = model SCREAMING_SNAKE_CASE__ : Optional[Any] = compiled_model return model def _a ( ): '''simple docstring''' PartialState().wait_for_everyone() def _a ( lowercase__ : str , lowercase__ : Optional[Any] ): '''simple docstring''' if PartialState().distributed_type == DistributedType.TPU: xm.save(lowercase__ , lowercase__ ) elif PartialState().local_process_index == 0: torch.save(lowercase__ , lowercase__ ) @contextmanager def _a ( **lowercase__ : str ): '''simple docstring''' for key, value in kwargs.items(): SCREAMING_SNAKE_CASE__ : int = str(lowercase__ ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if not hasattr(lowercase__ , '__qualname__' ) and not hasattr(lowercase__ , '__name__' ): SCREAMING_SNAKE_CASE__ : Any = getattr(lowercase__ , '__class__' , lowercase__ ) if hasattr(lowercase__ , '__qualname__' ): return obj.__qualname__ if hasattr(lowercase__ , '__name__' ): return obj.__name__ return str(lowercase__ ) def _a ( lowercase__ : List[str] , lowercase__ : List[Any] ): '''simple docstring''' for key, value in source.items(): if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : List[str] = destination.setdefault(lowercase__ , {} ) merge_dicts(lowercase__ , lowercase__ ) else: SCREAMING_SNAKE_CASE__ : List[Any] = value return destination def _a ( lowercase__ : int = None ): '''simple docstring''' if port is None: SCREAMING_SNAKE_CASE__ : int = 2_95_00 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(('localhost', port) ) == 0
636
0
from sklearn.metrics import fa_score import datasets SCREAMING_SNAKE_CASE__ : Optional[Any] = "\nThe F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:\nF1 = 2 * (precision * recall) / (precision + recall)\n" SCREAMING_SNAKE_CASE__ : Any = "\nArgs:\n predictions (`list` of `int`): Predicted labels.\n references (`list` of `int`): Ground truth labels.\n labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.\n pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.\n\n - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.\n - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.\n - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.\n\nExamples:\n\n Example 1-A simple binary example\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n >>> print(results)\n {'f1': 0.5}\n\n Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n >>> print(round(results['f1'], 2))\n 0.67\n\n Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n >>> print(round(results['f1'], 2))\n 0.35\n\n Example 4-A multiclass example, with different values for the `average` input.\n >>> predictions = [0, 2, 1, 0, 0, 1]\n >>> references = [0, 1, 2, 0, 1, 2]\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\")\n >>> print(round(results['f1'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\")\n >>> print(round(results['f1'], 2))\n 0.33\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\")\n >>> print(round(results['f1'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)\n >>> print(results)\n {'f1': array([0.8, 0. , 0. ])}\n" SCREAMING_SNAKE_CASE__ : Union[str, Any] = "\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case ( datasets.Metric ): def __lowercase( self : List[str] )-> List[str]: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('int32' ) ), 'references': datasets.Sequence(datasets.Value('int32' ) ), } if self.config_name == 'multilabel' else { 'predictions': datasets.Value('int32' ), 'references': datasets.Value('int32' ), } ) , reference_urls=['https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html'] , ) def __lowercase( self : List[Any] , a_ : Dict , a_ : Optional[int] , a_ : int=None , a_ : Optional[Any]=1 , a_ : Union[str, Any]="binary" , a_ : Union[str, Any]=None )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = fa_score( a_ , a_ , labels=a_ , pos_label=a_ , average=a_ , sample_weight=a_ ) return {"f1": float(a_ ) if score.size == 1 else score}
721
from __future__ import annotations def _a ( lowercase__ : list[int | float] , lowercase__ : int , lowercase__ : int ): '''simple docstring''' if len(lowercase__ ) == 0: raise ValueError('find_max() arg is an empty sequence' ) if ( left >= len(lowercase__ ) or left < -len(lowercase__ ) or right >= len(lowercase__ ) or right < -len(lowercase__ ) ): raise IndexError('list index out of range' ) if left == right: return nums[left] SCREAMING_SNAKE_CASE__ : Union[str, Any] = (left + right) >> 1 # the middle SCREAMING_SNAKE_CASE__ : int = find_max(lowercase__ , lowercase__ , lowercase__ ) # find max in range[left, mid] SCREAMING_SNAKE_CASE__ : Tuple = find_max(lowercase__ , mid + 1 , lowercase__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
636
0
def _a ( lowercase__ : int , lowercase__ : List[Any] ): '''simple docstring''' print('\nThe shortest path matrix using Floyd Warshall algorithm\n' ) for i in range(lowercase__ ): for j in range(lowercase__ ): if dist[i][j] != float('inf' ): print(int(dist[i][j] ) , end='\t' ) else: print('INF' , end='\t' ) print() def _a ( lowercase__ : Optional[Any] , lowercase__ : Union[str, Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = [[float('inf' ) for _ in range(lowercase__ )] for _ in range(lowercase__ )] for i in range(lowercase__ ): for j in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : Dict = graph[i][j] # check vertex k against all other vertices (i, j) for k in range(lowercase__ ): # looping through rows of graph array for i in range(lowercase__ ): # looping through columns of graph array for j in range(lowercase__ ): if ( dist[i][k] != float('inf' ) and dist[k][j] != float('inf' ) and dist[i][k] + dist[k][j] < dist[i][j] ): SCREAMING_SNAKE_CASE__ : Any = dist[i][k] + dist[k][j] _print_dist(lowercase__ , lowercase__ ) return dist, v if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : Optional[Any] = int(input("Enter number of vertices: ")) SCREAMING_SNAKE_CASE__ : Tuple = int(input("Enter number of edges: ")) SCREAMING_SNAKE_CASE__ : Optional[Any] = [[float("inf") for i in range(v)] for j in range(v)] for i in range(v): SCREAMING_SNAKE_CASE__ : Tuple = 0.0 # src and dst are indices that must be within the array size graph[e][v] # failure to follow this will result in an error for i in range(e): print("\nEdge ", i + 1) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(input("Enter source:")) SCREAMING_SNAKE_CASE__ : Tuple = int(input("Enter destination:")) SCREAMING_SNAKE_CASE__ : List[Any] = float(input("Enter weight:")) SCREAMING_SNAKE_CASE__ : Optional[Any] = weight floyd_warshall(graph, v) # Example Input # Enter number of vertices: 3 # Enter number of edges: 2 # # generated graph from vertex and edge inputs # [[inf, inf, inf], [inf, inf, inf], [inf, inf, inf]] # [[0.0, inf, inf], [inf, 0.0, inf], [inf, inf, 0.0]] # specify source, destination and weight for edge #1 # Edge 1 # Enter source:1 # Enter destination:2 # Enter weight:2 # specify source, destination and weight for edge #2 # Edge 2 # Enter source:2 # Enter destination:1 # Enter weight:1 # # Expected Output from the vertice, edge and src, dst, weight inputs!! # 0 INF INF # INF 0 2 # INF 1 0
700
# Copyright 2023 The HuggingFace 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 torch from accelerate import PartialState from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce def _a ( lowercase__ : Any ): '''simple docstring''' return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device ) def _a ( lowercase__ : Tuple ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = gather(lowercase__ ) assert gathered_tensor.tolist() == list(range(1 , state.num_processes**2 + 1 ) ) def _a ( lowercase__ : List[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [state.process_index] SCREAMING_SNAKE_CASE__ : Any = gather_object(lowercase__ ) assert len(lowercase__ ) == state.num_processes, f'''{gathered_obj}, {len(lowercase__ )} != {state.num_processes}''' assert gathered_obj == list(range(state.num_processes ) ), f'''{gathered_obj} != {list(range(state.num_processes ) )}''' def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = broadcast(lowercase__ ) assert broadcasted_tensor.shape == torch.Size([state.num_processes] ) assert broadcasted_tensor.tolist() == list(range(1 , state.num_processes + 1 ) ) def _a ( lowercase__ : int ): '''simple docstring''' if state.is_main_process: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.arange(state.num_processes + 1 ).to(state.device ) else: SCREAMING_SNAKE_CASE__ : List[Any] = torch.arange(state.num_processes ).to(state.device ) SCREAMING_SNAKE_CASE__ : Any = pad_across_processes(lowercase__ ) assert padded_tensor.shape == torch.Size([state.num_processes + 1] ) if not state.is_main_process: assert padded_tensor.tolist() == list(range(0 , state.num_processes ) ) + [0] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : List[Any] = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : str = reduce(lowercase__ , 'sum' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([4.0, 6] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' if state.num_processes != 2: return SCREAMING_SNAKE_CASE__ : Any = create_tensor(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = reduce(lowercase__ , 'mean' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([2.0, 3] ).to(state.device ) assert torch.allclose(lowercase__ , lowercase__ ), f'''{reduced_tensor} != {truth_tensor}''' def _a ( lowercase__ : int ): '''simple docstring''' main() def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = PartialState() state.print(f'''State: {state}''' ) state.print('testing gather' ) test_gather(lowercase__ ) state.print('testing gather_object' ) test_gather_object(lowercase__ ) state.print('testing broadcast' ) test_broadcast(lowercase__ ) state.print('testing pad_across_processes' ) test_pad_across_processes(lowercase__ ) state.print('testing reduce_sum' ) test_reduce_sum(lowercase__ ) state.print('testing reduce_mean' ) test_reduce_mean(lowercase__ ) if __name__ == "__main__": main()
636
0
import json import os import re import sys import urllib.request import requests from bsa import BeautifulSoup SCREAMING_SNAKE_CASE__ : Tuple = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" " (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582" } def _a ( lowercase__ : str = "dhaka" , lowercase__ : int = 5 ) -> List[Any]: '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = min(lowercase__ , 50 ) # Prevent abuse! SCREAMING_SNAKE_CASE__ : List[str] = { 'q': query, 'tbm': 'isch', 'hl': 'en', 'ijn': '0', } SCREAMING_SNAKE_CASE__ : Union[str, Any] = requests.get('https://www.google.com/search' , params=lowercase__ , headers=lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = BeautifulSoup(html.text , 'html.parser' ) SCREAMING_SNAKE_CASE__ : str = ''.join( re.findall(r'AF_initDataCallback\(([^<]+)\);' , str(soup.select('script' ) ) ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = json.dumps(lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = json.loads(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = re.findall( r'\[\"GRID_STATE0\",null,\[\[1,\[0,\".*?\",(.*),\"All\",' , lowercase__ , ) if not matched_google_image_data: return 0 SCREAMING_SNAKE_CASE__ : Union[str, Any] = re.sub( r'\[\"(https\:\/\/encrypted-tbn0\.gstatic\.com\/images\?.*?)\",\d+,\d+\]' , '' , str(lowercase__ ) , ) SCREAMING_SNAKE_CASE__ : List[str] = re.findall( r'(?:\'|,),\[\"(https:|http.*?)\",\d+,\d+\]' , lowercase__ , ) for index, fixed_full_res_image in enumerate(lowercase__ ): if index >= max_images: return index SCREAMING_SNAKE_CASE__ : Dict = bytes(lowercase__ , 'ascii' ).decode( 'unicode-escape' ) SCREAMING_SNAKE_CASE__ : List[Any] = bytes(lowercase__ , 'ascii' ).decode( 'unicode-escape' ) SCREAMING_SNAKE_CASE__ : int = urllib.request.build_opener() SCREAMING_SNAKE_CASE__ : int = [ ( 'User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' ' (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582', ) ] urllib.request.install_opener(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = f'''query_{query.replace(' ' , '_' )}''' if not os.path.exists(lowercase__ ): os.makedirs(lowercase__ ) urllib.request.urlretrieve( # noqa: S310 lowercase__ , f'''{path_name}/original_size_img_{index}.jpg''' ) return index if __name__ == "__main__": try: SCREAMING_SNAKE_CASE__ : Optional[Any] = download_images_from_google_query(sys.argv[1]) print(F"""{image_count} images were downloaded to disk.""") except IndexError: print("Please provide a search term.") raise
701
import unittest import numpy as np import requests from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11 else: SCREAMING_SNAKE_CASE__ : Any = False if is_vision_available(): from PIL import Image from transformers import PixaStructImageProcessor class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[int] , a_ : Dict=7 , a_ : Any=3 , a_ : Any=18 , a_ : int=30 , a_ : int=400 , a_ : List[Any]=None , a_ : int=True , a_ : int=True , a_ : Dict=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = size if size is not None else {'height': 20, 'width': 20} SCREAMING_SNAKE_CASE__ : str = parent SCREAMING_SNAKE_CASE__ : Union[str, Any] = batch_size SCREAMING_SNAKE_CASE__ : Any = num_channels SCREAMING_SNAKE_CASE__ : Optional[Any] = image_size SCREAMING_SNAKE_CASE__ : List[str] = min_resolution SCREAMING_SNAKE_CASE__ : Dict = max_resolution SCREAMING_SNAKE_CASE__ : List[Any] = size SCREAMING_SNAKE_CASE__ : Tuple = do_normalize SCREAMING_SNAKE_CASE__ : Optional[Any] = do_convert_rgb SCREAMING_SNAKE_CASE__ : List[str] = [512, 1024, 2048, 4096] SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size if patch_size is not None else {'height': 16, 'width': 16} def __lowercase( self : Optional[Any] )-> str: """simple docstring""" return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb} def __lowercase( self : Dict )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg' SCREAMING_SNAKE_CASE__ : str = Image.open(requests.get(a_ , stream=a_ ).raw ).convert('RGB' ) return raw_image @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PixaStructImageProcessor if is_vision_available() else None def __lowercase( self : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = PixaStructImageProcessingTester(self ) @property def __lowercase( self : Dict )-> Tuple: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , 'do_normalize' ) ) self.assertTrue(hasattr(a_ , 'do_convert_rgb' ) ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.image_processor_tester.prepare_dummy_image() SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) SCREAMING_SNAKE_CASE__ : List[Any] = 2048 SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(a_ , return_tensors='pt' , max_patches=a_ ) self.assertTrue(torch.allclose(inputs.flattened_patches.mean() , torch.tensor(0.0606 ) , atol=1e-3 , rtol=1e-3 ) ) def __lowercase( self : Any )-> Tuple: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : List[str] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Tuple = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : Any )-> Any: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Tuple = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 SCREAMING_SNAKE_CASE__ : int = True for max_patch in self.image_processor_tester.max_patches: # Test not batched input with self.assertRaises(a_ ): SCREAMING_SNAKE_CASE__ : Dict = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches SCREAMING_SNAKE_CASE__ : List[Any] = 'Hello' SCREAMING_SNAKE_CASE__ : List[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ , header_text=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Any = image_processor( a_ , return_tensors='pt' , max_patches=a_ , header_text=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Optional[int] = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , numpify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , np.ndarray ) SCREAMING_SNAKE_CASE__ : str = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : str = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : int = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : Any = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ , torchify=a_ ) for image in image_inputs: self.assertIsInstance(a_ , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE__ : Any = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * self.image_processor_tester.num_channels ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[Any] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , ) @unittest.skipIf( not is_torch_greater_or_equal_than_1_11 , reason='`Pix2StructImageProcessor` requires `torch>=1.11.0`.' , ) @require_torch @require_vision class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PixaStructImageProcessor if is_vision_available() else None def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = PixaStructImageProcessingTester(self , num_channels=4 ) SCREAMING_SNAKE_CASE__ : Dict = 3 @property def __lowercase( self : Any )-> Any: """simple docstring""" return self.image_processor_tester.prepare_image_processor_dict() def __lowercase( self : Dict )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(a_ , 'do_normalize' ) ) self.assertTrue(hasattr(a_ , 'do_convert_rgb' ) ) def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" # Initialize image_processor SCREAMING_SNAKE_CASE__ : str = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=a_ ) for image in image_inputs: self.assertIsInstance(a_ , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ : Dict = ( (self.image_processor_tester.patch_size['height'] * self.image_processor_tester.patch_size['width']) * (self.image_processor_tester.num_channels - 1) ) + 2 for max_patch in self.image_processor_tester.max_patches: # Test not batched input SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor( image_inputs[0] , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (1, max_patch, expected_hidden_dim) , ) # Test batched SCREAMING_SNAKE_CASE__ : Tuple = image_processor( a_ , return_tensors='pt' , max_patches=a_ ).flattened_patches self.assertEqual( encoded_images.shape , (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim) , )
636
0
import math def _a ( lowercase__ : int ): '''simple docstring''' assert isinstance(lowercase__ , lowercase__ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False SCREAMING_SNAKE_CASE__ : Tuple = range(3 , int(math.sqrt(lowercase__ ) + 1 ) , 2 ) return not any(not number % i for i in odd_numbers ) def _a ( lowercase__ : List[str] , lowercase__ : Any=1 , **lowercase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = factor * value SCREAMING_SNAKE_CASE__ : Dict = value while not is_prime(lowercase__ ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1 , **lowercase__ ) return value
702
import heapq as hq import math from collections.abc import Iterator class snake_case : def __init__( self : str , a_ : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = str(id_ ) SCREAMING_SNAKE_CASE__ : Any = None SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : Union[str, Any] = {} # {vertex:distance} def __lt__( self : int , a_ : Tuple )-> Union[str, Any]: """simple docstring""" return self.key < other.key def __repr__( self : Any )-> Dict: """simple docstring""" return self.id def __lowercase( self : Optional[Any] , a_ : int )-> List[str]: """simple docstring""" self.neighbors.append(a_ ) def __lowercase( self : int , a_ : int , a_ : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = weight def _a ( lowercase__ : Optional[Any] , lowercase__ : Union[str, Any] , lowercase__ : Tuple , lowercase__ : Dict ): '''simple docstring''' graph[a - 1].add_neighbor(graph[b - 1] ) graph[b - 1].add_neighbor(graph[a - 1] ) # add the edges: graph[a - 1].add_edge(graph[b - 1] , lowercase__ ) graph[b - 1].add_edge(graph[a - 1] , lowercase__ ) def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] for u in graph: SCREAMING_SNAKE_CASE__ : Dict = math.inf SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = 0 SCREAMING_SNAKE_CASE__ : int = graph[:] while q: SCREAMING_SNAKE_CASE__ : Optional[Any] = min(lowercase__ ) q.remove(lowercase__ ) for v in u.neighbors: if (v in q) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : int = u SCREAMING_SNAKE_CASE__ : Any = u.edges[v.id] for i in range(1 , len(lowercase__ ) ): a.append((int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) ) return a def _a ( lowercase__ : list , lowercase__ : Vertex ): '''simple docstring''' for u in graph: SCREAMING_SNAKE_CASE__ : List[str] = math.inf SCREAMING_SNAKE_CASE__ : int = None SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 SCREAMING_SNAKE_CASE__ : Tuple = list(lowercase__ ) hq.heapify(lowercase__ ) while h: SCREAMING_SNAKE_CASE__ : Optional[int] = hq.heappop(lowercase__ ) for v in u.neighbors: if (v in h) and (u.edges[v.id] < v.key): SCREAMING_SNAKE_CASE__ : List[str] = u SCREAMING_SNAKE_CASE__ : Dict = u.edges[v.id] hq.heapify(lowercase__ ) for i in range(1 , len(lowercase__ ) ): yield (int(graph[i].id ) + 1, int(graph[i].pi.id ) + 1) def _a ( ): '''simple docstring''' if __name__ == "__main__": import doctest doctest.testmod()
636
0
import datetime import platform import subprocess from typing import Optional, Tuple, Union import numpy as np def _a ( lowercase__ : bytes , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = f'''{sampling_rate}''' SCREAMING_SNAKE_CASE__ : Optional[int] = '1' SCREAMING_SNAKE_CASE__ : int = 'f32le' SCREAMING_SNAKE_CASE__ : int = [ 'ffmpeg', '-i', 'pipe:0', '-ac', ac, '-ar', ar, '-f', format_for_conversion, '-hide_banner', '-loglevel', 'quiet', 'pipe:1', ] try: with subprocess.Popen(lowercase__ , stdin=subprocess.PIPE , stdout=subprocess.PIPE ) as ffmpeg_process: SCREAMING_SNAKE_CASE__ : Dict = ffmpeg_process.communicate(lowercase__ ) except FileNotFoundError as error: raise ValueError('ffmpeg was not found but is required to load audio files from filename' ) from error SCREAMING_SNAKE_CASE__ : Tuple = output_stream[0] SCREAMING_SNAKE_CASE__ : Any = np.frombuffer(lowercase__ , np.floataa ) if audio.shape[0] == 0: raise ValueError('Malformed soundfile' ) return audio def _a ( lowercase__ : int , lowercase__ : float , lowercase__ : str = "f32le" , ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = f'''{sampling_rate}''' SCREAMING_SNAKE_CASE__ : Optional[Any] = '1' if format_for_conversion == "s16le": SCREAMING_SNAKE_CASE__ : Optional[Any] = 2 elif format_for_conversion == "f32le": SCREAMING_SNAKE_CASE__ : List[str] = 4 else: raise ValueError(f'''Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`''' ) SCREAMING_SNAKE_CASE__ : List[str] = platform.system() if system == "Linux": SCREAMING_SNAKE_CASE__ : Any = 'alsa' SCREAMING_SNAKE_CASE__ : int = 'default' elif system == "Darwin": SCREAMING_SNAKE_CASE__ : str = 'avfoundation' SCREAMING_SNAKE_CASE__ : Dict = ':0' elif system == "Windows": SCREAMING_SNAKE_CASE__ : Any = 'dshow' SCREAMING_SNAKE_CASE__ : Any = 'default' SCREAMING_SNAKE_CASE__ : List[str] = [ 'ffmpeg', '-f', format_, '-i', input_, '-ac', ac, '-ar', ar, '-f', format_for_conversion, '-fflags', 'nobuffer', '-hide_banner', '-loglevel', 'quiet', 'pipe:1', ] SCREAMING_SNAKE_CASE__ : Any = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample SCREAMING_SNAKE_CASE__ : List[Any] = _ffmpeg_stream(lowercase__ , lowercase__ ) for item in iterator: yield item def _a ( lowercase__ : int , lowercase__ : float , lowercase__ : Optional[int] = None , lowercase__ : Optional[Union[Tuple[float, float], float]] = None , lowercase__ : str = "f32le" , ): '''simple docstring''' if stream_chunk_s is not None: SCREAMING_SNAKE_CASE__ : Dict = stream_chunk_s else: SCREAMING_SNAKE_CASE__ : Optional[Any] = chunk_length_s SCREAMING_SNAKE_CASE__ : Union[str, Any] = ffmpeg_microphone(lowercase__ , lowercase__ , format_for_conversion=lowercase__ ) if format_for_conversion == "s16le": SCREAMING_SNAKE_CASE__ : Tuple = np.intaa SCREAMING_SNAKE_CASE__ : Any = 2 elif format_for_conversion == "f32le": SCREAMING_SNAKE_CASE__ : Any = np.floataa SCREAMING_SNAKE_CASE__ : int = 4 else: raise ValueError(f'''Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`''' ) if stride_length_s is None: SCREAMING_SNAKE_CASE__ : str = chunk_length_s / 6 SCREAMING_SNAKE_CASE__ : str = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample if isinstance(lowercase__ , (int, float) ): SCREAMING_SNAKE_CASE__ : Optional[Any] = [stride_length_s, stride_length_s] SCREAMING_SNAKE_CASE__ : Optional[int] = int(round(sampling_rate * stride_length_s[0] ) ) * size_of_sample SCREAMING_SNAKE_CASE__ : str = int(round(sampling_rate * stride_length_s[1] ) ) * size_of_sample SCREAMING_SNAKE_CASE__ : Any = datetime.datetime.now() SCREAMING_SNAKE_CASE__ : Any = datetime.timedelta(seconds=lowercase__ ) for item in chunk_bytes_iter(lowercase__ , lowercase__ , stride=(stride_left, stride_right) , stream=lowercase__ ): # Put everything back in numpy scale SCREAMING_SNAKE_CASE__ : Any = np.frombuffer(item['raw'] , dtype=lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = ( item['stride'][0] // size_of_sample, item['stride'][1] // size_of_sample, ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = sampling_rate audio_time += delta if datetime.datetime.now() > audio_time + 10 * delta: # We're late !! SKIP continue yield item def _a ( lowercase__ : Any , lowercase__ : int , lowercase__ : Tuple[int, int] , lowercase__ : bool = False ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = b'' SCREAMING_SNAKE_CASE__ : int = stride if stride_left + stride_right >= chunk_len: raise ValueError( f'''Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}''' ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 for raw in iterator: acc += raw if stream and len(lowercase__ ) < chunk_len: SCREAMING_SNAKE_CASE__ : Dict = (_stride_left, 0) yield {"raw": acc[:chunk_len], "stride": stride, "partial": True} else: while len(lowercase__ ) >= chunk_len: # We are flushing the accumulator SCREAMING_SNAKE_CASE__ : List[Any] = (_stride_left, stride_right) SCREAMING_SNAKE_CASE__ : List[str] = {'raw': acc[:chunk_len], 'stride': stride} if stream: SCREAMING_SNAKE_CASE__ : List[str] = False yield item SCREAMING_SNAKE_CASE__ : Optional[Any] = stride_left SCREAMING_SNAKE_CASE__ : Tuple = acc[chunk_len - stride_left - stride_right :] # Last chunk if len(lowercase__ ) > stride_left: SCREAMING_SNAKE_CASE__ : Tuple = {'raw': acc, 'stride': (_stride_left, 0)} if stream: SCREAMING_SNAKE_CASE__ : Tuple = False yield item def _a ( lowercase__ : List[Any] , lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = 2**24 # 16Mo try: with subprocess.Popen(lowercase__ , stdout=subprocess.PIPE , bufsize=lowercase__ ) as ffmpeg_process: while True: SCREAMING_SNAKE_CASE__ : int = ffmpeg_process.stdout.read(lowercase__ ) if raw == b"": break yield raw except FileNotFoundError as error: raise ValueError('ffmpeg was not found but is required to stream audio files from filename' ) from error
703
def _a ( lowercase__ : int , lowercase__ : int ): '''simple docstring''' return int((input_a, input_a).count(0 ) != 0 ) def _a ( ): '''simple docstring''' assert nand_gate(0 , 0 ) == 1 assert nand_gate(0 , 1 ) == 1 assert nand_gate(1 , 0 ) == 1 assert nand_gate(1 , 1 ) == 0 if __name__ == "__main__": print(nand_gate(0, 0)) print(nand_gate(0, 1)) print(nand_gate(1, 0)) print(nand_gate(1, 1))
636
0
import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class snake_case ( unittest.TestCase ): def __lowercase( self : int )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) SCREAMING_SNAKE_CASE__ : Optional[int] = get_activation('gelu' ) self.assertTrue(torch.allclose(gelu_python(a_ ) , torch_builtin(a_ ) ) ) self.assertFalse(torch.allclose(gelu_python(a_ ) , gelu_new(a_ ) ) ) def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100] ) SCREAMING_SNAKE_CASE__ : List[str] = get_activation('gelu' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = get_activation('gelu_10' ) SCREAMING_SNAKE_CASE__ : List[Any] = torch_builtin(a_ ) SCREAMING_SNAKE_CASE__ : Dict = geluaa(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = torch.where(y_gelu_aa < 10.0 , 1 , 0 ) self.assertTrue(torch.max(a_ ).item() == 10.0 ) self.assertTrue(torch.allclose(y_gelu * clipped_mask , y_gelu_aa * clipped_mask ) ) def __lowercase( self : Optional[int] )-> List[Any]: """simple docstring""" get_activation('gelu' ) get_activation('gelu_10' ) get_activation('gelu_fast' ) get_activation('gelu_new' ) get_activation('gelu_python' ) get_activation('gelu_pytorch_tanh' ) get_activation('linear' ) get_activation('mish' ) get_activation('quick_gelu' ) get_activation('relu' ) get_activation('sigmoid' ) get_activation('silu' ) get_activation('swish' ) get_activation('tanh' ) with self.assertRaises(a_ ): get_activation('bogus' ) with self.assertRaises(a_ ): get_activation(a_ ) def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = get_activation('gelu' ) SCREAMING_SNAKE_CASE__ : Tuple = 1 SCREAMING_SNAKE_CASE__ : int = get_activation('gelu' ) self.assertEqual(acta.a , 1 ) with self.assertRaises(a_ ): SCREAMING_SNAKE_CASE__ : Tuple = acta.a
704
from math import factorial, radians def _a ( lowercase__ : float , lowercase__ : int = 18 , lowercase__ : int = 10 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0) # Converting from degrees to radians SCREAMING_SNAKE_CASE__ : int = radians(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = angle_in_radians SCREAMING_SNAKE_CASE__ : Optional[int] = 3 SCREAMING_SNAKE_CASE__ : Optional[int] = -1 for _ in range(lowercase__ ): result += (b * (angle_in_radians**a)) / factorial(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(lowercase__ , lowercase__ ) if __name__ == "__main__": __import__("doctest").testmod()
636
0
from __future__ import annotations import numpy as np def _a ( lowercase__ : np.ndarray ): '''simple docstring''' __A : Any = np.shape(lowercase__ ) if rows != columns: __A : Dict = ( '\'table\' has to be of square shaped array but got a ' f'''{rows}x{columns} array:\n{table}''' ) raise ValueError(lowercase__ ) __A : Optional[Any] = np.zeros((rows, columns) ) __A : Optional[Any] = np.zeros((rows, columns) ) for i in range(lowercase__ ): for j in range(lowercase__ ): __A : Union[str, Any] = sum(lower[i][k] * upper[k][j] for k in range(lowercase__ ) ) if upper[j][j] == 0: raise ArithmeticError('No LU decomposition exists' ) __A : Optional[int] = (table[i][j] - total) / upper[j][j] __A : Union[str, Any] = 1 for j in range(lowercase__ , lowercase__ ): __A : Optional[Any] = sum(lower[i][k] * upper[k][j] for k in range(lowercase__ ) ) __A : Optional[int] = table[i][j] - total return lower, upper if __name__ == "__main__": import doctest doctest.testmod()
705
import math def _a ( lowercase__ : int ): '''simple docstring''' assert isinstance(lowercase__ , lowercase__ ) and ( number >= 0 ), "'number' must been an int and positive" if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or not number % 2: # Negatives, 0, 1 and all even numbers are not primes return False SCREAMING_SNAKE_CASE__ : Tuple = range(3 , int(math.sqrt(lowercase__ ) + 1 ) , 2 ) return not any(not number % i for i in odd_numbers ) def _a ( lowercase__ : List[str] , lowercase__ : Any=1 , **lowercase__ : Any ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = factor * value SCREAMING_SNAKE_CASE__ : Dict = value while not is_prime(lowercase__ ): value += 1 if not ("desc" in kwargs and kwargs["desc"] is True) else -1 if value == first_value_val: return next_prime(value + 1 , **lowercase__ ) return value
636
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE__ : Optional[int] = { "configuration_mobilebert": [ "MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "MobileBertConfig", "MobileBertOnnxConfig", ], "tokenization_mobilebert": ["MobileBertTokenizer"], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[str] = ["MobileBertTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = [ "MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "MobileBertForMaskedLM", "MobileBertForMultipleChoice", "MobileBertForNextSentencePrediction", "MobileBertForPreTraining", "MobileBertForQuestionAnswering", "MobileBertForSequenceClassification", "MobileBertForTokenClassification", "MobileBertLayer", "MobileBertModel", "MobileBertPreTrainedModel", "load_tf_weights_in_mobilebert", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE__ : List[Any] = [ "TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST", "TFMobileBertForMaskedLM", "TFMobileBertForMultipleChoice", "TFMobileBertForNextSentencePrediction", "TFMobileBertForPreTraining", "TFMobileBertForQuestionAnswering", "TFMobileBertForSequenceClassification", "TFMobileBertForTokenClassification", "TFMobileBertMainLayer", "TFMobileBertModel", "TFMobileBertPreTrainedModel", ] if TYPE_CHECKING: from .configuration_mobilebert import ( MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, MobileBertConfig, MobileBertOnnxConfig, ) from .tokenization_mobilebert import MobileBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mobilebert_fast import MobileBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mobilebert import ( MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, MobileBertForMaskedLM, MobileBertForMultipleChoice, MobileBertForNextSentencePrediction, MobileBertForPreTraining, MobileBertForQuestionAnswering, MobileBertForSequenceClassification, MobileBertForTokenClassification, MobileBertLayer, MobileBertModel, MobileBertPreTrainedModel, load_tf_weights_in_mobilebert, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mobilebert import ( TF_MOBILEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, TFMobileBertForMaskedLM, TFMobileBertForMultipleChoice, TFMobileBertForNextSentencePrediction, TFMobileBertForPreTraining, TFMobileBertForQuestionAnswering, TFMobileBertForSequenceClassification, TFMobileBertForTokenClassification, TFMobileBertMainLayer, TFMobileBertModel, TFMobileBertPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE__ : List[str] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
706
import inspect import unittest import warnings from transformers import DeiTConfig from transformers.models.auto import get_values from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING, MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING, MODEL_MAPPING, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, DeiTModel, ) from transformers.models.deit.modeling_deit import DEIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import DeiTImageProcessor class snake_case : def __init__( self : str , a_ : List[str] , a_ : Tuple=13 , a_ : Dict=30 , a_ : Optional[int]=2 , a_ : Tuple=3 , a_ : Dict=True , a_ : int=True , a_ : Optional[Any]=32 , a_ : List[str]=5 , a_ : Any=4 , a_ : Dict=37 , a_ : Dict="gelu" , a_ : int=0.1 , a_ : Optional[Any]=0.1 , a_ : Any=10 , a_ : List[str]=0.02 , a_ : Any=3 , a_ : List[str]=None , a_ : Optional[int]=2 , )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = parent SCREAMING_SNAKE_CASE__ : int = batch_size SCREAMING_SNAKE_CASE__ : int = image_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = patch_size SCREAMING_SNAKE_CASE__ : Optional[int] = num_channels SCREAMING_SNAKE_CASE__ : int = is_training SCREAMING_SNAKE_CASE__ : List[Any] = use_labels SCREAMING_SNAKE_CASE__ : str = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Tuple = num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[str] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] = type_sequence_label_size SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = scope SCREAMING_SNAKE_CASE__ : str = encoder_stride # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens) SCREAMING_SNAKE_CASE__ : Optional[int] = (image_size // patch_size) ** 2 SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_patches + 2 def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Dict = None if self.use_labels: SCREAMING_SNAKE_CASE__ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.get_config() return config, pixel_values, labels def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" return DeiTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=a_ , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def __lowercase( self : List[str] , a_ : List[str] , a_ : Optional[Any] , a_ : str )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = DeiTModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : List[str] , a_ : List[str] , a_ : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = DeiTForMaskedImageModeling(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Optional[int] = 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = DeiTForMaskedImageModeling(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : int = model(a_ ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowercase( self : List[str] , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Tuple )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : int = DeiTForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : List[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Dict = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( ( DeiTModel, DeiTForImageClassification, DeiTForImageClassificationWithTeacher, DeiTForMaskedImageModeling, ) if is_torch_available() else () ) lowercase_ = ( { 'feature-extraction': DeiTModel, 'image-classification': (DeiTForImageClassification, DeiTForImageClassificationWithTeacher), } if is_torch_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = DeiTModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , has_text_modality=a_ , hidden_size=37 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.config_tester.run_common_tests() @unittest.skip(reason='DeiT does not use inputs_embeds' ) def __lowercase( self : List[Any] )-> Dict: """simple docstring""" pass def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a_ , nn.Linear ) ) def __lowercase( self : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[str] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : int = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : List[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : List[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*a_ ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) def __lowercase( self : str , a_ : str , a_ : Tuple , a_ : Union[str, Any]=False )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = super()._prepare_for_class(a_ , a_ , return_labels=a_ ) if return_labels: if model_class.__name__ == "DeiTForImageClassificationWithTeacher": del inputs_dict["labels"] return inputs_dict def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[Any] = True for model_class in self.all_model_classes: # DeiTForImageClassificationWithTeacher supports inference-only if ( model_class in get_values(a_ ) or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue SCREAMING_SNAKE_CASE__ : Tuple = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : List[Any] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() if not self.model_tester.is_training: return SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = True for model_class in self.all_model_classes: if model_class in get_values(a_ ) or not model_class.supports_gradient_checkpointing: continue # DeiTForImageClassificationWithTeacher supports inference-only if model_class.__name__ == "DeiTForImageClassificationWithTeacher": continue SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(a_ ) model.gradient_checkpointing_enable() model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(**a_ ).loss loss.backward() def __lowercase( self : Optional[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[str] = [ {'title': 'multi_label_classification', 'num_labels': 2, 'dtype': torch.float}, {'title': 'single_label_classification', 'num_labels': 1, 'dtype': torch.long}, {'title': 'regression', 'num_labels': 1, 'dtype': torch.float}, ] for model_class in self.all_model_classes: if ( model_class not in [ *get_values(a_ ), *get_values(a_ ), ] or model_class.__name__ == "DeiTForImageClassificationWithTeacher" ): continue for problem_type in problem_types: with self.subTest(msg=F'''Testing {model_class} with {problem_type['title']}''' ): SCREAMING_SNAKE_CASE__ : int = problem_type['title'] SCREAMING_SNAKE_CASE__ : Tuple = problem_type['num_labels'] SCREAMING_SNAKE_CASE__ : str = model_class(a_ ) model.to(a_ ) model.train() SCREAMING_SNAKE_CASE__ : Optional[int] = self._prepare_for_class(a_ , a_ , return_labels=a_ ) if problem_type["num_labels"] > 1: SCREAMING_SNAKE_CASE__ : Optional[Any] = inputs['labels'].unsqueeze(1 ).repeat(1 , problem_type['num_labels'] ) SCREAMING_SNAKE_CASE__ : Any = inputs['labels'].to(problem_type['dtype'] ) # This tests that we do not trigger the warning form PyTorch "Using a target size that is different # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure # they have the same size." which is a symptom something in wrong for the regression problem. # See https://github.com/huggingface/transformers/issues/11780 with warnings.catch_warnings(record=a_ ) as warning_list: SCREAMING_SNAKE_CASE__ : str = model(**a_ ).loss for w in warning_list: if "Using a target size that is different to the input size" in str(w.message ): raise ValueError( F'''Something is going wrong in the regression problem: intercepted {w.message}''' ) loss.backward() @slow def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" for model_name in DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Optional[Any] = DeiTModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : int )-> Dict: """simple docstring""" return ( DeiTImageProcessor.from_pretrained('facebook/deit-base-distilled-patch16-224' ) if is_vision_available() else None ) @slow def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = DeiTForImageClassificationWithTeacher.from_pretrained('facebook/deit-base-distilled-patch16-224' ).to( a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.default_image_processor SCREAMING_SNAKE_CASE__ : List[Any] = prepare_img() SCREAMING_SNAKE_CASE__ : List[str] = image_processor(images=a_ , return_tensors='pt' ).to(a_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(**a_ ) # verify the logits SCREAMING_SNAKE_CASE__ : int = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.tensor([-1.0266, 0.1912, -1.2861] ).to(a_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a_ , atol=1e-4 ) ) @slow @require_accelerate @require_torch_gpu def __lowercase( self : Tuple )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = DeiTModel.from_pretrained( 'facebook/deit-base-distilled-patch16-224' , torch_dtype=torch.floataa , device_map='auto' ) SCREAMING_SNAKE_CASE__ : Dict = self.default_image_processor SCREAMING_SNAKE_CASE__ : Union[str, Any] = prepare_img() SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(images=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = inputs.pixel_values.to(a_ ) # forward pass to make sure inference works in fp16 with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ )
636
0
from ....configuration_utils import PretrainedConfig from ....utils import logging SCREAMING_SNAKE_CASE__ : Tuple = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : List[Any] = { "CarlCochet/trajectory-transformer-halfcheetah-medium-v2": ( "https://huggingface.co/CarlCochet/trajectory-transformer-halfcheetah-medium-v2/resolve/main/config.json" ), # See all TrajectoryTransformer models at https://huggingface.co/models?filter=trajectory_transformer } class snake_case ( UpperCamelCase_ ): lowercase_ = 'trajectory_transformer' lowercase_ = ['past_key_values'] lowercase_ = { 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self : Dict , a_ : List[str]=100 , a_ : str=5 , a_ : Optional[Any]=1 , a_ : str=1 , a_ : List[str]=249 , a_ : List[Any]=6 , a_ : Tuple=17 , a_ : Any=25 , a_ : Optional[Any]=4 , a_ : Tuple=4 , a_ : int=128 , a_ : Union[str, Any]=0.1 , a_ : Optional[Any]=0.1 , a_ : Tuple=0.1 , a_ : str=0.0006 , a_ : Optional[Any]=512 , a_ : Optional[int]=0.02 , a_ : Optional[Any]=1e-1_2 , a_ : Any=1 , a_ : int=True , a_ : Optional[int]=1 , a_ : Optional[Any]=5_0256 , a_ : Dict=5_0256 , **a_ : Optional[Any] , )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = vocab_size SCREAMING_SNAKE_CASE__ : Dict = action_weight SCREAMING_SNAKE_CASE__ : int = reward_weight SCREAMING_SNAKE_CASE__ : Optional[Any] = value_weight SCREAMING_SNAKE_CASE__ : List[Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : List[str] = block_size SCREAMING_SNAKE_CASE__ : int = action_dim SCREAMING_SNAKE_CASE__ : Any = observation_dim SCREAMING_SNAKE_CASE__ : Tuple = transition_dim SCREAMING_SNAKE_CASE__ : int = learning_rate SCREAMING_SNAKE_CASE__ : str = n_layer SCREAMING_SNAKE_CASE__ : Dict = n_head SCREAMING_SNAKE_CASE__ : List[str] = n_embd SCREAMING_SNAKE_CASE__ : int = embd_pdrop SCREAMING_SNAKE_CASE__ : str = attn_pdrop SCREAMING_SNAKE_CASE__ : Tuple = resid_pdrop SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Any = layer_norm_eps SCREAMING_SNAKE_CASE__ : Union[str, Any] = kaiming_initializer_range SCREAMING_SNAKE_CASE__ : int = use_cache super().__init__(pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , **a_ )
707
import math import unittest from transformers import BioGptConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification, BioGptModel, BioGptTokenizer, ) from transformers.models.biogpt.modeling_biogpt import BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case : def __init__( self : List[Any] , a_ : Dict , a_ : Any=13 , a_ : Any=7 , a_ : Tuple=True , a_ : Tuple=True , a_ : Optional[int]=False , a_ : Dict=True , a_ : Optional[Any]=99 , a_ : Any=32 , a_ : Dict=5 , a_ : Tuple=4 , a_ : List[str]=37 , a_ : Union[str, Any]="gelu" , a_ : Dict=0.1 , a_ : Tuple=0.1 , a_ : List[str]=512 , a_ : List[str]=16 , a_ : List[str]=2 , a_ : Optional[int]=0.02 , a_ : List[str]=3 , a_ : Union[str, Any]=4 , a_ : Optional[Any]=None , )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Dict = batch_size SCREAMING_SNAKE_CASE__ : Dict = seq_length SCREAMING_SNAKE_CASE__ : Optional[Any] = is_training SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_input_mask SCREAMING_SNAKE_CASE__ : Optional[Any] = use_token_type_ids SCREAMING_SNAKE_CASE__ : int = use_labels SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = intermediate_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_act SCREAMING_SNAKE_CASE__ : List[Any] = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : int = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : Any = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Tuple = initializer_range SCREAMING_SNAKE_CASE__ : List[Any] = num_labels SCREAMING_SNAKE_CASE__ : Dict = num_choices SCREAMING_SNAKE_CASE__ : str = scope def __lowercase( self : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Tuple = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : str = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE__ : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) SCREAMING_SNAKE_CASE__ : List[str] = None SCREAMING_SNAKE_CASE__ : str = None SCREAMING_SNAKE_CASE__ : List[str] = None if self.use_labels: SCREAMING_SNAKE_CASE__ : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor([self.batch_size] , self.num_choices ) SCREAMING_SNAKE_CASE__ : List[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def __lowercase( self : Dict )-> Tuple: """simple docstring""" return BioGptConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=a_ , initializer_range=self.initializer_range , ) def __lowercase( self : Any , a_ : str , a_ : Tuple , a_ : Dict , a_ : Optional[int] , a_ : List[Any] , a_ : Union[str, Any] , a_ : Tuple )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = BioGptModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def __lowercase( self : List[Any] , a_ : Union[str, Any] , a_ : Optional[int] , a_ : Tuple , a_ : Optional[Any] , a_ : int , a_ : Optional[int] , a_ : int , a_ : str , a_ : Optional[Any] , )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = BioGptForCausalLM(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , attention_mask=a_ , token_type_ids=a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def __lowercase( self : Tuple , a_ : Optional[int] , a_ : Union[str, Any] , a_ : Any , a_ : Any , a_ : Optional[int] , *a_ : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(config=a_ ) model.to(a_ ) model.eval() # create attention mask SCREAMING_SNAKE_CASE__ : Any = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.seq_length // 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = 0 # first forward pass SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model(a_ , attention_mask=a_ ).to_tuple() # create hypothetical next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 1) , config.vocab_size ) # change a random masked slice from input_ids SCREAMING_SNAKE_CASE__ : str = ids_tensor((1,) , a_ ).item() + 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = ids_tensor((self.batch_size, 1) , config.vocab_size ).squeeze(-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = random_other_next_tokens # append to next input_ids and attn_mask SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Dict = torch.cat( [attn_mask, torch.ones((attn_mask.shape[0], 1) , dtype=torch.long , device=a_ )] , dim=1 , ) # get two different outputs SCREAMING_SNAKE_CASE__ : str = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , past_key_values=a_ , attention_mask=a_ )['last_hidden_state'] # select random slice SCREAMING_SNAKE_CASE__ : Any = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : List[str] = output_from_no_past[:, -1, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : List[str] = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : str , a_ : List[Any] , a_ : str , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : Optional[Any] , *a_ : List[str] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel(config=a_ ).to(a_ ).eval() SCREAMING_SNAKE_CASE__ : Dict = torch.ones(input_ids.shape , dtype=torch.long , device=a_ ) # first forward pass SCREAMING_SNAKE_CASE__ : Any = model(a_ , attention_mask=a_ , use_cache=a_ ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Any = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids SCREAMING_SNAKE_CASE__ : Optional[Any] = ids_tensor((self.batch_size, 3) , config.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and SCREAMING_SNAKE_CASE__ : int = torch.cat([input_ids, next_tokens] , dim=-1 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) SCREAMING_SNAKE_CASE__ : int = model(a_ , attention_mask=a_ )['last_hidden_state'] SCREAMING_SNAKE_CASE__ : List[str] = model(a_ , attention_mask=a_ , past_key_values=a_ )[ 'last_hidden_state' ] # select random slice SCREAMING_SNAKE_CASE__ : int = ids_tensor((1,) , output_from_past.shape[-1] ).item() SCREAMING_SNAKE_CASE__ : Any = output_from_no_past[:, -3:, random_slice_idx].detach() SCREAMING_SNAKE_CASE__ : Optional[Any] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Any , a_ : List[str] , a_ : Optional[int] , a_ : Any , a_ : Tuple , a_ : Any , *a_ : List[Any] , a_ : Union[str, Any]=False )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = BioGptForCausalLM(a_ ) model.to(a_ ) if gradient_checkpointing: model.gradient_checkpointing_enable() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ , labels=a_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) result.loss.backward() def __lowercase( self : Union[str, Any] , a_ : List[str] , *a_ : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = BioGptModel(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers ) for key in model.state_dict().keys(): if "c_proj" in key and "weight" in key: self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key] ) - model_std ) , 0.001 ) self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key] ) - 0.0 ) , 0.01 ) def __lowercase( self : Dict , a_ : Tuple , a_ : Tuple , a_ : List[str] , a_ : Any , a_ : str , *a_ : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.num_labels SCREAMING_SNAKE_CASE__ : str = BioGptForTokenClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ , attention_mask=a_ , token_type_ids=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def __lowercase( self : Any )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.prepare_config_and_inputs() ( ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ( SCREAMING_SNAKE_CASE__ ) , ) : Tuple = config_and_inputs SCREAMING_SNAKE_CASE__ : Optional[Any] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification) if is_torch_available() else () ) lowercase_ = (BioGptForCausalLM,) if is_torch_available() else () lowercase_ = ( { 'feature-extraction': BioGptModel, 'text-classification': BioGptForSequenceClassification, 'text-generation': BioGptForCausalLM, 'token-classification': BioGptForTokenClassification, 'zero-shot': BioGptForSequenceClassification, } if is_torch_available() else {} ) lowercase_ = False def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptModelTester(self ) SCREAMING_SNAKE_CASE__ : List[Any] = ConfigTester(self , config_class=a_ , hidden_size=37 ) def __lowercase( self : Tuple )-> int: """simple docstring""" self.config_tester.run_common_tests() def __lowercase( self : Optional[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : Union[str, Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: SCREAMING_SNAKE_CASE__ : List[str] = type self.model_tester.create_and_check_model(*a_ ) def __lowercase( self : int )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_attention_mask_past(*a_ ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_forward_and_backwards(*a_ , gradient_checkpointing=a_ ) def __lowercase( self : Union[str, Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_model_past_large_inputs(*a_ ) def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_weight_initialization(*a_ ) def __lowercase( self : str )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_biogpt_for_token_classification(*a_ ) @slow def __lowercase( self : List[str] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = 'left' # Define PAD Token = EOS Token = 50256 SCREAMING_SNAKE_CASE__ : Any = tokenizer.eos_token SCREAMING_SNAKE_CASE__ : Tuple = model.config.eos_token_id # use different length sentences to test batching SCREAMING_SNAKE_CASE__ : Union[str, Any] = [ 'Hello, my dog is a little', 'Today, I', ] SCREAMING_SNAKE_CASE__ : Optional[Any] = tokenizer(a_ , return_tensors='pt' , padding=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = inputs['input_ids'].to(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = model.generate( input_ids=a_ , attention_mask=inputs['attention_mask'].to(a_ ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer(sentences[0] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Dict = model.generate(input_ids=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = inputs_non_padded.shape[-1] - inputs['attention_mask'][-1].long().sum().cpu().item() SCREAMING_SNAKE_CASE__ : Dict = tokenizer(sentences[1] , return_tensors='pt' ).input_ids.to(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = model.generate(input_ids=a_ , max_length=model.config.max_length - num_paddings ) SCREAMING_SNAKE_CASE__ : Any = tokenizer.batch_decode(a_ , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer.decode(output_non_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer.decode(output_padded[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = [ 'Hello, my dog is a little bit bigger than a little bit.', 'Today, I have a good idea of how to use the information', ] self.assertListEqual(a_ , a_ ) self.assertListEqual(a_ , [non_padded_sentence, padded_sentence] ) @slow def __lowercase( self : Any )-> List[Any]: """simple docstring""" for model_name in BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : List[Any] = BioGptModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def __lowercase( self : Optional[int] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] = 3 SCREAMING_SNAKE_CASE__ : List[Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : int = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def __lowercase( self : str )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : str = 3 SCREAMING_SNAKE_CASE__ : Any = 'multi_label_classification' SCREAMING_SNAKE_CASE__ : Union[str, Any] = input_dict['input_ids'] SCREAMING_SNAKE_CASE__ : Any = input_ids.ne(1 ).to(a_ ) SCREAMING_SNAKE_CASE__ : str = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForSequenceClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = model(a_ , attention_mask=a_ , labels=a_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @require_torch class snake_case ( unittest.TestCase ): @slow def __lowercase( self : Union[str, Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([[2, 4805, 9, 656, 21]] ) SCREAMING_SNAKE_CASE__ : Optional[int] = model(a_ )[0] SCREAMING_SNAKE_CASE__ : List[str] = 4_2384 SCREAMING_SNAKE_CASE__ : Dict = torch.Size((1, 5, vocab_size) ) self.assertEqual(output.shape , a_ ) SCREAMING_SNAKE_CASE__ : int = torch.tensor( [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , a_ , atol=1e-4 ) ) @slow def __lowercase( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = BioGptTokenizer.from_pretrained('microsoft/biogpt' ) SCREAMING_SNAKE_CASE__ : Dict = BioGptForCausalLM.from_pretrained('microsoft/biogpt' ) model.to(a_ ) torch.manual_seed(0 ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = tokenizer('COVID-19 is' , return_tensors='pt' ).to(a_ ) SCREAMING_SNAKE_CASE__ : int = model.generate( **a_ , min_length=100 , max_length=1024 , num_beams=5 , early_stopping=a_ , ) SCREAMING_SNAKE_CASE__ : int = tokenizer.decode(output_ids[0] , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ( 'COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the' ' causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and' ' territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),' ' and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and' ' more than 800,000 deaths.' ) self.assertEqual(a_ , a_ )
636
0
import numpy as np from matplotlib import pyplot as plt from sklearn.datasets import load_iris from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import train_test_split from xgboost import XGBClassifier def _a ( lowercase__ : dict ): '''simple docstring''' return (data["data"], data["target"]) def _a ( lowercase__ : np.ndarray , lowercase__ : np.ndarray ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = XGBClassifier() classifier.fit(lowercase__ , lowercase__ ) return classifier def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = load_iris() SCREAMING_SNAKE_CASE__ : Optional[int] = data_handling(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = train_test_split( lowercase__ , lowercase__ , test_size=0.25 ) SCREAMING_SNAKE_CASE__ : Tuple = iris['target_names'] # Create an XGBoost Classifier from the training data SCREAMING_SNAKE_CASE__ : Tuple = xgboost(lowercase__ , lowercase__ ) # Display the confusion matrix of the classifier with both training and test sets ConfusionMatrixDisplay.from_estimator( lowercase__ , lowercase__ , lowercase__ , display_labels=lowercase__ , cmap='Blues' , normalize='true' , ) plt.title('Normalized Confusion Matrix - IRIS Dataset' ) plt.show() if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
708
import itertools import random import unittest import numpy as np from transformers import BatchFeature, SpeechTaFeatureExtractor from transformers.testing_utils import require_torch from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : Optional[Any] = random.Random() def _a ( lowercase__ : List[str] , lowercase__ : List[Any]=1.0 , lowercase__ : Optional[int]=None , lowercase__ : List[str]=None ): '''simple docstring''' if rng is None: SCREAMING_SNAKE_CASE__ : Optional[int] = global_rng SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch class snake_case ( unittest.TestCase ): def __init__( self : List[Any] , a_ : Optional[Any] , a_ : Union[str, Any]=7 , a_ : Any=400 , a_ : List[Any]=2000 , a_ : Tuple=1 , a_ : Optional[int]=0.0 , a_ : Optional[Any]=1_6000 , a_ : str=True , a_ : Union[str, Any]=80 , a_ : Dict=16 , a_ : Tuple=64 , a_ : Any="hann_window" , a_ : Union[str, Any]=80 , a_ : List[Any]=7600 , a_ : Optional[Any]=1e-1_0 , a_ : Dict=True , )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = parent SCREAMING_SNAKE_CASE__ : List[Any] = batch_size SCREAMING_SNAKE_CASE__ : str = min_seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = max_seq_length SCREAMING_SNAKE_CASE__ : str = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE__ : int = feature_size SCREAMING_SNAKE_CASE__ : str = padding_value SCREAMING_SNAKE_CASE__ : Any = sampling_rate SCREAMING_SNAKE_CASE__ : Optional[int] = do_normalize SCREAMING_SNAKE_CASE__ : int = num_mel_bins SCREAMING_SNAKE_CASE__ : int = hop_length SCREAMING_SNAKE_CASE__ : str = win_length SCREAMING_SNAKE_CASE__ : Optional[Any] = win_function SCREAMING_SNAKE_CASE__ : List[str] = fmin SCREAMING_SNAKE_CASE__ : Dict = fmax SCREAMING_SNAKE_CASE__ : int = mel_floor SCREAMING_SNAKE_CASE__ : Tuple = return_attention_mask def __lowercase( self : Dict )-> Dict: """simple docstring""" return { "feature_size": self.feature_size, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "do_normalize": self.do_normalize, "num_mel_bins": self.num_mel_bins, "hop_length": self.hop_length, "win_length": self.win_length, "win_function": self.win_function, "fmin": self.fmin, "fmax": self.fmax, "mel_floor": self.mel_floor, "return_attention_mask": self.return_attention_mask, } def __lowercase( self : List[Any] , a_ : str=False , a_ : List[Any]=False )-> Optional[Any]: """simple docstring""" def _flatten(a_ : int ): return list(itertools.chain(*a_ ) ) if equal_length: SCREAMING_SNAKE_CASE__ : Tuple = floats_list((self.batch_size, self.max_seq_length) ) else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Optional[int] = [ _flatten(floats_list((x, self.feature_size) ) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : int = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs def __lowercase( self : Any , a_ : int=False , a_ : Any=False )-> Union[str, Any]: """simple docstring""" if equal_length: SCREAMING_SNAKE_CASE__ : str = [floats_list((self.max_seq_length, self.num_mel_bins) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size SCREAMING_SNAKE_CASE__ : Tuple = [ floats_list((x, self.num_mel_bins) ) for x in range(self.min_seq_length , self.max_seq_length , self.seq_length_diff ) ] if numpify: SCREAMING_SNAKE_CASE__ : List[str] = [np.asarray(a_ ) for x in speech_inputs] return speech_inputs @require_torch class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = SpeechTaFeatureExtractor def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = SpeechTaFeatureExtractionTester(self ) def __lowercase( self : Any , a_ : Optional[int] )-> List[str]: """simple docstring""" self.assertTrue(np.all(np.mean(a_ , axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(a_ , axis=0 ) - 1 ) < 1e-3 ) ) def __lowercase( self : Tuple )-> Dict: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : str = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = [np.asarray(a_ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : List[Any] = feat_extract(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Dict = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Tuple = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : str = feat_extract(a_ , padding=a_ , max_length=a_ , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self.assertTrue(input_values[0][800:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self.assertTrue(input_values[0][1000:].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : List[Any] = range(800 , 1400 , 200 ) SCREAMING_SNAKE_CASE__ : int = [floats_list((1, x) )[0] for x in lengths] SCREAMING_SNAKE_CASE__ : int = ['longest', 'max_length', 'do_not_pad'] SCREAMING_SNAKE_CASE__ : Union[str, Any] = [None, 1600, None] for max_length, padding in zip(a_ , a_ ): SCREAMING_SNAKE_CASE__ : List[str] = feat_extract(a_ , max_length=a_ , padding=a_ ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0][:800] ) self._check_zero_mean_unit_variance(input_values[1][:1000] ) self._check_zero_mean_unit_variance(input_values[2][:1200] ) def __lowercase( self : int )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Tuple = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='max_length' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Optional[int] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1] ) self._check_zero_mean_unit_variance(input_values[2] ) def __lowercase( self : Optional[Any] )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : List[str] = feat_extract( a_ , truncation=a_ , max_length=1000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : int = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertTrue(input_values.shape == (3, 1000) ) SCREAMING_SNAKE_CASE__ : Optional[int] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : str = feat_extract( a_ , truncation=a_ , max_length=2000 , padding='longest' , return_tensors='np' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed.input_values self._check_zero_mean_unit_variance(input_values[0, :800] ) self._check_zero_mean_unit_variance(input_values[1, :1000] ) self._check_zero_mean_unit_variance(input_values[2] ) # make sure that if max_length > longest -> then pad to longest self.assertTrue(input_values.shape == (3, 1200) ) def __lowercase( self : Any )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.random.rand(100 ).astype(np.floataa ) SCREAMING_SNAKE_CASE__ : int = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: SCREAMING_SNAKE_CASE__ : Any = feature_extractor.pad([{'input_values': inputs}] , return_tensors='np' ) self.assertTrue(np_processed.input_values.dtype == np.floataa ) SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor.pad([{'input_values': inputs}] , return_tensors='pt' ) self.assertTrue(pt_processed.input_values.dtype == torch.floataa ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" # Tests that all call wrap to encode_plus and batch_encode_plus SCREAMING_SNAKE_CASE__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE__ : List[Any] = [floats_list((1, x) )[0] for x in range(800 , 1400 , 200 )] SCREAMING_SNAKE_CASE__ : Dict = [np.asarray(a_ ) for speech_input in speech_inputs] # Test feature size SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(audio_target=a_ , padding=a_ , return_tensors='np' ).input_values self.assertTrue(input_values.ndim == 3 ) self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins ) # Test not batched input SCREAMING_SNAKE_CASE__ : Tuple = feature_extractor(speech_inputs[0] , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : int = feature_extractor(np_speech_inputs[0] , return_tensors='np' ).input_values self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test batched SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : Optional[Any] = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) # Test 2-D numpy arrays are batched. SCREAMING_SNAKE_CASE__ : List[str] = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE__ : List[str] = np.asarray(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = feature_extractor(a_ , return_tensors='np' ).input_values SCREAMING_SNAKE_CASE__ : str = feature_extractor(a_ , return_tensors='np' ).input_values for enc_seq_a, enc_seq_a in zip(a_ , a_ ): self.assertTrue(np.allclose(a_ , a_ , atol=1e-3 ) ) def __lowercase( self : Dict )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : List[Any] = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} ) self.assertTrue(all(len(a_ ) == len(a_ ) for x, y in zip(a_ , processed_features[input_name] ) ) ) SCREAMING_SNAKE_CASE__ : str = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} , tensor_type='np' ) SCREAMING_SNAKE_CASE__ : List[Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : int = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : List[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target(equal_length=a_ ) SCREAMING_SNAKE_CASE__ : Dict = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Any = BatchFeature({input_name: speech_inputs} , tensor_type='pt' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = processed_features[input_name] if len(batch_features_input.shape ) < 3: SCREAMING_SNAKE_CASE__ : Optional[Any] = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.num_mel_bins) ) @require_torch def __lowercase( self : Tuple )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.feature_extraction_class(**self.feat_extract_dict ) SCREAMING_SNAKE_CASE__ : Dict = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : str = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : List[Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.pad(a_ , padding='longest' , return_tensors='np' )[input_name] SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='pt' )[input_name] self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1e-2 ) def __lowercase( self : Any )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Any = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Optional[int] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Union[str, Any] = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : Any = feat_extract.pad(a_ , padding='longest' , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) ) self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , a_ ) def __lowercase( self : str )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self.feat_extract_dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = True SCREAMING_SNAKE_CASE__ : Optional[Any] = self.feature_extraction_class(**a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.feat_extract_tester.prepare_inputs_for_target() SCREAMING_SNAKE_CASE__ : Tuple = [len(a_ ) for x in speech_inputs] SCREAMING_SNAKE_CASE__ : Union[str, Any] = feat_extract.model_input_names[0] SCREAMING_SNAKE_CASE__ : Dict = BatchFeature({input_name: speech_inputs} ) SCREAMING_SNAKE_CASE__ : str = min(a_ ) SCREAMING_SNAKE_CASE__ : Any = feat_extract.num_mel_bins # hack! SCREAMING_SNAKE_CASE__ : int = feat_extract.pad( a_ , padding='max_length' , max_length=a_ , truncation=a_ , return_tensors='np' ) self.assertIn('attention_mask' , a_ ) self.assertListEqual( list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] ) def __lowercase( self : Optional[int] , a_ : List[str] )-> Any: """simple docstring""" from datasets import load_dataset SCREAMING_SNAKE_CASE__ : int = load_dataset('hf-internal-testing/librispeech_asr_dummy' , 'clean' , split='validation' ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE__ : List[Any] = ds.sort('id' ).select(range(a_ ) )[:num_samples]['audio'] return [x["array"] for x in speech_samples] def __lowercase( self : List[str] )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : List[Any] = torch.tensor( [2.3_8_0_4e-0_3, 2.0_7_5_2e-0_3, 1.9_8_3_6e-0_3, 2.1_0_5_7e-0_3, 1.6_1_7_4e-0_3, 3.0_5_1_8e-0_4, 9.1_5_5_3e-0_5, 3.3_5_6_9e-0_4, 9.7_6_5_6e-0_4, 1.8_3_1_1e-0_3, 2.0_1_4_2e-0_3, 2.1_0_5_7e-0_3, 1.7_3_9_5e-0_3, 4.5_7_7_6e-0_4, -3.9_6_7_3e-0_4, 4.5_7_7_6e-0_4, 1.0_0_7_1e-0_3, 9.1_5_5_3e-0_5, 4.8_8_2_8e-0_4, 1.1_5_9_7e-0_3, 7.3_2_4_2e-0_4, 9.4_6_0_4e-0_4, 1.8_0_0_5e-0_3, 1.8_3_1_1e-0_3, 8.8_5_0_1e-0_4, 4.2_7_2_5e-0_4, 4.8_8_2_8e-0_4, 7.3_2_4_2e-0_4, 1.0_9_8_6e-0_3, 2.1_0_5_7e-0_3] ) # fmt: on SCREAMING_SNAKE_CASE__ : List[str] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : List[str] = feature_extractor(a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 9_3680) ) self.assertTrue(torch.allclose(input_values[0, :30] , a_ , atol=1e-6 ) ) def __lowercase( self : Tuple )-> List[Any]: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor( [-2.6870, -3.0104, -3.1356, -3.5352, -3.0044, -3.0353, -3.4719, -3.6777, -3.1520, -2.9435, -2.6553, -2.8795, -2.9944, -2.5921, -3.0279, -3.0386, -3.0864, -3.1291, -3.2353, -2.7444, -2.6831, -2.7287, -3.1761, -3.1571, -3.2726, -3.0582, -3.1007, -3.4533, -3.4695, -3.0998] ) # fmt: on SCREAMING_SNAKE_CASE__ : Optional[Any] = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE__ : int = SpeechTaFeatureExtractor() SCREAMING_SNAKE_CASE__ : str = feature_extractor(audio_target=a_ , return_tensors='pt' ).input_values self.assertEquals(input_values.shape , (1, 366, 80) ) self.assertTrue(torch.allclose(input_values[0, 0, :30] , a_ , atol=1e-4 ) )
636
0
import collections import inspect import unittest from transformers import SwinvaConfig 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, _config_zero_init, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class snake_case : def __init__( self : List[Any] , a_ : List[Any] , a_ : Tuple=13 , a_ : int=32 , a_ : Optional[Any]=2 , a_ : List[Any]=3 , a_ : str=16 , a_ : List[Any]=[1, 2, 1] , a_ : List[str]=[2, 2, 4] , a_ : str=2 , a_ : str=2.0 , a_ : Any=True , a_ : Optional[int]=0.0 , a_ : Dict=0.0 , a_ : int=0.1 , a_ : Optional[Any]="gelu" , a_ : Tuple=False , a_ : Any=True , a_ : int=0.02 , a_ : List[str]=1e-5 , a_ : List[str]=True , a_ : Optional[Any]=None , a_ : str=True , a_ : Optional[Any]=10 , a_ : int=8 , )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = parent SCREAMING_SNAKE_CASE__ : Tuple = batch_size SCREAMING_SNAKE_CASE__ : Any = image_size SCREAMING_SNAKE_CASE__ : Any = patch_size SCREAMING_SNAKE_CASE__ : Any = num_channels SCREAMING_SNAKE_CASE__ : Any = embed_dim SCREAMING_SNAKE_CASE__ : List[Any] = depths SCREAMING_SNAKE_CASE__ : List[Any] = num_heads SCREAMING_SNAKE_CASE__ : Optional[int] = window_size SCREAMING_SNAKE_CASE__ : str = mlp_ratio SCREAMING_SNAKE_CASE__ : Tuple = qkv_bias SCREAMING_SNAKE_CASE__ : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] = drop_path_rate SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_act SCREAMING_SNAKE_CASE__ : Optional[Any] = use_absolute_embeddings SCREAMING_SNAKE_CASE__ : Optional[int] = patch_norm SCREAMING_SNAKE_CASE__ : Optional[int] = layer_norm_eps SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Dict = is_training SCREAMING_SNAKE_CASE__ : str = scope SCREAMING_SNAKE_CASE__ : str = use_labels SCREAMING_SNAKE_CASE__ : Tuple = type_sequence_label_size SCREAMING_SNAKE_CASE__ : Any = encoder_stride def __lowercase( self : Any )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Any = None if self.use_labels: SCREAMING_SNAKE_CASE__ : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) SCREAMING_SNAKE_CASE__ : Optional[int] = self.get_config() return config, pixel_values, labels def __lowercase( self : int )-> Union[str, Any]: """simple docstring""" return SwinvaConfig( 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 , ) def __lowercase( self : List[str] , a_ : Optional[int] , a_ : List[Any] , a_ : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = SwinvaModel(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : List[Any] = model(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) ) def __lowercase( self : Optional[Any] , a_ : Optional[int] , a_ : Union[str, Any] , a_ : str )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = SwinvaForMaskedImageModeling(config=a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Tuple = model(a_ ) self.parent.assertEqual( result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images SCREAMING_SNAKE_CASE__ : Dict = 1 SCREAMING_SNAKE_CASE__ : Dict = SwinvaForMaskedImageModeling(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : Dict = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def __lowercase( self : int , a_ : Union[str, Any] , a_ : Union[str, Any] , a_ : List[str] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = self.type_sequence_label_size SCREAMING_SNAKE_CASE__ : int = SwinvaForImageClassification(a_ ) model.to(a_ ) model.eval() SCREAMING_SNAKE_CASE__ : int = model(a_ , labels=a_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def __lowercase( self : List[Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ : List[Any] = config_and_inputs SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) lowercase_ = ( {'feature-extraction': SwinvaModel, 'image-classification': SwinvaForImageClassification} if is_torch_available() else {} ) lowercase_ = False lowercase_ = False lowercase_ = False lowercase_ = False def __lowercase( self : Optional[Any] )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = SwinvaModelTester(self ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = ConfigTester(self , config_class=a_ , embed_dim=37 ) def __lowercase( self : Optional[Any] )-> str: """simple docstring""" self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def __lowercase( self : List[Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*a_ ) @unittest.skip(reason='Got `CUDA error: misaligned address` with PyTorch 2.0.0.' ) def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" pass @unittest.skip(reason='Swinv2 does not use inputs_embeds' ) def __lowercase( self : str )-> List[str]: """simple docstring""" pass def __lowercase( self : Any )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Dict = model_class(a_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) SCREAMING_SNAKE_CASE__ : Any = model.get_output_embeddings() self.assertTrue(x is None or isinstance(a_ , nn.Linear ) ) def __lowercase( self : Tuple )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[Any] = model_class(a_ ) SCREAMING_SNAKE_CASE__ : Any = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic SCREAMING_SNAKE_CASE__ : str = [*signature.parameters.keys()] SCREAMING_SNAKE_CASE__ : Optional[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1] , a_ ) def __lowercase( self : Any )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : str = True for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : str = True SCREAMING_SNAKE_CASE__ : Dict = False SCREAMING_SNAKE_CASE__ : int = True SCREAMING_SNAKE_CASE__ : Any = model_class(a_ ) model.to(a_ ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Tuple = model(**self._prepare_for_class(a_ , a_ ) ) SCREAMING_SNAKE_CASE__ : Optional[int] = outputs.attentions SCREAMING_SNAKE_CASE__ : Optional[int] = len(self.model_tester.depths ) self.assertEqual(len(a_ ) , a_ ) # check that output_attentions also work using config del inputs_dict["output_attentions"] SCREAMING_SNAKE_CASE__ : str = True SCREAMING_SNAKE_CASE__ : Tuple = config.window_size**2 SCREAMING_SNAKE_CASE__ : int = model_class(a_ ) model.to(a_ ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[str] = model(**self._prepare_for_class(a_ , a_ ) ) SCREAMING_SNAKE_CASE__ : Tuple = outputs.attentions self.assertEqual(len(a_ ) , a_ ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) SCREAMING_SNAKE_CASE__ : str = len(a_ ) # Check attention is always last and order is fine SCREAMING_SNAKE_CASE__ : Optional[Any] = True SCREAMING_SNAKE_CASE__ : str = True SCREAMING_SNAKE_CASE__ : Any = model_class(a_ ) model.to(a_ ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : int = model(**self._prepare_for_class(a_ , a_ ) ) if hasattr(self.model_tester , 'num_hidden_states_types' ): SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states SCREAMING_SNAKE_CASE__ : Dict = 2 self.assertEqual(out_len + added_hidden_states , len(a_ ) ) SCREAMING_SNAKE_CASE__ : int = outputs.attentions self.assertEqual(len(a_ ) , a_ ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , ) def __lowercase( self : str , a_ : Tuple , a_ : List[str] , a_ : Dict , a_ : Optional[Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = model_class(a_ ) model.to(a_ ) model.eval() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = model(**self._prepare_for_class(a_ , a_ ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = outputs.hidden_states SCREAMING_SNAKE_CASE__ : List[Any] = getattr( self.model_tester , 'expected_num_hidden_layers' , len(self.model_tester.depths ) + 1 ) self.assertEqual(len(a_ ) , a_ ) # Swinv2 has a different seq_length SCREAMING_SNAKE_CASE__ : Optional[int] = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) SCREAMING_SNAKE_CASE__ : List[str] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = outputs.reshaped_hidden_states self.assertEqual(len(a_ ) , a_ ) SCREAMING_SNAKE_CASE__ : Tuple = reshaped_hidden_states[0].shape SCREAMING_SNAKE_CASE__ : List[Any] = ( reshaped_hidden_states[0].view(a_ , a_ , height * width ).permute(0 , 2 , 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , ) def __lowercase( self : Tuple )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : List[Any] = ( self.model_tester.image_size if isinstance(self.model_tester.image_size , collections.abc.Iterable ) else (self.model_tester.image_size, self.model_tester.image_size) ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = True self.check_hidden_states_output(a_ , a_ , a_ , a_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : int = True self.check_hidden_states_output(a_ , a_ , a_ , a_ ) def __lowercase( self : str )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[Any] = 3 SCREAMING_SNAKE_CASE__ : 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) ) SCREAMING_SNAKE_CASE__ : Optional[int] = ( config.patch_size if isinstance(config.patch_size , collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) SCREAMING_SNAKE_CASE__ : int = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) SCREAMING_SNAKE_CASE__ : Any = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Any = True self.check_hidden_states_output(a_ , a_ , a_ , (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] SCREAMING_SNAKE_CASE__ : Optional[int] = True self.check_hidden_states_output(a_ , a_ , a_ , (padded_height, padded_width) ) def __lowercase( self : Dict )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*a_ ) def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*a_ ) @slow def __lowercase( self : List[Any] )-> int: """simple docstring""" for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: SCREAMING_SNAKE_CASE__ : Union[str, Any] = SwinvaModel.from_pretrained(a_ ) self.assertIsNotNone(a_ ) def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.model_tester.prepare_config_and_inputs_for_common() SCREAMING_SNAKE_CASE__ : Optional[int] = _config_zero_init(a_ ) for model_class in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = model_class(config=a_ ) for name, param in model.named_parameters(): if "embeddings" not in name and "logit_scale" not in name and param.requires_grad: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item() , [0.0, 1.0] , msg=F'''Parameter {name} of model {model_class} seems not properly initialized''' , ) @require_vision @require_torch class snake_case ( unittest.TestCase ): @cached_property def __lowercase( self : Optional[int] )-> str: """simple docstring""" return ( AutoImageProcessor.from_pretrained('microsoft/swinv2-tiny-patch4-window8-256' ) if is_vision_available() else None ) @slow def __lowercase( self : Optional[Any] )-> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = SwinvaForImageClassification.from_pretrained('microsoft/swinv2-tiny-patch4-window8-256' ).to( a_ ) SCREAMING_SNAKE_CASE__ : int = self.default_image_processor SCREAMING_SNAKE_CASE__ : List[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) SCREAMING_SNAKE_CASE__ : Optional[int] = image_processor(images=a_ , return_tensors='pt' ).to(a_ ) # forward pass with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(**a_ ) # verify the logits SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([-0.3947, -0.4306, 0.0026] ).to(a_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , a_ , atol=1e-4 ) )
709
import math import sys def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = '' try: with open(lowercase__ , 'rb' ) as binary_file: SCREAMING_SNAKE_CASE__ : Tuple = binary_file.read() for dat in data: SCREAMING_SNAKE_CASE__ : Tuple = f'''{dat:08b}''' result += curr_byte return result except OSError: print('File not accessible' ) sys.exit() def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[str] = {'0': '0', '1': '1'} SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = '', '' SCREAMING_SNAKE_CASE__ : Tuple = len(lowercase__ ) for i in range(len(lowercase__ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue SCREAMING_SNAKE_CASE__ : int = lexicon[curr_string] result += last_match_id SCREAMING_SNAKE_CASE__ : str = last_match_id + '0' if math.loga(lowercase__ ).is_integer(): SCREAMING_SNAKE_CASE__ : List[str] = {} for curr_key in list(lowercase__ ): SCREAMING_SNAKE_CASE__ : Optional[int] = lexicon.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = new_lex SCREAMING_SNAKE_CASE__ : Any = last_match_id + '1' index += 1 SCREAMING_SNAKE_CASE__ : Tuple = '' return result def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = 8 try: with open(lowercase__ , 'wb' ) as opened_file: SCREAMING_SNAKE_CASE__ : Dict = [ 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 _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = 0 for letter in data_bits: if letter == "1": break counter += 1 SCREAMING_SNAKE_CASE__ : Optional[int] = data_bits[counter:] SCREAMING_SNAKE_CASE__ : int = data_bits[counter + 1 :] return data_bits def _a ( lowercase__ : str , lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = read_file_binary(lowercase__ ) SCREAMING_SNAKE_CASE__ : Dict = remove_prefix(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = decompress_data(lowercase__ ) write_file_binary(lowercase__ , lowercase__ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
636
0
from math import pow def _a ( lowercase__ : int , lowercase__ : int , lowercase__ : int , lowercase__ : int , lowercase__ : int , ): '''simple docstring''' if current_sum == needed_sum: # If the sum of the powers is equal to needed_sum, then we have a solution. solutions_count += 1 return current_sum, solutions_count SCREAMING_SNAKE_CASE__ : Union[str, Any] = int(pow(lowercase__ , lowercase__ ) ) if current_sum + i_to_n <= needed_sum: # If the sum of the powers is less than needed_sum, then continue adding powers. current_sum += i_to_n SCREAMING_SNAKE_CASE__ : List[str] = backtrack( lowercase__ , lowercase__ , current_number + 1 , lowercase__ , lowercase__ ) current_sum -= i_to_n if i_to_n < needed_sum: # If the power of i is less than needed_sum, then try with the next power. SCREAMING_SNAKE_CASE__ : Optional[int] = backtrack( lowercase__ , lowercase__ , current_number + 1 , lowercase__ , lowercase__ ) return current_sum, solutions_count def _a ( lowercase__ : int , lowercase__ : int ): '''simple docstring''' if not (1 <= needed_sum <= 10_00 and 2 <= power <= 10): raise ValueError( 'Invalid input\n' 'needed_sum must be between 1 and 1000, power between 2 and 10.' ) return backtrack(lowercase__ , lowercase__ , 1 , 0 , 0 )[1] # Return the solutions_count if __name__ == "__main__": import doctest doctest.testmod()
710
def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : List[Any] = set({'(', '[', '{'} ) SCREAMING_SNAKE_CASE__ : Optional[int] = set({')', ']', '}'} ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {'{': '}', '[': ']', '(': ')'} for i in range(len(lowercase__ ) ): if s[i] in open_brackets: stack.append(s[i] ) elif s[i] in closed_brackets and ( len(lowercase__ ) == 0 or (len(lowercase__ ) > 0 and open_to_closed[stack.pop()] != s[i]) ): return False return len(lowercase__ ) == 0 def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = input('Enter sequence of brackets: ' ) if is_balanced(lowercase__ ): print(lowercase__ , 'is balanced' ) else: print(lowercase__ , 'is not balanced' ) if __name__ == "__main__": main()
636
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 SCREAMING_SNAKE_CASE__ : List[Any] = get_tests_dir("fixtures/test_sentencepiece_no_bos.model") @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : int )-> List[Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : List[Any] = PegasusTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def __lowercase( self : Any , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Union[str, Any] , a_ : List[Any] )-> Optional[int]: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : Optional[int] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = '</s>' SCREAMING_SNAKE_CASE__ : Any = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : Dict )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = 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(a_ ) , 1103 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( '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>' ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word SCREAMING_SNAKE_CASE__ : Any = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 SCREAMING_SNAKE_CASE__ : int = 'To ensure a smooth flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ['This is going to be way too long.' * 150, 'short example'] SCREAMING_SNAKE_CASE__ : int = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. @slow def __lowercase( self : Any )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 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], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 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=a_ , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Any )-> Union[str, Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Optional[int] = PegasusTokenizer(a_ , offset=0 , mask_token_sent=a_ , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> List[str]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def __lowercase( self : List[str] , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Optional[Any] , a_ : Tuple )-> str: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE__ : str = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : str = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) @require_torch def __lowercase( self : List[str] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = ['This is going to be way too long.' * 1000, 'short example'] SCREAMING_SNAKE_CASE__ : Optional[int] = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : str = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._large_tokenizer(a_ ).input_ids self.assertListEqual( a_ , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
711
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 SCREAMING_SNAKE_CASE__ : List[Any] = get_tests_dir("fixtures/test_sentencepiece_no_bos.model") @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : int )-> List[Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : List[Any] = PegasusTokenizer(a_ ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> Optional[int]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/pegasus-large' ) def __lowercase( self : Any , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Union[str, Any] , a_ : List[Any] )-> Optional[int]: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : Optional[int] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = '</s>' SCREAMING_SNAKE_CASE__ : Any = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(a_ ) , a_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(a_ ) , a_ ) def __lowercase( self : Dict )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = 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(a_ ) , 1103 ) def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1103 ) def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( '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>' ) SCREAMING_SNAKE_CASE__ : List[str] = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : Optional[Any] = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : Any )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer # <mask_1> masks whole sentence while <mask_2> masks single word SCREAMING_SNAKE_CASE__ : Any = '<mask_1> To ensure a <mask_2> flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [2, 413, 615, 114, 3, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : List[Any] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) def __lowercase( self : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = self._large_tokenizer # The tracebacks for the following asserts are **better** without messages or self.assertEqual assert tokenizer.vocab_size == 9_6103 assert tokenizer.pad_token_id == 0 assert tokenizer.eos_token_id == 1 assert tokenizer.offset == 103 assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105 assert tokenizer.unk_token == "<unk>" assert tokenizer.model_max_length == 1024 SCREAMING_SNAKE_CASE__ : int = 'To ensure a smooth flow of bank resolutions.' SCREAMING_SNAKE_CASE__ : List[Any] = [413, 615, 114, 2291, 1971, 113, 1679, 1_0710, 107, 1] SCREAMING_SNAKE_CASE__ : Optional[int] = tokenizer([raw_input_str] , return_tensors=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3] ) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"] @require_torch def __lowercase( self : Union[str, Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = ['This is going to be way too long.' * 150, 'short example'] SCREAMING_SNAKE_CASE__ : int = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : Optional[int] = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 1024) assert batch.attention_mask.shape == (2, 1024) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. @slow def __lowercase( self : Any )-> str: """simple docstring""" # fmt: off SCREAMING_SNAKE_CASE__ : Optional[int] = {'input_ids': [[3_8979, 143, 1_8485, 606, 130, 2_6669, 8_7686, 121, 5_4189, 1129, 111, 2_6669, 8_7686, 121, 9114, 1_4787, 121, 1_3249, 158, 592, 956, 121, 1_4621, 3_1576, 143, 6_2613, 108, 9688, 930, 4_3430, 1_1562, 6_2613, 304, 108, 1_1443, 897, 108, 9314, 1_7415, 6_3399, 108, 1_1443, 7614, 1_8316, 118, 4284, 7148, 1_2430, 143, 1400, 2_5703, 158, 111, 4284, 7148, 1_1772, 143, 2_1297, 1064, 158, 122, 204, 3506, 1754, 1133, 1_4787, 1581, 115, 3_3224, 4482, 111, 1355, 110, 2_9173, 317, 5_0833, 108, 2_0147, 9_4665, 111, 7_7198, 107, 1], [110, 6_2613, 117, 638, 112, 1133, 121, 2_0098, 1355, 7_9050, 1_3872, 135, 1596, 5_3541, 1352, 141, 1_3039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 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], [139, 1235, 2799, 1_8289, 1_7780, 204, 109, 9474, 1296, 107, 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=a_ , model_name='google/bigbird-pegasus-large-arxiv' , revision='ba85d0851d708441f91440d509690f1ab6353415' , ) @require_sentencepiece @require_tokenizers class snake_case ( UpperCamelCase_ , unittest.TestCase ): lowercase_ = PegasusTokenizer lowercase_ = PegasusTokenizerFast lowercase_ = True lowercase_ = True def __lowercase( self : Any )-> Union[str, Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing SCREAMING_SNAKE_CASE__ : Optional[int] = PegasusTokenizer(a_ , offset=0 , mask_token_sent=a_ , mask_token='[MASK]' ) tokenizer.save_pretrained(self.tmpdirname ) @cached_property def __lowercase( self : Optional[Any] )-> List[str]: """simple docstring""" return PegasusTokenizer.from_pretrained('google/bigbird-pegasus-large-arxiv' ) def __lowercase( self : List[str] , **a_ : Optional[Any] )-> PegasusTokenizer: """simple docstring""" return PegasusTokenizer.from_pretrained(self.tmpdirname , **a_ ) def __lowercase( self : Optional[Any] , a_ : Tuple )-> str: """simple docstring""" return ("This is a test", "This is a test") def __lowercase( self : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = self.rust_tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.tokenizer_class.from_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'Let\'s see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>' ' <pad> <pad> <pad>' ) SCREAMING_SNAKE_CASE__ : str = rust_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] SCREAMING_SNAKE_CASE__ : str = py_tokenizer([raw_input_str] , return_tensors=a_ , add_special_tokens=a_ ).input_ids[0] self.assertListEqual(a_ , a_ ) @require_torch def __lowercase( self : List[str] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = ['This is going to be way too long.' * 1000, 'short example'] SCREAMING_SNAKE_CASE__ : Optional[int] = ['not super long but more than 5 tokens', 'tiny'] SCREAMING_SNAKE_CASE__ : str = self._large_tokenizer(a_ , padding=a_ , truncation=a_ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : int = self._large_tokenizer( text_target=a_ , max_length=5 , padding=a_ , truncation=a_ , return_tensors='pt' ) assert batch.input_ids.shape == (2, 4096) assert batch.attention_mask.shape == (2, 4096) assert targets["input_ids"].shape == (2, 5) assert len(a_ ) == 2 # input_ids, attention_mask. def __lowercase( self : Dict )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = ( 'This is an example string that is used to test the original TF implementation against the HF' ' implementation' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self._large_tokenizer(a_ ).input_ids self.assertListEqual( a_ , [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 2_5016, 3137, 464, 109, 2_6955, 3137, 1] , )
636
0
import inspect import jax import jax.lax as lax import jax.numpy as jnp from ..utils import add_start_docstrings from ..utils.logging import get_logger SCREAMING_SNAKE_CASE__ : Optional[Any] = get_logger(__name__) SCREAMING_SNAKE_CASE__ : List[Any] = r"\n Args:\n input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary.\n\n Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`):\n Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam\n search or log softmax for each vocabulary token when using beam search\n kwargs (`Dict[str, Any]`, *optional*):\n Additional logits processor specific kwargs.\n\n Return:\n `jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.\n\n" class snake_case : @add_start_docstrings(a_ ) def __call__( self : Optional[int] , a_ : jnp.ndarray , a_ : jnp.ndarray )-> jnp.ndarray: """simple docstring""" raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) class snake_case : @add_start_docstrings(a_ ) def __call__( self : Any , a_ : jnp.ndarray , a_ : jnp.ndarray )-> jnp.ndarray: """simple docstring""" raise NotImplementedError( F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.''' ) class snake_case ( UpperCamelCase_ ): @add_start_docstrings(a_ ) def __call__( self : Optional[Any] , a_ : jnp.ndarray , a_ : jnp.ndarray , a_ : int , **a_ : Union[str, Any] )-> jnp.ndarray: """simple docstring""" for processor in self: SCREAMING_SNAKE_CASE__ : List[str] = inspect.signature(processor.__call__ ).parameters if len(a_ ) > 3: if not all(arg in kwargs for arg in list(function_args.keys() )[2:] ): raise ValueError( F'''Make sure that all the required parameters: {list(function_args.keys() )} for ''' F'''{processor.__class__} are passed to the logits processor.''' ) SCREAMING_SNAKE_CASE__ : int = processor(a_ , a_ , a_ , **a_ ) else: SCREAMING_SNAKE_CASE__ : int = processor(a_ , a_ , a_ ) return scores class snake_case ( UpperCamelCase_ ): def __init__( self : Optional[Any] , a_ : float )-> str: """simple docstring""" if not isinstance(a_ , a_ ) or not (temperature > 0): raise ValueError(F'''`temperature` has to be a strictly positive float, but is {temperature}''' ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = temperature def __call__( self : Any , a_ : jnp.ndarray , a_ : jnp.ndarray , a_ : int )-> jnp.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = scores / self.temperature return scores class snake_case ( UpperCamelCase_ ): def __init__( self : Optional[Any] , a_ : float , a_ : float = -float('Inf' ) , a_ : int = 1 )-> Tuple: """simple docstring""" if not isinstance(a_ , a_ ) or (top_p < 0 or top_p > 1.0): raise ValueError(F'''`top_p` has to be a float > 0 and < 1, but is {top_p}''' ) if not isinstance(a_ , a_ ) or (min_tokens_to_keep < 1): raise ValueError(F'''`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = top_p SCREAMING_SNAKE_CASE__ : Optional[int] = filter_value SCREAMING_SNAKE_CASE__ : Optional[Any] = min_tokens_to_keep def __call__( self : Any , a_ : jnp.ndarray , a_ : jnp.ndarray , a_ : int )-> jnp.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = lax.top_k(a_ , scores.shape[-1] ) SCREAMING_SNAKE_CASE__ : List[str] = jnp.full_like(a_ , self.filter_value ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jax.nn.softmax(a_ , axis=-1 ).cumsum(axis=-1 ) SCREAMING_SNAKE_CASE__ : Optional[int] = cumulative_probs < self.top_p # include the token that is higher than top_p as well SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.roll(a_ , 1 ) score_mask |= score_mask.at[:, 0].set(a_ ) # min tokens to keep SCREAMING_SNAKE_CASE__ : Optional[Any] = score_mask.at[:, : self.min_tokens_to_keep].set(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = jnp.where(a_ , a_ , a_ ) SCREAMING_SNAKE_CASE__ : Any = jax.lax.sort_key_val(a_ , a_ )[-1] return next_scores class snake_case ( UpperCamelCase_ ): def __init__( self : Union[str, Any] , a_ : int , a_ : float = -float('Inf' ) , a_ : int = 1 )-> Optional[Any]: """simple docstring""" if not isinstance(a_ , a_ ) or top_k <= 0: raise ValueError(F'''`top_k` has to be a strictly positive integer, but is {top_k}''' ) SCREAMING_SNAKE_CASE__ : str = max(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Dict = filter_value def __call__( self : Dict , a_ : jnp.ndarray , a_ : jnp.ndarray , a_ : int )-> jnp.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = scores.shape SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.full(batch_size * vocab_size , self.filter_value ) SCREAMING_SNAKE_CASE__ : List[Any] = min(self.top_k , scores.shape[-1] ) # Safety check SCREAMING_SNAKE_CASE__ : Dict = lax.top_k(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Any = jnp.broadcast_to((jnp.arange(a_ ) * vocab_size)[:, None] , (batch_size, topk) ).flatten() SCREAMING_SNAKE_CASE__ : Any = topk_scores.flatten() SCREAMING_SNAKE_CASE__ : Union[str, Any] = topk_indices.flatten() + shift SCREAMING_SNAKE_CASE__ : Optional[int] = next_scores_flat.at[topk_indices_flat].set(a_ ) SCREAMING_SNAKE_CASE__ : str = next_scores_flat.reshape(a_ , a_ ) return next_scores class snake_case ( UpperCamelCase_ ): def __init__( self : str , a_ : int )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = bos_token_id def __call__( self : Optional[int] , a_ : jnp.ndarray , a_ : jnp.ndarray , a_ : int )-> jnp.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = jnp.full(scores.shape , -float('inf' ) ) SCREAMING_SNAKE_CASE__ : int = 1 - jnp.bool_(cur_len - 1 ) SCREAMING_SNAKE_CASE__ : Any = jnp.where(a_ , new_scores.at[:, self.bos_token_id].set(0 ) , a_ ) return scores class snake_case ( UpperCamelCase_ ): def __init__( self : Any , a_ : int , a_ : int )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = max_length SCREAMING_SNAKE_CASE__ : Dict = eos_token_id def __call__( self : Tuple , a_ : jnp.ndarray , a_ : jnp.ndarray , a_ : int )-> jnp.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.full(scores.shape , -float('inf' ) ) SCREAMING_SNAKE_CASE__ : List[str] = 1 - jnp.bool_(cur_len - self.max_length + 1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jnp.where(a_ , new_scores.at[:, self.eos_token_id].set(0 ) , a_ ) return scores class snake_case ( UpperCamelCase_ ): def __init__( self : Optional[Any] , a_ : int , a_ : int )-> Dict: """simple docstring""" if not isinstance(a_ , a_ ) or min_length < 0: raise ValueError(F'''`min_length` has to be a positive integer, but is {min_length}''' ) if not isinstance(a_ , a_ ) or eos_token_id < 0: raise ValueError(F'''`eos_token_id` has to be a positive integer, but is {eos_token_id}''' ) SCREAMING_SNAKE_CASE__ : Dict = min_length SCREAMING_SNAKE_CASE__ : Optional[Any] = eos_token_id def __call__( self : Any , a_ : jnp.ndarray , a_ : jnp.ndarray , a_ : int )-> jnp.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 1 - jnp.clip(cur_len - self.min_length , 0 , 1 ) SCREAMING_SNAKE_CASE__ : Dict = jnp.where(a_ , scores.at[:, self.eos_token_id].set(-float('inf' ) ) , a_ ) return scores class snake_case ( UpperCamelCase_ ): def __init__( self : Tuple , a_ : List[str] , a_ : Optional[int] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = list(a_ ) SCREAMING_SNAKE_CASE__ : int = begin_index def __call__( self : List[Any] , a_ : Dict , a_ : Optional[Any] , a_ : int )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = 1 - jnp.bool_(cur_len - self.begin_index ) SCREAMING_SNAKE_CASE__ : Optional[int] = jnp.where(a_ , scores.at[:, self.begin_suppress_tokens].set(-float('inf' ) ) , a_ ) return scores class snake_case ( UpperCamelCase_ ): def __init__( self : List[Any] , a_ : list )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = list(a_ ) def __call__( self : List[Any] , a_ : jnp.ndarray , a_ : jnp.ndarray , a_ : int )-> jnp.ndarray: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = scores.at[..., self.suppress_tokens].set(-float('inf' ) ) return scores class snake_case ( UpperCamelCase_ ): def __init__( self : List[Any] , a_ : Union[str, Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = dict(a_ ) # Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the # index of the array corresponds to the index of the token to be forced, for XLA compatibility. # Indexes without forced tokens will have a negative value. SCREAMING_SNAKE_CASE__ : int = jnp.ones((max(force_token_map.keys() ) + 1) , dtype=jnp.intaa ) * -1 for index, token in force_token_map.items(): if token is not None: SCREAMING_SNAKE_CASE__ : List[Any] = force_token_array.at[index].set(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.intaa(a_ ) def __call__( self : str , a_ : jnp.ndarray , a_ : jnp.ndarray , a_ : int )-> jnp.ndarray: """simple docstring""" def _force_token(a_ : Any ): SCREAMING_SNAKE_CASE__ : List[str] = scores.shape[0] SCREAMING_SNAKE_CASE__ : str = self.force_token_array[generation_idx] SCREAMING_SNAKE_CASE__ : Tuple = jnp.ones_like(a_ , dtype=scores.dtype ) * -float('inf' ) SCREAMING_SNAKE_CASE__ : List[str] = jnp.zeros((batch_size, 1) , dtype=scores.dtype ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = lax.dynamic_update_slice(a_ , a_ , (0, current_token) ) return new_scores SCREAMING_SNAKE_CASE__ : Any = lax.cond( cur_len >= self.force_token_array.shape[0] , lambda: scores , lambda: lax.cond( self.force_token_array[cur_len] >= 0 , lambda: _force_token(a_ ) , lambda: scores , ) , ) return scores class snake_case ( UpperCamelCase_ ): def __init__( self : int , a_ : Dict , a_ : Optional[int] , a_ : List[Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = generate_config.eos_token_id SCREAMING_SNAKE_CASE__ : Union[str, Any] = generate_config.no_timestamps_token_id SCREAMING_SNAKE_CASE__ : Optional[int] = generate_config.no_timestamps_token_id + 1 SCREAMING_SNAKE_CASE__ : int = decoder_input_length + 1 if generate_config.is_multilingual: # room for language token and task token self.begin_index += 2 if hasattr(a_ , 'max_initial_timestamp_index' ): SCREAMING_SNAKE_CASE__ : str = generate_config.max_initial_timestamp_index else: SCREAMING_SNAKE_CASE__ : List[Any] = model_config.vocab_size if self.max_initial_timestamp_index is None: SCREAMING_SNAKE_CASE__ : str = model_config.vocab_size def __call__( self : Union[str, Any] , a_ : List[str] , a_ : List[Any] , a_ : List[Any] )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = scores.at[:, self.no_timestamps_token_id].set(-float('inf' ) ) def handle_pairs(a_ : int , a_ : Union[str, Any] ): SCREAMING_SNAKE_CASE__ : List[str] = jnp.where((cur_len - self.begin_index) >= 1 , a_ , a_ ) SCREAMING_SNAKE_CASE__ : str = jnp.where( input_ids_k[cur_len - 1] >= self.timestamp_begin , True and last_was_timestamp , a_ , ) SCREAMING_SNAKE_CASE__ : List[Any] = jnp.where((cur_len - self.begin_index) < 2 , a_ , a_ ) SCREAMING_SNAKE_CASE__ : int = jnp.where( input_ids_k[cur_len - 2] >= self.timestamp_begin , a_ , a_ , ) return jnp.where( a_ , jnp.where( penultimate_was_timestamp > 0 , scores_k.at[self.timestamp_begin :].set(-float('inf' ) ) , scores_k.at[: self.eos_token_id].set(-float('inf' ) ) , ) , a_ , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jax.vmap(a_ )(a_ , a_ ) SCREAMING_SNAKE_CASE__ : int = jnp.where(cur_len == self.begin_index , a_ , a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = jnp.where( self.max_initial_timestamp_index is not None , True and apply_max_initial_timestamp , a_ , ) SCREAMING_SNAKE_CASE__ : str = self.timestamp_begin + self.max_initial_timestamp_index SCREAMING_SNAKE_CASE__ : List[str] = jnp.where( a_ , scores.at[:, last_allowed + 1 :].set(-float('inf' ) ) , a_ , ) # if sum of probability over timestamps is above any other token, sample timestamp SCREAMING_SNAKE_CASE__ : Union[str, Any] = jax.nn.log_softmax(a_ , axis=-1 ) def handle_cumulative_probs(a_ : str , a_ : Any ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = jax.nn.logsumexp(logprobs_k[self.timestamp_begin :] , axis=-1 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jnp.max(logprobs_k[: self.timestamp_begin] ) return jnp.where( timestamp_logprob > max_text_token_logprob , scores_k.at[: self.timestamp_begin].set(-float('inf' ) ) , a_ , ) SCREAMING_SNAKE_CASE__ : List[str] = jax.vmap(a_ )(a_ , a_ ) return scores
712
def _a ( lowercase__ : int = 1_00_00_00 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : str = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , lowercase__ ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
636
0
import argparse import torch from transformers import ( EncodecConfig, EncodecFeatureExtractor, EncodecModel, logging, ) # checkpoints downloaded from: # https://dl.fbaipublicfiles.com/encodec/v0/encodec_24khz-d7cc33bc.th # https://huggingface.co/facebook/musicgen-small/resolve/main/compression_state_dict.bin # https://dl.fbaipublicfiles.com/encodec/v0/encodec_48khz-7e698e3e.th logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : Union[str, Any] = logging.get_logger("transformers.models.encodec") SCREAMING_SNAKE_CASE__ : Tuple = { "quantizer.vq.layers.*._codebook.inited": "quantizer.layers.*.codebook.inited", "quantizer.vq.layers.*._codebook.cluster_size": "quantizer.layers.*.codebook.cluster_size", "quantizer.vq.layers.*._codebook.embed": "quantizer.layers.*.codebook.embed", "quantizer.vq.layers.*._codebook.embed_avg": "quantizer.layers.*.codebook.embed_avg", } SCREAMING_SNAKE_CASE__ : Union[str, Any] = { "encoder.model.0.conv.conv": "encoder.layers.0.conv", "encoder.model.1.block.1.conv.conv": "encoder.layers.1.block.1.conv", "encoder.model.1.block.3.conv.conv": "encoder.layers.1.block.3.conv", "encoder.model.1.shortcut.conv.conv": "encoder.layers.1.shortcut.conv", "encoder.model.3.conv.conv": "encoder.layers.3.conv", "encoder.model.4.block.1.conv.conv": "encoder.layers.4.block.1.conv", "encoder.model.4.block.3.conv.conv": "encoder.layers.4.block.3.conv", "encoder.model.4.shortcut.conv.conv": "encoder.layers.4.shortcut.conv", "encoder.model.6.conv.conv": "encoder.layers.6.conv", "encoder.model.7.block.1.conv.conv": "encoder.layers.7.block.1.conv", "encoder.model.7.block.3.conv.conv": "encoder.layers.7.block.3.conv", "encoder.model.7.shortcut.conv.conv": "encoder.layers.7.shortcut.conv", "encoder.model.9.conv.conv": "encoder.layers.9.conv", "encoder.model.10.block.1.conv.conv": "encoder.layers.10.block.1.conv", "encoder.model.10.block.3.conv.conv": "encoder.layers.10.block.3.conv", "encoder.model.10.shortcut.conv.conv": "encoder.layers.10.shortcut.conv", "encoder.model.12.conv.conv": "encoder.layers.12.conv", "encoder.model.13.lstm": "encoder.layers.13.lstm", "encoder.model.15.conv.conv": "encoder.layers.15.conv", } SCREAMING_SNAKE_CASE__ : str = { "encoder.model.0.conv.norm": "encoder.layers.0.norm", "encoder.model.1.block.1.conv.norm": "encoder.layers.1.block.1.norm", "encoder.model.1.block.3.conv.norm": "encoder.layers.1.block.3.norm", "encoder.model.1.shortcut.conv.norm": "encoder.layers.1.shortcut.norm", "encoder.model.3.conv.norm": "encoder.layers.3.norm", "encoder.model.4.block.1.conv.norm": "encoder.layers.4.block.1.norm", "encoder.model.4.block.3.conv.norm": "encoder.layers.4.block.3.norm", "encoder.model.4.shortcut.conv.norm": "encoder.layers.4.shortcut.norm", "encoder.model.6.conv.norm": "encoder.layers.6.norm", "encoder.model.7.block.1.conv.norm": "encoder.layers.7.block.1.norm", "encoder.model.7.block.3.conv.norm": "encoder.layers.7.block.3.norm", "encoder.model.7.shortcut.conv.norm": "encoder.layers.7.shortcut.norm", "encoder.model.9.conv.norm": "encoder.layers.9.norm", "encoder.model.10.block.1.conv.norm": "encoder.layers.10.block.1.norm", "encoder.model.10.block.3.conv.norm": "encoder.layers.10.block.3.norm", "encoder.model.10.shortcut.conv.norm": "encoder.layers.10.shortcut.norm", "encoder.model.12.conv.norm": "encoder.layers.12.norm", "encoder.model.15.conv.norm": "encoder.layers.15.norm", } SCREAMING_SNAKE_CASE__ : Any = { "decoder.model.0.conv.conv": "decoder.layers.0.conv", "decoder.model.1.lstm": "decoder.layers.1.lstm", "decoder.model.3.convtr.convtr": "decoder.layers.3.conv", "decoder.model.4.block.1.conv.conv": "decoder.layers.4.block.1.conv", "decoder.model.4.block.3.conv.conv": "decoder.layers.4.block.3.conv", "decoder.model.4.shortcut.conv.conv": "decoder.layers.4.shortcut.conv", "decoder.model.6.convtr.convtr": "decoder.layers.6.conv", "decoder.model.7.block.1.conv.conv": "decoder.layers.7.block.1.conv", "decoder.model.7.block.3.conv.conv": "decoder.layers.7.block.3.conv", "decoder.model.7.shortcut.conv.conv": "decoder.layers.7.shortcut.conv", "decoder.model.9.convtr.convtr": "decoder.layers.9.conv", "decoder.model.10.block.1.conv.conv": "decoder.layers.10.block.1.conv", "decoder.model.10.block.3.conv.conv": "decoder.layers.10.block.3.conv", "decoder.model.10.shortcut.conv.conv": "decoder.layers.10.shortcut.conv", "decoder.model.12.convtr.convtr": "decoder.layers.12.conv", "decoder.model.13.block.1.conv.conv": "decoder.layers.13.block.1.conv", "decoder.model.13.block.3.conv.conv": "decoder.layers.13.block.3.conv", "decoder.model.13.shortcut.conv.conv": "decoder.layers.13.shortcut.conv", "decoder.model.15.conv.conv": "decoder.layers.15.conv", } SCREAMING_SNAKE_CASE__ : str = { "decoder.model.0.conv.norm": "decoder.layers.0.norm", "decoder.model.3.convtr.norm": "decoder.layers.3.norm", "decoder.model.4.block.1.conv.norm": "decoder.layers.4.block.1.norm", "decoder.model.4.block.3.conv.norm": "decoder.layers.4.block.3.norm", "decoder.model.4.shortcut.conv.norm": "decoder.layers.4.shortcut.norm", "decoder.model.6.convtr.norm": "decoder.layers.6.norm", "decoder.model.7.block.1.conv.norm": "decoder.layers.7.block.1.norm", "decoder.model.7.block.3.conv.norm": "decoder.layers.7.block.3.norm", "decoder.model.7.shortcut.conv.norm": "decoder.layers.7.shortcut.norm", "decoder.model.9.convtr.norm": "decoder.layers.9.norm", "decoder.model.10.block.1.conv.norm": "decoder.layers.10.block.1.norm", "decoder.model.10.block.3.conv.norm": "decoder.layers.10.block.3.norm", "decoder.model.10.shortcut.conv.norm": "decoder.layers.10.shortcut.norm", "decoder.model.12.convtr.norm": "decoder.layers.12.norm", "decoder.model.13.block.1.conv.norm": "decoder.layers.13.block.1.norm", "decoder.model.13.block.3.conv.norm": "decoder.layers.13.block.3.norm", "decoder.model.13.shortcut.conv.norm": "decoder.layers.13.shortcut.norm", "decoder.model.15.conv.norm": "decoder.layers.15.norm", } SCREAMING_SNAKE_CASE__ : str = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_DECODER, } SCREAMING_SNAKE_CASE__ : Union[str, Any] = { **MAPPING_QUANTIZER, **MAPPING_ENCODER, **MAPPING_ENCODER_48K, **MAPPING_DECODER, **MAPPING_DECODER_48K, } SCREAMING_SNAKE_CASE__ : List[str] = [] SCREAMING_SNAKE_CASE__ : Dict = [] def _a ( lowercase__ : Union[str, Any] , lowercase__ : int , lowercase__ : Any , lowercase__ : Optional[Any] , lowercase__ : List[Any] ): '''simple docstring''' for attribute in key.split('.' ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = getattr(lowercase__ , lowercase__ ) if weight_type is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = getattr(lowercase__ , lowercase__ ).shape else: SCREAMING_SNAKE_CASE__ : Optional[int] = hf_pointer.shape if hf_shape != value.shape: raise ValueError( f'''Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be''' f''' {value.shape} for {full_name}''' ) if weight_type == "weight": SCREAMING_SNAKE_CASE__ : int = value elif weight_type == "weight_g": SCREAMING_SNAKE_CASE__ : Optional[int] = value elif weight_type == "weight_v": SCREAMING_SNAKE_CASE__ : List[Any] = value elif weight_type == "bias": SCREAMING_SNAKE_CASE__ : Optional[int] = value elif weight_type == "running_mean": SCREAMING_SNAKE_CASE__ : List[Any] = value elif weight_type == "running_var": SCREAMING_SNAKE_CASE__ : List[Any] = value elif weight_type == "num_batches_tracked": SCREAMING_SNAKE_CASE__ : Dict = value elif weight_type == "weight_ih_l0": SCREAMING_SNAKE_CASE__ : str = value elif weight_type == "weight_hh_l0": SCREAMING_SNAKE_CASE__ : Dict = value elif weight_type == "bias_ih_l0": SCREAMING_SNAKE_CASE__ : Tuple = value elif weight_type == "bias_hh_l0": SCREAMING_SNAKE_CASE__ : int = value elif weight_type == "weight_ih_l1": SCREAMING_SNAKE_CASE__ : str = value elif weight_type == "weight_hh_l1": SCREAMING_SNAKE_CASE__ : Any = value elif weight_type == "bias_ih_l1": SCREAMING_SNAKE_CASE__ : Optional[int] = value elif weight_type == "bias_hh_l1": SCREAMING_SNAKE_CASE__ : str = value else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = value logger.info(f'''{key + ('.' + weight_type if weight_type is not None else '')} was initialized from {full_name}.''' ) def _a ( lowercase__ : Tuple , lowercase__ : Tuple ): '''simple docstring''' for key in ignore_keys: if key.endswith('.*' ): if name.startswith(key[:-1] ): return True elif ".*." in key: SCREAMING_SNAKE_CASE__ : Optional[Any] = key.split('.*.' ) if prefix in name and suffix in name: return True elif key in name: return True return False def _a ( lowercase__ : Union[str, Any] , lowercase__ : Optional[Any] , lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = [] if model_name == "encodec_24khz" or "encodec_32khz": SCREAMING_SNAKE_CASE__ : Tuple = MAPPING_24K elif model_name == "encodec_48khz": SCREAMING_SNAKE_CASE__ : str = MAPPING_48K else: raise ValueError(f'''Unsupported model: {model_name}''' ) for name, value in orig_dict.items(): if should_ignore(lowercase__ , lowercase__ ): logger.info(f'''{name} was ignored''' ) continue SCREAMING_SNAKE_CASE__ : Any = False for key, mapped_key in MAPPING.items(): if "*" in key: SCREAMING_SNAKE_CASE__ : int = key.split('.*.' ) if prefix in name and suffix in name: SCREAMING_SNAKE_CASE__ : Dict = suffix if key in name: # HACK otherwise .embed gets initialized with .embed_avg too if key.endswith('embed' ) and name.endswith('embed_avg' ): continue SCREAMING_SNAKE_CASE__ : int = True if "*" in mapped_key: SCREAMING_SNAKE_CASE__ : str = name.split(lowercase__ )[0].split('.' )[-2] SCREAMING_SNAKE_CASE__ : Union[str, Any] = mapped_key.replace('*' , lowercase__ ) if "weight_g" in name: SCREAMING_SNAKE_CASE__ : Optional[int] = 'weight_g' elif "weight_v" in name: SCREAMING_SNAKE_CASE__ : Tuple = 'weight_v' elif "weight_ih_l0" in name: SCREAMING_SNAKE_CASE__ : List[Any] = 'weight_ih_l0' elif "weight_hh_l0" in name: SCREAMING_SNAKE_CASE__ : List[Any] = 'weight_hh_l0' elif "bias_ih_l0" in name: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'bias_ih_l0' elif "bias_hh_l0" in name: SCREAMING_SNAKE_CASE__ : Optional[int] = 'bias_hh_l0' elif "weight_ih_l1" in name: SCREAMING_SNAKE_CASE__ : Dict = 'weight_ih_l1' elif "weight_hh_l1" in name: SCREAMING_SNAKE_CASE__ : Tuple = 'weight_hh_l1' elif "bias_ih_l1" in name: SCREAMING_SNAKE_CASE__ : Optional[int] = 'bias_ih_l1' elif "bias_hh_l1" in name: SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'bias_hh_l1' elif "bias" in name: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'bias' elif "weight" in name: SCREAMING_SNAKE_CASE__ : Optional[int] = 'weight' elif "running_mean" in name: SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'running_mean' elif "running_var" in name: SCREAMING_SNAKE_CASE__ : List[str] = 'running_var' elif "num_batches_tracked" in name: SCREAMING_SNAKE_CASE__ : Union[str, Any] = 'num_batches_tracked' else: SCREAMING_SNAKE_CASE__ : Optional[Any] = None set_recursively(lowercase__ , lowercase__ , lowercase__ , lowercase__ , lowercase__ ) continue if not is_used: unused_weights.append(lowercase__ ) logger.warning(f'''Unused weights: {unused_weights}''' ) @torch.no_grad() def _a ( lowercase__ : Tuple , lowercase__ : Union[str, Any] , lowercase__ : List[str] , lowercase__ : Optional[Any]=None , lowercase__ : List[Any]=None , ): '''simple docstring''' if config_path is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = EncodecConfig.from_pretrained(lowercase__ ) else: SCREAMING_SNAKE_CASE__ : List[Any] = EncodecConfig() if model_name == "encodec_24khz": pass # config is already correct elif model_name == "encodec_32khz": SCREAMING_SNAKE_CASE__ : Optional[int] = [8, 5, 4, 4] SCREAMING_SNAKE_CASE__ : List[Any] = [2.2] SCREAMING_SNAKE_CASE__ : Dict = 64 SCREAMING_SNAKE_CASE__ : Dict = 3_20_00 SCREAMING_SNAKE_CASE__ : Optional[Any] = 20_48 SCREAMING_SNAKE_CASE__ : Tuple = False SCREAMING_SNAKE_CASE__ : Union[str, Any] = False SCREAMING_SNAKE_CASE__ : Optional[Any] = False elif model_name == "encodec_48khz": SCREAMING_SNAKE_CASE__ : Optional[Any] = [8, 5, 4, 2] SCREAMING_SNAKE_CASE__ : Any = [3.0, 6.0, 12.0, 24.0] SCREAMING_SNAKE_CASE__ : int = 4_80_00 SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Optional[Any] = False SCREAMING_SNAKE_CASE__ : Tuple = 'time_group_norm' SCREAMING_SNAKE_CASE__ : int = True SCREAMING_SNAKE_CASE__ : List[str] = 1.0 SCREAMING_SNAKE_CASE__ : Tuple = 0.01 else: raise ValueError(f'''Unknown model name: {model_name}''' ) SCREAMING_SNAKE_CASE__ : Any = EncodecModel(lowercase__ ) SCREAMING_SNAKE_CASE__ : int = EncodecFeatureExtractor( feature_size=config.audio_channels , sampling_rate=config.sampling_rate , chunk_length_s=config.chunk_length_s , overlap=config.overlap , ) feature_extractor.save_pretrained(lowercase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.load(lowercase__ ) if "best_state" in original_checkpoint: # we might have a training state saved, in which case discard the yaml results and just retain the weights SCREAMING_SNAKE_CASE__ : str = original_checkpoint['best_state'] recursively_load_weights(lowercase__ , lowercase__ , lowercase__ ) model.save_pretrained(lowercase__ ) if repo_id: print('Pushing to the hub...' ) feature_extractor.push_to_hub(lowercase__ ) model.push_to_hub(lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : int = argparse.ArgumentParser() parser.add_argument( "--model", default="encodec_24khz", type=str, help="The model to convert. Should be one of 'encodec_24khz', 'encodec_32khz', 'encodec_48khz'.", ) parser.add_argument("--checkpoint_path", required=True, default=None, type=str, help="Path to original checkpoint") parser.add_argument("--config_path", default=None, type=str, help="Path to hf config.json of model to convert") parser.add_argument( "--pytorch_dump_folder_path", required=True, default=None, type=str, help="Path to the output PyTorch model." ) parser.add_argument( "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub." ) SCREAMING_SNAKE_CASE__ : Dict = parser.parse_args() convert_checkpoint( args.model, args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
713
import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import ( BertTokenizer, ViltConfig, ViltForImageAndTextRetrieval, ViltForImagesAndTextClassification, ViltForMaskedLM, ViltForQuestionAnswering, ViltImageProcessor, ViltProcessor, ) from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) def _a ( lowercase__ : Union[str, Any] , lowercase__ : Union[str, Any]=False , lowercase__ : str=False , lowercase__ : Dict=False ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f'''transformer.blocks.{i}.norm1.weight''', f'''vilt.encoder.layer.{i}.layernorm_before.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm1.bias''', f'''vilt.encoder.layer.{i}.layernorm_before.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.weight''', f'''vilt.encoder.layer.{i}.attention.output.dense.weight''') ) rename_keys.append( (f'''transformer.blocks.{i}.attn.proj.bias''', f'''vilt.encoder.layer.{i}.attention.output.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.weight''', f'''vilt.encoder.layer.{i}.layernorm_after.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.norm2.bias''', f'''vilt.encoder.layer.{i}.layernorm_after.bias''') ) rename_keys.append( (f'''transformer.blocks.{i}.mlp.fc1.weight''', f'''vilt.encoder.layer.{i}.intermediate.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc1.bias''', f'''vilt.encoder.layer.{i}.intermediate.dense.bias''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.weight''', f'''vilt.encoder.layer.{i}.output.dense.weight''') ) rename_keys.append((f'''transformer.blocks.{i}.mlp.fc2.bias''', f'''vilt.encoder.layer.{i}.output.dense.bias''') ) # embeddings rename_keys.extend( [ # text embeddings ('text_embeddings.word_embeddings.weight', 'vilt.embeddings.text_embeddings.word_embeddings.weight'), ( 'text_embeddings.position_embeddings.weight', 'vilt.embeddings.text_embeddings.position_embeddings.weight', ), ('text_embeddings.position_ids', 'vilt.embeddings.text_embeddings.position_ids'), ( 'text_embeddings.token_type_embeddings.weight', 'vilt.embeddings.text_embeddings.token_type_embeddings.weight', ), ('text_embeddings.LayerNorm.weight', 'vilt.embeddings.text_embeddings.LayerNorm.weight'), ('text_embeddings.LayerNorm.bias', 'vilt.embeddings.text_embeddings.LayerNorm.bias'), # patch embeddings ('transformer.cls_token', 'vilt.embeddings.cls_token'), ('transformer.patch_embed.proj.weight', 'vilt.embeddings.patch_embeddings.projection.weight'), ('transformer.patch_embed.proj.bias', 'vilt.embeddings.patch_embeddings.projection.bias'), ('transformer.pos_embed', 'vilt.embeddings.position_embeddings'), # token type embeddings ('token_type_embeddings.weight', 'vilt.embeddings.token_type_embeddings.weight'), ] ) # final layernorm + pooler rename_keys.extend( [ ('transformer.norm.weight', 'vilt.layernorm.weight'), ('transformer.norm.bias', 'vilt.layernorm.bias'), ('pooler.dense.weight', 'vilt.pooler.dense.weight'), ('pooler.dense.bias', 'vilt.pooler.dense.bias'), ] ) # classifier head(s) if vqa_model: # classification head rename_keys.extend( [ ('vqa_classifier.0.weight', 'classifier.0.weight'), ('vqa_classifier.0.bias', 'classifier.0.bias'), ('vqa_classifier.1.weight', 'classifier.1.weight'), ('vqa_classifier.1.bias', 'classifier.1.bias'), ('vqa_classifier.3.weight', 'classifier.3.weight'), ('vqa_classifier.3.bias', 'classifier.3.bias'), ] ) elif nlvr_model: # classification head rename_keys.extend( [ ('nlvr2_classifier.0.weight', 'classifier.0.weight'), ('nlvr2_classifier.0.bias', 'classifier.0.bias'), ('nlvr2_classifier.1.weight', 'classifier.1.weight'), ('nlvr2_classifier.1.bias', 'classifier.1.bias'), ('nlvr2_classifier.3.weight', 'classifier.3.weight'), ('nlvr2_classifier.3.bias', 'classifier.3.bias'), ] ) else: pass return rename_keys def _a ( lowercase__ : List[str] , lowercase__ : Dict ): '''simple docstring''' for i in range(config.num_hidden_layers ): SCREAMING_SNAKE_CASE__ : Dict = 'vilt.' # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.weight''' ) SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(f'''transformer.blocks.{i}.attn.qkv.bias''' ) # next, add query, keys and values (in that order) to the state dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = in_proj_weight[ : config.hidden_size, : ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[: config.hidden_size] SCREAMING_SNAKE_CASE__ : int = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] SCREAMING_SNAKE_CASE__ : List[str] = in_proj_weight[ -config.hidden_size :, : ] SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[-config.hidden_size :] def _a ( lowercase__ : Optional[int] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = ['head.weight', 'head.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) def _a ( lowercase__ : int , lowercase__ : int , lowercase__ : Dict ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Tuple = dct.pop(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = val @torch.no_grad() def _a ( lowercase__ : Dict , lowercase__ : Optional[Any] ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : List[Any] = ViltConfig(image_size=3_84 , patch_size=32 , tie_word_embeddings=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : Tuple = False SCREAMING_SNAKE_CASE__ : List[str] = False SCREAMING_SNAKE_CASE__ : str = False if "vqa" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Any = True SCREAMING_SNAKE_CASE__ : str = 31_29 SCREAMING_SNAKE_CASE__ : Optional[Any] = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : int = 'vqa2-id2label.json' SCREAMING_SNAKE_CASE__ : str = json.load(open(hf_hub_download(lowercase__ , lowercase__ , repo_type='dataset' ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Optional[Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Dict = idalabel SCREAMING_SNAKE_CASE__ : str = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : List[str] = ViltForQuestionAnswering(lowercase__ ) elif "nlvr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Optional[int] = True SCREAMING_SNAKE_CASE__ : List[str] = 2 SCREAMING_SNAKE_CASE__ : Dict = {0: 'False', 1: 'True'} SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in config.idalabel.items()} SCREAMING_SNAKE_CASE__ : Tuple = 3 SCREAMING_SNAKE_CASE__ : int = ViltForImagesAndTextClassification(lowercase__ ) elif "irtr" in checkpoint_url: SCREAMING_SNAKE_CASE__ : Dict = True SCREAMING_SNAKE_CASE__ : str = ViltForImageAndTextRetrieval(lowercase__ ) elif "mlm_itm" in checkpoint_url: SCREAMING_SNAKE_CASE__ : int = True SCREAMING_SNAKE_CASE__ : Optional[int] = ViltForMaskedLM(lowercase__ ) else: raise ValueError('Unknown model type' ) # load state_dict of original model, remove and rename some keys SCREAMING_SNAKE_CASE__ : Any = torch.hub.load_state_dict_from_url(lowercase__ , map_location='cpu' )['state_dict'] SCREAMING_SNAKE_CASE__ : Any = create_rename_keys(lowercase__ , lowercase__ , lowercase__ , lowercase__ ) for src, dest in rename_keys: rename_key(lowercase__ , lowercase__ , lowercase__ ) read_in_q_k_v(lowercase__ , lowercase__ ) if mlm_model or irtr_model: SCREAMING_SNAKE_CASE__ : Any = ['itm_score.fc.weight', 'itm_score.fc.bias'] for k in ignore_keys: state_dict.pop(lowercase__ , lowercase__ ) # load state dict into HuggingFace model model.eval() if mlm_model: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = model.load_state_dict(lowercase__ , strict=lowercase__ ) assert missing_keys == ["mlm_score.decoder.bias"] else: model.load_state_dict(lowercase__ ) # Define processor SCREAMING_SNAKE_CASE__ : str = ViltImageProcessor(size=3_84 ) SCREAMING_SNAKE_CASE__ : List[Any] = BertTokenizer.from_pretrained('bert-base-uncased' ) SCREAMING_SNAKE_CASE__ : List[Any] = ViltProcessor(lowercase__ , lowercase__ ) # Forward pass on example inputs (image + text) if nlvr_model: SCREAMING_SNAKE_CASE__ : List[str] = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Any = Image.open(requests.get('https://lil.nlp.cornell.edu/nlvr/exs/ex0_0.jpg' , stream=lowercase__ ).raw ) SCREAMING_SNAKE_CASE__ : Tuple = ( 'The left image contains twice the number of dogs as the right image, and at least two dogs in total are' ' standing.' ) SCREAMING_SNAKE_CASE__ : List[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[str] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : List[Any] = model( input_ids=encoding_a.input_ids , pixel_values=encoding_a.pixel_values , pixel_values_a=encoding_a.pixel_values , ) else: SCREAMING_SNAKE_CASE__ : Tuple = Image.open(requests.get('http://images.cocodataset.org/val2017/000000039769.jpg' , stream=lowercase__ ).raw ) if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'a bunch of [MASK] laying on a [MASK].' else: SCREAMING_SNAKE_CASE__ : Optional[Any] = 'How many cats are there?' SCREAMING_SNAKE_CASE__ : Optional[Any] = processor(lowercase__ , lowercase__ , return_tensors='pt' ) SCREAMING_SNAKE_CASE__ : str = model(**lowercase__ ) # Verify outputs if mlm_model: SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.Size([1, 11, 3_05_22] ) SCREAMING_SNAKE_CASE__ : List[str] = torch.tensor([-12.5061, -12.5123, -12.5174] ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify masked token prediction equals "cats" SCREAMING_SNAKE_CASE__ : Union[str, Any] = outputs.logits[0, 4, :].argmax(-1 ).item() assert tokenizer.decode([predicted_id] ) == "cats" elif vqa_model: SCREAMING_SNAKE_CASE__ : str = torch.Size([1, 31_29] ) SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([-15.9495, -18.1472, -10.3041] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape assert torch.allclose(outputs.logits[0, 0, :3] , lowercase__ , atol=1E-4 ) # verify vqa prediction equals "2" SCREAMING_SNAKE_CASE__ : List[Any] = outputs.logits.argmax(-1 ).item() assert model.config.idalabel[predicted_idx] == "2" elif nlvr_model: SCREAMING_SNAKE_CASE__ : Optional[int] = torch.Size([1, 2] ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = torch.tensor([-2.8721, 2.1291] ) assert torch.allclose(outputs.logits[0, :3] , lowercase__ , atol=1E-4 ) assert outputs.logits.shape == expected_shape Path(lowercase__ ).mkdir(exist_ok=lowercase__ ) print(f'''Saving model and processor to {pytorch_dump_folder_path}''' ) model.save_pretrained(lowercase__ ) processor.save_pretrained(lowercase__ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint_url", default="https://github.com/dandelin/ViLT/releases/download/200k/vilt_200k_mlm_itm.ckpt", type=str, help="URL of the checkpoint you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() convert_vilt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)
636
0
import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_xlnet import XLNetTokenizer else: SCREAMING_SNAKE_CASE__ : Tuple = None SCREAMING_SNAKE_CASE__ : int = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Tuple = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"} SCREAMING_SNAKE_CASE__ : List[Any] = { "vocab_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model", }, "tokenizer_file": { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/tokenizer.json", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/tokenizer.json", }, } SCREAMING_SNAKE_CASE__ : int = { "xlnet-base-cased": None, "xlnet-large-cased": None, } SCREAMING_SNAKE_CASE__ : Any = "▁" # Segments (not really needed) SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : Union[str, Any] = 2 SCREAMING_SNAKE_CASE__ : List[str] = 3 SCREAMING_SNAKE_CASE__ : Tuple = 4 class snake_case ( UpperCamelCase_ ): lowercase_ = VOCAB_FILES_NAMES lowercase_ = PRETRAINED_VOCAB_FILES_MAP lowercase_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase_ = 'left' lowercase_ = XLNetTokenizer def __init__( self : Union[str, Any] , a_ : int=None , a_ : Dict=None , a_ : Optional[Any]=False , a_ : Tuple=True , a_ : Dict=False , a_ : str="<s>" , a_ : str="</s>" , a_ : int="<unk>" , a_ : Tuple="<sep>" , a_ : Union[str, Any]="<pad>" , a_ : List[str]="<cls>" , a_ : List[Any]="<mask>" , a_ : List[str]=["<eop>", "<eod>"] , **a_ : int , )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = AddedToken(a_ , lstrip=a_ , rstrip=a_ ) if isinstance(a_ , a_ ) else mask_token super().__init__( vocab_file=a_ , tokenizer_file=a_ , do_lower_case=a_ , remove_space=a_ , keep_accents=a_ , bos_token=a_ , eos_token=a_ , unk_token=a_ , sep_token=a_ , pad_token=a_ , cls_token=a_ , mask_token=a_ , additional_special_tokens=a_ , **a_ , ) SCREAMING_SNAKE_CASE__ : Optional[Any] = 3 SCREAMING_SNAKE_CASE__ : List[Any] = do_lower_case SCREAMING_SNAKE_CASE__ : str = remove_space SCREAMING_SNAKE_CASE__ : Tuple = keep_accents SCREAMING_SNAKE_CASE__ : str = vocab_file SCREAMING_SNAKE_CASE__ : Any = False if not self.vocab_file else True def __lowercase( self : Any , a_ : List[int] , a_ : Optional[List[int]] = None )-> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Dict = [self.cls_token_id] if token_ids_a is None: return token_ids_a + sep + cls return token_ids_a + sep + token_ids_a + sep + cls def __lowercase( self : str , a_ : List[int] , a_ : Optional[List[int]] = None )-> List[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = [self.sep_token_id] SCREAMING_SNAKE_CASE__ : Dict = [2] if token_ids_a is None: return len(token_ids_a + sep ) * [0] + cls_segment_id return len(token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] + cls_segment_id def __lowercase( self : List[Any] , a_ : str , a_ : Optional[str] = None )-> Tuple[str]: """simple docstring""" if not self.can_save_slow_tokenizer: raise ValueError( 'Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ' 'tokenizer.' ) if not os.path.isdir(a_ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return SCREAMING_SNAKE_CASE__ : Tuple = os.path.join( a_ , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(a_ ): copyfile(self.vocab_file , a_ ) return (out_vocab_file,)
714
from dataclasses import dataclass from typing import Tuple import numpy as np import torch @dataclass class snake_case : lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 # [batch_size x 3] lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 lowercase_ = 42 def __lowercase( self : List[Any] )-> Union[str, Any]: """simple docstring""" assert self.x.shape[0] == self.y.shape[0] == self.z.shape[0] == self.origin.shape[0] assert self.x.shape[1] == self.y.shape[1] == self.z.shape[1] == self.origin.shape[1] == 3 assert len(self.x.shape ) == len(self.y.shape ) == len(self.z.shape ) == len(self.origin.shape ) == 2 def __lowercase( self : Dict )-> Tuple: """simple docstring""" return torch.from_numpy(np.array([self.width, self.height] , dtype=np.floataa ) ) def __lowercase( self : Dict )-> Union[str, Any]: """simple docstring""" return torch.from_numpy(np.array([self.x_fov, self.y_fov] , dtype=np.floataa ) ) def __lowercase( self : Tuple )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = torch.arange(self.height * self.width ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.stack( [ pixel_indices % self.width, torch.div(a_ , self.width , rounding_mode='trunc' ), ] , axis=1 , ) return coords @property def __lowercase( self : Any )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.shape SCREAMING_SNAKE_CASE__ : Tuple = int(np.prod(a_ ) ) SCREAMING_SNAKE_CASE__ : List[str] = self.get_image_coords() SCREAMING_SNAKE_CASE__ : Dict = torch.broadcast_to(coords.unsqueeze(0 ) , [batch_size * inner_batch_size, *coords.shape] ) SCREAMING_SNAKE_CASE__ : Any = self.get_camera_rays(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = rays.view(a_ , inner_batch_size * self.height * self.width , 2 , 3 ) return rays def __lowercase( self : Optional[Any] , a_ : torch.Tensor )-> torch.Tensor: """simple docstring""" SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Dict = coords.shape assert n_coords == 2 assert batch_size == self.origin.shape[0] SCREAMING_SNAKE_CASE__ : str = coords.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : List[Any] = self.resolution() SCREAMING_SNAKE_CASE__ : str = self.fov() SCREAMING_SNAKE_CASE__ : Any = (flat.float() / (res - 1)) * 2 - 1 SCREAMING_SNAKE_CASE__ : Any = fracs * torch.tan(fov / 2 ) SCREAMING_SNAKE_CASE__ : List[str] = fracs.view(a_ , -1 , 2 ) SCREAMING_SNAKE_CASE__ : str = ( self.z.view(a_ , 1 , 3 ) + self.x.view(a_ , 1 , 3 ) * fracs[:, :, :1] + self.y.view(a_ , 1 , 3 ) * fracs[:, :, 1:] ) SCREAMING_SNAKE_CASE__ : Tuple = directions / directions.norm(dim=-1 , keepdim=a_ ) SCREAMING_SNAKE_CASE__ : Any = torch.stack( [ torch.broadcast_to(self.origin.view(a_ , 1 , 3 ) , [batch_size, directions.shape[1], 3] ), directions, ] , dim=2 , ) return rays.view(a_ , *a_ , 2 , 3 ) def __lowercase( self : Optional[int] , a_ : int , a_ : int )-> "DifferentiableProjectiveCamera": """simple docstring""" assert width * self.height == height * self.width, "The aspect ratio should not change." return DifferentiableProjectiveCamera( origin=self.origin , x=self.x , y=self.y , z=self.z , width=a_ , height=a_ , x_fov=self.x_fov , y_fov=self.y_fov , ) def _a ( lowercase__ : int ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = [] SCREAMING_SNAKE_CASE__ : List[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = [] SCREAMING_SNAKE_CASE__ : str = [] for theta in np.linspace(0 , 2 * np.pi , num=20 ): SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.sin(lowercase__ ), np.cos(lowercase__ ), -0.5] ) z /= np.sqrt(np.sum(z**2 ) ) SCREAMING_SNAKE_CASE__ : Tuple = -z * 4 SCREAMING_SNAKE_CASE__ : Optional[Any] = np.array([np.cos(lowercase__ ), -np.sin(lowercase__ ), 0.0] ) SCREAMING_SNAKE_CASE__ : Optional[int] = np.cross(lowercase__ , lowercase__ ) origins.append(lowercase__ ) xs.append(lowercase__ ) ys.append(lowercase__ ) zs.append(lowercase__ ) return DifferentiableProjectiveCamera( origin=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , x=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , y=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , z=torch.from_numpy(np.stack(lowercase__ , axis=0 ) ).float() , width=lowercase__ , height=lowercase__ , x_fov=0.7 , y_fov=0.7 , shape=(1, len(lowercase__ )) , )
636
0
import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax import jax.numpy as jnp from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel if is_torch_available(): import torch class snake_case : def __init__( self : Dict , a_ : str , a_ : Any=14 , a_ : int=7 , a_ : str=True , a_ : Dict=True , a_ : int=False , a_ : Dict=True , a_ : List[str]=99 , a_ : Union[str, Any]=32 , a_ : Optional[Any]=4 , a_ : List[Any]=4 , a_ : Union[str, Any]=4 , a_ : Dict=37 , a_ : List[Any]="gelu" , a_ : Optional[int]=0.1 , a_ : List[Any]=0.1 , a_ : Any=512 , a_ : Dict=0.02 , )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Tuple = parent SCREAMING_SNAKE_CASE__ : Optional[int] = batch_size SCREAMING_SNAKE_CASE__ : Optional[int] = seq_length SCREAMING_SNAKE_CASE__ : str = is_training SCREAMING_SNAKE_CASE__ : Any = use_input_mask SCREAMING_SNAKE_CASE__ : List[str] = use_token_type_ids SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_labels SCREAMING_SNAKE_CASE__ : Optional[int] = vocab_size SCREAMING_SNAKE_CASE__ : List[Any] = hidden_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = rotary_dim SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : str = num_attention_heads SCREAMING_SNAKE_CASE__ : List[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Tuple = hidden_act SCREAMING_SNAKE_CASE__ : str = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[int] = max_position_embeddings SCREAMING_SNAKE_CASE__ : List[Any] = initializer_range SCREAMING_SNAKE_CASE__ : Optional[Any] = None SCREAMING_SNAKE_CASE__ : List[Any] = vocab_size - 1 SCREAMING_SNAKE_CASE__ : Any = vocab_size - 1 SCREAMING_SNAKE_CASE__ : str = vocab_size - 1 def __lowercase( self : Optional[Any] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) SCREAMING_SNAKE_CASE__ : Optional[Any] = None if self.use_input_mask: SCREAMING_SNAKE_CASE__ : str = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE__ : List[Any] = GPTJConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , use_cache=a_ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , ) return (config, input_ids, input_mask) def __lowercase( self : List[Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.prepare_config_and_inputs() SCREAMING_SNAKE_CASE__ : Dict = config_and_inputs SCREAMING_SNAKE_CASE__ : str = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict def __lowercase( self : Tuple , a_ : List[Any] , a_ : Any , a_ : Any , a_ : Optional[Any] )-> Optional[int]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = 20 SCREAMING_SNAKE_CASE__ : int = model_class_name(a_ ) SCREAMING_SNAKE_CASE__ : Dict = model.init_cache(input_ids.shape[0] , a_ ) SCREAMING_SNAKE_CASE__ : Tuple = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype='i4' ) SCREAMING_SNAKE_CASE__ : List[str] = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model( input_ids[:, :-1] , attention_mask=a_ , past_key_values=a_ , position_ids=a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='i4' ) SCREAMING_SNAKE_CASE__ : Tuple = model( input_ids[:, -1:] , attention_mask=a_ , past_key_values=outputs_cache.past_key_values , position_ids=a_ , ) SCREAMING_SNAKE_CASE__ : List[str] = model(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, 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 __lowercase( self : Tuple , a_ : Dict , a_ : str , a_ : Dict , a_ : List[Any] )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = 20 SCREAMING_SNAKE_CASE__ : Tuple = model_class_name(a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] , axis=-1 , ) SCREAMING_SNAKE_CASE__ : Tuple = model.init_cache(input_ids.shape[0] , a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) SCREAMING_SNAKE_CASE__ : str = model( input_ids[:, :-1] , attention_mask=a_ , past_key_values=a_ , position_ids=a_ , ) SCREAMING_SNAKE_CASE__ : Any = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='i4' ) SCREAMING_SNAKE_CASE__ : str = model( input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=a_ , position_ids=a_ , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model(a_ , attention_mask=a_ ) SCREAMING_SNAKE_CASE__ : 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 snake_case ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ): lowercase_ = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () lowercase_ = (FlaxGPTJForCausalLM,) if is_flax_available() else () def __lowercase( self : List[Any] )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = FlaxGPTJModelTester(self ) def __lowercase( self : int )-> str: """simple docstring""" for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(a_ , a_ , a_ , a_ ) def __lowercase( self : Dict )-> str: """simple docstring""" for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( a_ , a_ , a_ , a_ ) @tooslow def __lowercase( self : Any )-> int: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = GPTaTokenizer.from_pretrained('gpt2' , pad_token='<|endoftext|>' , padding_side='left' ) SCREAMING_SNAKE_CASE__ : Tuple = tokenizer(['Hello this is a long string', 'Hey'] , return_tensors='np' , padding=a_ , truncation=a_ ) SCREAMING_SNAKE_CASE__ : Any = FlaxGPTJForCausalLM.from_pretrained('EleutherAI/gpt-j-6B' ) SCREAMING_SNAKE_CASE__ : List[Any] = False SCREAMING_SNAKE_CASE__ : Any = model.config.eos_token_id SCREAMING_SNAKE_CASE__ : Union[str, Any] = jax.jit(model.generate ) SCREAMING_SNAKE_CASE__ : Any = jit_generate( inputs['input_ids'] , attention_mask=inputs['attention_mask'] , pad_token_id=tokenizer.pad_token_id ).sequences SCREAMING_SNAKE_CASE__ : Any = tokenizer.batch_decode(a_ , skip_special_tokens=a_ ) SCREAMING_SNAKE_CASE__ : List[Any] = [ 'Hello this is a long string of text.\n\nI\'m trying to get the text of the', 'Hey, I\'m a little late to the party. I\'m going to', ] self.assertListEqual(a_ , a_ ) @is_pt_flax_cross_test def __lowercase( self : Optional[int] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs SCREAMING_SNAKE_CASE__ : Any = self._prepare_for_class(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class SCREAMING_SNAKE_CASE__ : List[str] = model_class.__name__[4:] # Skip the "Flax" at the beginning SCREAMING_SNAKE_CASE__ : List[str] = getattr(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Tuple = pt_inputs['input_ids'].shape SCREAMING_SNAKE_CASE__ : List[Any] = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(a_ ): SCREAMING_SNAKE_CASE__ : int = 0 SCREAMING_SNAKE_CASE__ : str = 1 SCREAMING_SNAKE_CASE__ : Dict = 0 SCREAMING_SNAKE_CASE__ : Any = 1 SCREAMING_SNAKE_CASE__ : Optional[Any] = pt_model_class(a_ ).eval() SCREAMING_SNAKE_CASE__ : int = model_class(a_ , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = fx_state with torch.no_grad(): SCREAMING_SNAKE_CASE__ : List[Any] = pt_model(**a_ ).to_tuple() SCREAMING_SNAKE_CASE__ : Dict = fx_model(**a_ ).to_tuple() self.assertEqual(len(a_ ) , len(a_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(a_ , a_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4e-2 ) with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = model_class.from_pretrained(a_ , from_pt=a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = fx_model_loaded(**a_ ).to_tuple() self.assertEqual( len(a_ ) , len(a_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output_loaded, pt_output in zip(a_ , a_ ): self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4e-2 ) @is_pt_flax_cross_test def __lowercase( self : int )-> Any: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs SCREAMING_SNAKE_CASE__ : List[Any] = self._prepare_for_class(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class SCREAMING_SNAKE_CASE__ : List[str] = model_class.__name__[4:] # Skip the "Flax" at the beginning SCREAMING_SNAKE_CASE__ : Optional[int] = getattr(a_ , a_ ) SCREAMING_SNAKE_CASE__ : Any = pt_model_class(a_ ).eval() SCREAMING_SNAKE_CASE__ : str = model_class(a_ , dtype=jnp.floataa ) SCREAMING_SNAKE_CASE__ : Dict = load_flax_weights_in_pytorch_model(a_ , fx_model.params ) SCREAMING_SNAKE_CASE__ : Optional[int] = pt_inputs['input_ids'].shape SCREAMING_SNAKE_CASE__ : List[Any] = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(a_ ): SCREAMING_SNAKE_CASE__ : Tuple = 0 SCREAMING_SNAKE_CASE__ : Optional[int] = 1 SCREAMING_SNAKE_CASE__ : Any = 0 SCREAMING_SNAKE_CASE__ : List[Any] = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): SCREAMING_SNAKE_CASE__ : str = pt_model(**a_ ).to_tuple() SCREAMING_SNAKE_CASE__ : Any = fx_model(**a_ ).to_tuple() self.assertEqual(len(a_ ) , len(a_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(a_ , a_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4e-2 ) with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(a_ ) SCREAMING_SNAKE_CASE__ : int = pt_model_class.from_pretrained(a_ , from_flax=a_ ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ : Any = pt_model_loaded(**a_ ).to_tuple() self.assertEqual( len(a_ ) , len(a_ ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(a_ , a_ ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4e-2 ) @tooslow def __lowercase( self : str )-> Union[str, Any]: """simple docstring""" for model_class_name in self.all_model_classes: SCREAMING_SNAKE_CASE__ : List[str] = model_class_name.from_pretrained('EleutherAI/gpt-j-6B' ) SCREAMING_SNAKE_CASE__ : Tuple = model(np.ones((1, 1) ) ) self.assertIsNotNone(a_ )
715
import requests SCREAMING_SNAKE_CASE__ : int = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=" def _a ( lowercase__ : str ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = requests.get(_NEWS_API + bbc_news_api_key ).json() # each article in the list is a dict for i, article in enumerate(bbc_news_page['articles'] , 1 ): print(f'''{i}.) {article['title']}''' ) if __name__ == "__main__": fetch_bbc_news(bbc_news_api_key="<Your BBC News API key goes here>")
636
0
import timeit import numpy as np import datasets from datasets.arrow_writer import ArrowWriter from datasets.features.features import _ArrayXD def _a ( lowercase__ : Optional[int] ): '''simple docstring''' def wrapper(*lowercase__ : str , **lowercase__ : List[str] ): SCREAMING_SNAKE_CASE__ : Optional[int] = timeit.default_timer() SCREAMING_SNAKE_CASE__ : Tuple = func(*lowercase__ , **lowercase__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = timeit.default_timer() - starttime return delta SCREAMING_SNAKE_CASE__ : List[str] = func.__name__ return wrapper def _a ( lowercase__ : dict , lowercase__ : List[str]=1_00 , lowercase__ : List[str]=None ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = [] SCREAMING_SNAKE_CASE__ : Optional[int] = seq_shapes or {} for i in range(lowercase__ ): SCREAMING_SNAKE_CASE__ : str = {} for col_id, (k, v) in enumerate(features.items() ): if isinstance(lowercase__ , _ArrayXD ): SCREAMING_SNAKE_CASE__ : Optional[Any] = np.random.rand(*v.shape ).astype(v.dtype ) elif isinstance(lowercase__ , datasets.Value ): if v.dtype == "string": SCREAMING_SNAKE_CASE__ : int = 'The small grey turtle was surprisingly fast when challenged.' else: SCREAMING_SNAKE_CASE__ : Tuple = np.random.randint(10 , size=1 ).astype(v.dtype ).item() elif isinstance(lowercase__ , datasets.Sequence ): while isinstance(lowercase__ , datasets.Sequence ): SCREAMING_SNAKE_CASE__ : Union[str, Any] = v.feature SCREAMING_SNAKE_CASE__ : Any = seq_shapes[k] SCREAMING_SNAKE_CASE__ : Tuple = np.random.rand(*lowercase__ ).astype(v.dtype ) SCREAMING_SNAKE_CASE__ : Optional[Any] = data dummy_data.append((i, example) ) return dummy_data def _a ( lowercase__ : int , lowercase__ : Optional[int] , lowercase__ : Optional[Any]=1_00 , lowercase__ : List[str]=None ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[int] = generate_examples(lowercase__ , num_examples=lowercase__ , seq_shapes=lowercase__ ) with ArrowWriter(features=lowercase__ , path=lowercase__ ) as writer: for key, record in dummy_data: SCREAMING_SNAKE_CASE__ : List[str] = features.encode_example(lowercase__ ) writer.write(lowercase__ ) SCREAMING_SNAKE_CASE__ : int = writer.finalize() if not num_final_examples == num_examples: raise ValueError( f'''Error writing the dataset, wrote {num_final_examples} examples but should have written {num_examples}.''' ) SCREAMING_SNAKE_CASE__ : Optional[int] = datasets.Dataset.from_file(filename=lowercase__ , info=datasets.DatasetInfo(features=lowercase__ ) ) return dataset
716
import argparse import json from dataclasses import dataclass, field from functools import partial from pathlib import Path from typing import Callable, Dict, List, Tuple import timm import torch import torch.nn as nn from classy_vision.models.regnet import RegNet, RegNetParams, RegNetYaagf, RegNetYaagf, RegNetYaaagf from huggingface_hub import cached_download, hf_hub_url from torch import Tensor from vissl.models.model_helpers import get_trunk_forward_outputs from transformers import AutoImageProcessor, RegNetConfig, RegNetForImageClassification, RegNetModel from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE__ : Tuple = logging.get_logger() @dataclass class snake_case : lowercase_ = 42 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) def __lowercase( self : Dict , a_ : Dict , a_ : Tensor , a_ : Tensor )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = len(list(m.modules() ) ) == 1 or isinstance(a_ , nn.Convad ) or isinstance(a_ , nn.BatchNormad ) if has_not_submodules: self.traced.append(a_ ) def __call__( self : Tuple , a_ : Tensor )-> Any: """simple docstring""" for m in self.module.modules(): self.handles.append(m.register_forward_hook(self._forward_hook ) ) self.module(a_ ) [x.remove() for x in self.handles] return self @property def __lowercase( self : Tuple )-> int: """simple docstring""" # check the len of the state_dict keys to see if we have learnable params return list(filter(lambda a_ : len(list(x.state_dict().keys() ) ) > 0 , self.traced ) ) @dataclass class snake_case : lowercase_ = 42 lowercase_ = 42 lowercase_ = 1 lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = field(default_factory=UpperCamelCase_ ) lowercase_ = True def __call__( self : List[Any] , a_ : Tensor )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = Tracker(self.dest )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : Optional[int] = Tracker(self.src )(a_ ).parametrized SCREAMING_SNAKE_CASE__ : List[str] = list(filter(lambda a_ : type(a_ ) not in self.src_skip , a_ ) ) SCREAMING_SNAKE_CASE__ : Dict = list(filter(lambda a_ : type(a_ ) not in self.dest_skip , a_ ) ) if len(a_ ) != len(a_ ) and self.raise_if_mismatch: raise Exception( F'''Numbers of operations are different. Source module has {len(a_ )} operations while''' F''' destination module has {len(a_ )}.''' ) for dest_m, src_m in zip(a_ , a_ ): dest_m.load_state_dict(src_m.state_dict() ) if self.verbose == 1: print(F'''Transfered from={src_m} to={dest_m}''' ) class snake_case ( nn.Module ): def __init__( self : List[Any] , a_ : nn.Module )-> Dict: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : List[Tuple[str, nn.Module]] = [] # - get the stem feature_blocks.append(('conv1', model.stem) ) # - get all the feature blocks for k, v in model.trunk_output.named_children(): assert k.startswith('block' ), F'''Unexpected layer name {k}''' SCREAMING_SNAKE_CASE__ : Optional[Any] = len(a_ ) + 1 feature_blocks.append((F'''res{block_index}''', v) ) SCREAMING_SNAKE_CASE__ : Any = nn.ModuleDict(a_ ) def __lowercase( self : Tuple , a_ : Tensor )-> Dict: """simple docstring""" return get_trunk_forward_outputs( a_ , out_feat_keys=a_ , feature_blocks=self._feature_blocks , ) class snake_case ( UpperCamelCase_ ): def __lowercase( self : Optional[Any] , a_ : str )-> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = x.split('-' ) return x_split[0] + x_split[1] + "_" + "".join(x_split[2:] ) def __getitem__( self : Union[str, Any] , a_ : str )-> Callable[[], Tuple[nn.Module, Dict]]: """simple docstring""" # default to timm! if x not in self: SCREAMING_SNAKE_CASE__ : Any = self.convert_name_to_timm(a_ ) SCREAMING_SNAKE_CASE__ : Tuple = partial(lambda: (timm.create_model(a_ , pretrained=a_ ).eval(), None) ) else: SCREAMING_SNAKE_CASE__ : List[str] = super().__getitem__(a_ ) return val class snake_case ( UpperCamelCase_ ): def __getitem__( self : Any , a_ : str )-> Callable[[], nn.Module]: """simple docstring""" if "seer" in x and "in1k" not in x: SCREAMING_SNAKE_CASE__ : Any = RegNetModel else: SCREAMING_SNAKE_CASE__ : Any = RegNetForImageClassification return val def _a ( lowercase__ : Any , lowercase__ : Optional[Any] , lowercase__ : List[Tuple[str, str]] ): '''simple docstring''' for from_key, to_key in keys: SCREAMING_SNAKE_CASE__ : Tuple = from_state_dict[from_key].clone() print(f'''Copied key={from_key} to={to_key}''' ) return to_state_dict def _a ( lowercase__ : str , lowercase__ : Callable[[], nn.Module] , lowercase__ : Callable[[], nn.Module] , lowercase__ : RegNetConfig , lowercase__ : Path , lowercase__ : bool = True , ): '''simple docstring''' print(f'''Converting {name}...''' ) with torch.no_grad(): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = from_model_func() SCREAMING_SNAKE_CASE__ : int = our_model_func(lowercase__ ).eval() SCREAMING_SNAKE_CASE__ : List[Any] = ModuleTransfer(src=lowercase__ , dest=lowercase__ , raise_if_mismatch=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = torch.randn((1, 3, 2_24, 2_24) ) module_transfer(lowercase__ ) if from_state_dict is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = [] # for seer - in1k finetuned we have to manually copy the head if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : int = [('0.clf.0.weight', 'classifier.1.weight'), ('0.clf.0.bias', 'classifier.1.bias')] SCREAMING_SNAKE_CASE__ : Optional[Any] = manually_copy_vissl_head(lowercase__ , our_model.state_dict() , lowercase__ ) our_model.load_state_dict(lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = our_model(lowercase__ , output_hidden_states=lowercase__ ) SCREAMING_SNAKE_CASE__ : Tuple = ( our_outputs.logits if isinstance(lowercase__ , lowercase__ ) else our_outputs.last_hidden_state ) SCREAMING_SNAKE_CASE__ : List[Any] = from_model(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[str] = from_output[-1] if type(lowercase__ ) is list else from_output # now since I don't want to use any config files, vissl seer model doesn't actually have an head, so let's just check the last hidden state if "seer" in name and "in1k" in name: SCREAMING_SNAKE_CASE__ : List[Any] = our_outputs.hidden_states[-1] assert torch.allclose(lowercase__ , lowercase__ ), "The model logits don't match the original one." if push_to_hub: our_model.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add model' , use_temp_dir=lowercase__ , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = 2_24 if 'seer' not in name else 3_84 # we can use the convnext one SCREAMING_SNAKE_CASE__ : Union[str, Any] = AutoImageProcessor.from_pretrained('facebook/convnext-base-224-22k-1k' , size=lowercase__ ) image_processor.push_to_hub( repo_path_or_name=save_directory / name , commit_message='Add image processor' , use_temp_dir=lowercase__ , ) print(f'''Pushed {name}''' ) def _a ( lowercase__ : Path , lowercase__ : str = None , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Any = 'imagenet-1k-id2label.json' SCREAMING_SNAKE_CASE__ : Tuple = 10_00 SCREAMING_SNAKE_CASE__ : Tuple = (1, num_labels) SCREAMING_SNAKE_CASE__ : str = 'huggingface/label-files' SCREAMING_SNAKE_CASE__ : Optional[Any] = num_labels SCREAMING_SNAKE_CASE__ : List[str] = json.load(open(cached_download(hf_hub_url(lowercase__ , lowercase__ , repo_type='dataset' ) ) , 'r' ) ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = {int(lowercase__ ): v for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : str = idalabel SCREAMING_SNAKE_CASE__ : Tuple = {v: k for k, v in idalabel.items()} SCREAMING_SNAKE_CASE__ : Any = partial(lowercase__ , num_labels=lowercase__ , idalabel=lowercase__ , labelaid=lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = { 'regnet-x-002': ImageNetPreTrainedConfig( depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 , layer_type='x' ), 'regnet-x-004': ImageNetPreTrainedConfig( depths=[1, 2, 7, 12] , hidden_sizes=[32, 64, 1_60, 3_84] , groups_width=16 , layer_type='x' ), 'regnet-x-006': ImageNetPreTrainedConfig( depths=[1, 3, 5, 7] , hidden_sizes=[48, 96, 2_40, 5_28] , groups_width=24 , layer_type='x' ), 'regnet-x-008': ImageNetPreTrainedConfig( depths=[1, 3, 7, 5] , hidden_sizes=[64, 1_28, 2_88, 6_72] , groups_width=16 , layer_type='x' ), 'regnet-x-016': ImageNetPreTrainedConfig( depths=[2, 4, 10, 2] , hidden_sizes=[72, 1_68, 4_08, 9_12] , groups_width=24 , layer_type='x' ), 'regnet-x-032': ImageNetPreTrainedConfig( depths=[2, 6, 15, 2] , hidden_sizes=[96, 1_92, 4_32, 10_08] , groups_width=48 , layer_type='x' ), 'regnet-x-040': ImageNetPreTrainedConfig( depths=[2, 5, 14, 2] , hidden_sizes=[80, 2_40, 5_60, 13_60] , groups_width=40 , layer_type='x' ), 'regnet-x-064': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 3_92, 7_84, 16_24] , groups_width=56 , layer_type='x' ), 'regnet-x-080': ImageNetPreTrainedConfig( depths=[2, 5, 15, 1] , hidden_sizes=[80, 2_40, 7_20, 19_20] , groups_width=1_20 , layer_type='x' ), 'regnet-x-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 , layer_type='x' ), 'regnet-x-160': ImageNetPreTrainedConfig( depths=[2, 6, 13, 1] , hidden_sizes=[2_56, 5_12, 8_96, 20_48] , groups_width=1_28 , layer_type='x' ), 'regnet-x-320': ImageNetPreTrainedConfig( depths=[2, 7, 13, 1] , hidden_sizes=[3_36, 6_72, 13_44, 25_20] , groups_width=1_68 , layer_type='x' ), # y variant 'regnet-y-002': ImageNetPreTrainedConfig(depths=[1, 1, 4, 7] , hidden_sizes=[24, 56, 1_52, 3_68] , groups_width=8 ), 'regnet-y-004': ImageNetPreTrainedConfig( depths=[1, 3, 6, 6] , hidden_sizes=[48, 1_04, 2_08, 4_40] , groups_width=8 ), 'regnet-y-006': ImageNetPreTrainedConfig( depths=[1, 3, 7, 4] , hidden_sizes=[48, 1_12, 2_56, 6_08] , groups_width=16 ), 'regnet-y-008': ImageNetPreTrainedConfig( depths=[1, 3, 8, 2] , hidden_sizes=[64, 1_28, 3_20, 7_68] , groups_width=16 ), 'regnet-y-016': ImageNetPreTrainedConfig( depths=[2, 6, 17, 2] , hidden_sizes=[48, 1_20, 3_36, 8_88] , groups_width=24 ), 'regnet-y-032': ImageNetPreTrainedConfig( depths=[2, 5, 13, 1] , hidden_sizes=[72, 2_16, 5_76, 15_12] , groups_width=24 ), 'regnet-y-040': ImageNetPreTrainedConfig( depths=[2, 6, 12, 2] , hidden_sizes=[1_28, 1_92, 5_12, 10_88] , groups_width=64 ), 'regnet-y-064': ImageNetPreTrainedConfig( depths=[2, 7, 14, 2] , hidden_sizes=[1_44, 2_88, 5_76, 12_96] , groups_width=72 ), 'regnet-y-080': ImageNetPreTrainedConfig( depths=[2, 4, 10, 1] , hidden_sizes=[1_68, 4_48, 8_96, 20_16] , groups_width=56 ), 'regnet-y-120': ImageNetPreTrainedConfig( depths=[2, 5, 11, 1] , hidden_sizes=[2_24, 4_48, 8_96, 22_40] , groups_width=1_12 ), 'regnet-y-160': ImageNetPreTrainedConfig( depths=[2, 4, 11, 1] , hidden_sizes=[2_24, 4_48, 12_32, 30_24] , groups_width=1_12 ), 'regnet-y-320': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), # models created by SEER -> https://arxiv.org/abs/2202.08360 'regnet-y-320-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer': RegNetConfig(depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer': RegNetConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer': RegNetConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), # finetuned on imagenet 'regnet-y-320-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[2_32, 6_96, 13_92, 37_12] , groups_width=2_32 ), 'regnet-y-640-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 5, 12, 1] , hidden_sizes=[3_28, 9_84, 19_68, 49_20] , groups_width=3_28 ), 'regnet-y-1280-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[5_28, 10_56, 29_04, 73_92] , groups_width=2_64 ), 'regnet-y-2560-seer-in1k': ImageNetPreTrainedConfig( depths=[3, 7, 16, 1] , hidden_sizes=[6_40, 16_96, 25_44, 50_88] , groups_width=6_40 ), 'regnet-y-10b-seer-in1k': ImageNetPreTrainedConfig( depths=[2, 7, 17, 1] , hidden_sizes=[20_20, 40_40, 1_11_10, 2_82_80] , groups_width=10_10 ), } SCREAMING_SNAKE_CASE__ : List[Any] = NameToOurModelFuncMap() SCREAMING_SNAKE_CASE__ : Dict = NameToFromModelFuncMap() # add seer weights logic def load_using_classy_vision(lowercase__ : str , lowercase__ : Callable[[], nn.Module] ) -> Tuple[nn.Module, Dict]: SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(lowercase__ , model_dir=str(lowercase__ ) , map_location='cpu' ) SCREAMING_SNAKE_CASE__ : Tuple = model_func() # check if we have a head, if yes add it SCREAMING_SNAKE_CASE__ : str = files['classy_state_dict']['base_model']['model'] SCREAMING_SNAKE_CASE__ : str = model_state_dict['trunk'] model.load_state_dict(lowercase__ ) return model.eval(), model_state_dict["heads"] # pretrained SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet32d/seer_regnet32gf_model_iteration244000.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : int = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet64/seer_regnet64gf_model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/swav_ig1b_regnet128Gf_cnstant_bs32_node16_sinkhorn10_proto16k_syncBN64_warmup8k/model_final_checkpoint_phase0.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_regnet10B/model_iteration124500_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) # IN1K finetuned SCREAMING_SNAKE_CASE__ : List[Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet32_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet64_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaagf() ) , ) SCREAMING_SNAKE_CASE__ : Optional[int] = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_regnet128_finetuned_in1k_model_final_checkpoint_phase78.torch' , lambda: FakeRegNetVisslWrapper(RegNetYaaagf() ) , ) SCREAMING_SNAKE_CASE__ : Any = partial( lowercase__ , 'https://dl.fbaipublicfiles.com/vissl/model_zoo/seer_finetuned/seer_10b_finetuned_in1k_model_phase28_conso.torch' , lambda: FakeRegNetVisslWrapper( RegNet(RegNetParams(depth=27 , group_width=10_10 , w_a=17_44 , w_a=620.83 , w_m=2.52 ) ) ) , ) if model_name: convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , names_to_config[model_name] , lowercase__ , lowercase__ , ) else: for model_name, config in names_to_config.items(): convert_weight_and_push( lowercase__ , names_to_from_model_map[model_name] , names_to_ours_model_map[model_name] , lowercase__ , lowercase__ , lowercase__ , ) return config, expected_shape if __name__ == "__main__": SCREAMING_SNAKE_CASE__ : str = argparse.ArgumentParser() # Required parameters parser.add_argument( "--model_name", default=None, type=str, help=( "The name of the model you wish to convert, it must be one of the supported regnet* architecture," " currently: regnetx-*, regnety-*. If `None`, all of them will the converted." ), ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=Path, required=True, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=True, type=bool, required=False, help="If True, push model and image processor to the hub.", ) SCREAMING_SNAKE_CASE__ : List[Any] = parser.parse_args() SCREAMING_SNAKE_CASE__ : Path = args.pytorch_dump_folder_path pytorch_dump_folder_path.mkdir(exist_ok=True, parents=True) convert_weights_and_push(pytorch_dump_folder_path, args.model_name, args.push_to_hub)
636
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices SCREAMING_SNAKE_CASE__ : List[str] = logging.get_logger(__name__) class snake_case ( UpperCamelCase_ , UpperCamelCase_ ): lowercase_ = 'maskformer-swin' lowercase_ = { 'num_attention_heads': 'num_heads', 'num_hidden_layers': 'num_layers', } def __init__( self : Optional[Any] , a_ : List[str]=224 , a_ : Tuple=4 , a_ : List[Any]=3 , a_ : Optional[int]=96 , a_ : Any=[2, 2, 6, 2] , a_ : int=[3, 6, 12, 24] , a_ : Any=7 , a_ : Any=4.0 , a_ : Optional[int]=True , a_ : Optional[Any]=0.0 , a_ : Optional[Any]=0.0 , a_ : Optional[int]=0.1 , a_ : Union[str, Any]="gelu" , a_ : Optional[Any]=False , a_ : Any=0.02 , a_ : Optional[int]=1e-5 , a_ : List[Any]=None , a_ : Dict=None , **a_ : Any , )-> Any: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : str = image_size SCREAMING_SNAKE_CASE__ : List[Any] = patch_size SCREAMING_SNAKE_CASE__ : str = num_channels SCREAMING_SNAKE_CASE__ : Dict = embed_dim SCREAMING_SNAKE_CASE__ : List[str] = depths SCREAMING_SNAKE_CASE__ : int = len(a_ ) SCREAMING_SNAKE_CASE__ : Dict = num_heads SCREAMING_SNAKE_CASE__ : Optional[Any] = window_size SCREAMING_SNAKE_CASE__ : Tuple = mlp_ratio SCREAMING_SNAKE_CASE__ : List[Any] = qkv_bias SCREAMING_SNAKE_CASE__ : str = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Union[str, Any] = drop_path_rate SCREAMING_SNAKE_CASE__ : List[Any] = hidden_act SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_absolute_embeddings SCREAMING_SNAKE_CASE__ : Tuple = layer_norm_eps SCREAMING_SNAKE_CASE__ : int = initializer_range # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel # this indicates the channel dimension after the last stage of the model SCREAMING_SNAKE_CASE__ : Dict = int(embed_dim * 2 ** (len(a_ ) - 1) ) SCREAMING_SNAKE_CASE__ : Tuple = ['stem'] + [F'''stage{idx}''' for idx in range(1 , len(a_ ) + 1 )] SCREAMING_SNAKE_CASE__ : Tuple = get_aligned_output_features_output_indices( out_features=a_ , out_indices=a_ , stage_names=self.stage_names )
717
import warnings from typing import List import numpy as np from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding from ...utils import is_flax_available, is_tf_available, is_torch_available class snake_case ( UpperCamelCase_ ): lowercase_ = ['image_processor', 'tokenizer'] lowercase_ = 'OwlViTImageProcessor' lowercase_ = ('CLIPTokenizer', 'CLIPTokenizerFast') def __init__( self : List[str] , a_ : List[Any]=None , a_ : str=None , **a_ : Any )-> Optional[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Dict = None if "feature_extractor" in kwargs: warnings.warn( 'The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`' ' instead.' , a_ , ) SCREAMING_SNAKE_CASE__ : Tuple = kwargs.pop('feature_extractor' ) SCREAMING_SNAKE_CASE__ : List[str] = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError('You need to specify an `image_processor`.' ) if tokenizer is None: raise ValueError('You need to specify a `tokenizer`.' ) super().__init__(a_ , a_ ) def __call__( self : Any , a_ : Optional[int]=None , a_ : Tuple=None , a_ : List[Any]=None , a_ : Tuple="max_length" , a_ : str="np" , **a_ : Any )-> int: """simple docstring""" if text is None and query_images is None and images is None: raise ValueError( 'You have to specify at least one text or query image or image. All three cannot be none.' ) if text is not None: if isinstance(a_ , a_ ) or (isinstance(a_ , a_ ) and not isinstance(text[0] , a_ )): SCREAMING_SNAKE_CASE__ : Tuple = [self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ )] elif isinstance(a_ , a_ ) and isinstance(text[0] , a_ ): SCREAMING_SNAKE_CASE__ : Any = [] # Maximum number of queries across batch SCREAMING_SNAKE_CASE__ : str = max([len(a_ ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(a_ ) != max_num_queries: SCREAMING_SNAKE_CASE__ : Tuple = t + [' '] * (max_num_queries - len(a_ )) SCREAMING_SNAKE_CASE__ : Optional[Any] = self.tokenizer(a_ , padding=a_ , return_tensors=a_ , **a_ ) encodings.append(a_ ) else: raise TypeError('Input text should be a string, a list of strings or a nested list of strings' ) if return_tensors == "np": SCREAMING_SNAKE_CASE__ : Dict = np.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : List[Any] = np.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp SCREAMING_SNAKE_CASE__ : Union[str, Any] = jnp.concatenate([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Optional[Any] = jnp.concatenate([encoding['attention_mask'] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch SCREAMING_SNAKE_CASE__ : int = torch.cat([encoding['input_ids'] for encoding in encodings] , dim=0 ) SCREAMING_SNAKE_CASE__ : Optional[int] = torch.cat([encoding['attention_mask'] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf SCREAMING_SNAKE_CASE__ : str = tf.stack([encoding['input_ids'] for encoding in encodings] , axis=0 ) SCREAMING_SNAKE_CASE__ : Dict = tf.stack([encoding['attention_mask'] for encoding in encodings] , axis=0 ) else: raise ValueError('Target return tensor type could not be returned' ) SCREAMING_SNAKE_CASE__ : Optional[int] = BatchEncoding() SCREAMING_SNAKE_CASE__ : List[str] = input_ids SCREAMING_SNAKE_CASE__ : Tuple = attention_mask if query_images is not None: SCREAMING_SNAKE_CASE__ : Any = BatchEncoding() SCREAMING_SNAKE_CASE__ : Dict = self.image_processor( a_ , return_tensors=a_ , **a_ ).pixel_values SCREAMING_SNAKE_CASE__ : Dict = query_pixel_values if images is not None: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.image_processor(a_ , return_tensors=a_ , **a_ ) if text is not None and images is not None: SCREAMING_SNAKE_CASE__ : Dict = image_features.pixel_values return encoding elif query_images is not None and images is not None: SCREAMING_SNAKE_CASE__ : Optional[int] = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ ) def __lowercase( self : str , *a_ : List[str] , **a_ : int )-> List[Any]: """simple docstring""" return self.image_processor.post_process(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : List[str] , **a_ : str )-> Union[str, Any]: """simple docstring""" return self.image_processor.post_process_object_detection(*a_ , **a_ ) def __lowercase( self : Optional[Any] , *a_ : str , **a_ : Dict )-> Optional[int]: """simple docstring""" return self.image_processor.post_process_image_guided_detection(*a_ , **a_ ) def __lowercase( self : Optional[int] , *a_ : Tuple , **a_ : Tuple )-> Optional[Any]: """simple docstring""" return self.tokenizer.batch_decode(*a_ , **a_ ) def __lowercase( self : Tuple , *a_ : Tuple , **a_ : Tuple )-> List[str]: """simple docstring""" return self.tokenizer.decode(*a_ , **a_ ) @property def __lowercase( self : Tuple )-> Any: """simple docstring""" warnings.warn( '`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.' , a_ , ) return self.image_processor_class @property def __lowercase( self : List[Any] )-> List[str]: """simple docstring""" warnings.warn( '`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.' , a_ , ) return self.image_processor
636
0
import copy import os from collections import OrderedDict from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : str = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : List[str] = { "google/owlvit-base-patch32": "https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json", "google/owlvit-base-patch16": "https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json", "google/owlvit-large-patch14": "https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json", } class snake_case ( UpperCamelCase_ ): lowercase_ = 'owlvit_text_model' def __init__( self : str , a_ : Optional[int]=4_9408 , a_ : int=512 , a_ : Dict=2048 , a_ : Dict=12 , a_ : List[str]=8 , a_ : Dict=16 , a_ : Optional[Any]="quick_gelu" , a_ : List[Any]=1e-5 , a_ : Any=0.0 , a_ : Optional[Any]=0.02 , a_ : List[str]=1.0 , a_ : Any=0 , a_ : List[str]=4_9406 , a_ : Optional[Any]=4_9407 , **a_ : Dict , )-> int: """simple docstring""" super().__init__(pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : Tuple = vocab_size SCREAMING_SNAKE_CASE__ : Any = hidden_size SCREAMING_SNAKE_CASE__ : Optional[int] = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[int] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[int] = num_attention_heads SCREAMING_SNAKE_CASE__ : Dict = max_position_embeddings SCREAMING_SNAKE_CASE__ : Optional[int] = hidden_act SCREAMING_SNAKE_CASE__ : str = layer_norm_eps SCREAMING_SNAKE_CASE__ : Dict = attention_dropout SCREAMING_SNAKE_CASE__ : List[str] = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = initializer_factor @classmethod def __lowercase( cls : Dict , a_ : Union[str, os.PathLike] , **a_ : Any )-> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(a_ ) SCREAMING_SNAKE_CASE__ : Any = cls.get_config_dict(a_ , **a_ ) # get the text config dict if we are loading from OwlViTConfig if config_dict.get('model_type' ) == "owlvit": SCREAMING_SNAKE_CASE__ : Any = 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(a_ , **a_ ) class snake_case ( UpperCamelCase_ ): lowercase_ = 'owlvit_vision_model' def __init__( self : Optional[int] , a_ : Union[str, Any]=768 , a_ : Optional[Any]=3072 , a_ : Optional[Any]=12 , a_ : Tuple=12 , a_ : int=3 , a_ : int=768 , a_ : Optional[int]=32 , a_ : str="quick_gelu" , a_ : int=1e-5 , a_ : List[Any]=0.0 , a_ : Union[str, Any]=0.02 , a_ : Optional[int]=1.0 , **a_ : Dict , )-> Optional[int]: """simple docstring""" super().__init__(**a_ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_size SCREAMING_SNAKE_CASE__ : Optional[Any] = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Dict = num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[int] = num_channels SCREAMING_SNAKE_CASE__ : Dict = image_size SCREAMING_SNAKE_CASE__ : Any = patch_size SCREAMING_SNAKE_CASE__ : int = hidden_act SCREAMING_SNAKE_CASE__ : Dict = layer_norm_eps SCREAMING_SNAKE_CASE__ : Tuple = attention_dropout SCREAMING_SNAKE_CASE__ : str = initializer_range SCREAMING_SNAKE_CASE__ : Tuple = initializer_factor @classmethod def __lowercase( cls : Optional[Any] , a_ : Union[str, os.PathLike] , **a_ : str )-> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(a_ ) SCREAMING_SNAKE_CASE__ : List[str] = cls.get_config_dict(a_ , **a_ ) # get the vision config dict if we are loading from OwlViTConfig if config_dict.get('model_type' ) == "owlvit": SCREAMING_SNAKE_CASE__ : Dict = 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(a_ , **a_ ) class snake_case ( UpperCamelCase_ ): lowercase_ = 'owlvit' lowercase_ = True def __init__( self : Tuple , a_ : Union[str, Any]=None , a_ : Any=None , a_ : Dict=512 , a_ : int=2.6592 , a_ : int=True , **a_ : int , )-> str: """simple docstring""" super().__init__(**a_ ) if text_config is None: SCREAMING_SNAKE_CASE__ : Any = {} logger.info('text_config is None. Initializing the OwlViTTextConfig with default values.' ) if vision_config is None: SCREAMING_SNAKE_CASE__ : Optional[int] = {} logger.info('vision_config is None. initializing the OwlViTVisionConfig with default values.' ) SCREAMING_SNAKE_CASE__ : str = OwlViTTextConfig(**a_ ) SCREAMING_SNAKE_CASE__ : List[str] = OwlViTVisionConfig(**a_ ) SCREAMING_SNAKE_CASE__ : Dict = projection_dim SCREAMING_SNAKE_CASE__ : Optional[int] = logit_scale_init_value SCREAMING_SNAKE_CASE__ : str = return_dict SCREAMING_SNAKE_CASE__ : Union[str, Any] = 1.0 @classmethod def __lowercase( cls : int , a_ : Union[str, os.PathLike] , **a_ : str )-> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(a_ ) SCREAMING_SNAKE_CASE__ : Optional[int] = cls.get_config_dict(a_ , **a_ ) 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(a_ , **a_ ) @classmethod def __lowercase( cls : int , a_ : Dict , a_ : Dict , **a_ : Tuple )-> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[Any] = {} SCREAMING_SNAKE_CASE__ : str = text_config SCREAMING_SNAKE_CASE__ : int = vision_config return cls.from_dict(a_ , **a_ ) def __lowercase( self : List[str] )-> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Optional[int] = copy.deepcopy(self.__dict__ ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.text_config.to_dict() SCREAMING_SNAKE_CASE__ : List[str] = self.vision_config.to_dict() SCREAMING_SNAKE_CASE__ : Optional[Any] = self.__class__.model_type return output class snake_case ( UpperCamelCase_ ): @property def __lowercase( self : Optional[Any] )-> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ('input_ids', {0: 'batch', 1: 'sequence'}), ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}), ('attention_mask', {0: 'batch', 1: 'sequence'}), ] ) @property def __lowercase( self : List[Any] )-> Mapping[str, Mapping[int, str]]: """simple docstring""" return OrderedDict( [ ('logits_per_image', {0: 'batch'}), ('logits_per_text', {0: 'batch'}), ('text_embeds', {0: 'batch'}), ('image_embeds', {0: 'batch'}), ] ) @property def __lowercase( self : int )-> float: """simple docstring""" return 1e-4 def __lowercase( self : Union[str, Any] , a_ : "ProcessorMixin" , a_ : int = -1 , a_ : int = -1 , a_ : Optional["TensorType"] = None , )-> Mapping[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Any = super().generate_dummy_inputs( processor.tokenizer , batch_size=a_ , seq_length=a_ , framework=a_ ) SCREAMING_SNAKE_CASE__ : Any = super().generate_dummy_inputs( processor.image_processor , batch_size=a_ , framework=a_ ) return {**text_input_dict, **image_input_dict} @property def __lowercase( self : int )-> int: """simple docstring""" return 14
718
class snake_case ( UpperCamelCase_ ): pass class snake_case ( UpperCamelCase_ ): pass class snake_case : def __init__( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [ [], [], [], ] def __lowercase( self : int , a_ : int , a_ : int )-> None: """simple docstring""" try: if len(self.queues[priority] ) >= 100: raise OverflowError('Maximum queue size is 100' ) self.queues[priority].append(a_ ) except IndexError: raise ValueError('Valid priorities are 0, 1, and 2' ) def __lowercase( self : int )-> int: """simple docstring""" for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError('All queues are empty' ) def __str__( self : Any )-> str: """simple docstring""" return "\n".join(F'''Priority {i}: {q}''' for i, q in enumerate(self.queues ) ) class snake_case : def __init__( self : Union[str, Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [] def __lowercase( self : List[str] , a_ : int )-> None: """simple docstring""" if len(self.queue ) == 100: raise OverFlowError('Maximum queue size is 100' ) self.queue.append(a_ ) def __lowercase( self : int )-> int: """simple docstring""" if not self.queue: raise UnderFlowError('The queue is empty' ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = min(self.queue ) self.queue.remove(a_ ) return data def __str__( self : List[str] )-> str: """simple docstring""" return str(self.queue ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 1_00 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 1_28 ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(1_00 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(1_28 ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
636
0
from math import factorial, radians def _a ( lowercase__ : float , lowercase__ : int = 18 , lowercase__ : int = 10 ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Optional[Any] = angle_in_degrees - ((angle_in_degrees // 360.0) * 360.0) # Converting from degrees to radians SCREAMING_SNAKE_CASE__ : int = radians(lowercase__ ) SCREAMING_SNAKE_CASE__ : List[Any] = angle_in_radians SCREAMING_SNAKE_CASE__ : Optional[int] = 3 SCREAMING_SNAKE_CASE__ : Optional[int] = -1 for _ in range(lowercase__ ): result += (b * (angle_in_radians**a)) / factorial(lowercase__ ) SCREAMING_SNAKE_CASE__ : Any = -b # One positive term and the next will be negative and so on... a += 2 # Increased by 2 for every term. return round(lowercase__ , lowercase__ ) if __name__ == "__main__": __import__("doctest").testmod()
719
from packaging import version from .import_utils import is_accelerate_available if is_accelerate_available(): import accelerate def _a ( lowercase__ : List[str] ): '''simple docstring''' if not is_accelerate_available(): return method SCREAMING_SNAKE_CASE__ : str = version.parse(accelerate.__version__ ).base_version if version.parse(lowercase__ ) < version.parse('0.17.0' ): return method def wrapper(self : Optional[int] , *lowercase__ : int , **lowercase__ : Tuple ): if hasattr(self , '_hf_hook' ) and hasattr(self._hf_hook , 'pre_forward' ): self._hf_hook.pre_forward(self ) return method(self , *lowercase__ , **lowercase__ ) return wrapper
636
0
class snake_case ( UpperCamelCase_ ): pass class snake_case ( UpperCamelCase_ ): pass class snake_case : def __init__( self : Union[str, Any] )-> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = [ [], [], [], ] def __lowercase( self : int , a_ : int , a_ : int )-> None: """simple docstring""" try: if len(self.queues[priority] ) >= 100: raise OverflowError('Maximum queue size is 100' ) self.queues[priority].append(a_ ) except IndexError: raise ValueError('Valid priorities are 0, 1, and 2' ) def __lowercase( self : int )-> int: """simple docstring""" for queue in self.queues: if queue: return queue.pop(0 ) raise UnderFlowError('All queues are empty' ) def __str__( self : Any )-> str: """simple docstring""" return "\n".join(F'''Priority {i}: {q}''' for i, q in enumerate(self.queues ) ) class snake_case : def __init__( self : Union[str, Any] )-> Dict: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[Any] = [] def __lowercase( self : List[str] , a_ : int )-> None: """simple docstring""" if len(self.queue ) == 100: raise OverFlowError('Maximum queue size is 100' ) self.queue.append(a_ ) def __lowercase( self : int )-> int: """simple docstring""" if not self.queue: raise UnderFlowError('The queue is empty' ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = min(self.queue ) self.queue.remove(a_ ) return data def __str__( self : List[str] )-> str: """simple docstring""" return str(self.queue ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : int = FixedPriorityQueue() fpq.enqueue(0 , 10 ) fpq.enqueue(1 , 70 ) fpq.enqueue(0 , 1_00 ) fpq.enqueue(2 , 1 ) fpq.enqueue(2 , 5 ) fpq.enqueue(1 , 7 ) fpq.enqueue(2 , 4 ) fpq.enqueue(1 , 64 ) fpq.enqueue(0 , 1_28 ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(lowercase__ ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) print(fpq.dequeue() ) def _a ( ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Dict = ElementPriorityQueue() epq.enqueue(10 ) epq.enqueue(70 ) epq.enqueue(1_00 ) epq.enqueue(1 ) epq.enqueue(5 ) epq.enqueue(7 ) epq.enqueue(4 ) epq.enqueue(64 ) epq.enqueue(1_28 ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(lowercase__ ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) print(epq.dequeue() ) if __name__ == "__main__": fixed_priority_queue() element_priority_queue()
720
import os import socket from contextlib import contextmanager import torch from ..commands.config.default import write_basic_config # noqa: F401 from ..state import PartialState from .dataclasses import DistributedType from .imports import is_deepspeed_available, is_tpu_available from .transformer_engine import convert_model from .versions import is_torch_version if is_deepspeed_available(): from deepspeed import DeepSpeedEngine if is_tpu_available(check_device=False): import torch_xla.core.xla_model as xm def _a ( lowercase__ : int ): '''simple docstring''' if is_torch_version('<' , '2.0.0' ) or not hasattr(lowercase__ , '_dynamo' ): return False return isinstance(lowercase__ , torch._dynamo.eval_frame.OptimizedModule ) def _a ( lowercase__ : Optional[Any] , lowercase__ : bool = True ): '''simple docstring''' SCREAMING_SNAKE_CASE__ : Union[str, Any] = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) SCREAMING_SNAKE_CASE__ : Dict = is_compiled_module(lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : Tuple = model SCREAMING_SNAKE_CASE__ : int = model._orig_mod if is_deepspeed_available(): options += (DeepSpeedEngine,) while isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : Any = model.module if not keep_fpaa_wrapper: SCREAMING_SNAKE_CASE__ : List[Any] = getattr(lowercase__ , 'forward' ) SCREAMING_SNAKE_CASE__ : str = model.__dict__.pop('_original_forward' , lowercase__ ) if original_forward is not None: while hasattr(lowercase__ , '__wrapped__' ): SCREAMING_SNAKE_CASE__ : Dict = forward.__wrapped__ if forward == original_forward: break SCREAMING_SNAKE_CASE__ : Dict = forward if getattr(lowercase__ , '_converted_to_transformer_engine' , lowercase__ ): convert_model(lowercase__ , to_transformer_engine=lowercase__ ) if is_compiled: SCREAMING_SNAKE_CASE__ : List[Any] = model SCREAMING_SNAKE_CASE__ : Optional[Any] = compiled_model return model def _a ( ): '''simple docstring''' PartialState().wait_for_everyone() def _a ( lowercase__ : str , lowercase__ : Optional[Any] ): '''simple docstring''' if PartialState().distributed_type == DistributedType.TPU: xm.save(lowercase__ , lowercase__ ) elif PartialState().local_process_index == 0: torch.save(lowercase__ , lowercase__ ) @contextmanager def _a ( **lowercase__ : str ): '''simple docstring''' for key, value in kwargs.items(): SCREAMING_SNAKE_CASE__ : int = str(lowercase__ ) yield for key in kwargs: if key.upper() in os.environ: del os.environ[key.upper()] def _a ( lowercase__ : Optional[Any] ): '''simple docstring''' if not hasattr(lowercase__ , '__qualname__' ) and not hasattr(lowercase__ , '__name__' ): SCREAMING_SNAKE_CASE__ : Any = getattr(lowercase__ , '__class__' , lowercase__ ) if hasattr(lowercase__ , '__qualname__' ): return obj.__qualname__ if hasattr(lowercase__ , '__name__' ): return obj.__name__ return str(lowercase__ ) def _a ( lowercase__ : List[str] , lowercase__ : List[Any] ): '''simple docstring''' for key, value in source.items(): if isinstance(lowercase__ , lowercase__ ): SCREAMING_SNAKE_CASE__ : List[str] = destination.setdefault(lowercase__ , {} ) merge_dicts(lowercase__ , lowercase__ ) else: SCREAMING_SNAKE_CASE__ : List[Any] = value return destination def _a ( lowercase__ : int = None ): '''simple docstring''' if port is None: SCREAMING_SNAKE_CASE__ : int = 2_95_00 with socket.socket(socket.AF_INET , socket.SOCK_STREAM ) as s: return s.connect_ex(('localhost', port) ) == 0
636
0
from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE__ : Tuple = logging.get_logger(__name__) SCREAMING_SNAKE_CASE__ : Optional[Any] = { "facebook/xlm-roberta-xl": "https://huggingface.co/facebook/xlm-roberta-xl/resolve/main/config.json", "facebook/xlm-roberta-xxl": "https://huggingface.co/facebook/xlm-roberta-xxl/resolve/main/config.json", # See all XLM-RoBERTa-XL models at https://huggingface.co/models?filter=xlm-roberta-xl } class snake_case ( UpperCamelCase_ ): lowercase_ = 'xlm-roberta-xl' def __init__( self : List[Any] , a_ : Optional[int]=25_0880 , a_ : Optional[Any]=2560 , a_ : List[Any]=36 , a_ : Union[str, Any]=32 , a_ : List[Any]=1_0240 , a_ : Union[str, Any]="gelu" , a_ : Optional[Any]=0.1 , a_ : int=0.1 , a_ : List[str]=514 , a_ : List[str]=1 , a_ : Union[str, Any]=0.02 , a_ : Union[str, Any]=1e-0_5 , a_ : Any=1 , a_ : int=0 , a_ : List[Any]=2 , a_ : Any="absolute" , a_ : str=True , a_ : Any=None , **a_ : Union[str, Any] , )-> int: """simple docstring""" super().__init__(pad_token_id=a_ , bos_token_id=a_ , eos_token_id=a_ , **a_ ) SCREAMING_SNAKE_CASE__ : str = vocab_size SCREAMING_SNAKE_CASE__ : int = hidden_size SCREAMING_SNAKE_CASE__ : str = num_hidden_layers SCREAMING_SNAKE_CASE__ : List[str] = num_attention_heads SCREAMING_SNAKE_CASE__ : Union[str, Any] = hidden_act SCREAMING_SNAKE_CASE__ : Any = intermediate_size SCREAMING_SNAKE_CASE__ : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Tuple = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : List[str] = max_position_embeddings SCREAMING_SNAKE_CASE__ : List[Any] = type_vocab_size SCREAMING_SNAKE_CASE__ : Tuple = initializer_range SCREAMING_SNAKE_CASE__ : List[str] = layer_norm_eps SCREAMING_SNAKE_CASE__ : str = position_embedding_type SCREAMING_SNAKE_CASE__ : str = use_cache SCREAMING_SNAKE_CASE__ : int = classifier_dropout class snake_case ( UpperCamelCase_ ): @property def __lowercase( self : int )-> Mapping[str, Mapping[int, str]]: """simple docstring""" if self.task == "multiple-choice": SCREAMING_SNAKE_CASE__ : Optional[int] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: SCREAMING_SNAKE_CASE__ : List[Any] = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
721
from __future__ import annotations def _a ( lowercase__ : list[int | float] , lowercase__ : int , lowercase__ : int ): '''simple docstring''' if len(lowercase__ ) == 0: raise ValueError('find_max() arg is an empty sequence' ) if ( left >= len(lowercase__ ) or left < -len(lowercase__ ) or right >= len(lowercase__ ) or right < -len(lowercase__ ) ): raise IndexError('list index out of range' ) if left == right: return nums[left] SCREAMING_SNAKE_CASE__ : Union[str, Any] = (left + right) >> 1 # the middle SCREAMING_SNAKE_CASE__ : int = find_max(lowercase__ , lowercase__ , lowercase__ ) # find max in range[left, mid] SCREAMING_SNAKE_CASE__ : Tuple = find_max(lowercase__ , mid + 1 , lowercase__ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
636
0
"""simple docstring""" def _snake_case ( _snake_case : int ): if upper_limit < 0: raise ValueError('''Limit for the Catalan sequence must be ≥ 0''' ) lowerCAmelCase : Tuple = [0] * (upper_limit + 1) # Base case: C(0) = C(1) = 1 lowerCAmelCase : str = 1 if upper_limit > 0: lowerCAmelCase : Union[str, Any] = 1 # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i for i in range(2 , upper_limit + 1 ): for j in range(_snake_case ): catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1] return catalan_list if __name__ == "__main__": print('''\n********* Catalan Numbers Using Dynamic Programming ************\n''') print('''\n*** Enter -1 at any time to quit ***''') print('''\nEnter the upper limit (≥ 0) for the Catalan number sequence: ''', end='''''') try: while True: snake_case__ : Dict = int(input().strip()) if N < 0: print('''\n********* Goodbye!! ************''') break else: print(f"""The Catalan numbers from 0 through {N} are:""") print(catalan_numbers(N)) print('''Try another upper limit for the sequence: ''', end='''''') except (NameError, ValueError): print('''\n********* Invalid input, goodbye! ************\n''') import doctest doctest.testmod()
637
"""simple docstring""" from __future__ import annotations from PIL import Image # Define glider example snake_case__ : int = [ [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 snake_case__ : Any = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] def _snake_case ( _snake_case : list[list[int]] ): lowerCAmelCase : Union[str, Any] = [] for i in range(len(_snake_case ) ): lowerCAmelCase : Any = [] for j in range(len(cells[i] ) ): # Get the number of live neighbours lowerCAmelCase : Optional[int] = 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(_snake_case ) - 1 and j > 0: neighbour_count += cells[i + 1][j - 1] if i < len(_snake_case ) - 1: neighbour_count += cells[i + 1][j] if i < len(_snake_case ) - 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. lowerCAmelCase : str = 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(_snake_case ) return next_generation def _snake_case ( _snake_case : list[list[int]] , _snake_case : int ): lowerCAmelCase : int = [] for _ in range(_snake_case ): # Create output image lowerCAmelCase : Union[str, Any] = Image.new('''RGB''' , (len(cells[0] ), len(_snake_case )) ) lowerCAmelCase : Union[str, Any] = img.load() # Save cells to image for x in range(len(_snake_case ) ): for y in range(len(cells[0] ) ): lowerCAmelCase : Optional[int] = 255 - cells[y][x] * 255 lowerCAmelCase : List[Any] = (colour, colour, colour) # Save image images.append(_snake_case ) lowerCAmelCase : Union[str, Any] = new_generation(_snake_case ) return images if __name__ == "__main__": snake_case__ : Union[str, Any] = generate_images(GLIDER, 16) images[0].save('''out.gif''', save_all=True, append_images=images[1:])
637
1
"""simple docstring""" import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class snake_case_( a__ ): def __init__( self : Optional[Any] , UpperCamelCase_ : List[Any] , UpperCamelCase_ : Optional[int]=1_3 , UpperCamelCase_ : int=7 , UpperCamelCase_ : Dict=True , UpperCamelCase_ : List[Any]=True , UpperCamelCase_ : List[Any]=False , UpperCamelCase_ : Optional[Any]=True , UpperCamelCase_ : List[Any]=9_9 , UpperCamelCase_ : List[str]=3_2 , UpperCamelCase_ : List[str]=5 , UpperCamelCase_ : Union[str, Any]=4 , UpperCamelCase_ : Any=6_4 , UpperCamelCase_ : Union[str, Any]="gelu" , UpperCamelCase_ : Dict=0.1 , UpperCamelCase_ : Any=0.1 , UpperCamelCase_ : Union[str, Any]=5_1_2 , UpperCamelCase_ : List[str]=1_6 , UpperCamelCase_ : Optional[Any]=2 , UpperCamelCase_ : List[Any]=0.02 , UpperCamelCase_ : Union[str, Any]=3 , UpperCamelCase_ : Any=4 , UpperCamelCase_ : Any=None , UpperCamelCase_ : Union[str, Any]=2 , UpperCamelCase_ : str=2 , UpperCamelCase_ : str=2 , UpperCamelCase_ : Union[str, Any]=2 , UpperCamelCase_ : Any=4 , UpperCamelCase_ : str=1 , ): lowerCAmelCase : Tuple = parent lowerCAmelCase : Dict = batch_size lowerCAmelCase : Optional[Any] = seq_length lowerCAmelCase : Union[str, Any] = is_training lowerCAmelCase : Dict = use_input_mask lowerCAmelCase : Any = use_token_type_ids lowerCAmelCase : Union[str, Any] = use_labels lowerCAmelCase : Optional[int] = vocab_size lowerCAmelCase : List[str] = hidden_size lowerCAmelCase : Tuple = num_hidden_layers lowerCAmelCase : Any = num_attention_heads lowerCAmelCase : int = intermediate_size lowerCAmelCase : Dict = hidden_act lowerCAmelCase : Dict = hidden_dropout_prob lowerCAmelCase : str = attention_probs_dropout_prob lowerCAmelCase : Union[str, Any] = max_position_embeddings lowerCAmelCase : int = type_vocab_size lowerCAmelCase : Union[str, Any] = type_sequence_label_size lowerCAmelCase : Any = initializer_range lowerCAmelCase : Dict = num_labels lowerCAmelCase : List[str] = num_choices lowerCAmelCase : str = scope lowerCAmelCase : Union[str, Any] = q_groups lowerCAmelCase : Union[str, Any] = k_groups lowerCAmelCase : Tuple = v_groups lowerCAmelCase : Optional[int] = post_attention_groups lowerCAmelCase : Dict = intermediate_groups lowerCAmelCase : Optional[int] = output_groups def lowerCamelCase__ ( self : Any ): lowerCAmelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase : List[Any] = None if self.use_input_mask: lowerCAmelCase : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase : int = None lowerCAmelCase : Union[str, Any] = None lowerCAmelCase : Optional[int] = None if self.use_labels: lowerCAmelCase : Optional[int] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCAmelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCAmelCase : List[Any] = ids_tensor([self.batch_size] , self.num_choices ) lowerCAmelCase : Union[str, Any] = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCamelCase__ ( self : Union[str, Any] ): return SqueezeBertConfig( embedding_size=self.hidden_size , vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , attention_probs_dropout_prob=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , q_groups=self.q_groups , k_groups=self.k_groups , v_groups=self.v_groups , post_attention_groups=self.post_attention_groups , intermediate_groups=self.intermediate_groups , output_groups=self.output_groups , ) def lowerCamelCase__ ( self : str , UpperCamelCase_ : List[str] , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : List[str] , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Optional[Any] ): lowerCAmelCase : Optional[Any] = SqueezeBertModel(config=UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowerCAmelCase : List[str] = model(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : int = model(UpperCamelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase__ ( self : Any , UpperCamelCase_ : int , UpperCamelCase_ : int , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : List[str] , UpperCamelCase_ : Dict , UpperCamelCase_ : List[Any] ): lowerCAmelCase : Optional[Any] = SqueezeBertForMaskedLM(config=UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowerCAmelCase : int = model(UpperCamelCase_ , attention_mask=UpperCamelCase_ , labels=UpperCamelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCamelCase__ ( self : Any , UpperCamelCase_ : List[Any] , UpperCamelCase_ : Any , UpperCamelCase_ : int , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : Optional[int] ): lowerCAmelCase : int = SqueezeBertForQuestionAnswering(config=UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowerCAmelCase : Dict = model( UpperCamelCase_ , attention_mask=UpperCamelCase_ , start_positions=UpperCamelCase_ , end_positions=UpperCamelCase_ ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowerCamelCase__ ( self : str , UpperCamelCase_ : Dict , UpperCamelCase_ : List[Any] , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : str , UpperCamelCase_ : Any , UpperCamelCase_ : Union[str, Any] ): lowerCAmelCase : Union[str, Any] = self.num_labels lowerCAmelCase : int = SqueezeBertForSequenceClassification(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowerCAmelCase : Tuple = model(UpperCamelCase_ , attention_mask=UpperCamelCase_ , labels=UpperCamelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowerCamelCase__ ( self : Tuple , UpperCamelCase_ : Tuple , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : str , UpperCamelCase_ : List[Any] , UpperCamelCase_ : List[str] , UpperCamelCase_ : Dict ): lowerCAmelCase : Optional[int] = self.num_labels lowerCAmelCase : Union[str, Any] = SqueezeBertForTokenClassification(config=UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowerCAmelCase : Any = model(UpperCamelCase_ , attention_mask=UpperCamelCase_ , labels=UpperCamelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowerCamelCase__ ( self : str , UpperCamelCase_ : Dict , UpperCamelCase_ : Tuple , UpperCamelCase_ : List[str] , UpperCamelCase_ : Tuple , UpperCamelCase_ : List[Any] , UpperCamelCase_ : str ): lowerCAmelCase : str = self.num_choices lowerCAmelCase : Tuple = SqueezeBertForMultipleChoice(config=UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowerCAmelCase : str = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowerCAmelCase : Dict = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() lowerCAmelCase : Tuple = model( UpperCamelCase_ , attention_mask=UpperCamelCase_ , labels=UpperCamelCase_ , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def lowerCamelCase__ ( self : Dict ): lowerCAmelCase : Any = self.prepare_config_and_inputs() ((lowerCAmelCase), (lowerCAmelCase), (lowerCAmelCase), (lowerCAmelCase), (lowerCAmelCase), (lowerCAmelCase)) : Dict = config_and_inputs lowerCAmelCase : str = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class snake_case_( a__ , a__ , unittest.TestCase ): __UpperCamelCase = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) __UpperCamelCase = ( { '''feature-extraction''': SqueezeBertModel, '''fill-mask''': SqueezeBertForMaskedLM, '''question-answering''': SqueezeBertForQuestionAnswering, '''text-classification''': SqueezeBertForSequenceClassification, '''token-classification''': SqueezeBertForTokenClassification, '''zero-shot''': SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = True __UpperCamelCase = False def lowerCamelCase__ ( self : List[str] ): lowerCAmelCase : Tuple = SqueezeBertModelTester(self ) lowerCAmelCase : Any = ConfigTester(self , config_class=UpperCamelCase_ , dim=3_7 ) def lowerCamelCase__ ( self : str ): self.config_tester.run_common_tests() def lowerCamelCase__ ( self : Union[str, Any] ): lowerCAmelCase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*UpperCamelCase_ ) def lowerCamelCase__ ( self : Optional[Any] ): lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*UpperCamelCase_ ) def lowerCamelCase__ ( self : List[str] ): lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*UpperCamelCase_ ) def lowerCamelCase__ ( self : Optional[int] ): lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*UpperCamelCase_ ) def lowerCamelCase__ ( self : int ): lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*UpperCamelCase_ ) def lowerCamelCase__ ( self : Tuple ): lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*UpperCamelCase_ ) @slow def lowerCamelCase__ ( self : List[Any] ): for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase : Union[str, Any] = SqueezeBertModel.from_pretrained(UpperCamelCase_ ) self.assertIsNotNone(UpperCamelCase_ ) @require_sentencepiece @require_tokenizers @require_torch class snake_case_( unittest.TestCase ): @slow def lowerCamelCase__ ( self : str ): lowerCAmelCase : List[str] = SqueezeBertForSequenceClassification.from_pretrained('''squeezebert/squeezebert-mnli''' ) lowerCAmelCase : List[Any] = torch.tensor([[1, 2_9_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 1_3, 1_5_8_8, 2]] ) lowerCAmelCase : List[str] = model(UpperCamelCase_ )[0] lowerCAmelCase : Tuple = torch.Size((1, 3) ) self.assertEqual(output.shape , UpperCamelCase_ ) lowerCAmelCase : Dict = torch.tensor([[0.6_401, -0.0_349, -0.6_041]] ) self.assertTrue(torch.allclose(UpperCamelCase_ , UpperCamelCase_ , atol=1E-4 ) )
637
"""simple docstring""" from __future__ import annotations class snake_case_: def __init__( self : int , UpperCamelCase_ : str , UpperCamelCase_ : str ): lowerCAmelCase, lowerCAmelCase : List[str] = text, pattern lowerCAmelCase, lowerCAmelCase : Union[str, Any] = len(UpperCamelCase_ ), len(UpperCamelCase_ ) def lowerCamelCase__ ( self : List[Any] , UpperCamelCase_ : str ): for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def lowerCamelCase__ ( self : Optional[Any] , UpperCamelCase_ : int ): for i in range(self.patLen - 1 , -1 , -1 ): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def lowerCamelCase__ ( self : Dict ): # searches pattern in text and returns index positions lowerCAmelCase : Union[str, Any] = [] for i in range(self.textLen - self.patLen + 1 ): lowerCAmelCase : str = self.mismatch_in_text(UpperCamelCase_ ) if mismatch_index == -1: positions.append(UpperCamelCase_ ) else: lowerCAmelCase : Optional[Any] = self.match_in_pattern(self.text[mismatch_index] ) lowerCAmelCase : int = ( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions snake_case__ : str = '''ABAABA''' snake_case__ : List[str] = '''AB''' snake_case__ : Union[str, Any] = BoyerMooreSearch(text, pattern) snake_case__ : Optional[Any] = bms.bad_character_heuristic() if len(positions) == 0: print('''No match found''') else: print('''Pattern found in following positions: ''') print(positions)
637
1
"""simple docstring""" from __future__ import annotations from collections.abc import Iterable, Iterator from dataclasses import dataclass snake_case__ : Union[str, Any] = (3, 9, -11, 0, 7, 5, 1, -1) snake_case__ : Union[str, Any] = (4, 6, 2, 0, 8, 10, 3, -2) @dataclass class snake_case_: __UpperCamelCase = 42 __UpperCamelCase = 42 class snake_case_: def __init__( self : List[str] , UpperCamelCase_ : Iterable[int] ): lowerCAmelCase : Node | None = None for i in sorted(UpperCamelCase_ , reverse=UpperCamelCase_ ): lowerCAmelCase : Dict = Node(UpperCamelCase_ , self.head ) def __iter__( self : Optional[int] ): lowerCAmelCase : Optional[int] = self.head while node: yield node.data lowerCAmelCase : List[str] = node.next_node def __len__( self : Optional[int] ): return sum(1 for _ in self ) def __str__( self : List[str] ): return " -> ".join([str(UpperCamelCase_ ) for node in self] ) def _snake_case ( _snake_case : SortedLinkedList , _snake_case : SortedLinkedList ): return SortedLinkedList(list(_snake_case ) + list(_snake_case ) ) if __name__ == "__main__": import doctest doctest.testmod() snake_case__ : List[str] = SortedLinkedList print(merge_lists(SSL(test_data_odd), SSL(test_data_even)))
637
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case_( a__ ): pass class snake_case_: def __init__( self : Any , UpperCamelCase_ : Any ): lowerCAmelCase : Any = data lowerCAmelCase : Node | None = None def __iter__( self : int ): lowerCAmelCase : Any = self lowerCAmelCase : Union[str, Any] = [] while node: if node in visited: raise ContainsLoopError visited.append(UpperCamelCase_ ) yield node.data lowerCAmelCase : Optional[int] = node.next_node @property def lowerCamelCase__ ( self : str ): try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": snake_case__ : Dict = Node(1) snake_case__ : Any = Node(2) snake_case__ : int = Node(3) snake_case__ : Any = Node(4) print(root_node.has_loop) # False snake_case__ : Tuple = root_node.next_node print(root_node.has_loop) # True snake_case__ : List[Any] = Node(5) snake_case__ : int = Node(6) snake_case__ : List[Any] = Node(5) snake_case__ : Dict = Node(6) print(root_node.has_loop) # False snake_case__ : Any = Node(1) print(root_node.has_loop) # False
637
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available snake_case__ : List[Any] = {'''configuration_glpn''': ['''GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GLPNConfig''']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case__ : List[Any] = ['''GLPNFeatureExtractor'''] snake_case__ : Optional[Any] = ['''GLPNImageProcessor'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case__ : List[Any] = [ '''GLPN_PRETRAINED_MODEL_ARCHIVE_LIST''', '''GLPNForDepthEstimation''', '''GLPNLayer''', '''GLPNModel''', '''GLPNPreTrainedModel''', ] if TYPE_CHECKING: from .configuration_glpn import GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP, GLPNConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_glpn import GLPNFeatureExtractor from .image_processing_glpn import GLPNImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_glpn import ( GLPN_PRETRAINED_MODEL_ARCHIVE_LIST, GLPNForDepthEstimation, GLPNLayer, GLPNModel, GLPNPreTrainedModel, ) else: import sys snake_case__ : str = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
637
"""simple docstring""" from torch import nn class snake_case_( nn.Module ): def __init__( self : int , UpperCamelCase_ : int , UpperCamelCase_ : int ): super().__init__() lowerCAmelCase : str = class_size lowerCAmelCase : Dict = embed_size # self.mlp1 = nn.Linear(embed_size, embed_size) # self.mlp2 = (nn.Linear(embed_size, class_size)) lowerCAmelCase : Any = nn.Linear(UpperCamelCase_ , UpperCamelCase_ ) def lowerCamelCase__ ( self : List[Any] , UpperCamelCase_ : Tuple ): # hidden_state = nn.functional.relu(self.mlp1(hidden_state)) # hidden_state = self.mlp2(hidden_state) lowerCAmelCase : int = self.mlp(UpperCamelCase_ ) return logits
637
1
"""simple docstring""" from itertools import count def _snake_case ( _snake_case : int = 50 ): lowerCAmelCase : List[Any] = [1] * min_block_length for n in count(_snake_case ): fill_count_functions.append(1 ) for block_length in range(_snake_case , n + 1 ): for block_start in range(n - block_length ): fill_count_functions[n] += fill_count_functions[ n - block_start - block_length - 1 ] fill_count_functions[n] += 1 if fill_count_functions[n] > 1000000: break return n if __name__ == "__main__": print(f"""{solution() = }""")
637
"""simple docstring""" class snake_case_: def __init__( self : Union[str, Any] , UpperCamelCase_ : str ): lowerCAmelCase : Dict = val lowerCAmelCase : str = None lowerCAmelCase : Dict = None def lowerCamelCase__ ( self : Union[str, Any] , UpperCamelCase_ : Dict ): if self.val: if val < self.val: if self.left is None: lowerCAmelCase : int = Node(UpperCamelCase_ ) else: self.left.insert(UpperCamelCase_ ) elif val > self.val: if self.right is None: lowerCAmelCase : Any = Node(UpperCamelCase_ ) else: self.right.insert(UpperCamelCase_ ) else: lowerCAmelCase : Optional[Any] = val def _snake_case ( _snake_case : Tuple , _snake_case : str ): # Recursive traversal if root: inorder(root.left , _snake_case ) res.append(root.val ) inorder(root.right , _snake_case ) def _snake_case ( _snake_case : Optional[Any] ): # Build BST if len(_snake_case ) == 0: return arr lowerCAmelCase : Optional[Any] = Node(arr[0] ) for i in range(1 , len(_snake_case ) ): root.insert(arr[i] ) # Traverse BST in order. lowerCAmelCase : Optional[int] = [] inorder(_snake_case , _snake_case ) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
637
1
"""simple docstring""" from __future__ import annotations import unittest import numpy as np from transformers import BlipTextConfig from transformers.testing_utils import require_tf, slow from transformers.utils import is_tf_available from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask if is_tf_available(): import tensorflow as tf from transformers import TFBlipTextModel from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST class snake_case_: def __init__( self : Union[str, Any] , UpperCamelCase_ : int , UpperCamelCase_ : Optional[Any]=1_2 , UpperCamelCase_ : List[Any]=7 , UpperCamelCase_ : Optional[Any]=True , UpperCamelCase_ : Dict=True , UpperCamelCase_ : Optional[int]=True , UpperCamelCase_ : List[Any]=9_9 , UpperCamelCase_ : Tuple=3_2 , UpperCamelCase_ : int=3_2 , UpperCamelCase_ : str=2 , UpperCamelCase_ : List[str]=4 , UpperCamelCase_ : List[str]=3_7 , UpperCamelCase_ : Tuple=0.1 , UpperCamelCase_ : Tuple=0.1 , UpperCamelCase_ : List[Any]=5_1_2 , UpperCamelCase_ : Union[str, Any]=0.02 , UpperCamelCase_ : Optional[int]=0 , UpperCamelCase_ : List[str]=None , ): lowerCAmelCase : int = parent lowerCAmelCase : Union[str, Any] = batch_size lowerCAmelCase : str = seq_length lowerCAmelCase : Any = is_training lowerCAmelCase : Tuple = use_input_mask lowerCAmelCase : List[Any] = use_labels lowerCAmelCase : List[str] = vocab_size lowerCAmelCase : Optional[Any] = hidden_size lowerCAmelCase : Any = projection_dim lowerCAmelCase : List[str] = num_hidden_layers lowerCAmelCase : Tuple = num_attention_heads lowerCAmelCase : str = intermediate_size lowerCAmelCase : List[str] = dropout lowerCAmelCase : int = attention_dropout lowerCAmelCase : str = max_position_embeddings lowerCAmelCase : Union[str, Any] = initializer_range lowerCAmelCase : List[str] = scope lowerCAmelCase : List[str] = bos_token_id def lowerCamelCase__ ( self : List[Any] ): lowerCAmelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase : int = None if self.use_input_mask: lowerCAmelCase : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) if input_mask is not None: lowerCAmelCase : Optional[int] = input_mask.numpy() lowerCAmelCase, lowerCAmelCase : str = input_mask.shape lowerCAmelCase : List[Any] = np.random.randint(1 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(UpperCamelCase_ ): lowerCAmelCase : List[Any] = 1 lowerCAmelCase : List[str] = 0 lowerCAmelCase : Tuple = self.get_config() return config, input_ids, tf.convert_to_tensor(UpperCamelCase_ ) def lowerCamelCase__ ( self : Optional[Any] ): return BlipTextConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , projection_dim=self.projection_dim , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , dropout=self.dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , bos_token_id=self.bos_token_id , ) def lowerCamelCase__ ( self : Union[str, Any] , UpperCamelCase_ : Tuple , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : List[str] ): lowerCAmelCase : List[Any] = TFBlipTextModel(config=UpperCamelCase_ ) lowerCAmelCase : Tuple = model(UpperCamelCase_ , attention_mask=UpperCamelCase_ , training=UpperCamelCase_ ) lowerCAmelCase : Any = model(UpperCamelCase_ , training=UpperCamelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def lowerCamelCase__ ( self : Optional[Any] ): lowerCAmelCase : Optional[int] = self.prepare_config_and_inputs() lowerCAmelCase, lowerCAmelCase, lowerCAmelCase : Optional[int] = config_and_inputs lowerCAmelCase : str = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_tf class snake_case_( a__ , unittest.TestCase ): __UpperCamelCase = (TFBlipTextModel,) if is_tf_available() else () __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def lowerCamelCase__ ( self : List[str] ): lowerCAmelCase : List[str] = BlipTextModelTester(self ) lowerCAmelCase : int = ConfigTester(self , config_class=UpperCamelCase_ , hidden_size=3_7 ) def lowerCamelCase__ ( self : List[str] ): self.config_tester.run_common_tests() def lowerCamelCase__ ( self : Tuple ): lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase_ ) def lowerCamelCase__ ( self : Dict ): pass def lowerCamelCase__ ( self : int ): pass @unittest.skip(reason='''Blip does not use inputs_embeds''' ) def lowerCamelCase__ ( self : Optional[Any] ): pass @unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING''' ) def lowerCamelCase__ ( self : Tuple ): pass @unittest.skip(reason='''BlipTextModel has no base class and is not available in MODEL_MAPPING''' ) def lowerCamelCase__ ( self : List[Any] ): pass @slow def lowerCamelCase__ ( self : Tuple ): for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase : str = TFBlipTextModel.from_pretrained(UpperCamelCase_ ) self.assertIsNotNone(UpperCamelCase_ ) def lowerCamelCase__ ( self : str , UpperCamelCase_ : Optional[int]=True ): super().test_pt_tf_model_equivalence(allow_missing_keys=UpperCamelCase_ )
637
"""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 snake_case__ : Tuple = logging.get_logger(__name__) snake_case__ : int = { '''facebook/levit-128S''': '''https://huggingface.co/facebook/levit-128S/resolve/main/config.json''', # See all LeViT models at https://huggingface.co/models?filter=levit } class snake_case_( a__ ): __UpperCamelCase = '''levit''' def __init__( self : str , UpperCamelCase_ : Union[str, Any]=2_2_4 , UpperCamelCase_ : Union[str, Any]=3 , UpperCamelCase_ : Union[str, Any]=3 , UpperCamelCase_ : int=2 , UpperCamelCase_ : Union[str, Any]=1 , UpperCamelCase_ : Tuple=1_6 , UpperCamelCase_ : Dict=[1_2_8, 2_5_6, 3_8_4] , UpperCamelCase_ : Optional[Any]=[4, 8, 1_2] , UpperCamelCase_ : Dict=[4, 4, 4] , UpperCamelCase_ : Any=[1_6, 1_6, 1_6] , UpperCamelCase_ : str=0 , UpperCamelCase_ : int=[2, 2, 2] , UpperCamelCase_ : Optional[Any]=[2, 2, 2] , UpperCamelCase_ : str=0.02 , **UpperCamelCase_ : List[str] , ): super().__init__(**UpperCamelCase_ ) lowerCAmelCase : Tuple = image_size lowerCAmelCase : int = num_channels lowerCAmelCase : Optional[int] = kernel_size lowerCAmelCase : Dict = stride lowerCAmelCase : List[Any] = padding lowerCAmelCase : Dict = hidden_sizes lowerCAmelCase : List[str] = num_attention_heads lowerCAmelCase : Tuple = depths lowerCAmelCase : Dict = key_dim lowerCAmelCase : Union[str, Any] = drop_path_rate lowerCAmelCase : List[Any] = patch_size lowerCAmelCase : Tuple = attention_ratio lowerCAmelCase : Optional[int] = mlp_ratio lowerCAmelCase : Union[str, Any] = initializer_range lowerCAmelCase : List[str] = [ ['''Subsample''', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['''Subsample''', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] class snake_case_( a__ ): __UpperCamelCase = version.parse('''1.11''' ) @property def lowerCamelCase__ ( self : Tuple ): return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def lowerCamelCase__ ( self : Optional[Any] ): return 1E-4
637
1
"""simple docstring""" import json import os import unittest from transformers.models.blenderbot_small.tokenization_blenderbot_small import ( VOCAB_FILES_NAMES, BlenderbotSmallTokenizer, ) from ...test_tokenization_common import TokenizerTesterMixin class snake_case_( a__ , unittest.TestCase ): __UpperCamelCase = BlenderbotSmallTokenizer __UpperCamelCase = False def lowerCamelCase__ ( self : List[str] ): super().setUp() lowerCAmelCase : int = ['''__start__''', '''adapt''', '''act''', '''ap@@''', '''te''', '''__end__''', '''__unk__'''] lowerCAmelCase : int = dict(zip(UpperCamelCase_ , range(len(UpperCamelCase_ ) ) ) ) lowerCAmelCase : str = ['''#version: 0.2''', '''a p''', '''t e</w>''', '''ap t</w>''', '''a d''', '''ad apt</w>''', '''a c''', '''ac t</w>''', ''''''] lowerCAmelCase : Union[str, Any] = {'''unk_token''': '''__unk__''', '''bos_token''': '''__start__''', '''eos_token''': '''__end__'''} lowerCAmelCase : str = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) lowerCAmelCase : Dict = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(UpperCamelCase_ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(UpperCamelCase_ ) ) def lowerCamelCase__ ( self : Union[str, Any] , **UpperCamelCase_ : Tuple ): kwargs.update(self.special_tokens_map ) return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname , **UpperCamelCase_ ) def lowerCamelCase__ ( self : Any , UpperCamelCase_ : Union[str, Any] ): lowerCAmelCase : List[Any] = '''adapt act apte''' lowerCAmelCase : str = '''adapt act apte''' return input_text, output_text def lowerCamelCase__ ( self : List[Any] ): lowerCAmelCase : int = BlenderbotSmallTokenizer(self.vocab_file , self.merges_file , **self.special_tokens_map ) lowerCAmelCase : List[str] = '''adapt act apte''' lowerCAmelCase : List[Any] = ['''adapt''', '''act''', '''ap@@''', '''te'''] lowerCAmelCase : List[str] = tokenizer.tokenize(UpperCamelCase_ ) self.assertListEqual(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : List[str] = [tokenizer.bos_token] + tokens + [tokenizer.eos_token] lowerCAmelCase : str = [0, 1, 2, 3, 4, 5] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase_ ) , UpperCamelCase_ ) def lowerCamelCase__ ( self : int ): lowerCAmelCase : Dict = BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' ) assert tok('''sam''' ).input_ids == [1_3_8_4] lowerCAmelCase : Optional[int] = '''I am a small frog.''' lowerCAmelCase : List[str] = tok([src_text] , padding=UpperCamelCase_ , truncation=UpperCamelCase_ )['''input_ids'''] lowerCAmelCase : int = tok.batch_decode(UpperCamelCase_ , skip_special_tokens=UpperCamelCase_ , clean_up_tokenization_spaces=UpperCamelCase_ )[0] assert src_text != decoded # I wish it did! assert decoded == "i am a small frog ." def lowerCamelCase__ ( self : Tuple ): lowerCAmelCase : List[str] = BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''' ) lowerCAmelCase : Dict = '''I am a small frog .''' lowerCAmelCase : Tuple = '''.''' lowerCAmelCase : Any = tok(UpperCamelCase_ )['''input_ids'''] lowerCAmelCase : Tuple = tok(UpperCamelCase_ )['''input_ids'''] assert encoded[-1] == encoded_dot[0]
637
"""simple docstring""" import time import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers.generation import ( MaxLengthCriteria, MaxNewTokensCriteria, MaxTimeCriteria, StoppingCriteriaList, validate_stopping_criteria, ) @require_torch class snake_case_( unittest.TestCase ): def lowerCamelCase__ ( self : int , UpperCamelCase_ : int ): lowerCAmelCase : str = 3 lowerCAmelCase : Tuple = 2_5_0 lowerCAmelCase : Optional[Any] = ids_tensor((batch_size, length) , UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = torch.ones((batch_size, length) , device=UpperCamelCase_ , dtype=torch.float ) / length return input_ids, scores def lowerCamelCase__ ( self : Optional[Any] ): lowerCAmelCase, lowerCAmelCase : Optional[int] = self._get_tensors(5 ) lowerCAmelCase : Union[str, Any] = StoppingCriteriaList( [ MaxLengthCriteria(max_length=1_0 ), MaxTimeCriteria(max_time=0.1 ), ] ) self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase, lowerCAmelCase : List[str] = self._get_tensors(9 ) self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase, lowerCAmelCase : Any = self._get_tensors(1_0 ) self.assertTrue(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) def lowerCamelCase__ ( self : Optional[Any] ): lowerCAmelCase : Optional[Any] = MaxLengthCriteria(max_length=1_0 ) lowerCAmelCase, lowerCAmelCase : Optional[Any] = self._get_tensors(5 ) self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase, lowerCAmelCase : List[str] = self._get_tensors(9 ) self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase, lowerCAmelCase : str = self._get_tensors(1_0 ) self.assertTrue(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) def lowerCamelCase__ ( self : List[Any] ): lowerCAmelCase : Optional[Any] = MaxNewTokensCriteria(start_length=5 , max_new_tokens=5 ) lowerCAmelCase, lowerCAmelCase : Optional[int] = self._get_tensors(5 ) self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase, lowerCAmelCase : Union[str, Any] = self._get_tensors(9 ) self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase, lowerCAmelCase : str = self._get_tensors(1_0 ) self.assertTrue(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase : Dict = StoppingCriteriaList([criteria] ) self.assertEqual(criteria_list.max_length , 1_0 ) def lowerCamelCase__ ( self : Union[str, Any] ): lowerCAmelCase, lowerCAmelCase : Tuple = self._get_tensors(5 ) lowerCAmelCase : List[str] = MaxTimeCriteria(max_time=0.1 ) self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase : List[str] = MaxTimeCriteria(max_time=0.1 , initial_timestamp=time.time() - 0.2 ) self.assertTrue(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) def lowerCamelCase__ ( self : str ): validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(1_0 )] ) , 1_0 ) with self.assertWarns(UpperCamelCase_ ): validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(1_0 )] ) , 1_1 ) lowerCAmelCase : str = validate_stopping_criteria(StoppingCriteriaList() , 1_1 ) self.assertEqual(len(UpperCamelCase_ ) , 1 )
637
1
"""simple docstring""" import json import os import unittest from transformers import DebertaTokenizer, DebertaTokenizerFast from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES from transformers.testing_utils import slow from ...test_tokenization_common import TokenizerTesterMixin class snake_case_( a__ , unittest.TestCase ): __UpperCamelCase = DebertaTokenizer __UpperCamelCase = True __UpperCamelCase = DebertaTokenizerFast def lowerCamelCase__ ( self : List[str] ): super().setUp() # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt lowerCAmelCase : List[Any] = [ '''l''', '''o''', '''w''', '''e''', '''r''', '''s''', '''t''', '''i''', '''d''', '''n''', '''\u0120''', '''\u0120l''', '''\u0120n''', '''\u0120lo''', '''\u0120low''', '''er''', '''\u0120lowest''', '''\u0120newer''', '''\u0120wider''', '''[UNK]''', ] lowerCAmelCase : Optional[Any] = dict(zip(UpperCamelCase_ , range(len(UpperCamelCase_ ) ) ) ) lowerCAmelCase : Any = ['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', ''''''] lowerCAmelCase : Union[str, Any] = {'''unk_token''': '''[UNK]'''} lowerCAmelCase : Optional[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] ) lowerCAmelCase : Union[str, Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''merges_file'''] ) with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write(json.dumps(UpperCamelCase_ ) + '''\n''' ) with open(self.merges_file , '''w''' , encoding='''utf-8''' ) as fp: fp.write('''\n'''.join(UpperCamelCase_ ) ) def lowerCamelCase__ ( self : Optional[int] , **UpperCamelCase_ : Optional[Any] ): kwargs.update(self.special_tokens_map ) return self.tokenizer_class.from_pretrained(self.tmpdirname , **UpperCamelCase_ ) def lowerCamelCase__ ( self : Optional[int] , UpperCamelCase_ : Dict ): lowerCAmelCase : Tuple = '''lower newer''' lowerCAmelCase : List[Any] = '''lower newer''' return input_text, output_text def lowerCamelCase__ ( self : str ): lowerCAmelCase : Optional[Any] = self.get_tokenizer() lowerCAmelCase : str = '''lower newer''' lowerCAmelCase : Optional[int] = ['''l''', '''o''', '''w''', '''er''', '''\u0120''', '''n''', '''e''', '''w''', '''er'''] lowerCAmelCase : Optional[int] = tokenizer.tokenize(UpperCamelCase_ ) self.assertListEqual(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = tokens + [tokenizer.unk_token] lowerCAmelCase : List[str] = [0, 1, 2, 1_5, 1_0, 9, 3, 2, 1_5, 1_9] self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCamelCase_ ) , UpperCamelCase_ ) def lowerCamelCase__ ( self : List[str] ): lowerCAmelCase : Any = self.get_tokenizer() lowerCAmelCase : List[Any] = tokenizer('''Hello''' , '''World''' ) lowerCAmelCase : str = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] self.assertListEqual(tokd['''token_type_ids'''] , UpperCamelCase_ ) @slow def lowerCamelCase__ ( self : Tuple ): lowerCAmelCase : Tuple = self.tokenizer_class.from_pretrained('''microsoft/deberta-base''' ) lowerCAmelCase : str = tokenizer.encode('''sequence builders''' , add_special_tokens=UpperCamelCase_ ) lowerCAmelCase : Optional[int] = tokenizer.encode('''multi-sequence build''' , add_special_tokens=UpperCamelCase_ ) lowerCAmelCase : Optional[int] = tokenizer.encode( '''sequence builders''' , add_special_tokens=UpperCamelCase_ , add_prefix_space=UpperCamelCase_ ) lowerCAmelCase : int = tokenizer.encode( '''sequence builders''' , '''multi-sequence build''' , add_special_tokens=UpperCamelCase_ , add_prefix_space=UpperCamelCase_ ) lowerCAmelCase : int = tokenizer.build_inputs_with_special_tokens(UpperCamelCase_ ) lowerCAmelCase : List[str] = tokenizer.build_inputs_with_special_tokens(UpperCamelCase_ , UpperCamelCase_ ) assert encoded_sentence == encoded_text_from_decode assert encoded_pair == encoded_pair_from_decode @slow def lowerCamelCase__ ( self : Union[str, Any] ): lowerCAmelCase : Union[str, Any] = [self.tokenizer_class] if self.test_rust_tokenizer: tokenizer_classes.append(self.rust_tokenizer_class ) for tokenizer_class in tokenizer_classes: lowerCAmelCase : Tuple = tokenizer_class.from_pretrained('''microsoft/deberta-base''' ) lowerCAmelCase : Tuple = [ '''ALBERT: A Lite BERT for Self-supervised Learning of Language Representations''', '''ALBERT incorporates two parameter reduction techniques''', '''The first one is a factorized embedding parameterization. By decomposing the large vocabulary''' ''' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of''' ''' vocabulary embedding.''', ] lowerCAmelCase : Dict = tokenizer(UpperCamelCase_ , padding=UpperCamelCase_ ) lowerCAmelCase : Optional[int] = [tokenizer.decode(UpperCamelCase_ , skip_special_tokens=UpperCamelCase_ ) for seq in encoding['''input_ids''']] # fmt: off lowerCAmelCase : int = { '''input_ids''': [ [1, 2_1_1_8, 1_1_1_2_6, 5_6_5, 3_5, 8_3, 2_5_1_9_1, 1_6_3, 1_8_8_5_4, 1_3, 1_2_1_5_6, 1_2, 1_6_1_0_1, 2_5_3_7_6, 1_3_8_0_7, 9, 2_2_2_0_5, 2_7_8_9_3, 1_6_3_5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 2_1_1_8, 1_1_1_2_6, 5_6_5, 2_4_5_3_6, 8_0, 4_3_7_9_7, 4_8_7_8, 7_3_7_3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1_3_3, 7_8, 6_5, 1_6, 1_0, 3_7_2_4, 1_5_3_8, 3_3_1_8_3, 1_1_3_0_3, 4_3_7_9_7, 1_9_3_8, 4, 8_7_0, 2_4_1_6_5, 2_9_1_0_5, 5, 7_3_9, 3_2_6_4_4, 3_3_1_8_3, 1_1_3_0_3, 3_6_1_7_3, 8_8, 8_0, 6_5_0, 7_8_2_1, 4_5_9_4_0, 6, 5_2, 2_5_5_9, 5, 1_8_3_6, 9, 5, 7_3_9_7, 1_3_1_7_1, 3_1, 5, 1_8_3_6, 9, 3_2_6_4_4, 3_3_1_8_3, 1_1_3_0_3, 4, 2] ], '''token_type_ids''': [ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ], '''attention_mask''': [ [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], [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], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ] } # fmt: on lowerCAmelCase : Any = [ '''ALBERT: A Lite BERT for Self-supervised Learning of Language Representations''', '''ALBERT incorporates two parameter reduction techniques''', '''The first one is a factorized embedding parameterization. By decomposing the large vocabulary''' ''' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of''' ''' vocabulary embedding.''', ] self.assertDictEqual(encoding.data , UpperCamelCase_ ) for expected, decoded in zip(UpperCamelCase_ , UpperCamelCase_ ): self.assertEqual(UpperCamelCase_ , UpperCamelCase_ )
637
"""simple docstring""" import math from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->UnCLIP class snake_case_( a__ ): __UpperCamelCase = 42 __UpperCamelCase = None def _snake_case ( _snake_case : Dict , _snake_case : List[str]=0.999 , _snake_case : Dict="cosine" , ): if alpha_transform_type == "cosine": def alpha_bar_fn(_snake_case : List[Any] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(_snake_case : Optional[int] ): return math.exp(t * -12.0 ) else: raise ValueError(f'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) lowerCAmelCase : List[Any] = [] for i in range(_snake_case ): lowerCAmelCase : int = i / num_diffusion_timesteps lowerCAmelCase : Tuple = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(_snake_case ) / alpha_bar_fn(_snake_case ) , _snake_case ) ) return torch.tensor(_snake_case , dtype=torch.floataa ) class snake_case_( a__ , a__ ): @register_to_config def __init__( self : Any , UpperCamelCase_ : int = 1_0_0_0 , UpperCamelCase_ : str = "fixed_small_log" , UpperCamelCase_ : bool = True , UpperCamelCase_ : Optional[float] = 1.0 , UpperCamelCase_ : str = "epsilon" , UpperCamelCase_ : str = "squaredcos_cap_v2" , ): if beta_schedule != "squaredcos_cap_v2": raise ValueError('''UnCLIPScheduler only supports `beta_schedule`: \'squaredcos_cap_v2\'''' ) lowerCAmelCase : Any = betas_for_alpha_bar(UpperCamelCase_ ) lowerCAmelCase : str = 1.0 - self.betas lowerCAmelCase : Union[str, Any] = torch.cumprod(self.alphas , dim=0 ) lowerCAmelCase : Tuple = torch.tensor(1.0 ) # standard deviation of the initial noise distribution lowerCAmelCase : Any = 1.0 # setable values lowerCAmelCase : Any = None lowerCAmelCase : Any = torch.from_numpy(np.arange(0 , UpperCamelCase_ )[::-1].copy() ) lowerCAmelCase : List[str] = variance_type def lowerCamelCase__ ( self : Union[str, Any] , UpperCamelCase_ : torch.FloatTensor , UpperCamelCase_ : Optional[int] = None ): return sample def lowerCamelCase__ ( self : Tuple , UpperCamelCase_ : int , UpperCamelCase_ : Union[str, torch.device] = None ): lowerCAmelCase : Any = num_inference_steps lowerCAmelCase : str = (self.config.num_train_timesteps - 1) / (self.num_inference_steps - 1) lowerCAmelCase : Tuple = (np.arange(0 , UpperCamelCase_ ) * step_ratio).round()[::-1].copy().astype(np.intaa ) lowerCAmelCase : Any = torch.from_numpy(UpperCamelCase_ ).to(UpperCamelCase_ ) def lowerCamelCase__ ( self : Optional[Any] , UpperCamelCase_ : List[Any] , UpperCamelCase_ : str=None , UpperCamelCase_ : Tuple=None , UpperCamelCase_ : Any=None ): if prev_timestep is None: lowerCAmelCase : Any = t - 1 lowerCAmelCase : int = self.alphas_cumprod[t] lowerCAmelCase : Union[str, Any] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one lowerCAmelCase : Dict = 1 - alpha_prod_t lowerCAmelCase : str = 1 - alpha_prod_t_prev if prev_timestep == t - 1: lowerCAmelCase : Tuple = self.betas[t] else: lowerCAmelCase : Union[str, Any] = 1 - alpha_prod_t / alpha_prod_t_prev # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample lowerCAmelCase : Optional[Any] = beta_prod_t_prev / beta_prod_t * beta if variance_type is None: lowerCAmelCase : List[str] = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small_log": lowerCAmelCase : Any = torch.log(torch.clamp(UpperCamelCase_ , min=1E-20 ) ) lowerCAmelCase : Union[str, Any] = torch.exp(0.5 * variance ) elif variance_type == "learned_range": # NOTE difference with DDPM scheduler lowerCAmelCase : Optional[Any] = variance.log() lowerCAmelCase : Union[str, Any] = beta.log() lowerCAmelCase : Dict = (predicted_variance + 1) / 2 lowerCAmelCase : Union[str, Any] = frac * max_log + (1 - frac) * min_log return variance def lowerCamelCase__ ( self : Optional[Any] , UpperCamelCase_ : torch.FloatTensor , UpperCamelCase_ : int , UpperCamelCase_ : torch.FloatTensor , UpperCamelCase_ : Optional[int] = None , UpperCamelCase_ : List[Any]=None , UpperCamelCase_ : bool = True , ): lowerCAmelCase : Optional[Any] = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type == "learned_range": lowerCAmelCase, lowerCAmelCase : List[Any] = torch.split(UpperCamelCase_ , sample.shape[1] , dim=1 ) else: lowerCAmelCase : Optional[int] = None # 1. compute alphas, betas if prev_timestep is None: lowerCAmelCase : Any = t - 1 lowerCAmelCase : Union[str, Any] = self.alphas_cumprod[t] lowerCAmelCase : Optional[int] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one lowerCAmelCase : int = 1 - alpha_prod_t lowerCAmelCase : str = 1 - alpha_prod_t_prev if prev_timestep == t - 1: lowerCAmelCase : List[Any] = self.betas[t] lowerCAmelCase : Optional[int] = self.alphas[t] else: lowerCAmelCase : List[Any] = 1 - alpha_prod_t / alpha_prod_t_prev lowerCAmelCase : Dict = 1 - beta # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": lowerCAmelCase : List[Any] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": lowerCAmelCase : Tuple = model_output else: raise ValueError( F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon` or `sample`''' ''' for the UnCLIPScheduler.''' ) # 3. Clip "predicted x_0" if self.config.clip_sample: lowerCAmelCase : Dict = torch.clamp( UpperCamelCase_ , -self.config.clip_sample_range , self.config.clip_sample_range ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowerCAmelCase : int = (alpha_prod_t_prev ** 0.5 * beta) / beta_prod_t lowerCAmelCase : List[Any] = alpha ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowerCAmelCase : str = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise lowerCAmelCase : int = 0 if t > 0: lowerCAmelCase : Union[str, Any] = randn_tensor( model_output.shape , dtype=model_output.dtype , generator=UpperCamelCase_ , device=model_output.device ) lowerCAmelCase : Any = self._get_variance( UpperCamelCase_ , predicted_variance=UpperCamelCase_ , prev_timestep=UpperCamelCase_ , ) if self.variance_type == "fixed_small_log": lowerCAmelCase : str = variance elif self.variance_type == "learned_range": lowerCAmelCase : Optional[Any] = (0.5 * variance).exp() else: raise ValueError( F'''variance_type given as {self.variance_type} must be one of `fixed_small_log` or `learned_range`''' ''' for the UnCLIPScheduler.''' ) lowerCAmelCase : List[Any] = variance * variance_noise lowerCAmelCase : int = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return UnCLIPSchedulerOutput(prev_sample=UpperCamelCase_ , pred_original_sample=UpperCamelCase_ ) def lowerCamelCase__ ( self : Optional[int] , UpperCamelCase_ : torch.FloatTensor , UpperCamelCase_ : torch.FloatTensor , UpperCamelCase_ : torch.IntTensor , ): # Make sure alphas_cumprod and timestep have same device and dtype as original_samples lowerCAmelCase : Tuple = self.alphas_cumprod.to(device=original_samples.device , dtype=original_samples.dtype ) lowerCAmelCase : int = timesteps.to(original_samples.device ) lowerCAmelCase : Dict = alphas_cumprod[timesteps] ** 0.5 lowerCAmelCase : str = sqrt_alpha_prod.flatten() while len(sqrt_alpha_prod.shape ) < len(original_samples.shape ): lowerCAmelCase : Any = sqrt_alpha_prod.unsqueeze(-1 ) lowerCAmelCase : List[str] = (1 - alphas_cumprod[timesteps]) ** 0.5 lowerCAmelCase : Tuple = sqrt_one_minus_alpha_prod.flatten() while len(sqrt_one_minus_alpha_prod.shape ) < len(original_samples.shape ): lowerCAmelCase : int = sqrt_one_minus_alpha_prod.unsqueeze(-1 ) lowerCAmelCase : Dict = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples
637
1
"""simple docstring""" import torch from diffusers import KDPMaDiscreteScheduler from diffusers.utils import torch_device from .test_schedulers import SchedulerCommonTest class snake_case_( a__ ): __UpperCamelCase = (KDPMaDiscreteScheduler,) __UpperCamelCase = 10 def lowerCamelCase__ ( self : Dict , **UpperCamelCase_ : Optional[int] ): lowerCAmelCase : Any = { '''num_train_timesteps''': 1_1_0_0, '''beta_start''': 0.0_001, '''beta_end''': 0.02, '''beta_schedule''': '''linear''', } config.update(**UpperCamelCase_ ) return config def lowerCamelCase__ ( self : str ): for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=UpperCamelCase_ ) def lowerCamelCase__ ( self : Optional[int] ): for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001] , [0.0_002, 0.002, 0.02] ): self.check_over_configs(beta_start=UpperCamelCase_ , beta_end=UpperCamelCase_ ) def lowerCamelCase__ ( self : Union[str, Any] ): for schedule in ["linear", "scaled_linear"]: self.check_over_configs(beta_schedule=UpperCamelCase_ ) def lowerCamelCase__ ( self : str ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=UpperCamelCase_ ) def lowerCamelCase__ ( self : Any ): lowerCAmelCase : Optional[Any] = self.scheduler_classes[0] lowerCAmelCase : Tuple = self.get_scheduler_config(prediction_type='''v_prediction''' ) lowerCAmelCase : int = scheduler_class(**UpperCamelCase_ ) scheduler.set_timesteps(self.num_inference_steps ) lowerCAmelCase : Union[str, Any] = self.dummy_model() lowerCAmelCase : Any = self.dummy_sample_deter * scheduler.init_noise_sigma lowerCAmelCase : Any = sample.to(UpperCamelCase_ ) for i, t in enumerate(scheduler.timesteps ): lowerCAmelCase : List[Any] = scheduler.scale_model_input(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = model(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : Optional[int] = scheduler.step(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : Tuple = output.prev_sample lowerCAmelCase : Optional[Any] = torch.sum(torch.abs(UpperCamelCase_ ) ) lowerCAmelCase : Optional[int] = torch.mean(torch.abs(UpperCamelCase_ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 4.6934E-07 ) < 1E-2 assert abs(result_mean.item() - 6.1112E-10 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 4.693428650170972E-07 ) < 1E-2 assert abs(result_mean.item() - 0.0_002 ) < 1E-3 def lowerCamelCase__ ( self : Any ): if torch_device == "mps": return lowerCAmelCase : Optional[Any] = self.scheduler_classes[0] lowerCAmelCase : List[Any] = self.get_scheduler_config() lowerCAmelCase : Dict = scheduler_class(**UpperCamelCase_ ) scheduler.set_timesteps(self.num_inference_steps ) lowerCAmelCase : Optional[Any] = self.dummy_model() lowerCAmelCase : Tuple = self.dummy_sample_deter * scheduler.init_noise_sigma lowerCAmelCase : Any = sample.to(UpperCamelCase_ ) for i, t in enumerate(scheduler.timesteps ): lowerCAmelCase : List[str] = scheduler.scale_model_input(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : Optional[int] = model(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : Tuple = scheduler.step(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : List[str] = output.prev_sample lowerCAmelCase : Optional[int] = torch.sum(torch.abs(UpperCamelCase_ ) ) lowerCAmelCase : Any = torch.mean(torch.abs(UpperCamelCase_ ) ) if torch_device in ["cpu", "mps"]: assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 def lowerCamelCase__ ( self : Optional[int] ): if torch_device == "mps": return lowerCAmelCase : Union[str, Any] = self.scheduler_classes[0] lowerCAmelCase : Tuple = self.get_scheduler_config() lowerCAmelCase : List[Any] = scheduler_class(**UpperCamelCase_ ) scheduler.set_timesteps(self.num_inference_steps , device=UpperCamelCase_ ) lowerCAmelCase : Optional[int] = self.dummy_model() lowerCAmelCase : str = self.dummy_sample_deter.to(UpperCamelCase_ ) * scheduler.init_noise_sigma for t in scheduler.timesteps: lowerCAmelCase : List[Any] = scheduler.scale_model_input(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : str = model(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = scheduler.step(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : Union[str, Any] = output.prev_sample lowerCAmelCase : List[Any] = torch.sum(torch.abs(UpperCamelCase_ ) ) lowerCAmelCase : Dict = torch.mean(torch.abs(UpperCamelCase_ ) ) if str(UpperCamelCase_ ).startswith('''cpu''' ): # The following sum varies between 148 and 156 on mps. Why? assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3 else: # CUDA assert abs(result_sum.item() - 20.4_125 ) < 1E-2 assert abs(result_mean.item() - 0.0_266 ) < 1E-3
637
"""simple docstring""" import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class snake_case_: def __init__( self : int , UpperCamelCase_ : List[Any] , UpperCamelCase_ : Dict=1_3 , UpperCamelCase_ : Optional[Any]=7 , UpperCamelCase_ : Optional[int]=True , UpperCamelCase_ : Dict=True , UpperCamelCase_ : Optional[int]=False , UpperCamelCase_ : Any=True , UpperCamelCase_ : List[str]=9_9 , UpperCamelCase_ : Tuple=3_2 , UpperCamelCase_ : Optional[Any]=5 , UpperCamelCase_ : str=4 , UpperCamelCase_ : Any=3_7 , UpperCamelCase_ : Optional[Any]="gelu" , UpperCamelCase_ : Tuple=0.1 , UpperCamelCase_ : Union[str, Any]=0.1 , UpperCamelCase_ : Union[str, Any]=5_1_2 , UpperCamelCase_ : Union[str, Any]=1_6 , UpperCamelCase_ : Any=2 , UpperCamelCase_ : Optional[Any]=0.02 , UpperCamelCase_ : List[Any]=3 , UpperCamelCase_ : Any=4 , UpperCamelCase_ : int=None , ): lowerCAmelCase : Any = parent lowerCAmelCase : Any = batch_size lowerCAmelCase : List[Any] = seq_length lowerCAmelCase : str = is_training lowerCAmelCase : List[Any] = use_input_mask lowerCAmelCase : Optional[int] = use_token_type_ids lowerCAmelCase : Union[str, Any] = use_labels lowerCAmelCase : List[str] = vocab_size lowerCAmelCase : Tuple = hidden_size lowerCAmelCase : int = num_hidden_layers lowerCAmelCase : Union[str, Any] = num_attention_heads lowerCAmelCase : Optional[int] = intermediate_size lowerCAmelCase : List[Any] = hidden_act lowerCAmelCase : int = hidden_dropout_prob lowerCAmelCase : Tuple = attention_probs_dropout_prob lowerCAmelCase : Optional[Any] = max_position_embeddings lowerCAmelCase : Optional[int] = type_vocab_size lowerCAmelCase : Tuple = type_sequence_label_size lowerCAmelCase : List[str] = initializer_range lowerCAmelCase : str = num_labels lowerCAmelCase : Optional[int] = num_choices lowerCAmelCase : Tuple = scope def lowerCamelCase__ ( self : Optional[int] ): lowerCAmelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase : Tuple = None if self.use_input_mask: lowerCAmelCase : str = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase : List[str] = None if self.use_token_type_ids: lowerCAmelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase : int = None lowerCAmelCase : int = None lowerCAmelCase : Tuple = None if self.use_labels: lowerCAmelCase : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCAmelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCAmelCase : Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices ) lowerCAmelCase : Optional[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCamelCase__ ( self : Tuple ): return LlamaConfig( 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=UpperCamelCase_ , initializer_range=self.initializer_range , ) def lowerCamelCase__ ( self : int , UpperCamelCase_ : Any , UpperCamelCase_ : Dict , UpperCamelCase_ : Any , UpperCamelCase_ : Dict , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : List[str] , UpperCamelCase_ : Tuple ): lowerCAmelCase : List[Any] = LlamaModel(config=UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowerCAmelCase : Dict = model(UpperCamelCase_ , attention_mask=UpperCamelCase_ ) lowerCAmelCase : Optional[int] = model(UpperCamelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase__ ( self : Any , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Tuple , UpperCamelCase_ : Tuple , UpperCamelCase_ : Dict , UpperCamelCase_ : int , UpperCamelCase_ : Dict , UpperCamelCase_ : Tuple , UpperCamelCase_ : int , UpperCamelCase_ : Any , ): lowerCAmelCase : Tuple = True lowerCAmelCase : Optional[int] = LlamaModel(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowerCAmelCase : List[Any] = model( UpperCamelCase_ , attention_mask=UpperCamelCase_ , encoder_hidden_states=UpperCamelCase_ , encoder_attention_mask=UpperCamelCase_ , ) lowerCAmelCase : Dict = model( UpperCamelCase_ , attention_mask=UpperCamelCase_ , encoder_hidden_states=UpperCamelCase_ , ) lowerCAmelCase : Tuple = model(UpperCamelCase_ , attention_mask=UpperCamelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase__ ( self : Any , UpperCamelCase_ : int , UpperCamelCase_ : Tuple , UpperCamelCase_ : Any , UpperCamelCase_ : List[Any] , UpperCamelCase_ : str , UpperCamelCase_ : int , UpperCamelCase_ : int , UpperCamelCase_ : int , UpperCamelCase_ : str , ): lowerCAmelCase : Optional[Any] = LlamaForCausalLM(config=UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowerCAmelCase : List[str] = model(UpperCamelCase_ , attention_mask=UpperCamelCase_ , labels=UpperCamelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCamelCase__ ( self : str , UpperCamelCase_ : List[str] , UpperCamelCase_ : int , UpperCamelCase_ : Tuple , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : int , UpperCamelCase_ : str , UpperCamelCase_ : Dict , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : List[Any] , ): lowerCAmelCase : Union[str, Any] = True lowerCAmelCase : str = True lowerCAmelCase : Tuple = LlamaForCausalLM(config=UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() # first forward pass lowerCAmelCase : Optional[Any] = model( UpperCamelCase_ , attention_mask=UpperCamelCase_ , encoder_hidden_states=UpperCamelCase_ , encoder_attention_mask=UpperCamelCase_ , use_cache=UpperCamelCase_ , ) lowerCAmelCase : Dict = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids lowerCAmelCase : Any = ids_tensor((self.batch_size, 3) , config.vocab_size ) lowerCAmelCase : Dict = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and lowerCAmelCase : Optional[Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) lowerCAmelCase : List[str] = torch.cat([input_mask, next_mask] , dim=-1 ) lowerCAmelCase : Dict = model( UpperCamelCase_ , attention_mask=UpperCamelCase_ , encoder_hidden_states=UpperCamelCase_ , encoder_attention_mask=UpperCamelCase_ , output_hidden_states=UpperCamelCase_ , )['''hidden_states'''][0] lowerCAmelCase : str = model( UpperCamelCase_ , attention_mask=UpperCamelCase_ , encoder_hidden_states=UpperCamelCase_ , encoder_attention_mask=UpperCamelCase_ , past_key_values=UpperCamelCase_ , output_hidden_states=UpperCamelCase_ , )['''hidden_states'''][0] # select random slice lowerCAmelCase : Tuple = ids_tensor((1,) , output_from_past.shape[-1] ).item() lowerCAmelCase : Any = output_from_no_past[:, -3:, random_slice_idx].detach() lowerCAmelCase : Optional[int] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCamelCase_ , UpperCamelCase_ , atol=1E-3 ) ) def lowerCamelCase__ ( self : Union[str, Any] ): lowerCAmelCase : Dict = self.prepare_config_and_inputs() ( ( lowerCAmelCase ), ( lowerCAmelCase ), ( lowerCAmelCase ), ( lowerCAmelCase ), ( lowerCAmelCase ), ( lowerCAmelCase ), ( lowerCAmelCase ), ) : Tuple = config_and_inputs lowerCAmelCase : Optional[int] = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class snake_case_( a__ , a__ , a__ , unittest.TestCase ): __UpperCamelCase = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () __UpperCamelCase = (LlamaForCausalLM,) if is_torch_available() else () __UpperCamelCase = ( { '''feature-extraction''': LlamaModel, '''text-classification''': LlamaForSequenceClassification, '''text-generation''': LlamaForCausalLM, '''zero-shot''': LlamaForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False def lowerCamelCase__ ( self : Optional[Any] ): lowerCAmelCase : Any = LlamaModelTester(self ) lowerCAmelCase : Dict = ConfigTester(self , config_class=UpperCamelCase_ , hidden_size=3_7 ) def lowerCamelCase__ ( self : str ): self.config_tester.run_common_tests() def lowerCamelCase__ ( self : Tuple ): lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase_ ) def lowerCamelCase__ ( self : List[Any] ): lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: lowerCAmelCase : str = type self.model_tester.create_and_check_model(*UpperCamelCase_ ) def lowerCamelCase__ ( self : List[Any] ): lowerCAmelCase, lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase : List[str] = 3 lowerCAmelCase : List[str] = input_dict['''input_ids'''] lowerCAmelCase : List[str] = input_ids.ne(1 ).to(UpperCamelCase_ ) lowerCAmelCase : Tuple = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) lowerCAmelCase : Union[str, Any] = LlamaForSequenceClassification(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowerCAmelCase : List[Any] = model(UpperCamelCase_ , attention_mask=UpperCamelCase_ , labels=UpperCamelCase_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def lowerCamelCase__ ( self : Optional[int] ): lowerCAmelCase, lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase : Any = 3 lowerCAmelCase : int = '''single_label_classification''' lowerCAmelCase : Tuple = input_dict['''input_ids'''] lowerCAmelCase : Tuple = input_ids.ne(1 ).to(UpperCamelCase_ ) lowerCAmelCase : str = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) lowerCAmelCase : Tuple = LlamaForSequenceClassification(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowerCAmelCase : Any = model(UpperCamelCase_ , attention_mask=UpperCamelCase_ , labels=UpperCamelCase_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def lowerCamelCase__ ( self : Union[str, Any] ): lowerCAmelCase, lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase : Any = 3 lowerCAmelCase : Dict = '''multi_label_classification''' lowerCAmelCase : Union[str, Any] = input_dict['''input_ids'''] lowerCAmelCase : Tuple = input_ids.ne(1 ).to(UpperCamelCase_ ) lowerCAmelCase : Any = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) lowerCAmelCase : Optional[int] = LlamaForSequenceClassification(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowerCAmelCase : Optional[Any] = model(UpperCamelCase_ , attention_mask=UpperCamelCase_ , labels=UpperCamelCase_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('''LLaMA buffers include complex numbers, which breaks this test''' ) def lowerCamelCase__ ( self : Optional[Any] ): pass @parameterized.expand([('''linear''',), ('''dynamic''',)] ) def lowerCamelCase__ ( self : List[str] , UpperCamelCase_ : Tuple ): lowerCAmelCase, lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase : Optional[int] = ids_tensor([1, 1_0] , config.vocab_size ) lowerCAmelCase : int = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(4_2 ) # Fixed seed at init time so the two models get the same random weights lowerCAmelCase : List[Any] = LlamaModel(UpperCamelCase_ ) original_model.to(UpperCamelCase_ ) original_model.eval() lowerCAmelCase : Optional[int] = original_model(UpperCamelCase_ ).last_hidden_state lowerCAmelCase : List[Any] = original_model(UpperCamelCase_ ).last_hidden_state set_seed(4_2 ) # Fixed seed at init time so the two models get the same random weights lowerCAmelCase : int = {'''type''': scaling_type, '''factor''': 10.0} lowerCAmelCase : List[str] = LlamaModel(UpperCamelCase_ ) scaled_model.to(UpperCamelCase_ ) scaled_model.eval() lowerCAmelCase : Union[str, Any] = scaled_model(UpperCamelCase_ ).last_hidden_state lowerCAmelCase : Optional[int] = scaled_model(UpperCamelCase_ ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(UpperCamelCase_ , UpperCamelCase_ , atol=1E-5 ) ) else: self.assertFalse(torch.allclose(UpperCamelCase_ , UpperCamelCase_ , atol=1E-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(UpperCamelCase_ , UpperCamelCase_ , atol=1E-5 ) ) @require_torch class snake_case_( unittest.TestCase ): @unittest.skip('''Logits are not exactly the same, once we fix the instabalities somehow, will update!''' ) @slow def lowerCamelCase__ ( self : List[Any] ): lowerCAmelCase : Tuple = [1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8] lowerCAmelCase : Optional[Any] = LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-7b-hf''' , device_map='''auto''' ) lowerCAmelCase : str = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 lowerCAmelCase : int = torch.tensor([[-6.6_550, -4.1_227, -4.9_859, -3.2_406, 0.8_262, -3.0_033, 1.2_964, -3.3_699]] ) torch.testing.assert_close(out.mean(-1 ) , UpperCamelCase_ , atol=1E-2 , rtol=1E-2 ) # slicing logits[0, 0, 0:30] # fmt: off lowerCAmelCase : Tuple = torch.tensor([-12.8_281, -7.4_453, -0.4_639, -8.0_625, -7.2_500, -8.0_000, -6.4_883, -7.7_695, -7.8_438, -7.0_312, -6.2_188, -7.1_328, -1.8_496, 1.9_961, -8.6_250, -6.7_227, -12.8_281, -6.9_492, -7.0_742, -7.7_852, -7.5_820, -7.9_062, -6.9_375, -7.9_805, -8.3_438, -8.1_562, -8.0_469, -7.6_250, -7.7_422, -7.3_398,] ) # fmt: on torch.testing.assert_close(out[0, 0, :3_0] , UpperCamelCase_ , atol=1E-5 , rtol=1E-5 ) @unittest.skip('''Logits are not exactly the same, once we fix the instabalities somehow, will update!''' ) @slow def lowerCamelCase__ ( self : Dict ): lowerCAmelCase : str = [1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8] lowerCAmelCase : Dict = LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-13b-hf''' , device_map='''auto''' ) lowerCAmelCase : str = model(torch.tensor(UpperCamelCase_ ) ) # Expected mean on dim = -1 lowerCAmelCase : Any = torch.tensor([[-2.0_622, -1.2_794, -1.1_638, -0.9_788, -1.4_603, -1.0_238, -1.7_893, -1.4_411]] ) torch.testing.assert_close(out.mean(-1 ) , UpperCamelCase_ , atol=1E-2 , rtol=1E-2 ) # slicing logits[0, 0, 0:30] # fmt: off lowerCAmelCase : Tuple = torch.tensor([-8.1_406, -8.0_547, 2.7_461, -1.2_344, -0.1_448, -1.8_262, -1.0_020, -1.8_154, -1.6_895, -1.8_516, -2.3_574, -0.9_277, 3.7_598, 6.5_742, -1.2_998, -0.1_177, -8.1_406, -2.9_688, -2.9_199, -3.1_699, -3.5_254, -2.3_555, -2.7_988, -3.4_141, -2.8_262, -4.5_195, -3.3_379, -3.3_164, -2.7_832, -3.0_273] ) # fmt: on torch.testing.assert_close(out[0, 0, :3_0] , UpperCamelCase_ , atol=1E-5 , rtol=1E-5 ) @unittest.skip('''Logits are not exactly the same, once we fix the instabalities somehow, will update!''' ) @slow def lowerCamelCase__ ( self : Optional[int] ): lowerCAmelCase : int = [1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8] lowerCAmelCase : List[str] = LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-13b-chat-hf''' , device_map='''auto''' ) lowerCAmelCase : List[Any] = model(torch.tensor(UpperCamelCase_ ) ) # Expected mean on dim = -1 lowerCAmelCase : List[str] = torch.tensor([[-0.8_562, -1.8_520, -0.7_551, -0.4_162, -1.5_161, -1.2_038, -2.4_823, -2.3_254]] ) torch.testing.assert_close(out.mean(-1 ) , UpperCamelCase_ , atol=1E-2 , rtol=1E-2 ) # slicing logits[0, 0, 0:30] # fmt: off lowerCAmelCase : Dict = torch.tensor([-2.2_227, 4.8_828, 0.9_023, -0.4_578, -0.7_871, -0.1_033, -0.6_221, -0.5_786, -0.7_803, -1.0_674, -1.2_920, -0.1_570, 0.8_008, 2.0_723, -0.9_497, 0.2_771, -2.2_227, -0.7_612, -1.4_346, -1.2_061, -1.6_426, -0.3_000, -0.7_139, -1.1_934, -1.8_691, -1.6_973, -1.5_947, -1.2_705, -0.3_523, -0.5_513] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) , UpperCamelCase_ , atol=1E-2 , rtol=1E-2 ) @unittest.skip( '''Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test''' ) @slow def lowerCamelCase__ ( self : List[str] ): lowerCAmelCase : Optional[Any] = [1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8] lowerCAmelCase : Optional[int] = LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-70b-hf''' , device_map='''auto''' ) lowerCAmelCase : Any = model(torch.tensor(UpperCamelCase_ ) ) lowerCAmelCase : Optional[Any] = torch.tensor( [[-4.2_327, -3.3_360, -4.6_665, -4.7_631, -1.8_180, -3.4_170, -1.4_211, -3.1_810]] , dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) , UpperCamelCase_ , atol=1E-2 , rtol=1E-2 ) # fmt: off lowerCAmelCase : Any = torch.tensor([-9.4_922, -3.9_551, 1.7_998, -5.6_758, -5.1_055, -5.8_984, -4.8_320, -6.8_086, -6.5_391, -5.6_172, -5.5_820, -5.5_352, 1.7_881, 3.6_289, -6.5_117, -3.4_785, -9.5_000, -6.0_352, -6.8_125, -6.0_195, -6.6_836, -5.4_727, -6.2_812, -6.0_391, -7.3_398, -7.4_297, -7.4_844, -6.5_820, -5.8_789, -5.5_312] ) # fmt: on torch.testing.assert_close(out[0, 0, :3_0] , UpperCamelCase_ , atol=1E-5 , rtol=1E-5 ) @unittest.skip('''Model is curently gated''' ) @slow def lowerCamelCase__ ( self : List[Any] ): lowerCAmelCase : List[Any] = '''Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi''' lowerCAmelCase : int = '''Simply put, the theory of relativity states that ''' lowerCAmelCase : str = LlamaTokenizer.from_pretrained('''meta-llama/Llama-2-13b-chat-hf''' ) lowerCAmelCase : Optional[int] = tokenizer.encode(UpperCamelCase_ , return_tensors='''pt''' ) lowerCAmelCase : List[Any] = LlamaForCausalLM.from_pretrained( '''meta-llama/Llama-2-13b-chat-hf''' , device_map='''sequential''' , use_safetensors=UpperCamelCase_ ) # greedy generation outputs lowerCAmelCase : int = model.generate(UpperCamelCase_ , max_new_tokens=6_4 , top_p=UpperCamelCase_ , temperature=1 , do_sample=UpperCamelCase_ ) lowerCAmelCase : int = tokenizer.decode(generated_ids[0] , skip_special_tokens=UpperCamelCase_ ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ )
637
1
"""simple docstring""" import json import os from functools import lru_cache from typing import Dict, List, Optional, Tuple, Union import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding, EncodedInput from ...utils import PaddingStrategy, logging snake_case__ : Optional[Any] = logging.get_logger(__name__) snake_case__ : Any = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt'''} # See all LED models at https://huggingface.co/models?filter=LED snake_case__ : Optional[Any] = { '''vocab_file''': { '''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json''', }, '''merges_file''': { '''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json''', }, } snake_case__ : List[Any] = { '''allenai/led-base-16384''': 16_384, } @lru_cache() # Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode def _snake_case ( ): lowerCAmelCase : Optional[int] = ( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) lowerCAmelCase : str = bs[:] lowerCAmelCase : Optional[int] = 0 for b in range(2**8 ): if b not in bs: bs.append(_snake_case ) cs.append(2**8 + n ) n += 1 lowerCAmelCase : int = [chr(_snake_case ) for n in cs] return dict(zip(_snake_case , _snake_case ) ) def _snake_case ( _snake_case : List[Any] ): lowerCAmelCase : List[str] = set() lowerCAmelCase : Any = word[0] for char in word[1:]: pairs.add((prev_char, char) ) lowerCAmelCase : Optional[Any] = char return pairs class snake_case_( a__ ): __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ['''input_ids''', '''attention_mask'''] def __init__( self : Tuple , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Dict , UpperCamelCase_ : Tuple="replace" , UpperCamelCase_ : Union[str, Any]="<s>" , UpperCamelCase_ : List[str]="</s>" , UpperCamelCase_ : str="</s>" , UpperCamelCase_ : int="<s>" , UpperCamelCase_ : int="<unk>" , UpperCamelCase_ : Union[str, Any]="<pad>" , UpperCamelCase_ : Tuple="<mask>" , UpperCamelCase_ : Optional[int]=False , **UpperCamelCase_ : Tuple , ): lowerCAmelCase : Any = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else bos_token lowerCAmelCase : Union[str, Any] = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else eos_token lowerCAmelCase : Optional[int] = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else sep_token lowerCAmelCase : int = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else cls_token lowerCAmelCase : Tuple = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else unk_token lowerCAmelCase : List[Any] = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it lowerCAmelCase : Tuple = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else mask_token super().__init__( errors=UpperCamelCase_ , bos_token=UpperCamelCase_ , eos_token=UpperCamelCase_ , unk_token=UpperCamelCase_ , sep_token=UpperCamelCase_ , cls_token=UpperCamelCase_ , pad_token=UpperCamelCase_ , mask_token=UpperCamelCase_ , add_prefix_space=UpperCamelCase_ , **UpperCamelCase_ , ) with open(UpperCamelCase_ , encoding='''utf-8''' ) as vocab_handle: lowerCAmelCase : Any = json.load(UpperCamelCase_ ) lowerCAmelCase : Dict = {v: k for k, v in self.encoder.items()} lowerCAmelCase : Optional[int] = errors # how to handle errors in decoding lowerCAmelCase : List[Any] = bytes_to_unicode() lowerCAmelCase : Optional[Any] = {v: k for k, v in self.byte_encoder.items()} with open(UpperCamelCase_ , encoding='''utf-8''' ) as merges_handle: lowerCAmelCase : Optional[int] = merges_handle.read().split('''\n''' )[1:-1] lowerCAmelCase : Optional[int] = [tuple(merge.split() ) for merge in bpe_merges] lowerCAmelCase : Optional[int] = dict(zip(UpperCamelCase_ , range(len(UpperCamelCase_ ) ) ) ) lowerCAmelCase : List[Any] = {} lowerCAmelCase : Optional[Any] = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions lowerCAmelCase : Dict = re.compile(r'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' ) @property # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size def lowerCamelCase__ ( self : Union[str, Any] ): return len(self.encoder ) def lowerCamelCase__ ( self : Union[str, Any] ): return dict(self.encoder , **self.added_tokens_encoder ) def lowerCamelCase__ ( self : Any , UpperCamelCase_ : int ): if token in self.cache: return self.cache[token] lowerCAmelCase : List[str] = tuple(UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = get_pairs(UpperCamelCase_ ) if not pairs: return token while True: lowerCAmelCase : List[Any] = min(UpperCamelCase_ , key=lambda UpperCamelCase_ : self.bpe_ranks.get(UpperCamelCase_ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break lowerCAmelCase, lowerCAmelCase : Any = bigram lowerCAmelCase : Tuple = [] lowerCAmelCase : Any = 0 while i < len(UpperCamelCase_ ): try: lowerCAmelCase : int = word.index(UpperCamelCase_ , UpperCamelCase_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) lowerCAmelCase : int = j if word[i] == first and i < len(UpperCamelCase_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 lowerCAmelCase : Tuple = tuple(UpperCamelCase_ ) lowerCAmelCase : Tuple = new_word if len(UpperCamelCase_ ) == 1: break else: lowerCAmelCase : Optional[Any] = get_pairs(UpperCamelCase_ ) lowerCAmelCase : Union[str, Any] = ''' '''.join(UpperCamelCase_ ) lowerCAmelCase : List[str] = word return word def lowerCamelCase__ ( self : Optional[Any] , UpperCamelCase_ : Tuple ): lowerCAmelCase : Dict = [] for token in re.findall(self.pat , UpperCamelCase_ ): lowerCAmelCase : Union[str, Any] = ''''''.join( self.byte_encoder[b] for b in token.encode('''utf-8''' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(UpperCamelCase_ ).split(''' ''' ) ) return bpe_tokens def lowerCamelCase__ ( self : int , UpperCamelCase_ : str ): return self.encoder.get(UpperCamelCase_ , self.encoder.get(self.unk_token ) ) def lowerCamelCase__ ( self : Any , UpperCamelCase_ : Union[str, Any] ): return self.decoder.get(UpperCamelCase_ ) def lowerCamelCase__ ( self : Any , UpperCamelCase_ : List[str] ): lowerCAmelCase : Optional[int] = ''''''.join(UpperCamelCase_ ) lowerCAmelCase : Optional[int] = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''' , errors=self.errors ) return text def lowerCamelCase__ ( self : str , UpperCamelCase_ : str , UpperCamelCase_ : Optional[str] = None ): if not os.path.isdir(UpperCamelCase_ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowerCAmelCase : int = os.path.join( UpperCamelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) lowerCAmelCase : Optional[Any] = os.path.join( UpperCamelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(UpperCamelCase_ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=UpperCamelCase_ , ensure_ascii=UpperCamelCase_ ) + '''\n''' ) lowerCAmelCase : Optional[int] = 0 with open(UpperCamelCase_ , '''w''' , encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda UpperCamelCase_ : kv[1] ): if index != token_index: logger.warning( F'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' ''' Please check that the tokenizer is not corrupted!''' ) lowerCAmelCase : Tuple = token_index writer.write(''' '''.join(UpperCamelCase_ ) + '''\n''' ) index += 1 return vocab_file, merge_file def lowerCamelCase__ ( self : Optional[Any] , UpperCamelCase_ : List[int] , UpperCamelCase_ : Optional[List[int]] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCAmelCase : Any = [self.cls_token_id] lowerCAmelCase : str = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowerCamelCase__ ( self : Any , UpperCamelCase_ : List[int] , UpperCamelCase_ : Optional[List[int]] = None , UpperCamelCase_ : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCamelCase_ , token_ids_a=UpperCamelCase_ , already_has_special_tokens=UpperCamelCase_ ) if token_ids_a is None: return [1] + ([0] * len(UpperCamelCase_ )) + [1] return [1] + ([0] * len(UpperCamelCase_ )) + [1, 1] + ([0] * len(UpperCamelCase_ )) + [1] def lowerCamelCase__ ( self : List[str] , UpperCamelCase_ : List[int] , UpperCamelCase_ : Optional[List[int]] = None ): lowerCAmelCase : Optional[Any] = [self.sep_token_id] lowerCAmelCase : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def lowerCamelCase__ ( self : int , UpperCamelCase_ : Any , UpperCamelCase_ : Dict=False , **UpperCamelCase_ : Tuple ): lowerCAmelCase : Union[str, Any] = kwargs.pop('''add_prefix_space''' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(UpperCamelCase_ ) > 0 and not text[0].isspace()): lowerCAmelCase : List[Any] = ''' ''' + text return (text, kwargs) def lowerCamelCase__ ( self : str , UpperCamelCase_ : Union[Dict[str, EncodedInput], BatchEncoding] , UpperCamelCase_ : Optional[int] = None , UpperCamelCase_ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , UpperCamelCase_ : Optional[int] = None , UpperCamelCase_ : Optional[bool] = None , ): lowerCAmelCase : Dict = super()._pad( encoded_inputs=UpperCamelCase_ , max_length=UpperCamelCase_ , padding_strategy=UpperCamelCase_ , pad_to_multiple_of=UpperCamelCase_ , return_attention_mask=UpperCamelCase_ , ) # Load from model defaults if return_attention_mask is None: lowerCAmelCase : Tuple = '''attention_mask''' in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: lowerCAmelCase : Dict = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. lowerCAmelCase : List[Any] = len(encoded_inputs['''global_attention_mask'''] ) != len(UpperCamelCase_ ) if needs_to_be_padded: lowerCAmelCase : int = len(UpperCamelCase_ ) - len(encoded_inputs['''global_attention_mask'''] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` lowerCAmelCase : Dict = ( encoded_inputs['''global_attention_mask'''] + [-1] * difference ) elif self.padding_side == "left": lowerCAmelCase : int = [-1] * difference + encoded_inputs[ '''global_attention_mask''' ] else: raise ValueError('''Invalid padding strategy:''' + str(self.padding_side ) ) return encoded_inputs
637
"""simple docstring""" import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def _snake_case ( _snake_case : Tuple , _snake_case : Union[str, Any]=10 ): lowerCAmelCase : Dict = [] for _ in range(_snake_case ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def _snake_case ( _snake_case : Optional[int] , _snake_case : int=10 ): lowerCAmelCase : Optional[int] = [] for step in range(_snake_case ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: lowerCAmelCase : List[str] = os.path.join(_snake_case , '''schedule.bin''' ) torch.save(scheduler.state_dict() , _snake_case ) lowerCAmelCase : List[Any] = torch.load(_snake_case ) scheduler.load_state_dict(_snake_case ) return lrs @require_torch class snake_case_( unittest.TestCase ): def lowerCamelCase__ ( self : Optional[int] , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : str , UpperCamelCase_ : Any ): self.assertEqual(len(UpperCamelCase_ ) , len(UpperCamelCase_ ) ) for a, b in zip(UpperCamelCase_ , UpperCamelCase_ ): self.assertAlmostEqual(UpperCamelCase_ , UpperCamelCase_ , delta=UpperCamelCase_ ) def lowerCamelCase__ ( self : Tuple ): lowerCAmelCase : Any = torch.tensor([0.1, -0.2, -0.1] , requires_grad=UpperCamelCase_ ) lowerCAmelCase : List[str] = torch.tensor([0.4, 0.2, -0.5] ) lowerCAmelCase : List[Any] = nn.MSELoss() # No warmup, constant schedule, no gradient clipping lowerCAmelCase : Union[str, Any] = AdamW(params=[w] , lr=2E-1 , weight_decay=0.0 ) for _ in range(1_0_0 ): lowerCAmelCase : Union[str, Any] = criterion(UpperCamelCase_ , UpperCamelCase_ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1E-2 ) def lowerCamelCase__ ( self : Union[str, Any] ): lowerCAmelCase : Tuple = torch.tensor([0.1, -0.2, -0.1] , requires_grad=UpperCamelCase_ ) lowerCAmelCase : Union[str, Any] = torch.tensor([0.4, 0.2, -0.5] ) lowerCAmelCase : Optional[int] = nn.MSELoss() # No warmup, constant schedule, no gradient clipping lowerCAmelCase : Any = Adafactor( params=[w] , lr=1E-2 , eps=(1E-30, 1E-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=UpperCamelCase_ , weight_decay=0.0 , relative_step=UpperCamelCase_ , scale_parameter=UpperCamelCase_ , warmup_init=UpperCamelCase_ , ) for _ in range(1_0_0_0 ): lowerCAmelCase : List[Any] = criterion(UpperCamelCase_ , UpperCamelCase_ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1E-2 ) @require_torch class snake_case_( unittest.TestCase ): __UpperCamelCase = nn.Linear(50 , 50 ) if is_torch_available() else None __UpperCamelCase = AdamW(m.parameters() , lr=10.0 ) if is_torch_available() else None __UpperCamelCase = 10 def lowerCamelCase__ ( self : Union[str, Any] , UpperCamelCase_ : str , UpperCamelCase_ : str , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Union[str, Any]=None ): self.assertEqual(len(UpperCamelCase_ ) , len(UpperCamelCase_ ) ) for a, b in zip(UpperCamelCase_ , UpperCamelCase_ ): self.assertAlmostEqual(UpperCamelCase_ , UpperCamelCase_ , delta=UpperCamelCase_ , msg=UpperCamelCase_ ) def lowerCamelCase__ ( self : Union[str, Any] ): lowerCAmelCase : Tuple = {'''num_warmup_steps''': 2, '''num_training_steps''': 1_0} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) lowerCAmelCase : Optional[Any] = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {'''num_warmup_steps''': 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, '''num_cycles''': 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, '''power''': 2.0, '''lr_end''': 1E-7}, [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156], ), get_inverse_sqrt_schedule: ( {'''num_warmup_steps''': 2}, [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714], ), } for scheduler_func, data in scheds.items(): lowerCAmelCase, lowerCAmelCase : Union[str, Any] = data lowerCAmelCase : List[Any] = scheduler_func(self.optimizer , **UpperCamelCase_ ) self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 ) lowerCAmelCase : str = unwrap_schedule(UpperCamelCase_ , self.num_steps ) self.assertListAlmostEqual( UpperCamelCase_ , UpperCamelCase_ , tol=1E-2 , msg=F'''failed for {scheduler_func} in normal scheduler''' , ) lowerCAmelCase : Optional[int] = scheduler_func(self.optimizer , **UpperCamelCase_ ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(UpperCamelCase_ ) # wrap to test picklability of the schedule lowerCAmelCase : List[Any] = unwrap_and_save_reload_schedule(UpperCamelCase_ , self.num_steps ) self.assertListEqual(UpperCamelCase_ , UpperCamelCase_ , msg=F'''failed for {scheduler_func} in save and reload''' ) class snake_case_: def __init__( self : List[Any] , UpperCamelCase_ : Any ): lowerCAmelCase : Tuple = fn def __call__( self : Union[str, Any] , *UpperCamelCase_ : Optional[Any] , **UpperCamelCase_ : List[Any] ): return self.fn(*UpperCamelCase_ , **UpperCamelCase_ ) @classmethod def lowerCamelCase__ ( self : Any , UpperCamelCase_ : Optional[int] ): lowerCAmelCase : Union[str, Any] = list(map(self , scheduler.lr_lambdas ) )
637
1
"""simple docstring""" import json import os import subprocess import unittest from ast import literal_eval import pytest from parameterized import parameterized_class from . import is_sagemaker_available if is_sagemaker_available(): from sagemaker import Session, TrainingJobAnalytics from sagemaker.huggingface import HuggingFace @pytest.mark.skipif( literal_eval(os.getenv('''TEST_SAGEMAKER''' , '''False''' ) ) is not True , reason='''Skipping test because should only be run when releasing minor transformers version''' , ) @pytest.mark.usefixtures('''sm_env''' ) @parameterized_class( [ { '''framework''': '''pytorch''', '''script''': '''run_glue.py''', '''model_name_or_path''': '''distilbert-base-cased''', '''instance_type''': '''ml.g4dn.xlarge''', '''results''': {'''train_runtime''': 650, '''eval_accuracy''': 0.6, '''eval_loss''': 0.9}, }, { '''framework''': '''tensorflow''', '''script''': '''run_tf.py''', '''model_name_or_path''': '''distilbert-base-cased''', '''instance_type''': '''ml.g4dn.xlarge''', '''results''': {'''train_runtime''': 600, '''eval_accuracy''': 0.3, '''eval_loss''': 0.9}, }, ] ) class snake_case_( unittest.TestCase ): def lowerCamelCase__ ( self : List[str] ): if self.framework == "pytorch": subprocess.run( F'''cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py'''.split() , encoding='''utf-8''' , check=UpperCamelCase_ , ) assert hasattr(self , '''env''' ) def lowerCamelCase__ ( self : Optional[int] , UpperCamelCase_ : Dict=1 ): # creates estimator return HuggingFace( entry_point=self.script , source_dir=self.env.test_path , role=self.env.role , image_uri=self.env.image_uri , base_job_name=F'''{self.env.base_job_name}-single''' , instance_count=UpperCamelCase_ , instance_type=self.instance_type , debugger_hook_config=UpperCamelCase_ , hyperparameters={**self.env.hyperparameters, '''model_name_or_path''': self.model_name_or_path} , metric_definitions=self.env.metric_definitions , py_version='''py36''' , ) def lowerCamelCase__ ( self : List[Any] , UpperCamelCase_ : List[str] ): TrainingJobAnalytics(UpperCamelCase_ ).export_csv(F'''{self.env.test_path}/{job_name}_metrics.csv''' ) def lowerCamelCase__ ( self : List[Any] ): # create estimator lowerCAmelCase : int = self.create_estimator() # run training estimator.fit() # result dataframe lowerCAmelCase : int = TrainingJobAnalytics(estimator.latest_training_job.name ).dataframe() # extract kpis lowerCAmelCase : Tuple = list(result_metrics_df[result_metrics_df.metric_name == '''eval_accuracy''']['''value'''] ) lowerCAmelCase : Dict = list(result_metrics_df[result_metrics_df.metric_name == '''eval_loss''']['''value'''] ) # get train time from SageMaker job, this includes starting, preprocessing, stopping lowerCAmelCase : Optional[int] = ( Session().describe_training_job(estimator.latest_training_job.name ).get('''TrainingTimeInSeconds''' , 9_9_9_9_9_9 ) ) # assert kpis assert train_runtime <= self.results["train_runtime"] assert all(t >= self.results['''eval_accuracy'''] for t in eval_accuracy ) assert all(t <= self.results['''eval_loss'''] for t in eval_loss ) # dump tests result into json file to share in PR with open(F'''{estimator.latest_training_job.name}.json''' , '''w''' ) as outfile: json.dump({'''train_time''': train_runtime, '''eval_accuracy''': eval_accuracy, '''eval_loss''': eval_loss} , UpperCamelCase_ )
637
"""simple docstring""" # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from ..models.auto import AutoModelForSeqaSeqLM, AutoTokenizer from .base import PipelineTool class snake_case_( a__ ): __UpperCamelCase = '''philschmid/bart-large-cnn-samsum''' __UpperCamelCase = ( '''This is a tool that summarizes an English text. It takes an input `text` containing the text to summarize, ''' '''and returns a summary of the text.''' ) __UpperCamelCase = '''summarizer''' __UpperCamelCase = AutoTokenizer __UpperCamelCase = AutoModelForSeqaSeqLM __UpperCamelCase = ['''text'''] __UpperCamelCase = ['''text'''] def lowerCamelCase__ ( self : Dict , UpperCamelCase_ : int ): return self.pre_processor(UpperCamelCase_ , return_tensors='''pt''' , truncation=UpperCamelCase_ ) def lowerCamelCase__ ( self : Optional[int] , UpperCamelCase_ : str ): return self.model.generate(**UpperCamelCase_ )[0] def lowerCamelCase__ ( self : Any , UpperCamelCase_ : Tuple ): return self.pre_processor.decode(UpperCamelCase_ , skip_special_tokens=UpperCamelCase_ , clean_up_tokenization_spaces=UpperCamelCase_ )
637
1
"""simple docstring""" import argparse import numpy as np import torch from transformers import SpeechTaHifiGan, SpeechTaHifiGanConfig, logging logging.set_verbosity_info() snake_case__ : Any = logging.get_logger('''transformers.models.speecht5''') def _snake_case ( _snake_case : Optional[Any] , _snake_case : int , _snake_case : List[Any] ): hf_model.apply_weight_norm() lowerCAmelCase : Optional[int] = checkpoint['''input_conv.weight_g'''] lowerCAmelCase : Tuple = checkpoint['''input_conv.weight_v'''] lowerCAmelCase : Tuple = checkpoint['''input_conv.bias'''] for i in range(len(config.upsample_rates ) ): lowerCAmelCase : Dict = checkpoint[f'''upsamples.{i}.1.weight_g'''] lowerCAmelCase : Any = checkpoint[f'''upsamples.{i}.1.weight_v'''] lowerCAmelCase : Dict = checkpoint[f'''upsamples.{i}.1.bias'''] for i in range(len(config.upsample_rates ) * len(config.resblock_kernel_sizes ) ): for j in range(len(config.resblock_dilation_sizes ) ): lowerCAmelCase : int = checkpoint[f'''blocks.{i}.convs1.{j}.1.weight_g'''] lowerCAmelCase : Union[str, Any] = checkpoint[f'''blocks.{i}.convs1.{j}.1.weight_v'''] lowerCAmelCase : int = checkpoint[f'''blocks.{i}.convs1.{j}.1.bias'''] lowerCAmelCase : List[Any] = checkpoint[f'''blocks.{i}.convs2.{j}.1.weight_g'''] lowerCAmelCase : Tuple = checkpoint[f'''blocks.{i}.convs2.{j}.1.weight_v'''] lowerCAmelCase : str = checkpoint[f'''blocks.{i}.convs2.{j}.1.bias'''] lowerCAmelCase : Any = checkpoint['''output_conv.1.weight_g'''] lowerCAmelCase : int = checkpoint['''output_conv.1.weight_v'''] lowerCAmelCase : List[str] = checkpoint['''output_conv.1.bias'''] hf_model.remove_weight_norm() @torch.no_grad() def _snake_case ( _snake_case : Union[str, Any] , _snake_case : Union[str, Any] , _snake_case : Dict , _snake_case : Optional[Any]=None , _snake_case : List[Any]=None , ): if config_path is not None: lowerCAmelCase : Optional[int] = SpeechTaHifiGanConfig.from_pretrained(_snake_case ) else: lowerCAmelCase : Optional[Any] = SpeechTaHifiGanConfig() lowerCAmelCase : int = SpeechTaHifiGan(_snake_case ) lowerCAmelCase : List[str] = torch.load(_snake_case ) load_weights(orig_checkpoint['''model''']['''generator'''] , _snake_case , _snake_case ) lowerCAmelCase : List[Any] = np.load(_snake_case ) lowerCAmelCase : Optional[Any] = stats[0].reshape(-1 ) lowerCAmelCase : Union[str, Any] = stats[1].reshape(-1 ) lowerCAmelCase : Union[str, Any] = torch.from_numpy(_snake_case ).float() lowerCAmelCase : List[str] = torch.from_numpy(_snake_case ).float() model.save_pretrained(_snake_case ) if repo_id: print('''Pushing to the hub...''' ) model.push_to_hub(_snake_case ) if __name__ == "__main__": snake_case__ : int = argparse.ArgumentParser() parser.add_argument('''--checkpoint_path''', required=True, default=None, type=str, help='''Path to original checkpoint''') parser.add_argument('''--stats_path''', required=True, default=None, type=str, help='''Path to stats.npy file''') parser.add_argument('''--config_path''', default=None, type=str, help='''Path to hf config.json of model to convert''') parser.add_argument( '''--pytorch_dump_folder_path''', required=True, default=None, type=str, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--push_to_hub''', default=None, type=str, help='''Where to upload the converted model on the 🤗 hub.''' ) snake_case__ : Optional[int] = parser.parse_args() convert_hifigan_checkpoint( args.checkpoint_path, args.stats_path, args.pytorch_dump_folder_path, args.config_path, args.push_to_hub, )
637
"""simple docstring""" snake_case__ : List[Any] = '''Tobias Carryer''' from time import time class snake_case_: def __init__( self : Optional[Any] , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Tuple , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : Dict=int(time() ) ): # noqa: B008 lowerCAmelCase : str = multiplier lowerCAmelCase : Optional[int] = increment lowerCAmelCase : Optional[Any] = modulo lowerCAmelCase : Optional[Any] = seed def lowerCamelCase__ ( self : Union[str, Any] ): lowerCAmelCase : Optional[int] = (self.multiplier * self.seed + self.increment) % self.modulo return self.seed if __name__ == "__main__": # Show the LCG in action. snake_case__ : int = LinearCongruentialGenerator(1_664_525, 1_013_904_223, 2 << 31) while True: print(lcg.next_number())
637
1
"""simple docstring""" import time import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers.generation import ( MaxLengthCriteria, MaxNewTokensCriteria, MaxTimeCriteria, StoppingCriteriaList, validate_stopping_criteria, ) @require_torch class snake_case_( unittest.TestCase ): def lowerCamelCase__ ( self : int , UpperCamelCase_ : int ): lowerCAmelCase : str = 3 lowerCAmelCase : Tuple = 2_5_0 lowerCAmelCase : Optional[Any] = ids_tensor((batch_size, length) , UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = torch.ones((batch_size, length) , device=UpperCamelCase_ , dtype=torch.float ) / length return input_ids, scores def lowerCamelCase__ ( self : Optional[Any] ): lowerCAmelCase, lowerCAmelCase : Optional[int] = self._get_tensors(5 ) lowerCAmelCase : Union[str, Any] = StoppingCriteriaList( [ MaxLengthCriteria(max_length=1_0 ), MaxTimeCriteria(max_time=0.1 ), ] ) self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase, lowerCAmelCase : List[str] = self._get_tensors(9 ) self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase, lowerCAmelCase : Any = self._get_tensors(1_0 ) self.assertTrue(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) def lowerCamelCase__ ( self : Optional[Any] ): lowerCAmelCase : Optional[Any] = MaxLengthCriteria(max_length=1_0 ) lowerCAmelCase, lowerCAmelCase : Optional[Any] = self._get_tensors(5 ) self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase, lowerCAmelCase : List[str] = self._get_tensors(9 ) self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase, lowerCAmelCase : str = self._get_tensors(1_0 ) self.assertTrue(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) def lowerCamelCase__ ( self : List[Any] ): lowerCAmelCase : Optional[Any] = MaxNewTokensCriteria(start_length=5 , max_new_tokens=5 ) lowerCAmelCase, lowerCAmelCase : Optional[int] = self._get_tensors(5 ) self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase, lowerCAmelCase : Union[str, Any] = self._get_tensors(9 ) self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase, lowerCAmelCase : str = self._get_tensors(1_0 ) self.assertTrue(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase : Dict = StoppingCriteriaList([criteria] ) self.assertEqual(criteria_list.max_length , 1_0 ) def lowerCamelCase__ ( self : Union[str, Any] ): lowerCAmelCase, lowerCAmelCase : Tuple = self._get_tensors(5 ) lowerCAmelCase : List[str] = MaxTimeCriteria(max_time=0.1 ) self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase : List[str] = MaxTimeCriteria(max_time=0.1 , initial_timestamp=time.time() - 0.2 ) self.assertTrue(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) def lowerCamelCase__ ( self : str ): validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(1_0 )] ) , 1_0 ) with self.assertWarns(UpperCamelCase_ ): validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(1_0 )] ) , 1_1 ) lowerCAmelCase : str = validate_stopping_criteria(StoppingCriteriaList() , 1_1 ) self.assertEqual(len(UpperCamelCase_ ) , 1 )
637
"""simple docstring""" import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_big_bird import BigBirdTokenizer else: snake_case__ : Optional[Any] = None snake_case__ : Union[str, Any] = logging.get_logger(__name__) snake_case__ : List[str] = {'''vocab_file''': '''spiece.model''', '''tokenizer_file''': '''tokenizer.json'''} snake_case__ : Any = { '''vocab_file''': { '''google/bigbird-roberta-base''': '''https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model''', '''google/bigbird-roberta-large''': ( '''https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model''' ), '''google/bigbird-base-trivia-itc''': ( '''https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model''' ), }, '''tokenizer_file''': { '''google/bigbird-roberta-base''': ( '''https://huggingface.co/google/bigbird-roberta-base/resolve/main/tokenizer.json''' ), '''google/bigbird-roberta-large''': ( '''https://huggingface.co/google/bigbird-roberta-large/resolve/main/tokenizer.json''' ), '''google/bigbird-base-trivia-itc''': ( '''https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/tokenizer.json''' ), }, } snake_case__ : int = { '''google/bigbird-roberta-base''': 4_096, '''google/bigbird-roberta-large''': 4_096, '''google/bigbird-base-trivia-itc''': 4_096, } snake_case__ : Optional[Any] = '''▁''' class snake_case_( a__ ): __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = BigBirdTokenizer __UpperCamelCase = ['''input_ids''', '''attention_mask'''] __UpperCamelCase = [] def __init__( self : Union[str, Any] , UpperCamelCase_ : str=None , UpperCamelCase_ : Any=None , UpperCamelCase_ : str="<unk>" , UpperCamelCase_ : str="<s>" , UpperCamelCase_ : str="</s>" , UpperCamelCase_ : int="<pad>" , UpperCamelCase_ : List[Any]="[SEP]" , UpperCamelCase_ : Dict="[MASK]" , UpperCamelCase_ : Any="[CLS]" , **UpperCamelCase_ : Any , ): lowerCAmelCase : Tuple = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else bos_token lowerCAmelCase : int = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else eos_token lowerCAmelCase : List[Any] = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else unk_token lowerCAmelCase : List[str] = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else pad_token lowerCAmelCase : Any = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else cls_token lowerCAmelCase : Tuple = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else sep_token # Mask token behave like a normal word, i.e. include the space before it lowerCAmelCase : Optional[Any] = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else mask_token super().__init__( UpperCamelCase_ , tokenizer_file=UpperCamelCase_ , bos_token=UpperCamelCase_ , eos_token=UpperCamelCase_ , unk_token=UpperCamelCase_ , sep_token=UpperCamelCase_ , pad_token=UpperCamelCase_ , cls_token=UpperCamelCase_ , mask_token=UpperCamelCase_ , **UpperCamelCase_ , ) lowerCAmelCase : Optional[int] = vocab_file lowerCAmelCase : Optional[int] = False if not self.vocab_file else True def lowerCamelCase__ ( self : Union[str, Any] , UpperCamelCase_ : List[int] , UpperCamelCase_ : Optional[List[int]] = None ): lowerCAmelCase : str = [self.sep_token_id] lowerCAmelCase : Tuple = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def lowerCamelCase__ ( self : Dict , UpperCamelCase_ : List[int] , UpperCamelCase_ : Optional[List[int]] = None , UpperCamelCase_ : bool = False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( '''You should not supply a second sequence if the provided sequence of ''' '''ids is already formatted with special tokens for the model.''' ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is None: return [1] + ([0] * len(UpperCamelCase_ )) + [1] return [1] + ([0] * len(UpperCamelCase_ )) + [1] + ([0] * len(UpperCamelCase_ )) + [1] def lowerCamelCase__ ( self : Dict , UpperCamelCase_ : List[int] , UpperCamelCase_ : Optional[List[int]] = None ): lowerCAmelCase : Tuple = [self.sep_token_id] lowerCAmelCase : Tuple = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def lowerCamelCase__ ( self : Optional[int] , UpperCamelCase_ : str , UpperCamelCase_ : Optional[str] = None ): if not self.can_save_slow_tokenizer: raise ValueError( '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow ''' '''tokenizer.''' ) if not os.path.isdir(UpperCamelCase_ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowerCAmelCase : Optional[int] = os.path.join( UpperCamelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(UpperCamelCase_ ): copyfile(self.vocab_file , UpperCamelCase_ ) return (out_vocab_file,)
637
1
"""simple docstring""" import gc import random import unittest import numpy as np import torch from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline from diffusers.pipelines.shap_e import ShapERenderer from diffusers.utils import floats_tensor, load_image, load_numpy, slow from diffusers.utils.testing_utils import require_torch_gpu, torch_device from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference class snake_case_( a__ , unittest.TestCase ): __UpperCamelCase = ShapEImgaImgPipeline __UpperCamelCase = ['''image'''] __UpperCamelCase = ['''image'''] __UpperCamelCase = [ '''num_images_per_prompt''', '''num_inference_steps''', '''generator''', '''latents''', '''guidance_scale''', '''frame_size''', '''output_type''', '''return_dict''', ] __UpperCamelCase = False @property def lowerCamelCase__ ( self : Dict ): return 3_2 @property def lowerCamelCase__ ( self : List[str] ): return 3_2 @property def lowerCamelCase__ ( self : Optional[int] ): return self.time_input_dim * 4 @property def lowerCamelCase__ ( self : Union[str, Any] ): return 8 @property def lowerCamelCase__ ( self : Dict ): torch.manual_seed(0 ) lowerCAmelCase : Tuple = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , image_size=6_4 , projection_dim=self.text_embedder_hidden_size , intermediate_size=3_7 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=1 , ) lowerCAmelCase : Optional[Any] = CLIPVisionModel(UpperCamelCase_ ) return model @property def lowerCamelCase__ ( self : Union[str, Any] ): lowerCAmelCase : List[str] = CLIPImageProcessor( crop_size=2_2_4 , do_center_crop=UpperCamelCase_ , do_normalize=UpperCamelCase_ , do_resize=UpperCamelCase_ , image_mean=[0.48_145_466, 0.4_578_275, 0.40_821_073] , image_std=[0.26_862_954, 0.26_130_258, 0.27_577_711] , resample=3 , size=2_2_4 , ) return image_processor @property def lowerCamelCase__ ( self : Optional[Any] ): torch.manual_seed(0 ) lowerCAmelCase : List[str] = { '''num_attention_heads''': 2, '''attention_head_dim''': 1_6, '''embedding_dim''': self.time_input_dim, '''num_embeddings''': 3_2, '''embedding_proj_dim''': self.text_embedder_hidden_size, '''time_embed_dim''': self.time_embed_dim, '''num_layers''': 1, '''clip_embed_dim''': self.time_input_dim * 2, '''additional_embeddings''': 0, '''time_embed_act_fn''': '''gelu''', '''norm_in_type''': '''layer''', '''embedding_proj_norm_type''': '''layer''', '''encoder_hid_proj_type''': None, '''added_emb_type''': None, } lowerCAmelCase : List[Any] = PriorTransformer(**UpperCamelCase_ ) return model @property def lowerCamelCase__ ( self : int ): torch.manual_seed(0 ) lowerCAmelCase : Union[str, Any] = { '''param_shapes''': ( (self.renderer_dim, 9_3), (self.renderer_dim, 8), (self.renderer_dim, 8), (self.renderer_dim, 8), ), '''d_latent''': self.time_input_dim, '''d_hidden''': self.renderer_dim, '''n_output''': 1_2, '''background''': ( 0.1, 0.1, 0.1, ), } lowerCAmelCase : Any = ShapERenderer(**UpperCamelCase_ ) return model def lowerCamelCase__ ( self : List[str] ): lowerCAmelCase : Optional[int] = self.dummy_prior lowerCAmelCase : str = self.dummy_image_encoder lowerCAmelCase : Optional[Any] = self.dummy_image_processor lowerCAmelCase : Tuple = self.dummy_renderer lowerCAmelCase : List[str] = HeunDiscreteScheduler( beta_schedule='''exp''' , num_train_timesteps=1_0_2_4 , prediction_type='''sample''' , use_karras_sigmas=UpperCamelCase_ , clip_sample=UpperCamelCase_ , clip_sample_range=1.0 , ) lowerCAmelCase : Optional[Any] = { '''prior''': prior, '''image_encoder''': image_encoder, '''image_processor''': image_processor, '''renderer''': renderer, '''scheduler''': scheduler, } return components def lowerCamelCase__ ( self : Any , UpperCamelCase_ : str , UpperCamelCase_ : Optional[int]=0 ): lowerCAmelCase : Any = floats_tensor((1, 3, 6_4, 6_4) , rng=random.Random(UpperCamelCase_ ) ).to(UpperCamelCase_ ) if str(UpperCamelCase_ ).startswith('''mps''' ): lowerCAmelCase : str = torch.manual_seed(UpperCamelCase_ ) else: lowerCAmelCase : Optional[int] = torch.Generator(device=UpperCamelCase_ ).manual_seed(UpperCamelCase_ ) lowerCAmelCase : int = { '''image''': input_image, '''generator''': generator, '''num_inference_steps''': 1, '''frame_size''': 3_2, '''output_type''': '''np''', } return inputs def lowerCamelCase__ ( self : List[Any] ): lowerCAmelCase : int = '''cpu''' lowerCAmelCase : List[str] = self.get_dummy_components() lowerCAmelCase : str = self.pipeline_class(**UpperCamelCase_ ) lowerCAmelCase : Any = pipe.to(UpperCamelCase_ ) pipe.set_progress_bar_config(disable=UpperCamelCase_ ) lowerCAmelCase : int = pipe(**self.get_dummy_inputs(UpperCamelCase_ ) ) lowerCAmelCase : Tuple = output.images[0] lowerCAmelCase : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (2_0, 3_2, 3_2, 3) lowerCAmelCase : List[Any] = np.array( [ 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, 0.00_039_216, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 def lowerCamelCase__ ( self : List[Any] ): # NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches self._test_inference_batch_consistent(batch_sizes=[1, 2] ) def lowerCamelCase__ ( self : Union[str, Any] ): lowerCAmelCase : List[Any] = torch_device == '''cpu''' lowerCAmelCase : List[str] = True self._test_inference_batch_single_identical( batch_size=2 , test_max_difference=UpperCamelCase_ , relax_max_difference=UpperCamelCase_ , ) def lowerCamelCase__ ( self : Union[str, Any] ): lowerCAmelCase : Union[str, Any] = self.get_dummy_components() lowerCAmelCase : int = self.pipeline_class(**UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = pipe.to(UpperCamelCase_ ) pipe.set_progress_bar_config(disable=UpperCamelCase_ ) lowerCAmelCase : Dict = 1 lowerCAmelCase : List[Any] = 2 lowerCAmelCase : Union[str, Any] = self.get_dummy_inputs(UpperCamelCase_ ) for key in inputs.keys(): if key in self.batch_params: lowerCAmelCase : Dict = batch_size * [inputs[key]] lowerCAmelCase : int = pipe(**UpperCamelCase_ , num_images_per_prompt=UpperCamelCase_ )[0] assert images.shape[0] == batch_size * num_images_per_prompt @slow @require_torch_gpu class snake_case_( unittest.TestCase ): def lowerCamelCase__ ( self : List[Any] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowerCamelCase__ ( self : Tuple ): lowerCAmelCase : Dict = load_image( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/corgi.png''' ) lowerCAmelCase : Union[str, Any] = load_numpy( '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/test_shap_e_img2img_out.npy''' ) lowerCAmelCase : int = ShapEImgaImgPipeline.from_pretrained('''openai/shap-e-img2img''' ) lowerCAmelCase : Any = pipe.to(UpperCamelCase_ ) pipe.set_progress_bar_config(disable=UpperCamelCase_ ) lowerCAmelCase : Any = torch.Generator(device=UpperCamelCase_ ).manual_seed(0 ) lowerCAmelCase : str = pipe( UpperCamelCase_ , generator=UpperCamelCase_ , guidance_scale=3.0 , num_inference_steps=6_4 , frame_size=6_4 , output_type='''np''' , ).images[0] assert images.shape == (2_0, 6_4, 6_4, 3) assert_mean_pixel_difference(UpperCamelCase_ , UpperCamelCase_ )
637
"""simple docstring""" # using dfs for finding eulerian path traversal def _snake_case ( _snake_case : Optional[Any] , _snake_case : List[Any] , _snake_case : str , _snake_case : List[Any]=None ): lowerCAmelCase : Any = (path or []) + [u] for v in graph[u]: if visited_edge[u][v] is False: lowerCAmelCase, lowerCAmelCase : Union[str, Any] = True, True lowerCAmelCase : int = dfs(_snake_case , _snake_case , _snake_case , _snake_case ) return path def _snake_case ( _snake_case : Optional[int] , _snake_case : Dict ): lowerCAmelCase : Tuple = 0 lowerCAmelCase : Optional[Any] = -1 for i in range(_snake_case ): if i not in graph.keys(): continue if len(graph[i] ) % 2 == 1: odd_degree_nodes += 1 lowerCAmelCase : Optional[Any] = i if odd_degree_nodes == 0: return 1, odd_node if odd_degree_nodes == 2: return 2, odd_node return 3, odd_node def _snake_case ( _snake_case : Tuple , _snake_case : List[Any] ): lowerCAmelCase : Any = [[False for _ in range(max_node + 1 )] for _ in range(max_node + 1 )] lowerCAmelCase, lowerCAmelCase : Optional[int] = check_circuit_or_path(_snake_case , _snake_case ) if check == 3: print('''graph is not Eulerian''' ) print('''no path''' ) return lowerCAmelCase : Dict = 1 if check == 2: lowerCAmelCase : int = odd_node print('''graph has a Euler path''' ) if check == 1: print('''graph has a Euler cycle''' ) lowerCAmelCase : List[str] = dfs(_snake_case , _snake_case , _snake_case ) print(_snake_case ) def _snake_case ( ): lowerCAmelCase : Optional[Any] = {1: [2, 3, 4], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [4]} lowerCAmelCase : Union[str, Any] = {1: [2, 3, 4, 5], 2: [1, 3], 3: [1, 2], 4: [1, 5], 5: [1, 4]} lowerCAmelCase : List[Any] = {1: [2, 3, 4], 2: [1, 3, 4], 3: [1, 2], 4: [1, 2, 5], 5: [4]} lowerCAmelCase : Optional[Any] = {1: [2, 3], 2: [1, 3], 3: [1, 2]} lowerCAmelCase : Any = { 1: [], 2: [] # all degree is zero } lowerCAmelCase : List[str] = 10 check_euler(_snake_case , _snake_case ) check_euler(_snake_case , _snake_case ) check_euler(_snake_case , _snake_case ) check_euler(_snake_case , _snake_case ) check_euler(_snake_case , _snake_case ) if __name__ == "__main__": main()
637
1
"""simple docstring""" import enum import os from hashlib import shaaaa from typing import Optional from .. import config from .logging import get_logger snake_case__ : str = get_logger(__name__) class snake_case_( enum.Enum ): __UpperCamelCase = '''all_checks''' __UpperCamelCase = '''basic_checks''' __UpperCamelCase = '''no_checks''' class snake_case_( a__ ): pass class snake_case_( a__ ): pass class snake_case_( a__ ): pass class snake_case_( a__ ): pass def _snake_case ( _snake_case : Optional[dict] , _snake_case : dict , _snake_case : List[Any]=None ): if expected_checksums is None: logger.info('''Unable to verify checksums.''' ) return if len(set(_snake_case ) - set(_snake_case ) ) > 0: raise ExpectedMoreDownloadedFiles(str(set(_snake_case ) - set(_snake_case ) ) ) if len(set(_snake_case ) - set(_snake_case ) ) > 0: raise UnexpectedDownloadedFile(str(set(_snake_case ) - set(_snake_case ) ) ) lowerCAmelCase : List[str] = [url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]] lowerCAmelCase : Any = ''' for ''' + verification_name if verification_name is not None else '''''' if len(_snake_case ) > 0: raise NonMatchingChecksumError( f'''Checksums didn\'t match{for_verification_name}:\n''' f'''{bad_urls}\n''' '''Set `verification_mode=\'no_checks\'` to skip checksums verification and ignore this error''' ) logger.info('''All the checksums matched successfully''' + for_verification_name ) class snake_case_( a__ ): pass class snake_case_( a__ ): pass class snake_case_( a__ ): pass class snake_case_( a__ ): pass def _snake_case ( _snake_case : Optional[dict] , _snake_case : dict ): if expected_splits is None: logger.info('''Unable to verify splits sizes.''' ) return if len(set(_snake_case ) - set(_snake_case ) ) > 0: raise ExpectedMoreSplits(str(set(_snake_case ) - set(_snake_case ) ) ) if len(set(_snake_case ) - set(_snake_case ) ) > 0: raise UnexpectedSplits(str(set(_snake_case ) - set(_snake_case ) ) ) lowerCAmelCase : Union[str, Any] = [ {'''expected''': expected_splits[name], '''recorded''': recorded_splits[name]} for name in expected_splits if expected_splits[name].num_examples != recorded_splits[name].num_examples ] if len(_snake_case ) > 0: raise NonMatchingSplitsSizesError(str(_snake_case ) ) logger.info('''All the splits matched successfully.''' ) def _snake_case ( _snake_case : str , _snake_case : bool = True ): if record_checksum: lowerCAmelCase : str = shaaaa() with open(_snake_case , '''rb''' ) as f: for chunk in iter(lambda: f.read(1 << 20 ) , B'''''' ): m.update(_snake_case ) lowerCAmelCase : Tuple = m.hexdigest() else: lowerCAmelCase : List[str] = None return {"num_bytes": os.path.getsize(_snake_case ), "checksum": checksum} def _snake_case ( _snake_case : Dict ): if dataset_size and config.IN_MEMORY_MAX_SIZE: return dataset_size < config.IN_MEMORY_MAX_SIZE else: return False
637
"""simple docstring""" import os import shutil import sys import tempfile import unittest from pathlib import Path import pytest import transformers from transformers import ( BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoTokenizer, BertConfig, BertTokenizer, BertTokenizerFast, CTRLTokenizer, GPTaTokenizer, GPTaTokenizerFast, PreTrainedTokenizerFast, RobertaTokenizer, RobertaTokenizerFast, is_tokenizers_available, ) from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig from transformers.models.auto.tokenization_auto import ( TOKENIZER_MAPPING, get_tokenizer_config, tokenizer_class_from_name, ) from transformers.models.roberta.configuration_roberta import RobertaConfig from transformers.testing_utils import ( DUMMY_DIFF_TOKENIZER_IDENTIFIER, DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, RequestCounter, require_tokenizers, slow, ) sys.path.append(str(Path(__file__).parent.parent.parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_tokenization import CustomTokenizer # noqa E402 if is_tokenizers_available(): from test_module.custom_tokenization_fast import CustomTokenizerFast class snake_case_( unittest.TestCase ): def lowerCamelCase__ ( self : Optional[int] ): lowerCAmelCase : Optional[Any] = 0 @slow def lowerCamelCase__ ( self : Dict ): for model_name in (x for x in BERT_PRETRAINED_CONFIG_ARCHIVE_MAP.keys() if "japanese" not in x): lowerCAmelCase : Optional[Any] = AutoTokenizer.from_pretrained(UpperCamelCase_ ) self.assertIsNotNone(UpperCamelCase_ ) self.assertIsInstance(UpperCamelCase_ , (BertTokenizer, BertTokenizerFast) ) self.assertGreater(len(UpperCamelCase_ ) , 0 ) for model_name in GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP.keys(): lowerCAmelCase : Tuple = AutoTokenizer.from_pretrained(UpperCamelCase_ ) self.assertIsNotNone(UpperCamelCase_ ) self.assertIsInstance(UpperCamelCase_ , (GPTaTokenizer, GPTaTokenizerFast) ) self.assertGreater(len(UpperCamelCase_ ) , 0 ) def lowerCamelCase__ ( self : Union[str, Any] ): lowerCAmelCase : Optional[Any] = AutoTokenizer.from_pretrained(UpperCamelCase_ ) self.assertIsInstance(UpperCamelCase_ , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 1_2 ) def lowerCamelCase__ ( self : Dict ): lowerCAmelCase : Tuple = AutoTokenizer.from_pretrained(UpperCamelCase_ ) self.assertIsInstance(UpperCamelCase_ , (RobertaTokenizer, RobertaTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 2_0 ) def lowerCamelCase__ ( self : Dict ): lowerCAmelCase : int = AutoConfig.from_pretrained(UpperCamelCase_ ) self.assertIsInstance(UpperCamelCase_ , UpperCamelCase_ ) # Check that tokenizer_type ≠ model_type lowerCAmelCase : List[Any] = AutoTokenizer.from_pretrained(UpperCamelCase_ , config=UpperCamelCase_ ) self.assertIsInstance(UpperCamelCase_ , (BertTokenizer, BertTokenizerFast) ) self.assertEqual(tokenizer.vocab_size , 1_2 ) def lowerCamelCase__ ( self : Any ): with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy('''./tests/fixtures/vocab.txt''' , os.path.join(UpperCamelCase_ , '''vocab.txt''' ) ) lowerCAmelCase : Any = AutoTokenizer.from_pretrained(UpperCamelCase_ , tokenizer_type='''bert''' , use_fast=UpperCamelCase_ ) self.assertIsInstance(UpperCamelCase_ , UpperCamelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy('''./tests/fixtures/vocab.json''' , os.path.join(UpperCamelCase_ , '''vocab.json''' ) ) shutil.copy('''./tests/fixtures/merges.txt''' , os.path.join(UpperCamelCase_ , '''merges.txt''' ) ) lowerCAmelCase : List[Any] = AutoTokenizer.from_pretrained(UpperCamelCase_ , tokenizer_type='''gpt2''' , use_fast=UpperCamelCase_ ) self.assertIsInstance(UpperCamelCase_ , UpperCamelCase_ ) @require_tokenizers def lowerCamelCase__ ( self : Union[str, Any] ): with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy('''./tests/fixtures/vocab.txt''' , os.path.join(UpperCamelCase_ , '''vocab.txt''' ) ) lowerCAmelCase : Optional[Any] = AutoTokenizer.from_pretrained(UpperCamelCase_ , tokenizer_type='''bert''' ) self.assertIsInstance(UpperCamelCase_ , UpperCamelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: shutil.copy('''./tests/fixtures/vocab.json''' , os.path.join(UpperCamelCase_ , '''vocab.json''' ) ) shutil.copy('''./tests/fixtures/merges.txt''' , os.path.join(UpperCamelCase_ , '''merges.txt''' ) ) lowerCAmelCase : int = AutoTokenizer.from_pretrained(UpperCamelCase_ , tokenizer_type='''gpt2''' ) self.assertIsInstance(UpperCamelCase_ , UpperCamelCase_ ) def lowerCamelCase__ ( self : Dict ): with pytest.raises(UpperCamelCase_ ): AutoTokenizer.from_pretrained('''./''' , tokenizer_type='''xxx''' ) @require_tokenizers def lowerCamelCase__ ( self : str ): for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: lowerCAmelCase : Dict = tokenizer_class.from_pretrained('''wietsedv/bert-base-dutch-cased''' ) self.assertIsInstance(UpperCamelCase_ , (BertTokenizer, BertTokenizerFast) ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ): self.assertEqual(tokenizer.basic_tokenizer.do_lower_case , UpperCamelCase_ ) else: self.assertEqual(tokenizer.do_lower_case , UpperCamelCase_ ) self.assertEqual(tokenizer.model_max_length , 5_1_2 ) @require_tokenizers def lowerCamelCase__ ( self : Optional[int] ): for tokenizer_class in [BertTokenizer, BertTokenizerFast, AutoTokenizer]: with self.assertRaisesRegex( UpperCamelCase_ , '''julien-c/herlolip-not-exists is not a local folder and is not a valid model identifier''' , ): lowerCAmelCase : Any = tokenizer_class.from_pretrained('''julien-c/herlolip-not-exists''' ) def lowerCamelCase__ ( self : Tuple ): # tests: https://github.com/huggingface/transformers/pull/13251 # 1. models with `-`, e.g. xlm-roberta -> xlm_roberta # 2. models that don't remap 1-1 from model-name to model file, e.g., openai-gpt -> openai lowerCAmelCase : Optional[Any] = TOKENIZER_MAPPING.values() lowerCAmelCase : Optional[Any] = [] for slow_tok, fast_tok in tokenizers: if slow_tok is not None: tokenizer_names.append(slow_tok.__name__ ) if fast_tok is not None: tokenizer_names.append(fast_tok.__name__ ) for tokenizer_name in tokenizer_names: # must find the right class tokenizer_class_from_name(UpperCamelCase_ ) @require_tokenizers def lowerCamelCase__ ( self : Any ): self.assertIsInstance(AutoTokenizer.from_pretrained('''bert-base-cased''' , use_fast=UpperCamelCase_ ) , UpperCamelCase_ ) self.assertIsInstance(AutoTokenizer.from_pretrained('''bert-base-cased''' ) , UpperCamelCase_ ) @require_tokenizers def lowerCamelCase__ ( self : Dict ): lowerCAmelCase : List[Any] = AutoTokenizer.from_pretrained('''distilbert-base-uncased''' , do_lower_case=UpperCamelCase_ ) lowerCAmelCase : Union[str, Any] = '''Hello, world. How are you?''' lowerCAmelCase : Optional[Any] = tokenizer.tokenize(UpperCamelCase_ ) self.assertEqual('''[UNK]''' , tokens[0] ) lowerCAmelCase : List[str] = AutoTokenizer.from_pretrained('''microsoft/mpnet-base''' , do_lower_case=UpperCamelCase_ ) lowerCAmelCase : Optional[int] = tokenizer.tokenize(UpperCamelCase_ ) self.assertEqual('''[UNK]''' , tokens[0] ) @require_tokenizers def lowerCamelCase__ ( self : int ): lowerCAmelCase : Union[str, Any] = AutoTokenizer.from_pretrained('''robot-test/dummy-tokenizer-fast-with-model-config''' ) self.assertEqual(type(UpperCamelCase_ ) , UpperCamelCase_ ) self.assertEqual(tokenizer.model_max_length , 5_1_2 ) self.assertEqual(tokenizer.vocab_size , 3_0_0_0_0 ) self.assertEqual(tokenizer.unk_token , '''[UNK]''' ) self.assertEqual(tokenizer.padding_side , '''right''' ) self.assertEqual(tokenizer.truncation_side , '''right''' ) def lowerCamelCase__ ( self : List[Any] ): lowerCAmelCase : int = AutoTokenizer.from_pretrained(UpperCamelCase_ ) self.assertIsInstance(UpperCamelCase_ , (BertTokenizer, BertTokenizerFast) ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(UpperCamelCase_ ) lowerCAmelCase : List[Any] = AutoTokenizer.from_pretrained(UpperCamelCase_ ) self.assertIsInstance(UpperCamelCase_ , tokenizer.__class__ ) self.assertEqual(tokenizera.vocab_size , 1_2 ) def lowerCamelCase__ ( self : List[str] ): lowerCAmelCase : List[Any] = AutoTokenizer.from_pretrained('''ctrl''' ) # There is no fast CTRL so this always gives us a slow tokenizer. self.assertIsInstance(UpperCamelCase_ , UpperCamelCase_ ) def lowerCamelCase__ ( self : Dict ): # Check we can load the tokenizer config of an online model. lowerCAmelCase : Any = get_tokenizer_config('''bert-base-cased''' ) lowerCAmelCase : Optional[int] = config.pop('''_commit_hash''' , UpperCamelCase_ ) # If we ever update bert-base-cased tokenizer config, this dict here will need to be updated. self.assertEqual(UpperCamelCase_ , {'''do_lower_case''': False} ) # This model does not have a tokenizer_config so we get back an empty dict. lowerCAmelCase : Union[str, Any] = get_tokenizer_config(UpperCamelCase_ ) self.assertDictEqual(UpperCamelCase_ , {} ) # A tokenizer saved with `save_pretrained` always creates a tokenizer config. lowerCAmelCase : List[Any] = AutoTokenizer.from_pretrained(UpperCamelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(UpperCamelCase_ ) lowerCAmelCase : Dict = get_tokenizer_config(UpperCamelCase_ ) # Check the class of the tokenizer was properly saved (note that it always saves the slow class). self.assertEqual(config['''tokenizer_class'''] , '''BertTokenizer''' ) def lowerCamelCase__ ( self : Optional[int] ): try: AutoConfig.register('''custom''' , UpperCamelCase_ ) AutoTokenizer.register(UpperCamelCase_ , slow_tokenizer_class=UpperCamelCase_ ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(UpperCamelCase_ ): AutoTokenizer.register(UpperCamelCase_ , slow_tokenizer_class=UpperCamelCase_ ) lowerCAmelCase : Union[str, Any] = CustomTokenizer.from_pretrained(UpperCamelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(UpperCamelCase_ ) lowerCAmelCase : Tuple = AutoTokenizer.from_pretrained(UpperCamelCase_ ) self.assertIsInstance(UpperCamelCase_ , UpperCamelCase_ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] @require_tokenizers def lowerCamelCase__ ( self : str ): try: AutoConfig.register('''custom''' , UpperCamelCase_ ) # Can register in two steps AutoTokenizer.register(UpperCamelCase_ , slow_tokenizer_class=UpperCamelCase_ ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, None) ) AutoTokenizer.register(UpperCamelCase_ , fast_tokenizer_class=UpperCamelCase_ ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) ) del TOKENIZER_MAPPING._extra_content[CustomConfig] # Can register in one step AutoTokenizer.register( UpperCamelCase_ , slow_tokenizer_class=UpperCamelCase_ , fast_tokenizer_class=UpperCamelCase_ ) self.assertEqual(TOKENIZER_MAPPING[CustomConfig] , (CustomTokenizer, CustomTokenizerFast) ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(UpperCamelCase_ ): AutoTokenizer.register(UpperCamelCase_ , fast_tokenizer_class=UpperCamelCase_ ) # We pass through a bert tokenizer fast cause there is no converter slow to fast for our new toknizer # and that model does not have a tokenizer.json with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase : Dict = BertTokenizerFast.from_pretrained(UpperCamelCase_ ) bert_tokenizer.save_pretrained(UpperCamelCase_ ) lowerCAmelCase : int = CustomTokenizerFast.from_pretrained(UpperCamelCase_ ) with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(UpperCamelCase_ ) lowerCAmelCase : Optional[int] = AutoTokenizer.from_pretrained(UpperCamelCase_ ) self.assertIsInstance(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : List[str] = AutoTokenizer.from_pretrained(UpperCamelCase_ , use_fast=UpperCamelCase_ ) self.assertIsInstance(UpperCamelCase_ , UpperCamelCase_ ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] def lowerCamelCase__ ( self : Optional[int] ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(UpperCamelCase_ ): lowerCAmelCase : int = AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer''' ) # If remote code is disabled, we can't load this config. with self.assertRaises(UpperCamelCase_ ): lowerCAmelCase : str = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=UpperCamelCase_ ) lowerCAmelCase : List[str] = AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=UpperCamelCase_ ) self.assertTrue(tokenizer.special_attribute_present ) # Test tokenizer can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = AutoTokenizer.from_pretrained(UpperCamelCase_ , trust_remote_code=UpperCamelCase_ ) self.assertTrue(reloaded_tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) # Test we can also load the slow version lowerCAmelCase : Union[str, Any] = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=UpperCamelCase_ , use_fast=UpperCamelCase_ ) self.assertTrue(tokenizer.special_attribute_present ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) # Test tokenizer can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: tokenizer.save_pretrained(UpperCamelCase_ ) lowerCAmelCase : List[str] = AutoTokenizer.from_pretrained(UpperCamelCase_ , trust_remote_code=UpperCamelCase_ , use_fast=UpperCamelCase_ ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , '''NewTokenizer''' ) self.assertTrue(reloaded_tokenizer.special_attribute_present ) else: self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) self.assertEqual(reloaded_tokenizer.__class__.__name__ , '''NewTokenizer''' ) @require_tokenizers def lowerCamelCase__ ( self : Optional[int] ): class snake_case_( a__ ): __UpperCamelCase = False class snake_case_( a__ ): __UpperCamelCase = NewTokenizer __UpperCamelCase = False try: AutoConfig.register('''custom''' , UpperCamelCase_ ) AutoTokenizer.register(UpperCamelCase_ , slow_tokenizer_class=UpperCamelCase_ ) AutoTokenizer.register(UpperCamelCase_ , fast_tokenizer_class=UpperCamelCase_ ) # If remote code is not set, the default is to use local lowerCAmelCase : Optional[int] = AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer''' ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) self.assertFalse(tokenizer.special_attribute_present ) lowerCAmelCase : str = AutoTokenizer.from_pretrained('''hf-internal-testing/test_dynamic_tokenizer''' , use_fast=UpperCamelCase_ ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) self.assertFalse(tokenizer.special_attribute_present ) # If remote code is disabled, we load the local one. lowerCAmelCase : Union[str, Any] = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=UpperCamelCase_ ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) self.assertFalse(tokenizer.special_attribute_present ) lowerCAmelCase : Dict = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=UpperCamelCase_ , use_fast=UpperCamelCase_ ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) self.assertFalse(tokenizer.special_attribute_present ) # If remote is enabled, we load from the Hub lowerCAmelCase : int = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=UpperCamelCase_ ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) self.assertTrue(tokenizer.special_attribute_present ) lowerCAmelCase : int = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer''' , trust_remote_code=UpperCamelCase_ , use_fast=UpperCamelCase_ ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) self.assertTrue(tokenizer.special_attribute_present ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in TOKENIZER_MAPPING._extra_content: del TOKENIZER_MAPPING._extra_content[CustomConfig] def lowerCamelCase__ ( self : Tuple ): lowerCAmelCase : str = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer_legacy''' , trust_remote_code=UpperCamelCase_ ) self.assertTrue(tokenizer.special_attribute_present ) if is_tokenizers_available(): self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizerFast''' ) # Test we can also load the slow version lowerCAmelCase : List[str] = AutoTokenizer.from_pretrained( '''hf-internal-testing/test_dynamic_tokenizer_legacy''' , trust_remote_code=UpperCamelCase_ , use_fast=UpperCamelCase_ ) self.assertTrue(tokenizer.special_attribute_present ) self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) else: self.assertEqual(tokenizer.__class__.__name__ , '''NewTokenizer''' ) def lowerCamelCase__ ( self : str ): with self.assertRaisesRegex( UpperCamelCase_ , '''bert-base is not a local folder and is not a valid model identifier''' ): lowerCAmelCase : List[str] = AutoTokenizer.from_pretrained('''bert-base''' ) def lowerCamelCase__ ( self : int ): with self.assertRaisesRegex( UpperCamelCase_ , r'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)''' ): lowerCAmelCase : List[Any] = AutoTokenizer.from_pretrained(UpperCamelCase_ , revision='''aaaaaa''' ) def lowerCamelCase__ ( self : Optional[int] ): # Make sure we have cached the tokenizer. lowerCAmelCase : List[str] = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) with RequestCounter() as counter: lowerCAmelCase : int = AutoTokenizer.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) self.assertEqual(counter.get_request_count , 0 ) self.assertEqual(counter.head_request_count , 1 ) self.assertEqual(counter.other_request_count , 0 )
637
1
"""simple docstring""" import numpy as np def _snake_case ( _snake_case : np.ndarray , _snake_case : np.ndarray , _snake_case : float = 1E-12 , _snake_case : int = 100 , ): assert np.shape(_snake_case )[0] == np.shape(_snake_case )[1] # Ensure proper dimensionality. assert np.shape(_snake_case )[0] == np.shape(_snake_case )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(_snake_case ) == np.iscomplexobj(_snake_case ) lowerCAmelCase : Dict = np.iscomplexobj(_snake_case ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(_snake_case , 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 : Any = False lowerCAmelCase : Optional[int] = 0 lowerCAmelCase : int = 0 lowerCAmelCase : Any = 1E12 while not convergence: # Multiple matrix by the vector. lowerCAmelCase : Optional[Any] = np.dot(_snake_case , _snake_case ) # Normalize the resulting output vector. lowerCAmelCase : Tuple = w / np.linalg.norm(_snake_case ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) lowerCAmelCase : List[Any] = vector.conj().T if is_complex else vector.T lowerCAmelCase : List[str] = np.dot(_snake_case , np.dot(_snake_case , _snake_case ) ) # Check convergence. lowerCAmelCase : Any = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: lowerCAmelCase : Optional[Any] = True lowerCAmelCase : Any = lambda_ if is_complex: lowerCAmelCase : Optional[int] = np.real(lambda_ ) return lambda_, vector def _snake_case ( ): lowerCAmelCase : Any = np.array([[41, 4, 20], [4, 26, 30], [20, 30, 50]] ) lowerCAmelCase : Dict = np.array([41, 4, 20] ) lowerCAmelCase : List[str] = real_input_matrix.astype(np.complexaaa ) lowerCAmelCase : Union[str, Any] = np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T lowerCAmelCase : Dict = np.array([41, 4, 20] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": lowerCAmelCase : str = real_input_matrix lowerCAmelCase : Dict = real_vector elif problem_type == "complex": lowerCAmelCase : List[Any] = complex_input_matrix lowerCAmelCase : Dict = complex_vector # Our implementation. lowerCAmelCase, lowerCAmelCase : Any = power_iteration(_snake_case , _snake_case ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). lowerCAmelCase, lowerCAmelCase : str = np.linalg.eigh(_snake_case ) # Last eigenvalue is the maximum one. lowerCAmelCase : Optional[int] = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. lowerCAmelCase : int = 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(_snake_case ) - np.abs(_snake_case ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
637
"""simple docstring""" import json import os from functools import lru_cache from typing import Dict, List, Optional, Tuple, Union import regex as re from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...tokenization_utils_base import BatchEncoding, EncodedInput from ...utils import PaddingStrategy, logging snake_case__ : Optional[Any] = logging.get_logger(__name__) snake_case__ : Any = {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt'''} # See all LED models at https://huggingface.co/models?filter=LED snake_case__ : Optional[Any] = { '''vocab_file''': { '''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json''', }, '''merges_file''': { '''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt''', }, '''tokenizer_file''': { '''allenai/led-base-16384''': '''https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json''', }, } snake_case__ : List[Any] = { '''allenai/led-base-16384''': 16_384, } @lru_cache() # Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode def _snake_case ( ): lowerCAmelCase : Optional[int] = ( list(range(ord('''!''' ) , ord('''~''' ) + 1 ) ) + list(range(ord('''¡''' ) , ord('''¬''' ) + 1 ) ) + list(range(ord('''®''' ) , ord('''ÿ''' ) + 1 ) ) ) lowerCAmelCase : str = bs[:] lowerCAmelCase : Optional[int] = 0 for b in range(2**8 ): if b not in bs: bs.append(_snake_case ) cs.append(2**8 + n ) n += 1 lowerCAmelCase : int = [chr(_snake_case ) for n in cs] return dict(zip(_snake_case , _snake_case ) ) def _snake_case ( _snake_case : List[Any] ): lowerCAmelCase : List[str] = set() lowerCAmelCase : Any = word[0] for char in word[1:]: pairs.add((prev_char, char) ) lowerCAmelCase : Optional[Any] = char return pairs class snake_case_( a__ ): __UpperCamelCase = VOCAB_FILES_NAMES __UpperCamelCase = PRETRAINED_VOCAB_FILES_MAP __UpperCamelCase = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __UpperCamelCase = ['''input_ids''', '''attention_mask'''] def __init__( self : Tuple , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Dict , UpperCamelCase_ : Tuple="replace" , UpperCamelCase_ : Union[str, Any]="<s>" , UpperCamelCase_ : List[str]="</s>" , UpperCamelCase_ : str="</s>" , UpperCamelCase_ : int="<s>" , UpperCamelCase_ : int="<unk>" , UpperCamelCase_ : Union[str, Any]="<pad>" , UpperCamelCase_ : Tuple="<mask>" , UpperCamelCase_ : Optional[int]=False , **UpperCamelCase_ : Tuple , ): lowerCAmelCase : Any = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else bos_token lowerCAmelCase : Union[str, Any] = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else eos_token lowerCAmelCase : Optional[int] = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else sep_token lowerCAmelCase : int = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else cls_token lowerCAmelCase : Tuple = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else unk_token lowerCAmelCase : List[Any] = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else pad_token # Mask token behave like a normal word, i.e. include the space before it lowerCAmelCase : Tuple = AddedToken(UpperCamelCase_ , lstrip=UpperCamelCase_ , rstrip=UpperCamelCase_ ) if isinstance(UpperCamelCase_ , UpperCamelCase_ ) else mask_token super().__init__( errors=UpperCamelCase_ , bos_token=UpperCamelCase_ , eos_token=UpperCamelCase_ , unk_token=UpperCamelCase_ , sep_token=UpperCamelCase_ , cls_token=UpperCamelCase_ , pad_token=UpperCamelCase_ , mask_token=UpperCamelCase_ , add_prefix_space=UpperCamelCase_ , **UpperCamelCase_ , ) with open(UpperCamelCase_ , encoding='''utf-8''' ) as vocab_handle: lowerCAmelCase : Any = json.load(UpperCamelCase_ ) lowerCAmelCase : Dict = {v: k for k, v in self.encoder.items()} lowerCAmelCase : Optional[int] = errors # how to handle errors in decoding lowerCAmelCase : List[Any] = bytes_to_unicode() lowerCAmelCase : Optional[Any] = {v: k for k, v in self.byte_encoder.items()} with open(UpperCamelCase_ , encoding='''utf-8''' ) as merges_handle: lowerCAmelCase : Optional[int] = merges_handle.read().split('''\n''' )[1:-1] lowerCAmelCase : Optional[int] = [tuple(merge.split() ) for merge in bpe_merges] lowerCAmelCase : Optional[int] = dict(zip(UpperCamelCase_ , range(len(UpperCamelCase_ ) ) ) ) lowerCAmelCase : List[Any] = {} lowerCAmelCase : Optional[Any] = add_prefix_space # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions lowerCAmelCase : Dict = re.compile(r'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+''' ) @property # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size def lowerCamelCase__ ( self : Union[str, Any] ): return len(self.encoder ) def lowerCamelCase__ ( self : Union[str, Any] ): return dict(self.encoder , **self.added_tokens_encoder ) def lowerCamelCase__ ( self : Any , UpperCamelCase_ : int ): if token in self.cache: return self.cache[token] lowerCAmelCase : List[str] = tuple(UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = get_pairs(UpperCamelCase_ ) if not pairs: return token while True: lowerCAmelCase : List[Any] = min(UpperCamelCase_ , key=lambda UpperCamelCase_ : self.bpe_ranks.get(UpperCamelCase_ , float('''inf''' ) ) ) if bigram not in self.bpe_ranks: break lowerCAmelCase, lowerCAmelCase : Any = bigram lowerCAmelCase : Tuple = [] lowerCAmelCase : Any = 0 while i < len(UpperCamelCase_ ): try: lowerCAmelCase : int = word.index(UpperCamelCase_ , UpperCamelCase_ ) except ValueError: new_word.extend(word[i:] ) break else: new_word.extend(word[i:j] ) lowerCAmelCase : int = j if word[i] == first and i < len(UpperCamelCase_ ) - 1 and word[i + 1] == second: new_word.append(first + second ) i += 2 else: new_word.append(word[i] ) i += 1 lowerCAmelCase : Tuple = tuple(UpperCamelCase_ ) lowerCAmelCase : Tuple = new_word if len(UpperCamelCase_ ) == 1: break else: lowerCAmelCase : Optional[Any] = get_pairs(UpperCamelCase_ ) lowerCAmelCase : Union[str, Any] = ''' '''.join(UpperCamelCase_ ) lowerCAmelCase : List[str] = word return word def lowerCamelCase__ ( self : Optional[Any] , UpperCamelCase_ : Tuple ): lowerCAmelCase : Dict = [] for token in re.findall(self.pat , UpperCamelCase_ ): lowerCAmelCase : Union[str, Any] = ''''''.join( self.byte_encoder[b] for b in token.encode('''utf-8''' ) ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case) bpe_tokens.extend(bpe_token for bpe_token in self.bpe(UpperCamelCase_ ).split(''' ''' ) ) return bpe_tokens def lowerCamelCase__ ( self : int , UpperCamelCase_ : str ): return self.encoder.get(UpperCamelCase_ , self.encoder.get(self.unk_token ) ) def lowerCamelCase__ ( self : Any , UpperCamelCase_ : Union[str, Any] ): return self.decoder.get(UpperCamelCase_ ) def lowerCamelCase__ ( self : Any , UpperCamelCase_ : List[str] ): lowerCAmelCase : Optional[int] = ''''''.join(UpperCamelCase_ ) lowerCAmelCase : Optional[int] = bytearray([self.byte_decoder[c] for c in text] ).decode('''utf-8''' , errors=self.errors ) return text def lowerCamelCase__ ( self : str , UpperCamelCase_ : str , UpperCamelCase_ : Optional[str] = None ): if not os.path.isdir(UpperCamelCase_ ): logger.error(F'''Vocabulary path ({save_directory}) should be a directory''' ) return lowerCAmelCase : int = os.path.join( UpperCamelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) lowerCAmelCase : Optional[Any] = os.path.join( UpperCamelCase_ , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file'''] ) with open(UpperCamelCase_ , '''w''' , encoding='''utf-8''' ) as f: f.write(json.dumps(self.encoder , indent=2 , sort_keys=UpperCamelCase_ , ensure_ascii=UpperCamelCase_ ) + '''\n''' ) lowerCAmelCase : Optional[int] = 0 with open(UpperCamelCase_ , '''w''' , encoding='''utf-8''' ) as writer: writer.write('''#version: 0.2\n''' ) for bpe_tokens, token_index in sorted(self.bpe_ranks.items() , key=lambda UpperCamelCase_ : kv[1] ): if index != token_index: logger.warning( F'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.''' ''' Please check that the tokenizer is not corrupted!''' ) lowerCAmelCase : Tuple = token_index writer.write(''' '''.join(UpperCamelCase_ ) + '''\n''' ) index += 1 return vocab_file, merge_file def lowerCamelCase__ ( self : Optional[Any] , UpperCamelCase_ : List[int] , UpperCamelCase_ : Optional[List[int]] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] lowerCAmelCase : Any = [self.cls_token_id] lowerCAmelCase : str = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def lowerCamelCase__ ( self : Any , UpperCamelCase_ : List[int] , UpperCamelCase_ : Optional[List[int]] = None , UpperCamelCase_ : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=UpperCamelCase_ , token_ids_a=UpperCamelCase_ , already_has_special_tokens=UpperCamelCase_ ) if token_ids_a is None: return [1] + ([0] * len(UpperCamelCase_ )) + [1] return [1] + ([0] * len(UpperCamelCase_ )) + [1, 1] + ([0] * len(UpperCamelCase_ )) + [1] def lowerCamelCase__ ( self : List[str] , UpperCamelCase_ : List[int] , UpperCamelCase_ : Optional[List[int]] = None ): lowerCAmelCase : Optional[Any] = [self.sep_token_id] lowerCAmelCase : Optional[int] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def lowerCamelCase__ ( self : int , UpperCamelCase_ : Any , UpperCamelCase_ : Dict=False , **UpperCamelCase_ : Tuple ): lowerCAmelCase : Union[str, Any] = kwargs.pop('''add_prefix_space''' , self.add_prefix_space ) if (is_split_into_words or add_prefix_space) and (len(UpperCamelCase_ ) > 0 and not text[0].isspace()): lowerCAmelCase : List[Any] = ''' ''' + text return (text, kwargs) def lowerCamelCase__ ( self : str , UpperCamelCase_ : Union[Dict[str, EncodedInput], BatchEncoding] , UpperCamelCase_ : Optional[int] = None , UpperCamelCase_ : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , UpperCamelCase_ : Optional[int] = None , UpperCamelCase_ : Optional[bool] = None , ): lowerCAmelCase : Dict = super()._pad( encoded_inputs=UpperCamelCase_ , max_length=UpperCamelCase_ , padding_strategy=UpperCamelCase_ , pad_to_multiple_of=UpperCamelCase_ , return_attention_mask=UpperCamelCase_ , ) # Load from model defaults if return_attention_mask is None: lowerCAmelCase : Tuple = '''attention_mask''' in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: lowerCAmelCase : Dict = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. lowerCAmelCase : List[Any] = len(encoded_inputs['''global_attention_mask'''] ) != len(UpperCamelCase_ ) if needs_to_be_padded: lowerCAmelCase : int = len(UpperCamelCase_ ) - len(encoded_inputs['''global_attention_mask'''] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` lowerCAmelCase : Dict = ( encoded_inputs['''global_attention_mask'''] + [-1] * difference ) elif self.padding_side == "left": lowerCAmelCase : int = [-1] * difference + encoded_inputs[ '''global_attention_mask''' ] else: raise ValueError('''Invalid padding strategy:''' + str(self.padding_side ) ) return encoded_inputs
637
1
"""simple docstring""" from math import ceil def _snake_case ( _snake_case : int = 1001 ): lowerCAmelCase : Dict = 1 for i in range(1 , int(ceil(n / 2.0 ) ) ): lowerCAmelCase : List[str] = 2 * i + 1 lowerCAmelCase : List[str] = 2 * i lowerCAmelCase : Tuple = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: snake_case__ : Dict = int(sys.argv[1]) print(solution(n)) except ValueError: print('''Invalid entry - please enter a number''')
637
"""simple docstring""" def _snake_case ( _snake_case : int = 4000000 ): lowerCAmelCase : int = [0, 1] lowerCAmelCase : List[str] = 0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1] ) if fib[i + 2] > n: break i += 1 lowerCAmelCase : int = 0 for j in range(len(_snake_case ) - 1 ): if fib[j] % 2 == 0: total += fib[j] return total if __name__ == "__main__": print(f"""{solution() = }""")
637
1
"""simple docstring""" import torch from diffusers import StableDiffusionPipeline snake_case__ : Optional[Any] = '''path-to-your-trained-model''' snake_case__ : Any = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.floataa).to('''cuda''') snake_case__ : Optional[Any] = '''A photo of sks dog in a bucket''' snake_case__ : Optional[int] = pipe(prompt, num_inference_steps=50, guidance_scale=7.5).images[0] image.save('''dog-bucket.png''')
637
"""simple docstring""" def _snake_case ( _snake_case : float , _snake_case : list[float] ): if discount_rate < 0: raise ValueError('''Discount rate cannot be negative''' ) if not cash_flows: raise ValueError('''Cash flows list cannot be empty''' ) lowerCAmelCase : List[str] = sum( cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(_snake_case ) ) return round(_snake_case , ndigits=2 ) if __name__ == "__main__": import doctest doctest.testmod()
637
1
"""simple docstring""" import copy import inspect import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import VideoMAEConfig from transformers.models.auto import get_values 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 torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEForPreTraining, VideoMAEForVideoClassification, VideoMAEModel, ) from transformers.models.videomae.modeling_videomae import VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class snake_case_: def __init__( self : Tuple , UpperCamelCase_ : List[str] , UpperCamelCase_ : List[Any]=1_3 , UpperCamelCase_ : Any=1_0 , UpperCamelCase_ : Dict=3 , UpperCamelCase_ : Union[str, Any]=2 , UpperCamelCase_ : Union[str, Any]=2 , UpperCamelCase_ : List[Any]=2 , UpperCamelCase_ : List[str]=True , UpperCamelCase_ : Tuple=True , UpperCamelCase_ : Tuple=3_2 , UpperCamelCase_ : List[str]=5 , UpperCamelCase_ : int=4 , UpperCamelCase_ : Any=3_7 , UpperCamelCase_ : int="gelu" , UpperCamelCase_ : List[str]=0.1 , UpperCamelCase_ : Optional[Any]=0.1 , UpperCamelCase_ : int=1_0 , UpperCamelCase_ : List[str]=0.02 , UpperCamelCase_ : Union[str, Any]=0.9 , UpperCamelCase_ : List[Any]=None , ): lowerCAmelCase : Dict = parent lowerCAmelCase : str = batch_size lowerCAmelCase : Union[str, Any] = image_size lowerCAmelCase : Union[str, Any] = num_channels lowerCAmelCase : Tuple = patch_size lowerCAmelCase : Optional[int] = tubelet_size lowerCAmelCase : Optional[int] = num_frames lowerCAmelCase : int = is_training lowerCAmelCase : str = use_labels lowerCAmelCase : Union[str, Any] = hidden_size lowerCAmelCase : Tuple = num_hidden_layers lowerCAmelCase : Any = num_attention_heads lowerCAmelCase : Dict = intermediate_size lowerCAmelCase : str = hidden_act lowerCAmelCase : List[Any] = hidden_dropout_prob lowerCAmelCase : Optional[int] = attention_probs_dropout_prob lowerCAmelCase : Optional[int] = type_sequence_label_size lowerCAmelCase : Optional[int] = initializer_range lowerCAmelCase : Optional[Any] = mask_ratio lowerCAmelCase : Optional[Any] = scope # in VideoMAE, the number of tokens equals num_frames/tubelet_size * num_patches per frame lowerCAmelCase : Tuple = (image_size // patch_size) ** 2 lowerCAmelCase : Union[str, Any] = (num_frames // tubelet_size) * self.num_patches_per_frame # use this variable to define bool_masked_pos lowerCAmelCase : str = int(mask_ratio * self.seq_length ) def lowerCamelCase__ ( self : Optional[Any] ): lowerCAmelCase : Dict = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) lowerCAmelCase : List[str] = None if self.use_labels: lowerCAmelCase : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCAmelCase : Tuple = self.get_config() return config, pixel_values, labels def lowerCamelCase__ ( self : List[Any] ): return VideoMAEConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_frames=self.num_frames , tubelet_size=self.tubelet_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 , is_decoder=UpperCamelCase_ , initializer_range=self.initializer_range , ) def lowerCamelCase__ ( self : int , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : Dict , UpperCamelCase_ : List[Any] ): lowerCAmelCase : str = VideoMAEModel(config=UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowerCAmelCase : Dict = model(UpperCamelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase__ ( self : Optional[int] , UpperCamelCase_ : List[str] , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Optional[Any] ): lowerCAmelCase : Optional[Any] = VideoMAEForPreTraining(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() # important: each video needs to have the same number of masked patches # hence we define a single mask, which we then repeat for each example in the batch lowerCAmelCase : List[Any] = torch.ones((self.num_masks,) ) lowerCAmelCase : Optional[Any] = torch.cat([mask, torch.zeros(self.seq_length - mask.size(0 ) )] ) lowerCAmelCase : Optional[int] = mask.expand(self.batch_size , -1 ).bool() lowerCAmelCase : Union[str, Any] = model(UpperCamelCase_ , UpperCamelCase_ ) # model only returns predictions for masked patches lowerCAmelCase : int = mask.sum().item() lowerCAmelCase : Dict = 3 * self.tubelet_size * self.patch_size**2 self.parent.assertEqual(result.logits.shape , (self.batch_size, num_masked_patches, decoder_num_labels) ) def lowerCamelCase__ ( self : int ): lowerCAmelCase : Dict = self.prepare_config_and_inputs() lowerCAmelCase, lowerCAmelCase, lowerCAmelCase : int = config_and_inputs lowerCAmelCase : List[Any] = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class snake_case_( a__ , a__ , unittest.TestCase ): __UpperCamelCase = ( (VideoMAEModel, VideoMAEForPreTraining, VideoMAEForVideoClassification) if is_torch_available() else () ) __UpperCamelCase = ( {'''feature-extraction''': VideoMAEModel, '''video-classification''': VideoMAEForVideoClassification} if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False __UpperCamelCase = False def lowerCamelCase__ ( self : int ): lowerCAmelCase : Tuple = VideoMAEModelTester(self ) lowerCAmelCase : str = ConfigTester(self , config_class=UpperCamelCase_ , has_text_modality=UpperCamelCase_ , hidden_size=3_7 ) def lowerCamelCase__ ( self : Any , UpperCamelCase_ : Tuple , UpperCamelCase_ : Tuple , UpperCamelCase_ : str=False ): lowerCAmelCase : Optional[int] = copy.deepcopy(UpperCamelCase_ ) if model_class == VideoMAEForPreTraining: # important: each video needs to have the same number of masked patches # hence we define a single mask, which we then repeat for each example in the batch lowerCAmelCase : List[str] = torch.ones((self.model_tester.num_masks,) ) lowerCAmelCase : Any = torch.cat([mask, torch.zeros(self.model_tester.seq_length - mask.size(0 ) )] ) lowerCAmelCase : List[Any] = mask.expand(self.model_tester.batch_size , -1 ).bool() lowerCAmelCase : Optional[int] = bool_masked_pos.to(UpperCamelCase_ ) if return_labels: if model_class in [ *get_values(UpperCamelCase_ ), ]: lowerCAmelCase : List[Any] = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=UpperCamelCase_ ) return inputs_dict def lowerCamelCase__ ( self : Union[str, Any] ): self.config_tester.run_common_tests() @unittest.skip(reason='''VideoMAE does not use inputs_embeds''' ) def lowerCamelCase__ ( self : List[Any] ): pass def lowerCamelCase__ ( self : int ): lowerCAmelCase, lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase : str = model_class(UpperCamelCase_ ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) lowerCAmelCase : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(UpperCamelCase_ , nn.Linear ) ) def lowerCamelCase__ ( self : Dict ): lowerCAmelCase, lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase : Dict = model_class(UpperCamelCase_ ) lowerCAmelCase : Union[str, Any] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic lowerCAmelCase : Tuple = [*signature.parameters.keys()] lowerCAmelCase : Optional[Any] = ['''pixel_values'''] self.assertListEqual(arg_names[:1] , UpperCamelCase_ ) def lowerCamelCase__ ( self : Union[str, Any] ): lowerCAmelCase : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase_ ) def lowerCamelCase__ ( self : Dict ): lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*UpperCamelCase_ ) @slow def lowerCamelCase__ ( self : Dict ): for model_name in VIDEOMAE_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: lowerCAmelCase : Dict = VideoMAEModel.from_pretrained(UpperCamelCase_ ) self.assertIsNotNone(UpperCamelCase_ ) def lowerCamelCase__ ( self : int ): if not self.has_attentions: pass else: lowerCAmelCase, lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase : Union[str, Any] = True for model_class in self.all_model_classes: lowerCAmelCase : Tuple = self.model_tester.seq_length - self.model_tester.num_masks lowerCAmelCase : Dict = ( num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length ) lowerCAmelCase : int = True lowerCAmelCase : int = False lowerCAmelCase : int = True lowerCAmelCase : str = model_class(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() with torch.no_grad(): lowerCAmelCase : Tuple = model(**self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase : str = outputs.attentions self.assertEqual(len(UpperCamelCase_ ) , self.model_tester.num_hidden_layers ) # check that output_attentions also work using config del inputs_dict["output_attentions"] lowerCAmelCase : Tuple = True lowerCAmelCase : Dict = model_class(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() with torch.no_grad(): lowerCAmelCase : List[Any] = model(**self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase : int = outputs.attentions self.assertEqual(len(UpperCamelCase_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) lowerCAmelCase : Optional[Any] = len(UpperCamelCase_ ) # Check attention is always last and order is fine lowerCAmelCase : Union[str, Any] = True lowerCAmelCase : Optional[Any] = True lowerCAmelCase : Optional[int] = model_class(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() with torch.no_grad(): lowerCAmelCase : str = model(**self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ ) ) self.assertEqual(out_len + 1 , len(UpperCamelCase_ ) ) lowerCAmelCase : List[str] = outputs.attentions self.assertEqual(len(UpperCamelCase_ ) , self.model_tester.num_hidden_layers ) self.assertListEqual( list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_attention_heads, seq_len, seq_len] , ) def lowerCamelCase__ ( self : str ): def check_hidden_states_output(UpperCamelCase_ : str , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : int ): lowerCAmelCase : str = model_class(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() with torch.no_grad(): lowerCAmelCase : List[Any] = model(**self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase : Any = outputs.hidden_states lowerCAmelCase : Any = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(UpperCamelCase_ ) , UpperCamelCase_ ) lowerCAmelCase : Dict = self.model_tester.seq_length - self.model_tester.num_masks lowerCAmelCase : Tuple = num_visible_patches if model_class == VideoMAEForPreTraining else self.model_tester.seq_length self.assertListEqual( list(hidden_states[0].shape[-2:] ) , [seq_length, self.model_tester.hidden_size] , ) lowerCAmelCase, lowerCAmelCase : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: lowerCAmelCase : List[Any] = True check_hidden_states_output(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] lowerCAmelCase : List[Any] = True check_hidden_states_output(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def lowerCamelCase__ ( self : Optional[int] ): pass def _snake_case ( ): lowerCAmelCase : Optional[int] = hf_hub_download( repo_id='''hf-internal-testing/spaghetti-video''' , filename='''eating_spaghetti.npy''' , repo_type='''dataset''' ) lowerCAmelCase : Optional[Any] = np.load(_snake_case ) return list(_snake_case ) @require_torch @require_vision class snake_case_( unittest.TestCase ): @cached_property def lowerCamelCase__ ( self : List[str] ): # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5] , image_std=[0.5, 0.5, 0.5] ) if is_vision_available() else None ) @slow def lowerCamelCase__ ( self : Dict ): lowerCAmelCase : Optional[Any] = VideoMAEForVideoClassification.from_pretrained('''MCG-NJU/videomae-base-finetuned-kinetics''' ).to( UpperCamelCase_ ) lowerCAmelCase : Tuple = self.default_image_processor lowerCAmelCase : Union[str, Any] = prepare_video() lowerCAmelCase : Union[str, Any] = image_processor(UpperCamelCase_ , return_tensors='''pt''' ).to(UpperCamelCase_ ) # forward pass with torch.no_grad(): lowerCAmelCase : Tuple = model(**UpperCamelCase_ ) # verify the logits lowerCAmelCase : int = torch.Size((1, 4_0_0) ) self.assertEqual(outputs.logits.shape , UpperCamelCase_ ) lowerCAmelCase : Optional[int] = torch.tensor([0.3_669, -0.0_688, -0.2_421] ).to(UpperCamelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCamelCase_ , atol=1E-4 ) ) @slow def lowerCamelCase__ ( self : Any ): lowerCAmelCase : Optional[Any] = VideoMAEForPreTraining.from_pretrained('''MCG-NJU/videomae-base-short''' ).to(UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = self.default_image_processor lowerCAmelCase : Optional[int] = prepare_video() lowerCAmelCase : Tuple = image_processor(UpperCamelCase_ , return_tensors='''pt''' ).to(UpperCamelCase_ ) # add boolean mask, indicating which patches to mask lowerCAmelCase : Union[str, Any] = hf_hub_download(repo_id='''hf-internal-testing/bool-masked-pos''' , filename='''bool_masked_pos.pt''' ) lowerCAmelCase : Tuple = torch.load(UpperCamelCase_ ) # forward pass with torch.no_grad(): lowerCAmelCase : Tuple = model(**UpperCamelCase_ ) # verify the logits lowerCAmelCase : Tuple = torch.Size([1, 1_4_0_8, 1_5_3_6] ) lowerCAmelCase : Optional[int] = torch.tensor( [[0.7_994, 0.9_612, 0.8_508], [0.7_401, 0.8_958, 0.8_302], [0.5_862, 0.7_468, 0.7_325]] , device=UpperCamelCase_ ) self.assertEqual(outputs.logits.shape , UpperCamelCase_ ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] , UpperCamelCase_ , atol=1E-4 ) ) # verify the loss (`config.norm_pix_loss` = `True`) lowerCAmelCase : str = torch.tensor([0.5_142] , device=UpperCamelCase_ ) self.assertTrue(torch.allclose(outputs.loss , UpperCamelCase_ , atol=1E-4 ) ) # verify the loss (`config.norm_pix_loss` = `False`) lowerCAmelCase : int = VideoMAEForPreTraining.from_pretrained('''MCG-NJU/videomae-base-short''' , norm_pix_loss=UpperCamelCase_ ).to( UpperCamelCase_ ) with torch.no_grad(): lowerCAmelCase : Optional[Any] = model(**UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = torch.tensor(torch.tensor([0.6_469] ) , device=UpperCamelCase_ ) self.assertTrue(torch.allclose(outputs.loss , UpperCamelCase_ , atol=1E-4 ) )
637
"""simple docstring""" from __future__ import annotations def _snake_case ( _snake_case : list[int] , _snake_case : int ): if len(_snake_case ) == 0: return False lowerCAmelCase : List[Any] = len(_snake_case ) // 2 if a_list[midpoint] == item: return True if item < a_list[midpoint]: return binary_search(a_list[:midpoint] , _snake_case ) else: return binary_search(a_list[midpoint + 1 :] , _snake_case ) if __name__ == "__main__": snake_case__ : List[str] = input('''Enter numbers separated by comma:\n''').strip() snake_case__ : Optional[int] = [int(item.strip()) for item in user_input.split(''',''')] snake_case__ : Dict = int(input('''Enter the number to be found in the list:\n''').strip()) snake_case__ : str = '''''' if binary_search(sequence, target) else '''not ''' print(f"""{target} was {not_str}found in {sequence}""")
637
1
"""simple docstring""" import os import tempfile import unittest from pathlib import Path from transformers import AutoConfig, is_tf_available from transformers.testing_utils import require_tf if is_tf_available(): import tensorflow as tf from transformers import TensorFlowBenchmark, TensorFlowBenchmarkArguments @require_tf class snake_case_( unittest.TestCase ): def lowerCamelCase__ ( self : Optional[int] , UpperCamelCase_ : Dict ): for model_result in results.values(): for batch_size, sequence_length in zip(model_result['''bs'''] , model_result['''ss'''] ): lowerCAmelCase : Dict = model_result['''result'''][batch_size][sequence_length] self.assertIsNotNone(UpperCamelCase_ ) def lowerCamelCase__ ( self : Any ): lowerCAmelCase : Optional[int] = '''sshleifer/tiny-gpt2''' lowerCAmelCase : int = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCamelCase_ , inference=UpperCamelCase_ , sequence_lengths=[8] , batch_sizes=[1] , eager_mode=UpperCamelCase_ , multi_process=UpperCamelCase_ , ) lowerCAmelCase : int = TensorFlowBenchmark(UpperCamelCase_ ) lowerCAmelCase : List[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def lowerCamelCase__ ( self : int ): lowerCAmelCase : Dict = '''sgugger/tiny-distilbert-classification''' lowerCAmelCase : int = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCamelCase_ , inference=UpperCamelCase_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCamelCase_ , only_pretrain_model=UpperCamelCase_ , ) lowerCAmelCase : Tuple = TensorFlowBenchmark(UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def lowerCamelCase__ ( self : str ): lowerCAmelCase : List[str] = '''sshleifer/tiny-gpt2''' lowerCAmelCase : Optional[int] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCamelCase_ , inference=UpperCamelCase_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCamelCase_ , ) lowerCAmelCase : str = TensorFlowBenchmark(UpperCamelCase_ ) lowerCAmelCase : Any = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def lowerCamelCase__ ( self : Any ): lowerCAmelCase : Optional[int] = '''sshleifer/tiny-gpt2''' lowerCAmelCase : Union[str, Any] = AutoConfig.from_pretrained(UpperCamelCase_ ) lowerCAmelCase : str = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCamelCase_ , inference=UpperCamelCase_ , sequence_lengths=[8] , batch_sizes=[1] , eager_mode=UpperCamelCase_ , multi_process=UpperCamelCase_ , ) lowerCAmelCase : List[str] = TensorFlowBenchmark(UpperCamelCase_ , [config] ) lowerCAmelCase : Optional[int] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def lowerCamelCase__ ( self : int ): lowerCAmelCase : int = '''sshleifer/tiny-gpt2''' lowerCAmelCase : List[Any] = AutoConfig.from_pretrained(UpperCamelCase_ ) lowerCAmelCase : List[str] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCamelCase_ , inference=UpperCamelCase_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCamelCase_ , ) lowerCAmelCase : List[Any] = TensorFlowBenchmark(UpperCamelCase_ , [config] ) lowerCAmelCase : Dict = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def lowerCamelCase__ ( self : Union[str, Any] ): lowerCAmelCase : Tuple = '''sshleifer/tiny-gpt2''' lowerCAmelCase : Optional[int] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCamelCase_ , inference=UpperCamelCase_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCamelCase_ , ) lowerCAmelCase : int = TensorFlowBenchmark(UpperCamelCase_ ) lowerCAmelCase : str = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def lowerCamelCase__ ( self : str ): lowerCAmelCase : str = '''sshleifer/tiny-gpt2''' lowerCAmelCase : List[str] = AutoConfig.from_pretrained(UpperCamelCase_ ) lowerCAmelCase : Optional[int] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCamelCase_ , inference=UpperCamelCase_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCamelCase_ , ) lowerCAmelCase : Dict = TensorFlowBenchmark(UpperCamelCase_ , [config] ) lowerCAmelCase : Tuple = benchmark.run() self.check_results_dict_not_empty(results.time_train_result ) self.check_results_dict_not_empty(results.memory_train_result ) def lowerCamelCase__ ( self : List[Any] ): lowerCAmelCase : Optional[int] = '''patrickvonplaten/t5-tiny-random''' lowerCAmelCase : List[Any] = AutoConfig.from_pretrained(UpperCamelCase_ ) lowerCAmelCase : List[str] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCamelCase_ , inference=UpperCamelCase_ , sequence_lengths=[8] , batch_sizes=[1] , multi_process=UpperCamelCase_ , ) lowerCAmelCase : Union[str, Any] = TensorFlowBenchmark(UpperCamelCase_ , configs=[config] ) lowerCAmelCase : List[str] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) @unittest.skipIf(is_tf_available() and len(tf.config.list_physical_devices('''GPU''' ) ) == 0 , '''Cannot do xla on CPU.''' ) def lowerCamelCase__ ( self : int ): lowerCAmelCase : List[Any] = '''sshleifer/tiny-gpt2''' lowerCAmelCase : List[str] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , training=UpperCamelCase_ , inference=UpperCamelCase_ , sequence_lengths=[8] , batch_sizes=[1] , use_xla=UpperCamelCase_ , multi_process=UpperCamelCase_ , ) lowerCAmelCase : Tuple = TensorFlowBenchmark(UpperCamelCase_ ) lowerCAmelCase : Union[str, Any] = benchmark.run() self.check_results_dict_not_empty(results.time_inference_result ) self.check_results_dict_not_empty(results.memory_inference_result ) def lowerCamelCase__ ( self : Union[str, Any] ): lowerCAmelCase : Optional[Any] = '''sshleifer/tiny-gpt2''' with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase : Optional[Any] = TensorFlowBenchmarkArguments( models=[MODEL_ID] , inference=UpperCamelCase_ , save_to_csv=UpperCamelCase_ , sequence_lengths=[8] , batch_sizes=[1] , inference_time_csv_file=os.path.join(UpperCamelCase_ , '''inf_time.csv''' ) , inference_memory_csv_file=os.path.join(UpperCamelCase_ , '''inf_mem.csv''' ) , env_info_csv_file=os.path.join(UpperCamelCase_ , '''env.csv''' ) , multi_process=UpperCamelCase_ , ) lowerCAmelCase : Tuple = TensorFlowBenchmark(UpperCamelCase_ ) benchmark.run() self.assertTrue(Path(os.path.join(UpperCamelCase_ , '''inf_time.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(UpperCamelCase_ , '''inf_mem.csv''' ) ).exists() ) self.assertTrue(Path(os.path.join(UpperCamelCase_ , '''env.csv''' ) ).exists() ) def lowerCamelCase__ ( self : List[str] ): lowerCAmelCase : Any = '''sshleifer/tiny-gpt2''' def _check_summary_is_not_empty(UpperCamelCase_ : List[Any] ): self.assertTrue(hasattr(UpperCamelCase_ , '''sequential''' ) ) self.assertTrue(hasattr(UpperCamelCase_ , '''cumulative''' ) ) self.assertTrue(hasattr(UpperCamelCase_ , '''current''' ) ) self.assertTrue(hasattr(UpperCamelCase_ , '''total''' ) ) with tempfile.TemporaryDirectory() as tmp_dir: lowerCAmelCase : Any = TensorFlowBenchmarkArguments( models=[MODEL_ID] , inference=UpperCamelCase_ , sequence_lengths=[8] , batch_sizes=[1] , log_filename=os.path.join(UpperCamelCase_ , '''log.txt''' ) , log_print=UpperCamelCase_ , trace_memory_line_by_line=UpperCamelCase_ , eager_mode=UpperCamelCase_ , multi_process=UpperCamelCase_ , ) lowerCAmelCase : str = TensorFlowBenchmark(UpperCamelCase_ ) lowerCAmelCase : int = benchmark.run() _check_summary_is_not_empty(result.inference_summary ) self.assertTrue(Path(os.path.join(UpperCamelCase_ , '''log.txt''' ) ).exists() )
637
"""simple docstring""" import os from collections import namedtuple import pytest from datasets import ClassLabel, Features, Sequence, Value from datasets.commands.test import TestCommand from datasets.info import DatasetInfo, DatasetInfosDict snake_case__ : Optional[Any] = namedtuple( '''_TestCommandArgs''', [ '''dataset''', '''name''', '''cache_dir''', '''data_dir''', '''all_configs''', '''save_infos''', '''ignore_verifications''', '''force_redownload''', '''clear_cache''', ], defaults=[None, None, None, False, False, False, False, False], ) def _snake_case ( _snake_case : List[Any] , _snake_case : List[str] ): return (abs(source - target ) / target) < 0.01 @pytest.mark.integration def _snake_case ( _snake_case : Any ): lowerCAmelCase : Union[str, Any] = _TestCommandArgs(dataset=_snake_case , all_configs=_snake_case , save_infos=_snake_case ) lowerCAmelCase : str = TestCommand(*_snake_case ) test_command.run() lowerCAmelCase : str = os.path.join(_snake_case , '''README.md''' ) assert os.path.exists(_snake_case ) lowerCAmelCase : Tuple = DatasetInfosDict.from_directory(_snake_case ) lowerCAmelCase : List[str] = DatasetInfosDict( { '''default''': DatasetInfo( features=Features( { '''tokens''': Sequence(Value('''string''' ) ), '''ner_tags''': Sequence( ClassLabel(names=['''O''', '''B-PER''', '''I-PER''', '''B-ORG''', '''I-ORG''', '''B-LOC''', '''I-LOC'''] ) ), '''langs''': Sequence(Value('''string''' ) ), '''spans''': Sequence(Value('''string''' ) ), } ) , splits=[ { '''name''': '''train''', '''num_bytes''': 2351563, '''num_examples''': 10000, }, { '''name''': '''validation''', '''num_bytes''': 238418, '''num_examples''': 1000, }, ] , download_size=3940680 , dataset_size=2589981 , ) } ) assert dataset_infos.keys() == expected_dataset_infos.keys() for key in DatasetInfo._INCLUDED_INFO_IN_YAML: lowerCAmelCase, lowerCAmelCase : Union[str, Any] = getattr(dataset_infos['''default'''] , _snake_case ), getattr(expected_dataset_infos['''default'''] , _snake_case ) if key == "num_bytes": assert is_apercent_close(_snake_case , _snake_case ) elif key == "splits": assert list(_snake_case ) == list(_snake_case ) for split in result: assert result[split].name == expected[split].name assert result[split].num_examples == expected[split].num_examples assert is_apercent_close(result[split].num_bytes , expected[split].num_bytes ) else: result == expected
637
1
"""simple docstring""" from __future__ import annotations import collections import pprint from pathlib import Path def _snake_case ( _snake_case : str ): return "".join(sorted(_snake_case ) ) def _snake_case ( _snake_case : str ): return word_by_signature[signature(_snake_case )] snake_case__ : str = Path(__file__).parent.joinpath('''words.txt''').read_text(encoding='''utf-8''') snake_case__ : Any = sorted({word.strip().lower() for word in data.splitlines()}) snake_case__ : List[Any] = collections.defaultdict(list) for word in word_list: word_by_signature[signature(word)].append(word) if __name__ == "__main__": snake_case__ : Optional[int] = {word: anagram(word) for word in word_list if len(anagram(word)) > 1} with open('''anagrams.txt''', '''w''') as file: file.write('''all_anagrams = \n ''') file.write(pprint.pformat(all_anagrams))
637
"""simple docstring""" def _snake_case ( _snake_case : int , _snake_case : int ): return base * power(_snake_case , (exponent - 1) ) if exponent else 1 if __name__ == "__main__": print('''Raise base to the power of exponent using recursion...''') snake_case__ : Union[str, Any] = int(input('''Enter the base: ''').strip()) snake_case__ : Optional[Any] = int(input('''Enter the exponent: ''').strip()) snake_case__ : Any = power(base, abs(exponent)) if exponent < 0: # power() does not properly deal w/ negative exponents snake_case__ : Dict = 1 / result print(f"""{base} to the power of {exponent} is {result}""")
637
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) snake_case__ : Dict = {'''configuration_xlnet''': ['''XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''XLNetConfig''']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case__ : Dict = ['''XLNetTokenizer'''] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case__ : Any = ['''XLNetTokenizerFast'''] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case__ : Any = [ '''XLNET_PRETRAINED_MODEL_ARCHIVE_LIST''', '''XLNetForMultipleChoice''', '''XLNetForQuestionAnswering''', '''XLNetForQuestionAnsweringSimple''', '''XLNetForSequenceClassification''', '''XLNetForTokenClassification''', '''XLNetLMHeadModel''', '''XLNetModel''', '''XLNetPreTrainedModel''', '''load_tf_weights_in_xlnet''', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case__ : int = [ '''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__ : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
637
"""simple docstring""" 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 snake_case__ : int = '''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 _snake_case ( _snake_case : str , _snake_case : Any , _snake_case : str=None , _snake_case : str=None , _snake_case : Dict=None , _snake_case : Tuple=None , _snake_case : str=None , _snake_case : Any=None , ): if attention_mask is None: lowerCAmelCase : List[str] = np.where(input_ids != config.pad_token_id , 1 , 0 ) if decoder_attention_mask is None: lowerCAmelCase : Optional[int] = np.where(decoder_input_ids != config.pad_token_id , 1 , 0 ) if head_mask is None: lowerCAmelCase : Any = np.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: lowerCAmelCase : int = np.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: lowerCAmelCase : List[str] = 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 snake_case_: def __init__( self : int , UpperCamelCase_ : Tuple , UpperCamelCase_ : int=1_3 , UpperCamelCase_ : Union[str, Any]=7 , UpperCamelCase_ : Union[str, Any]=True , UpperCamelCase_ : List[Any]=False , UpperCamelCase_ : Dict=9_9 , UpperCamelCase_ : Optional[int]=1_6 , UpperCamelCase_ : str=2 , UpperCamelCase_ : List[str]=4 , UpperCamelCase_ : List[Any]=4 , UpperCamelCase_ : int="gelu" , UpperCamelCase_ : Optional[int]=0.1 , UpperCamelCase_ : Any=0.1 , UpperCamelCase_ : str=3_2 , UpperCamelCase_ : str=2 , UpperCamelCase_ : Tuple=1 , UpperCamelCase_ : List[Any]=0 , UpperCamelCase_ : Any=0.02 , ): lowerCAmelCase : Tuple = parent lowerCAmelCase : str = batch_size lowerCAmelCase : List[Any] = seq_length lowerCAmelCase : Optional[int] = is_training lowerCAmelCase : int = use_labels lowerCAmelCase : List[Any] = vocab_size lowerCAmelCase : str = hidden_size lowerCAmelCase : List[Any] = num_hidden_layers lowerCAmelCase : Any = num_attention_heads lowerCAmelCase : List[Any] = intermediate_size lowerCAmelCase : Optional[int] = hidden_act lowerCAmelCase : Dict = hidden_dropout_prob lowerCAmelCase : Optional[int] = attention_probs_dropout_prob lowerCAmelCase : List[Any] = max_position_embeddings lowerCAmelCase : Union[str, Any] = eos_token_id lowerCAmelCase : Dict = pad_token_id lowerCAmelCase : Optional[Any] = bos_token_id lowerCAmelCase : List[str] = initializer_range def lowerCamelCase__ ( self : Dict ): lowerCAmelCase : List[Any] = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size ) lowerCAmelCase : str = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 ) lowerCAmelCase : Tuple = shift_tokens_right(UpperCamelCase_ , 1 , 2 ) lowerCAmelCase : 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=UpperCamelCase_ , ) lowerCAmelCase : Union[str, Any] = prepare_blenderbot_inputs_dict(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) return config, inputs_dict def lowerCamelCase__ ( self : str ): lowerCAmelCase, lowerCAmelCase : Optional[int] = self.prepare_config_and_inputs() return config, inputs_dict def lowerCamelCase__ ( self : List[str] , UpperCamelCase_ : List[str] , UpperCamelCase_ : str , UpperCamelCase_ : Tuple ): lowerCAmelCase : int = 2_0 lowerCAmelCase : Tuple = model_class_name(UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = model.encode(inputs_dict['''input_ids'''] ) lowerCAmelCase, lowerCAmelCase : str = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) lowerCAmelCase : str = model.init_cache(decoder_input_ids.shape[0] , UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : Union[str, Any] = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype='''i4''' ) lowerCAmelCase : Tuple = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) lowerCAmelCase : List[Any] = model.decode( decoder_input_ids[:, :-1] , UpperCamelCase_ , decoder_attention_mask=UpperCamelCase_ , past_key_values=UpperCamelCase_ , decoder_position_ids=UpperCamelCase_ , ) lowerCAmelCase : Any = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) lowerCAmelCase : List[str] = model.decode( decoder_input_ids[:, -1:] , UpperCamelCase_ , decoder_attention_mask=UpperCamelCase_ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=UpperCamelCase_ , ) lowerCAmelCase : Union[str, Any] = model.decode(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : int = 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 lowerCamelCase__ ( self : Union[str, Any] , UpperCamelCase_ : Any , UpperCamelCase_ : Any , UpperCamelCase_ : List[str] ): lowerCAmelCase : Optional[int] = 2_0 lowerCAmelCase : List[Any] = model_class_name(UpperCamelCase_ ) lowerCAmelCase : Union[str, Any] = model.encode(inputs_dict['''input_ids'''] ) lowerCAmelCase, lowerCAmelCase : Optional[int] = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) lowerCAmelCase : str = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) lowerCAmelCase : Union[str, Any] = model.init_cache(decoder_input_ids.shape[0] , UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : str = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) lowerCAmelCase : Dict = model.decode( decoder_input_ids[:, :-1] , UpperCamelCase_ , decoder_attention_mask=UpperCamelCase_ , past_key_values=UpperCamelCase_ , decoder_position_ids=UpperCamelCase_ , ) lowerCAmelCase : Any = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) lowerCAmelCase : Union[str, Any] = model.decode( decoder_input_ids[:, -1:] , UpperCamelCase_ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=UpperCamelCase_ , decoder_position_ids=UpperCamelCase_ , ) lowerCAmelCase : Dict = model.decode(UpperCamelCase_ , UpperCamelCase_ , decoder_attention_mask=UpperCamelCase_ ) lowerCAmelCase : 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 snake_case_( unittest.TestCase ): __UpperCamelCase = 99 def lowerCamelCase__ ( self : str ): lowerCAmelCase : List[Any] = np.array( [ [7_1, 8_2, 1_8, 3_3, 4_6, 9_1, 2], [6_8, 3_4, 2_6, 5_8, 3_0, 8_2, 2], [5, 9_7, 1_7, 3_9, 9_4, 4_0, 2], [7_6, 8_3, 9_4, 2_5, 7_0, 7_8, 2], [8_7, 5_9, 4_1, 3_5, 4_8, 6_6, 2], [5_5, 1_3, 1_6, 5_8, 5, 2, 1], # note padding [6_4, 2_7, 3_1, 5_1, 1_2, 7_5, 2], [5_2, 6_4, 8_6, 1_7, 8_3, 3_9, 2], [4_8, 6_1, 9, 2_4, 7_1, 8_2, 2], [2_6, 1, 6_0, 4_8, 2_2, 1_3, 2], [2_1, 5, 6_2, 2_8, 1_4, 7_6, 2], [4_5, 9_8, 3_7, 8_6, 5_9, 4_8, 2], [7_0, 7_0, 5_0, 9, 2_8, 0, 2], ] , dtype=np.intaa , ) lowerCAmelCase : List[Any] = input_ids.shape[0] lowerCAmelCase : Optional[Any] = BlenderbotConfig( vocab_size=self.vocab_size , d_model=2_4 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=3_2 , decoder_ffn_dim=3_2 , max_position_embeddings=4_8 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size def lowerCamelCase__ ( self : List[str] ): lowerCAmelCase, lowerCAmelCase, lowerCAmelCase : Any = self._get_config_and_data() lowerCAmelCase : Any = FlaxBlenderbotForConditionalGeneration(UpperCamelCase_ ) lowerCAmelCase : Optional[int] = lm_model(input_ids=UpperCamelCase_ ) lowerCAmelCase : Tuple = (batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs['''logits'''].shape , UpperCamelCase_ ) def lowerCamelCase__ ( self : Any ): lowerCAmelCase : Any = BlenderbotConfig( vocab_size=self.vocab_size , d_model=1_4 , 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=4_8 , ) lowerCAmelCase : int = FlaxBlenderbotForConditionalGeneration(UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = np.array([[7_1, 8_2, 1_8, 3_3, 4_6, 9_1, 2], [6_8, 3_4, 2_6, 5_8, 3_0, 2, 1]] , dtype=np.intaa ) lowerCAmelCase : List[str] = np.array([[8_2, 7_1, 8_2, 1_8, 2], [5_8, 6_8, 2, 1, 1]] , dtype=np.intaa ) lowerCAmelCase : List[Any] = lm_model(input_ids=UpperCamelCase_ , decoder_input_ids=UpperCamelCase_ ) lowerCAmelCase : str = (*summary.shape, config.vocab_size) self.assertEqual(outputs['''logits'''].shape , UpperCamelCase_ ) def lowerCamelCase__ ( self : int ): lowerCAmelCase : Any = np.array([[7_1, 8_2, 1_8, 3_3, 2, 1, 1], [6_8, 3_4, 2_6, 5_8, 3_0, 8_2, 2]] , dtype=np.intaa ) lowerCAmelCase : Tuple = shift_tokens_right(UpperCamelCase_ , 1 , 2 ) lowerCAmelCase : Optional[int] = np.equal(UpperCamelCase_ , 1 ).astype(np.floataa ).sum() lowerCAmelCase : str = np.equal(UpperCamelCase_ , 1 ).astype(np.floataa ).sum() self.assertEqual(shifted.shape , input_ids.shape ) self.assertEqual(UpperCamelCase_ , n_pad_before - 1 ) self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() ) @require_flax class snake_case_( a__ , unittest.TestCase , a__ ): __UpperCamelCase = True __UpperCamelCase = ( ( FlaxBlenderbotModel, FlaxBlenderbotForConditionalGeneration, ) if is_flax_available() else () ) __UpperCamelCase = (FlaxBlenderbotForConditionalGeneration,) if is_flax_available() else () def lowerCamelCase__ ( self : Dict ): lowerCAmelCase : Any = FlaxBlenderbotModelTester(self ) def lowerCamelCase__ ( self : Tuple ): lowerCAmelCase, lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) def lowerCamelCase__ ( self : List[str] ): lowerCAmelCase, lowerCAmelCase : Union[str, Any] = 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(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) def lowerCamelCase__ ( self : Tuple ): lowerCAmelCase, lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowerCAmelCase : Optional[int] = self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = model_class(UpperCamelCase_ ) @jax.jit def encode_jitted(UpperCamelCase_ : List[str] , UpperCamelCase_ : Optional[Any]=None , **UpperCamelCase_ : List[str] ): return model.encode(input_ids=UpperCamelCase_ , attention_mask=UpperCamelCase_ ) with self.subTest('''JIT Enabled''' ): lowerCAmelCase : List[str] = encode_jitted(**UpperCamelCase_ ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): lowerCAmelCase : int = encode_jitted(**UpperCamelCase_ ).to_tuple() self.assertEqual(len(UpperCamelCase_ ) , len(UpperCamelCase_ ) ) for jitted_output, output in zip(UpperCamelCase_ , UpperCamelCase_ ): self.assertEqual(jitted_output.shape , output.shape ) def lowerCamelCase__ ( self : Union[str, Any] ): lowerCAmelCase, lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowerCAmelCase : Tuple = model_class(UpperCamelCase_ ) lowerCAmelCase : int = model.encode(inputs_dict['''input_ids'''] , inputs_dict['''attention_mask'''] ) lowerCAmelCase : List[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(UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : Dict , UpperCamelCase_ : int ): return model.decode( decoder_input_ids=UpperCamelCase_ , decoder_attention_mask=UpperCamelCase_ , encoder_outputs=UpperCamelCase_ , ) with self.subTest('''JIT Enabled''' ): lowerCAmelCase : str = decode_jitted(**UpperCamelCase_ ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): lowerCAmelCase : Union[str, Any] = decode_jitted(**UpperCamelCase_ ).to_tuple() self.assertEqual(len(UpperCamelCase_ ) , len(UpperCamelCase_ ) ) for jitted_output, output in zip(UpperCamelCase_ , UpperCamelCase_ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def lowerCamelCase__ ( self : Optional[int] ): for model_class_name in self.all_model_classes: lowerCAmelCase : Optional[int] = model_class_name.from_pretrained('''facebook/blenderbot-400M-distill''' ) # FlaxBlenderbotForSequenceClassification expects eos token in input_ids lowerCAmelCase : int = np.ones((1, 1) ) * model.config.eos_token_id lowerCAmelCase : List[str] = model(UpperCamelCase_ ) self.assertIsNotNone(UpperCamelCase_ ) @unittest.skipUnless(jax_device != '''cpu''' , '''3B test too slow on CPU.''' ) @slow def lowerCamelCase__ ( self : Union[str, Any] ): lowerCAmelCase : Dict = {'''num_beams''': 1, '''early_stopping''': True, '''min_length''': 1_5, '''max_length''': 2_5} lowerCAmelCase : List[str] = {'''skip_special_tokens''': True, '''clean_up_tokenization_spaces''': True} lowerCAmelCase : Tuple = FlaxBlenderbotForConditionalGeneration.from_pretrained('''facebook/blenderbot-3B''' , from_pt=UpperCamelCase_ ) lowerCAmelCase : Union[str, Any] = BlenderbotTokenizer.from_pretrained('''facebook/blenderbot-3B''' ) lowerCAmelCase : List[Any] = ['''Sam'''] lowerCAmelCase : str = tokenizer(UpperCamelCase_ , return_tensors='''jax''' ) lowerCAmelCase : Union[str, Any] = model.generate(**UpperCamelCase_ , **UpperCamelCase_ ) lowerCAmelCase : Tuple = '''Sam is a great name. It means "sun" in Gaelic.''' lowerCAmelCase : Union[str, Any] = tokenizer.batch_decode(UpperCamelCase_ , **UpperCamelCase_ ) assert generated_txt[0].strip() == tgt_text
637
1
"""simple docstring""" from typing import Optional, Union import torch from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention from ...modeling_utils import PreTrainedModel from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging from .configuration_mobilenet_va import MobileNetVaConfig snake_case__ : Dict = logging.get_logger(__name__) # General docstring snake_case__ : int = '''MobileNetV1Config''' # Base docstring snake_case__ : List[str] = '''google/mobilenet_v1_1.0_224''' snake_case__ : List[Any] = [1, 1_024, 7, 7] # Image classification docstring snake_case__ : Optional[int] = '''google/mobilenet_v1_1.0_224''' snake_case__ : List[Any] = '''tabby, tabby cat''' snake_case__ : Any = [ '''google/mobilenet_v1_1.0_224''', '''google/mobilenet_v1_0.75_192''', # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1 ] def _snake_case ( _snake_case : int , _snake_case : Tuple , _snake_case : Union[str, Any]=None ): lowerCAmelCase : str = {} if isinstance(_snake_case , _snake_case ): lowerCAmelCase : Union[str, Any] = model.mobilenet_va else: lowerCAmelCase : Optional[int] = model lowerCAmelCase : Dict = '''MobilenetV1/Conv2d_0/''' lowerCAmelCase : int = backbone.conv_stem.convolution.weight lowerCAmelCase : Dict = backbone.conv_stem.normalization.bias lowerCAmelCase : str = backbone.conv_stem.normalization.weight lowerCAmelCase : int = backbone.conv_stem.normalization.running_mean lowerCAmelCase : Dict = backbone.conv_stem.normalization.running_var for i in range(13 ): lowerCAmelCase : int = i + 1 lowerCAmelCase : Optional[int] = i * 2 lowerCAmelCase : List[Any] = backbone.layer[pt_index] lowerCAmelCase : Union[str, Any] = f'''MobilenetV1/Conv2d_{tf_index}_depthwise/''' lowerCAmelCase : Dict = pointer.convolution.weight lowerCAmelCase : int = pointer.normalization.bias lowerCAmelCase : str = pointer.normalization.weight lowerCAmelCase : Any = pointer.normalization.running_mean lowerCAmelCase : Union[str, Any] = pointer.normalization.running_var lowerCAmelCase : Dict = backbone.layer[pt_index + 1] lowerCAmelCase : List[Any] = f'''MobilenetV1/Conv2d_{tf_index}_pointwise/''' lowerCAmelCase : str = pointer.convolution.weight lowerCAmelCase : Any = pointer.normalization.bias lowerCAmelCase : Tuple = pointer.normalization.weight lowerCAmelCase : Optional[int] = pointer.normalization.running_mean lowerCAmelCase : Tuple = pointer.normalization.running_var if isinstance(_snake_case , _snake_case ): lowerCAmelCase : Optional[Any] = '''MobilenetV1/Logits/Conv2d_1c_1x1/''' lowerCAmelCase : List[Any] = model.classifier.weight lowerCAmelCase : int = model.classifier.bias return tf_to_pt_map def _snake_case ( _snake_case : int , _snake_case : Dict , _snake_case : List[str] ): try: import numpy as np import tensorflow as tf except ImportError: logger.error( '''Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see ''' '''https://www.tensorflow.org/install/ for installation instructions.''' ) raise # Load weights from TF model lowerCAmelCase : Any = tf.train.list_variables(_snake_case ) lowerCAmelCase : Tuple = {} for name, shape in init_vars: logger.info(f'''Loading TF weight {name} with shape {shape}''' ) lowerCAmelCase : Any = tf.train.load_variable(_snake_case , _snake_case ) lowerCAmelCase : Tuple = array # Build TF to PyTorch weights loading map lowerCAmelCase : Optional[int] = _build_tf_to_pytorch_map(_snake_case , _snake_case , _snake_case ) for name, pointer in tf_to_pt_map.items(): logger.info(f'''Importing {name}''' ) if name not in tf_weights: logger.info(f'''{name} not in tf pre-trained weights, skipping''' ) continue lowerCAmelCase : Any = tf_weights[name] if "depthwise_weights" in name: logger.info('''Transposing depthwise''' ) lowerCAmelCase : str = np.transpose(_snake_case , (2, 3, 0, 1) ) elif "weights" in name: logger.info('''Transposing''' ) if len(pointer.shape ) == 2: # copying into linear layer lowerCAmelCase : Optional[Any] = array.squeeze().transpose() else: lowerCAmelCase : Dict = np.transpose(_snake_case , (3, 2, 0, 1) ) if pointer.shape != array.shape: raise ValueError(f'''Pointer shape {pointer.shape} and array shape {array.shape} mismatched''' ) logger.info(f'''Initialize PyTorch weight {name} {array.shape}''' ) lowerCAmelCase : Union[str, Any] = torch.from_numpy(_snake_case ) tf_weights.pop(_snake_case , _snake_case ) tf_weights.pop(name + '''/RMSProp''' , _snake_case ) tf_weights.pop(name + '''/RMSProp_1''' , _snake_case ) tf_weights.pop(name + '''/ExponentialMovingAverage''' , _snake_case ) logger.info(f'''Weights not copied to PyTorch model: {", ".join(tf_weights.keys() )}''' ) return model def _snake_case ( _snake_case : torch.Tensor , _snake_case : nn.Convad ): lowerCAmelCase, lowerCAmelCase : List[Any] = features.shape[-2:] lowerCAmelCase, lowerCAmelCase : str = conv_layer.stride lowerCAmelCase, lowerCAmelCase : Optional[int] = conv_layer.kernel_size if in_height % stride_height == 0: lowerCAmelCase : List[Any] = max(kernel_height - stride_height , 0 ) else: lowerCAmelCase : int = max(kernel_height - (in_height % stride_height) , 0 ) if in_width % stride_width == 0: lowerCAmelCase : Union[str, Any] = max(kernel_width - stride_width , 0 ) else: lowerCAmelCase : Optional[int] = max(kernel_width - (in_width % stride_width) , 0 ) lowerCAmelCase : Tuple = pad_along_width // 2 lowerCAmelCase : Dict = pad_along_width - pad_left lowerCAmelCase : str = pad_along_height // 2 lowerCAmelCase : Dict = pad_along_height - pad_top lowerCAmelCase : Any = (pad_left, pad_right, pad_top, pad_bottom) return nn.functional.pad(_snake_case , _snake_case , '''constant''' , 0.0 ) class snake_case_( nn.Module ): def __init__( self : Optional[Any] , UpperCamelCase_ : MobileNetVaConfig , UpperCamelCase_ : int , UpperCamelCase_ : int , UpperCamelCase_ : int , UpperCamelCase_ : Optional[int] = 1 , UpperCamelCase_ : Optional[int] = 1 , UpperCamelCase_ : bool = False , UpperCamelCase_ : Optional[bool] = True , UpperCamelCase_ : Optional[bool or str] = True , ): super().__init__() lowerCAmelCase : Any = config if in_channels % groups != 0: raise ValueError(F'''Input channels ({in_channels}) are not divisible by {groups} groups.''' ) if out_channels % groups != 0: raise ValueError(F'''Output channels ({out_channels}) are not divisible by {groups} groups.''' ) lowerCAmelCase : Any = 0 if config.tf_padding else int((kernel_size - 1) / 2 ) lowerCAmelCase : Tuple = nn.Convad( in_channels=UpperCamelCase_ , out_channels=UpperCamelCase_ , kernel_size=UpperCamelCase_ , stride=UpperCamelCase_ , padding=UpperCamelCase_ , groups=UpperCamelCase_ , bias=UpperCamelCase_ , padding_mode='''zeros''' , ) if use_normalization: lowerCAmelCase : str = nn.BatchNormad( num_features=UpperCamelCase_ , eps=config.layer_norm_eps , momentum=0.9_997 , affine=UpperCamelCase_ , track_running_stats=UpperCamelCase_ , ) else: lowerCAmelCase : Optional[Any] = None if use_activation: if isinstance(UpperCamelCase_ , UpperCamelCase_ ): lowerCAmelCase : Tuple = ACTaFN[use_activation] elif isinstance(config.hidden_act , UpperCamelCase_ ): lowerCAmelCase : Any = ACTaFN[config.hidden_act] else: lowerCAmelCase : Union[str, Any] = config.hidden_act else: lowerCAmelCase : List[str] = None def lowerCamelCase__ ( self : Dict , UpperCamelCase_ : torch.Tensor ): if self.config.tf_padding: lowerCAmelCase : List[Any] = apply_tf_padding(UpperCamelCase_ , self.convolution ) lowerCAmelCase : Dict = self.convolution(UpperCamelCase_ ) if self.normalization is not None: lowerCAmelCase : Dict = self.normalization(UpperCamelCase_ ) if self.activation is not None: lowerCAmelCase : Any = self.activation(UpperCamelCase_ ) return features class snake_case_( a__ ): __UpperCamelCase = MobileNetVaConfig __UpperCamelCase = load_tf_weights_in_mobilenet_va __UpperCamelCase = '''mobilenet_v1''' __UpperCamelCase = '''pixel_values''' __UpperCamelCase = False def lowerCamelCase__ ( self : Optional[Any] , UpperCamelCase_ : Union[nn.Linear, nn.Convad] ): if isinstance(UpperCamelCase_ , (nn.Linear, nn.Convad) ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() elif isinstance(UpperCamelCase_ , nn.BatchNormad ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) snake_case__ : Optional[Any] = R''' This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. ''' snake_case__ : List[str] = R''' Args: pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`MobileNetV1ImageProcessor.__call__`] for details. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. ''' @add_start_docstrings( '''The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.''' , a__ , ) class snake_case_( a__ ): def __init__( self : Dict , UpperCamelCase_ : MobileNetVaConfig , UpperCamelCase_ : bool = True ): super().__init__(UpperCamelCase_ ) lowerCAmelCase : Any = config lowerCAmelCase : List[Any] = 3_2 lowerCAmelCase : Optional[Any] = max(int(depth * config.depth_multiplier ) , config.min_depth ) lowerCAmelCase : List[Any] = MobileNetVaConvLayer( UpperCamelCase_ , in_channels=config.num_channels , out_channels=UpperCamelCase_ , kernel_size=3 , stride=2 , ) lowerCAmelCase : Any = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1] lowerCAmelCase : Optional[int] = nn.ModuleList() for i in range(1_3 ): lowerCAmelCase : List[Any] = out_channels if strides[i] == 2 or i == 0: depth *= 2 lowerCAmelCase : List[Any] = max(int(depth * config.depth_multiplier ) , config.min_depth ) self.layer.append( MobileNetVaConvLayer( UpperCamelCase_ , in_channels=UpperCamelCase_ , out_channels=UpperCamelCase_ , kernel_size=3 , stride=strides[i] , groups=UpperCamelCase_ , ) ) self.layer.append( MobileNetVaConvLayer( UpperCamelCase_ , in_channels=UpperCamelCase_ , out_channels=UpperCamelCase_ , kernel_size=1 , ) ) lowerCAmelCase : str = nn.AdaptiveAvgPoolad((1, 1) ) if add_pooling_layer else None # Initialize weights and apply final processing self.post_init() def lowerCamelCase__ ( self : int , UpperCamelCase_ : Dict ): raise NotImplementedError @add_start_docstrings_to_model_forward(UpperCamelCase_ ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=UpperCamelCase_ , config_class=_CONFIG_FOR_DOC , modality='''vision''' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def lowerCamelCase__ ( self : Union[str, Any] , UpperCamelCase_ : Optional[torch.Tensor] = None , UpperCamelCase_ : Optional[bool] = None , UpperCamelCase_ : Optional[bool] = None , ): lowerCAmelCase : List[Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) lowerCAmelCase : Tuple = return_dict if return_dict is not None else self.config.use_return_dict if pixel_values is None: raise ValueError('''You have to specify pixel_values''' ) lowerCAmelCase : str = self.conv_stem(UpperCamelCase_ ) lowerCAmelCase : Tuple = () if output_hidden_states else None for i, layer_module in enumerate(self.layer ): lowerCAmelCase : Optional[int] = layer_module(UpperCamelCase_ ) if output_hidden_states: lowerCAmelCase : Union[str, Any] = all_hidden_states + (hidden_states,) lowerCAmelCase : Any = hidden_states if self.pooler is not None: lowerCAmelCase : int = torch.flatten(self.pooler(UpperCamelCase_ ) , start_dim=1 ) else: lowerCAmelCase : Any = None if not return_dict: return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None ) return BaseModelOutputWithPoolingAndNoAttention( last_hidden_state=UpperCamelCase_ , pooler_output=UpperCamelCase_ , hidden_states=UpperCamelCase_ , ) @add_start_docstrings( ''' MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. ''' , a__ , ) class snake_case_( a__ ): def __init__( self : Optional[Any] , UpperCamelCase_ : MobileNetVaConfig ): super().__init__(UpperCamelCase_ ) lowerCAmelCase : int = config.num_labels lowerCAmelCase : Union[str, Any] = MobileNetVaModel(UpperCamelCase_ ) lowerCAmelCase : Union[str, Any] = self.mobilenet_va.layer[-1].convolution.out_channels # Classifier head lowerCAmelCase : List[str] = nn.Dropout(config.classifier_dropout_prob , inplace=UpperCamelCase_ ) lowerCAmelCase : Optional[int] = nn.Linear(UpperCamelCase_ , config.num_labels ) if config.num_labels > 0 else nn.Identity() # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UpperCamelCase_ ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=UpperCamelCase_ , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def lowerCamelCase__ ( self : Dict , UpperCamelCase_ : Optional[torch.Tensor] = None , UpperCamelCase_ : Optional[bool] = None , UpperCamelCase_ : Optional[torch.Tensor] = None , UpperCamelCase_ : Optional[bool] = None , ): lowerCAmelCase : Optional[Any] = return_dict if return_dict is not None else self.config.use_return_dict lowerCAmelCase : int = self.mobilenet_va(UpperCamelCase_ , output_hidden_states=UpperCamelCase_ , return_dict=UpperCamelCase_ ) lowerCAmelCase : int = outputs.pooler_output if return_dict else outputs[1] lowerCAmelCase : Optional[int] = self.classifier(self.dropout(UpperCamelCase_ ) ) lowerCAmelCase : Union[str, Any] = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: lowerCAmelCase : int = '''regression''' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): lowerCAmelCase : Union[str, Any] = '''single_label_classification''' else: lowerCAmelCase : Any = '''multi_label_classification''' if self.config.problem_type == "regression": lowerCAmelCase : Tuple = MSELoss() if self.num_labels == 1: lowerCAmelCase : int = loss_fct(logits.squeeze() , labels.squeeze() ) else: lowerCAmelCase : Union[str, Any] = loss_fct(UpperCamelCase_ , UpperCamelCase_ ) elif self.config.problem_type == "single_label_classification": lowerCAmelCase : Union[str, Any] = CrossEntropyLoss() lowerCAmelCase : int = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": lowerCAmelCase : Any = BCEWithLogitsLoss() lowerCAmelCase : Tuple = loss_fct(UpperCamelCase_ , UpperCamelCase_ ) if not return_dict: lowerCAmelCase : Tuple = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention( loss=UpperCamelCase_ , logits=UpperCamelCase_ , hidden_states=outputs.hidden_states , )
637
"""simple docstring""" from __future__ import annotations from PIL import Image # Define glider example snake_case__ : int = [ [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 snake_case__ : Any = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] def _snake_case ( _snake_case : list[list[int]] ): lowerCAmelCase : Union[str, Any] = [] for i in range(len(_snake_case ) ): lowerCAmelCase : Any = [] for j in range(len(cells[i] ) ): # Get the number of live neighbours lowerCAmelCase : Optional[int] = 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(_snake_case ) - 1 and j > 0: neighbour_count += cells[i + 1][j - 1] if i < len(_snake_case ) - 1: neighbour_count += cells[i + 1][j] if i < len(_snake_case ) - 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. lowerCAmelCase : str = 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(_snake_case ) return next_generation def _snake_case ( _snake_case : list[list[int]] , _snake_case : int ): lowerCAmelCase : int = [] for _ in range(_snake_case ): # Create output image lowerCAmelCase : Union[str, Any] = Image.new('''RGB''' , (len(cells[0] ), len(_snake_case )) ) lowerCAmelCase : Union[str, Any] = img.load() # Save cells to image for x in range(len(_snake_case ) ): for y in range(len(cells[0] ) ): lowerCAmelCase : Optional[int] = 255 - cells[y][x] * 255 lowerCAmelCase : List[Any] = (colour, colour, colour) # Save image images.append(_snake_case ) lowerCAmelCase : Union[str, Any] = new_generation(_snake_case ) return images if __name__ == "__main__": snake_case__ : Union[str, Any] = generate_images(GLIDER, 16) images[0].save('''out.gif''', save_all=True, append_images=images[1:])
637
1
"""simple docstring""" import argparse import json import os import fairseq import torch from fairseq.data import Dictionary # Register SEW's fairseq modules from sew_asapp import tasks # noqa: F401 from transformers import ( SEWConfig, SEWForCTC, SEWModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() snake_case__ : Optional[Any] = logging.get_logger(__name__) snake_case__ : List[Any] = { '''post_extract_proj''': '''feature_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.upsample.0''': '''encoder.upsample.projection''', '''encoder.layer_norm''': '''encoder.layer_norm''', '''w2v_model.layer_norm''': '''layer_norm''', '''w2v_encoder.proj''': '''lm_head''', '''mask_emb''': '''masked_spec_embed''', } def _snake_case ( _snake_case : str , _snake_case : Optional[int] , _snake_case : Optional[Any] , _snake_case : List[str] , _snake_case : Any ): for attribute in key.split('''.''' ): lowerCAmelCase : Tuple = getattr(_snake_case , _snake_case ) if weight_type is not None: lowerCAmelCase : int = getattr(_snake_case , _snake_case ).shape else: lowerCAmelCase : List[str] = 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": lowerCAmelCase : Any = value elif weight_type == "weight_g": lowerCAmelCase : Optional[Any] = value elif weight_type == "weight_v": lowerCAmelCase : Any = value elif weight_type == "bias": lowerCAmelCase : Optional[int] = value else: lowerCAmelCase : str = value logger.info(f'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' ) def _snake_case ( _snake_case : Dict , _snake_case : Dict , _snake_case : Tuple ): lowerCAmelCase : int = [] lowerCAmelCase : Dict = fairseq_model.state_dict() lowerCAmelCase : List[str] = hf_model.sew.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): lowerCAmelCase : Optional[int] = False if "conv_layers" in name: load_conv_layer( _snake_case , _snake_case , _snake_case , _snake_case , hf_model.config.feat_extract_norm == '''group''' , ) lowerCAmelCase : Union[str, Any] = True else: for key, mapped_key in MAPPING.items(): lowerCAmelCase : Tuple = '''sew.''' + mapped_key if (is_finetuned and mapped_key != '''lm_head''') else mapped_key if key in name or key.split('''w2v_model.''' )[-1] == name.split('''.''' )[0]: lowerCAmelCase : int = True if "*" in mapped_key: lowerCAmelCase : Optional[Any] = name.split(_snake_case )[0].split('''.''' )[-2] lowerCAmelCase : Optional[Any] = mapped_key.replace('''*''' , _snake_case ) if "weight_g" in name: lowerCAmelCase : Union[str, Any] = '''weight_g''' elif "weight_v" in name: lowerCAmelCase : List[Any] = '''weight_v''' elif "weight" in name: lowerCAmelCase : Any = '''weight''' elif "bias" in name: lowerCAmelCase : Optional[Any] = '''bias''' else: lowerCAmelCase : List[Any] = None set_recursively(_snake_case , _snake_case , _snake_case , _snake_case , _snake_case ) continue if not is_used: unused_weights.append(_snake_case ) logger.warning(f'''Unused weights: {unused_weights}''' ) def _snake_case ( _snake_case : Dict , _snake_case : str , _snake_case : List[Any] , _snake_case : List[Any] , _snake_case : Tuple ): lowerCAmelCase : str = full_name.split('''conv_layers.''' )[-1] lowerCAmelCase : str = name.split('''.''' ) lowerCAmelCase : Tuple = int(items[0] ) lowerCAmelCase : Any = 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.''' ) lowerCAmelCase : 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.''' ) lowerCAmelCase : Tuple = 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." ) lowerCAmelCase : Dict = 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.''' ) lowerCAmelCase : Optional[Any] = value logger.info(f'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(_snake_case ) def _snake_case ( _snake_case : Tuple , _snake_case : Optional[int] ): lowerCAmelCase : Tuple = SEWConfig() if is_finetuned: lowerCAmelCase : Optional[Any] = model.wav_encoder.wav_model.cfg else: lowerCAmelCase : Dict = model.cfg lowerCAmelCase : int = fs_config.conv_bias lowerCAmelCase : Any = eval(fs_config.conv_feature_layers ) lowerCAmelCase : Optional[int] = [x[0] for x in conv_layers] lowerCAmelCase : Any = [x[1] for x in conv_layers] lowerCAmelCase : Optional[int] = [x[2] for x in conv_layers] lowerCAmelCase : Optional[int] = '''gelu''' lowerCAmelCase : str = '''layer''' if fs_config.extractor_mode == '''layer_norm''' else '''group''' lowerCAmelCase : List[str] = 0.0 lowerCAmelCase : Optional[int] = fs_config.activation_fn.name lowerCAmelCase : int = fs_config.encoder_embed_dim lowerCAmelCase : List[str] = 0.02 lowerCAmelCase : Any = fs_config.encoder_ffn_embed_dim lowerCAmelCase : Optional[int] = 1E-5 lowerCAmelCase : List[str] = fs_config.encoder_layerdrop lowerCAmelCase : Dict = fs_config.encoder_attention_heads lowerCAmelCase : Dict = fs_config.conv_pos_groups lowerCAmelCase : Union[str, Any] = fs_config.conv_pos lowerCAmelCase : Tuple = len(_snake_case ) lowerCAmelCase : str = fs_config.encoder_layers lowerCAmelCase : str = fs_config.squeeze_factor # take care of any params that are overridden by the Wav2VecCtc model if is_finetuned: lowerCAmelCase : int = model.cfg lowerCAmelCase : List[Any] = fs_config.final_dropout lowerCAmelCase : Optional[int] = fs_config.layerdrop lowerCAmelCase : Union[str, Any] = fs_config.activation_dropout lowerCAmelCase : Union[str, Any] = fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0 lowerCAmelCase : Union[str, Any] = fs_config.attention_dropout lowerCAmelCase : str = fs_config.dropout_input lowerCAmelCase : List[Any] = fs_config.dropout lowerCAmelCase : Union[str, Any] = fs_config.mask_channel_length lowerCAmelCase : Tuple = fs_config.mask_channel_prob lowerCAmelCase : str = fs_config.mask_length lowerCAmelCase : str = fs_config.mask_prob lowerCAmelCase : List[str] = '''Wav2Vec2FeatureExtractor''' lowerCAmelCase : Any = '''Wav2Vec2CTCTokenizer''' return config @torch.no_grad() def _snake_case ( _snake_case : int , _snake_case : Dict , _snake_case : int=None , _snake_case : List[str]=None , _snake_case : List[Any]=True ): if is_finetuned: lowerCAmelCase, lowerCAmelCase, lowerCAmelCase : List[str] = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={'''data''': '''/'''.join(dict_path.split('''/''' )[:-1] )} ) else: lowerCAmelCase, lowerCAmelCase, lowerCAmelCase : Optional[Any] = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) if config_path is not None: lowerCAmelCase : str = SEWConfig.from_pretrained(_snake_case ) else: lowerCAmelCase : str = convert_config(model[0] , _snake_case ) lowerCAmelCase : Optional[int] = model[0].eval() lowerCAmelCase : Union[str, Any] = True if config.feat_extract_norm == '''layer''' else False lowerCAmelCase : int = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=_snake_case , return_attention_mask=_snake_case , ) if is_finetuned: if dict_path: lowerCAmelCase : Dict = Dictionary.load(_snake_case ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq lowerCAmelCase : str = target_dict.pad_index lowerCAmelCase : str = target_dict.bos_index lowerCAmelCase : str = target_dict.pad_index lowerCAmelCase : Optional[Any] = target_dict.bos_index lowerCAmelCase : int = target_dict.eos_index lowerCAmelCase : List[Any] = len(target_dict.symbols ) lowerCAmelCase : Union[str, Any] = os.path.join(_snake_case , '''vocab.json''' ) if not os.path.isdir(_snake_case ): logger.error('''--pytorch_dump_folder_path ({}) should be a directory'''.format(_snake_case ) ) return os.makedirs(_snake_case , exist_ok=_snake_case ) with open(_snake_case , '''w''' , encoding='''utf-8''' ) as vocab_handle: json.dump(target_dict.indices , _snake_case ) lowerCAmelCase : str = WavaVecaCTCTokenizer( _snake_case , 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=_snake_case , ) lowerCAmelCase : Optional[int] = WavaVecaProcessor(feature_extractor=_snake_case , tokenizer=_snake_case ) processor.save_pretrained(_snake_case ) lowerCAmelCase : List[str] = SEWForCTC(_snake_case ) else: lowerCAmelCase : List[str] = SEWModel(_snake_case ) feature_extractor.save_pretrained(_snake_case ) recursively_load_weights(_snake_case , _snake_case , _snake_case ) hf_model.save_pretrained(_snake_case ) if __name__ == "__main__": snake_case__ : Tuple = 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( '''--is_finetuned''', action='''store_true''', help='''Whether the model to convert is a fine-tuned model or not''' ) snake_case__ : Union[str, Any] = parser.parse_args() convert_sew_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, args.is_finetuned )
637
"""simple docstring""" from __future__ import annotations class snake_case_: def __init__( self : int , UpperCamelCase_ : str , UpperCamelCase_ : str ): lowerCAmelCase, lowerCAmelCase : List[str] = text, pattern lowerCAmelCase, lowerCAmelCase : Union[str, Any] = len(UpperCamelCase_ ), len(UpperCamelCase_ ) def lowerCamelCase__ ( self : List[Any] , UpperCamelCase_ : str ): for i in range(self.patLen - 1 , -1 , -1 ): if char == self.pattern[i]: return i return -1 def lowerCamelCase__ ( self : Optional[Any] , UpperCamelCase_ : int ): for i in range(self.patLen - 1 , -1 , -1 ): if self.pattern[i] != self.text[current_pos + i]: return current_pos + i return -1 def lowerCamelCase__ ( self : Dict ): # searches pattern in text and returns index positions lowerCAmelCase : Union[str, Any] = [] for i in range(self.textLen - self.patLen + 1 ): lowerCAmelCase : str = self.mismatch_in_text(UpperCamelCase_ ) if mismatch_index == -1: positions.append(UpperCamelCase_ ) else: lowerCAmelCase : Optional[Any] = self.match_in_pattern(self.text[mismatch_index] ) lowerCAmelCase : int = ( mismatch_index - match_index ) # shifting index lgtm [py/multiple-definition] return positions snake_case__ : str = '''ABAABA''' snake_case__ : List[str] = '''AB''' snake_case__ : Union[str, Any] = BoyerMooreSearch(text, pattern) snake_case__ : Optional[Any] = bms.bad_character_heuristic() if len(positions) == 0: print('''No match found''') else: print('''Pattern found in following positions: ''') print(positions)
637
1
"""simple docstring""" from collections.abc import Generator from math import sin def _snake_case ( _snake_case : bytes ): if len(_snake_case ) != 32: raise ValueError('''Input must be of length 32''' ) lowerCAmelCase : Any = B'''''' for i in [3, 2, 1, 0]: little_endian += string_aa[8 * i : 8 * i + 8] return little_endian def _snake_case ( _snake_case : int ): if i < 0: raise ValueError('''Input must be non-negative''' ) lowerCAmelCase : List[Any] = format(_snake_case , '''08x''' )[-8:] lowerCAmelCase : Tuple = B'''''' for i in [3, 2, 1, 0]: little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode('''utf-8''' ) return little_endian_hex def _snake_case ( _snake_case : bytes ): lowerCAmelCase : Dict = B'''''' for char in message: bit_string += format(_snake_case , '''08b''' ).encode('''utf-8''' ) lowerCAmelCase : Dict = format(len(_snake_case ) , '''064b''' ).encode('''utf-8''' ) # Pad bit_string to a multiple of 512 chars bit_string += b"1" while len(_snake_case ) % 512 != 448: bit_string += b"0" bit_string += to_little_endian(start_len[32:] ) + to_little_endian(start_len[:32] ) return bit_string def _snake_case ( _snake_case : bytes ): if len(_snake_case ) % 512 != 0: raise ValueError('''Input must have length that\'s a multiple of 512''' ) for pos in range(0 , len(_snake_case ) , 512 ): lowerCAmelCase : Optional[Any] = bit_string[pos : pos + 512] lowerCAmelCase : Tuple = [] for i in range(0 , 512 , 32 ): block_words.append(int(to_little_endian(block[i : i + 32] ) , 2 ) ) yield block_words def _snake_case ( _snake_case : int ): if i < 0: raise ValueError('''Input must be non-negative''' ) lowerCAmelCase : List[str] = format(_snake_case , '''032b''' ) lowerCAmelCase : Optional[Any] = '''''' for c in i_str: new_str += "1" if c == "0" else "0" return int(_snake_case , 2 ) def _snake_case ( _snake_case : int , _snake_case : int ): return (a + b) % 2**32 def _snake_case ( _snake_case : int , _snake_case : int ): if i < 0: raise ValueError('''Input must be non-negative''' ) if shift < 0: raise ValueError('''Shift must be non-negative''' ) return ((i << shift) ^ (i >> (32 - shift))) % 2**32 def _snake_case ( _snake_case : bytes ): lowerCAmelCase : List[Any] = preprocess(_snake_case ) lowerCAmelCase : Union[str, Any] = [int(2**32 * abs(sin(i + 1 ) ) ) for i in range(64 )] # Starting states lowerCAmelCase : int = 0X6745_2301 lowerCAmelCase : List[str] = 0Xefcd_ab89 lowerCAmelCase : Union[str, Any] = 0X98ba_dcfe lowerCAmelCase : Any = 0X1032_5476 lowerCAmelCase : Optional[Any] = [ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, ] # Process bit string in chunks, each with 16 32-char words for block_words in get_block_words(_snake_case ): lowerCAmelCase : str = aa lowerCAmelCase : str = ba lowerCAmelCase : List[Any] = ca lowerCAmelCase : int = da # Hash current chunk for i in range(64 ): if i <= 15: # f = (b & c) | (not_32(b) & d) # Alternate definition for f lowerCAmelCase : int = d ^ (b & (c ^ d)) lowerCAmelCase : Dict = i elif i <= 31: # f = (d & b) | (not_32(d) & c) # Alternate definition for f lowerCAmelCase : List[Any] = c ^ (d & (b ^ c)) lowerCAmelCase : Tuple = (5 * i + 1) % 16 elif i <= 47: lowerCAmelCase : Any = b ^ c ^ d lowerCAmelCase : int = (3 * i + 5) % 16 else: lowerCAmelCase : Any = c ^ (b | not_aa(_snake_case )) lowerCAmelCase : Tuple = (7 * i) % 16 lowerCAmelCase : List[Any] = (f + a + added_consts[i] + block_words[g]) % 2**32 lowerCAmelCase : Optional[int] = d lowerCAmelCase : Tuple = c lowerCAmelCase : Union[str, Any] = b lowerCAmelCase : List[Any] = sum_aa(_snake_case , left_rotate_aa(_snake_case , shift_amounts[i] ) ) # Add hashed chunk to running total lowerCAmelCase : Dict = sum_aa(_snake_case , _snake_case ) lowerCAmelCase : Tuple = sum_aa(_snake_case , _snake_case ) lowerCAmelCase : Union[str, Any] = sum_aa(_snake_case , _snake_case ) lowerCAmelCase : List[Any] = sum_aa(_snake_case , _snake_case ) lowerCAmelCase : str = reformat_hex(_snake_case ) + reformat_hex(_snake_case ) + reformat_hex(_snake_case ) + reformat_hex(_snake_case ) return digest if __name__ == "__main__": import doctest doctest.testmod()
637
"""simple docstring""" from __future__ import annotations from typing import Any class snake_case_( a__ ): pass class snake_case_: def __init__( self : Any , UpperCamelCase_ : Any ): lowerCAmelCase : Any = data lowerCAmelCase : Node | None = None def __iter__( self : int ): lowerCAmelCase : Any = self lowerCAmelCase : Union[str, Any] = [] while node: if node in visited: raise ContainsLoopError visited.append(UpperCamelCase_ ) yield node.data lowerCAmelCase : Optional[int] = node.next_node @property def lowerCamelCase__ ( self : str ): try: list(self ) return False except ContainsLoopError: return True if __name__ == "__main__": snake_case__ : Dict = Node(1) snake_case__ : Any = Node(2) snake_case__ : int = Node(3) snake_case__ : Any = Node(4) print(root_node.has_loop) # False snake_case__ : Tuple = root_node.next_node print(root_node.has_loop) # True snake_case__ : List[Any] = Node(5) snake_case__ : int = Node(6) snake_case__ : List[Any] = Node(5) snake_case__ : Dict = Node(6) print(root_node.has_loop) # False snake_case__ : Any = Node(1) print(root_node.has_loop) # False
637
1
"""simple docstring""" class snake_case_: def __init__( self : Union[str, Any] , UpperCamelCase_ : str ): lowerCAmelCase : Dict = val lowerCAmelCase : str = None lowerCAmelCase : Dict = None def lowerCamelCase__ ( self : Union[str, Any] , UpperCamelCase_ : Dict ): if self.val: if val < self.val: if self.left is None: lowerCAmelCase : int = Node(UpperCamelCase_ ) else: self.left.insert(UpperCamelCase_ ) elif val > self.val: if self.right is None: lowerCAmelCase : Any = Node(UpperCamelCase_ ) else: self.right.insert(UpperCamelCase_ ) else: lowerCAmelCase : Optional[Any] = val def _snake_case ( _snake_case : Tuple , _snake_case : str ): # Recursive traversal if root: inorder(root.left , _snake_case ) res.append(root.val ) inorder(root.right , _snake_case ) def _snake_case ( _snake_case : Optional[Any] ): # Build BST if len(_snake_case ) == 0: return arr lowerCAmelCase : Optional[Any] = Node(arr[0] ) for i in range(1 , len(_snake_case ) ): root.insert(arr[i] ) # Traverse BST in order. lowerCAmelCase : Optional[int] = [] inorder(_snake_case , _snake_case ) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
637
"""simple docstring""" from torch import nn class snake_case_( nn.Module ): def __init__( self : int , UpperCamelCase_ : int , UpperCamelCase_ : int ): super().__init__() lowerCAmelCase : str = class_size lowerCAmelCase : Dict = embed_size # self.mlp1 = nn.Linear(embed_size, embed_size) # self.mlp2 = (nn.Linear(embed_size, class_size)) lowerCAmelCase : Any = nn.Linear(UpperCamelCase_ , UpperCamelCase_ ) def lowerCamelCase__ ( self : List[Any] , UpperCamelCase_ : Tuple ): # hidden_state = nn.functional.relu(self.mlp1(hidden_state)) # hidden_state = self.mlp2(hidden_state) lowerCAmelCase : int = self.mlp(UpperCamelCase_ ) return logits
637
1
"""simple docstring""" import warnings from ..trainer import Trainer from ..utils import logging snake_case__ : List[str] = logging.get_logger(__name__) class snake_case_( a__ ): def __init__( self : int , UpperCamelCase_ : Tuple=None , **UpperCamelCase_ : List[str] ): warnings.warn( '''`SageMakerTrainer` is deprecated and will be removed in v5 of Transformers. You can use `Trainer` ''' '''instead.''' , UpperCamelCase_ , ) super().__init__(args=UpperCamelCase_ , **UpperCamelCase_ )
637
"""simple docstring""" class snake_case_: def __init__( self : Union[str, Any] , UpperCamelCase_ : str ): lowerCAmelCase : Dict = val lowerCAmelCase : str = None lowerCAmelCase : Dict = None def lowerCamelCase__ ( self : Union[str, Any] , UpperCamelCase_ : Dict ): if self.val: if val < self.val: if self.left is None: lowerCAmelCase : int = Node(UpperCamelCase_ ) else: self.left.insert(UpperCamelCase_ ) elif val > self.val: if self.right is None: lowerCAmelCase : Any = Node(UpperCamelCase_ ) else: self.right.insert(UpperCamelCase_ ) else: lowerCAmelCase : Optional[Any] = val def _snake_case ( _snake_case : Tuple , _snake_case : str ): # Recursive traversal if root: inorder(root.left , _snake_case ) res.append(root.val ) inorder(root.right , _snake_case ) def _snake_case ( _snake_case : Optional[Any] ): # Build BST if len(_snake_case ) == 0: return arr lowerCAmelCase : Optional[Any] = Node(arr[0] ) for i in range(1 , len(_snake_case ) ): root.insert(arr[i] ) # Traverse BST in order. lowerCAmelCase : Optional[int] = [] inorder(_snake_case , _snake_case ) return res if __name__ == "__main__": print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
637
1
"""simple docstring""" def _snake_case ( _snake_case : str ): lowerCAmelCase : str = '''''' for ch in key: if ch == " " or ch not in key_no_dups and ch.isalpha(): key_no_dups += ch return key_no_dups def _snake_case ( _snake_case : str ): lowerCAmelCase : Tuple = [chr(i + 65 ) for i in range(26 )] # Remove duplicate characters from key lowerCAmelCase : Union[str, Any] = remove_duplicates(key.upper() ) lowerCAmelCase : str = len(_snake_case ) # First fill cipher with key characters lowerCAmelCase : Optional[Any] = {alphabet[i]: char for i, char in enumerate(_snake_case )} # Then map remaining characters in alphabet to # the alphabet from the beginning for i in range(len(_snake_case ) , 26 ): lowerCAmelCase : Optional[Any] = alphabet[i - offset] # Ensure we are not mapping letters to letters previously mapped while char in key: offset -= 1 lowerCAmelCase : int = alphabet[i - offset] lowerCAmelCase : Optional[int] = char return cipher_alphabet def _snake_case ( _snake_case : str , _snake_case : dict[str, str] ): return "".join(cipher_map.get(_snake_case , _snake_case ) for ch in message.upper() ) def _snake_case ( _snake_case : str , _snake_case : dict[str, str] ): lowerCAmelCase : List[Any] = {v: k for k, v in cipher_map.items()} return "".join(rev_cipher_map.get(_snake_case , _snake_case ) for ch in message.upper() ) def _snake_case ( ): lowerCAmelCase : Dict = input('''Enter message to encode or decode: ''' ).strip() lowerCAmelCase : Dict = input('''Enter keyword: ''' ).strip() lowerCAmelCase : Optional[int] = input('''Encipher or decipher? E/D:''' ).strip()[0].lower() try: lowerCAmelCase : Union[str, Any] = {'''e''': encipher, '''d''': decipher}[option] except KeyError: raise KeyError('''invalid input option''' ) lowerCAmelCase : Any = create_cipher_map(_snake_case ) print(func(_snake_case , _snake_case ) ) if __name__ == "__main__": import doctest doctest.testmod() main()
637
"""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 snake_case__ : Tuple = logging.get_logger(__name__) snake_case__ : int = { '''facebook/levit-128S''': '''https://huggingface.co/facebook/levit-128S/resolve/main/config.json''', # See all LeViT models at https://huggingface.co/models?filter=levit } class snake_case_( a__ ): __UpperCamelCase = '''levit''' def __init__( self : str , UpperCamelCase_ : Union[str, Any]=2_2_4 , UpperCamelCase_ : Union[str, Any]=3 , UpperCamelCase_ : Union[str, Any]=3 , UpperCamelCase_ : int=2 , UpperCamelCase_ : Union[str, Any]=1 , UpperCamelCase_ : Tuple=1_6 , UpperCamelCase_ : Dict=[1_2_8, 2_5_6, 3_8_4] , UpperCamelCase_ : Optional[Any]=[4, 8, 1_2] , UpperCamelCase_ : Dict=[4, 4, 4] , UpperCamelCase_ : Any=[1_6, 1_6, 1_6] , UpperCamelCase_ : str=0 , UpperCamelCase_ : int=[2, 2, 2] , UpperCamelCase_ : Optional[Any]=[2, 2, 2] , UpperCamelCase_ : str=0.02 , **UpperCamelCase_ : List[str] , ): super().__init__(**UpperCamelCase_ ) lowerCAmelCase : Tuple = image_size lowerCAmelCase : int = num_channels lowerCAmelCase : Optional[int] = kernel_size lowerCAmelCase : Dict = stride lowerCAmelCase : List[Any] = padding lowerCAmelCase : Dict = hidden_sizes lowerCAmelCase : List[str] = num_attention_heads lowerCAmelCase : Tuple = depths lowerCAmelCase : Dict = key_dim lowerCAmelCase : Union[str, Any] = drop_path_rate lowerCAmelCase : List[Any] = patch_size lowerCAmelCase : Tuple = attention_ratio lowerCAmelCase : Optional[int] = mlp_ratio lowerCAmelCase : Union[str, Any] = initializer_range lowerCAmelCase : List[str] = [ ['''Subsample''', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2], ['''Subsample''', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2], ] class snake_case_( a__ ): __UpperCamelCase = version.parse('''1.11''' ) @property def lowerCamelCase__ ( self : Tuple ): return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def lowerCamelCase__ ( self : Optional[Any] ): return 1E-4
637
1
"""simple docstring""" import datasets from .evaluate import evaluate snake_case__ : List[Any] = '''\ @inproceedings{Rajpurkar2016SQuAD10, title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text}, author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang}, booktitle={EMNLP}, year={2016} } ''' snake_case__ : Tuple = ''' This metric wrap the official scoring script for version 1 of the Stanford Question Answering Dataset (SQuAD). Stanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by crowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span, from the corresponding reading passage, or the question might be unanswerable. ''' snake_case__ : List[Any] = ''' Computes SQuAD scores (F1 and EM). Args: predictions: List of question-answers dictionaries with the following key-values: - \'id\': id of the question-answer pair as given in the references (see below) - \'prediction_text\': the text of the answer references: List of question-answers dictionaries with the following key-values: - \'id\': id of the question-answer pair (see above), - \'answers\': a Dict in the SQuAD dataset format { \'text\': list of possible texts for the answer, as a list of strings \'answer_start\': list of start positions for the answer, as a list of ints } Note that answer_start values are not taken into account to compute the metric. Returns: \'exact_match\': Exact match (the normalized answer exactly match the gold answer) \'f1\': The F-score of predicted tokens versus the gold answer Examples: >>> predictions = [{\'prediction_text\': \'1976\', \'id\': \'56e10a3be3433e1400422b22\'}] >>> references = [{\'answers\': {\'answer_start\': [97], \'text\': [\'1976\']}, \'id\': \'56e10a3be3433e1400422b22\'}] >>> squad_metric = datasets.load_metric("squad") >>> results = squad_metric.compute(predictions=predictions, references=references) >>> print(results) {\'exact_match\': 100.0, \'f1\': 100.0} ''' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class snake_case_( datasets.Metric ): def lowerCamelCase__ ( self : Tuple ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { '''predictions''': {'''id''': datasets.Value('''string''' ), '''prediction_text''': datasets.Value('''string''' )}, '''references''': { '''id''': datasets.Value('''string''' ), '''answers''': datasets.features.Sequence( { '''text''': datasets.Value('''string''' ), '''answer_start''': datasets.Value('''int32''' ), } ), }, } ) , codebase_urls=['''https://rajpurkar.github.io/SQuAD-explorer/'''] , reference_urls=['''https://rajpurkar.github.io/SQuAD-explorer/'''] , ) def lowerCamelCase__ ( self : Any , UpperCamelCase_ : Any , UpperCamelCase_ : Dict ): lowerCAmelCase : Optional[int] = {prediction['''id''']: prediction['''prediction_text'''] for prediction in predictions} lowerCAmelCase : List[Any] = [ { '''paragraphs''': [ { '''qas''': [ { '''answers''': [{'''text''': answer_text} for answer_text in ref['''answers''']['''text''']], '''id''': ref['''id'''], } for ref in references ] } ] } ] lowerCAmelCase : Union[str, Any] = evaluate(dataset=UpperCamelCase_ , predictions=UpperCamelCase_ ) return score
637
"""simple docstring""" import time import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers.generation import ( MaxLengthCriteria, MaxNewTokensCriteria, MaxTimeCriteria, StoppingCriteriaList, validate_stopping_criteria, ) @require_torch class snake_case_( unittest.TestCase ): def lowerCamelCase__ ( self : int , UpperCamelCase_ : int ): lowerCAmelCase : str = 3 lowerCAmelCase : Tuple = 2_5_0 lowerCAmelCase : Optional[Any] = ids_tensor((batch_size, length) , UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = torch.ones((batch_size, length) , device=UpperCamelCase_ , dtype=torch.float ) / length return input_ids, scores def lowerCamelCase__ ( self : Optional[Any] ): lowerCAmelCase, lowerCAmelCase : Optional[int] = self._get_tensors(5 ) lowerCAmelCase : Union[str, Any] = StoppingCriteriaList( [ MaxLengthCriteria(max_length=1_0 ), MaxTimeCriteria(max_time=0.1 ), ] ) self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase, lowerCAmelCase : List[str] = self._get_tensors(9 ) self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase, lowerCAmelCase : Any = self._get_tensors(1_0 ) self.assertTrue(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) def lowerCamelCase__ ( self : Optional[Any] ): lowerCAmelCase : Optional[Any] = MaxLengthCriteria(max_length=1_0 ) lowerCAmelCase, lowerCAmelCase : Optional[Any] = self._get_tensors(5 ) self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase, lowerCAmelCase : List[str] = self._get_tensors(9 ) self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase, lowerCAmelCase : str = self._get_tensors(1_0 ) self.assertTrue(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) def lowerCamelCase__ ( self : List[Any] ): lowerCAmelCase : Optional[Any] = MaxNewTokensCriteria(start_length=5 , max_new_tokens=5 ) lowerCAmelCase, lowerCAmelCase : Optional[int] = self._get_tensors(5 ) self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase, lowerCAmelCase : Union[str, Any] = self._get_tensors(9 ) self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase, lowerCAmelCase : str = self._get_tensors(1_0 ) self.assertTrue(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase : Dict = StoppingCriteriaList([criteria] ) self.assertEqual(criteria_list.max_length , 1_0 ) def lowerCamelCase__ ( self : Union[str, Any] ): lowerCAmelCase, lowerCAmelCase : Tuple = self._get_tensors(5 ) lowerCAmelCase : List[str] = MaxTimeCriteria(max_time=0.1 ) self.assertFalse(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) lowerCAmelCase : List[str] = MaxTimeCriteria(max_time=0.1 , initial_timestamp=time.time() - 0.2 ) self.assertTrue(criteria(UpperCamelCase_ , UpperCamelCase_ ) ) def lowerCamelCase__ ( self : str ): validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(1_0 )] ) , 1_0 ) with self.assertWarns(UpperCamelCase_ ): validate_stopping_criteria(StoppingCriteriaList([MaxLengthCriteria(1_0 )] ) , 1_1 ) lowerCAmelCase : str = validate_stopping_criteria(StoppingCriteriaList() , 1_1 ) self.assertEqual(len(UpperCamelCase_ ) , 1 )
637
1
"""simple docstring""" 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 snake_case__ : int = '''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 _snake_case ( _snake_case : str , _snake_case : Any , _snake_case : str=None , _snake_case : str=None , _snake_case : Dict=None , _snake_case : Tuple=None , _snake_case : str=None , _snake_case : Any=None , ): if attention_mask is None: lowerCAmelCase : List[str] = np.where(input_ids != config.pad_token_id , 1 , 0 ) if decoder_attention_mask is None: lowerCAmelCase : Optional[int] = np.where(decoder_input_ids != config.pad_token_id , 1 , 0 ) if head_mask is None: lowerCAmelCase : Any = np.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: lowerCAmelCase : int = np.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: lowerCAmelCase : List[str] = 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 snake_case_: def __init__( self : int , UpperCamelCase_ : Tuple , UpperCamelCase_ : int=1_3 , UpperCamelCase_ : Union[str, Any]=7 , UpperCamelCase_ : Union[str, Any]=True , UpperCamelCase_ : List[Any]=False , UpperCamelCase_ : Dict=9_9 , UpperCamelCase_ : Optional[int]=1_6 , UpperCamelCase_ : str=2 , UpperCamelCase_ : List[str]=4 , UpperCamelCase_ : List[Any]=4 , UpperCamelCase_ : int="gelu" , UpperCamelCase_ : Optional[int]=0.1 , UpperCamelCase_ : Any=0.1 , UpperCamelCase_ : str=3_2 , UpperCamelCase_ : str=2 , UpperCamelCase_ : Tuple=1 , UpperCamelCase_ : List[Any]=0 , UpperCamelCase_ : Any=0.02 , ): lowerCAmelCase : Tuple = parent lowerCAmelCase : str = batch_size lowerCAmelCase : List[Any] = seq_length lowerCAmelCase : Optional[int] = is_training lowerCAmelCase : int = use_labels lowerCAmelCase : List[Any] = vocab_size lowerCAmelCase : str = hidden_size lowerCAmelCase : List[Any] = num_hidden_layers lowerCAmelCase : Any = num_attention_heads lowerCAmelCase : List[Any] = intermediate_size lowerCAmelCase : Optional[int] = hidden_act lowerCAmelCase : Dict = hidden_dropout_prob lowerCAmelCase : Optional[int] = attention_probs_dropout_prob lowerCAmelCase : List[Any] = max_position_embeddings lowerCAmelCase : Union[str, Any] = eos_token_id lowerCAmelCase : Dict = pad_token_id lowerCAmelCase : Optional[Any] = bos_token_id lowerCAmelCase : List[str] = initializer_range def lowerCamelCase__ ( self : Dict ): lowerCAmelCase : List[Any] = np.clip(ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) , 3 , self.vocab_size ) lowerCAmelCase : str = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1) , dtype=np.intaa )) , -1 ) lowerCAmelCase : Tuple = shift_tokens_right(UpperCamelCase_ , 1 , 2 ) lowerCAmelCase : 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=UpperCamelCase_ , ) lowerCAmelCase : Union[str, Any] = prepare_blenderbot_inputs_dict(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) return config, inputs_dict def lowerCamelCase__ ( self : str ): lowerCAmelCase, lowerCAmelCase : Optional[int] = self.prepare_config_and_inputs() return config, inputs_dict def lowerCamelCase__ ( self : List[str] , UpperCamelCase_ : List[str] , UpperCamelCase_ : str , UpperCamelCase_ : Tuple ): lowerCAmelCase : int = 2_0 lowerCAmelCase : Tuple = model_class_name(UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = model.encode(inputs_dict['''input_ids'''] ) lowerCAmelCase, lowerCAmelCase : str = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) lowerCAmelCase : str = model.init_cache(decoder_input_ids.shape[0] , UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : Union[str, Any] = jnp.ones((decoder_input_ids.shape[0], max_decoder_length) , dtype='''i4''' ) lowerCAmelCase : Tuple = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) lowerCAmelCase : List[Any] = model.decode( decoder_input_ids[:, :-1] , UpperCamelCase_ , decoder_attention_mask=UpperCamelCase_ , past_key_values=UpperCamelCase_ , decoder_position_ids=UpperCamelCase_ , ) lowerCAmelCase : Any = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) lowerCAmelCase : List[str] = model.decode( decoder_input_ids[:, -1:] , UpperCamelCase_ , decoder_attention_mask=UpperCamelCase_ , past_key_values=outputs_cache.past_key_values , decoder_position_ids=UpperCamelCase_ , ) lowerCAmelCase : Union[str, Any] = model.decode(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : int = 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 lowerCamelCase__ ( self : Union[str, Any] , UpperCamelCase_ : Any , UpperCamelCase_ : Any , UpperCamelCase_ : List[str] ): lowerCAmelCase : Optional[int] = 2_0 lowerCAmelCase : List[Any] = model_class_name(UpperCamelCase_ ) lowerCAmelCase : Union[str, Any] = model.encode(inputs_dict['''input_ids'''] ) lowerCAmelCase, lowerCAmelCase : Optional[int] = ( inputs_dict['''decoder_input_ids'''], inputs_dict['''decoder_attention_mask'''], ) lowerCAmelCase : str = jnp.concatenate( [ decoder_attention_mask, jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1]) ), ] , axis=-1 , ) lowerCAmelCase : Union[str, Any] = model.init_cache(decoder_input_ids.shape[0] , UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : str = jnp.broadcast_to( jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] , (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) , ) lowerCAmelCase : Dict = model.decode( decoder_input_ids[:, :-1] , UpperCamelCase_ , decoder_attention_mask=UpperCamelCase_ , past_key_values=UpperCamelCase_ , decoder_position_ids=UpperCamelCase_ , ) lowerCAmelCase : Any = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] , dtype='''i4''' ) lowerCAmelCase : Union[str, Any] = model.decode( decoder_input_ids[:, -1:] , UpperCamelCase_ , past_key_values=outputs_cache.past_key_values , decoder_attention_mask=UpperCamelCase_ , decoder_position_ids=UpperCamelCase_ , ) lowerCAmelCase : Dict = model.decode(UpperCamelCase_ , UpperCamelCase_ , decoder_attention_mask=UpperCamelCase_ ) lowerCAmelCase : 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 snake_case_( unittest.TestCase ): __UpperCamelCase = 99 def lowerCamelCase__ ( self : str ): lowerCAmelCase : List[Any] = np.array( [ [7_1, 8_2, 1_8, 3_3, 4_6, 9_1, 2], [6_8, 3_4, 2_6, 5_8, 3_0, 8_2, 2], [5, 9_7, 1_7, 3_9, 9_4, 4_0, 2], [7_6, 8_3, 9_4, 2_5, 7_0, 7_8, 2], [8_7, 5_9, 4_1, 3_5, 4_8, 6_6, 2], [5_5, 1_3, 1_6, 5_8, 5, 2, 1], # note padding [6_4, 2_7, 3_1, 5_1, 1_2, 7_5, 2], [5_2, 6_4, 8_6, 1_7, 8_3, 3_9, 2], [4_8, 6_1, 9, 2_4, 7_1, 8_2, 2], [2_6, 1, 6_0, 4_8, 2_2, 1_3, 2], [2_1, 5, 6_2, 2_8, 1_4, 7_6, 2], [4_5, 9_8, 3_7, 8_6, 5_9, 4_8, 2], [7_0, 7_0, 5_0, 9, 2_8, 0, 2], ] , dtype=np.intaa , ) lowerCAmelCase : List[Any] = input_ids.shape[0] lowerCAmelCase : Optional[Any] = BlenderbotConfig( vocab_size=self.vocab_size , d_model=2_4 , encoder_layers=2 , decoder_layers=2 , encoder_attention_heads=2 , decoder_attention_heads=2 , encoder_ffn_dim=3_2 , decoder_ffn_dim=3_2 , max_position_embeddings=4_8 , eos_token_id=2 , pad_token_id=1 , bos_token_id=0 , ) return config, input_ids, batch_size def lowerCamelCase__ ( self : List[str] ): lowerCAmelCase, lowerCAmelCase, lowerCAmelCase : Any = self._get_config_and_data() lowerCAmelCase : Any = FlaxBlenderbotForConditionalGeneration(UpperCamelCase_ ) lowerCAmelCase : Optional[int] = lm_model(input_ids=UpperCamelCase_ ) lowerCAmelCase : Tuple = (batch_size, input_ids.shape[1], config.vocab_size) self.assertEqual(outputs['''logits'''].shape , UpperCamelCase_ ) def lowerCamelCase__ ( self : Any ): lowerCAmelCase : Any = BlenderbotConfig( vocab_size=self.vocab_size , d_model=1_4 , 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=4_8 , ) lowerCAmelCase : int = FlaxBlenderbotForConditionalGeneration(UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = np.array([[7_1, 8_2, 1_8, 3_3, 4_6, 9_1, 2], [6_8, 3_4, 2_6, 5_8, 3_0, 2, 1]] , dtype=np.intaa ) lowerCAmelCase : List[str] = np.array([[8_2, 7_1, 8_2, 1_8, 2], [5_8, 6_8, 2, 1, 1]] , dtype=np.intaa ) lowerCAmelCase : List[Any] = lm_model(input_ids=UpperCamelCase_ , decoder_input_ids=UpperCamelCase_ ) lowerCAmelCase : str = (*summary.shape, config.vocab_size) self.assertEqual(outputs['''logits'''].shape , UpperCamelCase_ ) def lowerCamelCase__ ( self : int ): lowerCAmelCase : Any = np.array([[7_1, 8_2, 1_8, 3_3, 2, 1, 1], [6_8, 3_4, 2_6, 5_8, 3_0, 8_2, 2]] , dtype=np.intaa ) lowerCAmelCase : Tuple = shift_tokens_right(UpperCamelCase_ , 1 , 2 ) lowerCAmelCase : Optional[int] = np.equal(UpperCamelCase_ , 1 ).astype(np.floataa ).sum() lowerCAmelCase : str = np.equal(UpperCamelCase_ , 1 ).astype(np.floataa ).sum() self.assertEqual(shifted.shape , input_ids.shape ) self.assertEqual(UpperCamelCase_ , n_pad_before - 1 ) self.assertTrue(np.equal(shifted[:, 0] , 2 ).all() ) @require_flax class snake_case_( a__ , unittest.TestCase , a__ ): __UpperCamelCase = True __UpperCamelCase = ( ( FlaxBlenderbotModel, FlaxBlenderbotForConditionalGeneration, ) if is_flax_available() else () ) __UpperCamelCase = (FlaxBlenderbotForConditionalGeneration,) if is_flax_available() else () def lowerCamelCase__ ( self : Dict ): lowerCAmelCase : Any = FlaxBlenderbotModelTester(self ) def lowerCamelCase__ ( self : Tuple ): lowerCAmelCase, lowerCAmelCase : List[str] = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: self.model_tester.check_use_cache_forward(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) def lowerCamelCase__ ( self : List[str] ): lowerCAmelCase, lowerCAmelCase : Union[str, Any] = 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(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) def lowerCamelCase__ ( self : Tuple ): lowerCAmelCase, lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowerCAmelCase : Optional[int] = self._prepare_for_class(UpperCamelCase_ , UpperCamelCase_ ) lowerCAmelCase : Optional[Any] = model_class(UpperCamelCase_ ) @jax.jit def encode_jitted(UpperCamelCase_ : List[str] , UpperCamelCase_ : Optional[Any]=None , **UpperCamelCase_ : List[str] ): return model.encode(input_ids=UpperCamelCase_ , attention_mask=UpperCamelCase_ ) with self.subTest('''JIT Enabled''' ): lowerCAmelCase : List[str] = encode_jitted(**UpperCamelCase_ ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): lowerCAmelCase : int = encode_jitted(**UpperCamelCase_ ).to_tuple() self.assertEqual(len(UpperCamelCase_ ) , len(UpperCamelCase_ ) ) for jitted_output, output in zip(UpperCamelCase_ , UpperCamelCase_ ): self.assertEqual(jitted_output.shape , output.shape ) def lowerCamelCase__ ( self : Union[str, Any] ): lowerCAmelCase, lowerCAmelCase : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): lowerCAmelCase : Tuple = model_class(UpperCamelCase_ ) lowerCAmelCase : int = model.encode(inputs_dict['''input_ids'''] , inputs_dict['''attention_mask'''] ) lowerCAmelCase : List[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(UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : Dict , UpperCamelCase_ : int ): return model.decode( decoder_input_ids=UpperCamelCase_ , decoder_attention_mask=UpperCamelCase_ , encoder_outputs=UpperCamelCase_ , ) with self.subTest('''JIT Enabled''' ): lowerCAmelCase : str = decode_jitted(**UpperCamelCase_ ).to_tuple() with self.subTest('''JIT Disabled''' ): with jax.disable_jit(): lowerCAmelCase : Union[str, Any] = decode_jitted(**UpperCamelCase_ ).to_tuple() self.assertEqual(len(UpperCamelCase_ ) , len(UpperCamelCase_ ) ) for jitted_output, output in zip(UpperCamelCase_ , UpperCamelCase_ ): self.assertEqual(jitted_output.shape , output.shape ) @slow def lowerCamelCase__ ( self : Optional[int] ): for model_class_name in self.all_model_classes: lowerCAmelCase : Optional[int] = model_class_name.from_pretrained('''facebook/blenderbot-400M-distill''' ) # FlaxBlenderbotForSequenceClassification expects eos token in input_ids lowerCAmelCase : int = np.ones((1, 1) ) * model.config.eos_token_id lowerCAmelCase : List[str] = model(UpperCamelCase_ ) self.assertIsNotNone(UpperCamelCase_ ) @unittest.skipUnless(jax_device != '''cpu''' , '''3B test too slow on CPU.''' ) @slow def lowerCamelCase__ ( self : Union[str, Any] ): lowerCAmelCase : Dict = {'''num_beams''': 1, '''early_stopping''': True, '''min_length''': 1_5, '''max_length''': 2_5} lowerCAmelCase : List[str] = {'''skip_special_tokens''': True, '''clean_up_tokenization_spaces''': True} lowerCAmelCase : Tuple = FlaxBlenderbotForConditionalGeneration.from_pretrained('''facebook/blenderbot-3B''' , from_pt=UpperCamelCase_ ) lowerCAmelCase : Union[str, Any] = BlenderbotTokenizer.from_pretrained('''facebook/blenderbot-3B''' ) lowerCAmelCase : List[Any] = ['''Sam'''] lowerCAmelCase : str = tokenizer(UpperCamelCase_ , return_tensors='''jax''' ) lowerCAmelCase : Union[str, Any] = model.generate(**UpperCamelCase_ , **UpperCamelCase_ ) lowerCAmelCase : Tuple = '''Sam is a great name. It means "sun" in Gaelic.''' lowerCAmelCase : Union[str, Any] = tokenizer.batch_decode(UpperCamelCase_ , **UpperCamelCase_ ) assert generated_txt[0].strip() == tgt_text
637
"""simple docstring""" import math from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass # Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->UnCLIP class snake_case_( a__ ): __UpperCamelCase = 42 __UpperCamelCase = None def _snake_case ( _snake_case : Dict , _snake_case : List[str]=0.999 , _snake_case : Dict="cosine" , ): if alpha_transform_type == "cosine": def alpha_bar_fn(_snake_case : List[Any] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(_snake_case : Optional[int] ): return math.exp(t * -12.0 ) else: raise ValueError(f'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) lowerCAmelCase : List[Any] = [] for i in range(_snake_case ): lowerCAmelCase : int = i / num_diffusion_timesteps lowerCAmelCase : Tuple = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(_snake_case ) / alpha_bar_fn(_snake_case ) , _snake_case ) ) return torch.tensor(_snake_case , dtype=torch.floataa ) class snake_case_( a__ , a__ ): @register_to_config def __init__( self : Any , UpperCamelCase_ : int = 1_0_0_0 , UpperCamelCase_ : str = "fixed_small_log" , UpperCamelCase_ : bool = True , UpperCamelCase_ : Optional[float] = 1.0 , UpperCamelCase_ : str = "epsilon" , UpperCamelCase_ : str = "squaredcos_cap_v2" , ): if beta_schedule != "squaredcos_cap_v2": raise ValueError('''UnCLIPScheduler only supports `beta_schedule`: \'squaredcos_cap_v2\'''' ) lowerCAmelCase : Any = betas_for_alpha_bar(UpperCamelCase_ ) lowerCAmelCase : str = 1.0 - self.betas lowerCAmelCase : Union[str, Any] = torch.cumprod(self.alphas , dim=0 ) lowerCAmelCase : Tuple = torch.tensor(1.0 ) # standard deviation of the initial noise distribution lowerCAmelCase : Any = 1.0 # setable values lowerCAmelCase : Any = None lowerCAmelCase : Any = torch.from_numpy(np.arange(0 , UpperCamelCase_ )[::-1].copy() ) lowerCAmelCase : List[str] = variance_type def lowerCamelCase__ ( self : Union[str, Any] , UpperCamelCase_ : torch.FloatTensor , UpperCamelCase_ : Optional[int] = None ): return sample def lowerCamelCase__ ( self : Tuple , UpperCamelCase_ : int , UpperCamelCase_ : Union[str, torch.device] = None ): lowerCAmelCase : Any = num_inference_steps lowerCAmelCase : str = (self.config.num_train_timesteps - 1) / (self.num_inference_steps - 1) lowerCAmelCase : Tuple = (np.arange(0 , UpperCamelCase_ ) * step_ratio).round()[::-1].copy().astype(np.intaa ) lowerCAmelCase : Any = torch.from_numpy(UpperCamelCase_ ).to(UpperCamelCase_ ) def lowerCamelCase__ ( self : Optional[Any] , UpperCamelCase_ : List[Any] , UpperCamelCase_ : str=None , UpperCamelCase_ : Tuple=None , UpperCamelCase_ : Any=None ): if prev_timestep is None: lowerCAmelCase : Any = t - 1 lowerCAmelCase : int = self.alphas_cumprod[t] lowerCAmelCase : Union[str, Any] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one lowerCAmelCase : Dict = 1 - alpha_prod_t lowerCAmelCase : str = 1 - alpha_prod_t_prev if prev_timestep == t - 1: lowerCAmelCase : Tuple = self.betas[t] else: lowerCAmelCase : Union[str, Any] = 1 - alpha_prod_t / alpha_prod_t_prev # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) # and sample from it to get previous sample # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample lowerCAmelCase : Optional[Any] = beta_prod_t_prev / beta_prod_t * beta if variance_type is None: lowerCAmelCase : List[str] = self.config.variance_type # hacks - were probably added for training stability if variance_type == "fixed_small_log": lowerCAmelCase : Any = torch.log(torch.clamp(UpperCamelCase_ , min=1E-20 ) ) lowerCAmelCase : Union[str, Any] = torch.exp(0.5 * variance ) elif variance_type == "learned_range": # NOTE difference with DDPM scheduler lowerCAmelCase : Optional[Any] = variance.log() lowerCAmelCase : Union[str, Any] = beta.log() lowerCAmelCase : Dict = (predicted_variance + 1) / 2 lowerCAmelCase : Union[str, Any] = frac * max_log + (1 - frac) * min_log return variance def lowerCamelCase__ ( self : Optional[Any] , UpperCamelCase_ : torch.FloatTensor , UpperCamelCase_ : int , UpperCamelCase_ : torch.FloatTensor , UpperCamelCase_ : Optional[int] = None , UpperCamelCase_ : List[Any]=None , UpperCamelCase_ : bool = True , ): lowerCAmelCase : Optional[Any] = timestep if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type == "learned_range": lowerCAmelCase, lowerCAmelCase : List[Any] = torch.split(UpperCamelCase_ , sample.shape[1] , dim=1 ) else: lowerCAmelCase : Optional[int] = None # 1. compute alphas, betas if prev_timestep is None: lowerCAmelCase : Any = t - 1 lowerCAmelCase : Union[str, Any] = self.alphas_cumprod[t] lowerCAmelCase : Optional[int] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.one lowerCAmelCase : int = 1 - alpha_prod_t lowerCAmelCase : str = 1 - alpha_prod_t_prev if prev_timestep == t - 1: lowerCAmelCase : List[Any] = self.betas[t] lowerCAmelCase : Optional[int] = self.alphas[t] else: lowerCAmelCase : List[Any] = 1 - alpha_prod_t / alpha_prod_t_prev lowerCAmelCase : Dict = 1 - beta # 2. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf if self.config.prediction_type == "epsilon": lowerCAmelCase : List[Any] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5 elif self.config.prediction_type == "sample": lowerCAmelCase : Tuple = model_output else: raise ValueError( F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon` or `sample`''' ''' for the UnCLIPScheduler.''' ) # 3. Clip "predicted x_0" if self.config.clip_sample: lowerCAmelCase : Dict = torch.clamp( UpperCamelCase_ , -self.config.clip_sample_range , self.config.clip_sample_range ) # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowerCAmelCase : int = (alpha_prod_t_prev ** 0.5 * beta) / beta_prod_t lowerCAmelCase : List[Any] = alpha ** 0.5 * beta_prod_t_prev / beta_prod_t # 5. Compute predicted previous sample µ_t # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf lowerCAmelCase : str = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample # 6. Add noise lowerCAmelCase : int = 0 if t > 0: lowerCAmelCase : Union[str, Any] = randn_tensor( model_output.shape , dtype=model_output.dtype , generator=UpperCamelCase_ , device=model_output.device ) lowerCAmelCase : Any = self._get_variance( UpperCamelCase_ , predicted_variance=UpperCamelCase_ , prev_timestep=UpperCamelCase_ , ) if self.variance_type == "fixed_small_log": lowerCAmelCase : str = variance elif self.variance_type == "learned_range": lowerCAmelCase : Optional[Any] = (0.5 * variance).exp() else: raise ValueError( F'''variance_type given as {self.variance_type} must be one of `fixed_small_log` or `learned_range`''' ''' for the UnCLIPScheduler.''' ) lowerCAmelCase : List[Any] = variance * variance_noise lowerCAmelCase : int = pred_prev_sample + variance if not return_dict: return (pred_prev_sample,) return UnCLIPSchedulerOutput(prev_sample=UpperCamelCase_ , pred_original_sample=UpperCamelCase_ ) def lowerCamelCase__ ( self : Optional[int] , UpperCamelCase_ : torch.FloatTensor , UpperCamelCase_ : torch.FloatTensor , UpperCamelCase_ : torch.IntTensor , ): # Make sure alphas_cumprod and timestep have same device and dtype as original_samples lowerCAmelCase : Tuple = self.alphas_cumprod.to(device=original_samples.device , dtype=original_samples.dtype ) lowerCAmelCase : int = timesteps.to(original_samples.device ) lowerCAmelCase : Dict = alphas_cumprod[timesteps] ** 0.5 lowerCAmelCase : str = sqrt_alpha_prod.flatten() while len(sqrt_alpha_prod.shape ) < len(original_samples.shape ): lowerCAmelCase : Any = sqrt_alpha_prod.unsqueeze(-1 ) lowerCAmelCase : List[str] = (1 - alphas_cumprod[timesteps]) ** 0.5 lowerCAmelCase : Tuple = sqrt_one_minus_alpha_prod.flatten() while len(sqrt_one_minus_alpha_prod.shape ) < len(original_samples.shape ): lowerCAmelCase : int = sqrt_one_minus_alpha_prod.unsqueeze(-1 ) lowerCAmelCase : Dict = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise return noisy_samples
637
1
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available snake_case__ : List[Any] = { '''configuration_clipseg''': [ '''CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CLIPSegConfig''', '''CLIPSegTextConfig''', '''CLIPSegVisionConfig''', ], '''processing_clipseg''': ['''CLIPSegProcessor'''], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case__ : List[Any] = [ '''CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST''', '''CLIPSegModel''', '''CLIPSegPreTrainedModel''', '''CLIPSegTextModel''', '''CLIPSegVisionModel''', '''CLIPSegForImageSegmentation''', ] if TYPE_CHECKING: from .configuration_clipseg import ( CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPSegConfig, CLIPSegTextConfig, CLIPSegVisionConfig, ) from .processing_clipseg import CLIPSegProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clipseg import ( CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPSegForImageSegmentation, CLIPSegModel, CLIPSegPreTrainedModel, CLIPSegTextModel, CLIPSegVisionModel, ) else: import sys snake_case__ : List[str] = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
637
"""simple docstring""" import unittest from parameterized import parameterized from transformers import LlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import LlamaForCausalLM, LlamaForSequenceClassification, LlamaModel, LlamaTokenizer class snake_case_: def __init__( self : int , UpperCamelCase_ : List[Any] , UpperCamelCase_ : Dict=1_3 , UpperCamelCase_ : Optional[Any]=7 , UpperCamelCase_ : Optional[int]=True , UpperCamelCase_ : Dict=True , UpperCamelCase_ : Optional[int]=False , UpperCamelCase_ : Any=True , UpperCamelCase_ : List[str]=9_9 , UpperCamelCase_ : Tuple=3_2 , UpperCamelCase_ : Optional[Any]=5 , UpperCamelCase_ : str=4 , UpperCamelCase_ : Any=3_7 , UpperCamelCase_ : Optional[Any]="gelu" , UpperCamelCase_ : Tuple=0.1 , UpperCamelCase_ : Union[str, Any]=0.1 , UpperCamelCase_ : Union[str, Any]=5_1_2 , UpperCamelCase_ : Union[str, Any]=1_6 , UpperCamelCase_ : Any=2 , UpperCamelCase_ : Optional[Any]=0.02 , UpperCamelCase_ : List[Any]=3 , UpperCamelCase_ : Any=4 , UpperCamelCase_ : int=None , ): lowerCAmelCase : Any = parent lowerCAmelCase : Any = batch_size lowerCAmelCase : List[Any] = seq_length lowerCAmelCase : str = is_training lowerCAmelCase : List[Any] = use_input_mask lowerCAmelCase : Optional[int] = use_token_type_ids lowerCAmelCase : Union[str, Any] = use_labels lowerCAmelCase : List[str] = vocab_size lowerCAmelCase : Tuple = hidden_size lowerCAmelCase : int = num_hidden_layers lowerCAmelCase : Union[str, Any] = num_attention_heads lowerCAmelCase : Optional[int] = intermediate_size lowerCAmelCase : List[Any] = hidden_act lowerCAmelCase : int = hidden_dropout_prob lowerCAmelCase : Tuple = attention_probs_dropout_prob lowerCAmelCase : Optional[Any] = max_position_embeddings lowerCAmelCase : Optional[int] = type_vocab_size lowerCAmelCase : Tuple = type_sequence_label_size lowerCAmelCase : List[str] = initializer_range lowerCAmelCase : str = num_labels lowerCAmelCase : Optional[int] = num_choices lowerCAmelCase : Tuple = scope def lowerCamelCase__ ( self : Optional[int] ): lowerCAmelCase : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) lowerCAmelCase : Tuple = None if self.use_input_mask: lowerCAmelCase : str = random_attention_mask([self.batch_size, self.seq_length] ) lowerCAmelCase : List[str] = None if self.use_token_type_ids: lowerCAmelCase : Tuple = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) lowerCAmelCase : int = None lowerCAmelCase : int = None lowerCAmelCase : Tuple = None if self.use_labels: lowerCAmelCase : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) lowerCAmelCase : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) lowerCAmelCase : Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices ) lowerCAmelCase : Optional[Any] = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowerCamelCase__ ( self : Tuple ): return LlamaConfig( 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=UpperCamelCase_ , initializer_range=self.initializer_range , ) def lowerCamelCase__ ( self : int , UpperCamelCase_ : Any , UpperCamelCase_ : Dict , UpperCamelCase_ : Any , UpperCamelCase_ : Dict , UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : List[str] , UpperCamelCase_ : Tuple ): lowerCAmelCase : List[Any] = LlamaModel(config=UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowerCAmelCase : Dict = model(UpperCamelCase_ , attention_mask=UpperCamelCase_ ) lowerCAmelCase : Optional[int] = model(UpperCamelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase__ ( self : Any , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Tuple , UpperCamelCase_ : Tuple , UpperCamelCase_ : Dict , UpperCamelCase_ : int , UpperCamelCase_ : Dict , UpperCamelCase_ : Tuple , UpperCamelCase_ : int , UpperCamelCase_ : Any , ): lowerCAmelCase : Tuple = True lowerCAmelCase : Optional[int] = LlamaModel(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowerCAmelCase : List[Any] = model( UpperCamelCase_ , attention_mask=UpperCamelCase_ , encoder_hidden_states=UpperCamelCase_ , encoder_attention_mask=UpperCamelCase_ , ) lowerCAmelCase : Dict = model( UpperCamelCase_ , attention_mask=UpperCamelCase_ , encoder_hidden_states=UpperCamelCase_ , ) lowerCAmelCase : Tuple = model(UpperCamelCase_ , attention_mask=UpperCamelCase_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowerCamelCase__ ( self : Any , UpperCamelCase_ : int , UpperCamelCase_ : Tuple , UpperCamelCase_ : Any , UpperCamelCase_ : List[Any] , UpperCamelCase_ : str , UpperCamelCase_ : int , UpperCamelCase_ : int , UpperCamelCase_ : int , UpperCamelCase_ : str , ): lowerCAmelCase : Optional[Any] = LlamaForCausalLM(config=UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowerCAmelCase : List[str] = model(UpperCamelCase_ , attention_mask=UpperCamelCase_ , labels=UpperCamelCase_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowerCamelCase__ ( self : str , UpperCamelCase_ : List[str] , UpperCamelCase_ : int , UpperCamelCase_ : Tuple , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : int , UpperCamelCase_ : str , UpperCamelCase_ : Dict , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : List[Any] , ): lowerCAmelCase : Union[str, Any] = True lowerCAmelCase : str = True lowerCAmelCase : Tuple = LlamaForCausalLM(config=UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() # first forward pass lowerCAmelCase : Optional[Any] = model( UpperCamelCase_ , attention_mask=UpperCamelCase_ , encoder_hidden_states=UpperCamelCase_ , encoder_attention_mask=UpperCamelCase_ , use_cache=UpperCamelCase_ , ) lowerCAmelCase : Dict = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids lowerCAmelCase : Any = ids_tensor((self.batch_size, 3) , config.vocab_size ) lowerCAmelCase : Dict = ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and lowerCAmelCase : Optional[Any] = torch.cat([input_ids, next_tokens] , dim=-1 ) lowerCAmelCase : List[str] = torch.cat([input_mask, next_mask] , dim=-1 ) lowerCAmelCase : Dict = model( UpperCamelCase_ , attention_mask=UpperCamelCase_ , encoder_hidden_states=UpperCamelCase_ , encoder_attention_mask=UpperCamelCase_ , output_hidden_states=UpperCamelCase_ , )['''hidden_states'''][0] lowerCAmelCase : str = model( UpperCamelCase_ , attention_mask=UpperCamelCase_ , encoder_hidden_states=UpperCamelCase_ , encoder_attention_mask=UpperCamelCase_ , past_key_values=UpperCamelCase_ , output_hidden_states=UpperCamelCase_ , )['''hidden_states'''][0] # select random slice lowerCAmelCase : Tuple = ids_tensor((1,) , output_from_past.shape[-1] ).item() lowerCAmelCase : Any = output_from_no_past[:, -3:, random_slice_idx].detach() lowerCAmelCase : Optional[int] = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(UpperCamelCase_ , UpperCamelCase_ , atol=1E-3 ) ) def lowerCamelCase__ ( self : Union[str, Any] ): lowerCAmelCase : Dict = self.prepare_config_and_inputs() ( ( lowerCAmelCase ), ( lowerCAmelCase ), ( lowerCAmelCase ), ( lowerCAmelCase ), ( lowerCAmelCase ), ( lowerCAmelCase ), ( lowerCAmelCase ), ) : Tuple = config_and_inputs lowerCAmelCase : Optional[int] = {'''input_ids''': input_ids, '''attention_mask''': input_mask} return config, inputs_dict @require_torch class snake_case_( a__ , a__ , a__ , unittest.TestCase ): __UpperCamelCase = (LlamaModel, LlamaForCausalLM, LlamaForSequenceClassification) if is_torch_available() else () __UpperCamelCase = (LlamaForCausalLM,) if is_torch_available() else () __UpperCamelCase = ( { '''feature-extraction''': LlamaModel, '''text-classification''': LlamaForSequenceClassification, '''text-generation''': LlamaForCausalLM, '''zero-shot''': LlamaForSequenceClassification, } if is_torch_available() else {} ) __UpperCamelCase = False __UpperCamelCase = False def lowerCamelCase__ ( self : Optional[Any] ): lowerCAmelCase : Any = LlamaModelTester(self ) lowerCAmelCase : Dict = ConfigTester(self , config_class=UpperCamelCase_ , hidden_size=3_7 ) def lowerCamelCase__ ( self : str ): self.config_tester.run_common_tests() def lowerCamelCase__ ( self : Tuple ): lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*UpperCamelCase_ ) def lowerCamelCase__ ( self : List[Any] ): lowerCAmelCase : str = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: lowerCAmelCase : str = type self.model_tester.create_and_check_model(*UpperCamelCase_ ) def lowerCamelCase__ ( self : List[Any] ): lowerCAmelCase, lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase : List[str] = 3 lowerCAmelCase : List[str] = input_dict['''input_ids'''] lowerCAmelCase : List[str] = input_ids.ne(1 ).to(UpperCamelCase_ ) lowerCAmelCase : Tuple = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) lowerCAmelCase : Union[str, Any] = LlamaForSequenceClassification(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowerCAmelCase : List[Any] = model(UpperCamelCase_ , attention_mask=UpperCamelCase_ , labels=UpperCamelCase_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def lowerCamelCase__ ( self : Optional[int] ): lowerCAmelCase, lowerCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase : Any = 3 lowerCAmelCase : int = '''single_label_classification''' lowerCAmelCase : Tuple = input_dict['''input_ids'''] lowerCAmelCase : Tuple = input_ids.ne(1 ).to(UpperCamelCase_ ) lowerCAmelCase : str = ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) lowerCAmelCase : Tuple = LlamaForSequenceClassification(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowerCAmelCase : Any = model(UpperCamelCase_ , attention_mask=UpperCamelCase_ , labels=UpperCamelCase_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def lowerCamelCase__ ( self : Union[str, Any] ): lowerCAmelCase, lowerCAmelCase : Tuple = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase : Any = 3 lowerCAmelCase : Dict = '''multi_label_classification''' lowerCAmelCase : Union[str, Any] = input_dict['''input_ids'''] lowerCAmelCase : Tuple = input_ids.ne(1 ).to(UpperCamelCase_ ) lowerCAmelCase : Any = ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) lowerCAmelCase : Optional[int] = LlamaForSequenceClassification(UpperCamelCase_ ) model.to(UpperCamelCase_ ) model.eval() lowerCAmelCase : Optional[Any] = model(UpperCamelCase_ , attention_mask=UpperCamelCase_ , labels=UpperCamelCase_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('''LLaMA buffers include complex numbers, which breaks this test''' ) def lowerCamelCase__ ( self : Optional[Any] ): pass @parameterized.expand([('''linear''',), ('''dynamic''',)] ) def lowerCamelCase__ ( self : List[str] , UpperCamelCase_ : Tuple ): lowerCAmelCase, lowerCAmelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() lowerCAmelCase : Optional[int] = ids_tensor([1, 1_0] , config.vocab_size ) lowerCAmelCase : int = ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(4_2 ) # Fixed seed at init time so the two models get the same random weights lowerCAmelCase : List[Any] = LlamaModel(UpperCamelCase_ ) original_model.to(UpperCamelCase_ ) original_model.eval() lowerCAmelCase : Optional[int] = original_model(UpperCamelCase_ ).last_hidden_state lowerCAmelCase : List[Any] = original_model(UpperCamelCase_ ).last_hidden_state set_seed(4_2 ) # Fixed seed at init time so the two models get the same random weights lowerCAmelCase : int = {'''type''': scaling_type, '''factor''': 10.0} lowerCAmelCase : List[str] = LlamaModel(UpperCamelCase_ ) scaled_model.to(UpperCamelCase_ ) scaled_model.eval() lowerCAmelCase : Union[str, Any] = scaled_model(UpperCamelCase_ ).last_hidden_state lowerCAmelCase : Optional[int] = scaled_model(UpperCamelCase_ ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(UpperCamelCase_ , UpperCamelCase_ , atol=1E-5 ) ) else: self.assertFalse(torch.allclose(UpperCamelCase_ , UpperCamelCase_ , atol=1E-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(UpperCamelCase_ , UpperCamelCase_ , atol=1E-5 ) ) @require_torch class snake_case_( unittest.TestCase ): @unittest.skip('''Logits are not exactly the same, once we fix the instabalities somehow, will update!''' ) @slow def lowerCamelCase__ ( self : List[Any] ): lowerCAmelCase : Tuple = [1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8] lowerCAmelCase : Optional[Any] = LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-7b-hf''' , device_map='''auto''' ) lowerCAmelCase : str = model(torch.tensor([input_ids] ) ) # Expected mean on dim = -1 lowerCAmelCase : int = torch.tensor([[-6.6_550, -4.1_227, -4.9_859, -3.2_406, 0.8_262, -3.0_033, 1.2_964, -3.3_699]] ) torch.testing.assert_close(out.mean(-1 ) , UpperCamelCase_ , atol=1E-2 , rtol=1E-2 ) # slicing logits[0, 0, 0:30] # fmt: off lowerCAmelCase : Tuple = torch.tensor([-12.8_281, -7.4_453, -0.4_639, -8.0_625, -7.2_500, -8.0_000, -6.4_883, -7.7_695, -7.8_438, -7.0_312, -6.2_188, -7.1_328, -1.8_496, 1.9_961, -8.6_250, -6.7_227, -12.8_281, -6.9_492, -7.0_742, -7.7_852, -7.5_820, -7.9_062, -6.9_375, -7.9_805, -8.3_438, -8.1_562, -8.0_469, -7.6_250, -7.7_422, -7.3_398,] ) # fmt: on torch.testing.assert_close(out[0, 0, :3_0] , UpperCamelCase_ , atol=1E-5 , rtol=1E-5 ) @unittest.skip('''Logits are not exactly the same, once we fix the instabalities somehow, will update!''' ) @slow def lowerCamelCase__ ( self : Dict ): lowerCAmelCase : str = [1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8] lowerCAmelCase : Dict = LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-13b-hf''' , device_map='''auto''' ) lowerCAmelCase : str = model(torch.tensor(UpperCamelCase_ ) ) # Expected mean on dim = -1 lowerCAmelCase : Any = torch.tensor([[-2.0_622, -1.2_794, -1.1_638, -0.9_788, -1.4_603, -1.0_238, -1.7_893, -1.4_411]] ) torch.testing.assert_close(out.mean(-1 ) , UpperCamelCase_ , atol=1E-2 , rtol=1E-2 ) # slicing logits[0, 0, 0:30] # fmt: off lowerCAmelCase : Tuple = torch.tensor([-8.1_406, -8.0_547, 2.7_461, -1.2_344, -0.1_448, -1.8_262, -1.0_020, -1.8_154, -1.6_895, -1.8_516, -2.3_574, -0.9_277, 3.7_598, 6.5_742, -1.2_998, -0.1_177, -8.1_406, -2.9_688, -2.9_199, -3.1_699, -3.5_254, -2.3_555, -2.7_988, -3.4_141, -2.8_262, -4.5_195, -3.3_379, -3.3_164, -2.7_832, -3.0_273] ) # fmt: on torch.testing.assert_close(out[0, 0, :3_0] , UpperCamelCase_ , atol=1E-5 , rtol=1E-5 ) @unittest.skip('''Logits are not exactly the same, once we fix the instabalities somehow, will update!''' ) @slow def lowerCamelCase__ ( self : Optional[int] ): lowerCAmelCase : int = [1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8] lowerCAmelCase : List[str] = LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-13b-chat-hf''' , device_map='''auto''' ) lowerCAmelCase : List[Any] = model(torch.tensor(UpperCamelCase_ ) ) # Expected mean on dim = -1 lowerCAmelCase : List[str] = torch.tensor([[-0.8_562, -1.8_520, -0.7_551, -0.4_162, -1.5_161, -1.2_038, -2.4_823, -2.3_254]] ) torch.testing.assert_close(out.mean(-1 ) , UpperCamelCase_ , atol=1E-2 , rtol=1E-2 ) # slicing logits[0, 0, 0:30] # fmt: off lowerCAmelCase : Dict = torch.tensor([-2.2_227, 4.8_828, 0.9_023, -0.4_578, -0.7_871, -0.1_033, -0.6_221, -0.5_786, -0.7_803, -1.0_674, -1.2_920, -0.1_570, 0.8_008, 2.0_723, -0.9_497, 0.2_771, -2.2_227, -0.7_612, -1.4_346, -1.2_061, -1.6_426, -0.3_000, -0.7_139, -1.1_934, -1.8_691, -1.6_973, -1.5_947, -1.2_705, -0.3_523, -0.5_513] ) # fmt: on torch.testing.assert_close(out.mean(-1 ) , UpperCamelCase_ , atol=1E-2 , rtol=1E-2 ) @unittest.skip( '''Logits are not exactly the same, once we fix the instabalities somehow, will update! Also it is gonna be a `too_slow` test''' ) @slow def lowerCamelCase__ ( self : List[str] ): lowerCAmelCase : Optional[Any] = [1, 3_0_6, 4_6_5_8, 2_7_8, 6_5_9_3, 3_1_0, 2_8_3_4, 3_3_8] lowerCAmelCase : Optional[int] = LlamaForCausalLM.from_pretrained('''meta-llama/Llama-2-70b-hf''' , device_map='''auto''' ) lowerCAmelCase : Any = model(torch.tensor(UpperCamelCase_ ) ) lowerCAmelCase : Optional[Any] = torch.tensor( [[-4.2_327, -3.3_360, -4.6_665, -4.7_631, -1.8_180, -3.4_170, -1.4_211, -3.1_810]] , dtype=torch.floataa ) torch.testing.assert_close(out.mean(-1 ) , UpperCamelCase_ , atol=1E-2 , rtol=1E-2 ) # fmt: off lowerCAmelCase : Any = torch.tensor([-9.4_922, -3.9_551, 1.7_998, -5.6_758, -5.1_055, -5.8_984, -4.8_320, -6.8_086, -6.5_391, -5.6_172, -5.5_820, -5.5_352, 1.7_881, 3.6_289, -6.5_117, -3.4_785, -9.5_000, -6.0_352, -6.8_125, -6.0_195, -6.6_836, -5.4_727, -6.2_812, -6.0_391, -7.3_398, -7.4_297, -7.4_844, -6.5_820, -5.8_789, -5.5_312] ) # fmt: on torch.testing.assert_close(out[0, 0, :3_0] , UpperCamelCase_ , atol=1E-5 , rtol=1E-5 ) @unittest.skip('''Model is curently gated''' ) @slow def lowerCamelCase__ ( self : List[Any] ): lowerCAmelCase : List[Any] = '''Simply put, the theory of relativity states that 1) the laws of physics are the same everywhere in the universe and 2) the passage of time and the length of objects can vary depending on the observer\'s frame of reference.\n\nThe first part of the theory, that the laws of physics are the same everywhere, is known as the "princi''' lowerCAmelCase : int = '''Simply put, the theory of relativity states that ''' lowerCAmelCase : str = LlamaTokenizer.from_pretrained('''meta-llama/Llama-2-13b-chat-hf''' ) lowerCAmelCase : Optional[int] = tokenizer.encode(UpperCamelCase_ , return_tensors='''pt''' ) lowerCAmelCase : List[Any] = LlamaForCausalLM.from_pretrained( '''meta-llama/Llama-2-13b-chat-hf''' , device_map='''sequential''' , use_safetensors=UpperCamelCase_ ) # greedy generation outputs lowerCAmelCase : int = model.generate(UpperCamelCase_ , max_new_tokens=6_4 , top_p=UpperCamelCase_ , temperature=1 , do_sample=UpperCamelCase_ ) lowerCAmelCase : int = tokenizer.decode(generated_ids[0] , skip_special_tokens=UpperCamelCase_ ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ )
637
1
"""simple docstring""" from typing import List import datasets from datasets.tasks import AudioClassification from ..folder_based_builder import folder_based_builder snake_case__ : int = datasets.utils.logging.get_logger(__name__) class snake_case_( folder_based_builder.FolderBasedBuilderConfig ): __UpperCamelCase = None __UpperCamelCase = None class snake_case_( folder_based_builder.FolderBasedBuilder ): __UpperCamelCase = datasets.Audio() __UpperCamelCase = '''audio''' __UpperCamelCase = AudioFolderConfig __UpperCamelCase = 42 # definition at the bottom of the script __UpperCamelCase = AudioClassification(audio_column='''audio''' , label_column='''label''' ) snake_case__ : Union[str, Any] = [ '''.aiff''', '''.au''', '''.avr''', '''.caf''', '''.flac''', '''.htk''', '''.svx''', '''.mat4''', '''.mat5''', '''.mpc2k''', '''.ogg''', '''.paf''', '''.pvf''', '''.raw''', '''.rf64''', '''.sd2''', '''.sds''', '''.ircam''', '''.voc''', '''.w64''', '''.wav''', '''.nist''', '''.wavex''', '''.wve''', '''.xi''', '''.mp3''', '''.opus''', ] snake_case__ : str = AUDIO_EXTENSIONS
637
"""simple docstring""" import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def _snake_case ( _snake_case : Tuple , _snake_case : Union[str, Any]=10 ): lowerCAmelCase : Dict = [] for _ in range(_snake_case ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() return lrs def _snake_case ( _snake_case : Optional[int] , _snake_case : int=10 ): lowerCAmelCase : Optional[int] = [] for step in range(_snake_case ): lrs.append(scheduler.get_lr()[0] ) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: lowerCAmelCase : List[str] = os.path.join(_snake_case , '''schedule.bin''' ) torch.save(scheduler.state_dict() , _snake_case ) lowerCAmelCase : List[Any] = torch.load(_snake_case ) scheduler.load_state_dict(_snake_case ) return lrs @require_torch class snake_case_( unittest.TestCase ): def lowerCamelCase__ ( self : Optional[int] , UpperCamelCase_ : Optional[int] , UpperCamelCase_ : str , UpperCamelCase_ : Any ): self.assertEqual(len(UpperCamelCase_ ) , len(UpperCamelCase_ ) ) for a, b in zip(UpperCamelCase_ , UpperCamelCase_ ): self.assertAlmostEqual(UpperCamelCase_ , UpperCamelCase_ , delta=UpperCamelCase_ ) def lowerCamelCase__ ( self : Tuple ): lowerCAmelCase : Any = torch.tensor([0.1, -0.2, -0.1] , requires_grad=UpperCamelCase_ ) lowerCAmelCase : List[str] = torch.tensor([0.4, 0.2, -0.5] ) lowerCAmelCase : List[Any] = nn.MSELoss() # No warmup, constant schedule, no gradient clipping lowerCAmelCase : Union[str, Any] = AdamW(params=[w] , lr=2E-1 , weight_decay=0.0 ) for _ in range(1_0_0 ): lowerCAmelCase : Union[str, Any] = criterion(UpperCamelCase_ , UpperCamelCase_ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1E-2 ) def lowerCamelCase__ ( self : Union[str, Any] ): lowerCAmelCase : Tuple = torch.tensor([0.1, -0.2, -0.1] , requires_grad=UpperCamelCase_ ) lowerCAmelCase : Union[str, Any] = torch.tensor([0.4, 0.2, -0.5] ) lowerCAmelCase : Optional[int] = nn.MSELoss() # No warmup, constant schedule, no gradient clipping lowerCAmelCase : Any = Adafactor( params=[w] , lr=1E-2 , eps=(1E-30, 1E-3) , clip_threshold=1.0 , decay_rate=-0.8 , betaa=UpperCamelCase_ , weight_decay=0.0 , relative_step=UpperCamelCase_ , scale_parameter=UpperCamelCase_ , warmup_init=UpperCamelCase_ , ) for _ in range(1_0_0_0 ): lowerCAmelCase : List[Any] = criterion(UpperCamelCase_ , UpperCamelCase_ ) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist() , [0.4, 0.2, -0.5] , tol=1E-2 ) @require_torch class snake_case_( unittest.TestCase ): __UpperCamelCase = nn.Linear(50 , 50 ) if is_torch_available() else None __UpperCamelCase = AdamW(m.parameters() , lr=10.0 ) if is_torch_available() else None __UpperCamelCase = 10 def lowerCamelCase__ ( self : Union[str, Any] , UpperCamelCase_ : str , UpperCamelCase_ : str , UpperCamelCase_ : Optional[Any] , UpperCamelCase_ : Union[str, Any]=None ): self.assertEqual(len(UpperCamelCase_ ) , len(UpperCamelCase_ ) ) for a, b in zip(UpperCamelCase_ , UpperCamelCase_ ): self.assertAlmostEqual(UpperCamelCase_ , UpperCamelCase_ , delta=UpperCamelCase_ , msg=UpperCamelCase_ ) def lowerCamelCase__ ( self : Union[str, Any] ): lowerCAmelCase : Tuple = {'''num_warmup_steps''': 2, '''num_training_steps''': 1_0} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) lowerCAmelCase : Optional[Any] = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {'''num_warmup_steps''': 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, '''num_cycles''': 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, '''power''': 2.0, '''lr_end''': 1E-7}, [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156], ), get_inverse_sqrt_schedule: ( {'''num_warmup_steps''': 2}, [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714], ), } for scheduler_func, data in scheds.items(): lowerCAmelCase, lowerCAmelCase : Union[str, Any] = data lowerCAmelCase : List[Any] = scheduler_func(self.optimizer , **UpperCamelCase_ ) self.assertEqual(len([scheduler.get_lr()[0]] ) , 1 ) lowerCAmelCase : str = unwrap_schedule(UpperCamelCase_ , self.num_steps ) self.assertListAlmostEqual( UpperCamelCase_ , UpperCamelCase_ , tol=1E-2 , msg=F'''failed for {scheduler_func} in normal scheduler''' , ) lowerCAmelCase : Optional[int] = scheduler_func(self.optimizer , **UpperCamelCase_ ) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(UpperCamelCase_ ) # wrap to test picklability of the schedule lowerCAmelCase : List[Any] = unwrap_and_save_reload_schedule(UpperCamelCase_ , self.num_steps ) self.assertListEqual(UpperCamelCase_ , UpperCamelCase_ , msg=F'''failed for {scheduler_func} in save and reload''' ) class snake_case_: def __init__( self : List[Any] , UpperCamelCase_ : Any ): lowerCAmelCase : Tuple = fn def __call__( self : Union[str, Any] , *UpperCamelCase_ : Optional[Any] , **UpperCamelCase_ : List[Any] ): return self.fn(*UpperCamelCase_ , **UpperCamelCase_ ) @classmethod def lowerCamelCase__ ( self : Any , UpperCamelCase_ : Optional[int] ): lowerCAmelCase : Union[str, Any] = list(map(self , scheduler.lr_lambdas ) )
637
1