code
stringlengths
86
54.5k
code_codestyle
int64
0
371
style_context
stringlengths
87
49.2k
style_context_codestyle
int64
0
349
label
int64
0
1
import importlib import shutil import threading import warnings from typing import List import fsspec import fsspec.asyn from . import compression from .hffilesystem import HfFileSystem SCREAMING_SNAKE_CASE_ = importlib.util.find_spec("""s3fs""") is not None if _has_safs: from .safilesystem import SaFileSystem # noqa: F401 SCREAMING_SNAKE_CASE_ = [ compression.BzaFileSystem, compression.GzipFileSystem, compression.LzaFileSystem, compression.XzFileSystem, compression.ZstdFileSystem, ] # Register custom filesystems for fs_class in COMPRESSION_FILESYSTEMS + [HfFileSystem]: if fs_class.protocol in fsspec.registry and fsspec.registry[fs_class.protocol] is not fs_class: warnings.warn(F'''A filesystem protocol was already set for {fs_class.protocol} and will be overwritten.''') fsspec.register_implementation(fs_class.protocol, fs_class, clobber=True) def __lowercase ( _SCREAMING_SNAKE_CASE ) -> str: '''simple docstring''' if "://" in dataset_path: SCREAMING_SNAKE_CASE = dataset_path.split("""://""" )[1] return dataset_path def __lowercase ( _SCREAMING_SNAKE_CASE ) -> bool: '''simple docstring''' if fs is not None and fs.protocol != "file": return True else: return False def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Dict: '''simple docstring''' SCREAMING_SNAKE_CASE = not is_remote_filesystem(_SCREAMING_SNAKE_CASE ) if is_local: # LocalFileSystem.mv does copy + rm, it is more efficient to simply move a local directory shutil.move(fs._strip_protocol(_SCREAMING_SNAKE_CASE ) , fs._strip_protocol(_SCREAMING_SNAKE_CASE ) ) else: fs.mv(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , recursive=_SCREAMING_SNAKE_CASE ) def __lowercase ( ) -> None: '''simple docstring''' if hasattr(fsspec.asyn , """reset_lock""" ): # for future fsspec>2022.05.0 fsspec.asyn.reset_lock() else: SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = threading.Lock()
296
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_ = random.Random() def __lowercase ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE=1.0 , _SCREAMING_SNAKE_CASE=None , _SCREAMING_SNAKE_CASE=None ) -> Tuple: '''simple docstring''' if rng is None: SCREAMING_SNAKE_CASE = global_rng SCREAMING_SNAKE_CASE = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values class UpperCamelCase__ ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[Any] ,lowerCamelCase__ : str ,lowerCamelCase__ : Optional[int]=7 ,lowerCamelCase__ : Optional[Any]=400 ,lowerCamelCase__ : List[str]=2000 ,lowerCamelCase__ : List[str]=2048 ,lowerCamelCase__ : Any=128 ,lowerCamelCase__ : List[str]=1 ,lowerCamelCase__ : str=512 ,lowerCamelCase__ : Optional[Any]=30 ,lowerCamelCase__ : Tuple=44100 ,) -> Tuple: '''simple docstring''' SCREAMING_SNAKE_CASE = parent SCREAMING_SNAKE_CASE = batch_size SCREAMING_SNAKE_CASE = min_seq_length SCREAMING_SNAKE_CASE = max_seq_length SCREAMING_SNAKE_CASE = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) SCREAMING_SNAKE_CASE = spectrogram_length SCREAMING_SNAKE_CASE = feature_size SCREAMING_SNAKE_CASE = num_audio_channels SCREAMING_SNAKE_CASE = hop_length SCREAMING_SNAKE_CASE = chunk_length SCREAMING_SNAKE_CASE = sampling_rate def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> Optional[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 SCREAMING_SNAKE_CASE__ ( self : Optional[int] ,lowerCamelCase__ : Tuple=False ,lowerCamelCase__ : Union[str, Any]=False ) -> str: '''simple docstring''' def _flatten(lowerCamelCase__ : List[Any] ): return list(itertools.chain(*lowerCamelCase__ ) ) if equal_length: SCREAMING_SNAKE_CASE = [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 = [ 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 = [np.asarray(lowerCamelCase__ ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class UpperCamelCase__ ( lowerCAmelCase_ , unittest.TestCase ): '''simple docstring''' __snake_case : List[Any] = TvltFeatureExtractor def SCREAMING_SNAKE_CASE__ ( self : str ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = TvltFeatureExtractionTester(self ) def SCREAMING_SNAKE_CASE__ ( self : List[Any] ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) self.assertTrue(hasattr(lowerCamelCase__ ,"""spectrogram_length""" ) ) self.assertTrue(hasattr(lowerCamelCase__ ,"""feature_size""" ) ) self.assertTrue(hasattr(lowerCamelCase__ ,"""num_audio_channels""" ) ) self.assertTrue(hasattr(lowerCamelCase__ ,"""hop_length""" ) ) self.assertTrue(hasattr(lowerCamelCase__ ,"""chunk_length""" ) ) self.assertTrue(hasattr(lowerCamelCase__ ,"""sampling_rate""" ) ) def SCREAMING_SNAKE_CASE__ ( self : str ) -> Union[str, Any]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE = feat_extract_first.save_pretrained(lowerCamelCase__ )[0] check_json_file_has_correct_format(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_pretrained(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE = dict_first.pop("""mel_filters""" ) SCREAMING_SNAKE_CASE = dict_second.pop("""mel_filters""" ) self.assertTrue(np.allclose(lowerCamelCase__ ,lowerCamelCase__ ) ) self.assertEqual(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : Any ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) with tempfile.TemporaryDirectory() as tmpdirname: SCREAMING_SNAKE_CASE = os.path.join(lowerCamelCase__ ,"""feat_extract.json""" ) feat_extract_first.to_json_file(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = self.feature_extraction_class.from_json_file(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = feat_extract_first.to_dict() SCREAMING_SNAKE_CASE = feat_extract_second.to_dict() SCREAMING_SNAKE_CASE = dict_first.pop("""mel_filters""" ) SCREAMING_SNAKE_CASE = dict_second.pop("""mel_filters""" ) self.assertTrue(np.allclose(lowerCamelCase__ ,lowerCamelCase__ ) ) self.assertEqual(lowerCamelCase__ ,lowerCamelCase__ ) def SCREAMING_SNAKE_CASE__ ( self : str ) -> Optional[int]: '''simple docstring''' SCREAMING_SNAKE_CASE = self.feature_extraction_class(**self.feat_extract_dict ) # create three inputs of length 800, 1000, and 1200 SCREAMING_SNAKE_CASE = [floats_list((1, x) )[0] for x in range(800 ,1400 ,200 )] SCREAMING_SNAKE_CASE = [np.asarray(lowerCamelCase__ ) for speech_input in speech_inputs] # Test not batched input SCREAMING_SNAKE_CASE = feature_extractor(np_speech_inputs[0] ,return_tensors="""np""" ,sampling_rate=44100 ).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 = feature_extractor(lowerCamelCase__ ,return_tensors="""np""" ,sampling_rate=44100 ).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 = feature_extractor( lowerCamelCase__ ,return_tensors="""np""" ,sampling_rate=44100 ,mask_audio=lowerCamelCase__ ).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 = [floats_list((1, x) )[0] for x in (800, 800, 800)] SCREAMING_SNAKE_CASE = np.asarray(lowerCamelCase__ ) SCREAMING_SNAKE_CASE = feature_extractor(lowerCamelCase__ ,return_tensors="""np""" ,sampling_rate=44100 ).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 SCREAMING_SNAKE_CASE__ ( self : Any ,lowerCamelCase__ : str ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = load_dataset("""hf-internal-testing/librispeech_asr_dummy""" ,"""clean""" ,split="""validation""" ) # automatic decoding with librispeech SCREAMING_SNAKE_CASE = ds.sort("""id""" ).select(range(lowerCamelCase__ ) )[:num_samples]["""audio"""] return [x["array"] for x in speech_samples] def SCREAMING_SNAKE_CASE__ ( self : Tuple ) -> Any: '''simple docstring''' SCREAMING_SNAKE_CASE = self._load_datasamples(1 ) SCREAMING_SNAKE_CASE = TvltFeatureExtractor() SCREAMING_SNAKE_CASE = feature_extractor(lowerCamelCase__ ,return_tensors="""pt""" ).audio_values self.assertEquals(audio_values.shape ,(1, 1, 192, 128) ) SCREAMING_SNAKE_CASE = torch.tensor([[-0.3032, -0.2708], [-0.4434, -0.4007]] ) self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2] ,lowerCamelCase__ ,atol=1e-4 ) )
296
1
import warnings from typing import Dict, List, Optional, Tuple from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging UpperCAmelCase_ : Dict = logging.get_logger(__name__) class SCREAMING_SNAKE_CASE__ ( __SCREAMING_SNAKE_CASE ): snake_case__ : Tuple = ["input_ids", "attention_mask"] def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : str="</s>" , SCREAMING_SNAKE_CASE__ : List[Any]="<unk>" , SCREAMING_SNAKE_CASE__ : Optional[int]="<pad>" , SCREAMING_SNAKE_CASE__ : str=1_2_5 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=None , **SCREAMING_SNAKE_CASE__ : Dict , ) -> str: # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: a_ : Optional[int] = [F"""<extra_id_{i}>""" for i in range(_snake_case )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens a_ : List[Any] = len(set(filter(lambda SCREAMING_SNAKE_CASE__ : bool('extra_id' in str(_snake_case ) ) , _snake_case ) ) ) if extra_tokens != extra_ids: raise ValueError( F"""Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are""" ' provided to ByT5Tokenizer. In this case the additional_special_tokens must include the' ' extra_ids tokens' ) a_ : str = AddedToken(_snake_case , lstrip=_snake_case , rstrip=_snake_case ) if isinstance(_snake_case , _snake_case ) else pad_token a_ : Tuple = AddedToken(_snake_case , lstrip=_snake_case , rstrip=_snake_case ) if isinstance(_snake_case , _snake_case ) else eos_token a_ : Union[str, Any] = AddedToken(_snake_case , lstrip=_snake_case , rstrip=_snake_case ) if isinstance(_snake_case , _snake_case ) else unk_token super().__init__( eos_token=_snake_case , unk_token=_snake_case , pad_token=_snake_case , extra_ids=_snake_case , additional_special_tokens=_snake_case , **_snake_case , ) a_ : Union[str, Any] = extra_ids a_ : Dict = 2**8 # utf is 8 bits # define special tokens dict a_ : Dict[int, str] = { self.pad_token: 0, self.eos_token: 1, self.unk_token: 2, } a_ : Any = len(self.special_tokens_encoder ) a_ : List[str] = len(_snake_case ) for i, token in enumerate(_snake_case ): a_ : List[str] = self.vocab_size + i - n a_ : Dict[str, int] = {v: k for k, v in self.special_tokens_encoder.items()} @property def SCREAMING_SNAKE_CASE ( self : Dict ) -> List[str]: return self._utf_vocab_size + self._num_special_tokens + self._extra_ids def SCREAMING_SNAKE_CASE ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Dict = None , SCREAMING_SNAKE_CASE__ : Tuple = False ) -> Optional[int]: if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=_snake_case , token_ids_a=_snake_case , already_has_special_tokens=_snake_case ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(_snake_case )) + [1] return ([0] * len(_snake_case )) + [1] + ([0] * len(_snake_case )) + [1] def SCREAMING_SNAKE_CASE ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : List[Any] ) -> Tuple: if len(_snake_case ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( F"""This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated""" ' eos tokens being added.' ) return token_ids else: return token_ids + [self.eos_token_id] def SCREAMING_SNAKE_CASE ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : Union[str, Any] = None ) -> Any: a_ : List[Any] = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def SCREAMING_SNAKE_CASE ( self : str , SCREAMING_SNAKE_CASE__ : List[Any] , SCREAMING_SNAKE_CASE__ : List[Any] = None ) -> str: a_ : List[Any] = self._add_eos_if_not_present(_snake_case ) if token_ids_a is None: return token_ids_a else: a_ : Tuple = self._add_eos_if_not_present(_snake_case ) return token_ids_a + token_ids_a def SCREAMING_SNAKE_CASE ( self : List[str] , SCREAMING_SNAKE_CASE__ : int ) -> Dict: a_ : List[Any] = [chr(_snake_case ) for i in text.encode('utf-8' )] return tokens def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: if token in self.special_tokens_encoder: a_ : Optional[Any] = self.special_tokens_encoder[token] elif token in self.added_tokens_encoder: a_ : str = self.added_tokens_encoder[token] elif len(_snake_case ) != 1: a_ : Optional[int] = self.unk_token_id else: a_ : Union[str, Any] = ord(_snake_case ) + self._num_special_tokens return token_id def SCREAMING_SNAKE_CASE ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> Optional[int]: if index in self.special_tokens_decoder: a_ : Tuple = self.special_tokens_decoder[index] else: a_ : int = chr(index - self._num_special_tokens ) return token def SCREAMING_SNAKE_CASE ( self : int , SCREAMING_SNAKE_CASE__ : Tuple ) -> Any: a_ : Optional[int] = b"" for token in tokens: if token in self.special_tokens_decoder: a_ : Union[str, Any] = self.special_tokens_decoder[token].encode('utf-8' ) elif token in self.added_tokens_decoder: a_ : Dict = self.special_tokens_decoder[token].encode('utf-8' ) elif token in self.special_tokens_encoder: a_ : Optional[int] = token.encode('utf-8' ) elif token in self.added_tokens_encoder: a_ : Any = token.encode('utf-8' ) else: a_ : Optional[Any] = bytes([ord(_snake_case )] ) bstring += tok_string a_ : Tuple = bstring.decode('utf-8' , errors='ignore' ) return string def SCREAMING_SNAKE_CASE ( self : List[str] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : Union[str, Any] = None ) -> str: return ()
351
from typing import List, Optional, Tuple, Union import torch from torch import nn from torch.nn import CrossEntropyLoss from ... import AutoBackbone from ...modeling_outputs import SemanticSegmenterOutput from ...modeling_utils import PreTrainedModel from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings from ...utils.backbone_utils import BackboneMixin from .configuration_upernet import UperNetConfig UpperCAmelCase_ : Dict = [ 'openmmlab/upernet-convnext-tiny', # See all UperNet models at https://huggingface.co/models?filter=upernet ] # General docstring UpperCAmelCase_ : Dict = 'UperNetConfig' class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__( self : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : Union[int, Tuple[int, int]] , SCREAMING_SNAKE_CASE__ : Union[int, Tuple[int, int], str] = 0 , SCREAMING_SNAKE_CASE__ : bool = False , SCREAMING_SNAKE_CASE__ : Union[int, Tuple[int, int]] = 1 , ) -> None: super().__init__() a_ : Dict = nn.Convad( in_channels=SCREAMING_SNAKE_CASE__ , out_channels=SCREAMING_SNAKE_CASE__ , kernel_size=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , bias=SCREAMING_SNAKE_CASE__ , dilation=SCREAMING_SNAKE_CASE__ , ) a_ : List[str] = nn.BatchNormad(SCREAMING_SNAKE_CASE__ ) a_ : Tuple = nn.ReLU() def SCREAMING_SNAKE_CASE ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : torch.Tensor ) -> torch.Tensor: a_ : int = self.conv(SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = self.batch_norm(SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = self.activation(SCREAMING_SNAKE_CASE__ ) return output class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__( self : str , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int ) -> None: super().__init__() a_ : str = [ nn.AdaptiveAvgPoolad(SCREAMING_SNAKE_CASE__ ), UperNetConvModule(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , kernel_size=1 ), ] for i, layer in enumerate(self.layers ): self.add_module(str(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Any , SCREAMING_SNAKE_CASE__ : torch.Tensor ) -> torch.Tensor: a_ : Optional[int] = input for layer in self.layers: a_ : int = layer(SCREAMING_SNAKE_CASE__ ) return hidden_state class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Tuple[int, ...] , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : int , SCREAMING_SNAKE_CASE__ : bool ) -> None: super().__init__() a_ : Tuple = pool_scales a_ : List[Any] = align_corners a_ : Tuple = in_channels a_ : Optional[Any] = channels a_ : Tuple = [] for i, pool_scale in enumerate(SCREAMING_SNAKE_CASE__ ): a_ : Optional[int] = UperNetPyramidPoolingBlock(pool_scale=SCREAMING_SNAKE_CASE__ , in_channels=SCREAMING_SNAKE_CASE__ , channels=SCREAMING_SNAKE_CASE__ ) self.blocks.append(SCREAMING_SNAKE_CASE__ ) self.add_module(str(SCREAMING_SNAKE_CASE__ ) , SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : Any , SCREAMING_SNAKE_CASE__ : torch.Tensor ) -> List[torch.Tensor]: a_ : List[Any] = [] for ppm in self.blocks: a_ : List[Any] = ppm(SCREAMING_SNAKE_CASE__ ) a_ : str = nn.functional.interpolate( SCREAMING_SNAKE_CASE__ , size=x.size()[2:] , mode='bilinear' , align_corners=self.align_corners ) ppm_outs.append(SCREAMING_SNAKE_CASE__ ) return ppm_outs class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : str ) -> Tuple: super().__init__() a_ : List[str] = config a_ : Optional[int] = config.pool_scales # e.g. (1, 2, 3, 6) a_ : int = in_channels a_ : Dict = config.hidden_size a_ : Optional[Any] = False a_ : Tuple = nn.Convad(self.channels , config.num_labels , kernel_size=1 ) # PSP Module a_ : int = UperNetPyramidPoolingModule( self.pool_scales , self.in_channels[-1] , self.channels , align_corners=self.align_corners , ) a_ : int = UperNetConvModule( self.in_channels[-1] + len(self.pool_scales ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) # FPN Module a_ : str = nn.ModuleList() a_ : Dict = nn.ModuleList() for in_channels in self.in_channels[:-1]: # skip the top layer a_ : str = UperNetConvModule(SCREAMING_SNAKE_CASE__ , self.channels , kernel_size=1 ) a_ : Union[str, Any] = UperNetConvModule(self.channels , self.channels , kernel_size=3 , padding=1 ) self.lateral_convs.append(SCREAMING_SNAKE_CASE__ ) self.fpn_convs.append(SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = UperNetConvModule( len(self.in_channels ) * self.channels , self.channels , kernel_size=3 , padding=1 , ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: self.apply(self._init_weights ) def SCREAMING_SNAKE_CASE ( self : List[str] , SCREAMING_SNAKE_CASE__ : Dict ) -> str: if isinstance(SCREAMING_SNAKE_CASE__ , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def SCREAMING_SNAKE_CASE ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Tuple ) -> Dict: a_ : Dict = inputs[-1] a_ : str = [x] psp_outs.extend(self.psp_modules(SCREAMING_SNAKE_CASE__ ) ) a_ : List[Any] = torch.cat(SCREAMING_SNAKE_CASE__ , dim=1 ) a_ : Dict = self.bottleneck(SCREAMING_SNAKE_CASE__ ) return output def SCREAMING_SNAKE_CASE ( self : str , SCREAMING_SNAKE_CASE__ : torch.Tensor ) -> torch.Tensor: # build laterals a_ : List[str] = [lateral_conv(encoder_hidden_states[i] ) for i, lateral_conv in enumerate(self.lateral_convs )] laterals.append(self.psp_forward(SCREAMING_SNAKE_CASE__ ) ) # build top-down path a_ : List[str] = len(SCREAMING_SNAKE_CASE__ ) for i in range(used_backbone_levels - 1 , 0 , -1 ): a_ : Optional[Any] = laterals[i - 1].shape[2:] a_ : List[Any] = laterals[i - 1] + nn.functional.interpolate( laterals[i] , size=SCREAMING_SNAKE_CASE__ , mode='bilinear' , align_corners=self.align_corners ) # build outputs a_ : List[Any] = [self.fpn_convs[i](laterals[i] ) for i in range(used_backbone_levels - 1 )] # append psp feature fpn_outs.append(laterals[-1] ) for i in range(used_backbone_levels - 1 , 0 , -1 ): a_ : int = nn.functional.interpolate( fpn_outs[i] , size=fpn_outs[0].shape[2:] , mode='bilinear' , align_corners=self.align_corners ) a_ : Optional[int] = torch.cat(SCREAMING_SNAKE_CASE__ , dim=1 ) a_ : Tuple = self.fpn_bottleneck(SCREAMING_SNAKE_CASE__ ) a_ : Dict = self.classifier(SCREAMING_SNAKE_CASE__ ) return output class SCREAMING_SNAKE_CASE__ ( nn.Module ): def __init__( self : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : int = 2 , SCREAMING_SNAKE_CASE__ : int = 3 , SCREAMING_SNAKE_CASE__ : Union[int, Tuple[int, int]] = 1 ) -> None: super().__init__() a_ : Optional[int] = config a_ : str = config.auxiliary_in_channels a_ : Optional[int] = config.auxiliary_channels a_ : List[str] = config.auxiliary_num_convs a_ : Dict = config.auxiliary_concat_input a_ : int = in_index a_ : List[Any] = (kernel_size // 2) * dilation a_ : List[Any] = [] convs.append( UperNetConvModule( self.in_channels , self.channels , kernel_size=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , dilation=SCREAMING_SNAKE_CASE__ ) ) for i in range(self.num_convs - 1 ): convs.append( UperNetConvModule( self.channels , self.channels , kernel_size=SCREAMING_SNAKE_CASE__ , padding=SCREAMING_SNAKE_CASE__ , dilation=SCREAMING_SNAKE_CASE__ ) ) if self.num_convs == 0: a_ : Optional[int] = nn.Identity() else: a_ : int = nn.Sequential(*SCREAMING_SNAKE_CASE__ ) if self.concat_input: a_ : Union[str, Any] = UperNetConvModule( self.in_channels + self.channels , self.channels , kernel_size=SCREAMING_SNAKE_CASE__ , padding=kernel_size // 2 ) a_ : List[str] = nn.Convad(self.channels , config.num_labels , kernel_size=1 ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> List[str]: self.apply(self._init_weights ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Any ) -> List[str]: if isinstance(SCREAMING_SNAKE_CASE__ , nn.Convad ): module.weight.data.normal_(mean=0.0 , std=self.config.initializer_range ) if module.bias is not None: module.bias.data.zero_() def SCREAMING_SNAKE_CASE ( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : torch.Tensor ) -> torch.Tensor: # just take the relevant feature maps a_ : Optional[int] = encoder_hidden_states[self.in_index] a_ : int = self.convs(SCREAMING_SNAKE_CASE__ ) if self.concat_input: a_ : Optional[Any] = self.conv_cat(torch.cat([hidden_states, output] , dim=1 ) ) a_ : Dict = self.classifier(SCREAMING_SNAKE_CASE__ ) return output class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Any = UperNetConfig snake_case__ : Optional[int] = '''pixel_values''' snake_case__ : Optional[int] = True def SCREAMING_SNAKE_CASE ( self : List[str] , SCREAMING_SNAKE_CASE__ : Optional[Any] ) -> str: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): module.backbone.init_weights() module.decode_head.init_weights() module.auxiliary_head.init_weights() def SCREAMING_SNAKE_CASE ( self : Dict ) -> Dict: self.backbone.init_weights() self.decode_head.init_weights() self.auxiliary_head.init_weights() def SCREAMING_SNAKE_CASE ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int=False ) -> Any: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): a_ : Dict = value UpperCAmelCase_ : int = R'\n Parameters:\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n config ([`UperNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n' UpperCAmelCase_ : Tuple = R'\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using\n [`AutoImageProcessor`]. See [`SegformerImageProcessor.__call__`] for details.\n output_attentions (`bool`, *optional*):\n Whether or not to return the attentions tensors of all attention layers in case the backbone has them. See\n `attentions` under returned tensors for more detail.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers of the backbone. See `hidden_states` under\n returned tensors for more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( '''UperNet framework leveraging any vision backbone e.g. for ADE20k, CityScapes.''' , lowercase__ , ) class SCREAMING_SNAKE_CASE__ ( lowercase__ ): def __init__( self : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: super().__init__(SCREAMING_SNAKE_CASE__ ) a_ : List[str] = AutoBackbone.from_config(config.backbone_config ) # Semantic segmentation head(s) a_ : List[Any] = UperNetHead(SCREAMING_SNAKE_CASE__ , in_channels=self.backbone.channels ) a_ : Dict = UperNetFCNHead(SCREAMING_SNAKE_CASE__ ) if config.use_auxiliary_head else None # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(UPERNET_INPUTS_DOCSTRING.format('batch_size, sequence_length' ) ) @replace_return_docstrings(output_type=SCREAMING_SNAKE_CASE__ , config_class=_CONFIG_FOR_DOC ) def SCREAMING_SNAKE_CASE ( self : List[Any] , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , SCREAMING_SNAKE_CASE__ : Optional[torch.Tensor] = None , SCREAMING_SNAKE_CASE__ : Optional[bool] = None , ) -> Union[tuple, SemanticSegmenterOutput]: a_ : Optional[Any] = return_dict if return_dict is not None else self.config.use_return_dict a_ : Tuple = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) a_ : int = output_attentions if output_attentions is not None else self.config.output_attentions a_ : str = self.backbone.forward_with_filtered_kwargs( SCREAMING_SNAKE_CASE__ , output_hidden_states=SCREAMING_SNAKE_CASE__ , output_attentions=SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = outputs.feature_maps a_ : Tuple = self.decode_head(SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = nn.functional.interpolate(SCREAMING_SNAKE_CASE__ , size=pixel_values.shape[2:] , mode='bilinear' , align_corners=SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = None if self.auxiliary_head is not None: a_ : Any = self.auxiliary_head(SCREAMING_SNAKE_CASE__ ) a_ : int = nn.functional.interpolate( SCREAMING_SNAKE_CASE__ , size=pixel_values.shape[2:] , mode='bilinear' , align_corners=SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = None if labels is not None: if self.config.num_labels == 1: raise ValueError('The number of labels should be greater than one' ) else: # compute weighted loss a_ : List[str] = CrossEntropyLoss(ignore_index=self.config.loss_ignore_index ) a_ : Optional[Any] = loss_fct(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) a_ : str = loss_fct(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) a_ : str = main_loss + self.config.auxiliary_loss_weight * auxiliary_loss if not return_dict: if output_hidden_states: a_ : Optional[Any] = (logits,) + outputs[1:] else: a_ : List[str] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return SemanticSegmenterOutput( loss=SCREAMING_SNAKE_CASE__ , logits=SCREAMING_SNAKE_CASE__ , hidden_states=outputs.hidden_states , attentions=outputs.attentions , )
120
0
import logging import os import sys from pathlib import Path from unittest.mock import patch from parameterized import parameterized from run_eval import run_generate from run_eval_search import run_search from transformers.testing_utils import CaptureStdout, TestCasePlus, slow from utils import ROUGE_KEYS logging.basicConfig(level=logging.DEBUG) snake_case_ : str = logging.getLogger() def A (__A : Path , __A : list ) -> Tuple: """simple docstring""" UpperCAmelCase_ = '''\n'''.join(__A ) Path(__A ).open('''w''' ).writelines(__A ) snake_case_ : Union[str, Any] = "patrickvonplaten/t5-tiny-random" snake_case_ : int = "sshleifer/bart-tiny-random" snake_case_ : List[str] = "sshleifer/tiny-mbart" snake_case_ : int = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logging.disable(logging.CRITICAL) # remove noisy download output from tracebacks class __snake_case ( a ): def lowerCamelCase ( self : List[str] , _snake_case : int): """simple docstring""" UpperCAmelCase_ = Path(self.get_auto_remove_tmp_dir()) / '''utest_input.source''' UpperCAmelCase_ = input_file_name.parent / '''utest_output.txt''' assert not output_file_name.exists() UpperCAmelCase_ = [''' New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County.'''] _dump_articles(_snake_case , _snake_case) UpperCAmelCase_ = str(Path(self.get_auto_remove_tmp_dir()) / '''scores.json''') UpperCAmelCase_ = '''translation_en_to_de''' if model == T5_TINY else '''summarization''' UpperCAmelCase_ = F""" run_eval_search.py {model} {input_file_name} {output_file_name} --score_path {score_path} --task {task} --num_beams 2 --length_penalty 2.0 """.split() with patch.object(_snake_case , '''argv''' , _snake_case): run_generate() assert Path(_snake_case).exists() # os.remove(Path(output_file_name)) def lowerCamelCase ( self : Tuple): """simple docstring""" self.run_eval_tester(_snake_case) @parameterized.expand([BART_TINY, MBART_TINY]) @slow def lowerCamelCase ( self : List[Any] , _snake_case : Tuple): """simple docstring""" self.run_eval_tester(_snake_case) @parameterized.expand([T5_TINY, MBART_TINY]) @slow def lowerCamelCase ( self : str , _snake_case : List[Any]): """simple docstring""" UpperCAmelCase_ = Path(self.get_auto_remove_tmp_dir()) / '''utest_input.source''' UpperCAmelCase_ = input_file_name.parent / '''utest_output.txt''' assert not output_file_name.exists() UpperCAmelCase_ = { '''en''': ['''Machine learning is great, isn\'t it?''', '''I like to eat bananas''', '''Tomorrow is another great day!'''], '''de''': [ '''Maschinelles Lernen ist großartig, oder?''', '''Ich esse gerne Bananen''', '''Morgen ist wieder ein toller Tag!''', ], } UpperCAmelCase_ = Path(self.get_auto_remove_tmp_dir()) UpperCAmelCase_ = str(tmp_dir / '''scores.json''') UpperCAmelCase_ = str(tmp_dir / '''val.target''') _dump_articles(_snake_case , text['''en''']) _dump_articles(_snake_case , text['''de''']) UpperCAmelCase_ = '''translation_en_to_de''' if model == T5_TINY else '''summarization''' UpperCAmelCase_ = F""" run_eval_search.py {model} {str(_snake_case)} {str(_snake_case)} --score_path {score_path} --reference_path {reference_path} --task {task} """.split() testargs.extend(['''--search''', '''num_beams=1:2 length_penalty=0.9:1.0''']) with patch.object(_snake_case , '''argv''' , _snake_case): with CaptureStdout() as cs: run_search() UpperCAmelCase_ = [''' num_beams | length_penalty''', model, '''Best score args'''] UpperCAmelCase_ = ['''Info'''] if "translation" in task: expected_strings.append('''bleu''') else: expected_strings.extend(_snake_case) for w in expected_strings: assert w in cs.out for w in un_expected_strings: assert w not in cs.out assert Path(_snake_case).exists() os.remove(Path(_snake_case))
51
from diffusers.utils.testing_utils import require_onnxruntime @require_onnxruntime class __snake_case : pass
51
1
"""simple docstring""" from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxCrossAttnUpBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, FlaxUpBlockaD, ) @flax.struct.dataclass class lowerCAmelCase_ ( lowerCAmelCase ): """simple docstring""" _lowerCAmelCase : jnp.ndarray @flax_register_to_config class lowerCAmelCase_ ( nn.Module , lowerCAmelCase , lowerCAmelCase ): """simple docstring""" _lowerCAmelCase : int = 32 _lowerCAmelCase : int = 4 _lowerCAmelCase : int = 4 _lowerCAmelCase : Tuple[str] = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) _lowerCAmelCase : Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D") _lowerCAmelCase : Union[bool, Tuple[bool]] = False _lowerCAmelCase : Tuple[int] = (320, 640, 1280, 1280) _lowerCAmelCase : int = 2 _lowerCAmelCase : Union[int, Tuple[int]] = 8 _lowerCAmelCase : Optional[Union[int, Tuple[int]]] = None _lowerCAmelCase : int = 1280 _lowerCAmelCase : float = 0.0 _lowerCAmelCase : bool = False _lowerCAmelCase : jnp.dtype = jnp.floataa _lowerCAmelCase : bool = True _lowerCAmelCase : int = 0 _lowerCAmelCase : bool = False def snake_case ( self , lowerCAmelCase ): """simple docstring""" snake_case = (1, self.in_channels, self.sample_size, self.sample_size) snake_case = jnp.zeros(lowerCAmelCase , dtype=jnp.floataa ) snake_case = jnp.ones((1,) , dtype=jnp.intaa ) snake_case = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) snake_case ,snake_case = jax.random.split(lowerCAmelCase ) snake_case = {'params': params_rng, 'dropout': dropout_rng} return self.init(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase )["params"] def snake_case ( self ): """simple docstring""" snake_case = self.block_out_channels snake_case = block_out_channels[0] * 4 if self.num_attention_heads is not None: raise ValueError( 'At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19.' ) # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. snake_case = self.num_attention_heads or self.attention_head_dim # input snake_case = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time snake_case = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) snake_case = FlaxTimestepEmbedding(lowerCAmelCase , dtype=self.dtype ) snake_case = self.only_cross_attention if isinstance(lowerCAmelCase , lowerCAmelCase ): snake_case = (only_cross_attention,) * len(self.down_block_types ) if isinstance(lowerCAmelCase , lowerCAmelCase ): snake_case = (num_attention_heads,) * len(self.down_block_types ) # down snake_case = [] snake_case = block_out_channels[0] for i, down_block_type in enumerate(self.down_block_types ): snake_case = output_channel snake_case = block_out_channels[i] snake_case = i == len(lowerCAmelCase ) - 1 if down_block_type == "CrossAttnDownBlock2D": snake_case = FlaxCrossAttnDownBlockaD( in_channels=lowerCAmelCase , out_channels=lowerCAmelCase , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: snake_case = FlaxDownBlockaD( in_channels=lowerCAmelCase , out_channels=lowerCAmelCase , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(lowerCAmelCase ) snake_case = down_blocks # mid snake_case = FlaxUNetMidBlockaDCrossAttn( in_channels=block_out_channels[-1] , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) # up snake_case = [] snake_case = list(reversed(lowerCAmelCase ) ) snake_case = list(reversed(lowerCAmelCase ) ) snake_case = list(reversed(lowerCAmelCase ) ) snake_case = reversed_block_out_channels[0] for i, up_block_type in enumerate(self.up_block_types ): snake_case = output_channel snake_case = reversed_block_out_channels[i] snake_case = reversed_block_out_channels[min(i + 1 , len(lowerCAmelCase ) - 1 )] snake_case = i == len(lowerCAmelCase ) - 1 if up_block_type == "CrossAttnUpBlock2D": snake_case = FlaxCrossAttnUpBlockaD( in_channels=lowerCAmelCase , out_channels=lowerCAmelCase , prev_output_channel=lowerCAmelCase , num_layers=self.layers_per_block + 1 , num_attention_heads=reversed_num_attention_heads[i] , add_upsample=not is_final_block , dropout=self.dropout , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) else: snake_case = FlaxUpBlockaD( in_channels=lowerCAmelCase , out_channels=lowerCAmelCase , prev_output_channel=lowerCAmelCase , num_layers=self.layers_per_block + 1 , add_upsample=not is_final_block , dropout=self.dropout , dtype=self.dtype , ) up_blocks.append(lowerCAmelCase ) snake_case = output_channel snake_case = up_blocks # out snake_case = nn.GroupNorm(num_groups=32 , epsilon=1E-5 ) snake_case = nn.Conv( self.out_channels , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) def __call__( self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase=None , lowerCAmelCase=None , lowerCAmelCase = True , lowerCAmelCase = False , ): """simple docstring""" if not isinstance(lowerCAmelCase , jnp.ndarray ): snake_case = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(lowerCAmelCase , jnp.ndarray ) and len(timesteps.shape ) == 0: snake_case = timesteps.astype(dtype=jnp.floataa ) snake_case = jnp.expand_dims(lowerCAmelCase , 0 ) snake_case = self.time_proj(lowerCAmelCase ) snake_case = self.time_embedding(lowerCAmelCase ) # 2. pre-process snake_case = jnp.transpose(lowerCAmelCase , (0, 2, 3, 1) ) snake_case = self.conv_in(lowerCAmelCase ) # 3. down snake_case = (sample,) for down_block in self.down_blocks: if isinstance(lowerCAmelCase , lowerCAmelCase ): snake_case ,snake_case = down_block(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , deterministic=not train ) else: snake_case ,snake_case = down_block(lowerCAmelCase , lowerCAmelCase , deterministic=not train ) down_block_res_samples += res_samples if down_block_additional_residuals is not None: snake_case = () for down_block_res_sample, down_block_additional_residual in zip( lowerCAmelCase , lowerCAmelCase ): down_block_res_sample += down_block_additional_residual new_down_block_res_samples += (down_block_res_sample,) snake_case = new_down_block_res_samples # 4. mid snake_case = self.mid_block(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , deterministic=not train ) if mid_block_additional_residual is not None: sample += mid_block_additional_residual # 5. up for up_block in self.up_blocks: snake_case = down_block_res_samples[-(self.layers_per_block + 1) :] snake_case = down_block_res_samples[: -(self.layers_per_block + 1)] if isinstance(lowerCAmelCase , lowerCAmelCase ): snake_case = up_block( lowerCAmelCase , temb=lowerCAmelCase , encoder_hidden_states=lowerCAmelCase , res_hidden_states_tuple=lowerCAmelCase , deterministic=not train , ) else: snake_case = up_block(lowerCAmelCase , temb=lowerCAmelCase , res_hidden_states_tuple=lowerCAmelCase , deterministic=not train ) # 6. post-process snake_case = self.conv_norm_out(lowerCAmelCase ) snake_case = nn.silu(lowerCAmelCase ) snake_case = self.conv_out(lowerCAmelCase ) snake_case = jnp.transpose(lowerCAmelCase , (0, 3, 1, 2) ) if not return_dict: return (sample,) return FlaxUNetaDConditionOutput(sample=lowerCAmelCase )
149
"""simple docstring""" import secrets from random import shuffle from string import ascii_letters, ascii_lowercase, ascii_uppercase, digits, punctuation def lowerCAmelCase__ ( _UpperCamelCase : int = 8 ) -> str: """simple docstring""" snake_case = ascii_letters + digits + punctuation return "".join(secrets.choice(_UpperCamelCase ) for _ in range(_UpperCamelCase ) ) def lowerCAmelCase__ ( _UpperCamelCase : str , _UpperCamelCase : int ) -> str: """simple docstring""" i -= len(_UpperCamelCase ) snake_case = i // 3 snake_case = i % 3 # chars = chars_incl + random_letters(ascii_letters, i / 3 + remainder) + # random_number(digits, i / 3) + random_characters(punctuation, i / 3) snake_case = ( chars_incl + random(_UpperCamelCase , quotient + remainder ) + random(_UpperCamelCase , _UpperCamelCase ) + random(_UpperCamelCase , _UpperCamelCase ) ) snake_case = list(_UpperCamelCase ) shuffle(_UpperCamelCase ) return "".join(_UpperCamelCase ) # random is a generalised function for letters, characters and numbers def lowerCAmelCase__ ( _UpperCamelCase : str , _UpperCamelCase : int ) -> str: """simple docstring""" return "".join(secrets.choice(_UpperCamelCase ) for _ in range(_UpperCamelCase ) ) def lowerCAmelCase__ ( _UpperCamelCase : Optional[Any] , _UpperCamelCase : Optional[Any] ) -> List[Any]: """simple docstring""" pass # Put your code here... def lowerCAmelCase__ ( _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Optional[Any] ) -> Any: """simple docstring""" pass # Put your code here... def lowerCAmelCase__ ( _UpperCamelCase : Dict , _UpperCamelCase : Optional[Any] ) -> Union[str, Any]: """simple docstring""" pass # Put your code here... def lowerCAmelCase__ ( _UpperCamelCase : str , _UpperCamelCase : int = 8 ) -> bool: """simple docstring""" if len(_UpperCamelCase ) < min_length: # Your Password must be at least 8 characters long return False snake_case = any(char in ascii_uppercase for char in password ) snake_case = any(char in ascii_lowercase for char in password ) snake_case = any(char in digits for char in password ) snake_case = any(char in punctuation for char in password ) return upper and lower and num and spec_char # Passwords should contain UPPERCASE, lowerase # numbers, and special characters def lowerCAmelCase__ ( ) -> Any: """simple docstring""" snake_case = int(input('Please indicate the max length of your password: ' ).strip() ) snake_case = input( 'Please indicate the characters that must be in your password: ' ).strip() print('Password generated:' , password_generator(_UpperCamelCase ) ) print( 'Alternative Password generated:' , alternative_password_generator(_UpperCamelCase , _UpperCamelCase ) , ) print('[If you are thinking of using this passsword, You better save it.]' ) if __name__ == "__main__": main()
149
1
import inspect import tempfile import unittest from huggingface_hub import hf_hub_download from transformers import is_torch_available from transformers.testing_utils import is_flaky, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin SCREAMING_SNAKE_CASE : Optional[Any] = 1E-4 if is_torch_available(): import torch from transformers import AutoformerConfig, AutoformerForPrediction, AutoformerModel from transformers.models.autoformer.modeling_autoformer import AutoformerDecoder, AutoformerEncoder @require_torch class _lowerCamelCase: def __init__( self, lowerCamelCase, lowerCamelCase=16, lowerCamelCase=13, lowerCamelCase=7, lowerCamelCase=14, lowerCamelCase=10, lowerCamelCase=19, lowerCamelCase=5, lowerCamelCase=4, lowerCamelCase=True, lowerCamelCase=16, lowerCamelCase=2, lowerCamelCase=4, lowerCamelCase=4, lowerCamelCase="gelu", lowerCamelCase=0.1, lowerCamelCase=0.1, lowerCamelCase=[1, 2, 3, 4, 5], lowerCamelCase=25, lowerCamelCase=5, ) -> List[str]: """simple docstring""" _lowercase : Optional[Any] = d_model _lowercase : Optional[int] = parent _lowercase : Tuple = batch_size _lowercase : Optional[int] = prediction_length _lowercase : Optional[Any] = context_length _lowercase : Optional[int] = cardinality _lowercase : Union[str, Any] = num_time_features _lowercase : Union[str, Any] = lags_sequence _lowercase : Dict = embedding_dimension _lowercase : Dict = is_training _lowercase : List[Any] = hidden_size _lowercase : List[str] = num_hidden_layers _lowercase : Any = num_attention_heads _lowercase : List[Any] = intermediate_size _lowercase : Optional[Any] = hidden_act _lowercase : str = hidden_dropout_prob _lowercase : str = attention_probs_dropout_prob _lowercase : Union[str, Any] = context_length _lowercase : int = prediction_length + label_length _lowercase : Any = label_length _lowercase : str = moving_average _lowercase : int = autocorrelation_factor def UpperCamelCase ( self) -> List[Any]: """simple docstring""" return AutoformerConfig( d_model=self.d_model, 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, prediction_length=self.prediction_length, context_length=self.context_length, label_length=self.label_length, lags_sequence=self.lags_sequence, num_time_features=self.num_time_features, num_static_categorical_features=1, cardinality=[self.cardinality], embedding_dimension=[self.embedding_dimension], moving_average=self.moving_average, ) def UpperCamelCase ( self, lowerCamelCase) -> List[Any]: """simple docstring""" _lowercase : List[Any] = config.context_length + max(config.lags_sequence) _lowercase : Tuple = ids_tensor([self.batch_size, 1], config.cardinality[0]) _lowercase : Optional[Any] = floats_tensor([self.batch_size, _past_length, config.num_time_features]) _lowercase : str = floats_tensor([self.batch_size, _past_length]) _lowercase : Optional[Any] = floats_tensor([self.batch_size, _past_length]) > 0.5 # decoder inputs _lowercase : str = floats_tensor([self.batch_size, config.prediction_length, config.num_time_features]) _lowercase : Dict = floats_tensor([self.batch_size, config.prediction_length]) _lowercase : Dict = { """past_values""": past_values, """static_categorical_features""": static_categorical_features, """past_time_features""": past_time_features, """past_observed_mask""": past_observed_mask, """future_time_features""": future_time_features, """future_values""": future_values, } return inputs_dict def UpperCamelCase ( self) -> Any: """simple docstring""" _lowercase : Tuple = self.get_config() _lowercase : List[str] = self.prepare_autoformer_inputs_dict(_SCREAMING_SNAKE_CASE) return config, inputs_dict def UpperCamelCase ( self) -> List[str]: """simple docstring""" _lowercase : int = self.prepare_config_and_inputs() return config, inputs_dict def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase) -> List[str]: """simple docstring""" _lowercase : List[Any] = AutoformerModel(config=_SCREAMING_SNAKE_CASE).to(_SCREAMING_SNAKE_CASE).eval() _lowercase : List[str] = model(**_SCREAMING_SNAKE_CASE) _lowercase : List[str] = outputs.encoder_last_hidden_state _lowercase : Optional[Any] = outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: _lowercase : Any = model.get_encoder() encoder.save_pretrained(_SCREAMING_SNAKE_CASE) _lowercase : Optional[int] = AutoformerEncoder.from_pretrained(_SCREAMING_SNAKE_CASE).to(_SCREAMING_SNAKE_CASE) _lowercase : Union[str, Any] = model.create_network_inputs(**_SCREAMING_SNAKE_CASE) _lowercase : Tuple = model.decomposition_layer(transformer_inputs[:, : config.context_length, ...]) _lowercase : int = torch.cat( (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...]), dim=-1, ) _lowercase : Optional[Any] = encoder(inputs_embeds=_SCREAMING_SNAKE_CASE)[0] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3) _lowercase : str = ( torch.mean(transformer_inputs[:, : config.context_length, ...], dim=1) .unsqueeze(1) .repeat(1, config.prediction_length, 1) ) _lowercase : Optional[int] = torch.zeros( [transformer_inputs.shape[0], config.prediction_length, transformer_inputs.shape[2]], device=enc_input.device, ) _lowercase : str = torch.cat( ( torch.cat((seasonal_input[:, -config.label_length :, ...], zeros), dim=1), feature[:, config.context_length - config.label_length :, ...], ), dim=-1, ) _lowercase : Optional[int] = torch.cat( ( torch.cat((trend_input[:, -config.label_length :, ...], mean), dim=1), feature[:, config.context_length - config.label_length :, ...], ), dim=-1, ) with tempfile.TemporaryDirectory() as tmpdirname: _lowercase : str = model.get_decoder() decoder.save_pretrained(_SCREAMING_SNAKE_CASE) _lowercase : Optional[Any] = AutoformerDecoder.from_pretrained(_SCREAMING_SNAKE_CASE).to(_SCREAMING_SNAKE_CASE) _lowercase : Dict = decoder( trend=_SCREAMING_SNAKE_CASE, inputs_embeds=_SCREAMING_SNAKE_CASE, encoder_hidden_states=_SCREAMING_SNAKE_CASE, )[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3) @require_torch class _lowerCamelCase( UpperCAmelCase__, UpperCAmelCase__, unittest.TestCase ): lowercase_ : Any = (AutoformerModel, AutoformerForPrediction) if is_torch_available() else () lowercase_ : Any = (AutoformerForPrediction,) if is_torch_available() else () lowercase_ : int = {'feature-extraction': AutoformerModel} if is_torch_available() else {} lowercase_ : List[Any] = False lowercase_ : Tuple = False lowercase_ : Any = False lowercase_ : Union[str, Any] = False lowercase_ : Optional[Any] = False lowercase_ : Union[str, Any] = False def UpperCamelCase ( self) -> Optional[int]: """simple docstring""" _lowercase : int = AutoformerModelTester(self) _lowercase : Tuple = ConfigTester(self, config_class=_SCREAMING_SNAKE_CASE, has_text_modality=_SCREAMING_SNAKE_CASE) def UpperCamelCase ( self) -> int: """simple docstring""" self.config_tester.run_common_tests() def UpperCamelCase ( self) -> Any: """simple docstring""" _lowercase : Tuple = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: _lowercase : int = model_class(_SCREAMING_SNAKE_CASE) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(_SCREAMING_SNAKE_CASE) _lowercase : Union[str, Any] = model_class.from_pretrained(_SCREAMING_SNAKE_CASE, output_loading_info=_SCREAMING_SNAKE_CASE) self.assertEqual(info['missing_keys'], []) def UpperCamelCase ( self) -> Any: """simple docstring""" _lowercase : List[Any] = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*_SCREAMING_SNAKE_CASE) @unittest.skip(reason='Model has no tokens embeddings') def UpperCamelCase ( self) -> Union[str, Any]: """simple docstring""" pass def UpperCamelCase ( self) -> int: """simple docstring""" _lowercase : Union[str, Any] = inspect.signature(getattr(_SCREAMING_SNAKE_CASE, 'forward')) # The main input is the name of the argument after `self` _lowercase : Any = list(model_signature.parameters.keys())[1] self.assertEqual(AutoformerModel.main_input_name, _SCREAMING_SNAKE_CASE) def UpperCamelCase ( self) -> Union[str, Any]: """simple docstring""" _lowercase : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _lowercase : int = model_class(_SCREAMING_SNAKE_CASE) _lowercase : int = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic _lowercase : Any = [*signature.parameters.keys()] _lowercase : Optional[int] = [ """past_values""", """past_time_features""", """past_observed_mask""", """static_categorical_features""", """static_real_features""", """future_values""", """future_time_features""", ] if model.__class__.__name__ in ["AutoformerForPrediction"]: expected_arg_names.append('future_observed_mask') expected_arg_names.extend( [ 'decoder_attention_mask', 'head_mask', 'decoder_head_mask', 'cross_attn_head_mask', 'encoder_outputs', 'past_key_values', 'output_hidden_states', 'output_attentions', 'use_cache', 'return_dict', ]) self.assertListEqual(arg_names[: len(_SCREAMING_SNAKE_CASE)], _SCREAMING_SNAKE_CASE) def UpperCamelCase ( self) -> Union[str, Any]: """simple docstring""" _lowercase : Any = self.model_tester.prepare_config_and_inputs_for_common() _lowercase : List[Any] = True _lowercase : List[str] = getattr(self.model_tester, 'seq_length', _SCREAMING_SNAKE_CASE) _lowercase : Any = getattr(self.model_tester, 'decoder_seq_length', _SCREAMING_SNAKE_CASE) _lowercase : Union[str, Any] = getattr(self.model_tester, 'encoder_seq_length', _SCREAMING_SNAKE_CASE) _lowercase : Tuple = getattr(self.model_tester, 'd_model', _SCREAMING_SNAKE_CASE) _lowercase : Optional[Any] = getattr(self.model_tester, 'num_attention_heads', _SCREAMING_SNAKE_CASE) _lowercase : Optional[int] = d_model // num_attention_heads for model_class in self.all_model_classes: _lowercase : Any = True _lowercase : List[Any] = False _lowercase : Union[str, Any] = True _lowercase : List[Any] = model_class(_SCREAMING_SNAKE_CASE) model.to(_SCREAMING_SNAKE_CASE) model.eval() with torch.no_grad(): _lowercase : List[str] = model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE)) _lowercase : Optional[int] = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(_SCREAMING_SNAKE_CASE), self.model_tester.num_hidden_layers) # check that output_attentions also work using config del inputs_dict["output_attentions"] _lowercase : str = True _lowercase : Tuple = model_class(_SCREAMING_SNAKE_CASE) model.to(_SCREAMING_SNAKE_CASE) model.eval() with torch.no_grad(): _lowercase : Optional[int] = model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE)) _lowercase : Any = outputs.encoder_attentions self.assertEqual(len(_SCREAMING_SNAKE_CASE), self.model_tester.num_hidden_layers) self.assertListEqual( list(attentions[0].shape[-3:]), [self.model_tester.num_attention_heads, encoder_seq_length, dim], ) _lowercase : Optional[Any] = len(_SCREAMING_SNAKE_CASE) _lowercase : int = 7 if "last_hidden_state" in outputs: correct_outlen += 1 if "trend" in outputs: correct_outlen += 1 if "past_key_values" in outputs: correct_outlen += 1 # past_key_values have been returned if "loss" in outputs: correct_outlen += 1 if "params" in outputs: correct_outlen += 1 self.assertEqual(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE) # decoder attentions _lowercase : str = outputs.decoder_attentions self.assertIsInstance(_SCREAMING_SNAKE_CASE, (list, tuple)) self.assertEqual(len(_SCREAMING_SNAKE_CASE), self.model_tester.num_hidden_layers) self.assertListEqual( list(decoder_attentions[0].shape[-3:]), [self.model_tester.num_attention_heads, decoder_seq_length, dim], ) # cross attentions _lowercase : Dict = outputs.cross_attentions self.assertIsInstance(_SCREAMING_SNAKE_CASE, (list, tuple)) self.assertEqual(len(_SCREAMING_SNAKE_CASE), self.model_tester.num_hidden_layers) self.assertListEqual( list(cross_attentions[0].shape[-3:]), [self.model_tester.num_attention_heads, decoder_seq_length, dim], ) # Check attention is always last and order is fine _lowercase : int = True _lowercase : Optional[Any] = True _lowercase : List[Any] = model_class(_SCREAMING_SNAKE_CASE) model.to(_SCREAMING_SNAKE_CASE) model.eval() with torch.no_grad(): _lowercase : Dict = model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE, _SCREAMING_SNAKE_CASE)) self.assertEqual(out_len + 2, len(_SCREAMING_SNAKE_CASE)) _lowercase : Tuple = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(_SCREAMING_SNAKE_CASE), self.model_tester.num_hidden_layers) self.assertListEqual( list(self_attentions[0].shape[-3:]), [self.model_tester.num_attention_heads, encoder_seq_length, dim], ) @is_flaky() def UpperCamelCase ( self) -> List[Any]: """simple docstring""" super().test_retain_grad_hidden_states_attentions() def UpperCamelCase_( lowerCamelCase_="train-batch.pt" ) -> int: _lowercase : List[str] = hf_hub_download(repo_id='hf-internal-testing/tourism-monthly-batch' , filename=lowerCamelCase_ , repo_type='dataset' ) _lowercase : List[str] = torch.load(lowerCamelCase_ , map_location=lowerCamelCase_ ) return batch @require_torch @slow class _lowerCamelCase( unittest.TestCase ): def UpperCamelCase ( self) -> List[str]: """simple docstring""" _lowercase : str = AutoformerModel.from_pretrained('huggingface/autoformer-tourism-monthly').to(_SCREAMING_SNAKE_CASE) _lowercase : Union[str, Any] = prepare_batch() with torch.no_grad(): _lowercase : Any = model( past_values=batch['past_values'], past_time_features=batch['past_time_features'], past_observed_mask=batch['past_observed_mask'], static_categorical_features=batch['static_categorical_features'], future_values=batch['future_values'], future_time_features=batch['future_time_features'], )[0] _lowercase : Union[str, Any] = torch.Size( (64, model.config.prediction_length + model.config.label_length, model.config.feature_size)) self.assertEqual(output.shape, _SCREAMING_SNAKE_CASE) _lowercase : str = torch.tensor( [[0.3_5_9_3, -1.3_3_9_8, 0.6_3_3_0], [0.2_2_7_9, 1.5_3_9_6, -0.1_7_9_2], [0.0_4_5_0, 1.3_2_2_5, -0.2_3_3_5]], device=_SCREAMING_SNAKE_CASE) self.assertTrue(torch.allclose(output[0, :3, :3], _SCREAMING_SNAKE_CASE, atol=_SCREAMING_SNAKE_CASE)) def UpperCamelCase ( self) -> Any: """simple docstring""" _lowercase : Any = AutoformerForPrediction.from_pretrained('huggingface/autoformer-tourism-monthly').to(_SCREAMING_SNAKE_CASE) _lowercase : Dict = prepare_batch('val-batch.pt') with torch.no_grad(): _lowercase : Dict = model( past_values=batch['past_values'], past_time_features=batch['past_time_features'], past_observed_mask=batch['past_observed_mask'], static_categorical_features=batch['static_categorical_features'], ).encoder_last_hidden_state _lowercase : List[str] = torch.Size((64, model.config.context_length, model.config.d_model)) self.assertEqual(output.shape, _SCREAMING_SNAKE_CASE) _lowercase : Union[str, Any] = torch.tensor( [[-0.0_7_3_4, -0.9_0_3_6, 0.8_3_5_8], [4.7_1_8_6, 2.4_1_1_3, 1.9_5_8_1], [1.7_9_5_3, 2.3_5_5_8, 1.2_9_7_0]], device=_SCREAMING_SNAKE_CASE) self.assertTrue(torch.allclose(output[0, :3, :3], _SCREAMING_SNAKE_CASE, atol=_SCREAMING_SNAKE_CASE)) def UpperCamelCase ( self) -> Tuple: """simple docstring""" _lowercase : str = AutoformerForPrediction.from_pretrained('huggingface/autoformer-tourism-monthly').to(_SCREAMING_SNAKE_CASE) _lowercase : Optional[Any] = prepare_batch('val-batch.pt') with torch.no_grad(): _lowercase : Union[str, Any] = model.generate( static_categorical_features=batch['static_categorical_features'], past_time_features=batch['past_time_features'], past_values=batch['past_values'], future_time_features=batch['future_time_features'], past_observed_mask=batch['past_observed_mask'], ) _lowercase : List[Any] = torch.Size((64, model.config.num_parallel_samples, model.config.prediction_length)) self.assertEqual(outputs.sequences.shape, _SCREAMING_SNAKE_CASE) _lowercase : Tuple = torch.tensor([3_1_3_0.6_7_6_3, 4_0_5_6.5_2_9_3, 7_0_5_3.0_7_8_6], device=_SCREAMING_SNAKE_CASE) _lowercase : Dict = outputs.sequences.mean(dim=1) self.assertTrue(torch.allclose(mean_prediction[0, -3:], _SCREAMING_SNAKE_CASE, rtol=1E-1))
21
"""simple docstring""" import inspect import warnings from typing import Any, Dict, Optional, Union from packaging import version def _snake_case ( *UpperCamelCase : str , UpperCamelCase : Optional[Union[Dict, Any]] = None , UpperCamelCase : Tuple=True , UpperCamelCase : Optional[int]=2 ): from .. import __version__ UpperCAmelCase : Tuple = take_from UpperCAmelCase : Optional[Any] = () if not isinstance(args[0] , UpperCamelCase ): UpperCAmelCase : List[str] = (args,) for attribute, version_name, message in args: if version.parse(version.parse(UpperCamelCase ).base_version ) >= version.parse(UpperCamelCase ): raise ValueError( F"The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers'" F" version {__version__} is >= {version_name}" ) UpperCAmelCase : Optional[int] = None if isinstance(UpperCamelCase , UpperCamelCase ) and attribute in deprecated_kwargs: values += (deprecated_kwargs.pop(UpperCamelCase ),) UpperCAmelCase : List[str] = F"The `{attribute}` argument is deprecated and will be removed in version {version_name}." elif hasattr(UpperCamelCase , UpperCamelCase ): values += (getattr(UpperCamelCase , UpperCamelCase ),) UpperCAmelCase : List[Any] = F"The `{attribute}` attribute is deprecated and will be removed in version {version_name}." elif deprecated_kwargs is None: UpperCAmelCase : int = F"`{attribute}` is deprecated and will be removed in version {version_name}." if warning is not None: UpperCAmelCase : Optional[Any] = warning + """ """ if standard_warn else """""" warnings.warn(warning + message , UpperCamelCase , stacklevel=UpperCamelCase ) if isinstance(UpperCamelCase , UpperCamelCase ) and len(UpperCamelCase ) > 0: UpperCAmelCase : Optional[int] = inspect.getouterframes(inspect.currentframe() )[1] UpperCAmelCase : Union[str, Any] = call_frame.filename UpperCAmelCase : List[Any] = call_frame.lineno UpperCAmelCase : List[str] = call_frame.function UpperCAmelCase , UpperCAmelCase : Optional[int] = next(iter(deprecated_kwargs.items() ) ) raise TypeError(F"{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`" ) if len(UpperCamelCase ) == 0: return elif len(UpperCamelCase ) == 1: return values[0] return values
109
0
"""simple docstring""" import gc import unittest from transformers import CTRLConfig, 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 ( CTRL_PRETRAINED_MODEL_ARCHIVE_LIST, CTRLForSequenceClassification, CTRLLMHeadModel, CTRLModel, ) class _UpperCAmelCase : """simple docstring""" def __init__( self : Any , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Tuple=1_4 , lowerCAmelCase_ : List[str]=7 , lowerCAmelCase_ : int=True , lowerCAmelCase_ : Union[str, Any]=True , lowerCAmelCase_ : List[Any]=True , lowerCAmelCase_ : Tuple=True , lowerCAmelCase_ : int=True , lowerCAmelCase_ : Optional[Any]=9_9 , lowerCAmelCase_ : Union[str, Any]=3_2 , lowerCAmelCase_ : List[Any]=5 , lowerCAmelCase_ : int=4 , lowerCAmelCase_ : List[str]=3_7 , lowerCAmelCase_ : Tuple="gelu" , lowerCAmelCase_ : Optional[Any]=0.1 , lowerCAmelCase_ : Union[str, Any]=0.1 , lowerCAmelCase_ : Tuple=5_1_2 , lowerCAmelCase_ : str=1_6 , lowerCAmelCase_ : Optional[Any]=2 , lowerCAmelCase_ : int=0.02 , lowerCAmelCase_ : str=3 , lowerCAmelCase_ : List[str]=4 , lowerCAmelCase_ : Optional[Any]=None , ) -> Any: __lowerCAmelCase = parent __lowerCAmelCase = batch_size __lowerCAmelCase = seq_length __lowerCAmelCase = is_training __lowerCAmelCase = use_token_type_ids __lowerCAmelCase = use_input_mask __lowerCAmelCase = use_labels __lowerCAmelCase = use_mc_token_ids __lowerCAmelCase = vocab_size __lowerCAmelCase = hidden_size __lowerCAmelCase = num_hidden_layers __lowerCAmelCase = num_attention_heads __lowerCAmelCase = intermediate_size __lowerCAmelCase = hidden_act __lowerCAmelCase = hidden_dropout_prob __lowerCAmelCase = attention_probs_dropout_prob __lowerCAmelCase = max_position_embeddings __lowerCAmelCase = type_vocab_size __lowerCAmelCase = type_sequence_label_size __lowerCAmelCase = initializer_range __lowerCAmelCase = num_labels __lowerCAmelCase = num_choices __lowerCAmelCase = scope __lowerCAmelCase = self.vocab_size - 1 def lowercase ( self : str ) -> List[str]: __lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __lowerCAmelCase = None if self.use_input_mask: __lowerCAmelCase = random_attention_mask([self.batch_size, self.seq_length] ) __lowerCAmelCase = None if self.use_token_type_ids: __lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __lowerCAmelCase = None if self.use_mc_token_ids: __lowerCAmelCase = ids_tensor([self.batch_size, self.num_choices] , self.seq_length ) __lowerCAmelCase = None __lowerCAmelCase = None __lowerCAmelCase = None if self.use_labels: __lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __lowerCAmelCase = ids_tensor([self.batch_size] , self.num_choices ) __lowerCAmelCase = self.get_config() __lowerCAmelCase = ids_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, token_labels, choice_labels, ) def lowercase ( self : Optional[Any] ) -> Tuple: return CTRLConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , pad_token_id=self.pad_token_id , ) def lowercase ( self : str , lowerCAmelCase_ : Any , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : List[str] , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Tuple , *lowerCAmelCase_ : Optional[int] ) -> Dict: __lowerCAmelCase = CTRLModel(config=SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() model(SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , head_mask=SCREAMING_SNAKE_CASE_ ) model(SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = model(SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(len(result.past_key_values ) , config.n_layer ) def lowercase ( self : Any , lowerCAmelCase_ : Any , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : Optional[Any] , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Optional[int] , *lowerCAmelCase_ : str ) -> Any: __lowerCAmelCase = CTRLLMHeadModel(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() __lowerCAmelCase = model(SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.loss.shape , () ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowercase ( self : Optional[int] ) -> Optional[int]: __lowerCAmelCase = self.prepare_config_and_inputs() ( __lowerCAmelCase ) = config_and_inputs __lowerCAmelCase = {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """head_mask""": head_mask} return config, inputs_dict def lowercase ( self : Union[str, Any] , lowerCAmelCase_ : Optional[int] , lowerCAmelCase_ : int , lowerCAmelCase_ : str , lowerCAmelCase_ : str , *lowerCAmelCase_ : int ) -> Optional[int]: __lowerCAmelCase = self.num_labels __lowerCAmelCase = CTRLForSequenceClassification(SCREAMING_SNAKE_CASE_ ) model.to(SCREAMING_SNAKE_CASE_ ) model.eval() __lowerCAmelCase = ids_tensor([self.batch_size] , self.type_sequence_label_size ) __lowerCAmelCase = model(SCREAMING_SNAKE_CASE_ , token_type_ids=SCREAMING_SNAKE_CASE_ , labels=SCREAMING_SNAKE_CASE_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) @require_torch class _UpperCAmelCase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): """simple docstring""" a_ = (CTRLModel, CTRLLMHeadModel, CTRLForSequenceClassification) if is_torch_available() else () a_ = (CTRLLMHeadModel,) if is_torch_available() else () a_ = ( { 'feature-extraction': CTRLModel, 'text-classification': CTRLForSequenceClassification, 'text-generation': CTRLLMHeadModel, 'zero-shot': CTRLForSequenceClassification, } if is_torch_available() else {} ) a_ = True a_ = False a_ = False def lowercase ( self : Union[str, Any] , lowerCAmelCase_ : Tuple , lowerCAmelCase_ : Dict , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Union[str, Any] , lowerCAmelCase_ : Optional[int] ) -> Tuple: if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests": # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers. # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny # config could not be created. return True return False def lowercase ( self : int ) -> List[str]: __lowerCAmelCase = CTRLModelTester(self ) __lowerCAmelCase = ConfigTester(self , config_class=SCREAMING_SNAKE_CASE_ , n_embd=3_7 ) def lowercase ( self : Optional[Any] ) -> Dict: super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() def lowercase ( self : List[Any] ) -> List[str]: self.config_tester.run_common_tests() def lowercase ( self : str ) -> Optional[int]: __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_ctrl_model(*SCREAMING_SNAKE_CASE_ ) def lowercase ( self : Tuple ) -> Any: __lowerCAmelCase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_lm_head_model(*SCREAMING_SNAKE_CASE_ ) @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def lowercase ( self : List[str] ) -> Optional[Any]: pass @slow def lowercase ( self : str ) -> Any: for model_name in CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowerCAmelCase = CTRLModel.from_pretrained(SCREAMING_SNAKE_CASE_ ) self.assertIsNotNone(SCREAMING_SNAKE_CASE_ ) @unittest.skip('The model doesn\'t support left padding' ) # and it's not used enough to be worth fixing :) def lowercase ( self : Tuple ) -> int: pass @require_torch class _UpperCAmelCase ( unittest.TestCase ): """simple docstring""" def lowercase ( self : Union[str, Any] ) -> Optional[Any]: super().tearDown() # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() torch.cuda.empty_cache() @slow def lowercase ( self : List[Any] ) -> Tuple: __lowerCAmelCase = CTRLLMHeadModel.from_pretrained('ctrl' ) model.to(SCREAMING_SNAKE_CASE_ ) __lowerCAmelCase = torch.tensor( [[1_1_8_5_9, 0, 1_6_1_1, 8]] , dtype=torch.long , device=SCREAMING_SNAKE_CASE_ ) # Legal the president is __lowerCAmelCase = [ 1_1_8_5_9, 0, 1_6_1_1, 8, 5, 1_5_0, 2_6_4_4_9, 2, 1_9, 3_4_8, 4_6_9, 3, 2_5_9_5, 4_8, 2_0_7_4_0, 2_4_6_5_3_3, 2_4_6_5_3_3, 1_9, 3_0, 5, ] # Legal the president is a good guy and I don't want to lose my job. \n \n I have a __lowerCAmelCase = model.generate(SCREAMING_SNAKE_CASE_ , do_sample=SCREAMING_SNAKE_CASE_ ) self.assertListEqual(output_ids[0].tolist() , SCREAMING_SNAKE_CASE_ )
355
import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class _UpperCAmelCase ( unittest.TestCase ): """simple docstring""" def lowercase ( self : List[str] ) -> int: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def lowercase ( self : Union[str, Any] ) -> Any: torch.manual_seed(0 ) __lowerCAmelCase = UNetaDModel( sample_size=(3_2, 6_4) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , ) return model @property def lowercase ( self : Optional[Any] ) -> List[Any]: torch.manual_seed(0 ) __lowerCAmelCase = UNetaDConditionModel( sample_size=(6_4, 3_2) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , cross_attention_dim=1_0 , ) return model @property def lowercase ( self : Dict ) -> Optional[Any]: torch.manual_seed(0 ) __lowerCAmelCase = AutoencoderKL( sample_size=(1_2_8, 6_4) , in_channels=1 , out_channels=1 , latent_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D') , up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D') , ) __lowerCAmelCase = UNetaDModel( sample_size=(6_4, 3_2) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_2_8, 1_2_8) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , ) return vqvae, unet @slow def lowercase ( self : Dict ) -> Optional[Any]: __lowerCAmelCase = 'cpu' # ensure determinism for the device-dependent torch.Generator __lowerCAmelCase = Mel( x_res=self.dummy_unet.config.sample_size[1] , y_res=self.dummy_unet.config.sample_size[0] , ) __lowerCAmelCase = DDPMScheduler() __lowerCAmelCase = AudioDiffusionPipeline(vqvae=lowerCAmelCase_ , unet=self.dummy_unet , mel=lowerCAmelCase_ , scheduler=lowerCAmelCase_ ) __lowerCAmelCase = pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) __lowerCAmelCase = torch.Generator(device=lowerCAmelCase_ ).manual_seed(4_2 ) __lowerCAmelCase = pipe(generator=lowerCAmelCase_ , steps=4 ) __lowerCAmelCase = output.audios[0] __lowerCAmelCase = output.images[0] __lowerCAmelCase = torch.Generator(device=lowerCAmelCase_ ).manual_seed(4_2 ) __lowerCAmelCase = pipe(generator=lowerCAmelCase_ , steps=4 , return_dict=lowerCAmelCase_ ) __lowerCAmelCase = output[0][0] assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length) assert ( image.height == self.dummy_unet.config.sample_size[0] and image.width == self.dummy_unet.config.sample_size[1] ) __lowerCAmelCase = np.frombuffer(image.tobytes() , dtype='uint8' )[:1_0] __lowerCAmelCase = np.frombuffer(image_from_tuple.tobytes() , dtype='uint8' )[:1_0] __lowerCAmelCase = np.array([6_9, 2_5_5, 2_5_5, 2_5_5, 0, 0, 7_7, 1_8_1, 1_2, 1_2_7] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() == 0 __lowerCAmelCase = Mel( x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1] , y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0] , ) __lowerCAmelCase = DDIMScheduler() __lowerCAmelCase = self.dummy_vqvae_and_unet __lowerCAmelCase = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=dummy_vqvae_and_unet[1] , mel=lowerCAmelCase_ , scheduler=lowerCAmelCase_ ) __lowerCAmelCase = pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) np.random.seed(0 ) __lowerCAmelCase = np.random.uniform(-1 , 1 , ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,) ) __lowerCAmelCase = torch.Generator(device=lowerCAmelCase_ ).manual_seed(4_2 ) __lowerCAmelCase = pipe(raw_audio=lowerCAmelCase_ , generator=lowerCAmelCase_ , start_step=5 , steps=1_0 ) __lowerCAmelCase = output.images[0] assert ( image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0] and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1] ) __lowerCAmelCase = np.frombuffer(image.tobytes() , dtype='uint8' )[:1_0] __lowerCAmelCase = np.array([1_2_0, 1_1_7, 1_1_0, 1_0_9, 1_3_8, 1_6_7, 1_3_8, 1_4_8, 1_3_2, 1_2_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 __lowerCAmelCase = self.dummy_unet_condition __lowerCAmelCase = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=lowerCAmelCase_ , mel=lowerCAmelCase_ , scheduler=lowerCAmelCase_ ) __lowerCAmelCase = pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) np.random.seed(0 ) __lowerCAmelCase = torch.rand((1, 1, 1_0) ) __lowerCAmelCase = pipe(generator=lowerCAmelCase_ , encoding=lowerCAmelCase_ ) __lowerCAmelCase = output.images[0] __lowerCAmelCase = np.frombuffer(image.tobytes() , dtype='uint8' )[:1_0] __lowerCAmelCase = np.array([1_0_7, 1_0_3, 1_2_0, 1_2_7, 1_4_2, 1_2_2, 1_1_3, 1_2_2, 9_7, 1_1_1] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 @slow @require_torch_gpu class _UpperCAmelCase ( unittest.TestCase ): """simple docstring""" def lowercase ( self : List[Any] ) -> Optional[int]: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase ( self : Union[str, Any] ) -> Optional[int]: __lowerCAmelCase = torch_device __lowerCAmelCase = DiffusionPipeline.from_pretrained('teticio/audio-diffusion-ddim-256' ) __lowerCAmelCase = pipe.to(lowerCAmelCase_ ) pipe.set_progress_bar_config(disable=lowerCAmelCase_ ) __lowerCAmelCase = torch.Generator(device=lowerCAmelCase_ ).manual_seed(4_2 ) __lowerCAmelCase = pipe(generator=lowerCAmelCase_ ) __lowerCAmelCase = output.audios[0] __lowerCAmelCase = output.images[0] assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length) assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1] __lowerCAmelCase = np.frombuffer(image.tobytes() , dtype='uint8' )[:1_0] __lowerCAmelCase = np.array([1_5_1, 1_6_7, 1_5_4, 1_4_4, 1_2_2, 1_3_4, 1_2_1, 1_0_5, 7_0, 2_6] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
207
0
import argparse import collections import torch from flax import traverse_util from tax import checkpoints from transformers import TaConfig, TaEncoderModel, TaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def SCREAMING_SNAKE_CASE_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__="attention" ) -> str: lowerCAmelCase = params[f"{prefix}/layers_{i}/{layer_name}/key/kernel"] lowerCAmelCase = params[f"{prefix}/layers_{i}/{layer_name}/out/kernel"] lowerCAmelCase = params[f"{prefix}/layers_{i}/{layer_name}/query/kernel"] lowerCAmelCase = params[f"{prefix}/layers_{i}/{layer_name}/value/kernel"] return k, o, q, v def SCREAMING_SNAKE_CASE_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__=False ) -> Optional[Any]: if split_mlp_wi: lowerCAmelCase = params[f"{prefix}/layers_{i}/mlp/wi_0/kernel"] lowerCAmelCase = params[f"{prefix}/layers_{i}/mlp/wi_1/kernel"] lowerCAmelCase = (wi_a, wi_a) else: lowerCAmelCase = params[f"{prefix}/layers_{i}/mlp/wi/kernel"] lowerCAmelCase = params[f"{prefix}/layers_{i}/mlp/wo/kernel"] return wi, wo def SCREAMING_SNAKE_CASE_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ ) -> Tuple: return params[f"{prefix}/layers_{i}/{layer_name}/scale"] def SCREAMING_SNAKE_CASE_ ( snake_case__ , *, snake_case__ , snake_case__ ) -> Optional[Any]: lowerCAmelCase = traverse_util.flatten_dict(variables['''target'''] ) lowerCAmelCase = {'''/'''.join(snake_case__ ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi lowerCAmelCase = '''encoder/layers_0/mlp/wi_0/kernel''' in old print('''Split MLP:''' , snake_case__ ) lowerCAmelCase = collections.OrderedDict() # Shared embeddings. lowerCAmelCase = old['''token_embedder/embedding'''] # Encoder. for i in range(snake_case__ ): # Block i, layer 0 (Self Attention). lowerCAmelCase = tax_layer_norm_lookup(snake_case__ , snake_case__ , '''encoder''' , '''pre_attention_layer_norm''' ) lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = tax_attention_lookup(snake_case__ , snake_case__ , '''encoder''' , '''attention''' ) lowerCAmelCase = layer_norm lowerCAmelCase = k.T lowerCAmelCase = o.T lowerCAmelCase = q.T lowerCAmelCase = v.T # Block i, layer 1 (MLP). lowerCAmelCase = tax_layer_norm_lookup(snake_case__ , snake_case__ , '''encoder''' , '''pre_mlp_layer_norm''' ) lowerCAmelCase , lowerCAmelCase = tax_mlp_lookup(snake_case__ , snake_case__ , '''encoder''' , snake_case__ ) lowerCAmelCase = layer_norm if split_mlp_wi: lowerCAmelCase = wi[0].T lowerCAmelCase = wi[1].T else: lowerCAmelCase = wi.T lowerCAmelCase = wo.T lowerCAmelCase = old[ '''encoder/relpos_bias/rel_embedding''' ].T lowerCAmelCase = old['''encoder/encoder_norm/scale'''] if not is_encoder_only: # Decoder. for i in range(snake_case__ ): # Block i, layer 0 (Self Attention). lowerCAmelCase = tax_layer_norm_lookup(snake_case__ , snake_case__ , '''decoder''' , '''pre_self_attention_layer_norm''' ) lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = tax_attention_lookup(snake_case__ , snake_case__ , '''decoder''' , '''self_attention''' ) lowerCAmelCase = layer_norm lowerCAmelCase = k.T lowerCAmelCase = o.T lowerCAmelCase = q.T lowerCAmelCase = v.T # Block i, layer 1 (Cross Attention). lowerCAmelCase = tax_layer_norm_lookup(snake_case__ , snake_case__ , '''decoder''' , '''pre_cross_attention_layer_norm''' ) lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase = tax_attention_lookup(snake_case__ , snake_case__ , '''decoder''' , '''encoder_decoder_attention''' ) lowerCAmelCase = layer_norm lowerCAmelCase = k.T lowerCAmelCase = o.T lowerCAmelCase = q.T lowerCAmelCase = v.T # Block i, layer 2 (MLP). lowerCAmelCase = tax_layer_norm_lookup(snake_case__ , snake_case__ , '''decoder''' , '''pre_mlp_layer_norm''' ) lowerCAmelCase , lowerCAmelCase = tax_mlp_lookup(snake_case__ , snake_case__ , '''decoder''' , snake_case__ ) lowerCAmelCase = layer_norm if split_mlp_wi: lowerCAmelCase = wi[0].T lowerCAmelCase = wi[1].T else: lowerCAmelCase = wi.T lowerCAmelCase = wo.T lowerCAmelCase = old['''decoder/decoder_norm/scale'''] lowerCAmelCase = old[ '''decoder/relpos_bias/rel_embedding''' ].T # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: lowerCAmelCase = old['''decoder/logits_dense/kernel'''].T return new def SCREAMING_SNAKE_CASE_ ( snake_case__ , snake_case__ ) -> Union[str, Any]: lowerCAmelCase = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: lowerCAmelCase = state_dict['''shared.weight'''] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: lowerCAmelCase = state_dict['''shared.weight'''] if "lm_head.weight" not in state_dict: # For old 1.0 models. print('''Using shared word embeddings as lm_head.''' ) lowerCAmelCase = state_dict['''shared.weight'''] return state_dict def SCREAMING_SNAKE_CASE_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ ) -> Union[str, Any]: lowerCAmelCase = checkpoints.load_tax_checkpoint(snake_case__ ) lowerCAmelCase = convert_tax_to_pytorch(snake_case__ , num_layers=config.num_layers , is_encoder_only=snake_case__ ) lowerCAmelCase = make_state_dict(snake_case__ , snake_case__ ) model.load_state_dict(snake_case__ , strict=snake_case__ ) def SCREAMING_SNAKE_CASE_ ( snake_case__ , snake_case__ , snake_case__ , snake_case__ = False ) -> int: lowerCAmelCase = TaConfig.from_json_file(snake_case__ ) print(f"Building PyTorch model from configuration: {config}" ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: lowerCAmelCase = TaEncoderModel(snake_case__ ) else: lowerCAmelCase = TaForConditionalGeneration(snake_case__ ) # Load weights from tf checkpoint load_tax_weights_in_ta(snake_case__ , snake_case__ , snake_case__ , snake_case__ ) # Save pytorch-model print(f"Save PyTorch model to {pytorch_dump_path}" ) model.save_pretrained(snake_case__ ) # Verify that we can load the checkpoint. model.from_pretrained(snake_case__ ) print('''Done''' ) if __name__ == "__main__": lowercase__ : Dict = argparse.ArgumentParser(description='''Converts a native T5X checkpoint into a PyTorch checkpoint.''') # Required parameters parser.add_argument( '''--t5x_checkpoint_path''', default=None, type=str, required=True, help='''Path to the T5X checkpoint.''' ) parser.add_argument( '''--config_file''', default=None, type=str, required=True, help='''The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.''', ) parser.add_argument( '''--pytorch_dump_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) parser.add_argument( '''--is_encoder_only''', action='''store_true''', help='''Check if the model is encoder-decoder model''', default=False ) lowercase__ : Optional[Any] = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only )
338
import numpy as np import skfuzzy as fuzz if __name__ == "__main__": # Create universe of discourse in Python using linspace () lowercase__ : Dict = np.linspace(start=0, stop=7_5, num=7_5, endpoint=True, retstep=False) # Create two fuzzy sets by defining any membership function # (trapmf(), gbellmf(), gaussmf(), etc). lowercase__ : Optional[int] = [0, 2_5, 5_0] lowercase__ : Union[str, Any] = [2_5, 5_0, 7_5] lowercase__ : int = fuzz.membership.trimf(X, abca) lowercase__ : Tuple = fuzz.membership.trimf(X, abca) # Compute the different operations using inbuilt functions. lowercase__ : List[str] = np.ones(7_5) lowercase__ : Any = np.zeros((7_5,)) # 1. Union = max(µA(x), µB(x)) lowercase__ : Union[str, Any] = fuzz.fuzzy_or(X, young, X, middle_aged)[1] # 2. Intersection = min(µA(x), µB(x)) lowercase__ : int = fuzz.fuzzy_and(X, young, X, middle_aged)[1] # 3. Complement (A) = (1- min(µA(x)) lowercase__ : Union[str, Any] = fuzz.fuzzy_not(young) # 4. Difference (A/B) = min(µA(x),(1- µB(x))) lowercase__ : Optional[int] = fuzz.fuzzy_and(X, young, X, fuzz.fuzzy_not(middle_aged)[1])[1] # 5. Algebraic Sum = [µA(x) + µB(x) – (µA(x) * µB(x))] lowercase__ : Any = young + middle_aged - (young * middle_aged) # 6. Algebraic Product = (µA(x) * µB(x)) lowercase__ : str = young * middle_aged # 7. Bounded Sum = min[1,(µA(x), µB(x))] lowercase__ : Tuple = fuzz.fuzzy_and(X, one, X, young + middle_aged)[1] # 8. Bounded difference = min[0,(µA(x), µB(x))] lowercase__ : Tuple = fuzz.fuzzy_or(X, zero, X, young - middle_aged)[1] # max-min composition # max-product composition # Plot each set A, set B and each operation result using plot() and subplot(). from matplotlib import pyplot as plt plt.figure() plt.subplot(4, 3, 1) plt.plot(X, young) plt.title('''Young''') plt.grid(True) plt.subplot(4, 3, 2) plt.plot(X, middle_aged) plt.title('''Middle aged''') plt.grid(True) plt.subplot(4, 3, 3) plt.plot(X, union) plt.title('''union''') plt.grid(True) plt.subplot(4, 3, 4) plt.plot(X, intersection) plt.title('''intersection''') plt.grid(True) plt.subplot(4, 3, 5) plt.plot(X, complement_a) plt.title('''complement_a''') plt.grid(True) plt.subplot(4, 3, 6) plt.plot(X, difference) plt.title('''difference a/b''') plt.grid(True) plt.subplot(4, 3, 7) plt.plot(X, alg_sum) plt.title('''alg_sum''') plt.grid(True) plt.subplot(4, 3, 8) plt.plot(X, alg_product) plt.title('''alg_product''') plt.grid(True) plt.subplot(4, 3, 9) plt.plot(X, bdd_sum) plt.title('''bdd_sum''') plt.grid(True) plt.subplot(4, 3, 1_0) plt.plot(X, bdd_difference) plt.title('''bdd_difference''') plt.grid(True) plt.subplots_adjust(hspace=0.5) plt.show()
338
1
'''simple docstring''' def UpperCAmelCase_ (__a : str = 1_0_0_0 ): """simple docstring""" _a : Optional[Any] = 1, 1 _a : Any = [] for i in range(1 , n + 1 ): _a : Union[str, Any] = prev_numerator + 2 * prev_denominator _a : List[Any] = prev_numerator + prev_denominator if len(str(_UpperCAmelCase ) ) > len(str(_UpperCAmelCase ) ): result.append(_UpperCAmelCase ) _a : Union[str, Any] = numerator _a : Union[str, Any] = denominator return len(_UpperCAmelCase ) if __name__ == "__main__": print(f'''{solution() = }''')
364
'''simple docstring''' from collections.abc import Generator from math import sin def UpperCAmelCase_ (__a : bytes ): """simple docstring""" if len(__a ) != 3_2: raise ValueError('Input must be of length 32' ) _a : Any = b'' for i in [3, 2, 1, 0]: little_endian += string_aa[8 * i : 8 * i + 8] return little_endian def UpperCAmelCase_ (__a : int ): """simple docstring""" if i < 0: raise ValueError('Input must be non-negative' ) _a : List[str] = format(__a , '08x' )[-8:] _a : str = 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 UpperCAmelCase_ (__a : bytes ): """simple docstring""" _a : List[Any] = b'' for char in message: bit_string += format(__a , '08b' ).encode('utf-8' ) _a : int = format(len(__a ) , '064b' ).encode('utf-8' ) # Pad bit_string to a multiple of 512 chars bit_string += b"1" while len(__a ) % 5_1_2 != 4_4_8: bit_string += b"0" bit_string += to_little_endian(start_len[3_2:] ) + to_little_endian(start_len[:3_2] ) return bit_string def UpperCAmelCase_ (__a : bytes ): """simple docstring""" if len(__a ) % 5_1_2 != 0: raise ValueError('Input must have length that\'s a multiple of 512' ) for pos in range(0 , len(__a ) , 5_1_2 ): _a : List[Any] = bit_string[pos : pos + 5_1_2] _a : str = [] for i in range(0 , 5_1_2 , 3_2 ): block_words.append(int(to_little_endian(block[i : i + 3_2] ) , 2 ) ) yield block_words def UpperCAmelCase_ (__a : int ): """simple docstring""" if i < 0: raise ValueError('Input must be non-negative' ) _a : List[str] = format(__a , '032b' ) _a : int = '' for c in i_str: new_str += "1" if c == "0" else "0" return int(__a , 2 ) def UpperCAmelCase_ (__a : int , __a : int ): """simple docstring""" return (a + b) % 2**3_2 def UpperCAmelCase_ (__a : int , __a : int ): """simple docstring""" if i < 0: raise ValueError('Input must be non-negative' ) if shift < 0: raise ValueError('Shift must be non-negative' ) return ((i << shift) ^ (i >> (3_2 - shift))) % 2**3_2 def UpperCAmelCase_ (__a : bytes ): """simple docstring""" _a : str = preprocess(__a ) _a : Optional[int] = [int(2**3_2 * abs(sin(i + 1 ) ) ) for i in range(6_4 )] # Starting states _a : int = 0x67_45_23_01 _a : Union[str, Any] = 0xEF_CD_AB_89 _a : str = 0x98_BA_DC_FE _a : List[Any] = 0x10_32_54_76 _a : Optional[int] = [ 7, 1_2, 1_7, 2_2, 7, 1_2, 1_7, 2_2, 7, 1_2, 1_7, 2_2, 7, 1_2, 1_7, 2_2, 5, 9, 1_4, 2_0, 5, 9, 1_4, 2_0, 5, 9, 1_4, 2_0, 5, 9, 1_4, 2_0, 4, 1_1, 1_6, 2_3, 4, 1_1, 1_6, 2_3, 4, 1_1, 1_6, 2_3, 4, 1_1, 1_6, 2_3, 6, 1_0, 1_5, 2_1, 6, 1_0, 1_5, 2_1, 6, 1_0, 1_5, 2_1, 6, 1_0, 1_5, 2_1, ] # Process bit string in chunks, each with 16 32-char words for block_words in get_block_words(__a ): _a : Union[str, Any] = aa _a : List[Any] = ba _a : List[Any] = ca _a : Dict = da # Hash current chunk for i in range(6_4 ): if i <= 1_5: # f = (b & c) | (not_32(b) & d) # Alternate definition for f _a : Optional[int] = d ^ (b & (c ^ d)) _a : Optional[Any] = i elif i <= 3_1: # f = (d & b) | (not_32(d) & c) # Alternate definition for f _a : Optional[Any] = c ^ (d & (b ^ c)) _a : Dict = (5 * i + 1) % 1_6 elif i <= 4_7: _a : Optional[Any] = b ^ c ^ d _a : Dict = (3 * i + 5) % 1_6 else: _a : int = c ^ (b | not_aa(__a )) _a : List[str] = (7 * i) % 1_6 _a : Optional[int] = (f + a + added_consts[i] + block_words[g]) % 2**3_2 _a : Union[str, Any] = d _a : Tuple = c _a : Optional[int] = b _a : Union[str, Any] = sum_aa(__a , left_rotate_aa(__a , shift_amounts[i] ) ) # Add hashed chunk to running total _a : Any = sum_aa(__a , __a ) _a : Dict = sum_aa(__a , __a ) _a : Union[str, Any] = sum_aa(__a , __a ) _a : str = sum_aa(__a , __a ) _a : Optional[Any] = reformat_hex(__a ) + reformat_hex(__a ) + reformat_hex(__a ) + reformat_hex(__a ) return digest if __name__ == "__main__": import doctest doctest.testmod()
5
0
"""simple docstring""" from argparse import ArgumentParser from . import BaseTransformersCLICommand def lowercase ( lowerCAmelCase__ : List[Any] ) -> Any: return DownloadCommand(args.model , args.cache_dir , args.force , args.trust_remote_code ) class __lowerCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @staticmethod def __UpperCAmelCase ( _a ): __a = parser.add_parser('''download''' ) download_parser.add_argument( '''--cache-dir''' , type=_a , default=_a , help='''Path to location to store the models''' ) download_parser.add_argument( '''--force''' , action='''store_true''' , help='''Force the model to be download even if already in cache-dir''' ) download_parser.add_argument( '''--trust-remote-code''' , action='''store_true''' , help='''Whether or not to allow for custom models defined on the Hub in their own modeling files. Use only if you\'ve reviewed the code as it will execute on your local machine''' , ) download_parser.add_argument('''model''' , type=_a , help='''Name of the model to download''' ) download_parser.set_defaults(func=_a ) def __init__( self , _a , _a , _a , _a ): __a = model __a = cache __a = force __a = trust_remote_code def __UpperCAmelCase ( self ): from ..models.auto import AutoModel, AutoTokenizer AutoModel.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code ) AutoTokenizer.from_pretrained( self._model , cache_dir=self._cache , force_download=self._force , trust_remote_code=self._trust_remote_code )
45
"""simple docstring""" import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class __lowerCAmelCase ( unittest.TestCase ): '''simple docstring''' def __UpperCAmelCase ( self ): __a = inspect.getfile(accelerate.test_utils ) __a = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_script.py'''] ) __a = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_distributed_data_loop.py'''] ) __a = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ['''scripts''', '''test_ops.py'''] ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices.''' ) __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices.''' ) __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.operation_file_path] print(f'''Command: {cmd}''' ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(_a , env=os.environ.copy() ) @require_multi_gpu def __UpperCAmelCase ( self ): print(f'''Found {torch.cuda.device_count()} devices, using 2 devices only''' ) __a = ['''torchrun''', f'''--nproc_per_node={torch.cuda.device_count()}''', self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices='''0,1''' ): execute_subprocess_async(_a , env=os.environ.copy() ) if __name__ == "__main__": lowercase_ = Accelerator() lowercase_ = (accelerator.state.process_index + 2, 1_0) lowercase_ = torch.randint(0, 1_0, shape).to(accelerator.device) lowercase_ = "" lowercase_ = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." lowercase_ = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += F"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." lowercase_ = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
45
1
import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot from transformers import AutoTokenizer, FlaxMTaForConditionalGeneration from transformers.models.ta.modeling_flax_ta import shift_tokens_right @require_torch @require_sentencepiece @require_tokenizers @require_flax class a ( unittest.TestCase ): @slow def _UpperCAmelCase ( self ): '''simple docstring''' _UpperCAmelCase : Dict = FlaxMTaForConditionalGeneration.from_pretrained("google/mt5-small" ) _UpperCAmelCase : Dict = AutoTokenizer.from_pretrained("google/mt5-small" ) _UpperCAmelCase : List[Any] = tokenizer("Hello there" , return_tensors="np" ).input_ids _UpperCAmelCase : int = tokenizer("Hi I am" , return_tensors="np" ).input_ids _UpperCAmelCase : List[Any] = shift_tokens_right(A_ , model.config.pad_token_id , model.config.decoder_start_token_id ) _UpperCAmelCase : List[str] = model(A_ , decoder_input_ids=A_ ).logits _UpperCAmelCase : Optional[Any] = optax.softmax_cross_entropy(A_ , onehot(A_ , logits.shape[-1] ) ).mean() _UpperCAmelCase : str = -(labels.shape[-1] * loss.item()) _UpperCAmelCase : str = -84.91_27 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1e-4 )
189
from __future__ import annotations from random import choice def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: Any ) -> Optional[int]: return choice(lowerCAmelCase ) def __SCREAMING_SNAKE_CASE ( lowerCAmelCase: list[int] , lowerCAmelCase: int ) -> int: _UpperCAmelCase : List[Any] = random_pivot(lowerCAmelCase ) # partition based on pivot # linear time _UpperCAmelCase : List[str] = [e for e in lst if e < pivot] _UpperCAmelCase : Any = [e for e in lst if e > pivot] # if we get lucky, pivot might be the element we want. # we can easily see this: # small (elements smaller than k) # + pivot (kth element) # + big (elements larger than k) if len(lowerCAmelCase ) == k - 1: return pivot # pivot is in elements bigger than k elif len(lowerCAmelCase ) < k - 1: return kth_number(lowerCAmelCase , k - len(lowerCAmelCase ) - 1 ) # pivot is in elements smaller than k else: return kth_number(lowerCAmelCase , lowerCAmelCase ) if __name__ == "__main__": import doctest doctest.testmod()
189
1
# Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version UpperCAmelCase_ = get_logger(__name__) class lowerCamelCase__: UpperCAmelCase__ : List[Any] = 'dummy_data' UpperCAmelCase__ : str = 'datasets' UpperCAmelCase__ : Tuple = False def __init__( self: Optional[Any] , UpperCamelCase_: str , UpperCamelCase_: str , UpperCamelCase_: Union[Version, str] , UpperCamelCase_: Optional[str] = None , UpperCamelCase_: bool = False , UpperCamelCase_: bool = True , UpperCamelCase_: Optional[List[Callable]] = None , ): __lowerCamelCase = 0 __lowerCamelCase = dataset_name __lowerCamelCase = cache_dir __lowerCamelCase = use_local_dummy_data __lowerCamelCase = config # download_callbacks take a single url as input __lowerCamelCase = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root __lowerCamelCase = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general __lowerCamelCase = str(UpperCamelCase_ ) # to be downloaded __lowerCamelCase = None __lowerCamelCase = None @property def lowerCAmelCase__ ( self: List[Any] ): if self._dummy_file is None: __lowerCamelCase = self.download_dummy_data() return self._dummy_file @property def lowerCAmelCase__ ( self: str ): if self.config is not None: # structure is dummy / config_name / version_name return os.path.join("""dummy""" , self.config.name , self.version_name ) # structure is dummy / version_name return os.path.join("""dummy""" , self.version_name ) @property def lowerCAmelCase__ ( self: Optional[Any] ): return os.path.join(self.dummy_data_folder , """dummy_data.zip""" ) def lowerCAmelCase__ ( self: Any ): __lowerCamelCase = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) __lowerCamelCase = cached_path( UpperCamelCase_ , cache_dir=self.cache_dir , extract_compressed_file=UpperCamelCase_ , force_extract=UpperCamelCase_ ) return os.path.join(UpperCamelCase_ , self.dummy_file_name ) @property def lowerCAmelCase__ ( self: Optional[Any] ): return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file ) @property def lowerCAmelCase__ ( self: Tuple ): if self._bucket_url is None: __lowerCamelCase = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , """/""" ) ) return self._bucket_url @property def lowerCAmelCase__ ( self: str ): # return full path if its a dir if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep , """/""" ).split("""/""" )[:-1] ) def lowerCAmelCase__ ( self: List[str] , UpperCamelCase_: Dict , *UpperCamelCase_: str ): if self.load_existing_dummy_data: # dummy data is downloaded and tested __lowerCamelCase = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned __lowerCamelCase = self.dummy_file_name # special case when data_url is a dict if isinstance(UpperCamelCase_ , UpperCamelCase_ ): return self.create_dummy_data_dict(UpperCamelCase_ , UpperCamelCase_ ) elif isinstance(UpperCamelCase_ , (list, tuple) ): return self.create_dummy_data_list(UpperCamelCase_ , UpperCamelCase_ ) else: return self.create_dummy_data_single(UpperCamelCase_ , UpperCamelCase_ ) def lowerCAmelCase__ ( self: Any , UpperCamelCase_: Optional[Any] , *UpperCamelCase_: str ): return self.download_and_extract(UpperCamelCase_ ) def lowerCAmelCase__ ( self: List[Any] , UpperCamelCase_: Tuple , UpperCamelCase_: str ): return self.download_and_extract(UpperCamelCase_ ) def lowerCAmelCase__ ( self: str , UpperCamelCase_: int , *UpperCamelCase_: List[str] , **UpperCamelCase_: str ): return path def lowerCAmelCase__ ( self: Dict ): return {} def lowerCAmelCase__ ( self: str , UpperCamelCase_: List[Any] , UpperCamelCase_: Union[str, Any] ): __lowerCamelCase = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(UpperCamelCase_ , UpperCamelCase_ ): for single_url in single_urls: download_callback(UpperCamelCase_ ) else: __lowerCamelCase = single_urls download_callback(UpperCamelCase_ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(UpperCamelCase_ , UpperCamelCase_ ): __lowerCamelCase = [os.path.join(UpperCamelCase_ , urllib.parse.quote_plus(Path(UpperCamelCase_ ).name ) ) for x in single_urls] else: __lowerCamelCase = single_urls __lowerCamelCase = os.path.join(UpperCamelCase_ , urllib.parse.quote_plus(Path(UpperCamelCase_ ).name ) ) __lowerCamelCase = value # make sure that values are unique if all(isinstance(UpperCamelCase_ , UpperCamelCase_ ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique __lowerCamelCase = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def lowerCAmelCase__ ( self: Optional[Any] , UpperCamelCase_: Optional[Any] , UpperCamelCase_: Optional[int] ): __lowerCamelCase = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one __lowerCamelCase = all(bool(re.findall("""[0-9]{3,}-of-[0-9]{3,}""" , UpperCamelCase_ ) ) for url in data_url ) __lowerCamelCase = all( url.startswith("""https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed""" ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): __lowerCamelCase = [data_url[0]] * len(UpperCamelCase_ ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(UpperCamelCase_ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus __lowerCamelCase = os.path.join(UpperCamelCase_ , urllib.parse.quote_plus(single_url.split("""/""" )[-1] ) ) dummy_data_list.append(UpperCamelCase_ ) return dummy_data_list def lowerCAmelCase__ ( self: Tuple , UpperCamelCase_: Optional[int] , UpperCamelCase_: Optional[Any] ): for download_callback in self.download_callbacks: download_callback(UpperCamelCase_ ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus __lowerCamelCase = os.path.join(UpperCamelCase_ , urllib.parse.quote_plus(data_url.split("""/""" )[-1] ) ) if os.path.exists(UpperCamelCase_ ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def lowerCAmelCase__ ( self: Optional[Any] ): pass def lowerCAmelCase__ ( self: List[Any] ): pass def lowerCAmelCase__ ( self: Any , UpperCamelCase_: Dict ): def _iter_archive_members(UpperCamelCase_: Any ): # this preserves the order of the members inside the ZIP archive __lowerCamelCase = Path(self.dummy_file ).parent __lowerCamelCase = path.relative_to(UpperCamelCase_ ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: __lowerCamelCase = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(UpperCamelCase_ ) __lowerCamelCase = Path(UpperCamelCase_ ) __lowerCamelCase = _iter_archive_members(UpperCamelCase_ ) if self.use_local_dummy_data else path.rglob("""*""" ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith((""".""", """__""") ): yield file_path.relative_to(UpperCamelCase_ ).as_posix(), file_path.open("""rb""" ) def lowerCAmelCase__ ( self: List[str] , UpperCamelCase_: Dict ): if not isinstance(UpperCamelCase_ , UpperCamelCase_ ): __lowerCamelCase = [paths] for path in paths: if os.path.isfile(UpperCamelCase_ ): if os.path.basename(UpperCamelCase_ ).startswith((""".""", """__""") ): return yield path else: for dirpath, dirnames, filenames in os.walk(UpperCamelCase_ ): if os.path.basename(UpperCamelCase_ ).startswith((""".""", """__""") ): continue dirnames.sort() for filename in sorted(UpperCamelCase_ ): if filename.startswith((""".""", """__""") ): continue yield os.path.join(UpperCamelCase_ , UpperCamelCase_ )
12
import os import shutil from pathlib import Path from typing import Optional, Union import numpy as np from huggingface_hub import hf_hub_download from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging if is_onnx_available(): import onnxruntime as ort UpperCAmelCase_ = logging.get_logger(__name__) UpperCAmelCase_ = { 'tensor(bool)': np.bool_, 'tensor(int8)': np.inta, 'tensor(uint8)': np.uinta, 'tensor(int16)': np.intaa, 'tensor(uint16)': np.uintaa, 'tensor(int32)': np.intaa, 'tensor(uint32)': np.uintaa, 'tensor(int64)': np.intaa, 'tensor(uint64)': np.uintaa, 'tensor(float16)': np.floataa, 'tensor(float)': np.floataa, 'tensor(double)': np.floataa, } class lowerCamelCase__: def __init__( self: str , UpperCamelCase_: List[Any]=None , **UpperCamelCase_: str ): logger.info("""`diffusers.OnnxRuntimeModel` is experimental and might change in the future.""" ) __lowerCamelCase = model __lowerCamelCase = kwargs.get("""model_save_dir""" , UpperCamelCase_ ) __lowerCamelCase = kwargs.get("""latest_model_name""" , UpperCamelCase_ ) def __call__( self: Dict , **UpperCamelCase_: Any ): __lowerCamelCase = {k: np.array(UpperCamelCase_ ) for k, v in kwargs.items()} return self.model.run(UpperCamelCase_ , UpperCamelCase_ ) @staticmethod def lowerCAmelCase__ ( UpperCamelCase_: Union[str, Path] , UpperCamelCase_: Tuple=None , UpperCamelCase_: Tuple=None ): if provider is None: logger.info("""No onnxruntime provider specified, using CPUExecutionProvider""" ) __lowerCamelCase = """CPUExecutionProvider""" return ort.InferenceSession(UpperCamelCase_ , providers=[provider] , sess_options=UpperCamelCase_ ) def lowerCAmelCase__ ( self: int , UpperCamelCase_: Union[str, Path] , UpperCamelCase_: Optional[str] = None , **UpperCamelCase_: Optional[int] ): __lowerCamelCase = file_name if file_name is not None else ONNX_WEIGHTS_NAME __lowerCamelCase = self.model_save_dir.joinpath(self.latest_model_name ) __lowerCamelCase = Path(UpperCamelCase_ ).joinpath(UpperCamelCase_ ) try: shutil.copyfile(UpperCamelCase_ , UpperCamelCase_ ) except shutil.SameFileError: pass # copy external weights (for models >2GB) __lowerCamelCase = self.model_save_dir.joinpath(UpperCamelCase_ ) if src_path.exists(): __lowerCamelCase = Path(UpperCamelCase_ ).joinpath(UpperCamelCase_ ) try: shutil.copyfile(UpperCamelCase_ , UpperCamelCase_ ) except shutil.SameFileError: pass def lowerCAmelCase__ ( self: List[Any] , UpperCamelCase_: Union[str, os.PathLike] , **UpperCamelCase_: Optional[Any] , ): if os.path.isfile(UpperCamelCase_ ): logger.error(F'Provided path ({save_directory}) should be a directory, not a file' ) return os.makedirs(UpperCamelCase_ , exist_ok=UpperCamelCase_ ) # saving model weights/files self._save_pretrained(UpperCamelCase_ , **UpperCamelCase_ ) @classmethod def lowerCAmelCase__ ( cls: str , UpperCamelCase_: Union[str, Path] , UpperCamelCase_: Optional[Union[bool, str, None]] = None , UpperCamelCase_: Optional[Union[str, None]] = None , UpperCamelCase_: bool = False , UpperCamelCase_: Optional[str] = None , UpperCamelCase_: Optional[str] = None , UpperCamelCase_: Optional[str] = None , UpperCamelCase_: Optional["ort.SessionOptions"] = None , **UpperCamelCase_: int , ): __lowerCamelCase = file_name if file_name is not None else ONNX_WEIGHTS_NAME # load model from local directory if os.path.isdir(UpperCamelCase_ ): __lowerCamelCase = OnnxRuntimeModel.load_model( os.path.join(UpperCamelCase_ , UpperCamelCase_ ) , provider=UpperCamelCase_ , sess_options=UpperCamelCase_ ) __lowerCamelCase = Path(UpperCamelCase_ ) # load model from hub else: # download model __lowerCamelCase = hf_hub_download( repo_id=UpperCamelCase_ , filename=UpperCamelCase_ , use_auth_token=UpperCamelCase_ , revision=UpperCamelCase_ , cache_dir=UpperCamelCase_ , force_download=UpperCamelCase_ , ) __lowerCamelCase = Path(UpperCamelCase_ ).parent __lowerCamelCase = Path(UpperCamelCase_ ).name __lowerCamelCase = OnnxRuntimeModel.load_model(UpperCamelCase_ , provider=UpperCamelCase_ , sess_options=UpperCamelCase_ ) return cls(model=UpperCamelCase_ , **UpperCamelCase_ ) @classmethod def lowerCAmelCase__ ( cls: Optional[int] , UpperCamelCase_: Union[str, Path] , UpperCamelCase_: bool = True , UpperCamelCase_: Optional[str] = None , UpperCamelCase_: Optional[str] = None , **UpperCamelCase_: int , ): __lowerCamelCase = None if len(str(UpperCamelCase_ ).split("""@""" ) ) == 2: __lowerCamelCase, __lowerCamelCase = model_id.split("""@""" ) return cls._from_pretrained( model_id=UpperCamelCase_ , revision=UpperCamelCase_ , cache_dir=UpperCamelCase_ , force_download=UpperCamelCase_ , use_auth_token=UpperCamelCase_ , **UpperCamelCase_ , )
12
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 ( SCREAMING_SNAKE_CASE_ ): def __init__( self , __UpperCAmelCase , __UpperCAmelCase=13 , __UpperCAmelCase=7 , __UpperCAmelCase=True , __UpperCAmelCase=True , __UpperCAmelCase=False , __UpperCAmelCase=True , __UpperCAmelCase=99 , __UpperCAmelCase=32 , __UpperCAmelCase=5 , __UpperCAmelCase=4 , __UpperCAmelCase=64 , __UpperCAmelCase="gelu" , __UpperCAmelCase=0.1 , __UpperCAmelCase=0.1 , __UpperCAmelCase=5_12 , __UpperCAmelCase=16 , __UpperCAmelCase=2 , __UpperCAmelCase=0.02 , __UpperCAmelCase=3 , __UpperCAmelCase=4 , __UpperCAmelCase=None , __UpperCAmelCase=2 , __UpperCAmelCase=2 , __UpperCAmelCase=2 , __UpperCAmelCase=2 , __UpperCAmelCase=4 , __UpperCAmelCase=1 , ) ->Any: a_ = parent a_ = batch_size a_ = seq_length a_ = is_training a_ = use_input_mask a_ = use_token_type_ids a_ = use_labels a_ = vocab_size a_ = hidden_size a_ = num_hidden_layers a_ = num_attention_heads a_ = intermediate_size a_ = hidden_act a_ = hidden_dropout_prob a_ = attention_probs_dropout_prob a_ = max_position_embeddings a_ = type_vocab_size a_ = type_sequence_label_size a_ = initializer_range a_ = num_labels a_ = num_choices a_ = scope a_ = q_groups a_ = k_groups a_ = v_groups a_ = post_attention_groups a_ = intermediate_groups a_ = output_groups def UpperCAmelCase__ ( self) ->Union[str, Any]: a_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size) a_ = None if self.use_input_mask: a_ = random_attention_mask([self.batch_size, self.seq_length]) a_ = None a_ = None a_ = None if self.use_labels: a_ = ids_tensor([self.batch_size] , self.type_sequence_label_size) a_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels) a_ = ids_tensor([self.batch_size] , self.num_choices) a_ = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCAmelCase__ ( self) ->int: 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 UpperCAmelCase__ ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase) ->Dict: a_ = SqueezeBertModel(config=__UpperCAmelCase) model.to(__UpperCAmelCase) model.eval() a_ = model(__UpperCAmelCase , __UpperCAmelCase) a_ = model(__UpperCAmelCase) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size)) def UpperCAmelCase__ ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase) ->Any: a_ = SqueezeBertForMaskedLM(config=__UpperCAmelCase) model.to(__UpperCAmelCase) model.eval() a_ = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , labels=__UpperCAmelCase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size)) def UpperCAmelCase__ ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase) ->Union[str, Any]: a_ = SqueezeBertForQuestionAnswering(config=__UpperCAmelCase) model.to(__UpperCAmelCase) model.eval() a_ = 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 UpperCAmelCase__ ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase) ->Tuple: a_ = self.num_labels a_ = SqueezeBertForSequenceClassification(__UpperCAmelCase) model.to(__UpperCAmelCase) model.eval() a_ = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , labels=__UpperCAmelCase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)) def UpperCAmelCase__ ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase) ->Dict: a_ = self.num_labels a_ = SqueezeBertForTokenClassification(config=__UpperCAmelCase) model.to(__UpperCAmelCase) model.eval() a_ = model(__UpperCAmelCase , attention_mask=__UpperCAmelCase , labels=__UpperCAmelCase) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels)) def UpperCAmelCase__ ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase) ->List[str]: a_ = self.num_choices a_ = SqueezeBertForMultipleChoice(config=__UpperCAmelCase) model.to(__UpperCAmelCase) model.eval() a_ = input_ids.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() a_ = input_mask.unsqueeze(1).expand(-1 , self.num_choices , -1).contiguous() a_ = model( __UpperCAmelCase , attention_mask=__UpperCAmelCase , labels=__UpperCAmelCase , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices)) def UpperCAmelCase__ ( self) ->Any: a_ = self.prepare_config_and_inputs() ((a_) , (a_) , (a_) , (a_) , (a_) , (a_)) = config_and_inputs a_ = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class snake_case ( SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , unittest.TestCase ): a_ : Optional[Any] = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) a_ : Union[str, Any] = ( { """feature-extraction""": SqueezeBertModel, """fill-mask""": SqueezeBertForMaskedLM, """question-answering""": SqueezeBertForQuestionAnswering, """text-classification""": SqueezeBertForSequenceClassification, """token-classification""": SqueezeBertForTokenClassification, """zero-shot""": SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) a_ : List[Any] = False a_ : Tuple = True a_ : Optional[int] = False def UpperCAmelCase__ ( self) ->Optional[Any]: a_ = SqueezeBertModelTester(self) a_ = ConfigTester(self , config_class=__UpperCAmelCase , dim=37) def UpperCAmelCase__ ( self) ->Tuple: self.config_tester.run_common_tests() def UpperCAmelCase__ ( self) ->Tuple: a_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*__UpperCAmelCase) def UpperCAmelCase__ ( self) ->List[str]: a_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*__UpperCAmelCase) def UpperCAmelCase__ ( self) ->List[Any]: a_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*__UpperCAmelCase) def UpperCAmelCase__ ( self) ->Any: a_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*__UpperCAmelCase) def UpperCAmelCase__ ( self) ->str: a_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*__UpperCAmelCase) def UpperCAmelCase__ ( self) ->Tuple: a_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*__UpperCAmelCase) @slow def UpperCAmelCase__ ( self) ->int: for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a_ = SqueezeBertModel.from_pretrained(__UpperCAmelCase) self.assertIsNotNone(__UpperCAmelCase) @require_sentencepiece @require_tokenizers @require_torch class snake_case ( unittest.TestCase ): @slow def UpperCAmelCase__ ( self) ->Union[str, Any]: a_ = SqueezeBertForSequenceClassification.from_pretrained("squeezebert/squeezebert-mnli") a_ = torch.tensor([[1, 2_94_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 13, 15_88, 2]]) a_ = model(__UpperCAmelCase)[0] a_ = torch.Size((1, 3)) self.assertEqual(output.shape , __UpperCAmelCase) a_ = torch.tensor([[0.6_401, -0.0_349, -0.6_041]]) self.assertTrue(torch.allclose(__UpperCAmelCase , __UpperCAmelCase , atol=1E-4))
303
"""simple docstring""" import os import numpy import onnx def UpperCamelCase ( UpperCAmelCase , UpperCAmelCase ) ->List[str]: """simple docstring""" a_ = a.name a_ = b.name a_ = "" a_ = "" a_ = a == b a_ = name_a a_ = name_b return res def UpperCamelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) ->List[Any]: """simple docstring""" for i, input_name in enumerate(node_proto.input ): if input_name == name: node_proto.input.insert(UpperCAmelCase , UpperCAmelCase ) node_proto.input.pop(i + 1 ) if node_proto.op_type == "If": _graph_replace_input_with(node_proto.attribute[0].g , UpperCAmelCase , UpperCAmelCase ) _graph_replace_input_with(node_proto.attribute[1].g , UpperCAmelCase , UpperCAmelCase ) if node_proto.op_type == "Loop": _graph_replace_input_with(node_proto.attribute[0].g , UpperCAmelCase , UpperCAmelCase ) def UpperCamelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) ->Dict: """simple docstring""" for n in graph_proto.node: _node_replace_input_with(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) def UpperCamelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) ->int: """simple docstring""" a_ = list(model.graph.initializer ) a_ = list(model_without_ext.graph.initializer ) for i, ref_i in ind_to_replace: assert inits_with_data[i].name == inits[i].name assert inits_with_data[ref_i].name == inits[ref_i].name assert i > ref_i a_ = inits[i].name a_ = inits[ref_i].name model_without_ext.graph.initializer.remove(inits[i] ) # for n in model.graph.node: _graph_replace_input_with(model_without_ext.graph , UpperCAmelCase , UpperCAmelCase ) def UpperCamelCase ( UpperCAmelCase ) ->Union[str, Any]: """simple docstring""" a_ = os.path.dirname(UpperCAmelCase ) a_ = os.path.basename(UpperCAmelCase ) a_ = onnx.load(os.path.join(UpperCAmelCase , UpperCAmelCase ) ) a_ = list(model.graph.initializer ) a_ = set() a_ = {} a_ = [] a_ = 0 for i in range(len(UpperCAmelCase ) ): if i in dup_set: continue for j in range(i + 1 , len(UpperCAmelCase ) ): if j in dup_set: continue if _is_equal_tensor_proto(inits[i] , inits[j] ): dup_set.add(UpperCAmelCase ) dup_set.add(UpperCAmelCase ) a_ = inits[j].data_type a_ = numpy.prod(inits[j].dims ) if dtype == 1: mem_size *= 4 elif dtype == 6: mem_size *= 4 elif dtype == 7 or dtype == 11: mem_size *= 8 else: print("unexpected data type: " , UpperCAmelCase ) total_reduced_size += mem_size a_ = inits[i].name a_ = inits[j].name if name_i in dup_map: dup_map[name_i].append(UpperCAmelCase ) else: a_ = [name_j] ind_to_replace.append((j, i) ) print("total reduced size: " , total_reduced_size / 1_024 / 1_024 / 1_024 , "GB" ) a_ = sorted(UpperCAmelCase ) _remove_dup_initializers_from_model(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) a_ = "optimized_" + model_file_name a_ = os.path.join(UpperCAmelCase , UpperCAmelCase ) onnx.save(UpperCAmelCase , UpperCAmelCase ) return new_model
303
1
'''simple docstring''' import numpy as np from scipy.spatial.distance import cdist from sklearn.metrics import fa_score import datasets lowerCamelCase : List[Any] = "\\n @inproceedings{kakwani2020indicnlpsuite,\n title={{IndicNLPSuite: Monolingual Corpora, Evaluation Benchmarks and Pre-trained Multilingual Language Models for Indian Languages}},\n author={Divyanshu Kakwani and Anoop Kunchukuttan and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar},\n year={2020},\n booktitle={Findings of EMNLP},\n}\n" lowerCamelCase : Optional[Any] = "\\n IndicGLUE is a natural language understanding benchmark for Indian languages. It contains a wide\n variety of tasks and covers 11 major Indian languages - as, bn, gu, hi, kn, ml, mr, or, pa, ta, te.\n" lowerCamelCase : int = "\nCompute IndicGLUE evaluation metric associated to each IndicGLUE dataset.\nArgs:\n predictions: list of predictions to score (as int64),\n except for 'cvit-mkb-clsr' where each prediction is a vector (of float32).\n references: list of ground truth labels corresponding to the predictions (as int64),\n except for 'cvit-mkb-clsr' where each reference is a vector (of float32).\nReturns: depending on the IndicGLUE subset, one or several of:\n \"accuracy\": Accuracy\n \"f1\": F1 score\n \"precision\": Precision@10\nExamples:\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wnli') # 'wnli' or any of [\"copa\", \"sna\", \"csqa\", \"wstp\", \"inltkh\", \"bbca\", \"iitp-mr\", \"iitp-pr\", \"actsa-sc\", \"md\"]\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'wiki-ner')\n >>> references = [0, 1]\n >>> predictions = [0, 1]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'accuracy': 1.0, 'f1': 1.0}\n\n >>> indic_glue_metric = datasets.load_metric('indic_glue', 'cvit-mkb-clsr')\n >>> references = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> predictions = [[0.5, 0.5, 0.5], [0.1, 0.2, 0.3]]\n >>> results = indic_glue_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {'precision@10': 1.0}\n\n" def _lowerCAmelCase ( _UpperCamelCase : List[str] , _UpperCamelCase : Tuple ) -> List[Any]: """simple docstring""" return float((preds == labels).mean() ) def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Any ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =simple_accuracy(_UpperCamelCase , _UpperCamelCase ) _SCREAMING_SNAKE_CASE =float(fa_score(y_true=_UpperCamelCase , y_pred=_UpperCamelCase ) ) return { "accuracy": acc, "f1": fa, } def _lowerCAmelCase ( _UpperCamelCase : Any , _UpperCamelCase : int ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =np.array(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =en_sentvecs.shape[0] # mean centering _SCREAMING_SNAKE_CASE =en_sentvecs - np.mean(_UpperCamelCase , axis=0 ) _SCREAMING_SNAKE_CASE =in_sentvecs - np.mean(_UpperCamelCase , axis=0 ) _SCREAMING_SNAKE_CASE =cdist(_UpperCamelCase , _UpperCamelCase , 'cosine' ) _SCREAMING_SNAKE_CASE =np.array(range(_UpperCamelCase ) ) _SCREAMING_SNAKE_CASE =sim.argsort(axis=1 )[:, :10] _SCREAMING_SNAKE_CASE =np.any(preds == actual[:, None] , axis=1 ) return float(matches.mean() ) @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class A__ ( datasets.Metric ): def A ( self : Any ) -> List[str]: '''simple docstring''' if self.config_name not in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", "wiki-ner", ]: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]' ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('int64' ) if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32' ) ), 'references': datasets.Value('int64' ) if self.config_name != 'cvit-mkb-clsr' else datasets.Sequence(datasets.Value('float32' ) ), } ) , codebase_urls=[] , reference_urls=[] , format='numpy' if self.config_name != 'cvit-mkb-clsr' else None , ) def A ( self : List[str] , _a : Tuple , _a : Optional[int] ) -> int: '''simple docstring''' if self.config_name == "cvit-mkb-clsr": return {"precision@10": precision_at_aa(_a , _a )} elif self.config_name in ["wiki-ner"]: return acc_and_fa(_a , _a ) elif self.config_name in [ "wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", "iitp-mr", "iitp-pr", "actsa-sc", "md", ]: return {"accuracy": simple_accuracy(_a , _a )} else: raise KeyError( 'You should supply a configuration name selected in ' '["wnli", "copa", "sna", "csqa", "wstp", "inltkh", "bbca", ' '"cvit-mkb-clsr", "iitp-mr", "iitp-pr", "actsa-sc", "md", ' '"wiki-ner"]' )
47
import json import os import tempfile import unittest import unittest.mock as mock from pathlib import Path from requests.exceptions import HTTPError from transformers.utils import ( CONFIG_NAME, FLAX_WEIGHTS_NAME, TF2_WEIGHTS_NAME, TRANSFORMERS_CACHE, WEIGHTS_NAME, cached_file, get_file_from_repo, has_file, ) _SCREAMING_SNAKE_CASE : List[str] = "hf-internal-testing/tiny-random-bert" _SCREAMING_SNAKE_CASE : Optional[Any] = os.path.join(TRANSFORMERS_CACHE, "models--hf-internal-testing--tiny-random-bert") _SCREAMING_SNAKE_CASE : Optional[int] = "9b8c223d42b2188cb49d29af482996f9d0f3e5a6" class A__ ( unittest.TestCase ): """simple docstring""" def a_ ( self ): snake_case = cached_file(__snake_case , __snake_case ) # Should have downloaded the file in here self.assertTrue(os.path.isdir(__snake_case ) ) # Cache should contain at least those three subfolders: for subfolder in ["blobs", "refs", "snapshots"]: self.assertTrue(os.path.isdir(os.path.join(__snake_case , __snake_case ) ) ) with open(os.path.join(__snake_case , '''refs''' , '''main''' ) ) as f: snake_case = f.read() self.assertEqual(__snake_case , os.path.join(__snake_case , '''snapshots''' , __snake_case , __snake_case ) ) self.assertTrue(os.path.isfile(__snake_case ) ) # File is cached at the same place the second time. snake_case = cached_file(__snake_case , __snake_case ) self.assertEqual(__snake_case , __snake_case ) # Using a specific revision to test the full commit hash. snake_case = cached_file(__snake_case , __snake_case , revision='''9b8c223''' ) self.assertEqual(__snake_case , os.path.join(__snake_case , '''snapshots''' , __snake_case , __snake_case ) ) def a_ ( self ): with self.assertRaisesRegex(__snake_case , '''is not a valid model identifier''' ): snake_case = cached_file('''tiny-random-bert''' , __snake_case ) with self.assertRaisesRegex(__snake_case , '''is not a valid git identifier''' ): snake_case = cached_file(__snake_case , __snake_case , revision='''aaaa''' ) with self.assertRaisesRegex(__snake_case , '''does not appear to have a file named''' ): snake_case = cached_file(__snake_case , '''conf''' ) def a_ ( self ): with self.assertRaisesRegex(__snake_case , '''does not appear to have a file named''' ): snake_case = cached_file(__snake_case , '''conf''' ) with open(os.path.join(__snake_case , '''refs''' , '''main''' ) ) as f: snake_case = f.read() self.assertTrue(os.path.isfile(os.path.join(__snake_case , '''.no_exist''' , __snake_case , '''conf''' ) ) ) snake_case = cached_file(__snake_case , '''conf''' , _raise_exceptions_for_missing_entries=__snake_case ) self.assertIsNone(__snake_case ) snake_case = cached_file(__snake_case , '''conf''' , local_files_only=__snake_case , _raise_exceptions_for_missing_entries=__snake_case ) self.assertIsNone(__snake_case ) snake_case = mock.Mock() snake_case = 5_0_0 snake_case = {} snake_case = HTTPError snake_case = {} # Under the mock environment we get a 500 error when trying to reach the tokenizer. with mock.patch('''requests.Session.request''' , return_value=__snake_case ) as mock_head: snake_case = cached_file(__snake_case , '''conf''' , _raise_exceptions_for_connection_errors=__snake_case ) self.assertIsNone(__snake_case ) # This check we did call the fake head request mock_head.assert_called() def a_ ( self ): self.assertTrue(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __snake_case ) ) self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __snake_case ) ) self.assertFalse(has_file('''hf-internal-testing/tiny-bert-pt-only''' , __snake_case ) ) def a_ ( self ): # `get_file_from_repo` returns None if the file does not exist self.assertIsNone(get_file_from_repo('''bert-base-cased''' , '''ahah.txt''' ) ) # The function raises if the repository does not exist. with self.assertRaisesRegex(__snake_case , '''is not a valid model identifier''' ): get_file_from_repo('''bert-base-case''' , __snake_case ) # The function raises if the revision does not exist. with self.assertRaisesRegex(__snake_case , '''is not a valid git identifier''' ): get_file_from_repo('''bert-base-cased''' , __snake_case , revision='''ahaha''' ) snake_case = get_file_from_repo('''bert-base-cased''' , __snake_case ) # The name is the cached name which is not very easy to test, so instead we load the content. snake_case = json.loads(open(__snake_case , '''r''' ).read() ) self.assertEqual(config['''hidden_size'''] , 7_6_8 ) def a_ ( self ): with tempfile.TemporaryDirectory() as tmp_dir: snake_case = Path(__snake_case ) / '''a.txt''' filename.touch() self.assertEqual(get_file_from_repo(__snake_case , '''a.txt''' ) , str(__snake_case ) ) self.assertIsNone(get_file_from_repo(__snake_case , '''b.txt''' ) )
127
0
"""simple docstring""" import math def lowercase__ ( _UpperCAmelCase ) -> int: '''simple docstring''' if not isinstance(_UpperCAmelCase , _UpperCAmelCase ): lowercase : Optional[Any] = f'''Input value of [number={number}] must be an integer''' raise TypeError(_UpperCAmelCase ) if number < 1: lowercase : int = f'''Input value of [number={number}] must be > 0''' raise ValueError(_UpperCAmelCase ) elif number == 1: return 3 elif number == 2: return 5 else: lowercase : Optional[int] = int(math.log(number // 3 , 2 ) ) + 2 lowercase : str = [3, 5] lowercase : str = 2 lowercase : Optional[Any] = 3 for block in range(1 , _UpperCAmelCase ): for _ in range(_UpperCAmelCase ): proth_list.append(2 ** (block + 1) + proth_list[proth_index - 1] ) proth_index += 1 increment *= 2 return proth_list[number - 1] if __name__ == "__main__": import doctest doctest.testmod() for number in range(1_1): _UpperCamelCase: Union[str, Any] = 0 try: _UpperCamelCase: int = proth(number) except ValueError: print(f'''ValueError: there is no {number}th Proth number''') continue print(f'''The {number}th Proth number: {value}''')
53
"""simple docstring""" import gc import random import unittest import numpy as np import torch from PIL import Image from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, EulerAncestralDiscreteScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionInstructPixaPixPipeline, UNetaDConditionModel, ) from diffusers.image_processor import VaeImageProcessor from diffusers.utils import floats_tensor, load_image, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class a__ ( SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, SCREAMING_SNAKE_CASE__, unittest.TestCase ): _lowerCamelCase = StableDiffusionInstructPixaPixPipeline _lowerCamelCase = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'height', 'width', 'cross_attention_kwargs'} _lowerCamelCase = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS _lowerCamelCase = IMAGE_TO_IMAGE_IMAGE_PARAMS _lowerCamelCase = IMAGE_TO_IMAGE_IMAGE_PARAMS def lowercase ( self : str ) -> str: torch.manual_seed(0 ) lowercase : int = UNetaDConditionModel( block_out_channels=(32, 64), layers_per_block=2, sample_size=32, in_channels=8, out_channels=4, down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D'), up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D'), cross_attention_dim=32, ) lowercase : int = PNDMScheduler(skip_prk_steps=lowerCAmelCase ) torch.manual_seed(0 ) lowercase : Union[str, Any] = AutoencoderKL( block_out_channels=[32, 64], in_channels=3, out_channels=3, down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'], up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'], latent_channels=4, ) torch.manual_seed(0 ) lowercase : Union[str, Any] = CLIPTextConfig( bos_token_id=0, eos_token_id=2, hidden_size=32, intermediate_size=37, layer_norm_eps=1e-05, num_attention_heads=4, num_hidden_layers=5, pad_token_id=1, vocab_size=1000, ) lowercase : Optional[int] = CLIPTextModel(lowerCAmelCase ) lowercase : str = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) lowercase : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def lowercase ( self : int, lowerCAmelCase : str, lowerCAmelCase : Tuple=0 ) -> Tuple: lowercase : Optional[int] = floats_tensor((1, 3, 32, 32), rng=random.Random(lowerCAmelCase ) ).to(lowerCAmelCase ) lowercase : Dict = image.cpu().permute(0, 2, 3, 1 )[0] lowercase : Any = Image.fromarray(np.uinta(lowerCAmelCase ) ).convert('RGB' ) if str(lowerCAmelCase ).startswith('mps' ): lowercase : str = torch.manual_seed(lowerCAmelCase ) else: lowercase : Optional[Any] = torch.Generator(device=lowerCAmelCase ).manual_seed(lowerCAmelCase ) lowercase : Union[str, Any] = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 6.0, 'image_guidance_scale': 1, 'output_type': 'numpy', } return inputs def lowercase ( self : Tuple ) -> Optional[Any]: lowercase : str = 'cpu' # ensure determinism for the device-dependent torch.Generator lowercase : int = self.get_dummy_components() lowercase : str = StableDiffusionInstructPixaPixPipeline(**lowerCAmelCase ) lowercase : Union[str, Any] = sd_pipe.to(lowerCAmelCase ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase ) lowercase : Union[str, Any] = self.get_dummy_inputs(lowerCAmelCase ) lowercase : Union[str, Any] = sd_pipe(**lowerCAmelCase ).images lowercase : str = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) lowercase : str = np.array([0.7526, 0.3750, 0.4547, 0.6117, 0.5866, 0.5016, 0.4327, 0.5642, 0.4815] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowercase ( self : Optional[Any] ) -> int: lowercase : Union[str, Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator lowercase : Union[str, Any] = self.get_dummy_components() lowercase : Optional[int] = StableDiffusionInstructPixaPixPipeline(**lowerCAmelCase ) lowercase : Union[str, Any] = sd_pipe.to(lowerCAmelCase ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase ) lowercase : Optional[Any] = self.get_dummy_inputs(lowerCAmelCase ) lowercase : Any = 'french fries' lowercase : Tuple = sd_pipe(**lowerCAmelCase, negative_prompt=lowerCAmelCase ) lowercase : Optional[Any] = output.images lowercase : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) lowercase : Dict = np.array([0.7511, 0.3642, 0.4553, 0.6236, 0.5797, 0.5013, 0.4343, 0.5611, 0.4831] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowercase ( self : Optional[int] ) -> str: lowercase : List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator lowercase : str = self.get_dummy_components() lowercase : Optional[int] = StableDiffusionInstructPixaPixPipeline(**lowerCAmelCase ) lowercase : str = sd_pipe.to(lowerCAmelCase ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase ) lowercase : Any = self.get_dummy_inputs(lowerCAmelCase ) lowercase : int = [inputs['prompt']] * 2 lowercase : Dict = np.array(inputs['image'] ).astype(np.floataa ) / 255.0 lowercase : Optional[int] = torch.from_numpy(lowerCAmelCase ).unsqueeze(0 ).to(lowerCAmelCase ) lowercase : List[Any] = image / 2 + 0.5 lowercase : List[str] = image.permute(0, 3, 1, 2 ) lowercase : List[str] = image.repeat(2, 1, 1, 1 ) lowercase : Dict = sd_pipe(**lowerCAmelCase ).images lowercase : Union[str, Any] = image[-1, -3:, -3:, -1] assert image.shape == (2, 32, 32, 3) lowercase : Optional[int] = np.array([0.5812, 0.5748, 0.5222, 0.5908, 0.5695, 0.7174, 0.6804, 0.5523, 0.5579] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowercase ( self : Union[str, Any] ) -> Any: lowercase : str = 'cpu' # ensure determinism for the device-dependent torch.Generator lowercase : Optional[int] = self.get_dummy_components() lowercase : str = EulerAncestralDiscreteScheduler( beta_start=0.0_0085, beta_end=0.012, beta_schedule='scaled_linear' ) lowercase : Tuple = StableDiffusionInstructPixaPixPipeline(**lowerCAmelCase ) lowercase : str = sd_pipe.to(lowerCAmelCase ) sd_pipe.set_progress_bar_config(disable=lowerCAmelCase ) lowercase : Dict = self.get_dummy_inputs(lowerCAmelCase ) lowercase : Dict = sd_pipe(**lowerCAmelCase ).images lowercase : Tuple = image[0, -3:, -3:, -1] lowercase : Optional[int] = [round(lowerCAmelCase, 4 ) for x in image_slice.flatten().tolist()] print(','.join([str(lowerCAmelCase ) for x in slice] ) ) assert image.shape == (1, 32, 32, 3) lowercase : List[str] = np.array([0.7417, 0.3842, 0.4732, 0.5776, 0.5891, 0.5139, 0.4052, 0.5673, 0.4986] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowercase ( self : List[str] ) -> Dict: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) def lowercase ( self : int ) -> Optional[Any]: lowercase : List[Any] = self.get_dummy_components() lowercase : Optional[Any] = StableDiffusionInstructPixaPixPipeline(**lowerCAmelCase ) lowercase : List[str] = VaeImageProcessor(do_resize=lowerCAmelCase, do_normalize=lowerCAmelCase ) lowercase : int = pipe.to(lowerCAmelCase ) pipe.set_progress_bar_config(disable=lowerCAmelCase ) lowercase : Dict = pipe(**self.get_dummy_inputs_by_type(lowerCAmelCase, input_image_type='pt' ) )[0] lowercase : Optional[Any] = components['vae'] lowercase : str = self.get_dummy_inputs_by_type(lowerCAmelCase, input_image_type='pt' ) for image_param in self.image_latents_params: if image_param in inputs.keys(): lowercase : Optional[Any] = vae.encode(inputs[image_param] ).latent_dist.mode() lowercase : Optional[int] = pipe(**lowerCAmelCase )[0] lowercase : int = np.abs(out - out_latents_inputs ).max() self.assertLess(lowerCAmelCase, 1e-4, 'passing latents as image input generate different result from passing image' ) @slow @require_torch_gpu class a__ ( unittest.TestCase ): def lowercase ( self : List[str] ) -> Dict: super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase ( self : List[str], lowerCAmelCase : int=0 ) -> str: lowercase : Dict = torch.manual_seed(lowerCAmelCase ) lowercase : Optional[Any] = load_image( 'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_pix2pix/example.jpg' ) lowercase : int = { 'prompt': 'turn him into a cyborg', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'guidance_scale': 7.5, 'image_guidance_scale': 1.0, 'output_type': 'numpy', } return inputs def lowercase ( self : int ) -> str: lowercase : str = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix', safety_checker=lowerCAmelCase ) pipe.to(lowerCAmelCase ) pipe.set_progress_bar_config(disable=lowerCAmelCase ) pipe.enable_attention_slicing() lowercase : Optional[Any] = self.get_inputs() lowercase : List[Any] = pipe(**lowerCAmelCase ).images lowercase : Tuple = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) lowercase : List[str] = np.array([0.5902, 0.6015, 0.6027, 0.5983, 0.6092, 0.6061, 0.5765, 0.5785, 0.5555] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def lowercase ( self : Optional[Any] ) -> Optional[Any]: lowercase : Any = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix', safety_checker=lowerCAmelCase ) lowercase : List[Any] = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.to(lowerCAmelCase ) pipe.set_progress_bar_config(disable=lowerCAmelCase ) pipe.enable_attention_slicing() lowercase : List[Any] = self.get_inputs() lowercase : Tuple = pipe(**lowerCAmelCase ).images lowercase : Dict = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) lowercase : str = np.array([0.6578, 0.6817, 0.6972, 0.6761, 0.6856, 0.6916, 0.6428, 0.6516, 0.6301] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def lowercase ( self : Optional[Any] ) -> List[Any]: lowercase : int = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix', safety_checker=lowerCAmelCase ) lowercase : List[Any] = DDIMScheduler.from_config(pipe.scheduler.config ) pipe.to(lowerCAmelCase ) pipe.set_progress_bar_config(disable=lowerCAmelCase ) pipe.enable_attention_slicing() lowercase : Any = self.get_inputs() lowercase : Union[str, Any] = pipe(**lowerCAmelCase ).images lowercase : List[Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) lowercase : int = np.array([0.3828, 0.3834, 0.3818, 0.3792, 0.3865, 0.3752, 0.3792, 0.3847, 0.3753] ) assert np.abs(expected_slice - image_slice ).max() < 1e-3 def lowercase ( self : Tuple ) -> Dict: lowercase : Dict = 0 def callback_fn(lowerCAmelCase : int, lowerCAmelCase : int, lowerCAmelCase : torch.FloatTensor ) -> None: lowercase : Optional[Any] = True nonlocal number_of_steps number_of_steps += 1 if step == 1: lowercase : str = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) lowercase : Union[str, Any] = latents[0, -3:, -3:, -1] lowercase : List[str] = np.array([-0.2463, -0.4644, -0.9756, 1.5176, 1.4414, 0.7866, 0.9897, 0.8521, 0.7983] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 elif step == 2: lowercase : Optional[Any] = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 64) lowercase : Union[str, Any] = latents[0, -3:, -3:, -1] lowercase : str = np.array([-0.2644, -0.4626, -0.9653, 1.5176, 1.4551, 0.7686, 0.9805, 0.8452, 0.8115] ) assert np.abs(latents_slice.flatten() - expected_slice ).max() < 5e-2 lowercase : Union[str, Any] = False lowercase : List[str] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix', safety_checker=lowerCAmelCase, torch_dtype=torch.floataa ) lowercase : Optional[int] = pipe.to(lowerCAmelCase ) pipe.set_progress_bar_config(disable=lowerCAmelCase ) pipe.enable_attention_slicing() lowercase : Union[str, Any] = self.get_inputs() pipe(**lowerCAmelCase, callback=lowerCAmelCase, callback_steps=1 ) assert callback_fn.has_been_called assert number_of_steps == 3 def lowercase ( self : Union[str, Any] ) -> Union[str, Any]: torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() lowercase : Optional[int] = StableDiffusionInstructPixaPixPipeline.from_pretrained( 'timbrooks/instruct-pix2pix', safety_checker=lowerCAmelCase, torch_dtype=torch.floataa ) lowercase : Dict = pipe.to(lowerCAmelCase ) pipe.set_progress_bar_config(disable=lowerCAmelCase ) pipe.enable_attention_slicing(1 ) pipe.enable_sequential_cpu_offload() lowercase : Dict = self.get_inputs() lowercase : List[Any] = pipe(**lowerCAmelCase ) lowercase : Any = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 10**9 def lowercase ( self : Union[str, Any] ) -> Tuple: lowercase : int = self.get_inputs() # resize to resolution that is divisible by 8 but not 16 or 32 lowercase : Optional[Any] = inputs['image'].resize((504, 504) ) lowercase : Union[str, Any] = 'timbrooks/instruct-pix2pix' lowercase : Any = StableDiffusionInstructPixaPixPipeline.from_pretrained( lowerCAmelCase, safety_checker=lowerCAmelCase, ) pipe.to(lowerCAmelCase ) pipe.set_progress_bar_config(disable=lowerCAmelCase ) pipe.enable_attention_slicing() lowercase : str = pipe(**lowerCAmelCase ) lowercase : int = output.images[0] lowercase : int = image[255:258, 383:386, -1] assert image.shape == (504, 504, 3) lowercase : Union[str, Any] = np.array([0.2726, 0.2529, 0.2664, 0.2655, 0.2641, 0.2642, 0.2591, 0.2649, 0.2590] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3
53
1
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, BertConfig, DPRConfig, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) class snake_case__ : """simple docstring""" def __init__( self , __lowercase , __lowercase=1_3 , __lowercase=7 , __lowercase=True , __lowercase=True , __lowercase=True , __lowercase=True , __lowercase=9_9 , __lowercase=3_2 , __lowercase=2 , __lowercase=4 , __lowercase=3_7 , __lowercase="gelu" , __lowercase=0.1 , __lowercase=0.1 , __lowercase=5_1_2 , __lowercase=1_6 , __lowercase=2 , __lowercase=0.0_2 , __lowercase=3 , __lowercase=4 , __lowercase=None , __lowercase=0 , ) -> Optional[Any]: """simple docstring""" a__ : Optional[int] = parent a__ : int = batch_size a__ : Dict = seq_length a__ : Optional[Any] = is_training a__ : Optional[Any] = use_input_mask a__ : str = use_token_type_ids a__ : List[Any] = use_labels a__ : int = vocab_size a__ : List[Any] = hidden_size a__ : int = num_hidden_layers a__ : Optional[Any] = num_attention_heads a__ : Tuple = intermediate_size a__ : Dict = hidden_act a__ : Any = hidden_dropout_prob a__ : List[str] = attention_probs_dropout_prob a__ : Optional[Any] = max_position_embeddings a__ : List[Any] = type_vocab_size a__ : Dict = type_sequence_label_size a__ : List[Any] = initializer_range a__ : Dict = num_labels a__ : int = num_choices a__ : Union[str, Any] = scope a__ : str = projection_dim def SCREAMING_SNAKE_CASE__( self ) -> List[str]: """simple docstring""" a__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a__ : Optional[int] = None if self.use_input_mask: # follow test_modeling_tf_ctrl.py a__ : str = random_attention_mask([self.batch_size, self.seq_length] ) a__ : Tuple = None if self.use_token_type_ids: a__ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a__ : str = None a__ : List[str] = None a__ : int = None if self.use_labels: a__ : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a__ : Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices ) a__ : int = BertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__lowercase , initializer_range=self.initializer_range , ) a__ : str = DPRConfig(projection_dim=self.projection_dim , **config.to_dict() ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> str: """simple docstring""" a__ : Tuple = TFDPRContextEncoder(config=__lowercase ) a__ : Optional[int] = model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase ) a__ : Dict = model(__lowercase , token_type_ids=__lowercase ) a__ : List[str] = model(__lowercase ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def SCREAMING_SNAKE_CASE__( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> Optional[Any]: """simple docstring""" a__ : List[str] = TFDPRQuestionEncoder(config=__lowercase ) a__ : Optional[Any] = model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase ) a__ : str = model(__lowercase , token_type_ids=__lowercase ) a__ : Optional[int] = model(__lowercase ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def SCREAMING_SNAKE_CASE__( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> Union[str, Any]: """simple docstring""" a__ : int = TFDPRReader(config=__lowercase ) a__ : List[Any] = model(__lowercase , attention_mask=__lowercase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.relevance_logits.shape , (self.batch_size,) ) def SCREAMING_SNAKE_CASE__( self ) -> str: """simple docstring""" a__ : Union[str, Any] = self.prepare_config_and_inputs() ( ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ) : Union[str, Any] = config_and_inputs a__ : str = {"""input_ids""": input_ids} return config, inputs_dict @require_tf class snake_case__ (A__ , A__ , unittest.TestCase ): """simple docstring""" __lowerCAmelCase :Optional[int] = ( ( TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) if is_tf_available() else () ) __lowerCAmelCase :Dict = {"feature-extraction": TFDPRQuestionEncoder} if is_tf_available() else {} __lowerCAmelCase :List[Any] = False __lowerCAmelCase :Optional[Any] = False __lowerCAmelCase :Dict = False __lowerCAmelCase :int = False __lowerCAmelCase :Optional[Any] = False def SCREAMING_SNAKE_CASE__( self ) -> List[str]: """simple docstring""" a__ : Optional[Any] = TFDPRModelTester(self ) a__ : Dict = ConfigTester(self , config_class=__lowercase , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE__( self ) -> Any: """simple docstring""" self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__( self ) -> Dict: """simple docstring""" a__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_context_encoder(*__lowercase ) def SCREAMING_SNAKE_CASE__( self ) -> Dict: """simple docstring""" a__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_question_encoder(*__lowercase ) def SCREAMING_SNAKE_CASE__( self ) -> Any: """simple docstring""" a__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_reader(*__lowercase ) @slow def SCREAMING_SNAKE_CASE__( self ) -> int: """simple docstring""" for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__ : Optional[Any] = TFDPRContextEncoder.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__ : str = TFDPRContextEncoder.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__ : Optional[Any] = TFDPRQuestionEncoder.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__ : int = TFDPRReader.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) @require_tf class snake_case__ (unittest.TestCase ): """simple docstring""" @slow def SCREAMING_SNAKE_CASE__( self ) -> Tuple: """simple docstring""" a__ : Any = TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base""" ) a__ : Union[str, Any] = tf.constant( [[1_0_1, 7_5_9_2, 1_0_1_0, 2_0_0_3, 2_0_2_6, 3_8_9_9, 1_0_1_4_0, 1_0_2_9, 1_0_2]] ) # [CLS] hello, is my dog cute? [SEP] a__ : Any = model(__lowercase )[0] # embedding shape = (1, 768) # compare the actual values for a slice. a__ : Optional[int] = tf.constant( [ [ 0.0_3_2_3_6_2_5_3, 0.1_2_7_5_3_3_3_5, 0.1_6_8_1_8_5_0_9, 0.0_0_2_7_9_7_8_6, 0.3_8_9_6_9_3_3, 0.2_4_2_6_4_9_4_5, 0.2_1_7_8_9_7_1, -0.0_2_3_3_5_2_2_7, -0.0_8_4_8_1_9_5_9, -0.1_4_3_2_4_1_1_7, ] ] ) self.assertTrue(numpy.allclose(output[:, :1_0].numpy() , expected_slice.numpy() , atol=1E-4 ) )
170
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import numpy import tensorflow as tf from transformers import ( TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST, TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST, BertConfig, DPRConfig, TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) class snake_case__ : """simple docstring""" def __init__( self , __lowercase , __lowercase=1_3 , __lowercase=7 , __lowercase=True , __lowercase=True , __lowercase=True , __lowercase=True , __lowercase=9_9 , __lowercase=3_2 , __lowercase=2 , __lowercase=4 , __lowercase=3_7 , __lowercase="gelu" , __lowercase=0.1 , __lowercase=0.1 , __lowercase=5_1_2 , __lowercase=1_6 , __lowercase=2 , __lowercase=0.0_2 , __lowercase=3 , __lowercase=4 , __lowercase=None , __lowercase=0 , ) -> Optional[Any]: """simple docstring""" a__ : Optional[int] = parent a__ : int = batch_size a__ : Dict = seq_length a__ : Optional[Any] = is_training a__ : Optional[Any] = use_input_mask a__ : str = use_token_type_ids a__ : List[Any] = use_labels a__ : int = vocab_size a__ : List[Any] = hidden_size a__ : int = num_hidden_layers a__ : Optional[Any] = num_attention_heads a__ : Tuple = intermediate_size a__ : Dict = hidden_act a__ : Any = hidden_dropout_prob a__ : List[str] = attention_probs_dropout_prob a__ : Optional[Any] = max_position_embeddings a__ : List[Any] = type_vocab_size a__ : Dict = type_sequence_label_size a__ : List[Any] = initializer_range a__ : Dict = num_labels a__ : int = num_choices a__ : Union[str, Any] = scope a__ : str = projection_dim def SCREAMING_SNAKE_CASE__( self ) -> List[str]: """simple docstring""" a__ : Optional[int] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a__ : Optional[int] = None if self.use_input_mask: # follow test_modeling_tf_ctrl.py a__ : str = random_attention_mask([self.batch_size, self.seq_length] ) a__ : Tuple = None if self.use_token_type_ids: a__ : Dict = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a__ : str = None a__ : List[str] = None a__ : int = None if self.use_labels: a__ : List[str] = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a__ : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a__ : Union[str, Any] = ids_tensor([self.batch_size] , self.num_choices ) a__ : int = BertConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__lowercase , initializer_range=self.initializer_range , ) a__ : str = DPRConfig(projection_dim=self.projection_dim , **config.to_dict() ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def SCREAMING_SNAKE_CASE__( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> str: """simple docstring""" a__ : Tuple = TFDPRContextEncoder(config=__lowercase ) a__ : Optional[int] = model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase ) a__ : Dict = model(__lowercase , token_type_ids=__lowercase ) a__ : List[str] = model(__lowercase ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def SCREAMING_SNAKE_CASE__( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> Optional[Any]: """simple docstring""" a__ : List[str] = TFDPRQuestionEncoder(config=__lowercase ) a__ : Optional[Any] = model(__lowercase , attention_mask=__lowercase , token_type_ids=__lowercase ) a__ : str = model(__lowercase , token_type_ids=__lowercase ) a__ : Optional[int] = model(__lowercase ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.projection_dim or self.hidden_size) ) def SCREAMING_SNAKE_CASE__( self , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase , __lowercase ) -> Union[str, Any]: """simple docstring""" a__ : int = TFDPRReader(config=__lowercase ) a__ : List[Any] = model(__lowercase , attention_mask=__lowercase ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.relevance_logits.shape , (self.batch_size,) ) def SCREAMING_SNAKE_CASE__( self ) -> str: """simple docstring""" a__ : Union[str, Any] = self.prepare_config_and_inputs() ( ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ( a__ ) , ) : Union[str, Any] = config_and_inputs a__ : str = {"""input_ids""": input_ids} return config, inputs_dict @require_tf class snake_case__ (A__ , A__ , unittest.TestCase ): """simple docstring""" __lowerCAmelCase :Optional[int] = ( ( TFDPRContextEncoder, TFDPRQuestionEncoder, TFDPRReader, ) if is_tf_available() else () ) __lowerCAmelCase :Dict = {"feature-extraction": TFDPRQuestionEncoder} if is_tf_available() else {} __lowerCAmelCase :List[Any] = False __lowerCAmelCase :Optional[Any] = False __lowerCAmelCase :Dict = False __lowerCAmelCase :int = False __lowerCAmelCase :Optional[Any] = False def SCREAMING_SNAKE_CASE__( self ) -> List[str]: """simple docstring""" a__ : Optional[Any] = TFDPRModelTester(self ) a__ : Dict = ConfigTester(self , config_class=__lowercase , hidden_size=3_7 ) def SCREAMING_SNAKE_CASE__( self ) -> Any: """simple docstring""" self.config_tester.run_common_tests() def SCREAMING_SNAKE_CASE__( self ) -> Dict: """simple docstring""" a__ : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_context_encoder(*__lowercase ) def SCREAMING_SNAKE_CASE__( self ) -> Dict: """simple docstring""" a__ : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_question_encoder(*__lowercase ) def SCREAMING_SNAKE_CASE__( self ) -> Any: """simple docstring""" a__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_dpr_reader(*__lowercase ) @slow def SCREAMING_SNAKE_CASE__( self ) -> int: """simple docstring""" for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__ : Optional[Any] = TFDPRContextEncoder.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) for model_name in TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__ : str = TFDPRContextEncoder.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) for model_name in TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__ : Optional[Any] = TFDPRQuestionEncoder.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) for model_name in TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a__ : int = TFDPRReader.from_pretrained(__lowercase ) self.assertIsNotNone(__lowercase ) @require_tf class snake_case__ (unittest.TestCase ): """simple docstring""" @slow def SCREAMING_SNAKE_CASE__( self ) -> Tuple: """simple docstring""" a__ : Any = TFDPRQuestionEncoder.from_pretrained("""facebook/dpr-question_encoder-single-nq-base""" ) a__ : Union[str, Any] = tf.constant( [[1_0_1, 7_5_9_2, 1_0_1_0, 2_0_0_3, 2_0_2_6, 3_8_9_9, 1_0_1_4_0, 1_0_2_9, 1_0_2]] ) # [CLS] hello, is my dog cute? [SEP] a__ : Any = model(__lowercase )[0] # embedding shape = (1, 768) # compare the actual values for a slice. a__ : Optional[int] = tf.constant( [ [ 0.0_3_2_3_6_2_5_3, 0.1_2_7_5_3_3_3_5, 0.1_6_8_1_8_5_0_9, 0.0_0_2_7_9_7_8_6, 0.3_8_9_6_9_3_3, 0.2_4_2_6_4_9_4_5, 0.2_1_7_8_9_7_1, -0.0_2_3_3_5_2_2_7, -0.0_8_4_8_1_9_5_9, -0.1_4_3_2_4_1_1_7, ] ] ) self.assertTrue(numpy.allclose(output[:, :1_0].numpy() , expected_slice.numpy() , atol=1E-4 ) )
170
1
import os def SCREAMING_SNAKE_CASE ( ) -> Dict: lowerCamelCase__ : int = os.path.dirname(os.path.realpath(_UpperCAmelCase ) ) lowerCamelCase__ : Optional[int] = os.path.join(_UpperCAmelCase , 'triangle.txt' ) with open(_UpperCAmelCase ) as f: lowerCamelCase__ : Optional[Any] = f.readlines() lowerCamelCase__ : str = [] for line in triangle: lowerCamelCase__ : Union[str, Any] = [] for number in line.strip().split(' ' ): numbers_from_line.append(int(_UpperCAmelCase ) ) a.append(_UpperCAmelCase ) for i in range(1 , len(_UpperCAmelCase ) ): for j in range(len(a[i] ) ): lowerCamelCase__ : Any = a[i - 1][j] if j != len(a[i - 1] ) else 0 lowerCamelCase__ : Dict = a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(_UpperCAmelCase , _UpperCAmelCase ) return max(a[-1] ) if __name__ == "__main__": print(solution())
350
from __future__ import annotations def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ) -> None: lowerCamelCase__ : Optional[Any] = len(_UpperCAmelCase ) # If row is equal to the size of the board it means there are a queen in each row in # the current board (possible_board) if row == n: # We convert the variable possible_board that looks like this: [1, 3, 0, 2] to # this: ['. Q . . ', '. . . Q ', 'Q . . . ', '. . Q . '] boards.append(['. ' * i + 'Q ' + '. ' * (n - 1 - i) for i in possible_board] ) return # We iterate each column in the row to find all possible results in each row for col in range(_UpperCAmelCase ): # We apply that we learned previously. First we check that in the current board # (possible_board) there are not other same value because if there is it means # that there are a collision in vertical. Then we apply the two formulas we # learned before: # # 45º: y - x = b or 45: row - col = b # 135º: y + x = b or row + col = b. # # And we verify if the results of this two formulas not exist in their variables # respectively. (diagonal_right_collisions, diagonal_left_collisions) # # If any or these are True it means there is a collision so we continue to the # next value in the for loop. if ( col in possible_board or row - col in diagonal_right_collisions or row + col in diagonal_left_collisions ): continue # If it is False we call dfs function again and we update the inputs depth_first_search( [*possible_board, col] , [*diagonal_right_collisions, row - col] , [*diagonal_left_collisions, row + col] , _UpperCAmelCase , _UpperCAmelCase , ) def SCREAMING_SNAKE_CASE ( _UpperCAmelCase ) -> None: lowerCamelCase__ : list[list[str]] = [] depth_first_search([] , [] , [] , _UpperCAmelCase , _UpperCAmelCase ) # Print all the boards for board in boards: for column in board: print(_UpperCAmelCase ) print('' ) print(len(_UpperCAmelCase ) , 'solutions were found.' ) if __name__ == "__main__": import doctest doctest.testmod() n_queens_solution(4)
45
0
"""simple docstring""" from math import factorial a_ = {str(d): factorial(d) for d in range(10)} def __lowercase ( snake_case_ : Optional[Any] ) ->int: '''simple docstring''' return sum(DIGIT_FACTORIAL[d] for d in str(snake_case_ ) ) def __lowercase ( ) ->int: '''simple docstring''' __A : Optional[Any] = 7 * factorial(9 ) + 1 return sum(i for i in range(3 ,snake_case_ ) if sum_of_digit_factorial(snake_case_ ) == i ) if __name__ == "__main__": print(f'''{solution() = }''')
179
from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class __a ( __UpperCamelCase ): __lowercase : Any = ['vqvae'] def __init__( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , ) -> Union[str, Any]: '''simple docstring''' super().__init__() self.register_modules(unet=lowerCAmelCase__ , scheduler=lowerCAmelCase__ , mel=lowerCAmelCase__ , vqvae=lowerCAmelCase__ ) def SCREAMING_SNAKE_CASE__ ( self ) -> int: '''simple docstring''' return 50 if isinstance(self.scheduler , lowerCAmelCase__ ) else 1_000 @torch.no_grad() def __call__( self , lowerCAmelCase__ = 1 , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = 0 , lowerCAmelCase__ = 0 , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__ = 0 , lowerCAmelCase__ = 0 , lowerCAmelCase__ = None , lowerCAmelCase__ = 0 , lowerCAmelCase__ = None , lowerCAmelCase__ = None , lowerCAmelCase__=True , ) -> Union[ Union[AudioPipelineOutput, ImagePipelineOutput], Tuple[List[Image.Image], Tuple[int, List[np.ndarray]]], ]: '''simple docstring''' lowercase__: Union[str, Any] = steps or self.get_default_steps() self.scheduler.set_timesteps(lowerCAmelCase__ ) lowercase__: Optional[int] = step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: lowercase__: Optional[int] = (self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: lowercase__: List[str] = randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) , generator=lowerCAmelCase__ , device=self.device , ) lowercase__: List[Any] = noise lowercase__: int = None if audio_file is not None or raw_audio is not None: self.mel.load_audio(lowerCAmelCase__ , lowerCAmelCase__ ) lowercase__: int = self.mel.audio_slice_to_image(lowerCAmelCase__ ) lowercase__: int = np.frombuffer(input_image.tobytes() , dtype='uint8' ).reshape( (input_image.height, input_image.width) ) lowercase__: str = (input_image / 255) * 2 - 1 lowercase__: Union[str, Any] = torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device ) if self.vqvae is not None: lowercase__: Optional[int] = self.vqvae.encode(torch.unsqueeze(lowerCAmelCase__ , 0 ) ).latent_dist.sample( generator=lowerCAmelCase__ )[0] lowercase__: Dict = self.vqvae.config.scaling_factor * input_images if start_step > 0: lowercase__: List[Any] = self.scheduler.add_noise(lowerCAmelCase__ , lowerCAmelCase__ , self.scheduler.timesteps[start_step - 1] ) lowercase__: str = ( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) lowercase__: Dict = int(mask_start_secs * pixels_per_second ) lowercase__: Tuple = int(mask_end_secs * pixels_per_second ) lowercase__: List[Any] = self.scheduler.add_noise(lowerCAmelCase__ , lowerCAmelCase__ , torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet , lowerCAmelCase__ ): lowercase__: Union[str, Any] = self.unet(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )['sample'] else: lowercase__: Optional[Any] = self.unet(lowerCAmelCase__ , lowerCAmelCase__ )['sample'] if isinstance(self.scheduler , lowerCAmelCase__ ): lowercase__: List[str] = self.scheduler.step( model_output=lowerCAmelCase__ , timestep=lowerCAmelCase__ , sample=lowerCAmelCase__ , eta=lowerCAmelCase__ , generator=lowerCAmelCase__ , )['prev_sample'] else: lowercase__: int = self.scheduler.step( model_output=lowerCAmelCase__ , timestep=lowerCAmelCase__ , sample=lowerCAmelCase__ , generator=lowerCAmelCase__ , )['prev_sample'] if mask is not None: if mask_start > 0: lowercase__: List[Any] = mask[:, step, :, :mask_start] if mask_end > 0: lowercase__: Optional[int] = mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance lowercase__: Union[str, Any] = 1 / self.vqvae.config.scaling_factor * images lowercase__: Optional[Any] = self.vqvae.decode(lowerCAmelCase__ )['sample'] lowercase__: Dict = (images / 2 + 0.5).clamp(0 , 1 ) lowercase__: List[Any] = images.cpu().permute(0 , 2 , 3 , 1 ).numpy() lowercase__: int = (images * 255).round().astype('uint8' ) lowercase__: Optional[Any] = list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(lowerCAmelCase__ , mode='RGB' ).convert('L' ) for _ in images) ) lowercase__: Dict = [self.mel.image_to_audio(lowerCAmelCase__ ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(lowerCAmelCase__ )[:, np.newaxis, :] ) , **ImagePipelineOutput(lowerCAmelCase__ ) ) @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ , lowerCAmelCase__ = 50 ) -> np.ndarray: '''simple docstring''' assert isinstance(self.scheduler , lowerCAmelCase__ ) self.scheduler.set_timesteps(lowerCAmelCase__ ) lowercase__: List[str] = np.array( [np.frombuffer(image.tobytes() , dtype='uint8' ).reshape((1, image.height, image.width) ) for image in images] ) lowercase__: str = (sample / 255) * 2 - 1 lowercase__: str = torch.Tensor(lowerCAmelCase__ ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ): lowercase__: Union[str, Any] = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps lowercase__: Optional[Any] = self.scheduler.alphas_cumprod[t] lowercase__: str = ( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) lowercase__: str = 1 - alpha_prod_t lowercase__: int = self.unet(lowerCAmelCase__ , lowerCAmelCase__ )['sample'] lowercase__: int = (1 - alpha_prod_t_prev) ** 0.5 * model_output lowercase__: Optional[int] = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) lowercase__: Any = sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) -> torch.Tensor: '''simple docstring''' lowercase__: Any = acos(torch.dot(torch.flatten(lowerCAmelCase__ ) , torch.flatten(lowerCAmelCase__ ) ) / torch.norm(lowerCAmelCase__ ) / torch.norm(lowerCAmelCase__ ) ) return sin((1 - alpha) * theta ) * xa / sin(lowerCAmelCase__ ) + sin(alpha * theta ) * xa / sin(lowerCAmelCase__ )
196
0
'''simple docstring''' import random def lowercase (_A ): """simple docstring""" _lowerCAmelCase : Union[str, Any] = num - 1 _lowerCAmelCase : Optional[Any] = 0 while s % 2 == 0: _lowerCAmelCase : Optional[int] = s // 2 t += 1 for _ in range(5 ): _lowerCAmelCase : Dict = random.randrange(2 , num - 1 ) _lowerCAmelCase : Dict = pow(_A , _A , _A ) if v != 1: _lowerCAmelCase : str = 0 while v != (num - 1): if i == t - 1: return False else: _lowerCAmelCase : Tuple = i + 1 _lowerCAmelCase : Optional[Any] = (v**2) % num return True def lowercase (_A ): """simple docstring""" if num < 2: return False _lowerCAmelCase : List[Any] = [ 2, 3, 5, 7, 1_1, 1_3, 1_7, 1_9, 2_3, 2_9, 3_1, 3_7, 4_1, 4_3, 4_7, 5_3, 5_9, 6_1, 6_7, 7_1, 7_3, 7_9, 8_3, 8_9, 9_7, 1_0_1, 1_0_3, 1_0_7, 1_0_9, 1_1_3, 1_2_7, 1_3_1, 1_3_7, 1_3_9, 1_4_9, 1_5_1, 1_5_7, 1_6_3, 1_6_7, 1_7_3, 1_7_9, 1_8_1, 1_9_1, 1_9_3, 1_9_7, 1_9_9, 2_1_1, 2_2_3, 2_2_7, 2_2_9, 2_3_3, 2_3_9, 2_4_1, 2_5_1, 2_5_7, 2_6_3, 2_6_9, 2_7_1, 2_7_7, 2_8_1, 2_8_3, 2_9_3, 3_0_7, 3_1_1, 3_1_3, 3_1_7, 3_3_1, 3_3_7, 3_4_7, 3_4_9, 3_5_3, 3_5_9, 3_6_7, 3_7_3, 3_7_9, 3_8_3, 3_8_9, 3_9_7, 4_0_1, 4_0_9, 4_1_9, 4_2_1, 4_3_1, 4_3_3, 4_3_9, 4_4_3, 4_4_9, 4_5_7, 4_6_1, 4_6_3, 4_6_7, 4_7_9, 4_8_7, 4_9_1, 4_9_9, 5_0_3, 5_0_9, 5_2_1, 5_2_3, 5_4_1, 5_4_7, 5_5_7, 5_6_3, 5_6_9, 5_7_1, 5_7_7, 5_8_7, 5_9_3, 5_9_9, 6_0_1, 6_0_7, 6_1_3, 6_1_7, 6_1_9, 6_3_1, 6_4_1, 6_4_3, 6_4_7, 6_5_3, 6_5_9, 6_6_1, 6_7_3, 6_7_7, 6_8_3, 6_9_1, 7_0_1, 7_0_9, 7_1_9, 7_2_7, 7_3_3, 7_3_9, 7_4_3, 7_5_1, 7_5_7, 7_6_1, 7_6_9, 7_7_3, 7_8_7, 7_9_7, 8_0_9, 8_1_1, 8_2_1, 8_2_3, 8_2_7, 8_2_9, 8_3_9, 8_5_3, 8_5_7, 8_5_9, 8_6_3, 8_7_7, 8_8_1, 8_8_3, 8_8_7, 9_0_7, 9_1_1, 9_1_9, 9_2_9, 9_3_7, 9_4_1, 9_4_7, 9_5_3, 9_6_7, 9_7_1, 9_7_7, 9_8_3, 9_9_1, 9_9_7, ] if num in low_primes: return True for prime in low_primes: if (num % prime) == 0: return False return rabin_miller(_A ) def lowercase (_A = 1_0_2_4 ): """simple docstring""" while True: _lowerCAmelCase : Any = random.randrange(2 ** (keysize - 1) , 2 ** (keysize) ) if is_prime_low_num(_A ): return num if __name__ == "__main__": lowerCAmelCase : Tuple = generate_large_prime() print(("""Prime number:""", num)) print(("""is_prime_low_num:""", is_prime_low_num(num)))
353
'''simple docstring''' import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartaaTokenizer, MBartaaTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase : Tuple = get_tests_dir("""fixtures/test_sentencepiece.model""") if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right lowerCAmelCase : Union[str, Any] = 25_00_04 lowerCAmelCase : int = 25_00_20 @require_sentencepiece @require_tokenizers class UpperCamelCase__ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): """simple docstring""" __magic_name__ = MBartaaTokenizer __magic_name__ = MBartaaTokenizerFast __magic_name__ = True __magic_name__ = True def a ( self ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing _lowerCAmelCase : List[Any] = MBartaaTokenizer(snake_case__ , src_lang='en_XX' , tgt_lang='ro_RO' , keep_accents=snake_case__ ) tokenizer.save_pretrained(self.tmpdirname ) def a ( self ): '''simple docstring''' _lowerCAmelCase : Optional[int] = '<s>' _lowerCAmelCase : str = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(snake_case__ ) , snake_case__ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(snake_case__ ) , snake_case__ ) def a ( self ): '''simple docstring''' _lowerCAmelCase : 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(snake_case__ ) , 1054 ) def a ( self ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1054 ) def a ( self ): '''simple docstring''' _lowerCAmelCase : Optional[Any] = MBartaaTokenizer(snake_case__ , src_lang='en_XX' , tgt_lang='ro_RO' , keep_accents=snake_case__ ) _lowerCAmelCase : Any = tokenizer.tokenize('This is a test' ) self.assertListEqual(snake_case__ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(snake_case__ ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) _lowerCAmelCase : Tuple = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( snake_case__ , [SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.'] , ) _lowerCAmelCase : Optional[int] = tokenizer.convert_tokens_to_ids(snake_case__ ) self.assertListEqual( snake_case__ , [ 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] ] , ) _lowerCAmelCase : Optional[Any] = tokenizer.convert_ids_to_tokens(snake_case__ ) self.assertListEqual( snake_case__ , [SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.'] , ) @slow def a ( self ): '''simple docstring''' _lowerCAmelCase : Dict = {'input_ids': [[25_0004, 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], [25_0004, 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], [25_0004, 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=snake_case__ , model_name='facebook/mbart-large-50' , revision='d3913889c59cd5c9e456b269c376325eabad57e2' , ) def a ( self ): '''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 _lowerCAmelCase : Optional[int] = (self.rust_tokenizer_class, 'hf-internal-testing/tiny-random-mbart50', {}) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})' ): _lowerCAmelCase : Union[str, Any] = self.rust_tokenizer_class.from_pretrained(snake_case__ , **snake_case__ ) _lowerCAmelCase : Tuple = self.tokenizer_class.from_pretrained(snake_case__ , **snake_case__ ) _lowerCAmelCase : Optional[Any] = tempfile.mkdtemp() _lowerCAmelCase : Tuple = tokenizer_r.save_pretrained(snake_case__ ) _lowerCAmelCase : str = tokenizer_p.save_pretrained(snake_case__ ) # 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 ) ) _lowerCAmelCase : Any = tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(snake_case__ , snake_case__ ) # Checks everything loads correctly in the same way _lowerCAmelCase : List[str] = tokenizer_r.from_pretrained(snake_case__ ) _lowerCAmelCase : Optional[int] = tokenizer_p.from_pretrained(snake_case__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(snake_case__ , snake_case__ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(snake_case__ ) # Save tokenizer rust, legacy_format=True _lowerCAmelCase : Union[str, Any] = tempfile.mkdtemp() _lowerCAmelCase : Dict = tokenizer_r.save_pretrained(snake_case__ , legacy_format=snake_case__ ) _lowerCAmelCase : Any = tokenizer_p.save_pretrained(snake_case__ ) # Checks it save with the same files self.assertSequenceEqual(snake_case__ , snake_case__ ) # Checks everything loads correctly in the same way _lowerCAmelCase : Dict = tokenizer_r.from_pretrained(snake_case__ ) _lowerCAmelCase : List[str] = tokenizer_p.from_pretrained(snake_case__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(snake_case__ , snake_case__ ) ) shutil.rmtree(snake_case__ ) # Save tokenizer rust, legacy_format=False _lowerCAmelCase : Optional[int] = tempfile.mkdtemp() _lowerCAmelCase : int = tokenizer_r.save_pretrained(snake_case__ , legacy_format=snake_case__ ) _lowerCAmelCase : Tuple = tokenizer_p.save_pretrained(snake_case__ ) # 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 _lowerCAmelCase : int = tokenizer_r.from_pretrained(snake_case__ ) _lowerCAmelCase : str = tokenizer_p.from_pretrained(snake_case__ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(snake_case__ , snake_case__ ) ) shutil.rmtree(snake_case__ ) @require_torch @require_sentencepiece @require_tokenizers class UpperCamelCase__ ( unittest.TestCase ): """simple docstring""" __magic_name__ = "facebook/mbart-large-50-one-to-many-mmt" __magic_name__ = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.", ] __magic_name__ = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" " pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor" " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] __magic_name__ = [EN_CODE, 8_2_7_4, 1_2_7_8_7_3, 2_5_9_1_6, 7, 8_6_2_2, 2_0_7_1, 4_3_8, 6_7_4_8_5, 5_3, 1_8_7_8_9_5, 2_3, 5_1_7_1_2, 2] @classmethod def a ( cls ): '''simple docstring''' _lowerCAmelCase : MBartaaTokenizer = MBartaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang='en_XX' , tgt_lang='ro_RO' ) _lowerCAmelCase : Dict = 1 return cls def a ( self ): '''simple docstring''' self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ar_AR'] , 25_0001 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['en_EN'] , 25_0004 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ro_RO'] , 25_0020 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['mr_IN'] , 25_0038 ) def a ( self ): '''simple docstring''' _lowerCAmelCase : int = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , snake_case__ ) def a ( self ): '''simple docstring''' self.assertIn(snake_case__ , self.tokenizer.all_special_ids ) _lowerCAmelCase : Union[str, Any] = [RO_CODE, 884, 9019, 96, 9, 916, 8_6792, 36, 1_8743, 1_5596, 5, 2] _lowerCAmelCase : List[str] = self.tokenizer.decode(snake_case__ , skip_special_tokens=snake_case__ ) _lowerCAmelCase : str = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=snake_case__ ) self.assertEqual(snake_case__ , snake_case__ ) self.assertNotIn(self.tokenizer.eos_token , snake_case__ ) def a ( self ): '''simple docstring''' _lowerCAmelCase : str = ['this is gunna be a long sentence ' * 20] assert isinstance(src_text[0] , snake_case__ ) _lowerCAmelCase : List[str] = 10 _lowerCAmelCase : Any = self.tokenizer(snake_case__ , max_length=snake_case__ , truncation=snake_case__ ).input_ids[0] self.assertEqual(ids[0] , snake_case__ ) self.assertEqual(ids[-1] , 2 ) self.assertEqual(len(snake_case__ ) , snake_case__ ) def a ( self ): '''simple docstring''' self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['<mask>', 'ar_AR'] ) , [25_0053, 25_0001] ) def a ( self ): '''simple docstring''' _lowerCAmelCase : Optional[Any] = tempfile.mkdtemp() _lowerCAmelCase : Dict = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(snake_case__ ) _lowerCAmelCase : Tuple = MBartaaTokenizer.from_pretrained(snake_case__ ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , snake_case__ ) @require_torch def a ( self ): '''simple docstring''' _lowerCAmelCase : str = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=snake_case__ , return_tensors='pt' ) _lowerCAmelCase : Optional[int] = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == RO_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2].tolist() == [2, RO_CODE] @require_torch def a ( self ): '''simple docstring''' _lowerCAmelCase : str = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=snake_case__ , truncation=snake_case__ , max_length=len(self.expected_src_tokens ) , return_tensors='pt' , ) _lowerCAmelCase : int = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) self.assertIsInstance(snake_case__ , snake_case__ ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) _lowerCAmelCase : Union[str, Any] = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , snake_case__ ) self.assertEqual(2 , batch.decoder_input_ids[0, 0] ) # decoder_start_token_id # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def a ( self ): '''simple docstring''' _lowerCAmelCase : Union[str, Any] = self.tokenizer(self.src_text , padding=snake_case__ , truncation=snake_case__ , max_length=3 , return_tensors='pt' ) _lowerCAmelCase : str = self.tokenizer( text_target=self.tgt_text , padding=snake_case__ , truncation=snake_case__ , max_length=10 , return_tensors='pt' ) _lowerCAmelCase : List[Any] = targets['input_ids'] _lowerCAmelCase : Any = shift_tokens_right(snake_case__ , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def a ( self ): '''simple docstring''' _lowerCAmelCase : Optional[int] = self.tokenizer._build_translation_inputs( 'A test' , return_tensors='pt' , src_lang='en_XX' , tgt_lang='ar_AR' ) self.assertEqual( nested_simplify(snake_case__ ) , { # en_XX, A, test, EOS 'input_ids': [[25_0004, 62, 3034, 2]], 'attention_mask': [[1, 1, 1, 1]], # ar_AR 'forced_bos_token_id': 25_0001, } , )
25
0
def _lowercase ( UpperCamelCase_ ) -> str: '''simple docstring''' return "".join(chr(ord(__lowerCamelCase ) - 32 ) if 'a' <= char <= 'z' else char for char in word ) if __name__ == "__main__": from doctest import testmod testmod()
176
__UpperCamelCase : Optional[int] = { "Pillow": "Pillow", "accelerate": "accelerate>=0.11.0", "compel": "compel==0.1.8", "black": "black~=23.1", "datasets": "datasets", "filelock": "filelock", "flax": "flax>=0.4.1", "hf-doc-builder": "hf-doc-builder>=0.3.0", "huggingface-hub": "huggingface-hub>=0.13.2", "requests-mock": "requests-mock==1.10.0", "importlib_metadata": "importlib_metadata", "invisible-watermark": "invisible-watermark", "isort": "isort>=5.5.4", "jax": "jax>=0.2.8,!=0.3.2", "jaxlib": "jaxlib>=0.1.65", "Jinja2": "Jinja2", "k-diffusion": "k-diffusion>=0.0.12", "torchsde": "torchsde", "note_seq": "note_seq", "librosa": "librosa", "numpy": "numpy", "omegaconf": "omegaconf", "parameterized": "parameterized", "protobuf": "protobuf>=3.20.3,<4", "pytest": "pytest", "pytest-timeout": "pytest-timeout", "pytest-xdist": "pytest-xdist", "ruff": "ruff>=0.0.241", "safetensors": "safetensors", "sentencepiece": "sentencepiece>=0.1.91,!=0.1.92", "scipy": "scipy", "onnx": "onnx", "regex": "regex!=2019.12.17", "requests": "requests", "tensorboard": "tensorboard", "torch": "torch>=1.4", "torchvision": "torchvision", "transformers": "transformers>=4.25.1", "urllib3": "urllib3<=2.0.0", }
228
0
from __future__ import annotations __UpperCAmelCase = tuple[int, int, int] __UpperCAmelCase = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase __UpperCAmelCase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # -------------------------- default selection -------------------------- # rotors -------------------------- __UpperCAmelCase = 'EGZWVONAHDCLFQMSIPJBYUKXTR' __UpperCAmelCase = 'FOBHMDKEXQNRAULPGSJVTYICZW' __UpperCAmelCase = 'ZJXESIUQLHAVRMDOYGTNFWPBKC' # reflector -------------------------- __UpperCAmelCase = { 'A': 'N', 'N': 'A', 'B': 'O', 'O': 'B', 'C': 'P', 'P': 'C', 'D': 'Q', 'Q': 'D', 'E': 'R', 'R': 'E', 'F': 'S', 'S': 'F', 'G': 'T', 'T': 'G', 'H': 'U', 'U': 'H', 'I': 'V', 'V': 'I', 'J': 'W', 'W': 'J', 'K': 'X', 'X': 'K', 'L': 'Y', 'Y': 'L', 'M': 'Z', 'Z': 'M', } # -------------------------- extra rotors -------------------------- __UpperCAmelCase = 'RMDJXFUWGISLHVTCQNKYPBEZOA' __UpperCAmelCase = 'SGLCPQWZHKXAREONTFBVIYJUDM' __UpperCAmelCase = 'HVSICLTYKQUBXDWAJZOMFGPREN' __UpperCAmelCase = 'RZWQHFMVDBKICJLNTUXAGYPSOE' __UpperCAmelCase = 'LFKIJODBEGAMQPXVUHYSTCZRWN' __UpperCAmelCase = 'KOAEGVDHXPQZMLFTYWJNBRCIUS' def lowercase__ ( __snake_case : RotorPositionT , __snake_case : RotorSelectionT , __snake_case : str ): '''simple docstring''' if (unique_rotsel := len(set(snake_case_ ) )) < 3: UpperCAmelCase_ : int = F"Please use 3 unique rotors (not {unique_rotsel})" raise Exception(snake_case_ ) # Checks if rotor positions are valid UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : List[str] = rotpos if not 0 < rotorposa <= len(snake_case_ ): UpperCAmelCase_ : Any = F"First rotor position is not within range of 1..26 ({rotorposa}" raise ValueError(snake_case_ ) if not 0 < rotorposa <= len(snake_case_ ): UpperCAmelCase_ : Any = F"Second rotor position is not within range of 1..26 ({rotorposa})" raise ValueError(snake_case_ ) if not 0 < rotorposa <= len(snake_case_ ): UpperCAmelCase_ : Dict = F"Third rotor position is not within range of 1..26 ({rotorposa})" raise ValueError(snake_case_ ) # Validates string and returns dict UpperCAmelCase_ : Tuple = _plugboard(snake_case_ ) return rotpos, rotsel, pbdict def lowercase__ ( __snake_case : str ): '''simple docstring''' if not isinstance(snake_case_ , snake_case_ ): UpperCAmelCase_ : List[str] = F"Plugboard setting isn't type string ({type(snake_case_ )})" raise TypeError(snake_case_ ) elif len(snake_case_ ) % 2 != 0: UpperCAmelCase_ : Tuple = F"Odd number of symbols ({len(snake_case_ )})" raise Exception(snake_case_ ) elif pbstring == "": return {} pbstring.replace(' ' , '' ) # Checks if all characters are unique UpperCAmelCase_ : List[str] = set() for i in pbstring: if i not in abc: UpperCAmelCase_ : Tuple = F"'{i}' not in list of symbols" raise Exception(snake_case_ ) elif i in tmppbl: UpperCAmelCase_ : Dict = F"Duplicate symbol ({i})" raise Exception(snake_case_ ) else: tmppbl.add(snake_case_ ) del tmppbl # Created the dictionary UpperCAmelCase_ : Optional[Any] = {} for j in range(0 , len(snake_case_ ) - 1 , 2 ): UpperCAmelCase_ : List[Any] = pbstring[j + 1] UpperCAmelCase_ : List[str] = pbstring[j] return pb def lowercase__ ( __snake_case : str , __snake_case : RotorPositionT , __snake_case : RotorSelectionT = (rotora, rotora, rotora) , __snake_case : str = "" , ): '''simple docstring''' UpperCAmelCase_ : Optional[int] = text.upper() UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Dict = _validator( snake_case_ , snake_case_ , plugb.upper() ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : Optional[Any] = rotor_position UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ : str = rotor_selection rotorposa -= 1 rotorposa -= 1 rotorposa -= 1 UpperCAmelCase_ : Dict = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: UpperCAmelCase_ : List[Any] = plugboard[symbol] # rotor ra -------------------------- UpperCAmelCase_ : int = abc.index(snake_case_ ) + rotorposa UpperCAmelCase_ : List[str] = rotora[index % len(snake_case_ )] # rotor rb -------------------------- UpperCAmelCase_ : List[str] = abc.index(snake_case_ ) + rotorposa UpperCAmelCase_ : Optional[int] = rotora[index % len(snake_case_ )] # rotor rc -------------------------- UpperCAmelCase_ : Dict = abc.index(snake_case_ ) + rotorposa UpperCAmelCase_ : Optional[int] = rotora[index % len(snake_case_ )] # reflector -------------------------- # this is the reason you don't need another machine to decipher UpperCAmelCase_ : Tuple = reflector[symbol] # 2nd rotors UpperCAmelCase_ : Tuple = abc[rotora.index(snake_case_ ) - rotorposa] UpperCAmelCase_ : Dict = abc[rotora.index(snake_case_ ) - rotorposa] UpperCAmelCase_ : Union[str, Any] = abc[rotora.index(snake_case_ ) - rotorposa] # 2nd plugboard if symbol in plugboard: UpperCAmelCase_ : Optional[Any] = plugboard[symbol] # moves/resets rotor positions rotorposa += 1 if rotorposa >= len(snake_case_ ): UpperCAmelCase_ : Optional[Any] = 0 rotorposa += 1 if rotorposa >= len(snake_case_ ): UpperCAmelCase_ : int = 0 rotorposa += 1 if rotorposa >= len(snake_case_ ): UpperCAmelCase_ : int = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(snake_case_ ) return "".join(snake_case_ ) if __name__ == "__main__": __UpperCAmelCase = 'This is my Python script that emulates the Enigma machine from WWII.' __UpperCAmelCase = (1, 1, 1) __UpperCAmelCase = 'pictures' __UpperCAmelCase = (rotora, rotora, rotora) __UpperCAmelCase = enigma(message, rotor_pos, rotor_sel, pb) print('Encrypted message:', en) print('Decrypted message:', enigma(en, rotor_pos, rotor_sel, pb))
368
import torch from diffusers import DDPMParallelScheduler from .test_schedulers import SchedulerCommonTest class lowerCamelCase (_snake_case ): '''simple docstring''' _snake_case : Any = (DDPMParallelScheduler,) def __UpperCAmelCase ( self , **_UpperCamelCase ) -> Any: UpperCAmelCase_ : List[str] = { 'num_train_timesteps': 1_0_0_0, 'beta_start': 0.00_01, 'beta_end': 0.02, 'beta_schedule': 'linear', 'variance_type': 'fixed_small', 'clip_sample': True, } config.update(**_UpperCamelCase ) return config def __UpperCAmelCase ( self ) -> Any: for timesteps in [1, 5, 1_0_0, 1_0_0_0]: self.check_over_configs(num_train_timesteps=_UpperCamelCase ) def __UpperCAmelCase ( self ) -> int: for beta_start, beta_end in zip([0.00_01, 0.0_01, 0.01, 0.1] , [0.0_02, 0.02, 0.2, 2] ): self.check_over_configs(beta_start=_UpperCamelCase , beta_end=_UpperCamelCase ) def __UpperCAmelCase ( self ) -> Any: for schedule in ["linear", "squaredcos_cap_v2"]: self.check_over_configs(beta_schedule=_UpperCamelCase ) def __UpperCAmelCase ( self ) -> Optional[Any]: for variance in ["fixed_small", "fixed_large", "other"]: self.check_over_configs(variance_type=_UpperCamelCase ) def __UpperCAmelCase ( self ) -> Optional[int]: for clip_sample in [True, False]: self.check_over_configs(clip_sample=_UpperCamelCase ) def __UpperCAmelCase ( self ) -> Union[str, Any]: self.check_over_configs(thresholding=_UpperCamelCase ) for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs( thresholding=_UpperCamelCase , prediction_type=_UpperCamelCase , sample_max_value=_UpperCamelCase , ) def __UpperCAmelCase ( self ) -> Any: for prediction_type in ["epsilon", "sample", "v_prediction"]: self.check_over_configs(prediction_type=_UpperCamelCase ) def __UpperCAmelCase ( self ) -> Union[str, Any]: for t in [0, 5_0_0, 9_9_9]: self.check_over_forward(time_step=_UpperCamelCase ) def __UpperCAmelCase ( self ) -> Dict: UpperCAmelCase_ : Dict = self.scheduler_classes[0] UpperCAmelCase_ : int = self.get_scheduler_config() UpperCAmelCase_ : Union[str, Any] = scheduler_class(**_UpperCamelCase ) assert torch.sum(torch.abs(scheduler._get_variance(0 ) - 0.0 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(4_8_7 ) - 0.0_09_79 ) ) < 1E-5 assert torch.sum(torch.abs(scheduler._get_variance(9_9_9 ) - 0.02 ) ) < 1E-5 def __UpperCAmelCase ( self ) -> Dict: UpperCAmelCase_ : List[Any] = self.scheduler_classes[0] UpperCAmelCase_ : Any = self.get_scheduler_config() UpperCAmelCase_ : Union[str, Any] = scheduler_class(**_UpperCamelCase ) UpperCAmelCase_ : Optional[Any] = len(_UpperCamelCase ) UpperCAmelCase_ : Any = self.dummy_model() UpperCAmelCase_ : List[Any] = self.dummy_sample_deter UpperCAmelCase_ : Union[str, Any] = self.dummy_sample_deter + 0.1 UpperCAmelCase_ : str = self.dummy_sample_deter - 0.1 UpperCAmelCase_ : Tuple = samplea.shape[0] UpperCAmelCase_ : Tuple = torch.stack([samplea, samplea, samplea] , dim=0 ) UpperCAmelCase_ : str = torch.arange(_UpperCamelCase )[0:3, None].repeat(1 , _UpperCamelCase ) UpperCAmelCase_ : Any = model(samples.flatten(0 , 1 ) , timesteps.flatten(0 , 1 ) ) UpperCAmelCase_ : Dict = scheduler.batch_step_no_noise(_UpperCamelCase , timesteps.flatten(0 , 1 ) , samples.flatten(0 , 1 ) ) UpperCAmelCase_ : List[Any] = torch.sum(torch.abs(_UpperCamelCase ) ) UpperCAmelCase_ : Any = torch.mean(torch.abs(_UpperCamelCase ) ) assert abs(result_sum.item() - 11_53.18_33 ) < 1E-2 assert abs(result_mean.item() - 0.50_05 ) < 1E-3 def __UpperCAmelCase ( self ) -> Union[str, Any]: UpperCAmelCase_ : List[str] = self.scheduler_classes[0] UpperCAmelCase_ : List[Any] = self.get_scheduler_config() UpperCAmelCase_ : Any = scheduler_class(**_UpperCamelCase ) UpperCAmelCase_ : Optional[int] = len(_UpperCamelCase ) UpperCAmelCase_ : Optional[int] = self.dummy_model() UpperCAmelCase_ : Optional[int] = self.dummy_sample_deter UpperCAmelCase_ : Union[str, Any] = torch.manual_seed(0 ) for t in reversed(range(_UpperCamelCase ) ): # 1. predict noise residual UpperCAmelCase_ : Union[str, Any] = model(_UpperCamelCase , _UpperCamelCase ) # 2. predict previous mean of sample x_t-1 UpperCAmelCase_ : str = scheduler.step(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , generator=_UpperCamelCase ).prev_sample UpperCAmelCase_ : str = pred_prev_sample UpperCAmelCase_ : Optional[int] = torch.sum(torch.abs(_UpperCamelCase ) ) UpperCAmelCase_ : Optional[int] = torch.mean(torch.abs(_UpperCamelCase ) ) assert abs(result_sum.item() - 2_58.96_06 ) < 1E-2 assert abs(result_mean.item() - 0.33_72 ) < 1E-3 def __UpperCAmelCase ( self ) -> int: UpperCAmelCase_ : List[Any] = self.scheduler_classes[0] UpperCAmelCase_ : Optional[int] = self.get_scheduler_config(prediction_type='v_prediction' ) UpperCAmelCase_ : Tuple = scheduler_class(**_UpperCamelCase ) UpperCAmelCase_ : Tuple = len(_UpperCamelCase ) UpperCAmelCase_ : Tuple = self.dummy_model() UpperCAmelCase_ : List[str] = self.dummy_sample_deter UpperCAmelCase_ : Any = torch.manual_seed(0 ) for t in reversed(range(_UpperCamelCase ) ): # 1. predict noise residual UpperCAmelCase_ : Optional[Any] = model(_UpperCamelCase , _UpperCamelCase ) # 2. predict previous mean of sample x_t-1 UpperCAmelCase_ : Any = scheduler.step(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase , generator=_UpperCamelCase ).prev_sample UpperCAmelCase_ : List[str] = pred_prev_sample UpperCAmelCase_ : Optional[int] = torch.sum(torch.abs(_UpperCamelCase ) ) UpperCAmelCase_ : Any = torch.mean(torch.abs(_UpperCamelCase ) ) assert abs(result_sum.item() - 2_02.02_96 ) < 1E-2 assert abs(result_mean.item() - 0.26_31 ) < 1E-3 def __UpperCAmelCase ( self ) -> List[Any]: UpperCAmelCase_ : Any = self.scheduler_classes[0] UpperCAmelCase_ : Optional[Any] = self.get_scheduler_config() UpperCAmelCase_ : str = scheduler_class(**_UpperCamelCase ) UpperCAmelCase_ : Optional[int] = [1_0_0, 8_7, 5_0, 1, 0] scheduler.set_timesteps(timesteps=_UpperCamelCase ) UpperCAmelCase_ : Tuple = scheduler.timesteps for i, timestep in enumerate(_UpperCamelCase ): if i == len(_UpperCamelCase ) - 1: UpperCAmelCase_ : List[str] = -1 else: UpperCAmelCase_ : int = timesteps[i + 1] UpperCAmelCase_ : int = scheduler.previous_timestep(_UpperCamelCase ) UpperCAmelCase_ : Optional[Any] = prev_t.item() self.assertEqual(_UpperCamelCase , _UpperCamelCase ) def __UpperCAmelCase ( self ) -> List[Any]: UpperCAmelCase_ : str = self.scheduler_classes[0] UpperCAmelCase_ : Tuple = self.get_scheduler_config() UpperCAmelCase_ : Union[str, Any] = scheduler_class(**_UpperCamelCase ) UpperCAmelCase_ : Optional[int] = [1_0_0, 8_7, 5_0, 5_1, 0] with self.assertRaises(_UpperCamelCase , msg='`custom_timesteps` must be in descending order.' ): scheduler.set_timesteps(timesteps=_UpperCamelCase ) def __UpperCAmelCase ( self ) -> Tuple: UpperCAmelCase_ : Any = self.scheduler_classes[0] UpperCAmelCase_ : List[str] = self.get_scheduler_config() UpperCAmelCase_ : List[str] = scheduler_class(**_UpperCamelCase ) UpperCAmelCase_ : Tuple = [1_0_0, 8_7, 5_0, 1, 0] UpperCAmelCase_ : Optional[Any] = len(_UpperCamelCase ) with self.assertRaises(_UpperCamelCase , msg='Can only pass one of `num_inference_steps` or `custom_timesteps`.' ): scheduler.set_timesteps(num_inference_steps=_UpperCamelCase , timesteps=_UpperCamelCase ) def __UpperCAmelCase ( self ) -> Dict: UpperCAmelCase_ : List[str] = self.scheduler_classes[0] UpperCAmelCase_ : Any = self.get_scheduler_config() UpperCAmelCase_ : Optional[Any] = scheduler_class(**_UpperCamelCase ) UpperCAmelCase_ : Dict = [scheduler.config.num_train_timesteps] with self.assertRaises( _UpperCamelCase , msg='`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}' , ): scheduler.set_timesteps(timesteps=_UpperCamelCase )
145
0
from transformers import BertTokenizer, EncoderDecoderModel, SeqaSeqTrainer, SeqaSeqTrainingArguments from transformers.testing_utils import TestCasePlus, require_torch, slow from transformers.utils import is_datasets_available if is_datasets_available(): import datasets class _UpperCamelCase ( __A ): '''simple docstring''' @slow @require_torch def __UpperCamelCase ( self : Optional[Any] ) -> Dict: """simple docstring""" SCREAMING_SNAKE_CASE : List[str] = EncoderDecoderModel.from_encoder_decoder_pretrained("prajjwal1/bert-tiny" , "prajjwal1/bert-tiny" ) SCREAMING_SNAKE_CASE : Any = BertTokenizer.from_pretrained("bert-base-uncased" ) SCREAMING_SNAKE_CASE : int = bertabert.config.encoder.vocab_size SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.sep_token_id SCREAMING_SNAKE_CASE : Tuple = tokenizer.cls_token_id SCREAMING_SNAKE_CASE : Optional[int] = 128 SCREAMING_SNAKE_CASE : str = datasets.load_dataset("cnn_dailymail" , "3.0.0" , split="train[:1%]" ) SCREAMING_SNAKE_CASE : Optional[int] = datasets.load_dataset("cnn_dailymail" , "3.0.0" , split="validation[:1%]" ) SCREAMING_SNAKE_CASE : List[str] = train_dataset.select(range(32 ) ) SCREAMING_SNAKE_CASE : Dict = val_dataset.select(range(16 ) ) SCREAMING_SNAKE_CASE : str = 4 def _map_to_encoder_decoder_inputs(a : List[str] ): # Tokenizer will automatically set [BOS] <text> [EOS] SCREAMING_SNAKE_CASE : Any = tokenizer(batch["article"] , padding="max_length" , truncation=a , max_length=512 ) SCREAMING_SNAKE_CASE : Union[str, Any] = tokenizer(batch["highlights"] , padding="max_length" , truncation=a , max_length=128 ) SCREAMING_SNAKE_CASE : Optional[Any] = inputs.input_ids SCREAMING_SNAKE_CASE : List[str] = inputs.attention_mask SCREAMING_SNAKE_CASE : str = outputs.input_ids SCREAMING_SNAKE_CASE : List[str] = outputs.input_ids.copy() SCREAMING_SNAKE_CASE : List[str] = [ [-100 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch["labels"] ] SCREAMING_SNAKE_CASE : Any = outputs.attention_mask assert all(len(a ) == 512 for x in inputs.input_ids ) assert all(len(a ) == 128 for x in outputs.input_ids ) return batch def _compute_metrics(a : int ): SCREAMING_SNAKE_CASE : Dict = pred.label_ids SCREAMING_SNAKE_CASE : Optional[Any] = pred.predictions # all unnecessary tokens are removed SCREAMING_SNAKE_CASE : Optional[int] = tokenizer.batch_decode(a , skip_special_tokens=a ) SCREAMING_SNAKE_CASE : int = tokenizer.batch_decode(a , skip_special_tokens=a ) SCREAMING_SNAKE_CASE : int = sum([int(pred_str[i] == label_str[i] ) for i in range(len(a ) )] ) / len(a ) return {"accuracy": accuracy} # map train dataset SCREAMING_SNAKE_CASE : Optional[Any] = train_dataset.map( _map_to_encoder_decoder_inputs , batched=a , batch_size=a , remove_columns=["article", "highlights"] , ) train_dataset.set_format( type="torch" , columns=["input_ids", "attention_mask", "decoder_input_ids", "decoder_attention_mask", "labels"] , ) # same for validation dataset SCREAMING_SNAKE_CASE : Union[str, Any] = val_dataset.map( _map_to_encoder_decoder_inputs , batched=a , batch_size=a , remove_columns=["article", "highlights"] , ) val_dataset.set_format( type="torch" , columns=["input_ids", "attention_mask", "decoder_input_ids", "decoder_attention_mask", "labels"] , ) SCREAMING_SNAKE_CASE : int = self.get_auto_remove_tmp_dir() SCREAMING_SNAKE_CASE : Any = SeqaSeqTrainingArguments( output_dir=a , per_device_train_batch_size=a , per_device_eval_batch_size=a , predict_with_generate=a , evaluation_strategy="steps" , do_train=a , do_eval=a , warmup_steps=0 , eval_steps=2 , logging_steps=2 , ) # instantiate trainer SCREAMING_SNAKE_CASE : Optional[Any] = SeqaSeqTrainer( model=a , args=a , compute_metrics=_compute_metrics , train_dataset=a , eval_dataset=a , tokenizer=a , ) # start training trainer.train()
76
def lowerCamelCase__ ( _a , _a): _validate_point(_a) _validate_point(_a) if len(_a) != len(_a): raise ValueError("Both points must be in the same n-dimensional space") return float(sum(abs(a - b) for a, b in zip(_a , _a))) def lowerCamelCase__ ( _a): if point: if isinstance(_a , _a): for item in point: if not isinstance(_a , (int, float)): SCREAMING_SNAKE_CASE : List[Any] = ( "Expected a list of numbers as input, found " f"{type(_a).__name__}" ) raise TypeError(_a) else: SCREAMING_SNAKE_CASE : List[Any] = f"Expected a list of numbers as input, found {type(_a).__name__}" raise TypeError(_a) else: raise ValueError("Missing an input") def lowerCamelCase__ ( _a , _a): _validate_point(_a) _validate_point(_a) if len(_a) != len(_a): raise ValueError("Both points must be in the same n-dimensional space") return float(sum(abs(x - y) for x, y in zip(_a , _a))) if __name__ == "__main__": import doctest doctest.testmod()
76
1
'''simple docstring''' from __future__ import annotations def a ( lowerCamelCase__ , lowerCamelCase__ = None ): '''simple docstring''' A_ : int = word_bank or [] # create a table A_ : int = len(lowerCamelCase__ ) + 1 A_ : list[list[list[str]]] = [] for _ in range(lowerCamelCase__ ): table.append([] ) # seed value A_ : Dict = [[]] # because empty string has empty combination # iterate through the indices for i in range(lowerCamelCase__ ): # condition if table[i] != []: for word in word_bank: # slice condition if target[i : i + len(lowerCamelCase__ )] == word: A_ : list[list[str]] = [ [word, *way] for way in table[i] ] # adds the word to every combination the current position holds # now,push that combination to the table[i+len(word)] table[i + len(lowerCamelCase__ )] += new_combinations # combinations are in reverse order so reverse for better output for combination in table[len(lowerCamelCase__ )]: combination.reverse() return table[len(lowerCamelCase__ )] if __name__ == "__main__": print(all_construct('''jwajalapa''', ['''jwa''', '''j''', '''w''', '''a''', '''la''', '''lapa'''])) print(all_construct('''rajamati''', ['''s''', '''raj''', '''amat''', '''raja''', '''ma''', '''i''', '''t'''])) print( all_construct( '''hexagonosaurus''', ['''h''', '''ex''', '''hex''', '''ag''', '''ago''', '''ru''', '''auru''', '''rus''', '''go''', '''no''', '''o''', '''s'''], ) )
361
'''simple docstring''' def a ( lowerCamelCase__ ): '''simple docstring''' return " ".join(input_str.split()[::-1] ) if __name__ == "__main__": import doctest doctest.testmod()
135
0
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Union[str, Any]: global f # a global dp table for knapsack if f[i][j] < 0: if j < wt[i - 1]: __lowerCamelCase = mf_knapsack(i - 1 , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) else: __lowerCamelCase = max( mf_knapsack(i - 1 , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) , mf_knapsack(i - 1 , UpperCamelCase__ , UpperCamelCase__ , j - wt[i - 1] ) + val[i - 1] , ) __lowerCamelCase = val return f[i][j] def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> List[Any]: __lowerCamelCase = [[0] * (w + 1) for _ in range(n + 1 )] for i in range(1 , n + 1 ): for w_ in range(1 , w + 1 ): if wt[i - 1] <= w_: __lowerCamelCase = max(val[i - 1] + dp[i - 1][w_ - wt[i - 1]] , dp[i - 1][w_] ) else: __lowerCamelCase = dp[i - 1][w_] return dp[n][w_], dp def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> int: if not (isinstance(UpperCamelCase__ , (list, tuple) ) and isinstance(UpperCamelCase__ , (list, tuple) )): raise ValueError( '''Both the weights and values vectors must be either lists or tuples''' ) __lowerCamelCase = len(UpperCamelCase__ ) if num_items != len(UpperCamelCase__ ): __lowerCamelCase = ( '''The number of weights must be the same as the number of values.\n''' f"""But got {num_items} weights and {len(UpperCamelCase__ )} values""" ) raise ValueError(UpperCamelCase__ ) for i in range(UpperCamelCase__ ): if not isinstance(wt[i] , UpperCamelCase__ ): __lowerCamelCase = ( '''All weights must be integers but got weight of ''' f"""type {type(wt[i] )} at index {i}""" ) raise TypeError(UpperCamelCase__ ) __lowerCamelCase , __lowerCamelCase = knapsack(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) __lowerCamelCase = set() _construct_solution(UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) return optimal_val, example_optional_set def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ ) -> Union[str, Any]: # for the current item i at a maximum weight j to be part of an optimal subset, # the optimal value at (i, j) must be greater than the optimal value at (i-1, j). # where i - 1 means considering only the previous items at the given maximum weight if i > 0 and j > 0: if dp[i - 1][j] == dp[i][j]: _construct_solution(UpperCamelCase__ , UpperCamelCase__ , i - 1 , UpperCamelCase__ , UpperCamelCase__ ) else: optimal_set.add(UpperCamelCase__ ) _construct_solution(UpperCamelCase__ , UpperCamelCase__ , i - 1 , j - wt[i - 1] , UpperCamelCase__ ) if __name__ == "__main__": __UpperCAmelCase =[3, 2, 4, 4] __UpperCAmelCase =[4, 3, 2, 3] __UpperCAmelCase =4 __UpperCAmelCase =6 __UpperCAmelCase =[[0] * (w + 1)] + [[0] + [-1] * (w + 1) for _ in range(n + 1)] __UpperCAmelCase , __UpperCAmelCase =knapsack(w, wt, val, n) print(optimal_solution) print(mf_knapsack(n, wt, val, w)) # switched the n and w # testing the dynamic programming problem with example # the optimal subset for the above example are items 3 and 4 __UpperCAmelCase , __UpperCAmelCase =knapsack_with_example_solution(w, wt, val) assert optimal_solution == 8 assert optimal_subset == {3, 4} print("optimal_value = ", optimal_solution) print("An optimal subset corresponding to the optimal value", optimal_subset)
67
'''simple docstring''' def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> Optional[int]: if b == 0: return 1 if (b % 2) == 0: return actual_power(UpperCamelCase__ , int(b / 2 ) ) * actual_power(UpperCamelCase__ , int(b / 2 ) ) else: return a * actual_power(UpperCamelCase__ , int(b / 2 ) ) * actual_power(UpperCamelCase__ , int(b / 2 ) ) def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> float: if b < 0: return 1 / actual_power(UpperCamelCase__ , UpperCamelCase__ ) return actual_power(UpperCamelCase__ , UpperCamelCase__ ) if __name__ == "__main__": print(power(-2, -3))
67
1
"""simple docstring""" class __lowerCamelCase : """simple docstring""" def __init__( self , UpperCAmelCase ) -> None: '''simple docstring''' lowercase_ = len(UpperCAmelCase ) lowercase_ = [0] * len_array if len_array > 0: lowercase_ = array[0] for i in range(1 , UpperCAmelCase ): lowercase_ = self.prefix_sum[i - 1] + array[i] def A__ ( self , UpperCAmelCase , UpperCAmelCase ) -> int: '''simple docstring''' if start == 0: return self.prefix_sum[end] return self.prefix_sum[end] - self.prefix_sum[start - 1] def A__ ( self , UpperCAmelCase ) -> bool: '''simple docstring''' lowercase_ = {0} for sum_item in self.prefix_sum: if sum_item - target_sum in sums: return True sums.add(UpperCAmelCase ) return False if __name__ == "__main__": import doctest doctest.testmod()
350
def SCREAMING_SNAKE_CASE_ ( __lowerCamelCase: int ): '''simple docstring''' if a < 0: raise ValueError("Input value must be a positive integer" ) elif isinstance(__lowerCamelCase , __lowerCamelCase ): raise TypeError("Input value must be a 'int' type" ) return bin(__lowerCamelCase ).count("1" ) if __name__ == "__main__": import doctest doctest.testmod()
297
0
import json import logging import os import sys from pathlib import Path import finetune_rag from transformers.file_utils import is_apex_available from transformers.testing_utils import ( TestCasePlus, execute_subprocess_async, require_ray, require_torch_gpu, require_torch_multi_gpu, ) logging.basicConfig(level=logging.DEBUG) UpperCamelCase__ = logging.getLogger() UpperCamelCase__ = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class a__ ( snake_case__ ): def __SCREAMING_SNAKE_CASE( self , _A ): """simple docstring""" os.makedirs(_A , exist_ok=_A ) __lowerCAmelCase = {"source": "What is love ?", "target": "life"} __lowerCAmelCase = {"train": 1_2, "val": 2, "test": 2} for split in ["train", "test", "val"]: for field in ["source", "target"]: __lowerCAmelCase = "\n".join([contents[field]] * n_lines[split] ) with open(os.path.join(_A , f"""{split}.{field}""" ) , "w" ) as f: f.write(_A ) def __SCREAMING_SNAKE_CASE( self , _A , _A = "pytorch" ): """simple docstring""" __lowerCAmelCase = self.get_auto_remove_tmp_dir() __lowerCAmelCase = os.path.join(_A , "output" ) __lowerCAmelCase = os.path.join(_A , "data" ) self._create_dummy_data(data_dir=_A ) __lowerCAmelCase = f""" --data_dir {data_dir} \ --output_dir {output_dir} \ --model_name_or_path facebook/rag-sequence-base \ --model_type rag_sequence \ --do_train \ --do_predict \ --n_val -1 \ --val_check_interval 1.0 \ --train_batch_size 2 \ --eval_batch_size 1 \ --max_source_length 25 \ --max_target_length 25 \ --val_max_target_length 25 \ --test_max_target_length 25 \ --label_smoothing 0.1 \ --dropout 0.1 \ --attention_dropout 0.1 \ --weight_decay 0.001 \ --adam_epsilon 1e-08 \ --max_grad_norm 0.1 \ --lr_scheduler polynomial \ --learning_rate 3e-04 \ --num_train_epochs 1 \ --warmup_steps 4 \ --gradient_accumulation_steps 1 \ --distributed-port 8787 \ --use_dummy_dataset 1 \ --distributed_retriever {distributed_retriever} \ """.split() if gpus > 0: testargs.append(f"""--gpus={gpus}""" ) if is_apex_available(): testargs.append("--fp16" ) else: testargs.append("--gpus=0" ) testargs.append("--distributed_backend=ddp_cpu" ) testargs.append("--num_processes=2" ) __lowerCAmelCase = [sys.executable, str(Path(finetune_rag.__file__ ).resolve() )] + testargs execute_subprocess_async(_A , env=self.get_env() ) __lowerCAmelCase = os.path.join(_A , "metrics.json" ) with open(_A ) as f: __lowerCAmelCase = json.load(_A ) return result @require_torch_gpu def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self._run_finetune(gpus=1 ) self.assertGreaterEqual(result["test"][0]["test_avg_em"] , 0.2 ) @require_torch_multi_gpu def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self._run_finetune(gpus=2 ) self.assertGreaterEqual(result["test"][0]["test_avg_em"] , 0.2 ) @require_torch_gpu @require_ray def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self._run_finetune(gpus=1 , distributed_retriever="ray" ) self.assertGreaterEqual(result["test"][0]["test_avg_em"] , 0.2 ) @require_torch_multi_gpu @require_ray def __SCREAMING_SNAKE_CASE( self ): """simple docstring""" __lowerCAmelCase = self._run_finetune(gpus=1 , distributed_retriever="ray" ) self.assertGreaterEqual(result["test"][0]["test_avg_em"] , 0.2 )
92
"""simple docstring""" from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import tensorflow as tf from transformers import AutoTokenizer, TFAutoModelForSeqaSeqLM @require_tf @require_sentencepiece @require_tokenizers class a__ ( unittest.TestCase ): @slow def lowercase ( self : List[Any] ) -> List[Any]: lowercase : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained('google/mt5-small' ) lowercase : Dict = AutoTokenizer.from_pretrained('google/mt5-small' ) lowercase : List[Any] = tokenizer('Hello there', return_tensors='tf' ).input_ids lowercase : Any = tokenizer('Hi I am', return_tensors='tf' ).input_ids lowercase : Dict = model(lowerCAmelCase, labels=lowerCAmelCase ).loss lowercase : Optional[int] = -tf.math.reduce_mean(lowerCAmelCase ).numpy() lowercase : Tuple = -21.22_8168 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 2e-4 )
255
0
'''simple docstring''' import collections.abc from typing import Optional, Tuple, Union import torch import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from ...activations import ACTaFN from ...modeling_outputs import BaseModelOutputWithNoAttention, 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_poolformer import PoolFormerConfig UpperCamelCase_ = logging.get_logger(__name__) # General docstring UpperCamelCase_ = "PoolFormerConfig" # Base docstring UpperCamelCase_ = "sail/poolformer_s12" UpperCamelCase_ = [1, 5_1_2, 7, 7] # Image classification docstring UpperCamelCase_ = "sail/poolformer_s12" UpperCamelCase_ = "tabby, tabby cat" UpperCamelCase_ = [ "sail/poolformer_s12", # See all PoolFormer models at https://huggingface.co/models?filter=poolformer ] def lowercase__( __UpperCamelCase: List[str] ,__UpperCamelCase: float = 0.0 ,__UpperCamelCase: bool = False ): """simple docstring""" if drop_prob == 0.0 or not training: return input SCREAMING_SNAKE_CASE : List[str] = 1 - drop_prob SCREAMING_SNAKE_CASE : Tuple = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets SCREAMING_SNAKE_CASE : Tuple = keep_prob + torch.rand(__UpperCamelCase ,dtype=input.dtype ,device=input.device ) random_tensor.floor_() # binarize SCREAMING_SNAKE_CASE : Dict = input.div(__UpperCamelCase ) * random_tensor return output class _a ( nn.Module ): '''simple docstring''' def __init__( self, A = None ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE : List[Any] = drop_prob def UpperCamelCase_ ( self, A ): '''simple docstring''' return drop_path(A, self.drop_prob, self.training ) def UpperCamelCase_ ( self ): '''simple docstring''' return "p={}".format(self.drop_prob ) class _a ( nn.Module ): '''simple docstring''' def __init__( self, A, A, A, A, A, A=None ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE : Optional[int] = patch_size if isinstance(A, collections.abc.Iterable ) else (patch_size, patch_size) SCREAMING_SNAKE_CASE : Union[str, Any] = stride if isinstance(A, collections.abc.Iterable ) else (stride, stride) SCREAMING_SNAKE_CASE : List[str] = padding if isinstance(A, collections.abc.Iterable ) else (padding, padding) SCREAMING_SNAKE_CASE : Optional[int] = nn.Convad(A, A, kernel_size=A, stride=A, padding=A ) SCREAMING_SNAKE_CASE : List[str] = norm_layer(A ) if norm_layer else nn.Identity() def UpperCamelCase_ ( self, A ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.projection(A ) SCREAMING_SNAKE_CASE : List[str] = self.norm(A ) return embeddings class _a ( nn.GroupNorm ): '''simple docstring''' def __init__( self, A, **A ): '''simple docstring''' super().__init__(1, A, **A ) class _a ( nn.Module ): '''simple docstring''' def __init__( self, A ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE : Union[str, Any] = nn.AvgPoolad(A, stride=1, padding=pool_size // 2, count_include_pad=A ) def UpperCamelCase_ ( self, A ): '''simple docstring''' return self.pool(A ) - hidden_states class _a ( nn.Module ): '''simple docstring''' def __init__( self, A, A, A, A ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE : List[Any] = nn.Convad(A, A, 1 ) SCREAMING_SNAKE_CASE : Optional[Any] = nn.Convad(A, A, 1 ) SCREAMING_SNAKE_CASE : Union[str, Any] = PoolFormerDropPath(A ) if isinstance(config.hidden_act, A ): SCREAMING_SNAKE_CASE : Any = ACTaFN[config.hidden_act] else: SCREAMING_SNAKE_CASE : List[str] = config.hidden_act def UpperCamelCase_ ( self, A ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = self.conva(A ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.act_fn(A ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.drop(A ) SCREAMING_SNAKE_CASE : Union[str, Any] = self.conva(A ) SCREAMING_SNAKE_CASE : List[str] = self.drop(A ) return hidden_states class _a ( nn.Module ): '''simple docstring''' def __init__( self, A, A, A, A, A, A ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE : Union[str, Any] = PoolFormerPooling(A ) SCREAMING_SNAKE_CASE : Any = PoolFormerOutput(A, A, A, A ) SCREAMING_SNAKE_CASE : Union[str, Any] = PoolFormerGroupNorm(A ) SCREAMING_SNAKE_CASE : Any = PoolFormerGroupNorm(A ) # Useful for training neural nets SCREAMING_SNAKE_CASE : int = PoolFormerDropPath(A ) if drop_path > 0.0 else nn.Identity() SCREAMING_SNAKE_CASE : List[Any] = config.use_layer_scale if config.use_layer_scale: SCREAMING_SNAKE_CASE : Union[str, Any] = nn.Parameter( config.layer_scale_init_value * torch.ones((A) ), requires_grad=A ) SCREAMING_SNAKE_CASE : Optional[int] = nn.Parameter( config.layer_scale_init_value * torch.ones((A) ), requires_grad=A ) def UpperCamelCase_ ( self, A ): '''simple docstring''' if self.use_layer_scale: SCREAMING_SNAKE_CASE : str = self.pooling(self.before_norm(A ) ) SCREAMING_SNAKE_CASE : List[str] = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * pooling_output # First residual connection SCREAMING_SNAKE_CASE : List[Any] = hidden_states + self.drop_path(A ) SCREAMING_SNAKE_CASE : Any = () SCREAMING_SNAKE_CASE : List[str] = self.output(self.after_norm(A ) ) SCREAMING_SNAKE_CASE : Tuple = self.layer_scale_a.unsqueeze(-1 ).unsqueeze(-1 ) * layer_output # Second residual connection SCREAMING_SNAKE_CASE : Optional[Any] = hidden_states + self.drop_path(A ) SCREAMING_SNAKE_CASE : Dict = (output,) + outputs return outputs else: SCREAMING_SNAKE_CASE : Any = self.drop_path(self.pooling(self.before_norm(A ) ) ) # First residual connection SCREAMING_SNAKE_CASE : List[str] = pooling_output + hidden_states SCREAMING_SNAKE_CASE : List[str] = () # Second residual connection inside the PoolFormerOutput block SCREAMING_SNAKE_CASE : Any = self.drop_path(self.output(self.after_norm(A ) ) ) SCREAMING_SNAKE_CASE : Tuple = hidden_states + layer_output SCREAMING_SNAKE_CASE : Dict = (output,) + outputs return outputs class _a ( nn.Module ): '''simple docstring''' def __init__( self, A ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE : Union[str, Any] = config # stochastic depth decay rule SCREAMING_SNAKE_CASE : Union[str, Any] = [x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths ) )] # patch embeddings SCREAMING_SNAKE_CASE : Any = [] for i in range(config.num_encoder_blocks ): embeddings.append( PoolFormerEmbeddings( patch_size=config.patch_sizes[i], stride=config.strides[i], padding=config.padding[i], num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1], hidden_size=config.hidden_sizes[i], ) ) SCREAMING_SNAKE_CASE : int = nn.ModuleList(A ) # Transformer blocks SCREAMING_SNAKE_CASE : Dict = [] SCREAMING_SNAKE_CASE : str = 0 for i in range(config.num_encoder_blocks ): # each block consists of layers SCREAMING_SNAKE_CASE : int = [] if i != 0: cur += config.depths[i - 1] for j in range(config.depths[i] ): layers.append( PoolFormerLayer( A, num_channels=config.hidden_sizes[i], pool_size=config.pool_size, hidden_size=config.hidden_sizes[i], intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio ), drop_path=dpr[cur + j], ) ) blocks.append(nn.ModuleList(A ) ) SCREAMING_SNAKE_CASE : str = nn.ModuleList(A ) def UpperCamelCase_ ( self, A, A=False, A=True ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = () if output_hidden_states else None SCREAMING_SNAKE_CASE : Tuple = pixel_values for idx, layers in enumerate(zip(self.patch_embeddings, self.block ) ): SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Tuple = layers # Get patch embeddings from hidden_states SCREAMING_SNAKE_CASE : int = embedding_layer(A ) # Send the embeddings through the blocks for _, blk in enumerate(A ): SCREAMING_SNAKE_CASE : Any = blk(A ) SCREAMING_SNAKE_CASE : Any = layer_outputs[0] if output_hidden_states: SCREAMING_SNAKE_CASE : Union[str, Any] = all_hidden_states + (hidden_states,) if not return_dict: return tuple(v for v in [hidden_states, all_hidden_states] if v is not None ) return BaseModelOutputWithNoAttention(last_hidden_state=A, hidden_states=A ) class _a ( SCREAMING_SNAKE_CASE ): '''simple docstring''' A : int = PoolFormerConfig A : Tuple = '''poolformer''' A : int = '''pixel_values''' A : Optional[Any] = True def UpperCamelCase_ ( self, A ): '''simple docstring''' if isinstance(A, (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(A, nn.LayerNorm ): module.bias.data.zero_() module.weight.data.fill_(1.0 ) def UpperCamelCase_ ( self, A, A=False ): '''simple docstring''' if isinstance(A, A ): SCREAMING_SNAKE_CASE : Union[str, Any] = value UpperCamelCase_ = R"\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n" UpperCamelCase_ = R"\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`PoolFormerImageProcessor.__call__`] for details.\n" @add_start_docstrings( '''The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.''' , SCREAMING_SNAKE_CASE , ) class _a ( SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self, A ): '''simple docstring''' super().__init__(A ) SCREAMING_SNAKE_CASE : int = config SCREAMING_SNAKE_CASE : Any = PoolFormerEncoder(A ) # Initialize weights and apply final processing self.post_init() def UpperCamelCase_ ( self ): '''simple docstring''' return self.embeddings.patch_embeddings @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC, output_type=A, config_class=_CONFIG_FOR_DOC, modality='vision', expected_output=_EXPECTED_OUTPUT_SHAPE, ) def UpperCamelCase_ ( self, A = None, A = None, A = None, ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) SCREAMING_SNAKE_CASE : List[str] = 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' ) SCREAMING_SNAKE_CASE : str = self.encoder( A, output_hidden_states=A, return_dict=A, ) SCREAMING_SNAKE_CASE : List[Any] = encoder_outputs[0] if not return_dict: return (sequence_output, None) + encoder_outputs[1:] return BaseModelOutputWithNoAttention( last_hidden_state=A, hidden_states=encoder_outputs.hidden_states, ) class _a ( nn.Module ): '''simple docstring''' def __init__( self, A ): '''simple docstring''' super().__init__() SCREAMING_SNAKE_CASE : Dict = nn.Linear(config.hidden_size, config.hidden_size ) def UpperCamelCase_ ( self, A ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.dense(A ) return output @add_start_docstrings( ''' PoolFormer Model transformer with an image classification head on top ''' , SCREAMING_SNAKE_CASE , ) class _a ( SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self, A ): '''simple docstring''' super().__init__(A ) SCREAMING_SNAKE_CASE : Any = config.num_labels SCREAMING_SNAKE_CASE : str = PoolFormerModel(A ) # Final norm SCREAMING_SNAKE_CASE : Any = PoolFormerGroupNorm(config.hidden_sizes[-1] ) # Classifier head SCREAMING_SNAKE_CASE : str = ( nn.Linear(config.hidden_sizes[-1], config.num_labels ) if config.num_labels > 0 else nn.Identity() ) # Initialize weights and apply final processing self.post_init() @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT, output_type=A, config_class=_CONFIG_FOR_DOC, expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT, ) def UpperCamelCase_ ( self, A = None, A = None, A = None, A = None, ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = return_dict if return_dict is not None else self.config.use_return_dict SCREAMING_SNAKE_CASE : Any = self.poolformer( A, output_hidden_states=A, return_dict=A, ) SCREAMING_SNAKE_CASE : Tuple = outputs[0] SCREAMING_SNAKE_CASE : List[str] = self.classifier(self.norm(A ).mean([-2, -1] ) ) SCREAMING_SNAKE_CASE : Dict = None if labels is not None: if self.config.problem_type is None: if self.num_labels == 1: SCREAMING_SNAKE_CASE : str = 'regression' elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): SCREAMING_SNAKE_CASE : int = 'single_label_classification' else: SCREAMING_SNAKE_CASE : List[str] = 'multi_label_classification' if self.config.problem_type == "regression": SCREAMING_SNAKE_CASE : Union[str, Any] = MSELoss() if self.num_labels == 1: SCREAMING_SNAKE_CASE : Union[str, Any] = loss_fct(logits.squeeze(), labels.squeeze() ) else: SCREAMING_SNAKE_CASE : Union[str, Any] = loss_fct(A, A ) elif self.config.problem_type == "single_label_classification": SCREAMING_SNAKE_CASE : Dict = CrossEntropyLoss() SCREAMING_SNAKE_CASE : int = loss_fct(logits.view(-1, self.num_labels ), labels.view(-1 ) ) elif self.config.problem_type == "multi_label_classification": SCREAMING_SNAKE_CASE : Tuple = BCEWithLogitsLoss() SCREAMING_SNAKE_CASE : List[str] = loss_fct(A, A ) if not return_dict: SCREAMING_SNAKE_CASE : int = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return ImageClassifierOutputWithNoAttention(loss=A, logits=A, hidden_states=outputs.hidden_states )
246
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = {"openai-gpt": "https://huggingface.co/openai-gpt/resolve/main/config.json"} class _a ( SCREAMING_SNAKE_CASE ): '''simple docstring''' A : int = '''openai-gpt''' A : Dict = { '''max_position_embeddings''': '''n_positions''', '''hidden_size''': '''n_embd''', '''num_attention_heads''': '''n_head''', '''num_hidden_layers''': '''n_layer''', } def __init__( self, A=40_478, A=512, A=768, A=12, A=12, A="gelu", A=0.1, A=0.1, A=0.1, A=1E-5, A=0.02, A="cls_index", A=True, A=None, A=True, A=0.1, **A, ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = vocab_size SCREAMING_SNAKE_CASE : Union[str, Any] = n_positions SCREAMING_SNAKE_CASE : Tuple = n_embd SCREAMING_SNAKE_CASE : Any = n_layer SCREAMING_SNAKE_CASE : Tuple = n_head SCREAMING_SNAKE_CASE : Union[str, Any] = afn SCREAMING_SNAKE_CASE : List[str] = resid_pdrop SCREAMING_SNAKE_CASE : List[str] = embd_pdrop SCREAMING_SNAKE_CASE : Tuple = attn_pdrop SCREAMING_SNAKE_CASE : List[str] = layer_norm_epsilon SCREAMING_SNAKE_CASE : Any = initializer_range SCREAMING_SNAKE_CASE : List[Any] = summary_type SCREAMING_SNAKE_CASE : int = summary_use_proj SCREAMING_SNAKE_CASE : Union[str, Any] = summary_activation SCREAMING_SNAKE_CASE : List[str] = summary_first_dropout SCREAMING_SNAKE_CASE : Any = summary_proj_to_labels super().__init__(**A )
246
1
"""simple docstring""" from typing import Any, Dict, Optional import torch import torch.nn.functional as F from torch import nn from ..utils import maybe_allow_in_graph from .activations import get_activation from .attention_processor import Attention from .embeddings import CombinedTimestepLabelEmbeddings @maybe_allow_in_graph class lowerCAmelCase_ (nn.Module ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = "geglu" , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = False , SCREAMING_SNAKE_CASE__ = True , SCREAMING_SNAKE_CASE__ = "layer_norm" , SCREAMING_SNAKE_CASE__ = False , ) -> Optional[Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : List[Any] = only_cross_attention SCREAMING_SNAKE_CASE__ : List[Any] = (num_embeds_ada_norm is not None) and norm_type == """ada_norm_zero""" SCREAMING_SNAKE_CASE__ : Optional[Any] = (num_embeds_ada_norm is not None) and norm_type == """ada_norm""" if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None: raise ValueError( F'''`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to''' F''' define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.''' ) # Define 3 blocks. Each block has its own normalization layer. # 1. Self-Attn if self.use_ada_layer_norm: SCREAMING_SNAKE_CASE__ : int = AdaLayerNorm(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif self.use_ada_layer_norm_zero: SCREAMING_SNAKE_CASE__ : Tuple = AdaLayerNormZero(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else: SCREAMING_SNAKE_CASE__ : Optional[int] = nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Dict = Attention( query_dim=SCREAMING_SNAKE_CASE__ , heads=SCREAMING_SNAKE_CASE__ , dim_head=SCREAMING_SNAKE_CASE__ , dropout=SCREAMING_SNAKE_CASE__ , bias=SCREAMING_SNAKE_CASE__ , cross_attention_dim=cross_attention_dim if only_cross_attention else None , upcast_attention=SCREAMING_SNAKE_CASE__ , ) # 2. Cross-Attn if cross_attention_dim is not None or double_self_attention: # We currently only use AdaLayerNormZero for self attention where there will only be one attention block. # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during # the second cross attention block. SCREAMING_SNAKE_CASE__ : Any = ( AdaLayerNorm(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if self.use_ada_layer_norm else nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ ) ) SCREAMING_SNAKE_CASE__ : Tuple = Attention( query_dim=SCREAMING_SNAKE_CASE__ , cross_attention_dim=cross_attention_dim if not double_self_attention else None , heads=SCREAMING_SNAKE_CASE__ , dim_head=SCREAMING_SNAKE_CASE__ , dropout=SCREAMING_SNAKE_CASE__ , bias=SCREAMING_SNAKE_CASE__ , upcast_attention=SCREAMING_SNAKE_CASE__ , ) # is self-attn if encoder_hidden_states is none else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = None SCREAMING_SNAKE_CASE__ : str = None # 3. Feed-forward SCREAMING_SNAKE_CASE__ : Optional[Any] = nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[int] = FeedForward(SCREAMING_SNAKE_CASE__ , dropout=SCREAMING_SNAKE_CASE__ , activation_fn=SCREAMING_SNAKE_CASE__ , final_dropout=SCREAMING_SNAKE_CASE__ ) # let chunk size default to None SCREAMING_SNAKE_CASE__ : Tuple = None SCREAMING_SNAKE_CASE__ : Dict = 0 def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> List[Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : Union[str, Any] = chunk_size SCREAMING_SNAKE_CASE__ : str = dim def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = None , ) -> Any: """simple docstring""" if self.use_ada_layer_norm: SCREAMING_SNAKE_CASE__ : Any = self.norma(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif self.use_ada_layer_norm_zero: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = self.norma( SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , hidden_dtype=hidden_states.dtype ) else: SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.norma(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : int = cross_attention_kwargs if cross_attention_kwargs is not None else {} SCREAMING_SNAKE_CASE__ : List[Any] = self.attna( SCREAMING_SNAKE_CASE__ , encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None , attention_mask=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) if self.use_ada_layer_norm_zero: SCREAMING_SNAKE_CASE__ : List[str] = gate_msa.unsqueeze(1 ) * attn_output SCREAMING_SNAKE_CASE__ : Dict = attn_output + hidden_states # 2. Cross-Attention if self.attna is not None: SCREAMING_SNAKE_CASE__ : str = ( self.norma(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if self.use_ada_layer_norm else self.norma(SCREAMING_SNAKE_CASE__ ) ) SCREAMING_SNAKE_CASE__ : List[str] = self.attna( SCREAMING_SNAKE_CASE__ , encoder_hidden_states=SCREAMING_SNAKE_CASE__ , attention_mask=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = attn_output + hidden_states # 3. Feed-forward SCREAMING_SNAKE_CASE__ : Any = self.norma(SCREAMING_SNAKE_CASE__ ) if self.use_ada_layer_norm_zero: SCREAMING_SNAKE_CASE__ : Optional[int] = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None] if self._chunk_size is not None: # "feed_forward_chunk_size" can be used to save memory if norm_hidden_states.shape[self._chunk_dim] % self._chunk_size != 0: raise ValueError( F'''`hidden_states` dimension to be chunked: {norm_hidden_states.shape[self._chunk_dim]} has to be divisible by chunk size: {self._chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`.''' ) SCREAMING_SNAKE_CASE__ : List[str] = norm_hidden_states.shape[self._chunk_dim] // self._chunk_size SCREAMING_SNAKE_CASE__ : int = torch.cat( [self.ff(SCREAMING_SNAKE_CASE__ ) for hid_slice in norm_hidden_states.chunk(SCREAMING_SNAKE_CASE__ , dim=self._chunk_dim )] , dim=self._chunk_dim , ) else: SCREAMING_SNAKE_CASE__ : int = self.ff(SCREAMING_SNAKE_CASE__ ) if self.use_ada_layer_norm_zero: SCREAMING_SNAKE_CASE__ : Tuple = gate_mlp.unsqueeze(1 ) * ff_output SCREAMING_SNAKE_CASE__ : Optional[Any] = ff_output + hidden_states return hidden_states class lowerCAmelCase_ (nn.Module ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = 4 , SCREAMING_SNAKE_CASE__ = 0.0 , SCREAMING_SNAKE_CASE__ = "geglu" , SCREAMING_SNAKE_CASE__ = False , ) -> Tuple: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Optional[int] = int(dim * mult ) SCREAMING_SNAKE_CASE__ : Tuple = dim_out if dim_out is not None else dim if activation_fn == "gelu": SCREAMING_SNAKE_CASE__ : str = GELU(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if activation_fn == "gelu-approximate": SCREAMING_SNAKE_CASE__ : List[str] = GELU(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , approximate="""tanh""" ) elif activation_fn == "geglu": SCREAMING_SNAKE_CASE__ : Optional[Any] = GEGLU(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) elif activation_fn == "geglu-approximate": SCREAMING_SNAKE_CASE__ : int = ApproximateGELU(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Any = nn.ModuleList([] ) # project in self.net.append(SCREAMING_SNAKE_CASE__ ) # project dropout self.net.append(nn.Dropout(SCREAMING_SNAKE_CASE__ ) ) # project out self.net.append(nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) ) # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout if final_dropout: self.net.append(nn.Dropout(SCREAMING_SNAKE_CASE__ ) ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> Union[str, Any]: """simple docstring""" for module in self.net: SCREAMING_SNAKE_CASE__ : Dict = module(SCREAMING_SNAKE_CASE__ ) return hidden_states class lowerCAmelCase_ (nn.Module ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = "none" ) -> List[Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Optional[int] = nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Any = approximate def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> Optional[int]: """simple docstring""" if gate.device.type != "mps": return F.gelu(SCREAMING_SNAKE_CASE__ , approximate=self.approximate ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) , approximate=self.approximate ).to(dtype=gate.dtype ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> str: """simple docstring""" SCREAMING_SNAKE_CASE__ : str = self.proj(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : List[Any] = self.gelu(SCREAMING_SNAKE_CASE__ ) return hidden_states class lowerCAmelCase_ (nn.Module ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Dict: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Dict = nn.Linear(SCREAMING_SNAKE_CASE__ , dim_out * 2 ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> int: """simple docstring""" if gate.device.type != "mps": return F.gelu(SCREAMING_SNAKE_CASE__ ) # mps: gelu is not implemented for float16 return F.gelu(gate.to(dtype=torch.floataa ) ).to(dtype=gate.dtype ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Union[str, Any] = self.proj(SCREAMING_SNAKE_CASE__ ).chunk(2 , dim=-1 ) return hidden_states * self.gelu(SCREAMING_SNAKE_CASE__ ) class lowerCAmelCase_ (nn.Module ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> List[Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : str = nn.Linear(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ ) -> Tuple: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.proj(SCREAMING_SNAKE_CASE__ ) return x * torch.sigmoid(1.702 * x ) class lowerCAmelCase_ (nn.Module ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Optional[Any]: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : List[Any] = nn.Embedding(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Dict = nn.SiLU() SCREAMING_SNAKE_CASE__ : Union[str, Any] = nn.Linear(SCREAMING_SNAKE_CASE__ , embedding_dim * 2 ) SCREAMING_SNAKE_CASE__ : List[str] = nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> List[str]: """simple docstring""" SCREAMING_SNAKE_CASE__ : List[str] = self.linear(self.silu(self.emb(SCREAMING_SNAKE_CASE__ ) ) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = torch.chunk(SCREAMING_SNAKE_CASE__ , 2 ) SCREAMING_SNAKE_CASE__ : Dict = self.norm(SCREAMING_SNAKE_CASE__ ) * (1 + scale) + shift return x class lowerCAmelCase_ (nn.Module ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> int: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : Any = CombinedTimestepLabelEmbeddings(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Optional[Any] = nn.SiLU() SCREAMING_SNAKE_CASE__ : List[Any] = nn.Linear(SCREAMING_SNAKE_CASE__ , 6 * embedding_dim , bias=SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : List[Any] = nn.LayerNorm(SCREAMING_SNAKE_CASE__ , elementwise_affine=SCREAMING_SNAKE_CASE__ , eps=1E-6 ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=None ) -> Union[str, Any]: """simple docstring""" SCREAMING_SNAKE_CASE__ : int = self.linear(self.silu(self.emb(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , hidden_dtype=SCREAMING_SNAKE_CASE__ ) ) ) SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : int = emb.chunk(6 , dim=1 ) SCREAMING_SNAKE_CASE__ : Tuple = self.norm(SCREAMING_SNAKE_CASE__ ) * (1 + scale_msa[:, None]) + shift_msa[:, None] return x, gate_msa, shift_mlp, scale_mlp, gate_mlp class lowerCAmelCase_ (nn.Module ): """simple docstring""" def __init__(self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = 1E-5 ) -> int: """simple docstring""" super().__init__() SCREAMING_SNAKE_CASE__ : List[Any] = num_groups SCREAMING_SNAKE_CASE__ : Any = eps if act_fn is None: SCREAMING_SNAKE_CASE__ : Any = None else: SCREAMING_SNAKE_CASE__ : Dict = get_activation(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : List[Any] = nn.Linear(SCREAMING_SNAKE_CASE__ , out_dim * 2 ) def __magic_name__ (self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Any: """simple docstring""" if self.act: SCREAMING_SNAKE_CASE__ : Tuple = self.act(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Dict = self.linear(SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : Dict = emb[:, :, None, None] SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : List[Any] = emb.chunk(2 , dim=1 ) SCREAMING_SNAKE_CASE__ : Dict = F.group_norm(SCREAMING_SNAKE_CASE__ , self.num_groups , eps=self.eps ) SCREAMING_SNAKE_CASE__ : Union[str, Any] = x * (1 + scale) + shift return x
25
"""simple docstring""" import copy import tempfile import unittest from huggingface_hub import HfFolder, delete_repo from parameterized import parameterized from requests.exceptions import HTTPError from transformers import AutoConfig, GenerationConfig from transformers.testing_utils import TOKEN, USER, is_staging_test class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @parameterized.expand([(None,), ('''foo.json''',)]) def _SCREAMING_SNAKE_CASE ( self : Dict , lowercase_ : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : List[str] = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowercase_ , config_name=lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig.from_pretrained(lowercase_ , config_name=lowercase_) # Checks parameters that were specified self.assertEqual(loaded_config.do_sample , lowercase_) self.assertEqual(loaded_config.temperature , 0.7) self.assertEqual(loaded_config.length_penalty , 1.0) self.assertEqual(loaded_config.bad_words_ids , [[1, 2, 3], [4, 5]]) # Checks parameters that were not specified (defaults) self.assertEqual(loaded_config.top_k , 50) self.assertEqual(loaded_config.max_length , 20) self.assertEqual(loaded_config.max_time , lowercase_) def _SCREAMING_SNAKE_CASE ( self : Optional[Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = AutoConfig.from_pretrained('''gpt2''') SCREAMING_SNAKE_CASE_ : int = GenerationConfig.from_model_config(lowercase_) SCREAMING_SNAKE_CASE_ : int = GenerationConfig() # The generation config has loaded a few non-default parameters from the model config self.assertNotEqual(lowercase_ , lowercase_) # One of those parameters is eos_token_id -- check if it matches self.assertNotEqual(generation_config_from_model.eos_token_id , default_generation_config.eos_token_id) self.assertEqual(generation_config_from_model.eos_token_id , model_config.eos_token_id) def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = GenerationConfig() SCREAMING_SNAKE_CASE_ : Any = { '''max_new_tokens''': 1024, '''foo''': '''bar''', } SCREAMING_SNAKE_CASE_ : str = copy.deepcopy(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = generation_config.update(**lowercase_) # update_kwargs was not modified (no side effects) self.assertEqual(lowercase_ , lowercase_) # update_kwargs was used to update the config on valid attributes self.assertEqual(generation_config.max_new_tokens , 1024) # `.update()` returns a dictionary of unused kwargs self.assertEqual(lowercase_ , {'''foo''': '''bar'''}) def _SCREAMING_SNAKE_CASE ( self : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Optional[Any] = GenerationConfig() SCREAMING_SNAKE_CASE_ : List[str] = '''bar''' with tempfile.TemporaryDirectory('''test-generation-config''') as tmp_dir: generation_config.save_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : List[Any] = GenerationConfig.from_pretrained(lowercase_) # update_kwargs was used to update the config on valid attributes self.assertEqual(new_config.foo , '''bar''') SCREAMING_SNAKE_CASE_ : Optional[Any] = GenerationConfig.from_model_config(lowercase_) assert not hasattr(lowercase_ , '''foo''') # no new kwargs should be initialized if from config def _SCREAMING_SNAKE_CASE ( self : Tuple): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig() self.assertEqual(default_config.temperature , 1.0) self.assertEqual(default_config.do_sample , lowercase_) self.assertEqual(default_config.num_beams , 1) SCREAMING_SNAKE_CASE_ : Dict = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , bad_words_ids=[[1, 2, 3], [4, 5]] , ) self.assertEqual(config.temperature , 0.7) self.assertEqual(config.do_sample , lowercase_) self.assertEqual(config.num_beams , 1) with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(lowercase_) SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig.from_pretrained(lowercase_ , temperature=1.0) self.assertEqual(loaded_config.temperature , 1.0) self.assertEqual(loaded_config.do_sample , lowercase_) self.assertEqual(loaded_config.num_beams , 1) # default value @is_staging_test class lowerCAmelCase__ ( unittest.TestCase ): '''simple docstring''' @classmethod def _SCREAMING_SNAKE_CASE ( cls : Any): '''simple docstring''' SCREAMING_SNAKE_CASE_ : str = TOKEN HfFolder.save_token(lowercase_) @classmethod def _SCREAMING_SNAKE_CASE ( cls : List[str]): '''simple docstring''' try: delete_repo(token=cls._token , repo_id='''test-generation-config''') except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-generation-config-org''') except HTTPError: pass def _SCREAMING_SNAKE_CASE ( self : Dict): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Tuple = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''test-generation-config''' , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : int = GenerationConfig.from_pretrained(F'{USER}/test-generation-config') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) # Reset repo delete_repo(token=self._token , repo_id='''test-generation-config''') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowercase_ , repo_id='''test-generation-config''' , push_to_hub=lowercase_ , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Optional[int] = GenerationConfig.from_pretrained(F'{USER}/test-generation-config') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) def _SCREAMING_SNAKE_CASE ( self : Union[str, Any]): '''simple docstring''' SCREAMING_SNAKE_CASE_ : Dict = GenerationConfig( do_sample=lowercase_ , temperature=0.7 , length_penalty=1.0 , ) config.push_to_hub('''valid_org/test-generation-config-org''' , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Any = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_)) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-generation-config-org''') # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( lowercase_ , repo_id='''valid_org/test-generation-config-org''' , push_to_hub=lowercase_ , use_auth_token=self._token) SCREAMING_SNAKE_CASE_ : Any = GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''') for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(lowercase_ , getattr(lowercase_ , lowercase_))
91
0
def UpperCamelCase ( __magic_name__ : list ) -> list: """simple docstring""" if len(__magic_name__ ) <= 1: return lst lowercase__ = 1 while i < len(__magic_name__ ): if lst[i - 1] <= lst[i]: i += 1 else: lowercase__ , lowercase__ = lst[i], lst[i - 1] i -= 1 if i == 0: lowercase__ = 1 return lst if __name__ == "__main__": A : Union[str, Any] = input('Enter numbers separated by a comma:\n').strip() A : Optional[int] = [int(item) for item in user_input.split(',')] print(gnome_sort(unsorted))
146
import gc import unittest from parameterized import parameterized from diffusers import FlaxUNetaDConditionModel from diffusers.utils import is_flax_available from diffusers.utils.testing_utils import load_hf_numpy, require_flax, slow if is_flax_available(): import jax import jax.numpy as jnp @slow @require_flax class A ( unittest.TestCase ): '''simple docstring''' def lowerCamelCase__ (self : Any , _UpperCAmelCase : List[str] , _UpperCAmelCase : Union[str, Any] ) -> int: """simple docstring""" return f'''gaussian_noise_s={seed}_shape={"_".join([str(_UpperCAmelCase ) for s in shape] )}.npy''' def lowerCamelCase__ (self : Any ) -> int: """simple docstring""" super().tearDown() gc.collect() def lowerCamelCase__ (self : List[Any] , _UpperCAmelCase : Any=0 , _UpperCAmelCase : Optional[Any]=(4, 4, 64, 64) , _UpperCAmelCase : Any=False ) -> List[Any]: """simple docstring""" lowercase__ = jnp.bfloataa if fpaa else jnp.floataa lowercase__ = jnp.array(load_hf_numpy(self.get_file_format(_UpperCAmelCase , _UpperCAmelCase ) ) , dtype=_UpperCAmelCase ) return image def lowerCamelCase__ (self : Optional[Any] , _UpperCAmelCase : str=False , _UpperCAmelCase : str="CompVis/stable-diffusion-v1-4" ) -> Dict: """simple docstring""" lowercase__ = jnp.bfloataa if fpaa else jnp.floataa lowercase__ = """bf16""" if fpaa else None lowercase__ , lowercase__ = FlaxUNetaDConditionModel.from_pretrained( _UpperCAmelCase , subfolder="""unet""" , dtype=_UpperCAmelCase , revision=_UpperCAmelCase ) return model, params def lowerCamelCase__ (self : List[Any] , _UpperCAmelCase : int=0 , _UpperCAmelCase : Optional[int]=(4, 77, 768) , _UpperCAmelCase : Any=False ) -> Optional[Any]: """simple docstring""" lowercase__ = jnp.bfloataa if fpaa else jnp.floataa lowercase__ = jnp.array(load_hf_numpy(self.get_file_format(_UpperCAmelCase , _UpperCAmelCase ) ) , dtype=_UpperCAmelCase ) return hidden_states @parameterized.expand( [ # fmt: off [83, 4, [-0.2_323, -0.1_304, 0.0_813, -0.3_093, -0.0_919, -0.1_571, -0.1_125, -0.5_806]], [17, 0.55, [-0.0_831, -0.2_443, 0.0_901, -0.0_919, 0.3_396, 0.0_103, -0.3_743, 0.0_701]], [8, 0.89, [-0.4_863, 0.0_859, 0.0_875, -0.1_658, 0.9_199, -0.0_114, 0.4_839, 0.4_639]], [3, 1000, [-0.5_649, 0.2_402, -0.5_518, 0.1_248, 1.1_328, -0.2_443, -0.0_325, -1.0_078]], # fmt: on ] ) def lowerCamelCase__ (self : int , _UpperCAmelCase : str , _UpperCAmelCase : Union[str, Any] , _UpperCAmelCase : int ) -> str: """simple docstring""" lowercase__ , lowercase__ = self.get_unet_model(model_id="""CompVis/stable-diffusion-v1-4""" , fpaa=_UpperCAmelCase ) lowercase__ = self.get_latents(_UpperCAmelCase , fpaa=_UpperCAmelCase ) lowercase__ = self.get_encoder_hidden_states(_UpperCAmelCase , fpaa=_UpperCAmelCase ) lowercase__ = model.apply( {"""params""": params} , _UpperCAmelCase , jnp.array(_UpperCAmelCase , dtype=jnp.intaa ) , encoder_hidden_states=_UpperCAmelCase , ).sample assert sample.shape == latents.shape lowercase__ = jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten()) ) , dtype=jnp.floataa ) lowercase__ = jnp.array(_UpperCAmelCase , dtype=jnp.floataa ) # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, in the same hardware assert jnp.allclose(_UpperCAmelCase , _UpperCAmelCase , atol=1E-2 ) @parameterized.expand( [ # fmt: off [83, 4, [0.1_514, 0.0_807, 0.1_624, 0.1_016, -0.1_896, 0.0_263, 0.0_677, 0.2_310]], [17, 0.55, [0.1_164, -0.0_216, 0.0_170, 0.1_589, -0.3_120, 0.1_005, -0.0_581, -0.1_458]], [8, 0.89, [-0.1_758, -0.0_169, 0.1_004, -0.1_411, 0.1_312, 0.1_103, -0.1_996, 0.2_139]], [3, 1000, [0.1_214, 0.0_352, -0.0_731, -0.1_562, -0.0_994, -0.0_906, -0.2_340, -0.0_539]], # fmt: on ] ) def lowerCamelCase__ (self : Optional[Any] , _UpperCAmelCase : Tuple , _UpperCAmelCase : int , _UpperCAmelCase : List[str] ) -> str: """simple docstring""" lowercase__ , lowercase__ = self.get_unet_model(model_id="""stabilityai/stable-diffusion-2""" , fpaa=_UpperCAmelCase ) lowercase__ = self.get_latents(_UpperCAmelCase , shape=(4, 4, 96, 96) , fpaa=_UpperCAmelCase ) lowercase__ = self.get_encoder_hidden_states(_UpperCAmelCase , shape=(4, 77, 1024) , fpaa=_UpperCAmelCase ) lowercase__ = model.apply( {"""params""": params} , _UpperCAmelCase , jnp.array(_UpperCAmelCase , dtype=jnp.intaa ) , encoder_hidden_states=_UpperCAmelCase , ).sample assert sample.shape == latents.shape lowercase__ = jnp.asarray(jax.device_get((sample[-1, -2:, -2:, :2].flatten()) ) , dtype=jnp.floataa ) lowercase__ = jnp.array(_UpperCAmelCase , dtype=jnp.floataa ) # Found torch (float16) and flax (bfloat16) outputs to be within this tolerance, on the same hardware assert jnp.allclose(_UpperCAmelCase , _UpperCAmelCase , atol=1E-2 )
146
1
'''simple docstring''' # Lint as: python3 import itertools import os import re lowerCamelCase : Any = re.compile(R'([A-Z]+)([A-Z][a-z])') lowerCamelCase : str = re.compile(R'([a-z\d])([A-Z])') lowerCamelCase : Optional[int] = re.compile(R'(?<!_)_(?!_)') lowerCamelCase : List[Any] = re.compile(R'(_{2,})') lowerCamelCase : str = R'^\w+(\.\w+)*$' lowerCamelCase : Dict = R'<>:/\|?*' def _SCREAMING_SNAKE_CASE (A ) -> Any: """simple docstring""" lowercase__ = _uppercase_uppercase_re.sub(R'''\1_\2''' , A ) lowercase__ = _lowercase_uppercase_re.sub(R'''\1_\2''' , A ) return name.lower() def _SCREAMING_SNAKE_CASE (A ) -> Tuple: """simple docstring""" lowercase__ = _single_underscore_re.split(A ) lowercase__ = [_multiple_underscores_re.split(A ) for n in name] return "".join(n.capitalize() for n in itertools.chain.from_iterable(A ) if n != '''''' ) def _SCREAMING_SNAKE_CASE (A ) -> Tuple: """simple docstring""" if os.path.basename(A ) != name: raise ValueError(f"Should be a dataset name, not a path: {name}" ) return camelcase_to_snakecase(A ) def _SCREAMING_SNAKE_CASE (A , A ) -> Optional[Any]: """simple docstring""" if os.path.basename(A ) != name: raise ValueError(f"Should be a dataset name, not a path: {name}" ) if not re.match(_split_re , A ): raise ValueError(f"Split name should match '{_split_re}'' but got '{split}'." ) return f"{filename_prefix_for_name(A )}-{split}" def _SCREAMING_SNAKE_CASE (A , A , A , A=None ) -> List[str]: """simple docstring""" lowercase__ = filename_prefix_for_split(A , A ) if filetype_suffix: prefix += f".{filetype_suffix}" lowercase__ = os.path.join(A , A ) return f"{filepath}*" def _SCREAMING_SNAKE_CASE (A , A , A , A=None , A=None ) -> Optional[Any]: """simple docstring""" lowercase__ = filename_prefix_for_split(A , A ) lowercase__ = os.path.join(A , A ) if shard_lengths: lowercase__ = len(A ) lowercase__ = [f"{prefix}-{shard_id:05d}-of-{num_shards:05d}" for shard_id in range(A )] if filetype_suffix: lowercase__ = [filename + f".{filetype_suffix}" for filename in filenames] return filenames else: lowercase__ = prefix if filetype_suffix: filename += f".{filetype_suffix}" return [filename]
2
'''simple docstring''' import unittest from transformers import DebertaVaTokenizer, DebertaVaTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin lowerCamelCase : List[str] = get_tests_dir('fixtures/spiece.model') @require_sentencepiece @require_tokenizers class __lowerCAmelCase (lowercase_ , unittest.TestCase ): '''simple docstring''' lowerCAmelCase__ : int = DebertaVaTokenizer lowerCAmelCase__ : List[Any] = DebertaVaTokenizerFast lowerCAmelCase__ : str = True lowerCAmelCase__ : Tuple = True def UpperCamelCase__ (self : Tuple ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing lowercase__ = DebertaVaTokenizer(UpperCamelCase , unk_token='''<unk>''' ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCamelCase__ (self : Union[str, Any] , UpperCamelCase : str ): '''simple docstring''' lowercase__ = '''this is a test''' lowercase__ = '''this is a test''' return input_text, output_text def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' lowercase__ = '''<pad>''' lowercase__ = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCamelCase ) , UpperCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCamelCase ) , UpperCamelCase ) def UpperCamelCase__ (self : Dict ): '''simple docstring''' lowercase__ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<pad>''' ) self.assertEqual(vocab_keys[1] , '''<unk>''' ) self.assertEqual(vocab_keys[-1] , '''[PAD]''' ) self.assertEqual(len(UpperCamelCase ) , 30001 ) def UpperCamelCase__ (self : int ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 30000 ) def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' lowercase__ = ''' \tHeLLo!how \n Are yoU? ''' lowercase__ = ['''▁hello''', '''!''', '''how''', '''▁are''', '''▁you''', '''?'''] # fmt: on lowercase__ = DebertaVaTokenizer(UpperCamelCase , do_lower_case=UpperCamelCase ) lowercase__ = tokenizer.convert_ids_to_tokens(tokenizer.encode(UpperCamelCase , add_special_tokens=UpperCamelCase ) ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) lowercase__ = DebertaVaTokenizerFast(UpperCamelCase , do_lower_case=UpperCamelCase ) lowercase__ = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(UpperCamelCase , add_special_tokens=UpperCamelCase ) ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) @unittest.skip('''There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.''' ) def UpperCamelCase__ (self : List[Any] ): '''simple docstring''' pass @unittest.skip('''There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.''' ) def UpperCamelCase__ (self : List[str] ): '''simple docstring''' pass def UpperCamelCase__ (self : Optional[int] ): '''simple docstring''' lowercase__ = '''I was born in 92000, and this is falsé.''' lowercase__ = ['''▁''', '''<unk>''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', '''▁''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''▁''', '''.''', ] # fmt: on lowercase__ = DebertaVaTokenizer(UpperCamelCase , split_by_punct=UpperCamelCase ) lowercase__ = tokenizer.convert_ids_to_tokens(tokenizer.encode(UpperCamelCase , add_special_tokens=UpperCamelCase ) ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) lowercase__ = DebertaVaTokenizerFast(UpperCamelCase , split_by_punct=UpperCamelCase ) lowercase__ = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(UpperCamelCase , add_special_tokens=UpperCamelCase ) ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) def UpperCamelCase__ (self : int ): '''simple docstring''' lowercase__ = '''I was born in 92000, and this is falsé.''' lowercase__ = ['''▁i''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', '''▁''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''▁''', '''.''', ] # fmt: on lowercase__ = DebertaVaTokenizer(UpperCamelCase , do_lower_case=UpperCamelCase , split_by_punct=UpperCamelCase ) lowercase__ = tokenizer.convert_ids_to_tokens(tokenizer.encode(UpperCamelCase , add_special_tokens=UpperCamelCase ) ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) lowercase__ = DebertaVaTokenizerFast(UpperCamelCase , do_lower_case=UpperCamelCase , split_by_punct=UpperCamelCase ) lowercase__ = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(UpperCamelCase , add_special_tokens=UpperCamelCase ) ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) def UpperCamelCase__ (self : Optional[Any] ): '''simple docstring''' lowercase__ = '''I was born in 92000, and this is falsé.''' lowercase__ = ['''▁i''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''.''', ] # fmt: on lowercase__ = DebertaVaTokenizer(UpperCamelCase , do_lower_case=UpperCamelCase , split_by_punct=UpperCamelCase ) lowercase__ = tokenizer.convert_ids_to_tokens(tokenizer.encode(UpperCamelCase , add_special_tokens=UpperCamelCase ) ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) lowercase__ = DebertaVaTokenizerFast(UpperCamelCase , do_lower_case=UpperCamelCase , split_by_punct=UpperCamelCase ) lowercase__ = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(UpperCamelCase , add_special_tokens=UpperCamelCase ) ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = '''I was born in 92000, and this is falsé.''' lowercase__ = ['''▁''', '''<unk>''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', '''▁''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''▁''', '''.''', ] # fmt: on lowercase__ = DebertaVaTokenizer(UpperCamelCase , do_lower_case=UpperCamelCase , split_by_punct=UpperCamelCase ) lowercase__ = tokenizer.convert_ids_to_tokens(tokenizer.encode(UpperCamelCase , add_special_tokens=UpperCamelCase ) ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) lowercase__ = DebertaVaTokenizerFast(UpperCamelCase , do_lower_case=UpperCamelCase , split_by_punct=UpperCamelCase ) lowercase__ = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(UpperCamelCase , add_special_tokens=UpperCamelCase ) ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = ''' \tHeLLo!how \n Are yoU? ''' lowercase__ = ['''▁''', '''<unk>''', '''e''', '''<unk>''', '''o''', '''!''', '''how''', '''▁''', '''<unk>''', '''re''', '''▁yo''', '''<unk>''', '''?'''] # fmt: on lowercase__ = DebertaVaTokenizer(UpperCamelCase , do_lower_case=UpperCamelCase , split_by_punct=UpperCamelCase ) lowercase__ = tokenizer.convert_ids_to_tokens(tokenizer.encode(UpperCamelCase , add_special_tokens=UpperCamelCase ) ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) lowercase__ = DebertaVaTokenizerFast(UpperCamelCase , do_lower_case=UpperCamelCase , split_by_punct=UpperCamelCase ) lowercase__ = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(UpperCamelCase , add_special_tokens=UpperCamelCase ) ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) def UpperCamelCase__ (self : Union[str, Any] ): '''simple docstring''' lowercase__ = self.get_tokenizer() lowercase__ = self.get_rust_tokenizer() lowercase__ = '''I was born in 92000, and this is falsé.''' lowercase__ = tokenizer.convert_ids_to_tokens(tokenizer.encode(UpperCamelCase , add_special_tokens=UpperCamelCase ) ) lowercase__ = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(UpperCamelCase , add_special_tokens=UpperCamelCase ) ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) lowercase__ = tokenizer.encode(UpperCamelCase , add_special_tokens=UpperCamelCase ) lowercase__ = rust_tokenizer.encode(UpperCamelCase , add_special_tokens=UpperCamelCase ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) lowercase__ = self.get_rust_tokenizer() lowercase__ = tokenizer.encode(UpperCamelCase ) lowercase__ = rust_tokenizer.encode(UpperCamelCase ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) def UpperCamelCase__ (self : int ): '''simple docstring''' lowercase__ = '''This is a test''' lowercase__ = [13, 1, 4398, 25, 21, 1289] lowercase__ = ['''▁''', '''T''', '''his''', '''▁is''', '''▁a''', '''▁test'''] lowercase__ = ['''▁''', '''<unk>''', '''his''', '''▁is''', '''▁a''', '''▁test'''] lowercase__ = DebertaVaTokenizer(UpperCamelCase , keep_accents=UpperCamelCase ) lowercase__ = DebertaVaTokenizerFast(UpperCamelCase , keep_accents=UpperCamelCase ) lowercase__ = tokenizer.encode(UpperCamelCase , add_special_tokens=UpperCamelCase ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) lowercase__ = tokenizer.tokenize(UpperCamelCase ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) lowercase__ = tokenizer.convert_ids_to_tokens(UpperCamelCase ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) lowercase__ = rust_tokenizer.encode(UpperCamelCase , add_special_tokens=UpperCamelCase ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) lowercase__ = rust_tokenizer.tokenize(UpperCamelCase ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) lowercase__ = rust_tokenizer.convert_ids_to_tokens(UpperCamelCase ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) # fmt: off lowercase__ = '''I was born in 92000, and this is falsé.''' lowercase__ = [13, 1, 23, 386, 19, 561, 3050, 15, 17, 48, 25, 8256, 18, 1, 9] lowercase__ = ['''▁''', '''I''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''é''', '''.''', ] lowercase__ = ['''▁''', '''<unk>''', '''▁was''', '''▁born''', '''▁in''', '''▁9''', '''2000''', ''',''', '''▁and''', '''▁this''', '''▁is''', '''▁fal''', '''s''', '''<unk>''', '''.''', ] # fmt: on lowercase__ = tokenizer.encode(UpperCamelCase , add_special_tokens=UpperCamelCase ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) lowercase__ = tokenizer.tokenize(UpperCamelCase ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) lowercase__ = tokenizer.convert_ids_to_tokens(UpperCamelCase ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) lowercase__ = rust_tokenizer.encode(UpperCamelCase , add_special_tokens=UpperCamelCase ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) lowercase__ = rust_tokenizer.tokenize(UpperCamelCase ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) lowercase__ = rust_tokenizer.convert_ids_to_tokens(UpperCamelCase ) self.assertListEqual(UpperCamelCase , UpperCamelCase ) def UpperCamelCase__ (self : int ): '''simple docstring''' lowercase__ = DebertaVaTokenizer(UpperCamelCase ) lowercase__ = tokenizer.encode('''sequence builders''' ) lowercase__ = tokenizer.encode('''multi-sequence build''' ) lowercase__ = tokenizer.build_inputs_with_special_tokens(UpperCamelCase ) lowercase__ = tokenizer.build_inputs_with_special_tokens(UpperCamelCase , UpperCamelCase ) self.assertEqual([tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] , UpperCamelCase ) self.assertEqual( [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [tokenizer.sep_token_id] , UpperCamelCase , ) @slow def UpperCamelCase__ (self : int ): '''simple docstring''' lowercase__ = {'''input_ids''': [[1, 39867, 36, 19390, 486, 27, 35052, 81436, 18, 60685, 1225, 7, 35052, 81436, 18, 9367, 16899, 18, 15937, 53, 594, 773, 18, 16287, 30465, 36, 15937, 6, 41139, 38, 36979, 60763, 191, 6, 34132, 99, 6, 50538, 390, 43230, 6, 34132, 2779, 20850, 14, 699, 1072, 1194, 36, 382, 10901, 53, 7, 699, 1072, 2084, 36, 20422, 630, 53, 19, 105, 3049, 1896, 1053, 16899, 1506, 11, 37978, 4243, 7, 1237, 31869, 200, 16566, 654, 6, 35052, 81436, 7, 55630, 13593, 4, 2], [1, 26, 15011, 13, 667, 8, 1053, 18, 23611, 1237, 72356, 12820, 34, 104134, 1209, 35, 13313, 6627, 21, 202, 347, 7, 164, 2399, 11, 46, 4485, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 5, 1232, 2864, 15785, 14951, 105, 5, 8581, 1250, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''token_type_ids''': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=UpperCamelCase , model_name='''microsoft/deberta-v2-xlarge''' , revision='''ad6e42c1532ddf3a15c39246b63f5559d558b670''' , )
2
1
'''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 = logging.get_logger(__name__) __snake_case = { '''sail/poolformer_s12''': '''https://huggingface.co/sail/poolformer_s12/resolve/main/config.json''', # See all PoolFormer models at https://huggingface.co/models?filter=poolformer } class lowercase ( A__ ): """simple docstring""" _a = 'poolformer' def __init__( self , UpperCamelCase_=3 , UpperCamelCase_=16 , UpperCamelCase_=16 , UpperCamelCase_=3 , UpperCamelCase_=4.0 , UpperCamelCase_=[2, 2, 6, 2] , UpperCamelCase_=[64, 128, 320, 512] , UpperCamelCase_=[7, 3, 3, 3] , UpperCamelCase_=[4, 2, 2, 2] , UpperCamelCase_=[2, 1, 1, 1] , UpperCamelCase_=4 , UpperCamelCase_=0.0 , UpperCamelCase_="gelu" , UpperCamelCase_=True , UpperCamelCase_=1e-5 , UpperCamelCase_=0.02 , **UpperCamelCase_ , ): '''simple docstring''' UpperCamelCase__ :str = num_channels UpperCamelCase__ :Any = patch_size UpperCamelCase__ :Optional[Any] = stride UpperCamelCase__ :Optional[int] = padding UpperCamelCase__ :List[Any] = pool_size UpperCamelCase__ :str = hidden_sizes UpperCamelCase__ :int = mlp_ratio UpperCamelCase__ :List[Any] = depths UpperCamelCase__ :Any = patch_sizes UpperCamelCase__ :Optional[Any] = strides UpperCamelCase__ :str = num_encoder_blocks UpperCamelCase__ :List[str] = drop_path_rate UpperCamelCase__ :Optional[int] = hidden_act UpperCamelCase__ :List[str] = use_layer_scale UpperCamelCase__ :Optional[int] = layer_scale_init_value UpperCamelCase__ :Union[str, Any] = initializer_range super().__init__(**UpperCamelCase_ ) class lowercase ( A__ ): """simple docstring""" _a = version.parse('1.11' ) @property def lowerCAmelCase__ ( self ): '''simple docstring''' return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ] ) @property def lowerCAmelCase__ ( self ): '''simple docstring''' return 2e-3
219
'''simple docstring''' import argparse import json import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType from accelerate.utils.deepspeed import DummyOptim, DummyScheduler __snake_case = 16 __snake_case = 32 def a ( __a , __a = 16 , __a = "bert-base-cased" ) -> Any: '''simple docstring''' UpperCamelCase__ :List[str] = AutoTokenizer.from_pretrained(__a ) UpperCamelCase__ :List[Any] = load_dataset('''glue''' , '''mrpc''' ) def tokenize_function(__a ): # max_length=None => use the model max length (it's actually the default) UpperCamelCase__ :Tuple = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=__a , max_length=__a ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset UpperCamelCase__ :Optional[int] = datasets.map( __a , batched=__a , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , load_from_cache_file=__a ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCamelCase__ :Optional[int] = tokenized_datasets.rename_column('''label''' , '''labels''' ) def collate_fn(__a ): # On TPU it's best to pad everything to the same length or training will be very slow. if accelerator.distributed_type == DistributedType.TPU: return tokenizer.pad(__a , padding='''max_length''' , max_length=128 , return_tensors='''pt''' ) return tokenizer.pad(__a , padding='''longest''' , return_tensors='''pt''' ) # Instantiate dataloaders. UpperCamelCase__ :Dict = DataLoader( tokenized_datasets['''train'''] , shuffle=__a , collate_fn=__a , batch_size=__a ) UpperCamelCase__ :str = DataLoader( tokenized_datasets['''validation'''] , shuffle=__a , collate_fn=__a , batch_size=__a ) return train_dataloader, eval_dataloader def a ( __a , __a , __a , __a ) -> str: '''simple docstring''' model.eval() UpperCamelCase__ :List[str] = 0 for step, batch in enumerate(__a ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCamelCase__ :int = model(**__a ) UpperCamelCase__ :Tuple = outputs.logits.argmax(dim=-1 ) # It is slightly faster to call this once, than multiple times UpperCamelCase__ , UpperCamelCase__ :int = accelerator.gather( (predictions, batch['''labels''']) ) # If we are in a multiprocess environment, the last batch has duplicates if accelerator.use_distributed: if step == len(__a ) - 1: UpperCamelCase__ :Union[str, Any] = predictions[: len(eval_dataloader.dataset ) - samples_seen] UpperCamelCase__ :List[str] = references[: len(eval_dataloader.dataset ) - samples_seen] else: samples_seen += references.shape[0] metric.add_batch( predictions=__a , references=__a , ) UpperCamelCase__ :Union[str, Any] = metric.compute() return eval_metric["accuracy"] def a ( __a , __a ) -> List[Any]: '''simple docstring''' UpperCamelCase__ :Any = Accelerator() # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCamelCase__ :Any = config['''lr'''] UpperCamelCase__ :Optional[int] = int(config['''num_epochs'''] ) UpperCamelCase__ :List[Any] = int(config['''seed'''] ) UpperCamelCase__ :List[Any] = int(config['''batch_size'''] ) UpperCamelCase__ :List[Any] = args.model_name_or_path set_seed(__a ) UpperCamelCase__ , UpperCamelCase__ :Any = get_dataloaders(__a , __a , __a ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCamelCase__ :Union[str, Any] = AutoModelForSequenceClassification.from_pretrained(__a , return_dict=__a ) # Instantiate optimizer UpperCamelCase__ :Any = ( AdamW if accelerator.state.deepspeed_plugin is None or '''optimizer''' not in accelerator.state.deepspeed_plugin.deepspeed_config else DummyOptim ) UpperCamelCase__ :Optional[Any] = optimizer_cls(params=model.parameters() , lr=__a ) if accelerator.state.deepspeed_plugin is not None: UpperCamelCase__ :Tuple = accelerator.state.deepspeed_plugin.deepspeed_config[ '''gradient_accumulation_steps''' ] else: UpperCamelCase__ :Dict = 1 UpperCamelCase__ :Tuple = (len(__a ) * num_epochs) // gradient_accumulation_steps # Instantiate scheduler if ( accelerator.state.deepspeed_plugin is None or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config ): UpperCamelCase__ :Any = get_linear_schedule_with_warmup( optimizer=__a , num_warmup_steps=0 , num_training_steps=__a , ) else: UpperCamelCase__ :Any = DummyScheduler(__a , total_num_steps=__a , warmup_num_steps=0 ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ :Dict = accelerator.prepare( __a , __a , __a , __a , __a ) # We need to keep track of how many total steps we have iterated over UpperCamelCase__ :Tuple = 0 # We also need to keep track of the stating epoch so files are named properly UpperCamelCase__ :Optional[Any] = 0 UpperCamelCase__ :Optional[int] = evaluate.load('''glue''' , '''mrpc''' ) UpperCamelCase__ :List[Any] = num_epochs if args.partial_train_epoch is not None: UpperCamelCase__ :Optional[Any] = args.partial_train_epoch if args.resume_from_checkpoint: accelerator.load_state(args.resume_from_checkpoint ) UpperCamelCase__ :Dict = args.resume_from_checkpoint.split('''epoch_''' )[1] UpperCamelCase__ :Tuple = '''''' for char in epoch_string: if char.isdigit(): state_epoch_num += char else: break UpperCamelCase__ :Any = int(__a ) + 1 UpperCamelCase__ :Dict = evaluation_loop(__a , __a , __a , __a ) accelerator.print('''resumed checkpoint performance:''' , __a ) accelerator.print('''resumed checkpoint\'s scheduler\'s lr:''' , lr_scheduler.get_lr()[0] ) accelerator.print('''resumed optimizers\'s lr:''' , optimizer.param_groups[0]['''lr'''] ) with open(os.path.join(args.output_dir , f'''state_{starting_epoch-1}.json''' ) , '''r''' ) as f: UpperCamelCase__ :Optional[int] = json.load(__a ) assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" assert ( resumed_state["lr"] == lr_scheduler.get_lr()[0] ), "Scheduler learning rate mismatch, loading from checkpoint failed" assert ( resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] ), "Optimizer learning rate mismatch, loading from checkpoint failed" assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" return # Now we train the model UpperCamelCase__ :Optional[Any] = {} for epoch in range(__a , __a ): model.train() for step, batch in enumerate(__a ): UpperCamelCase__ :Optional[int] = model(**__a ) UpperCamelCase__ :Optional[int] = outputs.loss UpperCamelCase__ :str = loss / gradient_accumulation_steps accelerator.backward(__a ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() overall_step += 1 UpperCamelCase__ :Union[str, Any] = f'''epoch_{epoch}''' UpperCamelCase__ :List[Any] = os.path.join(args.output_dir , __a ) accelerator.save_state(__a ) UpperCamelCase__ :List[Any] = evaluation_loop(__a , __a , __a , __a ) UpperCamelCase__ :int = accuracy UpperCamelCase__ :List[Any] = lr_scheduler.get_lr()[0] UpperCamelCase__ :Any = optimizer.param_groups[0]['''lr'''] UpperCamelCase__ :int = epoch UpperCamelCase__ :Tuple = overall_step accelerator.print(f'''epoch {epoch}:''' , __a ) accelerator.wait_for_everyone() if accelerator.is_main_process: with open(os.path.join(args.output_dir , f'''state_{epoch}.json''' ) , '''w''' ) as f: json.dump(__a , __a ) def a ( ) -> Tuple: '''simple docstring''' UpperCamelCase__ :List[Any] = argparse.ArgumentParser(description='''Simple example of training script tracking peak GPU memory usage.''' ) parser.add_argument( '''--model_name_or_path''' , type=__a , default='''bert-base-cased''' , help='''Path to pretrained model or model identifier from huggingface.co/models.''' , required=__a , ) parser.add_argument( '''--output_dir''' , type=__a , default='''.''' , help='''Optional save directory where all checkpoint folders will be stored. Default is the current working directory.''' , ) parser.add_argument( '''--resume_from_checkpoint''' , type=__a , default=__a , help='''If the training should continue from a checkpoint folder.''' , ) parser.add_argument( '''--partial_train_epoch''' , type=__a , default=__a , help='''If passed, the training will stop after this number of epochs.''' , ) parser.add_argument( '''--num_epochs''' , type=__a , default=2 , help='''Number of train epochs.''' , ) UpperCamelCase__ :Optional[int] = parser.parse_args() UpperCamelCase__ :List[str] = {'''lr''': 2e-5, '''num_epochs''': args.num_epochs, '''seed''': 42, '''batch_size''': 16} training_function(__a , __a ) if __name__ == "__main__": main()
219
1
import argparse import collections import numpy as np import torch from flax import traverse_util from tax import checkpoints from transformers import MTaConfig, UMTaEncoderModel, UMTaForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() def lowerCAmelCase ( _lowerCAmelCase : str , _lowerCAmelCase : List[str] , _lowerCAmelCase : Any ): """simple docstring""" return params[F'''{prefix}/{prefix}/relpos_bias/rel_embedding'''][:, i, :] def lowerCAmelCase ( _lowerCAmelCase : int , _lowerCAmelCase : Dict , _lowerCAmelCase : Any , _lowerCAmelCase : List[str]="attention" ): """simple docstring""" UpperCAmelCase__ = UpperCAmelCase__ = np.ascontiguousarray(params[F'''{prefix}/{prefix}/{layer_name}/key/kernel'''][:, i, :, :] ) UpperCAmelCase__ = k_tmp.reshape(k_tmp.shape[0] , k_tmp.shape[1] * k_tmp.shape[2] ) UpperCAmelCase__ = np.ascontiguousarray(params[F'''{prefix}/{prefix}/{layer_name}/out/kernel'''][:, i, :, :] ) UpperCAmelCase__ = o_tmp.reshape(o_tmp.shape[0] * o_tmp.shape[1] , o_tmp.shape[2] ) UpperCAmelCase__ = np.ascontiguousarray(params[F'''{prefix}/{prefix}/{layer_name}/query/kernel'''][:, i, :, :] ) UpperCAmelCase__ = q_tmp.reshape(q_tmp.shape[0] , q_tmp.shape[1] * q_tmp.shape[2] ) UpperCAmelCase__ = np.ascontiguousarray(params[F'''{prefix}/{prefix}/{layer_name}/value/kernel'''][:, i, :, :] ) UpperCAmelCase__ = v_tmp.reshape(v_tmp.shape[0] , v_tmp.shape[1] * v_tmp.shape[2] ) return k, o, q, v def lowerCAmelCase ( _lowerCAmelCase : Optional[int] , _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : List[str] , _lowerCAmelCase : str=False ): """simple docstring""" if split_mlp_wi: UpperCAmelCase__ = params[F'''{prefix}/{prefix}/mlp/wi_0/kernel'''][:, i, :] UpperCAmelCase__ = params[F'''{prefix}/{prefix}/mlp/wi_1/kernel'''][:, i, :] UpperCAmelCase__ = (wi_a, wi_a) else: UpperCAmelCase__ = params[F'''{prefix}/{prefix}/mlp/wi/kernel'''][:, i, :] UpperCAmelCase__ = params[F'''{prefix}/{prefix}/mlp/wo/kernel'''][:, i, :] return wi, wo def lowerCAmelCase ( _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : Optional[int] , _lowerCAmelCase : str , _lowerCAmelCase : List[Any] ): """simple docstring""" return params[F'''{prefix}/{prefix}/{layer_name}/scale'''][:, i] def lowerCAmelCase ( _lowerCAmelCase : dict , *, _lowerCAmelCase : int , _lowerCAmelCase : bool , _lowerCAmelCase : bool = False ): """simple docstring""" UpperCAmelCase__ = traverse_util.flatten_dict(variables["target"] ) UpperCAmelCase__ = {"/".join(_lowerCAmelCase ): v for k, v in old.items()} # v1.1 models have a gated GeLU with wi_0 and wi_1 instead of wi UpperCAmelCase__ = "encoder/encoder/mlp/wi_0/kernel" in old print("Split MLP:" , _lowerCAmelCase ) UpperCAmelCase__ = collections.OrderedDict() # Shared embeddings. UpperCAmelCase__ = old["token_embedder/embedding"] # Encoder. for i in range(_lowerCAmelCase ): # Block i, layer 0 (Self Attention). UpperCAmelCase__ = tax_layer_norm_lookup(_lowerCAmelCase , _lowerCAmelCase , "encoder" , "pre_attention_layer_norm" ) UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = tax_attention_lookup(_lowerCAmelCase , _lowerCAmelCase , "encoder" , "attention" ) UpperCAmelCase__ = layer_norm UpperCAmelCase__ = k.T UpperCAmelCase__ = o.T UpperCAmelCase__ = q.T UpperCAmelCase__ = v.T # Block i, layer 1 (MLP). UpperCAmelCase__ = tax_layer_norm_lookup(_lowerCAmelCase , _lowerCAmelCase , "encoder" , "pre_mlp_layer_norm" ) UpperCAmelCase__ , UpperCAmelCase__ = tax_mlp_lookup(_lowerCAmelCase , _lowerCAmelCase , "encoder" , _lowerCAmelCase ) UpperCAmelCase__ = layer_norm if split_mlp_wi: UpperCAmelCase__ = wi[0].T UpperCAmelCase__ = wi[1].T else: UpperCAmelCase__ = wi.T UpperCAmelCase__ = wo.T if scalable_attention: # convert the rel_embedding of each layer UpperCAmelCase__ = tax_relpos_bias_lookup( _lowerCAmelCase , _lowerCAmelCase , "encoder" ).T UpperCAmelCase__ = old["encoder/encoder_norm/scale"] if not scalable_attention: UpperCAmelCase__ = tax_relpos_bias_lookup( _lowerCAmelCase , 0 , "encoder" ).T UpperCAmelCase__ = tax_relpos_bias_lookup( _lowerCAmelCase , 0 , "decoder" ).T if not is_encoder_only: # Decoder. for i in range(_lowerCAmelCase ): # Block i, layer 0 (Self Attention). UpperCAmelCase__ = tax_layer_norm_lookup(_lowerCAmelCase , _lowerCAmelCase , "decoder" , "pre_self_attention_layer_norm" ) UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = tax_attention_lookup(_lowerCAmelCase , _lowerCAmelCase , "decoder" , "self_attention" ) UpperCAmelCase__ = layer_norm UpperCAmelCase__ = k.T UpperCAmelCase__ = o.T UpperCAmelCase__ = q.T UpperCAmelCase__ = v.T # Block i, layer 1 (Cross Attention). UpperCAmelCase__ = tax_layer_norm_lookup(_lowerCAmelCase , _lowerCAmelCase , "decoder" , "pre_cross_attention_layer_norm" ) UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ = tax_attention_lookup(_lowerCAmelCase , _lowerCAmelCase , "decoder" , "encoder_decoder_attention" ) UpperCAmelCase__ = layer_norm UpperCAmelCase__ = k.T UpperCAmelCase__ = o.T UpperCAmelCase__ = q.T UpperCAmelCase__ = v.T # Block i, layer 2 (MLP). UpperCAmelCase__ = tax_layer_norm_lookup(_lowerCAmelCase , _lowerCAmelCase , "decoder" , "pre_mlp_layer_norm" ) UpperCAmelCase__ , UpperCAmelCase__ = tax_mlp_lookup(_lowerCAmelCase , _lowerCAmelCase , "decoder" , _lowerCAmelCase ) UpperCAmelCase__ = layer_norm if split_mlp_wi: UpperCAmelCase__ = wi[0].T UpperCAmelCase__ = wi[1].T else: UpperCAmelCase__ = wi.T UpperCAmelCase__ = wo.T if scalable_attention: # convert the rel_embedding of each layer UpperCAmelCase__ = tax_relpos_bias_lookup(_lowerCAmelCase , _lowerCAmelCase , "decoder" ).T UpperCAmelCase__ = old["decoder/decoder_norm/scale"] # LM Head (only in v1.1 checkpoints, in v1.0 embeddings are used instead) if "decoder/logits_dense/kernel" in old: UpperCAmelCase__ = old["decoder/logits_dense/kernel"].T return new def lowerCAmelCase ( _lowerCAmelCase : Union[str, Any] , _lowerCAmelCase : bool ): """simple docstring""" UpperCAmelCase__ = collections.OrderedDict([(k, torch.from_numpy(v.copy() )) for (k, v) in converted_params.items()] ) # Add what is missing. if "encoder.embed_tokens.weight" not in state_dict: UpperCAmelCase__ = state_dict["shared.weight"] if not is_encoder_only: if "decoder.embed_tokens.weight" not in state_dict: UpperCAmelCase__ = state_dict["shared.weight"] if "lm_head.weight" not in state_dict: # For old 1.0 models. print("Using shared word embeddings as lm_head." ) UpperCAmelCase__ = state_dict["shared.weight"] return state_dict def lowerCAmelCase ( _lowerCAmelCase : Optional[Any] , _lowerCAmelCase : str , _lowerCAmelCase : List[str] , _lowerCAmelCase : List[str] , _lowerCAmelCase : Optional[int] ): """simple docstring""" UpperCAmelCase__ = checkpoints.load_tax_checkpoint(_lowerCAmelCase ) UpperCAmelCase__ = convert_tax_to_pytorch( _lowerCAmelCase , num_layers=config.num_layers , is_encoder_only=_lowerCAmelCase , scalable_attention=_lowerCAmelCase ) UpperCAmelCase__ = make_state_dict(_lowerCAmelCase , _lowerCAmelCase ) model.load_state_dict(_lowerCAmelCase , strict=_lowerCAmelCase ) def lowerCAmelCase ( _lowerCAmelCase : str , _lowerCAmelCase : List[str] , _lowerCAmelCase : Dict , _lowerCAmelCase : bool = False , _lowerCAmelCase : bool = False , ): """simple docstring""" UpperCAmelCase__ = MTaConfig.from_json_file(_lowerCAmelCase ) print(F'''Building PyTorch model from configuration: {config}''' ) # Non-v1.1 checkpoints could also use T5Model, but this works for all. # The v1.0 checkpoints will simply have an LM head that is the word embeddings. if is_encoder_only: UpperCAmelCase__ = UMTaEncoderModel(_lowerCAmelCase ) else: UpperCAmelCase__ = UMTaForConditionalGeneration(_lowerCAmelCase ) # Load weights from tf checkpoint load_tax_weights_in_ta(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) # Save pytorch-model print(F'''Save PyTorch model to {pytorch_dump_path}''' ) model.save_pretrained(_lowerCAmelCase ) # Verify that we can load the checkpoint. model.from_pretrained(_lowerCAmelCase ) print("Done" ) if __name__ == "__main__": _lowerCAmelCase : str = argparse.ArgumentParser(description="Converts a native T5X checkpoint into a PyTorch checkpoint.") # Required parameters parser.add_argument( "--t5x_checkpoint_path", default=None, type=str, required=True, help="Path to the T5X checkpoint." ) parser.add_argument( "--config_file", default=None, type=str, required=True, help="The config json file corresponding to the pre-trained T5 model.\nThis specifies the model architecture.", ) parser.add_argument( "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model." ) parser.add_argument( "--is_encoder_only", action="store_true", help="Check if the model is encoder-decoder model", default=False ) parser.add_argument( "--scalable_attention", action="store_true", help="Whether the model uses scaled attention (umt5 model)", default=False, ) _lowerCAmelCase : Optional[int] = parser.parse_args() convert_tax_checkpoint_to_pytorch( args.tax_checkpoint_path, args.config_file, args.pytorch_dump_path, args.is_encoder_only, args.scalable_attention, )
169
from ...configuration_utils import PretrainedConfig from ...utils import logging _lowerCAmelCase : List[str] = logging.get_logger(__name__) _lowerCAmelCase : Optional[Any] = { "microsoft/markuplm-base": "https://huggingface.co/microsoft/markuplm-base/resolve/main/config.json", "microsoft/markuplm-large": "https://huggingface.co/microsoft/markuplm-large/resolve/main/config.json", } class _UpperCamelCase ( lowerCAmelCase ): UpperCAmelCase_ = """markuplm""" def __init__( self :Dict , lowerCamelCase :List[Any]=3_0522 , lowerCamelCase :List[Any]=768 , lowerCamelCase :Union[str, Any]=12 , lowerCamelCase :Optional[int]=12 , lowerCamelCase :List[str]=3072 , lowerCamelCase :Dict="gelu" , lowerCamelCase :List[str]=0.1 , lowerCamelCase :Union[str, Any]=0.1 , lowerCamelCase :int=512 , lowerCamelCase :Union[str, Any]=2 , lowerCamelCase :int=0.02 , lowerCamelCase :int=1e-12 , lowerCamelCase :Tuple=0 , lowerCamelCase :List[str]=0 , lowerCamelCase :int=2 , lowerCamelCase :Optional[int]=256 , lowerCamelCase :List[str]=1024 , lowerCamelCase :Optional[Any]=216 , lowerCamelCase :str=1001 , lowerCamelCase :List[str]=32 , lowerCamelCase :Dict=50 , lowerCamelCase :int="absolute" , lowerCamelCase :Union[str, Any]=True , lowerCamelCase :Dict=None , **lowerCamelCase :List[Any] , ) -> int: super().__init__( pad_token_id=lowerCamelCase , bos_token_id=lowerCamelCase , eos_token_id=lowerCamelCase , **lowerCamelCase , ) UpperCAmelCase__ = vocab_size UpperCAmelCase__ = hidden_size UpperCAmelCase__ = num_hidden_layers UpperCAmelCase__ = num_attention_heads UpperCAmelCase__ = hidden_act UpperCAmelCase__ = intermediate_size UpperCAmelCase__ = hidden_dropout_prob UpperCAmelCase__ = attention_probs_dropout_prob UpperCAmelCase__ = max_position_embeddings UpperCAmelCase__ = type_vocab_size UpperCAmelCase__ = initializer_range UpperCAmelCase__ = layer_norm_eps UpperCAmelCase__ = position_embedding_type UpperCAmelCase__ = use_cache UpperCAmelCase__ = classifier_dropout # additional properties UpperCAmelCase__ = max_depth UpperCAmelCase__ = max_xpath_tag_unit_embeddings UpperCAmelCase__ = max_xpath_subs_unit_embeddings UpperCAmelCase__ = tag_pad_id UpperCAmelCase__ = subs_pad_id UpperCAmelCase__ = xpath_unit_hidden_size
169
1
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss a__ = pytest.mark.integration @require_faiss class UpperCAmelCase_ ( __lowercase ): """simple docstring""" def __lowercase ( self ) -> List[Any]: _a : Tuple = Dataset.from_dict({'''filename''': ['''my_name-train''' + '''_''' + str(_a ) for x in np.arange(3_0 ).tolist()]} ) return dset def __lowercase ( self ) -> List[Any]: import faiss _a : Dataset = self._create_dummy_dataset() _a : Union[str, Any] = dset.map( lambda _a , _a : {"vecs": i * np.ones(5 , dtype=np.floataa )} , with_indices=_a , keep_in_memory=_a ) _a : List[str] = dset.add_faiss_index('''vecs''' , batch_size=1_0_0 , metric_type=faiss.METRIC_INNER_PRODUCT ) _a : Optional[Any] = dset.get_nearest_examples('''vecs''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) dset.drop_index('''vecs''' ) def __lowercase ( self ) -> Optional[int]: import faiss _a : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((3_0, 5) ) * np.arange(3_0 ).reshape(-1 , 1 ) , index_name='''vecs''' , batch_size=1_0_0 , metric_type=faiss.METRIC_INNER_PRODUCT , ) _a : Union[str, Any] = dset.get_nearest_examples('''vecs''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) def __lowercase ( self ) -> str: import faiss _a : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((3_0, 5) ) * np.arange(3_0 ).reshape(-1 , 1 ) , index_name='''vecs''' , metric_type=faiss.METRIC_INNER_PRODUCT , ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=_a ) as tmp_file: dset.save_faiss_index('''vecs''' , tmp_file.name ) dset.load_faiss_index('''vecs2''' , tmp_file.name ) os.unlink(tmp_file.name ) _a : str = dset.get_nearest_examples('''vecs2''' , np.ones(5 , dtype=np.floataa ) ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) def __lowercase ( self ) -> Optional[int]: _a : Dataset = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((3_0, 5) ) * np.arange(3_0 ).reshape(-1 , 1 ) , index_name='''vecs''' ) dset.drop_index('''vecs''' ) self.assertRaises(_a , partial(dset.get_nearest_examples , '''vecs2''' , np.ones(5 , dtype=np.floataa ) ) ) def __lowercase ( self ) -> Any: from elasticsearch import Elasticsearch _a : Dataset = self._create_dummy_dataset() with patch('''elasticsearch.Elasticsearch.search''' ) as mocked_search, patch( '''elasticsearch.client.IndicesClient.create''' ) as mocked_index_create, patch('''elasticsearch.helpers.streaming_bulk''' ) as mocked_bulk: _a : Dict = {'''acknowledged''': True} mocked_bulk.return_value([(True, None)] * 3_0 ) _a : Tuple = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 2_9}]}} _a : Optional[int] = Elasticsearch() dset.add_elasticsearch_index('''filename''' , es_client=_a ) _a : Optional[Any] = dset.get_nearest_examples('''filename''' , '''my_name-train_29''' ) self.assertEqual(examples['''filename'''][0] , '''my_name-train_29''' ) @require_faiss class UpperCAmelCase_ ( __lowercase ): """simple docstring""" def __lowercase ( self ) -> Tuple: import faiss _a : Tuple = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal , 5 ) index.add_vectors(np.zeros((5, 5) , dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal , 1_0 ) # single query _a : Optional[int] = np.zeros(5 , dtype=np.floataa ) _a : Optional[int] = 1 _a : int = index.search(_a ) self.assertRaises(_a , index.search , query.reshape(-1 , 1 ) ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) # batched queries _a : Dict = np.eye(5 , dtype=np.floataa )[::-1] _a : Any = index.search_batch(_a ) self.assertRaises(_a , index.search_batch , queries[0] ) _a : Dict = [scores[0] for scores in total_scores] _a : Any = [indices[0] for indices in total_indices] self.assertGreater(np.min(_a ) , 0 ) self.assertListEqual([4, 3, 2, 1, 0] , _a ) def __lowercase ( self ) -> str: import faiss _a : int = FaissIndex(string_factory='''Flat''' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) _a : Optional[Any] = FaissIndex(string_factory='''LSH''' ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexLSH ) with self.assertRaises(_a ): _a : List[str] = FaissIndex(string_factory='''Flat''' , custom_index=faiss.IndexFlat(5 ) ) def __lowercase ( self ) -> str: import faiss _a : int = faiss.IndexFlat(5 ) _a : str = FaissIndex(custom_index=_a ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index , faiss.IndexFlat ) def __lowercase ( self ) -> str: import faiss _a : Tuple = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=_a ) as tmp_file: index.save(tmp_file.name ) _a : Union[str, Any] = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) _a : List[Any] = np.zeros(5 , dtype=np.floataa ) _a : int = 1 _a : Union[str, Any] = index.search(_a ) self.assertGreater(scores[0] , 0 ) self.assertEqual(indices[0] , 1 ) @require_faiss def __UpperCAmelCase ( __a : Optional[int] ) -> List[Any]: """simple docstring""" import faiss _a : Optional[Any] = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) _a : str = '''index.faiss''' _a : int = F"""mock://{index_name}""" index.save(__a ,storage_options=mockfs.storage_options ) _a : int = FaissIndex.load(__a ,storage_options=mockfs.storage_options ) _a : Tuple = np.zeros(5 ,dtype=np.floataa ) _a : str = 1 _a : Union[str, Any] = index.search(__a ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class UpperCAmelCase_ ( __lowercase ): """simple docstring""" def __lowercase ( self ) -> List[str]: from elasticsearch import Elasticsearch with patch('''elasticsearch.Elasticsearch.search''' ) as mocked_search, patch( '''elasticsearch.client.IndicesClient.create''' ) as mocked_index_create, patch('''elasticsearch.helpers.streaming_bulk''' ) as mocked_bulk: _a : int = Elasticsearch() _a : List[Any] = {'''acknowledged''': True} _a : List[str] = ElasticSearchIndex(es_client=_a ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(['''foo''', '''bar''', '''foobar'''] ) # single query _a : str = '''foo''' _a : List[str] = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} _a : Optional[Any] = index.search(_a ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # single query with timeout _a : Any = '''foo''' _a : List[str] = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 0}]}} _a : Optional[int] = index.search(_a , request_timeout=3_0 ) self.assertEqual(scores[0] , 1 ) self.assertEqual(indices[0] , 0 ) # batched queries _a : str = ['''foo''', '''bar''', '''foobar'''] _a : Optional[int] = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} _a : Union[str, Any] = index.search_batch(_a ) _a : Union[str, Any] = [scores[0] for scores in total_scores] _a : Optional[int] = [indices[0] for indices in total_indices] self.assertGreater(np.min(_a ) , 0 ) self.assertListEqual([1, 1, 1] , _a ) # batched queries with timeout _a : Tuple = ['''foo''', '''bar''', '''foobar'''] _a : str = {'''hits''': {'''hits''': [{'''_score''': 1, '''_id''': 1}]}} _a : int = index.search_batch(_a , request_timeout=3_0 ) _a : Tuple = [scores[0] for scores in total_scores] _a : Optional[int] = [indices[0] for indices in total_indices] self.assertGreater(np.min(_a ) , 0 ) self.assertListEqual([1, 1, 1] , _a )
351
from math import ceil def __UpperCAmelCase ( __a : int = 1_001 ) -> int: """simple docstring""" _a : Dict = 1 for i in range(1 ,int(ceil(n / 2.0 ) ) ): _a : int = 2 * i + 1 _a : str = 2 * i _a : Any = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: a__ = int(sys.argv[1]) print(solution(n)) except ValueError: print('''Invalid entry - please enter a number''')
15
0
from __future__ import absolute_import, division, print_function, unicode_literals from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers import RobertaConfig from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.roberta.modeling_roberta import ( ROBERTA_INPUTS_DOCSTRING, ROBERTA_START_DOCSTRING, RobertaEmbeddings, ) from .modeling_highway_bert import BertPreTrainedModel, DeeBertModel, HighwayException, entropy @add_start_docstrings( '''The RoBERTa Model transformer with early exiting (DeeRoBERTa). ''' , lowerCamelCase__ , ) class __lowerCAmelCase ( lowerCamelCase__ ): __lowerCamelCase = RobertaConfig __lowerCamelCase = '''roberta''' def __init__( self , _snake_case ): """simple docstring""" super().__init__(_snake_case ) _lowerCAmelCase = RobertaEmbeddings(_snake_case ) self.init_weights() @add_start_docstrings( '''RoBERTa Model (with early exiting - DeeRoBERTa) with a classifier on top, also takes care of multi-layer training. ''' , lowerCamelCase__ , ) class __lowerCAmelCase ( lowerCamelCase__ ): __lowerCamelCase = RobertaConfig __lowerCamelCase = '''roberta''' def __init__( self , _snake_case ): """simple docstring""" super().__init__(_snake_case ) _lowerCAmelCase = config.num_labels _lowerCAmelCase = config.num_hidden_layers _lowerCAmelCase = DeeRobertaModel(_snake_case ) _lowerCAmelCase = nn.Dropout(config.hidden_dropout_prob ) _lowerCAmelCase = nn.Linear(config.hidden_size , self.config.num_labels ) @add_start_docstrings_to_model_forward(_snake_case ) def snake_case ( self , _snake_case=None , _snake_case=None , _snake_case=None , _snake_case=None , _snake_case=None , _snake_case=None , _snake_case=None , _snake_case=-1 , _snake_case=False , ): """simple docstring""" _lowerCAmelCase = self.num_layers try: _lowerCAmelCase = self.roberta( _snake_case , attention_mask=_snake_case , token_type_ids=_snake_case , position_ids=_snake_case , head_mask=_snake_case , inputs_embeds=_snake_case , ) _lowerCAmelCase = outputs[1] _lowerCAmelCase = self.dropout(_snake_case ) _lowerCAmelCase = self.classifier(_snake_case ) _lowerCAmelCase = (logits,) + outputs[2:] # add hidden states and attention if they are here except HighwayException as e: _lowerCAmelCase = e.message _lowerCAmelCase = e.exit_layer _lowerCAmelCase = outputs[0] if not self.training: _lowerCAmelCase = entropy(_snake_case ) _lowerCAmelCase = [] _lowerCAmelCase = [] if labels is not None: if self.num_labels == 1: # We are doing regression _lowerCAmelCase = MSELoss() _lowerCAmelCase = loss_fct(logits.view(-1 ) , labels.view(-1 ) ) else: _lowerCAmelCase = CrossEntropyLoss() _lowerCAmelCase = loss_fct(logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) # work with highway exits _lowerCAmelCase = [] for highway_exit in outputs[-1]: _lowerCAmelCase = highway_exit[0] if not self.training: highway_logits_all.append(_snake_case ) highway_entropy.append(highway_exit[2] ) if self.num_labels == 1: # We are doing regression _lowerCAmelCase = MSELoss() _lowerCAmelCase = loss_fct(highway_logits.view(-1 ) , labels.view(-1 ) ) else: _lowerCAmelCase = CrossEntropyLoss() _lowerCAmelCase = loss_fct(highway_logits.view(-1 , self.num_labels ) , labels.view(-1 ) ) highway_losses.append(_snake_case ) if train_highway: _lowerCAmelCase = (sum(highway_losses[:-1] ),) + outputs # exclude the final highway, of course else: _lowerCAmelCase = (loss,) + outputs if not self.training: _lowerCAmelCase = outputs + ((original_entropy, highway_entropy), exit_layer) if output_layer >= 0: _lowerCAmelCase = ( (outputs[0],) + (highway_logits_all[output_layer],) + outputs[2:] ) # use the highway of the last layer return outputs # (loss), logits, (hidden_states), (attentions), entropy
82
# 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__ ( lowerCAmelCase_ ): """simple docstring""" _SCREAMING_SNAKE_CASE = """philschmid/bart-large-cnn-samsum""" _SCREAMING_SNAKE_CASE = ( """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.""" ) _SCREAMING_SNAKE_CASE = """summarizer""" _SCREAMING_SNAKE_CASE = AutoTokenizer _SCREAMING_SNAKE_CASE = AutoModelForSeqaSeqLM _SCREAMING_SNAKE_CASE = ["""text"""] _SCREAMING_SNAKE_CASE = ["""text"""] def lowercase_ ( self : Optional[Any], _snake_case : str ) ->Any: return self.pre_processor(_snake_case, return_tensors='pt', truncation=_snake_case ) def lowercase_ ( self : int, _snake_case : List[Any] ) ->Any: return self.model.generate(**_snake_case )[0] def lowercase_ ( self : int, _snake_case : int ) ->str: return self.pre_processor.decode(_snake_case, skip_special_tokens=_snake_case, clean_up_tokenization_spaces=_snake_case )
277
0
'''simple docstring''' import pandas as pd from matplotlib import pyplot as plt from sklearn.linear_model import LinearRegression # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split # Fitting Polynomial Regression to the dataset from sklearn.preprocessing import PolynomialFeatures # Importing the dataset a__ : Tuple = pd.read_csv( 'https://s3.us-west-2.amazonaws.com/public.gamelab.fun/dataset/' 'position_salaries.csv' ) a__ : Any = dataset.iloc[:, 1:2].values a__ : int = dataset.iloc[:, 2].values a__ , a__ , a__ , a__ : List[Any] = train_test_split(X, y, test_size=0.2, random_state=0) a__ : Any = PolynomialFeatures(degree=4) a__ : Optional[Any] = poly_reg.fit_transform(X) a__ : Optional[int] = LinearRegression() pol_reg.fit(X_poly, y) def _lowercase ( ): '''simple docstring''' plt.scatter(__A ,__A ,color="""red""" ) plt.plot(__A ,pol_reg.predict(poly_reg.fit_transform(__A ) ) ,color="""blue""" ) plt.title("""Truth or Bluff (Linear Regression)""" ) plt.xlabel("""Position level""" ) plt.ylabel("""Salary""" ) plt.show() if __name__ == "__main__": viz_polymonial() # Predicting a new result with Polymonial Regression pol_reg.predict(poly_reg.fit_transform([[5.5]])) # output should be 132148.43750003
243
'''simple docstring''' def _lowercase ( __A = 10 ,__A = 22 ): '''simple docstring''' __UpperCamelCase = range(1 ,__A ) __UpperCamelCase = range(1 ,__A ) return sum( 1 for power in powers for base in bases if len(str(base**power ) ) == power ) if __name__ == "__main__": print(f'''{solution(1_0, 2_2) = }''')
243
1
def UpperCamelCase__ ( A__ , A__ ) -> Optional[int]: snake_case__ : Union[str, Any] = len(_UpperCAmelCase ) print('The following activities are selected:' ) # The first activity is always selected snake_case__ : Any = 0 print(_UpperCAmelCase , end=',' ) # Consider rest of the activities for j in range(_UpperCAmelCase ): # If this activity has start time greater than # or equal to the finish time of previously # selected activity, then select it if start[j] >= finish[i]: print(_UpperCAmelCase , end=',' ) snake_case__ : int = j if __name__ == "__main__": import doctest doctest.testmod() lowerCAmelCase__ : Union[str, Any] = [1, 3, 0, 5, 8, 5] lowerCAmelCase__ : List[str] = [2, 4, 6, 7, 9, 9] print_max_activities(start, finish)
143
"""simple docstring""" 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 lowercase ( __UpperCAmelCase): __lowerCAmelCase : str = ["""image_processor""", """tokenizer"""] __lowerCAmelCase : Optional[Any] = """OwlViTImageProcessor""" __lowerCAmelCase : Any = ("""CLIPTokenizer""", """CLIPTokenizerFast""") def __init__( self : Union[str, Any] , _lowerCamelCase : str=None , _lowerCamelCase : Tuple=None , **_lowerCamelCase : List[Any] ): """simple docstring""" A_ : Optional[Any] = None if "feature_extractor" in kwargs: warnings.warn( '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`''' ''' instead.''' , _lowerCamelCase , ) A_ : List[Any] = kwargs.pop('''feature_extractor''' ) A_ : Any = 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__(_lowerCamelCase , _lowerCamelCase ) def __call__( self : Optional[int] , _lowerCamelCase : List[Any]=None , _lowerCamelCase : Dict=None , _lowerCamelCase : int=None , _lowerCamelCase : str="max_length" , _lowerCamelCase : List[Any]="np" , **_lowerCamelCase : Optional[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(_lowerCamelCase , _lowerCamelCase ) or (isinstance(_lowerCamelCase , _lowerCamelCase ) and not isinstance(text[0] , _lowerCamelCase )): A_ : List[str] = [self.tokenizer(_lowerCamelCase , padding=_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase )] elif isinstance(_lowerCamelCase , _lowerCamelCase ) and isinstance(text[0] , _lowerCamelCase ): A_ : Optional[int] = [] # Maximum number of queries across batch A_ : Any = max([len(_lowerCamelCase ) for t in text] ) # Pad all batch samples to max number of text queries for t in text: if len(_lowerCamelCase ) != max_num_queries: A_ : Optional[int] = t + [''' '''] * (max_num_queries - len(_lowerCamelCase )) A_ : Tuple = self.tokenizer(_lowerCamelCase , padding=_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase ) encodings.append(_lowerCamelCase ) else: raise TypeError('''Input text should be a string, a list of strings or a nested list of strings''' ) if return_tensors == "np": A_ : Union[str, Any] = np.concatenate([encoding['''input_ids'''] for encoding in encodings] , axis=0 ) A_ : Dict = np.concatenate([encoding['''attention_mask'''] for encoding in encodings] , axis=0 ) elif return_tensors == "jax" and is_flax_available(): import jax.numpy as jnp A_ : List[Any] = jnp.concatenate([encoding['''input_ids'''] for encoding in encodings] , axis=0 ) A_ : Any = jnp.concatenate([encoding['''attention_mask'''] for encoding in encodings] , axis=0 ) elif return_tensors == "pt" and is_torch_available(): import torch A_ : Any = torch.cat([encoding['''input_ids'''] for encoding in encodings] , dim=0 ) A_ : Union[str, Any] = torch.cat([encoding['''attention_mask'''] for encoding in encodings] , dim=0 ) elif return_tensors == "tf" and is_tf_available(): import tensorflow as tf A_ : Tuple = tf.stack([encoding['''input_ids'''] for encoding in encodings] , axis=0 ) A_ : str = tf.stack([encoding['''attention_mask'''] for encoding in encodings] , axis=0 ) else: raise ValueError('''Target return tensor type could not be returned''' ) A_ : Any = BatchEncoding() A_ : Optional[Any] = input_ids A_ : str = attention_mask if query_images is not None: A_ : Union[str, Any] = BatchEncoding() A_ : Optional[Any] = self.image_processor( _lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase ).pixel_values A_ : Dict = query_pixel_values if images is not None: A_ : int = self.image_processor(_lowerCamelCase , return_tensors=_lowerCamelCase , **_lowerCamelCase ) if text is not None and images is not None: A_ : str = image_features.pixel_values return encoding elif query_images is not None and images is not None: A_ : Union[str, Any] = image_features.pixel_values return encoding elif text is not None or query_images is not None: return encoding else: return BatchEncoding(data=dict(**_lowerCamelCase ) , tensor_type=_lowerCamelCase ) def a_ ( self : Optional[Any] , *_lowerCamelCase : int , **_lowerCamelCase : Dict ): """simple docstring""" return self.image_processor.post_process(*_lowerCamelCase , **_lowerCamelCase ) def a_ ( self : Optional[Any] , *_lowerCamelCase : Optional[Any] , **_lowerCamelCase : Dict ): """simple docstring""" return self.image_processor.post_process_object_detection(*_lowerCamelCase , **_lowerCamelCase ) def a_ ( self : List[Any] , *_lowerCamelCase : List[str] , **_lowerCamelCase : Optional[int] ): """simple docstring""" return self.image_processor.post_process_image_guided_detection(*_lowerCamelCase , **_lowerCamelCase ) def a_ ( self : str , *_lowerCamelCase : Tuple , **_lowerCamelCase : List[Any] ): """simple docstring""" return self.tokenizer.batch_decode(*_lowerCamelCase , **_lowerCamelCase ) def a_ ( self : Dict , *_lowerCamelCase : Any , **_lowerCamelCase : Union[str, Any] ): """simple docstring""" return self.tokenizer.decode(*_lowerCamelCase , **_lowerCamelCase ) @property def a_ ( self : List[str] ): """simple docstring""" warnings.warn( '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , _lowerCamelCase , ) return self.image_processor_class @property def a_ ( self : Any ): """simple docstring""" warnings.warn( '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , _lowerCamelCase , ) return self.image_processor
167
0
"""simple docstring""" import importlib import json import os from collections import OrderedDict from typing import Dict, Optional, Union # Build the list of all image processors from ...configuration_utils import PretrainedConfig from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code from ...image_processing_utils import ImageProcessingMixin from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging from .auto_factory import _LazyAutoMapping from .configuration_auto import ( CONFIG_MAPPING_NAMES, AutoConfig, model_type_to_module_name, replace_list_option_in_docstrings, ) __A = logging.get_logger(__name__) __A = OrderedDict( [ ("align", "EfficientNetImageProcessor"), ("beit", "BeitImageProcessor"), ("bit", "BitImageProcessor"), ("blip", "BlipImageProcessor"), ("blip-2", "BlipImageProcessor"), ("bridgetower", "BridgeTowerImageProcessor"), ("chinese_clip", "ChineseCLIPImageProcessor"), ("clip", "CLIPImageProcessor"), ("clipseg", "ViTImageProcessor"), ("conditional_detr", "ConditionalDetrImageProcessor"), ("convnext", "ConvNextImageProcessor"), ("convnextv2", "ConvNextImageProcessor"), ("cvt", "ConvNextImageProcessor"), ("data2vec-vision", "BeitImageProcessor"), ("deformable_detr", "DeformableDetrImageProcessor"), ("deit", "DeiTImageProcessor"), ("deta", "DetaImageProcessor"), ("detr", "DetrImageProcessor"), ("dinat", "ViTImageProcessor"), ("donut-swin", "DonutImageProcessor"), ("dpt", "DPTImageProcessor"), ("efficientformer", "EfficientFormerImageProcessor"), ("efficientnet", "EfficientNetImageProcessor"), ("flava", "FlavaImageProcessor"), ("focalnet", "BitImageProcessor"), ("git", "CLIPImageProcessor"), ("glpn", "GLPNImageProcessor"), ("groupvit", "CLIPImageProcessor"), ("imagegpt", "ImageGPTImageProcessor"), ("instructblip", "BlipImageProcessor"), ("layoutlmv2", "LayoutLMv2ImageProcessor"), ("layoutlmv3", "LayoutLMv3ImageProcessor"), ("levit", "LevitImageProcessor"), ("mask2former", "Mask2FormerImageProcessor"), ("maskformer", "MaskFormerImageProcessor"), ("mgp-str", "ViTImageProcessor"), ("mobilenet_v1", "MobileNetV1ImageProcessor"), ("mobilenet_v2", "MobileNetV2ImageProcessor"), ("mobilevit", "MobileViTImageProcessor"), ("mobilevit", "MobileViTImageProcessor"), ("mobilevitv2", "MobileViTImageProcessor"), ("nat", "ViTImageProcessor"), ("oneformer", "OneFormerImageProcessor"), ("owlvit", "OwlViTImageProcessor"), ("perceiver", "PerceiverImageProcessor"), ("pix2struct", "Pix2StructImageProcessor"), ("poolformer", "PoolFormerImageProcessor"), ("regnet", "ConvNextImageProcessor"), ("resnet", "ConvNextImageProcessor"), ("sam", "SamImageProcessor"), ("segformer", "SegformerImageProcessor"), ("swiftformer", "ViTImageProcessor"), ("swin", "ViTImageProcessor"), ("swin2sr", "Swin2SRImageProcessor"), ("swinv2", "ViTImageProcessor"), ("table-transformer", "DetrImageProcessor"), ("timesformer", "VideoMAEImageProcessor"), ("tvlt", "TvltImageProcessor"), ("upernet", "SegformerImageProcessor"), ("van", "ConvNextImageProcessor"), ("videomae", "VideoMAEImageProcessor"), ("vilt", "ViltImageProcessor"), ("vit", "ViTImageProcessor"), ("vit_hybrid", "ViTHybridImageProcessor"), ("vit_mae", "ViTImageProcessor"), ("vit_msn", "ViTImageProcessor"), ("xclip", "CLIPImageProcessor"), ("yolos", "YolosImageProcessor"), ] ) __A = _LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES) def a__ ( __SCREAMING_SNAKE_CASE ) -> Tuple: for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items(): if class_name in extractors: __lowerCAmelCase: Any = model_type_to_module_name(__SCREAMING_SNAKE_CASE ) __lowerCAmelCase: Dict = importlib.import_module(F".{module_name}" , "transformers.models" ) try: return getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) except AttributeError: continue for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items(): if getattr(__SCREAMING_SNAKE_CASE , "__name__" , __SCREAMING_SNAKE_CASE ) == class_name: return extractor # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main # init and we return the proper dummy to get an appropriate error message. __lowerCAmelCase: str = importlib.import_module("transformers" ) if hasattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): return getattr(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) return None def a__ ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = False , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = None , __SCREAMING_SNAKE_CASE = False , **__SCREAMING_SNAKE_CASE , ) -> Any: __lowerCAmelCase: List[Any] = get_file_from_repo( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , cache_dir=__SCREAMING_SNAKE_CASE , force_download=__SCREAMING_SNAKE_CASE , resume_download=__SCREAMING_SNAKE_CASE , proxies=__SCREAMING_SNAKE_CASE , use_auth_token=__SCREAMING_SNAKE_CASE , revision=__SCREAMING_SNAKE_CASE , local_files_only=__SCREAMING_SNAKE_CASE , ) if resolved_config_file is None: logger.info( "Could not locate the image processor configuration file, will try to use the model config instead." ) return {} with open(__SCREAMING_SNAKE_CASE , encoding="utf-8" ) as reader: return json.load(__SCREAMING_SNAKE_CASE ) class snake_case : def __init__( self : List[str])-> str: '''simple docstring''' raise EnvironmentError( "AutoImageProcessor is designed to be instantiated " "using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.") @classmethod @replace_list_option_in_docstrings(UpperCamelCase__) def lowercase_ ( cls : Tuple , UpperCamelCase__ : str , **UpperCamelCase__ : Optional[int])-> List[Any]: '''simple docstring''' __lowerCAmelCase: Any = kwargs.pop("config" , UpperCamelCase__) __lowerCAmelCase: Tuple = kwargs.pop("trust_remote_code" , UpperCamelCase__) __lowerCAmelCase: List[str] = True __lowerCAmelCase: List[str] = ImageProcessingMixin.get_image_processor_dict(UpperCamelCase__ , **UpperCamelCase__) __lowerCAmelCase: Optional[int] = config_dict.get("image_processor_type" , UpperCamelCase__) __lowerCAmelCase: int = None if "AutoImageProcessor" in config_dict.get("auto_map" , {}): __lowerCAmelCase: str = config_dict["auto_map"]["AutoImageProcessor"] # If we still don't have the image processor class, check if we're loading from a previous feature extractor config # and if so, infer the image processor class from there. if image_processor_class is None and image_processor_auto_map is None: __lowerCAmelCase: Dict = config_dict.pop("feature_extractor_type" , UpperCamelCase__) if feature_extractor_class is not None: logger.warning( "Could not find image processor class in the image processor config or the model config. Loading" " based on pattern matching with the model's feature extractor configuration.") __lowerCAmelCase: Tuple = feature_extractor_class.replace("FeatureExtractor" , "ImageProcessor") if "AutoFeatureExtractor" in config_dict.get("auto_map" , {}): __lowerCAmelCase: List[str] = config_dict["auto_map"]["AutoFeatureExtractor"] __lowerCAmelCase: Dict = feature_extractor_auto_map.replace("FeatureExtractor" , "ImageProcessor") logger.warning( "Could not find image processor auto map in the image processor config or the model config." " Loading based on pattern matching with the model's feature extractor configuration.") # If we don't find the image processor class in the image processor config, let's try the model config. if image_processor_class is None and image_processor_auto_map is None: if not isinstance(UpperCamelCase__ , UpperCamelCase__): __lowerCAmelCase: Any = AutoConfig.from_pretrained(UpperCamelCase__ , **UpperCamelCase__) # It could be in `config.image_processor_type`` __lowerCAmelCase: str = getattr(UpperCamelCase__ , "image_processor_type" , UpperCamelCase__) if hasattr(UpperCamelCase__ , "auto_map") and "AutoImageProcessor" in config.auto_map: __lowerCAmelCase: List[str] = config.auto_map["AutoImageProcessor"] if image_processor_class is not None: __lowerCAmelCase: Tuple = image_processor_class_from_name(UpperCamelCase__) __lowerCAmelCase: int = image_processor_auto_map is not None __lowerCAmelCase: str = image_processor_class is not None or type(UpperCamelCase__) in IMAGE_PROCESSOR_MAPPING __lowerCAmelCase: List[str] = resolve_trust_remote_code( UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__) if has_remote_code and trust_remote_code: __lowerCAmelCase: List[Any] = get_class_from_dynamic_module( UpperCamelCase__ , UpperCamelCase__ , **UpperCamelCase__) __lowerCAmelCase: Optional[int] = kwargs.pop("code_revision" , UpperCamelCase__) if os.path.isdir(UpperCamelCase__): image_processor_class.register_for_auto_class() return image_processor_class.from_dict(UpperCamelCase__ , **UpperCamelCase__) elif image_processor_class is not None: return image_processor_class.from_dict(UpperCamelCase__ , **UpperCamelCase__) # Last try: we use the IMAGE_PROCESSOR_MAPPING. elif type(UpperCamelCase__) in IMAGE_PROCESSOR_MAPPING: __lowerCAmelCase: Dict = IMAGE_PROCESSOR_MAPPING[type(UpperCamelCase__)] return image_processor_class.from_dict(UpperCamelCase__ , **UpperCamelCase__) raise ValueError( f"Unrecognized image processor in {pretrained_model_name_or_path}. Should have a " f"`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following " f"`model_type` keys in its {CONFIG_NAME}: {', '.join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys())}") @staticmethod def lowercase_ ( UpperCamelCase__ : str , UpperCamelCase__ : Optional[Any])-> Any: '''simple docstring''' IMAGE_PROCESSOR_MAPPING.register(UpperCamelCase__ , UpperCamelCase__)
365
"""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 __A = logging.get_logger(__name__) __A = { "facebook/data2vec-vision-base-ft": ( "https://huggingface.co/facebook/data2vec-vision-base-ft/resolve/main/config.json" ), } class snake_case ( __snake_case ): SCREAMING_SNAKE_CASE_ : Union[str, Any] = """data2vec-vision""" def __init__( self : Optional[int] , UpperCamelCase__ : str=7_6_8 , UpperCamelCase__ : Any=1_2 , UpperCamelCase__ : str=1_2 , UpperCamelCase__ : Optional[Any]=3_0_7_2 , UpperCamelCase__ : Union[str, Any]="gelu" , UpperCamelCase__ : List[Any]=0.0 , UpperCamelCase__ : Dict=0.0 , UpperCamelCase__ : Union[str, Any]=0.02 , UpperCamelCase__ : str=1e-12 , UpperCamelCase__ : Dict=2_2_4 , UpperCamelCase__ : List[Any]=1_6 , UpperCamelCase__ : Optional[Any]=3 , UpperCamelCase__ : List[str]=False , UpperCamelCase__ : List[Any]=False , UpperCamelCase__ : str=False , UpperCamelCase__ : List[str]=False , UpperCamelCase__ : int=0.1 , UpperCamelCase__ : List[Any]=0.1 , UpperCamelCase__ : Optional[Any]=True , UpperCamelCase__ : List[Any]=[3, 5, 7, 1_1] , UpperCamelCase__ : List[str]=[1, 2, 3, 6] , UpperCamelCase__ : Union[str, Any]=True , UpperCamelCase__ : Any=0.4 , UpperCamelCase__ : Union[str, Any]=2_5_6 , UpperCamelCase__ : List[Any]=1 , UpperCamelCase__ : str=False , UpperCamelCase__ : Optional[int]=2_5_5 , **UpperCamelCase__ : Dict , )-> List[str]: '''simple docstring''' super().__init__(**UpperCamelCase__) __lowerCAmelCase: List[str] = hidden_size __lowerCAmelCase: Union[str, Any] = num_hidden_layers __lowerCAmelCase: Dict = num_attention_heads __lowerCAmelCase: Optional[int] = intermediate_size __lowerCAmelCase: int = hidden_act __lowerCAmelCase: Union[str, Any] = hidden_dropout_prob __lowerCAmelCase: Any = attention_probs_dropout_prob __lowerCAmelCase: Dict = initializer_range __lowerCAmelCase: Any = layer_norm_eps __lowerCAmelCase: Union[str, Any] = image_size __lowerCAmelCase: Tuple = patch_size __lowerCAmelCase: List[str] = num_channels __lowerCAmelCase: Optional[Any] = use_mask_token __lowerCAmelCase: str = use_absolute_position_embeddings __lowerCAmelCase: Optional[int] = use_relative_position_bias __lowerCAmelCase: str = use_shared_relative_position_bias __lowerCAmelCase: Union[str, Any] = layer_scale_init_value __lowerCAmelCase: Any = drop_path_rate __lowerCAmelCase: Dict = use_mean_pooling # decode head attributes (semantic segmentation) __lowerCAmelCase: int = out_indices __lowerCAmelCase: Any = pool_scales # auxiliary head attributes (semantic segmentation) __lowerCAmelCase: List[Any] = use_auxiliary_head __lowerCAmelCase: int = auxiliary_loss_weight __lowerCAmelCase: Dict = auxiliary_channels __lowerCAmelCase: Any = auxiliary_num_convs __lowerCAmelCase: Any = auxiliary_concat_input __lowerCAmelCase: Any = semantic_loss_ignore_index class snake_case ( __snake_case ): SCREAMING_SNAKE_CASE_ : Dict = version.parse("""1.11""" ) @property def lowercase_ ( self : Optional[Any])-> Mapping[str, Mapping[int, str]]: '''simple docstring''' return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ]) @property def lowercase_ ( self : Any)-> float: '''simple docstring''' return 1e-4
108
0
'''simple docstring''' import os import sys from contextlib import contextmanager # Windows only if os.name == "nt": import ctypes import msvcrt # noqa class UpperCAmelCase_ ( ctypes.Structure ): # _fields is a specific attr expected by ctypes lowerCamelCase : List[Any] = [('''size''', ctypes.c_int), ('''visible''', ctypes.c_byte)] def a_ ( ): if os.name == "nt": lowerCAmelCase = CursorInfo() lowerCAmelCase = ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(lowerCamelCase , ctypes.byref(lowerCamelCase ) ) lowerCAmelCase = False ctypes.windll.kernelaa.SetConsoleCursorInfo(lowerCamelCase , ctypes.byref(lowerCamelCase ) ) elif os.name == "posix": sys.stdout.write('\033[?25l' ) sys.stdout.flush() def a_ ( ): if os.name == "nt": lowerCAmelCase = CursorInfo() lowerCAmelCase = ctypes.windll.kernelaa.GetStdHandle(-11 ) ctypes.windll.kernelaa.GetConsoleCursorInfo(lowerCamelCase , ctypes.byref(lowerCamelCase ) ) lowerCAmelCase = True ctypes.windll.kernelaa.SetConsoleCursorInfo(lowerCamelCase , ctypes.byref(lowerCamelCase ) ) elif os.name == "posix": sys.stdout.write('\033[?25h' ) sys.stdout.flush() @contextmanager def a_ ( ): try: hide_cursor() yield finally: show_cursor()
4
import datasets from .evaluate import evaluate _A : Optional[int] = '\\n@inproceedings{Rajpurkar2016SQuAD10,\n title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text},\n author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang},\n booktitle={EMNLP},\n year={2016}\n}\n' _A : int = '\nThis metric wrap the official scoring script for version 1 of the Stanford Question Answering Dataset (SQuAD).\n\nStanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by\ncrowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,\nfrom the corresponding reading passage, or the question might be unanswerable.\n' _A : int = '\nComputes SQuAD scores (F1 and EM).\nArgs:\n predictions: List of question-answers dictionaries with the following key-values:\n - \'id\': id of the question-answer pair as given in the references (see below)\n - \'prediction_text\': the text of the answer\n references: List of question-answers dictionaries with the following key-values:\n - \'id\': id of the question-answer pair (see above),\n - \'answers\': a Dict in the SQuAD dataset format\n {\n \'text\': list of possible texts for the answer, as a list of strings\n \'answer_start\': list of start positions for the answer, as a list of ints\n }\n Note that answer_start values are not taken into account to compute the metric.\nReturns:\n \'exact_match\': Exact match (the normalized answer exactly match the gold answer)\n \'f1\': The F-score of predicted tokens versus the gold answer\nExamples:\n\n >>> predictions = [{\'prediction_text\': \'1976\', \'id\': \'56e10a3be3433e1400422b22\'}]\n >>> references = [{\'answers\': {\'answer_start\': [97], \'text\': [\'1976\']}, \'id\': \'56e10a3be3433e1400422b22\'}]\n >>> squad_metric = datasets.load_metric("squad")\n >>> results = squad_metric.compute(predictions=predictions, references=references)\n >>> print(results)\n {\'exact_match\': 100.0, \'f1\': 100.0}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION ,_KWARGS_DESCRIPTION ) class __SCREAMING_SNAKE_CASE ( datasets.Metric ): def __lowerCamelCase ( self : Optional[Any] ) ->List[Any]: 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 : Dict , A : Tuple , A : Tuple ) ->int: lowerCamelCase__ : Optional[Any] = {prediction['''id''']: prediction['''prediction_text'''] for prediction in predictions} lowerCamelCase__ : int = [ { '''paragraphs''': [ { '''qas''': [ { '''answers''': [{'''text''': answer_text} for answer_text in ref['''answers''']['''text''']], '''id''': ref['''id'''], } for ref in references ] } ] } ] lowerCamelCase__ : Tuple = evaluate(dataset=A , predictions=A ) return score
142
0
import math import numpy as np import qiskit from qiskit import Aer, ClassicalRegister, QuantumCircuit, QuantumRegister, execute def snake_case_ ( snake_case = 3 ) -> qiskit.result.counts.Counts: if isinstance(snake_case , snake_case ): raise TypeError('number of qubits must be a integer.' ) if number_of_qubits <= 0: raise ValueError('number of qubits must be > 0.' ) if math.floor(snake_case ) != number_of_qubits: raise ValueError('number of qubits must be exact integer.' ) if number_of_qubits > 10: raise ValueError('number of qubits too large to simulate(>10).' ) lowercase__: str = QuantumRegister(snake_case , 'qr' ) lowercase__: str = ClassicalRegister(snake_case , 'cr' ) lowercase__: List[Any] = QuantumCircuit(snake_case , snake_case ) lowercase__: int = number_of_qubits for i in range(snake_case ): quantum_circuit.h(number_of_qubits - i - 1 ) counter -= 1 for j in range(snake_case ): quantum_circuit.cp(np.pi / 2 ** (counter - j) , snake_case , snake_case ) for k in range(number_of_qubits // 2 ): quantum_circuit.swap(snake_case , number_of_qubits - k - 1 ) # measure all the qubits quantum_circuit.measure(snake_case , snake_case ) # simulate with 10000 shots lowercase__: str = Aer.get_backend('qasm_simulator' ) lowercase__: Union[str, Any] = execute(snake_case , snake_case , shots=1_00_00 ) return job.result().get_counts(snake_case ) if __name__ == "__main__": print( F'''Total count for quantum fourier transform state is: \ {quantum_fourier_transform(3)}''' )
366
from collections import deque from math import floor from random import random from time import time class __a : def __init__( self ) -> Dict: '''simple docstring''' lowercase__: Dict = {} def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=1 ) -> Optional[int]: '''simple docstring''' if self.graph.get(lowerCAmelCase__ ): if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: lowercase__: int = [[w, v]] if not self.graph.get(lowerCAmelCase__ ): lowercase__: Union[str, Any] = [] def SCREAMING_SNAKE_CASE__ ( self ) -> Any: '''simple docstring''' return list(self.graph ) def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> Optional[int]: '''simple docstring''' if self.graph.get(lowerCAmelCase__ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(lowerCAmelCase__ ) def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__=-2 , lowerCAmelCase__=-1 ) -> Union[str, Any]: '''simple docstring''' if s == d: return [] lowercase__: Tuple = [] lowercase__: Tuple = [] if s == -2: lowercase__: Any = list(self.graph )[0] stack.append(lowerCAmelCase__ ) visited.append(lowerCAmelCase__ ) lowercase__: Dict = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowercase__: Dict = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(lowerCAmelCase__ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) lowercase__: Union[str, Any] = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(lowerCAmelCase__ ) != 0: lowercase__: Optional[int] = stack[len(lowerCAmelCase__ ) - 1] else: lowercase__: Dict = ss # check if se have reached the starting point if len(lowerCAmelCase__ ) == 0: return visited def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__=-1 ) -> List[str]: '''simple docstring''' if c == -1: lowercase__: int = floor(random() * 10_000 ) + 10 for i in range(lowerCAmelCase__ ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): lowercase__: str = floor(random() * c ) + 1 if n != i: self.add_pair(lowerCAmelCase__ , lowerCAmelCase__ , 1 ) def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__=-2 ) -> Dict: '''simple docstring''' lowercase__: int = deque() lowercase__: Dict = [] if s == -2: lowercase__: Optional[int] = list(self.graph )[0] d.append(lowerCAmelCase__ ) visited.append(lowerCAmelCase__ ) while d: lowercase__: str = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ ) -> Dict: '''simple docstring''' lowercase__: Tuple = 0 for x in self.graph: for y in self.graph[x]: if y[1] == u: count += 1 return count def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ ) -> Union[str, Any]: '''simple docstring''' return len(self.graph[u] ) def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__=-2 ) -> Optional[Any]: '''simple docstring''' lowercase__: Tuple = [] lowercase__: str = [] if s == -2: lowercase__: Dict = list(self.graph )[0] stack.append(lowerCAmelCase__ ) visited.append(lowerCAmelCase__ ) lowercase__: List[Any] = s lowercase__: Any = [] while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowercase__: List[str] = s for node in self.graph[s]: if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowercase__: Dict = node[1] break # check if all the children are visited if s == ss: sorted_nodes.append(stack.pop() ) if len(lowerCAmelCase__ ) != 0: lowercase__: int = stack[len(lowerCAmelCase__ ) - 1] else: lowercase__: Optional[int] = ss # check if se have reached the starting point if len(lowerCAmelCase__ ) == 0: return sorted_nodes def SCREAMING_SNAKE_CASE__ ( self ) -> Any: '''simple docstring''' lowercase__: List[Any] = [] lowercase__: int = [] lowercase__: List[str] = list(self.graph )[0] stack.append(lowerCAmelCase__ ) visited.append(lowerCAmelCase__ ) lowercase__: Dict = -2 lowercase__: Union[str, Any] = [] lowercase__: List[str] = s lowercase__: Dict = False lowercase__: Union[str, Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowercase__: Any = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowercase__: List[Any] = len(lowerCAmelCase__ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowercase__: Union[str, Any] = node[1] break # check if all the children are visited if s == ss: stack.pop() lowercase__: Any = True if len(lowerCAmelCase__ ) != 0: lowercase__: Optional[Any] = stack[len(lowerCAmelCase__ ) - 1] else: lowercase__: Union[str, Any] = False indirect_parents.append(lowerCAmelCase__ ) lowercase__: int = s lowercase__: str = ss # check if se have reached the starting point if len(lowerCAmelCase__ ) == 0: return list(lowerCAmelCase__ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]: '''simple docstring''' lowercase__: Any = [] lowercase__: int = [] lowercase__: Dict = list(self.graph )[0] stack.append(lowerCAmelCase__ ) visited.append(lowerCAmelCase__ ) lowercase__: Optional[int] = -2 lowercase__: List[Any] = [] lowercase__: List[str] = s lowercase__: List[Any] = False lowercase__: str = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowercase__: Dict = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowercase__: Any = len(lowerCAmelCase__ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowercase__: List[Any] = node[1] break # check if all the children are visited if s == ss: stack.pop() lowercase__: Optional[Any] = True if len(lowerCAmelCase__ ) != 0: lowercase__: Any = stack[len(lowerCAmelCase__ ) - 1] else: lowercase__: Optional[Any] = False indirect_parents.append(lowerCAmelCase__ ) lowercase__: Dict = s lowercase__: Dict = ss # check if se have reached the starting point if len(lowerCAmelCase__ ) == 0: return False def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__=-2 , lowerCAmelCase__=-1 ) -> Dict: '''simple docstring''' lowercase__: Union[str, Any] = time() self.dfs(lowerCAmelCase__ , lowerCAmelCase__ ) lowercase__: Optional[Any] = time() return end - begin def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__=-2 ) -> List[str]: '''simple docstring''' lowercase__: str = time() self.bfs(lowerCAmelCase__ ) lowercase__: List[str] = time() return end - begin class __a : def __init__( self ) -> Tuple: '''simple docstring''' lowercase__: Dict = {} def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__=1 ) -> List[Any]: '''simple docstring''' # check if the u exists if self.graph.get(lowerCAmelCase__ ): # if there already is a edge if self.graph[u].count([w, v] ) == 0: self.graph[u].append([w, v] ) else: # if u does not exist lowercase__: str = [[w, v]] # add the other way if self.graph.get(lowerCAmelCase__ ): # if there already is a edge if self.graph[v].count([w, u] ) == 0: self.graph[v].append([w, u] ) else: # if u does not exist lowercase__: Union[str, Any] = [[w, u]] def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ , lowerCAmelCase__ ) -> str: '''simple docstring''' if self.graph.get(lowerCAmelCase__ ): for _ in self.graph[u]: if _[1] == v: self.graph[u].remove(lowerCAmelCase__ ) # the other way round if self.graph.get(lowerCAmelCase__ ): for _ in self.graph[v]: if _[1] == u: self.graph[v].remove(lowerCAmelCase__ ) def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__=-2 , lowerCAmelCase__=-1 ) -> List[str]: '''simple docstring''' if s == d: return [] lowercase__: str = [] lowercase__: int = [] if s == -2: lowercase__: Tuple = list(self.graph )[0] stack.append(lowerCAmelCase__ ) visited.append(lowerCAmelCase__ ) lowercase__: int = s while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowercase__: int = s for node in self.graph[s]: if visited.count(node[1] ) < 1: if node[1] == d: visited.append(lowerCAmelCase__ ) return visited else: stack.append(node[1] ) visited.append(node[1] ) lowercase__: List[Any] = node[1] break # check if all the children are visited if s == ss: stack.pop() if len(lowerCAmelCase__ ) != 0: lowercase__: Union[str, Any] = stack[len(lowerCAmelCase__ ) - 1] else: lowercase__: Optional[Any] = ss # check if se have reached the starting point if len(lowerCAmelCase__ ) == 0: return visited def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__=-1 ) -> Optional[Any]: '''simple docstring''' if c == -1: lowercase__: Any = floor(random() * 10_000 ) + 10 for i in range(lowerCAmelCase__ ): # every vertex has max 100 edges for _ in range(floor(random() * 102 ) + 1 ): lowercase__: Optional[Any] = floor(random() * c ) + 1 if n != i: self.add_pair(lowerCAmelCase__ , lowerCAmelCase__ , 1 ) def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__=-2 ) -> List[Any]: '''simple docstring''' lowercase__: str = deque() lowercase__: List[Any] = [] if s == -2: lowercase__: str = list(self.graph )[0] d.append(lowerCAmelCase__ ) visited.append(lowerCAmelCase__ ) while d: lowercase__: Union[str, Any] = d.popleft() if len(self.graph[s] ) != 0: for node in self.graph[s]: if visited.count(node[1] ) < 1: d.append(node[1] ) visited.append(node[1] ) return visited def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__ ) -> List[Any]: '''simple docstring''' return len(self.graph[u] ) def SCREAMING_SNAKE_CASE__ ( self ) -> str: '''simple docstring''' lowercase__: str = [] lowercase__: Dict = [] lowercase__: Optional[int] = list(self.graph )[0] stack.append(lowerCAmelCase__ ) visited.append(lowerCAmelCase__ ) lowercase__: Dict = -2 lowercase__: Dict = [] lowercase__: List[Any] = s lowercase__: Union[str, Any] = False lowercase__: List[str] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowercase__: Optional[int] = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowercase__: Any = len(lowerCAmelCase__ ) - 1 while len_stack >= 0: if stack[len_stack] == node[1]: anticipating_nodes.add(node[1] ) break else: anticipating_nodes.add(stack[len_stack] ) len_stack -= 1 if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowercase__: List[str] = node[1] break # check if all the children are visited if s == ss: stack.pop() lowercase__: str = True if len(lowerCAmelCase__ ) != 0: lowercase__: Dict = stack[len(lowerCAmelCase__ ) - 1] else: lowercase__: int = False indirect_parents.append(lowerCAmelCase__ ) lowercase__: Tuple = s lowercase__: List[Any] = ss # check if se have reached the starting point if len(lowerCAmelCase__ ) == 0: return list(lowerCAmelCase__ ) def SCREAMING_SNAKE_CASE__ ( self ) -> Any: '''simple docstring''' lowercase__: Tuple = [] lowercase__: Optional[int] = [] lowercase__: Optional[Any] = list(self.graph )[0] stack.append(lowerCAmelCase__ ) visited.append(lowerCAmelCase__ ) lowercase__: Tuple = -2 lowercase__: Any = [] lowercase__: int = s lowercase__: Optional[int] = False lowercase__: List[Any] = set() while True: # check if there is any non isolated nodes if len(self.graph[s] ) != 0: lowercase__: Optional[int] = s for node in self.graph[s]: if ( visited.count(node[1] ) > 0 and node[1] != parent and indirect_parents.count(node[1] ) > 0 and not on_the_way_back ): lowercase__: Union[str, Any] = len(lowerCAmelCase__ ) - 1 while len_stack_minus_one >= 0: if stack[len_stack_minus_one] == node[1]: anticipating_nodes.add(node[1] ) break else: return True if visited.count(node[1] ) < 1: stack.append(node[1] ) visited.append(node[1] ) lowercase__: Any = node[1] break # check if all the children are visited if s == ss: stack.pop() lowercase__: List[str] = True if len(lowerCAmelCase__ ) != 0: lowercase__: List[str] = stack[len(lowerCAmelCase__ ) - 1] else: lowercase__: Dict = False indirect_parents.append(lowerCAmelCase__ ) lowercase__: Optional[Any] = s lowercase__: Optional[int] = ss # check if se have reached the starting point if len(lowerCAmelCase__ ) == 0: return False def SCREAMING_SNAKE_CASE__ ( self ) -> List[Any]: '''simple docstring''' return list(self.graph ) def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__=-2 , lowerCAmelCase__=-1 ) -> Union[str, Any]: '''simple docstring''' lowercase__: Dict = time() self.dfs(lowerCAmelCase__ , lowerCAmelCase__ ) lowercase__: List[Any] = time() return end - begin def SCREAMING_SNAKE_CASE__ ( self , lowerCAmelCase__=-2 ) -> List[Any]: '''simple docstring''' lowercase__: str = time() self.bfs(lowerCAmelCase__ ) lowercase__: List[str] = time() return end - begin
288
0
'''simple docstring''' import copy from collections import OrderedDict from typing import Dict, Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging from ..auto import CONFIG_MAPPING lowerCAmelCase__ = logging.get_logger(__name__) lowerCAmelCase__ = { '''facebook/detr-resnet-50''': '''https://huggingface.co/facebook/detr-resnet-50/resolve/main/config.json''', # See all DETR models at https://huggingface.co/models?filter=detr } class lowercase_ (lowerCamelCase__ ): """simple docstring""" SCREAMING_SNAKE_CASE : Dict = 'detr' SCREAMING_SNAKE_CASE : List[Any] = ['past_key_values'] SCREAMING_SNAKE_CASE : Optional[int] = { 'hidden_size': 'd_model', 'num_attention_heads': 'encoder_attention_heads', } def __init__( self : Tuple ,lowercase__ : int=True ,lowercase__ : Union[str, Any]=None ,lowercase__ : Optional[Any]=3 ,lowercase__ : Optional[Any]=1_0_0 ,lowercase__ : Optional[Any]=6 ,lowercase__ : Optional[int]=2_0_4_8 ,lowercase__ : List[str]=8 ,lowercase__ : Optional[int]=6 ,lowercase__ : Dict=2_0_4_8 ,lowercase__ : List[Any]=8 ,lowercase__ : Optional[int]=0.0 ,lowercase__ : str=0.0 ,lowercase__ : List[str]=True ,lowercase__ : Union[str, Any]="relu" ,lowercase__ : List[str]=2_5_6 ,lowercase__ : Optional[int]=0.1 ,lowercase__ : Tuple=0.0 ,lowercase__ : str=0.0 ,lowercase__ : Dict=0.0_2 ,lowercase__ : Tuple=1.0 ,lowercase__ : List[str]=False ,lowercase__ : Optional[int]="sine" ,lowercase__ : Any="resnet50" ,lowercase__ : str=True ,lowercase__ : Any=False ,lowercase__ : Tuple=1 ,lowercase__ : Optional[int]=5 ,lowercase__ : Any=2 ,lowercase__ : Union[str, Any]=1 ,lowercase__ : Dict=1 ,lowercase__ : List[str]=5 ,lowercase__ : int=2 ,lowercase__ : Union[str, Any]=0.1 ,**lowercase__ : Tuple ,): if backbone_config is not None and use_timm_backbone: raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.''' ) if not use_timm_backbone: if backbone_config is None: logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' ) __lowercase = CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''] ) elif isinstance(lowercase__ ,lowercase__ ): __lowercase = backbone_config.get('''model_type''' ) __lowercase = CONFIG_MAPPING[backbone_model_type] __lowercase = config_class.from_dict(lowercase__ ) # set timm attributes to None __lowercase , __lowercase , __lowercase = None, None, None __lowercase = use_timm_backbone __lowercase = backbone_config __lowercase = num_channels __lowercase = num_queries __lowercase = d_model __lowercase = encoder_ffn_dim __lowercase = encoder_layers __lowercase = encoder_attention_heads __lowercase = decoder_ffn_dim __lowercase = decoder_layers __lowercase = decoder_attention_heads __lowercase = dropout __lowercase = attention_dropout __lowercase = activation_dropout __lowercase = activation_function __lowercase = init_std __lowercase = init_xavier_std __lowercase = encoder_layerdrop __lowercase = decoder_layerdrop __lowercase = encoder_layers __lowercase = auxiliary_loss __lowercase = position_embedding_type __lowercase = backbone __lowercase = use_pretrained_backbone __lowercase = dilation # Hungarian matcher __lowercase = class_cost __lowercase = bbox_cost __lowercase = giou_cost # Loss coefficients __lowercase = mask_loss_coefficient __lowercase = dice_loss_coefficient __lowercase = bbox_loss_coefficient __lowercase = giou_loss_coefficient __lowercase = eos_coefficient super().__init__(is_encoder_decoder=lowercase__ ,**lowercase__ ) @property def SCREAMING_SNAKE_CASE ( self : Tuple ): return self.encoder_attention_heads @property def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): return self.d_model @classmethod def SCREAMING_SNAKE_CASE ( cls : List[str] ,lowercase__ : PretrainedConfig ,**lowercase__ : int ): return cls(backbone_config=lowercase__ ,**lowercase__ ) def SCREAMING_SNAKE_CASE ( self : Any ): __lowercase = copy.deepcopy(self.__dict__ ) if output["backbone_config"] is not None: __lowercase = self.backbone_config.to_dict() __lowercase = self.__class__.model_type return output class lowercase_ (lowerCamelCase__ ): """simple docstring""" SCREAMING_SNAKE_CASE : int = version.parse('1.11' ) @property def SCREAMING_SNAKE_CASE ( self : List[str] ): return OrderedDict( [ ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}), ('''pixel_mask''', {0: '''batch'''}), ] ) @property def SCREAMING_SNAKE_CASE ( self : Optional[int] ): return 1e-5 @property def SCREAMING_SNAKE_CASE ( self : Any ): return 1_2
104
'''simple docstring''' import inspect import math import tempfile import unittest import numpy as np from transformers import ViTMAEConfig 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 ViTMAEForPreTraining, ViTMAEModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class lowercase_ : """simple docstring""" def __init__( self : str ,lowercase__ : Tuple ,lowercase__ : Dict=1_3 ,lowercase__ : List[str]=3_0 ,lowercase__ : Tuple=2 ,lowercase__ : Optional[int]=3 ,lowercase__ : List[str]=True ,lowercase__ : Tuple=True ,lowercase__ : int=3_2 ,lowercase__ : List[str]=5 ,lowercase__ : Tuple=4 ,lowercase__ : Any=3_7 ,lowercase__ : Any="gelu" ,lowercase__ : Union[str, Any]=0.1 ,lowercase__ : Optional[int]=0.1 ,lowercase__ : str=1_0 ,lowercase__ : Optional[int]=0.0_2 ,lowercase__ : Union[str, Any]=3 ,lowercase__ : Optional[int]=0.6 ,lowercase__ : List[Any]=None ,): __lowercase = parent __lowercase = batch_size __lowercase = image_size __lowercase = patch_size __lowercase = num_channels __lowercase = is_training __lowercase = use_labels __lowercase = hidden_size __lowercase = num_hidden_layers __lowercase = num_attention_heads __lowercase = intermediate_size __lowercase = hidden_act __lowercase = hidden_dropout_prob __lowercase = attention_probs_dropout_prob __lowercase = type_sequence_label_size __lowercase = initializer_range __lowercase = mask_ratio __lowercase = scope # in ViTMAE, the expected sequence length = (num_patches + 1) * (1 - config.mask_ratio), rounded above # (we add 1 for the [CLS] token) __lowercase = (image_size // patch_size) ** 2 __lowercase = int(math.ceil((1 - mask_ratio) * (num_patches + 1) ) ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): __lowercase = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __lowercase = None if self.use_labels: __lowercase = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) __lowercase = self.get_config() return config, pixel_values, labels def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): return ViTMAEConfig( 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=lowercase__ ,initializer_range=self.initializer_range ,mask_ratio=self.mask_ratio ,) def SCREAMING_SNAKE_CASE ( self : List[Any] ,lowercase__ : str ,lowercase__ : Optional[int] ,lowercase__ : List[str] ): __lowercase = ViTMAEModel(config=lowercase__ ) model.to(lowercase__ ) model.eval() __lowercase = model(lowercase__ ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def SCREAMING_SNAKE_CASE ( self : Any ,lowercase__ : List[Any] ,lowercase__ : int ,lowercase__ : Optional[Any] ): __lowercase = ViTMAEForPreTraining(lowercase__ ) model.to(lowercase__ ) model.eval() __lowercase = model(lowercase__ ) __lowercase = (self.image_size // self.patch_size) ** 2 __lowercase = self.patch_size**2 * self.num_channels self.parent.assertEqual(result.logits.shape ,(self.batch_size, num_patches, expected_num_channels) ) # test greyscale images __lowercase = 1 __lowercase = ViTMAEForPreTraining(lowercase__ ) model.to(lowercase__ ) model.eval() __lowercase = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) __lowercase = model(lowercase__ ) __lowercase = self.patch_size**2 self.parent.assertEqual(result.logits.shape ,(self.batch_size, num_patches, expected_num_channels) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): __lowercase = self.prepare_config_and_inputs() __lowercase , __lowercase , __lowercase = config_and_inputs __lowercase = {'''pixel_values''': pixel_values} return config, inputs_dict @require_torch class lowercase_ (lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): """simple docstring""" SCREAMING_SNAKE_CASE : str = (ViTMAEModel, ViTMAEForPreTraining) if is_torch_available() else () SCREAMING_SNAKE_CASE : Dict = {'feature-extraction': ViTMAEModel} if is_torch_available() else {} SCREAMING_SNAKE_CASE : Any = False SCREAMING_SNAKE_CASE : Optional[int] = False SCREAMING_SNAKE_CASE : List[str] = False SCREAMING_SNAKE_CASE : Union[str, Any] = False def SCREAMING_SNAKE_CASE ( self : int ): __lowercase = ViTMAEModelTester(self ) __lowercase = ConfigTester(self ,config_class=lowercase__ ,has_text_modality=lowercase__ ,hidden_size=3_7 ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ): self.config_tester.run_common_tests() @unittest.skip(reason='''ViTMAE does not use inputs_embeds''' ) def SCREAMING_SNAKE_CASE ( self : Any ): pass def SCREAMING_SNAKE_CASE ( self : Tuple ): __lowercase , __lowercase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowercase = model_class(lowercase__ ) self.assertIsInstance(model.get_input_embeddings() ,(nn.Module) ) __lowercase = model.get_output_embeddings() self.assertTrue(x is None or isinstance(lowercase__ ,nn.Linear ) ) def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): __lowercase , __lowercase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowercase = model_class(lowercase__ ) __lowercase = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __lowercase = [*signature.parameters.keys()] __lowercase = ['''pixel_values'''] self.assertListEqual(arg_names[:1] ,lowercase__ ) def SCREAMING_SNAKE_CASE ( self : List[Any] ): __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*lowercase__ ) def SCREAMING_SNAKE_CASE ( self : Any ): __lowercase = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*lowercase__ ) def SCREAMING_SNAKE_CASE ( self : Any ,lowercase__ : Optional[int] ,lowercase__ : List[str] ,lowercase__ : Optional[Any] ): # make masks reproducible np.random.seed(2 ) __lowercase = int((pt_model.config.image_size // pt_model.config.patch_size) ** 2 ) __lowercase = np.random.uniform(size=(self.model_tester.batch_size, num_patches) ) __lowercase = torch.from_numpy(lowercase__ ) # Add `noise` argument. # PT inputs will be prepared in `super().check_pt_tf_models()` with this added `noise` argument __lowercase = pt_noise super().check_pt_tf_models(lowercase__ ,lowercase__ ,lowercase__ ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): __lowercase , __lowercase = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __lowercase = model_class(lowercase__ ) model.to(lowercase__ ) model.eval() # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): __lowercase = model(**self._prepare_for_class(lowercase__ ,lowercase__ ) ) __lowercase = outputs[0].cpu().numpy() __lowercase = 0 with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(lowercase__ ) __lowercase = model_class.from_pretrained(lowercase__ ) model.to(lowercase__ ) # make random mask reproducible torch.manual_seed(2 ) with torch.no_grad(): __lowercase = model(**self._prepare_for_class(lowercase__ ,lowercase__ ) ) # Make sure we don't have nans __lowercase = after_outputs[0].cpu().numpy() __lowercase = 0 __lowercase = np.amax(np.abs(out_a - out_a ) ) self.assertLessEqual(lowercase__ ,1e-5 ) @unittest.skip( reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.''' ) def SCREAMING_SNAKE_CASE ( self : Tuple ): pass @unittest.skip( reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.''' ) def SCREAMING_SNAKE_CASE ( self : int ): pass @unittest.skip( reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load to get deterministic results.''' ) def SCREAMING_SNAKE_CASE ( self : Any ): pass @unittest.skip(reason='''ViTMAE returns a random mask + ids_restore in each forward pass. See test_save_load''' ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ): pass @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' ) def SCREAMING_SNAKE_CASE ( self : Any ): pass @slow def SCREAMING_SNAKE_CASE ( self : Optional[Any] ): for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __lowercase = ViTMAEModel.from_pretrained(lowercase__ ) self.assertIsNotNone(lowercase__ ) def _A ( ): """simple docstring""" __lowercase = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' ) return image @require_torch @require_vision class lowercase_ (unittest.TestCase ): """simple docstring""" @cached_property def SCREAMING_SNAKE_CASE ( self : str ): return ViTImageProcessor.from_pretrained('''facebook/vit-mae-base''' ) if is_vision_available() else None @slow def SCREAMING_SNAKE_CASE ( self : str ): # make random mask reproducible across the PT and TF model np.random.seed(2 ) __lowercase = ViTMAEForPreTraining.from_pretrained('''facebook/vit-mae-base''' ).to(lowercase__ ) __lowercase = self.default_image_processor __lowercase = prepare_img() __lowercase = image_processor(images=lowercase__ ,return_tensors='''pt''' ).to(lowercase__ ) # prepare a noise vector that will be also used for testing the TF model # (this way we can ensure that the PT and TF models operate on the same inputs) __lowercase = ViTMAEConfig() __lowercase = int((vit_mae_config.image_size // vit_mae_config.patch_size) ** 2 ) __lowercase = np.random.uniform(size=(1, num_patches) ) # forward pass with torch.no_grad(): __lowercase = model(**lowercase__ ,noise=torch.from_numpy(lowercase__ ).to(device=lowercase__ ) ) # verify the logits __lowercase = torch.Size((1, 1_9_6, 7_6_8) ) self.assertEqual(outputs.logits.shape ,lowercase__ ) __lowercase = torch.tensor( [[-0.0_5_4_8, -1.7_0_2_3, -0.9_3_2_5], [0.3_7_2_1, -0.5_6_7_0, -0.2_2_3_3], [0.8_2_3_5, -1.3_8_7_8, -0.3_5_2_4]] ) self.assertTrue(torch.allclose(outputs.logits[0, :3, :3] ,expected_slice.to(lowercase__ ) ,atol=1e-4 ) )
104
1
import os import tempfile import unittest import uuid from pathlib import Path from transformers.testing_utils import get_tests_dir, require_soundfile, require_torch, require_vision from transformers.tools.agent_types import AgentAudio, AgentImage, AgentText from transformers.utils import is_soundfile_availble, is_torch_available, is_vision_available if is_torch_available(): import torch if is_soundfile_availble(): import soundfile as sf if is_vision_available(): from PIL import Image def SCREAMING_SNAKE_CASE ( __UpperCamelCase="") -> str: a = tempfile.mkdtemp() return os.path.join(__UpperCamelCase , str(uuid.uuida()) + suffix) @require_soundfile @require_torch class a__ ( unittest.TestCase ): def lowerCAmelCase_ ( self ) -> Any: '''simple docstring''' a = torch.rand(12 , dtype=torch.floataa ) - 0.5 a = AgentAudio(A ) a = str(agent_type.to_string() ) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(A , agent_type.to_raw() , atol=1e-4 ) ) del agent_type # Ensure the path remains even after the object deletion self.assertTrue(os.path.exists(A ) ) # Ensure that the file contains the same value as the original tensor a , a = sf.read(A ) self.assertTrue(torch.allclose(A , torch.tensor(A ) , atol=1e-4 ) ) def lowerCAmelCase_ ( self ) -> str: '''simple docstring''' a = torch.rand(12 , dtype=torch.floataa ) - 0.5 a = get_new_path(suffix=".wav" ) sf.write(A , A , 16000 ) a = AgentAudio(A ) self.assertTrue(torch.allclose(A , agent_type.to_raw() , atol=1e-4 ) ) self.assertEqual(agent_type.to_string() , A ) @require_vision @require_torch class a__ ( unittest.TestCase ): def lowerCAmelCase_ ( self ) -> Tuple: '''simple docstring''' a = torch.randint(0 , 256 , (64, 64, 3) ) a = AgentImage(A ) a = str(agent_type.to_string() ) # Ensure that the tensor and the agent_type's tensor are the same self.assertTrue(torch.allclose(A , agent_type._tensor , atol=1e-4 ) ) self.assertIsInstance(agent_type.to_raw() , Image.Image ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(A ) ) def lowerCAmelCase_ ( self ) -> Union[str, Any]: '''simple docstring''' a = Path(get_tests_dir("fixtures/tests_samples/COCO" ) ) / "000000039769.png" a = Image.open(A ) a = AgentImage(A ) self.assertTrue(path.samefile(agent_type.to_string() ) ) self.assertTrue(image == agent_type.to_raw() ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(A ) ) def lowerCAmelCase_ ( self ) -> Dict: '''simple docstring''' a = Path(get_tests_dir("fixtures/tests_samples/COCO" ) ) / "000000039769.png" a = Image.open(A ) a = AgentImage(A ) self.assertFalse(path.samefile(agent_type.to_string() ) ) self.assertTrue(image == agent_type.to_raw() ) # Ensure the path remains even after the object deletion del agent_type self.assertTrue(os.path.exists(A ) ) class a__ ( unittest.TestCase ): def lowerCAmelCase_ ( self ) -> Tuple: '''simple docstring''' a = "Hey!" a = AgentText(A ) self.assertEqual(A , agent_type.to_string() ) self.assertEqual(A , agent_type.to_raw() ) self.assertEqual(A , A )
180
lowercase__ : List[Any] = { "a": "AAAAA", "b": "AAAAB", "c": "AAABA", "d": "AAABB", "e": "AABAA", "f": "AABAB", "g": "AABBA", "h": "AABBB", "i": "ABAAA", "j": "BBBAA", "k": "ABAAB", "l": "ABABA", "m": "ABABB", "n": "ABBAA", "o": "ABBAB", "p": "ABBBA", "q": "ABBBB", "r": "BAAAA", "s": "BAAAB", "t": "BAABA", "u": "BAABB", "v": "BBBAB", "w": "BABAA", "x": "BABAB", "y": "BABBA", "z": "BABBB", " ": " ", } lowercase__ : str = {value: key for key, value in encode_dict.items()} def SCREAMING_SNAKE_CASE ( __UpperCamelCase) -> str: a = "" for letter in word.lower(): if letter.isalpha() or letter == " ": encoded += encode_dict[letter] else: raise Exception("encode() accepts only letters of the alphabet and spaces") return encoded def SCREAMING_SNAKE_CASE ( __UpperCamelCase) -> str: if set(__UpperCamelCase) - {"A", "B", " "} != set(): raise Exception("decode() accepts only 'A', 'B' and spaces") a = "" for word in coded.split(): while len(__UpperCamelCase) != 0: decoded += decode_dict[word[:5]] a = word[5:] decoded += " " return decoded.strip() if __name__ == "__main__": from doctest import testmod testmod()
180
1
import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor a_ = logging.get_logger(__name__) class _lowercase ( snake_case_ ): def __init__( self : Union[str, Any] , *snake_case : Tuple , **snake_case : List[str] ) -> None: """simple docstring""" warnings.warn( 'The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please' ' use DeiTImageProcessor instead.' , snake_case , ) super().__init__(*snake_case , **snake_case )
175
def __lowercase ( lowerCamelCase : str , lowerCamelCase : str ): def get_matched_characters(lowerCamelCase : str , lowerCamelCase : str ) -> str: UpperCamelCase_ : Tuple = [] UpperCamelCase_ : List[Any] = min(len(_stra ) , len(_stra ) ) // 2 for i, l in enumerate(_stra ): UpperCamelCase_ : int = int(max(0 , i - limit ) ) UpperCamelCase_ : Dict = int(min(i + limit + 1 , len(_stra ) ) ) if l in _stra[left:right]: matched.append(lowerCamelCase ) UpperCamelCase_ : Dict = F"{_stra[0:_stra.index(lowerCamelCase )]} {_stra[_stra.index(lowerCamelCase ) + 1:]}" return "".join(lowerCamelCase ) # matching characters UpperCamelCase_ : str = get_matched_characters(lowerCamelCase , lowerCamelCase ) UpperCamelCase_ : str = get_matched_characters(lowerCamelCase , lowerCamelCase ) UpperCamelCase_ : Union[str, Any] = len(lowerCamelCase ) # transposition UpperCamelCase_ : int = ( len([(ca, ca) for ca, ca in zip(lowerCamelCase , lowerCamelCase ) if ca != ca] ) // 2 ) if not match_count: UpperCamelCase_ : Union[str, Any] = 0.0 else: UpperCamelCase_ : str = ( 1 / 3 * ( match_count / len(lowerCamelCase ) + match_count / len(lowerCamelCase ) + (match_count - transpositions) / match_count ) ) # common prefix up to 4 characters UpperCamelCase_ : Dict = 0 for ca, ca in zip(stra[:4] , stra[:4] ): if ca == ca: prefix_len += 1 else: break return jaro + 0.1 * prefix_len * (1 - jaro) if __name__ == "__main__": import doctest doctest.testmod() print(jaro_winkler('hello', 'world'))
175
1
"""simple docstring""" from __future__ import annotations import unittest from transformers import DebertaVaConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, TFDebertaVaModel, ) class A_ : def __init__( self: Dict ,__lowerCAmelCase: Optional[Any] ,__lowerCAmelCase: Tuple=13 ,__lowerCAmelCase: List[Any]=7 ,__lowerCAmelCase: Optional[Any]=True ,__lowerCAmelCase: int=True ,__lowerCAmelCase: Union[str, Any]=True ,__lowerCAmelCase: Dict=True ,__lowerCAmelCase: Optional[int]=99 ,__lowerCAmelCase: Union[str, Any]=32 ,__lowerCAmelCase: Tuple=2 ,__lowerCAmelCase: Any=4 ,__lowerCAmelCase: List[Any]=37 ,__lowerCAmelCase: Optional[Any]="gelu" ,__lowerCAmelCase: Union[str, Any]=0.1 ,__lowerCAmelCase: str=0.1 ,__lowerCAmelCase: Dict=512 ,__lowerCAmelCase: List[Any]=16 ,__lowerCAmelCase: Union[str, Any]=2 ,__lowerCAmelCase: int=0.02 ,__lowerCAmelCase: Optional[int]=False ,__lowerCAmelCase: Any=True ,__lowerCAmelCase: List[str]="None" ,__lowerCAmelCase: Optional[int]=3 ,__lowerCAmelCase: Optional[int]=4 ,__lowerCAmelCase: Dict=None ,): '''simple docstring''' _lowerCamelCase : Dict = parent _lowerCamelCase : int = batch_size _lowerCamelCase : Union[str, Any] = seq_length _lowerCamelCase : List[str] = is_training _lowerCamelCase : List[str] = use_input_mask _lowerCamelCase : Dict = use_token_type_ids _lowerCamelCase : Optional[int] = use_labels _lowerCamelCase : List[Any] = vocab_size _lowerCamelCase : List[str] = hidden_size _lowerCamelCase : Any = num_hidden_layers _lowerCamelCase : Optional[Any] = num_attention_heads _lowerCamelCase : str = intermediate_size _lowerCamelCase : int = hidden_act _lowerCamelCase : Any = hidden_dropout_prob _lowerCamelCase : Any = attention_probs_dropout_prob _lowerCamelCase : Union[str, Any] = max_position_embeddings _lowerCamelCase : List[Any] = type_vocab_size _lowerCamelCase : List[str] = type_sequence_label_size _lowerCamelCase : Optional[Any] = initializer_range _lowerCamelCase : List[Any] = num_labels _lowerCamelCase : Any = num_choices _lowerCamelCase : Optional[int] = relative_attention _lowerCamelCase : Any = position_biased_input _lowerCamelCase : List[Any] = pos_att_type _lowerCamelCase : int = scope def _lowercase ( self: Tuple ): '''simple docstring''' _lowerCamelCase : str = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) _lowerCamelCase : List[Any] = None if self.use_input_mask: _lowerCamelCase : Dict = random_attention_mask([self.batch_size, self.seq_length] ) _lowerCamelCase : Tuple = None if self.use_token_type_ids: _lowerCamelCase : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] ,self.type_vocab_size ) _lowerCamelCase : List[Any] = None _lowerCamelCase : Dict = None _lowerCamelCase : str = None if self.use_labels: _lowerCamelCase : Union[str, Any] = ids_tensor([self.batch_size] ,self.type_sequence_label_size ) _lowerCamelCase : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] ,self.num_labels ) _lowerCamelCase : Dict = DebertaVaConfig( 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 ,relative_attention=self.relative_attention ,position_biased_input=self.position_biased_input ,initializer_range=self.initializer_range ,return_dict=__lowerCAmelCase ,) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowercase ( self: List[str] ,__lowerCAmelCase: str ,__lowerCAmelCase: Optional[Any] ,__lowerCAmelCase: List[str] ,__lowerCAmelCase: Optional[Any] ,__lowerCAmelCase: str ,__lowerCAmelCase: Dict ,__lowerCAmelCase: Optional[int] ): '''simple docstring''' _lowerCamelCase : str = TFDebertaVaModel(config=__lowerCAmelCase ) _lowerCamelCase : List[Any] = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids} _lowerCamelCase : List[str] = [input_ids, input_mask] _lowerCamelCase : int = model(__lowerCAmelCase ) _lowerCamelCase : str = model(__lowerCAmelCase ) self.parent.assertEqual(result.last_hidden_state.shape ,(self.batch_size, self.seq_length, self.hidden_size) ) def _lowercase ( self: Tuple ,__lowerCAmelCase: Tuple ,__lowerCAmelCase: Dict ,__lowerCAmelCase: List[str] ,__lowerCAmelCase: int ,__lowerCAmelCase: List[str] ,__lowerCAmelCase: Tuple ,__lowerCAmelCase: Any ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = TFDebertaVaForMaskedLM(config=__lowerCAmelCase ) _lowerCamelCase : List[Any] = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } _lowerCamelCase : List[Any] = model(__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.vocab_size) ) def _lowercase ( self: List[str] ,__lowerCAmelCase: Any ,__lowerCAmelCase: Optional[Any] ,__lowerCAmelCase: List[Any] ,__lowerCAmelCase: int ,__lowerCAmelCase: Optional[int] ,__lowerCAmelCase: List[str] ,__lowerCAmelCase: Any ): '''simple docstring''' _lowerCamelCase : Dict = self.num_labels _lowerCamelCase : str = TFDebertaVaForSequenceClassification(config=__lowerCAmelCase ) _lowerCamelCase : List[str] = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } _lowerCamelCase : Any = model(__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def _lowercase ( self: Dict ,__lowerCAmelCase: Optional[int] ,__lowerCAmelCase: str ,__lowerCAmelCase: Optional[Any] ,__lowerCAmelCase: str ,__lowerCAmelCase: Optional[Any] ,__lowerCAmelCase: List[Any] ,__lowerCAmelCase: int ): '''simple docstring''' _lowerCamelCase : Any = self.num_labels _lowerCamelCase : List[str] = TFDebertaVaForTokenClassification(config=__lowerCAmelCase ) _lowerCamelCase : Tuple = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } _lowerCamelCase : Tuple = model(__lowerCAmelCase ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.seq_length, self.num_labels) ) def _lowercase ( self: int ,__lowerCAmelCase: Dict ,__lowerCAmelCase: int ,__lowerCAmelCase: Optional[int] ,__lowerCAmelCase: List[Any] ,__lowerCAmelCase: Dict ,__lowerCAmelCase: str ,__lowerCAmelCase: Dict ): '''simple docstring''' _lowerCamelCase : str = TFDebertaVaForQuestionAnswering(config=__lowerCAmelCase ) _lowerCamelCase : Dict = { "input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids, } _lowerCamelCase : Dict = model(__lowerCAmelCase ) self.parent.assertEqual(result.start_logits.shape ,(self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape ,(self.batch_size, self.seq_length) ) def _lowercase ( self: str ): '''simple docstring''' _lowerCamelCase : List[Any] = self.prepare_config_and_inputs() ( ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ( _lowerCamelCase ), ) : List[str] = config_and_inputs _lowerCamelCase : Union[str, Any] = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_tf class A_ ( a_ , a_ , unittest.TestCase ): lowerCAmelCase__ = ( ( TFDebertaVaModel, TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, ) if is_tf_available() else () ) lowerCAmelCase__ = ( { "feature-extraction": TFDebertaVaModel, "fill-mask": TFDebertaVaForMaskedLM, "question-answering": TFDebertaVaForQuestionAnswering, "text-classification": TFDebertaVaForSequenceClassification, "token-classification": TFDebertaVaForTokenClassification, "zero-shot": TFDebertaVaForSequenceClassification, } if is_tf_available() else {} ) lowerCAmelCase__ = False lowerCAmelCase__ = False def _lowercase ( self: Tuple ): '''simple docstring''' _lowerCamelCase : Tuple = TFDebertaVaModelTester(self ) _lowerCamelCase : Tuple = ConfigTester(self ,config_class=__lowerCAmelCase ,hidden_size=37 ) def _lowercase ( self: Tuple ): '''simple docstring''' self.config_tester.run_common_tests() def _lowercase ( self: str ): '''simple docstring''' _lowerCamelCase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__lowerCAmelCase ) def _lowercase ( self: List[str] ): '''simple docstring''' _lowerCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__lowerCAmelCase ) def _lowercase ( self: Union[str, Any] ): '''simple docstring''' _lowerCamelCase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__lowerCAmelCase ) def _lowercase ( self: Any ): '''simple docstring''' _lowerCamelCase : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__lowerCAmelCase ) def _lowercase ( self: Tuple ): '''simple docstring''' _lowerCamelCase : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__lowerCAmelCase ) @slow def _lowercase ( self: Optional[Any] ): '''simple docstring''' _lowerCamelCase : str = TFDebertaVaModel.from_pretrained("kamalkraj/deberta-v2-xlarge" ) self.assertIsNotNone(__lowerCAmelCase ) @require_tf class A_ ( unittest.TestCase ): @unittest.skip(reason="Model not available yet" ) def _lowercase ( self: Tuple ): '''simple docstring''' pass @slow def _lowercase ( self: List[Any] ): '''simple docstring''' _lowerCamelCase : Any = TFDebertaVaModel.from_pretrained("kamalkraj/deberta-v2-xlarge" ) _lowerCamelCase : Optional[Any] = tf.constant([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] ) _lowerCamelCase : str = tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) _lowerCamelCase : int = model(__lowerCAmelCase ,attention_mask=__lowerCAmelCase )[0] _lowerCamelCase : Union[str, Any] = tf.constant( [[[0.23_56, 0.19_48, 0.03_69], [-0.10_63, 0.35_86, -0.51_52], [-0.63_99, -0.02_59, -0.25_25]]] ) tf.debugging.assert_near(output[:, 1:4, 1:4] ,__lowerCAmelCase ,atol=1e-4 )
350
"""simple docstring""" from collections import defaultdict def lowerCamelCase_( _lowerCamelCase ) -> int: '''simple docstring''' _lowerCamelCase : Optional[int] = 1 _lowerCamelCase : str = True for v in tree[start]: if v not in visited: ret += dfs(_lowerCamelCase ) if ret % 2 == 0: cuts.append(_lowerCamelCase ) return ret def lowerCamelCase_( ) -> int: '''simple docstring''' dfs(1 ) if __name__ == "__main__": _lowerCAmelCase , _lowerCAmelCase : Optional[Any] = 10, 9 _lowerCAmelCase : str = defaultdict(list) _lowerCAmelCase : dict[int, bool] = {} _lowerCAmelCase : list[int] = [] _lowerCAmelCase : Any = 0 _lowerCAmelCase : Any = [(2, 1), (3, 1), (4, 3), (5, 2), (6, 1), (7, 2), (8, 6), (9, 8), (10, 8)] for u, v in edges: tree[u].append(v) tree[v].append(u) even_tree() print(len(cuts) - 1)
340
0
"""simple docstring""" def lowercase ( _snake_case : Optional[Any] ) ->List[str]: """simple docstring""" __snake_case , __snake_case : List[str] = [], [] while len(_snake_case ) > 1: __snake_case , __snake_case : Optional[Any] = min(_snake_case ), max(_snake_case ) start.append(_snake_case ) end.append(_snake_case ) collection.remove(_snake_case ) collection.remove(_snake_case ) end.reverse() return start + collection + end if __name__ == "__main__": SCREAMING_SNAKE_CASE : Any = input("""Enter numbers separated by a comma:\n""").strip() SCREAMING_SNAKE_CASE : int = [int(item) for item in user_input.split(""",""")] print(*merge_sort(unsorted), sep=""",""")
102
"""simple docstring""" import unittest from transformers import BigBirdTokenizer, BigBirdTokenizerFast 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 : str = """▁""" SCREAMING_SNAKE_CASE : List[str] = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class _UpperCAmelCase ( __snake_case, unittest.TestCase ): '''simple docstring''' lowerCamelCase__ =BigBirdTokenizer lowerCamelCase__ =BigBirdTokenizerFast lowerCamelCase__ =True lowerCamelCase__ =True def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' super().setUp() __snake_case : List[Any] = self.tokenizer_class(a_ , keep_accents=a_ ) tokenizer.save_pretrained(self.tmpdirname ) def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Optional[Any] = '''<s>''' __snake_case : Optional[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 SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Dict = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<unk>''' ) self.assertEqual(vocab_keys[1] , '''<s>''' ) self.assertEqual(vocab_keys[-1] , '''[MASK]''' ) self.assertEqual(len(a_ ) , 10_04 ) def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 10_00 ) def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' if not self.test_rust_tokenizer: return __snake_case : str = self.get_tokenizer() __snake_case : Dict = self.get_rust_tokenizer() __snake_case : Dict = '''I was born in 92000, and this is falsé.''' __snake_case : int = tokenizer.tokenize(a_ ) __snake_case : str = rust_tokenizer.tokenize(a_ ) self.assertListEqual(a_ , a_ ) __snake_case : Tuple = tokenizer.encode(a_ , add_special_tokens=a_ ) __snake_case : Tuple = rust_tokenizer.encode(a_ , add_special_tokens=a_ ) self.assertListEqual(a_ , a_ ) __snake_case : Optional[Any] = self.get_rust_tokenizer() __snake_case : Optional[int] = tokenizer.encode(a_ ) __snake_case : Dict = rust_tokenizer.encode(a_ ) self.assertListEqual(a_ , a_ ) def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : List[Any] = BigBirdTokenizer(a_ , keep_accents=a_ ) __snake_case : Optional[int] = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(a_ , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(a_ ) , [2_85, 46, 10, 1_70, 3_82] , ) __snake_case : Union[str, Any] = 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''', '''é''', '''.''', ] , ) __snake_case : Tuple = tokenizer.convert_tokens_to_ids(a_ ) self.assertListEqual( a_ , [8, 21, 84, 55, 24, 19, 7, 0, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) __snake_case : Optional[Any] = 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>''', '''.''', ] , ) @cached_property def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' return BigBirdTokenizer.from_pretrained('''google/bigbird-roberta-base''' ) @slow def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : List[str] = '''Hello World!''' __snake_case : List[Any] = [65, 1_85_36, 22_60, 1_01, 66] self.assertListEqual(a_ , self.big_tokenizer.encode(a_ ) ) @slow def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Optional[Any] = ( '''This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will''' ''' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth''' ) # fmt: off __snake_case : Optional[int] = [65, 8_71, 4_19, 3_58, 9_46, 9_91, 25_21, 4_52, 3_58, 13_57, 3_87, 77_51, 35_36, 1_12, 9_85, 4_56, 1_26, 8_65, 9_38, 54_00, 57_34, 4_58, 13_68, 4_67, 7_86, 24_62, 52_46, 11_59, 6_33, 8_65, 45_19, 4_57, 5_82, 8_52, 25_57, 4_27, 9_16, 5_08, 4_05, 3_43_24, 4_97, 3_91, 4_08, 1_13_42, 12_44, 3_85, 1_00, 9_38, 9_85, 4_56, 5_74, 3_62, 1_25_97, 32_00, 31_29, 11_72, 66] # noqa: E231 # fmt: on self.assertListEqual(a_ , self.big_tokenizer.encode(a_ ) ) @require_torch @slow def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' import torch from transformers import BigBirdConfig, BigBirdModel # Build sequence __snake_case : str = list(self.big_tokenizer.get_vocab().keys() )[:10] __snake_case : Tuple = ''' '''.join(a_ ) __snake_case : Tuple = self.big_tokenizer.encode_plus(a_ , return_tensors='''pt''' , return_token_type_ids=a_ ) __snake_case : List[Any] = self.big_tokenizer.batch_encode_plus( [sequence + ''' ''' + sequence] , return_tensors='''pt''' , return_token_type_ids=a_ ) __snake_case : Optional[int] = BigBirdConfig(attention_type='''original_full''' ) __snake_case : str = BigBirdModel(a_ ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**a_ ) model(**a_ ) @slow def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : List[Any] = BigBirdTokenizer.from_pretrained('''google/bigbird-roberta-base''' ) __snake_case : Any = tokenizer.decode(tokenizer('''Paris is the [MASK].''' ).input_ids ) self.assertTrue(decoded_text == '''[CLS] Paris is the[MASK].[SEP]''' ) @slow def SCREAMING_SNAKE_CASE (self ): '''simple docstring''' __snake_case : Tuple = {'''input_ids''': [[65, 3_92_86, 4_58, 3_63_35, 20_01, 4_56, 1_30_73, 1_32_66, 4_55, 1_13, 77_46, 17_41, 1_11_57, 3_91, 1_30_73, 1_32_66, 4_55, 1_13, 39_67, 3_54_12, 1_13, 49_36, 1_09, 38_70, 23_77, 1_13, 3_00_84, 4_57_20, 4_58, 1_34, 1_74_96, 1_12, 5_03, 1_16_72, 1_13, 1_18, 1_12, 56_65, 1_33_47, 3_86_87, 1_12, 14_96, 3_13_89, 1_12, 32_68, 4_72_64, 1_34, 9_62, 1_12, 1_63_77, 80_35, 2_31_30, 4_30, 1_21_69, 1_55_18, 2_85_92, 4_58, 1_46, 4_16_97, 1_09, 3_91, 1_21_69, 1_55_18, 1_66_89, 4_58, 1_46, 4_13_58, 1_09, 4_52, 7_26, 40_34, 1_11, 7_63, 3_54_12, 50_82, 3_88, 19_03, 1_11, 90_51, 3_91, 28_70, 4_89_18, 19_00, 11_23, 5_50, 9_98, 1_12, 95_86, 1_59_85, 4_55, 3_91, 4_10, 2_29_55, 3_76_36, 1_14, 66], [65, 4_48, 1_74_96, 4_19, 36_63, 3_85, 7_63, 1_13, 2_75_33, 28_70, 32_83, 1_30_43, 16_39, 2_47_13, 5_23, 6_56, 2_40_13, 1_85_50, 25_21, 5_17, 2_70_14, 2_12_44, 4_20, 12_12, 14_65, 3_91, 9_27, 48_33, 3_88, 5_78, 1_17_86, 1_14, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [65, 4_84, 21_69, 76_87, 2_19_32, 1_81_46, 7_26, 3_63, 1_70_32, 33_91, 1_14, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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], [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]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=a_ , model_name='''google/bigbird-roberta-base''' , revision='''215c99f1600e06f83acce68422f2035b2b5c3510''' , )
102
1
"""simple docstring""" from typing import Dict import numpy as np from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException if is_tf_available(): import tensorflow as tf from ..tf_utils import stable_softmax if is_torch_available(): import torch UpperCAmelCase_ : Dict = logging.get_logger(__name__) @add_end_docstrings( lowercase__ , r''' top_k (`int`, defaults to 5): The number of predictions to return. targets (`str` or `List[str]`, *optional*): When passed, the model will limit the scores to the passed targets instead of looking up in the whole vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting token will be used (with a warning, and that might be slower). ''' , ) class SCREAMING_SNAKE_CASE__ ( lowercase__ ): def SCREAMING_SNAKE_CASE ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : GenericTensor ) -> np.ndarray: if self.framework == "tf": a_ : Optional[Any] = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy() elif self.framework == "pt": a_ : Dict = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=SCREAMING_SNAKE_CASE__ ) else: raise ValueError('Unsupported framework' ) return masked_index def SCREAMING_SNAKE_CASE ( self : str , SCREAMING_SNAKE_CASE__ : GenericTensor ) -> np.ndarray: a_ : List[str] = self.get_masked_index(SCREAMING_SNAKE_CASE__ ) a_ : Optional[Any] = np.prod(masked_index.shape ) if numel < 1: raise PipelineException( 'fill-mask' , self.model.base_model_prefix , F"""No mask_token ({self.tokenizer.mask_token}) found on the input""" , ) def SCREAMING_SNAKE_CASE ( self : Tuple , SCREAMING_SNAKE_CASE__ : GenericTensor ) -> Tuple: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): for model_input in model_inputs: self._ensure_exactly_one_mask_token(model_input['input_ids'][0] ) else: for input_ids in model_inputs["input_ids"]: self._ensure_exactly_one_mask_token(SCREAMING_SNAKE_CASE__ ) def SCREAMING_SNAKE_CASE ( self : str , SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : int=None , **SCREAMING_SNAKE_CASE__ : Tuple ) -> Dict[str, GenericTensor]: if return_tensors is None: a_ : str = self.framework a_ : Tuple = self.tokenizer(SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ ) self.ensure_exactly_one_mask_token(SCREAMING_SNAKE_CASE__ ) return model_inputs def SCREAMING_SNAKE_CASE ( self : Any , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: a_ : Dict = self.model(**SCREAMING_SNAKE_CASE__ ) a_ : List[Any] = model_inputs['input_ids'] return model_outputs def SCREAMING_SNAKE_CASE ( self : int , SCREAMING_SNAKE_CASE__ : Any , SCREAMING_SNAKE_CASE__ : str=5 , SCREAMING_SNAKE_CASE__ : Optional[int]=None ) -> Optional[Any]: # Cap top_k if there are targets if target_ids is not None and target_ids.shape[0] < top_k: a_ : str = target_ids.shape[0] a_ : Dict = model_outputs['input_ids'][0] a_ : Tuple = model_outputs['logits'] if self.framework == "tf": a_ : Tuple = tf.where(input_ids == self.tokenizer.mask_token_id ).numpy()[:, 0] a_ : Any = outputs.numpy() a_ : Tuple = outputs[0, masked_index, :] a_ : List[Any] = stable_softmax(SCREAMING_SNAKE_CASE__ , axis=-1 ) if target_ids is not None: a_ : List[Any] = tf.gather_nd(tf.squeeze(SCREAMING_SNAKE_CASE__ , 0 ) , target_ids.reshape(-1 , 1 ) ) a_ : Tuple = tf.expand_dims(SCREAMING_SNAKE_CASE__ , 0 ) a_ : Dict = tf.math.top_k(SCREAMING_SNAKE_CASE__ , k=SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = topk.values.numpy(), topk.indices.numpy() else: a_ : Dict = torch.nonzero(input_ids == self.tokenizer.mask_token_id , as_tuple=SCREAMING_SNAKE_CASE__ ).squeeze(-1 ) # Fill mask pipeline supports only one ${mask_token} per sample a_ : List[str] = outputs[0, masked_index, :] a_ : Dict = logits.softmax(dim=-1 ) if target_ids is not None: a_ : Optional[int] = probs[..., target_ids] a_ : str = probs.topk(SCREAMING_SNAKE_CASE__ ) a_ : Tuple = [] a_ : Tuple = values.shape[0] == 1 for i, (_values, _predictions) in enumerate(zip(values.tolist() , predictions.tolist() ) ): a_ : Optional[Any] = [] for v, p in zip(_values , _predictions ): # Copy is important since we're going to modify this array in place a_ : Dict = input_ids.numpy().copy() if target_ids is not None: a_ : Dict = target_ids[p].tolist() a_ : Optional[int] = p # Filter padding out: a_ : Optional[int] = tokens[np.where(tokens != self.tokenizer.pad_token_id )] # Originally we skip special tokens to give readable output. # For multi masks though, the other [MASK] would be removed otherwise # making the output look odd, so we add them back a_ : Union[str, Any] = self.tokenizer.decode(SCREAMING_SNAKE_CASE__ , skip_special_tokens=SCREAMING_SNAKE_CASE__ ) a_ : List[str] = {'score': v, 'token': p, 'token_str': self.tokenizer.decode([p] ), 'sequence': sequence} row.append(SCREAMING_SNAKE_CASE__ ) result.append(SCREAMING_SNAKE_CASE__ ) if single_mask: return result[0] return result def SCREAMING_SNAKE_CASE ( self : int , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : int=None ) -> str: if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ): a_ : Union[str, Any] = [targets] try: a_ : Union[str, Any] = self.tokenizer.get_vocab() except Exception: a_ : Optional[int] = {} a_ : Any = [] for target in targets: a_ : Optional[int] = vocab.get(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) if id_ is None: a_ : str = self.tokenizer( SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , return_attention_mask=SCREAMING_SNAKE_CASE__ , return_token_type_ids=SCREAMING_SNAKE_CASE__ , max_length=1 , truncation=SCREAMING_SNAKE_CASE__ , )['input_ids'] if len(SCREAMING_SNAKE_CASE__ ) == 0: logger.warning( F"""The specified target token `{target}` does not exist in the model vocabulary. """ 'We cannot replace it with anything meaningful, ignoring it' ) continue a_ : Optional[Any] = input_ids[0] # XXX: If users encounter this pass # it becomes pretty slow, so let's make sure # The warning enables them to fix the input to # get faster performance. logger.warning( F"""The specified target token `{target}` does not exist in the model vocabulary. """ F"""Replacing with `{self.tokenizer.convert_ids_to_tokens(id_ )}`.""" ) target_ids.append(id_ ) a_ : Optional[int] = list(set(SCREAMING_SNAKE_CASE__ ) ) if len(SCREAMING_SNAKE_CASE__ ) == 0: raise ValueError('At least one target must be provided when passed.' ) a_ : List[str] = np.array(SCREAMING_SNAKE_CASE__ ) return target_ids def SCREAMING_SNAKE_CASE ( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Any=None , SCREAMING_SNAKE_CASE__ : Optional[int]=None ) -> List[str]: a_ : Any = {} if targets is not None: a_ : List[str] = self.get_target_ids(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) a_ : Any = target_ids if top_k is not None: a_ : Tuple = top_k if self.tokenizer.mask_token_id is None: raise PipelineException( 'fill-mask' , self.model.base_model_prefix , 'The tokenizer does not define a `mask_token`.' ) return {}, {}, postprocess_params def __call__( self : int , SCREAMING_SNAKE_CASE__ : List[str] , *SCREAMING_SNAKE_CASE__ : List[Any] , **SCREAMING_SNAKE_CASE__ : Dict ) -> Dict: a_ : Optional[Any] = super().__call__(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and len(SCREAMING_SNAKE_CASE__ ) == 1: return outputs[0] return outputs
366
import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase_ : str = logging.get_logger(__name__) UpperCAmelCase_ : str = { 'Salesforce/instruct-blip-flan-t5': 'https://huggingface.co/Salesforce/instruct-blip-flan-t5/resolve/main/config.json', } class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : int = '''instructblip_vision_model''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : List[Any]=1_4_0_8 , SCREAMING_SNAKE_CASE__ : int=6_1_4_4 , SCREAMING_SNAKE_CASE__ : Dict=3_9 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=1_6 , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2_2_4 , SCREAMING_SNAKE_CASE__ : Optional[int]=1_4 , SCREAMING_SNAKE_CASE__ : List[Any]="gelu" , SCREAMING_SNAKE_CASE__ : List[str]=1E-6 , SCREAMING_SNAKE_CASE__ : Tuple=0.0 , SCREAMING_SNAKE_CASE__ : List[str]=1E-10 , SCREAMING_SNAKE_CASE__ : str=True , **SCREAMING_SNAKE_CASE__ : Dict , ) -> int: super().__init__(**SCREAMING_SNAKE_CASE__ ) a_ : List[str] = hidden_size a_ : Any = intermediate_size a_ : str = num_hidden_layers a_ : Dict = num_attention_heads a_ : str = patch_size a_ : Any = image_size a_ : Dict = initializer_range a_ : List[Any] = attention_dropout a_ : Union[str, Any] = layer_norm_eps a_ : Optional[Any] = hidden_act a_ : Optional[Any] = qkv_bias @classmethod def SCREAMING_SNAKE_CASE ( cls : Any , SCREAMING_SNAKE_CASE__ : Union[str, os.PathLike] , **SCREAMING_SNAKE_CASE__ : List[str] ) -> "PretrainedConfig": cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE__ ) a_ , a_ : Dict = cls.get_config_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # get the vision config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": a_ : List[Any] = config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : List[Any] = '''instructblip_qformer''' def __init__( self : Optional[int] , SCREAMING_SNAKE_CASE__ : Union[str, Any]=3_0_5_2_2 , SCREAMING_SNAKE_CASE__ : str=7_6_8 , SCREAMING_SNAKE_CASE__ : List[str]=1_2 , SCREAMING_SNAKE_CASE__ : Any=1_2 , SCREAMING_SNAKE_CASE__ : Optional[int]=3_0_7_2 , SCREAMING_SNAKE_CASE__ : List[str]="gelu" , SCREAMING_SNAKE_CASE__ : Dict=0.1 , SCREAMING_SNAKE_CASE__ : int=0.1 , SCREAMING_SNAKE_CASE__ : Optional[int]=5_1_2 , SCREAMING_SNAKE_CASE__ : Optional[Any]=0.02 , SCREAMING_SNAKE_CASE__ : int=1E-12 , SCREAMING_SNAKE_CASE__ : Dict=0 , SCREAMING_SNAKE_CASE__ : Optional[Any]="absolute" , SCREAMING_SNAKE_CASE__ : Union[str, Any]=2 , SCREAMING_SNAKE_CASE__ : str=1_4_0_8 , **SCREAMING_SNAKE_CASE__ : Dict , ) -> Optional[Any]: super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) a_ : Union[str, Any] = vocab_size a_ : List[str] = hidden_size a_ : Any = num_hidden_layers a_ : Dict = num_attention_heads a_ : Optional[int] = hidden_act a_ : List[str] = intermediate_size a_ : Tuple = hidden_dropout_prob a_ : Union[str, Any] = attention_probs_dropout_prob a_ : List[str] = max_position_embeddings a_ : List[str] = initializer_range a_ : Any = layer_norm_eps a_ : Tuple = position_embedding_type a_ : List[str] = cross_attention_frequency a_ : Union[str, Any] = encoder_hidden_size @classmethod def SCREAMING_SNAKE_CASE ( cls : str , SCREAMING_SNAKE_CASE__ : Union[str, os.PathLike] , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> "PretrainedConfig": cls._set_token_in_kwargs(SCREAMING_SNAKE_CASE__ ) a_ , a_ : Union[str, Any] = cls.get_config_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) # get the qformer config dict if we are loading from InstructBlipConfig if config_dict.get('model_type' ) == "instructblip": a_ : Dict = config_dict['qformer_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( F"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ F"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : Union[str, Any] = '''instructblip''' snake_case__ : List[str] = True def __init__( self : Tuple , SCREAMING_SNAKE_CASE__ : Optional[Any]=None , SCREAMING_SNAKE_CASE__ : Dict=None , SCREAMING_SNAKE_CASE__ : List[Any]=None , SCREAMING_SNAKE_CASE__ : int=3_2 , **SCREAMING_SNAKE_CASE__ : Union[str, Any] ) -> Tuple: super().__init__(**SCREAMING_SNAKE_CASE__ ) if vision_config is None: a_ : Dict = {} logger.info('vision_config is None. initializing the InstructBlipVisionConfig with default values.' ) if qformer_config is None: a_ : List[str] = {} logger.info('qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.' ) if text_config is None: a_ : Any = {} logger.info('text_config is None. Initializing the text config with default values (`OPTConfig`).' ) a_ : int = InstructBlipVisionConfig(**SCREAMING_SNAKE_CASE__ ) a_ : int = InstructBlipQFormerConfig(**SCREAMING_SNAKE_CASE__ ) a_ : Optional[Any] = text_config['model_type'] if 'model_type' in text_config else 'opt' a_ : List[Any] = CONFIG_MAPPING[text_model_type](**SCREAMING_SNAKE_CASE__ ) a_ : Tuple = self.text_config.tie_word_embeddings a_ : List[Any] = self.text_config.is_encoder_decoder a_ : Optional[Any] = num_query_tokens a_ : int = self.vision_config.hidden_size a_ : List[str] = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES a_ : Optional[int] = 1.0 a_ : Any = 0.02 @classmethod def SCREAMING_SNAKE_CASE ( cls : List[Any] , SCREAMING_SNAKE_CASE__ : InstructBlipVisionConfig , SCREAMING_SNAKE_CASE__ : InstructBlipQFormerConfig , SCREAMING_SNAKE_CASE__ : PretrainedConfig , **SCREAMING_SNAKE_CASE__ : List[str] , ) -> Any: return cls( vision_config=vision_config.to_dict() , qformer_config=qformer_config.to_dict() , text_config=text_config.to_dict() , **SCREAMING_SNAKE_CASE__ , ) def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Union[str, Any]: a_ : List[Any] = copy.deepcopy(self.__dict__ ) a_ : Optional[int] = self.vision_config.to_dict() a_ : Optional[Any] = self.qformer_config.to_dict() a_ : Union[str, Any] = self.text_config.to_dict() a_ : Optional[Any] = self.__class__.model_type return output
120
0
def lowercase_ (A : int ): snake_case__ : str = generate_pascal_triangle(A ) for row_idx in range(A ): # Print left spaces for _ in range(num_rows - row_idx - 1 ): print(end=' ' ) # Print row values for col_idx in range(row_idx + 1 ): if col_idx != row_idx: print(triangle[row_idx][col_idx] , end=' ' ) else: print(triangle[row_idx][col_idx] , end='' ) print() def lowercase_ (A : int ): if not isinstance(A , A ): raise TypeError('The input value of \'num_rows\' should be \'int\'' ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( 'The input value of \'num_rows\' should be greater than or equal to 0' ) snake_case__ : list[list[int]] = [] for current_row_idx in range(A ): snake_case__ : Optional[int] = populate_current_row(A , A ) triangle.append(A ) return triangle def lowercase_ (A : list[list[int]] , A : int ): snake_case__ : str = [-1] * (current_row_idx + 1) # first and last elements of current row are equal to 1 snake_case__ , snake_case__ : Optional[Any] = 1, 1 for current_col_idx in range(1 , A ): calculate_current_element( A , A , A , A ) return current_row def lowercase_ (A : list[list[int]] , A : list[int] , A : int , A : int , ): snake_case__ : Optional[int] = triangle[current_row_idx - 1][current_col_idx - 1] snake_case__ : Any = triangle[current_row_idx - 1][current_col_idx] snake_case__ : List[Any] = above_to_left_elt + above_to_right_elt def lowercase_ (A : int ): if not isinstance(A , A ): raise TypeError('The input value of \'num_rows\' should be \'int\'' ) if num_rows == 0: return [] elif num_rows < 0: raise ValueError( 'The input value of \'num_rows\' should be greater than or equal to 0' ) snake_case__ : list[list[int]] = [[1]] for row_index in range(1 , A ): snake_case__ : int = [0] + result[-1] + [0] snake_case__ : int = row_index + 1 # Calculate the number of distinct elements in a row snake_case__ : int = sum(divmod(A , 2 ) ) snake_case__ : Optional[Any] = [ temp_row[i - 1] + temp_row[i] for i in range(1 , distinct_elements + 1 ) ] snake_case__ : str = row_first_half[: (row_index + 1) // 2] row_second_half.reverse() snake_case__ : Optional[int] = row_first_half + row_second_half result.append(A ) return result def lowercase_ (): from collections.abc import Callable from timeit import timeit def benchmark_a_function(A : Callable , A : int ) -> None: snake_case__ : Optional[int] = F'''{func.__name__}({value})''' snake_case__ : Optional[Any] = timeit(F'''__main__.{call}''' , setup='import __main__' ) # print(f"{call:38} = {func(value)} -- {timing:.4f} seconds") print(F'''{call:38} -- {timing:.4f} seconds''' ) for value in range(1_5 ): # (1, 7, 14): for func in (generate_pascal_triangle, generate_pascal_triangle_optimized): benchmark_a_function(A , A ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
277
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__ : """simple docstring""" def __init__( self : Tuple, _snake_case : Any, _snake_case : int=1_3, _snake_case : Optional[int]=3_2, _snake_case : Tuple=2, _snake_case : Any=3, _snake_case : Tuple=1_6, _snake_case : Tuple=[1, 2, 1], _snake_case : Dict=[2, 2, 4], _snake_case : str=2, _snake_case : Union[str, Any]=2.0, _snake_case : Dict=True, _snake_case : Dict=0.0, _snake_case : str=0.0, _snake_case : str=0.1, _snake_case : List[str]="gelu", _snake_case : int=False, _snake_case : Optional[Any]=True, _snake_case : List[Any]=0.0_2, _snake_case : Union[str, Any]=1e-5, _snake_case : Union[str, Any]=True, _snake_case : List[Any]=None, _snake_case : Any=True, _snake_case : List[Any]=1_0, _snake_case : str=8, ) ->Union[str, Any]: snake_case__ : Any = parent snake_case__ : Tuple = batch_size snake_case__ : Tuple = image_size snake_case__ : Any = patch_size snake_case__ : Optional[int] = num_channels snake_case__ : Tuple = embed_dim snake_case__ : Any = depths snake_case__ : Any = num_heads snake_case__ : List[str] = window_size snake_case__ : Dict = mlp_ratio snake_case__ : Optional[int] = qkv_bias snake_case__ : Optional[Any] = hidden_dropout_prob snake_case__ : List[str] = attention_probs_dropout_prob snake_case__ : Union[str, Any] = drop_path_rate snake_case__ : str = hidden_act snake_case__ : Union[str, Any] = use_absolute_embeddings snake_case__ : Union[str, Any] = patch_norm snake_case__ : Any = layer_norm_eps snake_case__ : Tuple = initializer_range snake_case__ : Dict = is_training snake_case__ : Any = scope snake_case__ : Optional[Any] = use_labels snake_case__ : str = type_sequence_label_size snake_case__ : List[Any] = encoder_stride def lowercase_ ( self : Tuple ) ->str: snake_case__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case__ : List[Any] = None if self.use_labels: snake_case__ : Optional[Any] = ids_tensor([self.batch_size], self.type_sequence_label_size ) snake_case__ : Any = self.get_config() return config, pixel_values, labels def lowercase_ ( self : Optional[int] ) ->Optional[int]: 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 : Optional[int], _snake_case : str, _snake_case : List[str], _snake_case : int ) ->Dict: snake_case__ : List[Any] = SwinvaModel(config=_snake_case ) model.to(_snake_case ) model.eval() snake_case__ : Optional[int] = model(_snake_case ) snake_case__ : List[Any] = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) snake_case__ : List[Any] = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, expected_seq_len, expected_dim) ) def lowercase_ ( self : Optional[Any], _snake_case : Any, _snake_case : List[str], _snake_case : Dict ) ->List[Any]: snake_case__ : List[str] = SwinvaForMaskedImageModeling(config=_snake_case ) model.to(_snake_case ) model.eval() snake_case__ : Union[str, Any] = model(_snake_case ) self.parent.assertEqual( result.logits.shape, (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images snake_case__ : Optional[Any] = 1 snake_case__ : Optional[int] = SwinvaForMaskedImageModeling(_snake_case ) model.to(_snake_case ) model.eval() snake_case__ : Tuple = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) snake_case__ : Any = model(_snake_case ) self.parent.assertEqual(result.logits.shape, (self.batch_size, 1, self.image_size, self.image_size) ) def lowercase_ ( self : List[str], _snake_case : int, _snake_case : List[Any], _snake_case : Optional[int] ) ->Any: snake_case__ : Tuple = self.type_sequence_label_size snake_case__ : int = SwinvaForImageClassification(_snake_case ) model.to(_snake_case ) model.eval() snake_case__ : Tuple = model(_snake_case, labels=_snake_case ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size) ) def lowercase_ ( self : Any ) ->Dict: snake_case__ : str = self.prepare_config_and_inputs() snake_case__ , snake_case__ , snake_case__ : List[str] = config_and_inputs snake_case__ : Union[str, Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class snake_case__ ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" _SCREAMING_SNAKE_CASE = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE = ( {"""feature-extraction""": SwinvaModel, """image-classification""": SwinvaForImageClassification} if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False def lowercase_ ( self : Union[str, Any] ) ->Dict: snake_case__ : Optional[int] = SwinvaModelTester(self ) snake_case__ : int = ConfigTester(self, config_class=_snake_case, embed_dim=3_7 ) def lowercase_ ( self : Tuple ) ->int: 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 : Any ) ->str: snake_case__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_snake_case ) @unittest.skip(reason='Got `CUDA error: misaligned address` with PyTorch 2.0.0.' ) def lowercase_ ( self : Any ) ->Union[str, Any]: pass @unittest.skip(reason='Swinv2 does not use inputs_embeds' ) def lowercase_ ( self : str ) ->Union[str, Any]: pass def lowercase_ ( self : Optional[Any] ) ->Union[str, Any]: snake_case__ , snake_case__ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : Union[str, Any] = model_class(_snake_case ) self.assertIsInstance(model.get_input_embeddings(), (nn.Module) ) snake_case__ : Union[str, Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_snake_case, nn.Linear ) ) def lowercase_ ( self : List[str] ) ->Optional[int]: snake_case__ , snake_case__ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : Any = model_class(_snake_case ) snake_case__ : Dict = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case__ : Optional[Any] = [*signature.parameters.keys()] snake_case__ : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1], _snake_case ) def lowercase_ ( self : str ) ->Union[str, Any]: snake_case__ , snake_case__ : Any = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : int = True for model_class in self.all_model_classes: snake_case__ : str = True snake_case__ : Union[str, Any] = False snake_case__ : Tuple = True snake_case__ : int = model_class(_snake_case ) model.to(_snake_case ) model.eval() with torch.no_grad(): snake_case__ : Optional[int] = model(**self._prepare_for_class(_snake_case, _snake_case ) ) snake_case__ : List[str] = outputs.attentions snake_case__ : List[Any] = len(self.model_tester.depths ) self.assertEqual(len(_snake_case ), _snake_case ) # check that output_attentions also work using config del inputs_dict["output_attentions"] snake_case__ : str = True snake_case__ : Tuple = config.window_size**2 snake_case__ : Optional[int] = model_class(_snake_case ) model.to(_snake_case ) model.eval() with torch.no_grad(): snake_case__ : str = model(**self._prepare_for_class(_snake_case, _snake_case ) ) snake_case__ : Tuple = outputs.attentions self.assertEqual(len(_snake_case ), _snake_case ) self.assertListEqual( list(attentions[0].shape[-3:] ), [self.model_tester.num_heads[0], window_size_squared, window_size_squared], ) snake_case__ : Optional[Any] = len(_snake_case ) # Check attention is always last and order is fine snake_case__ : Optional[int] = True snake_case__ : Dict = True snake_case__ : List[Any] = model_class(_snake_case ) model.to(_snake_case ) model.eval() with torch.no_grad(): snake_case__ : Optional[int] = model(**self._prepare_for_class(_snake_case, _snake_case ) ) if hasattr(self.model_tester, 'num_hidden_states_types' ): snake_case__ : str = self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states snake_case__ : Dict = 2 self.assertEqual(out_len + added_hidden_states, len(_snake_case ) ) snake_case__ : Any = outputs.attentions self.assertEqual(len(_snake_case ), _snake_case ) self.assertListEqual( list(self_attentions[0].shape[-3:] ), [self.model_tester.num_heads[0], window_size_squared, window_size_squared], ) def lowercase_ ( self : Dict, _snake_case : Tuple, _snake_case : Any, _snake_case : int, _snake_case : Optional[int] ) ->str: snake_case__ : Dict = model_class(_snake_case ) model.to(_snake_case ) model.eval() with torch.no_grad(): snake_case__ : List[Any] = model(**self._prepare_for_class(_snake_case, _snake_case ) ) snake_case__ : Dict = outputs.hidden_states snake_case__ : int = getattr( self.model_tester, 'expected_num_hidden_layers', len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_snake_case ), _snake_case ) # Swinv2 has a different seq_length snake_case__ : int = ( config.patch_size if isinstance(config.patch_size, collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) snake_case__ : Optional[Any] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ), [num_patches, self.model_tester.embed_dim], ) snake_case__ : Union[str, Any] = outputs.reshaped_hidden_states self.assertEqual(len(_snake_case ), _snake_case ) snake_case__ , snake_case__ , snake_case__ , snake_case__ : str = reshaped_hidden_states[0].shape snake_case__ : Any = ( reshaped_hidden_states[0].view(_snake_case, _snake_case, height * width ).permute(0, 2, 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ), [num_patches, self.model_tester.embed_dim], ) def lowercase_ ( self : str ) ->List[Any]: snake_case__ , snake_case__ : Any = self.model_tester.prepare_config_and_inputs_for_common() 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: snake_case__ : Optional[int] = True self.check_hidden_states_output(_snake_case, _snake_case, _snake_case, _snake_case ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case__ : Dict = True self.check_hidden_states_output(_snake_case, _snake_case, _snake_case, _snake_case ) def lowercase_ ( self : List[str] ) ->str: snake_case__ , snake_case__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : List[str] = 3 snake_case__ : Union[str, 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) ) snake_case__ : str = ( config.patch_size if isinstance(config.patch_size, collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) snake_case__ : Tuple = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) snake_case__ : Optional[Any] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: snake_case__ : int = True self.check_hidden_states_output(_snake_case, _snake_case, _snake_case, (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case__ : List[str] = True self.check_hidden_states_output(_snake_case, _snake_case, _snake_case, (padded_height, padded_width) ) def lowercase_ ( self : List[str] ) ->Optional[int]: snake_case__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_snake_case ) def lowercase_ ( self : List[Any] ) ->str: snake_case__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_snake_case ) @slow def lowercase_ ( self : str ) ->Union[str, Any]: for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case__ : Dict = SwinvaModel.from_pretrained(_snake_case ) self.assertIsNotNone(_snake_case ) def lowercase_ ( self : Optional[int] ) ->List[str]: snake_case__ , snake_case__ : Any = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : List[Any] = _config_zero_init(_snake_case ) for model_class in self.all_model_classes: snake_case__ : List[str] = model_class(config=_snake_case ) 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 ): """simple docstring""" @cached_property def lowercase_ ( self : Union[str, Any] ) ->List[str]: return ( AutoImageProcessor.from_pretrained('microsoft/swinv2-tiny-patch4-window8-256' ) if is_vision_available() else None ) @slow def lowercase_ ( self : int ) ->List[Any]: snake_case__ : Any = SwinvaForImageClassification.from_pretrained('microsoft/swinv2-tiny-patch4-window8-256' ).to( _snake_case ) snake_case__ : int = self.default_image_processor snake_case__ : Union[str, Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) snake_case__ : Optional[Any] = image_processor(images=_snake_case, return_tensors='pt' ).to(_snake_case ) # forward pass with torch.no_grad(): snake_case__ : List[str] = model(**_snake_case ) # verify the logits snake_case__ : int = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape, _snake_case ) snake_case__ : Optional[int] = torch.tensor([-0.3_9_4_7, -0.4_3_0_6, 0.0_0_2_6] ).to(_snake_case ) self.assertTrue(torch.allclose(outputs.logits[0, :3], _snake_case, atol=1e-4 ) )
277
1
from typing import List, Optional, Tuple from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_herbert import HerbertTokenizer UpperCAmelCase__ : str =logging.get_logger(__name__) UpperCAmelCase__ : int ={'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt''', '''tokenizer_file''': '''tokenizer.json'''} UpperCAmelCase__ : List[Any] ={ '''vocab_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/vocab.json''' }, '''merges_file''': { '''allegro/herbert-base-cased''': '''https://huggingface.co/allegro/herbert-base-cased/resolve/main/merges.txt''' }, } UpperCAmelCase__ : List[Any] ={'''allegro/herbert-base-cased''': 5_14} UpperCAmelCase__ : int ={} class __A ( a ): __A = VOCAB_FILES_NAMES __A = PRETRAINED_VOCAB_FILES_MAP __A = PRETRAINED_INIT_CONFIGURATION __A = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES __A = HerbertTokenizer def __init__( self , UpperCAmelCase_=None , UpperCAmelCase_=None , UpperCAmelCase_=None , UpperCAmelCase_="<s>" , UpperCAmelCase_="<unk>" , UpperCAmelCase_="<pad>" , UpperCAmelCase_="<mask>" , UpperCAmelCase_="</s>" , **UpperCAmelCase_ , ): super().__init__( UpperCAmelCase_ , UpperCAmelCase_ , tokenizer_file=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , **UpperCAmelCase_ , ) def _snake_case ( self , UpperCAmelCase_ , UpperCAmelCase_ = None ): lowerCamelCase =[self.cls_token_id] lowerCamelCase =[self.sep_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 _snake_case ( self , UpperCAmelCase_ , UpperCAmelCase_ = None , UpperCAmelCase_ = 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] + ([0] * len(UpperCAmelCase_ )) + [1] def _snake_case ( self , UpperCAmelCase_ , UpperCAmelCase_ = None ): lowerCamelCase =[self.sep_token_id] lowerCamelCase =[self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1] def _snake_case ( self , UpperCAmelCase_ , UpperCAmelCase_ = None ): lowerCamelCase =self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_ ) return tuple(UpperCAmelCase_ )
262
from math import cos, sin, sqrt, tau from audio_filters.iir_filter import IIRFilter def _lowercase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 1 / sqrt(2 ) ) -> IIRFilter: lowerCamelCase =tau * frequency / samplerate lowerCamelCase =sin(_UpperCAmelCase ) lowerCamelCase =cos(_UpperCAmelCase ) lowerCamelCase =_sin / (2 * q_factor) lowerCamelCase =(1 - _cos) / 2 lowerCamelCase =1 - _cos lowerCamelCase =1 + alpha lowerCamelCase =-2 * _cos lowerCamelCase =1 - alpha lowerCamelCase =IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _lowercase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 1 / sqrt(2 ) ) -> IIRFilter: lowerCamelCase =tau * frequency / samplerate lowerCamelCase =sin(_UpperCAmelCase ) lowerCamelCase =cos(_UpperCAmelCase ) lowerCamelCase =_sin / (2 * q_factor) lowerCamelCase =(1 + _cos) / 2 lowerCamelCase =-1 - _cos lowerCamelCase =1 + alpha lowerCamelCase =-2 * _cos lowerCamelCase =1 - alpha lowerCamelCase =IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _lowercase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 1 / sqrt(2 ) ) -> IIRFilter: lowerCamelCase =tau * frequency / samplerate lowerCamelCase =sin(_UpperCAmelCase ) lowerCamelCase =cos(_UpperCAmelCase ) lowerCamelCase =_sin / (2 * q_factor) lowerCamelCase =_sin / 2 lowerCamelCase =0 lowerCamelCase =-ba lowerCamelCase =1 + alpha lowerCamelCase =-2 * _cos lowerCamelCase =1 - alpha lowerCamelCase =IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _lowercase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 1 / sqrt(2 ) ) -> IIRFilter: lowerCamelCase =tau * frequency / samplerate lowerCamelCase =sin(_UpperCAmelCase ) lowerCamelCase =cos(_UpperCAmelCase ) lowerCamelCase =_sin / (2 * q_factor) lowerCamelCase =1 - alpha lowerCamelCase =-2 * _cos lowerCamelCase =1 + alpha lowerCamelCase =IIRFilter(2 ) filt.set_coefficients([ba, ba, ba] , [ba, ba, ba] ) return filt def _lowercase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 1 / sqrt(2 ) , ) -> IIRFilter: lowerCamelCase =tau * frequency / samplerate lowerCamelCase =sin(_UpperCAmelCase ) lowerCamelCase =cos(_UpperCAmelCase ) lowerCamelCase =_sin / (2 * q_factor) lowerCamelCase =10 ** (gain_db / 40) lowerCamelCase =1 + alpha * big_a lowerCamelCase =-2 * _cos lowerCamelCase =1 - alpha * big_a lowerCamelCase =1 + alpha / big_a lowerCamelCase =-2 * _cos lowerCamelCase =1 - alpha / big_a lowerCamelCase =IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _lowercase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 1 / sqrt(2 ) , ) -> IIRFilter: lowerCamelCase =tau * frequency / samplerate lowerCamelCase =sin(_UpperCAmelCase ) lowerCamelCase =cos(_UpperCAmelCase ) lowerCamelCase =_sin / (2 * q_factor) lowerCamelCase =10 ** (gain_db / 40) lowerCamelCase =(big_a + 1) - (big_a - 1) * _cos lowerCamelCase =(big_a + 1) + (big_a - 1) * _cos lowerCamelCase =(big_a - 1) - (big_a + 1) * _cos lowerCamelCase =(big_a - 1) + (big_a + 1) * _cos lowerCamelCase =2 * sqrt(_UpperCAmelCase ) * alpha lowerCamelCase =big_a * (pmc + aaa) lowerCamelCase =2 * big_a * mpc lowerCamelCase =big_a * (pmc - aaa) lowerCamelCase =ppmc + aaa lowerCamelCase =-2 * pmpc lowerCamelCase =ppmc - aaa lowerCamelCase =IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt def _lowercase ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = 1 / sqrt(2 ) , ) -> IIRFilter: lowerCamelCase =tau * frequency / samplerate lowerCamelCase =sin(_UpperCAmelCase ) lowerCamelCase =cos(_UpperCAmelCase ) lowerCamelCase =_sin / (2 * q_factor) lowerCamelCase =10 ** (gain_db / 40) lowerCamelCase =(big_a + 1) - (big_a - 1) * _cos lowerCamelCase =(big_a + 1) + (big_a - 1) * _cos lowerCamelCase =(big_a - 1) - (big_a + 1) * _cos lowerCamelCase =(big_a - 1) + (big_a + 1) * _cos lowerCamelCase =2 * sqrt(_UpperCAmelCase ) * alpha lowerCamelCase =big_a * (ppmc + aaa) lowerCamelCase =-2 * big_a * pmpc lowerCamelCase =big_a * (ppmc - aaa) lowerCamelCase =pmc + aaa lowerCamelCase =2 * mpc lowerCamelCase =pmc - aaa lowerCamelCase =IIRFilter(2 ) filt.set_coefficients([aa, aa, aa] , [ba, ba, ba] ) return filt
262
1
'''simple docstring''' from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar _lowerCAmelCase = TypeVar('''T''') def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" return (position - 1) // 2 def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" return (2 * position) + 1 def _SCREAMING_SNAKE_CASE ( UpperCamelCase ): """simple docstring""" return (2 * position) + 2 class lowerCAmelCase_( Generic[T] ): '''simple docstring''' def __init__( self ) -> None: lowerCAmelCase__ : list[tuple[T, int]] = [] lowerCAmelCase__ : dict[T, int] = {} lowerCAmelCase__ : int = 0 def __len__( self ) -> int: return self.elements def __repr__( self ) -> str: return str(self.heap ) def UpperCAmelCase_ ( self ) -> bool: # Check if the priority queue is empty return self.elements == 0 def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase ) -> None: # Add an element with given priority to the queue self.heap.append((elem, weight) ) lowerCAmelCase__ : str = self.elements self.elements += 1 self._bubble_up(__UpperCAmelCase ) def UpperCAmelCase_ ( self ) -> T: # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0 ,self.elements - 1 ) lowerCAmelCase__ , lowerCAmelCase__ : Optional[int] = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: lowerCAmelCase__ , lowerCAmelCase__ : str = self.heap[0] self._bubble_down(__UpperCAmelCase ) return elem def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase ) -> None: # Update the weight of the given key lowerCAmelCase__ : int = self.position_map[elem] lowerCAmelCase__ : List[Any] = (elem, weight) if position > 0: lowerCAmelCase__ : Dict = get_parent_position(__UpperCAmelCase ) lowerCAmelCase__ , lowerCAmelCase__ : Optional[int] = self.heap[parent_position] if parent_weight > weight: self._bubble_up(__UpperCAmelCase ) else: self._bubble_down(__UpperCAmelCase ) else: self._bubble_down(__UpperCAmelCase ) def UpperCAmelCase_ ( self ,__UpperCAmelCase ) -> None: # Place a node at the proper position (upward movement) [to be used internally # only] lowerCAmelCase__ : List[str] = self.position_map[elem] if curr_pos == 0: return None lowerCAmelCase__ : int = get_parent_position(__UpperCAmelCase ) lowerCAmelCase__ , lowerCAmelCase__ : Any = self.heap[curr_pos] lowerCAmelCase__ , lowerCAmelCase__ : List[str] = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(__UpperCAmelCase ,__UpperCAmelCase ) return self._bubble_up(__UpperCAmelCase ) return None def UpperCAmelCase_ ( self ,__UpperCAmelCase ) -> None: # Place a node at the proper position (downward movement) [to be used # internally only] lowerCAmelCase__ : List[Any] = self.position_map[elem] lowerCAmelCase__ , lowerCAmelCase__ : Dict = self.heap[curr_pos] lowerCAmelCase__ : str = get_child_left_position(__UpperCAmelCase ) lowerCAmelCase__ : Union[str, Any] = get_child_right_position(__UpperCAmelCase ) if child_left_position < self.elements and child_right_position < self.elements: lowerCAmelCase__ , lowerCAmelCase__ : Dict = self.heap[child_left_position] lowerCAmelCase__ , lowerCAmelCase__ : Any = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(__UpperCAmelCase ,__UpperCAmelCase ) return self._bubble_down(__UpperCAmelCase ) if child_left_position < self.elements: lowerCAmelCase__ , lowerCAmelCase__ : List[str] = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(__UpperCAmelCase ,__UpperCAmelCase ) return self._bubble_down(__UpperCAmelCase ) else: return None if child_right_position < self.elements: lowerCAmelCase__ , lowerCAmelCase__ : Any = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(__UpperCAmelCase ,__UpperCAmelCase ) return self._bubble_down(__UpperCAmelCase ) return None def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase ) -> None: # Swap the nodes at the given positions lowerCAmelCase__ : str = self.heap[nodea_pos][0] lowerCAmelCase__ : Dict = self.heap[nodea_pos][0] lowerCAmelCase__ , lowerCAmelCase__ : Tuple = ( self.heap[nodea_pos], self.heap[nodea_pos], ) lowerCAmelCase__ : int = nodea_pos lowerCAmelCase__ : int = nodea_pos class lowerCAmelCase_( Generic[T] ): '''simple docstring''' def __init__( self ) -> None: lowerCAmelCase__ : dict[T, dict[T, int]] = {} lowerCAmelCase__ : int = 0 def __repr__( self ) -> str: return str(self.connections ) def __len__( self ) -> int: return self.nodes def UpperCAmelCase_ ( self ,__UpperCAmelCase ) -> None: # Add a node in the graph if it is not in the graph if node not in self.connections: lowerCAmelCase__ : Optional[int] = {} self.nodes += 1 def UpperCAmelCase_ ( self ,__UpperCAmelCase ,__UpperCAmelCase ,__UpperCAmelCase ) -> None: # Add an edge between 2 nodes in the graph self.add_node(__UpperCAmelCase ) self.add_node(__UpperCAmelCase ) lowerCAmelCase__ : Any = weight lowerCAmelCase__ : Tuple = weight def _SCREAMING_SNAKE_CASE ( UpperCamelCase , ): """simple docstring""" lowerCAmelCase__ : dict[T, int] = {node: maxsize for node in graph.connections} lowerCAmelCase__ : dict[T, T | None] = {node: None for node in graph.connections} lowerCAmelCase__ : MinPriorityQueue[T] = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(UpperCamelCase , UpperCamelCase ) if priority_queue.is_empty(): return dist, parent # initialization lowerCAmelCase__ : List[Any] = priority_queue.extract_min() lowerCAmelCase__ : str = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: lowerCAmelCase__ : Any = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(UpperCamelCase , dist[neighbour] ) lowerCAmelCase__ : List[str] = node # running prim's algorithm while not priority_queue.is_empty(): lowerCAmelCase__ : Any = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: lowerCAmelCase__ : Optional[int] = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(UpperCamelCase , dist[neighbour] ) lowerCAmelCase__ : Optional[int] = node return dist, parent
37
'''simple docstring''' def _A ( ): lowercase__ = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] lowercase__ = 6 lowercase__ = 1 lowercase__ = 1901 lowercase__ = 0 while year < 2001: day += 7 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0): if day > days_per_month[month - 1] and month != 2: month += 1 lowercase__ = day - days_per_month[month - 2] elif day > 29 and month == 2: month += 1 lowercase__ = day - 29 else: if day > days_per_month[month - 1]: month += 1 lowercase__ = day - days_per_month[month - 2] if month > 12: year += 1 lowercase__ = 1 if year < 2001 and day == 1: sundays += 1 return sundays if __name__ == "__main__": print(solution())
164
0
def lowerCamelCase__ ( _lowercase , _lowercase ): '''simple docstring''' return number | (1 << position) def lowerCamelCase__ ( _lowercase , _lowercase ): '''simple docstring''' return number & ~(1 << position) def lowerCamelCase__ ( _lowercase , _lowercase ): '''simple docstring''' return number ^ (1 << position) def lowerCamelCase__ ( _lowercase , _lowercase ): '''simple docstring''' return ((number >> position) & 1) == 1 def lowerCamelCase__ ( _lowercase , _lowercase ): '''simple docstring''' return int((number & (1 << position)) != 0 ) if __name__ == "__main__": import doctest doctest.testmod()
365
from __future__ import annotations from fractions import Fraction def lowerCamelCase__ ( _lowercase , _lowercase ): '''simple docstring''' return ( num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den ) def lowerCamelCase__ ( _lowercase ): '''simple docstring''' UpperCAmelCase_ : Optional[int] = [] UpperCAmelCase_ : Tuple = 11 UpperCAmelCase_ : int = int('''1''' + '''0''' * digit_len ) for num in range(_lowercase , _lowercase ): while den <= 99: if (num != den) and (num % 10 == den // 10) and (den % 10 != 0): if is_digit_cancelling(_lowercase , _lowercase ): solutions.append(f'''{num}/{den}''' ) den += 1 num += 1 UpperCAmelCase_ : Any = 10 return solutions def lowerCamelCase__ ( _lowercase = 2 ): '''simple docstring''' UpperCAmelCase_ : Tuple = 1.0 for fraction in fraction_list(_lowercase ): UpperCAmelCase_ : Optional[Any] = Fraction(_lowercase ) result *= frac.denominator / frac.numerator return int(_lowercase ) if __name__ == "__main__": print(solution())
235
0
import os from pathlib import Path from unittest.mock import patch import pytest import zstandard as zstd from datasets.download.download_config import DownloadConfig from datasets.utils.file_utils import ( OfflineModeIsEnabled, cached_path, fsspec_get, fsspec_head, ftp_get, ftp_head, get_from_cache, http_get, http_head, ) UpperCAmelCase_ = "\\n Text data.\n Second line of data." UpperCAmelCase_ = "file" @pytest.fixture(scope="""session""" ) def lowerCamelCase__ ( A__ : Dict ): '''simple docstring''' __lowerCamelCase = tmp_path_factory.mktemp("""data""" ) / (FILE_PATH + """.zstd""") __lowerCamelCase = bytes(_UpperCamelCase , """utf-8""" ) with zstd.open(_UpperCamelCase , """wb""" ) as f: f.write(_UpperCamelCase ) return path @pytest.fixture def lowerCamelCase__ ( A__ : List[str] ): '''simple docstring''' with open(os.path.join(tmpfs.local_root_dir , _UpperCamelCase ) , """w""" ) as f: f.write(_UpperCamelCase ) return FILE_PATH @pytest.mark.parametrize("""compression_format""" , ["""gzip""", """xz""", """zstd"""] ) def lowerCamelCase__ ( A__ : Optional[int] , A__ : Optional[Any] , A__ : Optional[Any] , A__ : Any , A__ : Union[str, Any] , A__ : str ): '''simple docstring''' __lowerCamelCase = {"""gzip""": gz_file, """xz""": xz_file, """zstd""": zstd_path} __lowerCamelCase = input_paths[compression_format] __lowerCamelCase = tmp_path / """cache""" __lowerCamelCase = DownloadConfig(cache_dir=_UpperCamelCase , extract_compressed_file=_UpperCamelCase ) __lowerCamelCase = cached_path(_UpperCamelCase , download_config=_UpperCamelCase ) with open(_UpperCamelCase ) as f: __lowerCamelCase = f.read() with open(_UpperCamelCase ) as f: __lowerCamelCase = f.read() assert extracted_file_content == expected_file_content @pytest.mark.parametrize("""default_extracted""" , [True, False] ) @pytest.mark.parametrize("""default_cache_dir""" , [True, False] ) def lowerCamelCase__ ( A__ : List[str] , A__ : str , A__ : Tuple , A__ : List[str] , A__ : Optional[int] ): '''simple docstring''' __lowerCamelCase = """custom_cache""" __lowerCamelCase = """custom_extracted_dir""" __lowerCamelCase = tmp_path / """custom_extracted_path""" if default_extracted: __lowerCamelCase = ("""downloads""" if default_cache_dir else custom_cache_dir, """extracted""") else: monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_DIR""" , _UpperCamelCase ) monkeypatch.setattr("""datasets.config.EXTRACTED_DATASETS_PATH""" , str(_UpperCamelCase ) ) __lowerCamelCase = custom_extracted_path.parts[-2:] if default_cache_dir else (custom_cache_dir, custom_extracted_dir) __lowerCamelCase = xz_file __lowerCamelCase = ( DownloadConfig(extract_compressed_file=_UpperCamelCase ) if default_cache_dir else DownloadConfig(cache_dir=tmp_path / custom_cache_dir , extract_compressed_file=_UpperCamelCase ) ) __lowerCamelCase = cached_path(_UpperCamelCase , download_config=_UpperCamelCase ) assert Path(_UpperCamelCase ).parent.parts[-2:] == expected def lowerCamelCase__ ( A__ : Optional[Any] ): '''simple docstring''' __lowerCamelCase = str(Path(_UpperCamelCase ).resolve() ) assert cached_path(_UpperCamelCase ) == text_file # relative path __lowerCamelCase = str(Path(_UpperCamelCase ).resolve().relative_to(Path(os.getcwd() ) ) ) assert cached_path(_UpperCamelCase ) == text_file def lowerCamelCase__ ( A__ : List[str] ): '''simple docstring''' __lowerCamelCase = str(tmp_path.resolve() / """__missing_file__.txt""" ) with pytest.raises(_UpperCamelCase ): cached_path(_UpperCamelCase ) # relative path __lowerCamelCase = """./__missing_file__.txt""" with pytest.raises(_UpperCamelCase ): cached_path(_UpperCamelCase ) def lowerCamelCase__ ( A__ : Optional[Any] ): '''simple docstring''' __lowerCamelCase = get_from_cache(f'tmp://{tmpfs_file}' ) with open(_UpperCamelCase ) as f: __lowerCamelCase = f.read() assert output_file_content == FILE_CONTENT @patch("""datasets.config.HF_DATASETS_OFFLINE""" , _UpperCamelCase ) def lowerCamelCase__ ( ): '''simple docstring''' with pytest.raises(_UpperCamelCase ): cached_path("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , _UpperCamelCase ) def lowerCamelCase__ ( A__ : List[str] ): '''simple docstring''' __lowerCamelCase = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(_UpperCamelCase ): http_get("""https://huggingface.co""" , temp_file=_UpperCamelCase ) with pytest.raises(_UpperCamelCase ): http_head("""https://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , _UpperCamelCase ) def lowerCamelCase__ ( A__ : List[Any] ): '''simple docstring''' __lowerCamelCase = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(_UpperCamelCase ): ftp_get("""ftp://huggingface.co""" , temp_file=_UpperCamelCase ) with pytest.raises(_UpperCamelCase ): ftp_head("""ftp://huggingface.co""" ) @patch("""datasets.config.HF_DATASETS_OFFLINE""" , _UpperCamelCase ) def lowerCamelCase__ ( A__ : Tuple ): '''simple docstring''' __lowerCamelCase = tmp_path_factory.mktemp("""data""" ) / """file.html""" with pytest.raises(_UpperCamelCase ): fsspec_get("""s3://huggingface.co""" , temp_file=_UpperCamelCase ) with pytest.raises(_UpperCamelCase ): fsspec_head("""s3://huggingface.co""" )
12
'''simple docstring''' # Copyright 2021 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 json import os from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType from ...utils.imports import is_botoa_available from .config_args import SageMakerConfig from .config_utils import ( DYNAMO_BACKENDS, _ask_field, _ask_options, _convert_dynamo_backend, _convert_mixed_precision, _convert_sagemaker_distributed_mode, _convert_yes_no_to_bool, ) if is_botoa_available(): import botoa # noqa: F401 def _lowerCAmelCase ( _UpperCamelCase : Optional[int] ) -> List[str]: """simple docstring""" _SCREAMING_SNAKE_CASE =botoa.client('iam' ) _SCREAMING_SNAKE_CASE ={ 'Version': '2012-10-17', 'Statement': [ {'Effect': 'Allow', 'Principal': {'Service': 'sagemaker.amazonaws.com'}, 'Action': 'sts:AssumeRole'} ], } try: # create the role, associated with the chosen trust policy iam_client.create_role( RoleName=_UpperCamelCase , AssumeRolePolicyDocument=json.dumps(_UpperCamelCase , indent=2 ) ) _SCREAMING_SNAKE_CASE ={ 'Version': '2012-10-17', 'Statement': [ { 'Effect': 'Allow', 'Action': [ 'sagemaker:*', 'ecr:GetDownloadUrlForLayer', 'ecr:BatchGetImage', 'ecr:BatchCheckLayerAvailability', 'ecr:GetAuthorizationToken', 'cloudwatch:PutMetricData', 'cloudwatch:GetMetricData', 'cloudwatch:GetMetricStatistics', 'cloudwatch:ListMetrics', 'logs:CreateLogGroup', 'logs:CreateLogStream', 'logs:DescribeLogStreams', 'logs:PutLogEvents', 'logs:GetLogEvents', 's3:CreateBucket', 's3:ListBucket', 's3:GetBucketLocation', 's3:GetObject', 's3:PutObject', ], 'Resource': '*', } ], } # attach policy to role iam_client.put_role_policy( RoleName=_UpperCamelCase , PolicyName=f"{role_name}_policy_permission" , PolicyDocument=json.dumps(_UpperCamelCase , indent=2 ) , ) except iam_client.exceptions.EntityAlreadyExistsException: print(f"role {role_name} already exists. Using existing one" ) def _lowerCAmelCase ( _UpperCamelCase : List[str] ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =botoa.client('iam' ) return iam_client.get_role(RoleName=_UpperCamelCase )["Role"]["Arn"] def _lowerCAmelCase ( ) -> Optional[int]: """simple docstring""" _SCREAMING_SNAKE_CASE =_ask_options( 'How do you want to authorize?' , ['AWS Profile', 'Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) '] , _UpperCamelCase , ) _SCREAMING_SNAKE_CASE =None if credentials_configuration == 0: _SCREAMING_SNAKE_CASE =_ask_field('Enter your AWS Profile name: [default] ' , default='default' ) _SCREAMING_SNAKE_CASE =aws_profile else: print( 'Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with,' '`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`' ) _SCREAMING_SNAKE_CASE =_ask_field('AWS Access Key ID: ' ) _SCREAMING_SNAKE_CASE =aws_access_key_id _SCREAMING_SNAKE_CASE =_ask_field('AWS Secret Access Key: ' ) _SCREAMING_SNAKE_CASE =aws_secret_access_key _SCREAMING_SNAKE_CASE =_ask_field('Enter your AWS Region: [us-east-1]' , default='us-east-1' ) _SCREAMING_SNAKE_CASE =aws_region _SCREAMING_SNAKE_CASE =_ask_options( 'Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?' , ['Provide IAM Role name', 'Create new IAM role using credentials'] , _UpperCamelCase , ) if role_management == 0: _SCREAMING_SNAKE_CASE =_ask_field('Enter your IAM role name: ' ) else: _SCREAMING_SNAKE_CASE ='accelerate_sagemaker_execution_role' print(f"Accelerate will create an iam role \"{iam_role_name}\" using the provided credentials" ) _create_iam_role_for_sagemaker(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want to use custom Docker image? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) _SCREAMING_SNAKE_CASE =None if is_custom_docker_image: _SCREAMING_SNAKE_CASE =_ask_field('Enter your Docker image: ' , lambda _UpperCamelCase : str(_UpperCamelCase ).lower() ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want to provide SageMaker input channels with data locations? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) _SCREAMING_SNAKE_CASE =None if is_sagemaker_inputs_enabled: _SCREAMING_SNAKE_CASE =_ask_field( 'Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): ' , lambda _UpperCamelCase : str(_UpperCamelCase ).lower() , ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want to enable SageMaker metrics? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) _SCREAMING_SNAKE_CASE =None if is_sagemaker_metrics_enabled: _SCREAMING_SNAKE_CASE =_ask_field( 'Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): ' , lambda _UpperCamelCase : str(_UpperCamelCase ).lower() , ) _SCREAMING_SNAKE_CASE =_ask_options( 'What is the distributed mode?' , ['No distributed training', 'Data parallelism'] , _convert_sagemaker_distributed_mode , ) _SCREAMING_SNAKE_CASE ={} _SCREAMING_SNAKE_CASE =_ask_field( 'Do you wish to optimize your script with torch dynamo?[yes/NO]:' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) if use_dynamo: _SCREAMING_SNAKE_CASE ='dynamo_' _SCREAMING_SNAKE_CASE =_ask_options( 'Which dynamo backend would you like to use?' , [x.lower() for x in DYNAMO_BACKENDS] , _convert_dynamo_backend , default=2 , ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want to customize the defaults sent to torch.compile? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) if use_custom_options: _SCREAMING_SNAKE_CASE =_ask_options( 'Which mode do you want to use?' , _UpperCamelCase , lambda _UpperCamelCase : TORCH_DYNAMO_MODES[int(_UpperCamelCase )] , default='default' , ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) _SCREAMING_SNAKE_CASE =_ask_field( 'Do you want to enable dynamic shape tracing? [yes/NO]: ' , _convert_yes_no_to_bool , default=_UpperCamelCase , error_message='Please enter yes or no.' , ) _SCREAMING_SNAKE_CASE ='Which EC2 instance type you want to use for your training?' if distributed_type != SageMakerDistributedType.NO: _SCREAMING_SNAKE_CASE =_ask_options( _UpperCamelCase , _UpperCamelCase , lambda _UpperCamelCase : SAGEMAKER_PARALLEL_EC2_INSTANCES[int(_UpperCamelCase )] ) else: eca_instance_query += "? [ml.p3.2xlarge]:" _SCREAMING_SNAKE_CASE =_ask_field(_UpperCamelCase , lambda _UpperCamelCase : str(_UpperCamelCase ).lower() , default='ml.p3.2xlarge' ) _SCREAMING_SNAKE_CASE =1 if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): _SCREAMING_SNAKE_CASE =_ask_field( 'How many machines do you want use? [1]: ' , _UpperCamelCase , default=1 , ) _SCREAMING_SNAKE_CASE =_ask_options( 'Do you wish to use FP16 or BF16 (mixed precision)?' , ['no', 'fp16', 'bf16', 'fp8'] , _convert_mixed_precision , ) if use_dynamo and mixed_precision == "no": print( 'Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts.' ) return SageMakerConfig( image_uri=_UpperCamelCase , compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER , distributed_type=_UpperCamelCase , use_cpu=_UpperCamelCase , dynamo_config=_UpperCamelCase , eca_instance_type=_UpperCamelCase , profile=_UpperCamelCase , region=_UpperCamelCase , iam_role_name=_UpperCamelCase , mixed_precision=_UpperCamelCase , num_machines=_UpperCamelCase , sagemaker_inputs_file=_UpperCamelCase , sagemaker_metrics_file=_UpperCamelCase , )
47
0
import argparse import os import numpy as np import tensorflow as tf import torch from transformers import BertModel def UpperCamelCase__( UpperCamelCase__ : BertModel , UpperCamelCase__ : str , UpperCamelCase__ : str )->List[Any]: A__ = ('''dense.weight''', '''attention.self.query''', '''attention.self.key''', '''attention.self.value''') A__ = ( ('''layer.''', '''layer_'''), ('''word_embeddings.weight''', '''word_embeddings'''), ('''position_embeddings.weight''', '''position_embeddings'''), ('''token_type_embeddings.weight''', '''token_type_embeddings'''), ('''.''', '''/'''), ('''LayerNorm/weight''', '''LayerNorm/gamma'''), ('''LayerNorm/bias''', '''LayerNorm/beta'''), ('''weight''', '''kernel'''), ) if not os.path.isdir(UpperCamelCase__ ): os.makedirs(UpperCamelCase__ ) A__ = model.state_dict() def to_tf_var_name(UpperCamelCase__ : str ): for patt, repl in iter(UpperCamelCase__ ): A__ = name.replace(UpperCamelCase__ , UpperCamelCase__ ) return f"bert/{name}" def create_tf_var(UpperCamelCase__ : np.ndarray , UpperCamelCase__ : str , UpperCamelCase__ : tf.Session ): A__ = tf.dtypes.as_dtype(tensor.dtype ) A__ = tf.get_variable(dtype=UpperCamelCase__ , shape=tensor.shape , name=UpperCamelCase__ , initializer=tf.zeros_initializer() ) session.run(tf.variables_initializer([tf_var] ) ) session.run(UpperCamelCase__ ) return tf_var tf.reset_default_graph() with tf.Session() as session: for var_name in state_dict: A__ = to_tf_var_name(UpperCamelCase__ ) A__ = state_dict[var_name].numpy() if any(x in var_name for x in tensors_to_transpose ): A__ = torch_tensor.T A__ = create_tf_var(tensor=UpperCamelCase__ , name=UpperCamelCase__ , session=UpperCamelCase__ ) tf.keras.backend.set_value(UpperCamelCase__ , UpperCamelCase__ ) A__ = session.run(UpperCamelCase__ ) print(f"Successfully created {tf_name}: {np.allclose(UpperCamelCase__ , UpperCamelCase__ )}" ) A__ = tf.train.Saver(tf.trainable_variables() ) saver.save(UpperCamelCase__ , os.path.join(UpperCamelCase__ , model_name.replace('''-''' , '''_''' ) + '''.ckpt''' ) ) def UpperCamelCase__( UpperCamelCase__ : int=None )->Tuple: A__ = argparse.ArgumentParser() parser.add_argument('''--model_name''' , type=UpperCamelCase__ , required=UpperCamelCase__ , help='''model name e.g. bert-base-uncased''' ) parser.add_argument( '''--cache_dir''' , type=UpperCamelCase__ , default=UpperCamelCase__ , required=UpperCamelCase__ , help='''Directory containing pytorch model''' ) parser.add_argument('''--pytorch_model_path''' , type=UpperCamelCase__ , required=UpperCamelCase__ , help='''/path/to/<pytorch-model-name>.bin''' ) parser.add_argument('''--tf_cache_dir''' , type=UpperCamelCase__ , required=UpperCamelCase__ , help='''Directory in which to save tensorflow model''' ) A__ = parser.parse_args(UpperCamelCase__ ) A__ = BertModel.from_pretrained( pretrained_model_name_or_path=args.model_name , state_dict=torch.load(args.pytorch_model_path ) , cache_dir=args.cache_dir , ) convert_pytorch_checkpoint_to_tf(model=UpperCamelCase__ , ckpt_dir=args.tf_cache_dir , model_name=args.model_name ) if __name__ == "__main__": main()
39
import functools import operator from ...configuration_utils import PretrainedConfig from ...utils import logging a__: List[Any] = logging.get_logger(__name__) a__: Optional[Any] = { 'microsoft/unispeech-large-1500h-cv': ( 'https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json' ), # See all UniSpeech models at https://huggingface.co/models?filter=unispeech } class SCREAMING_SNAKE_CASE__ ( UpperCamelCase__ ): __SCREAMING_SNAKE_CASE = '''unispeech''' def __init__( self,__lowerCamelCase=32,__lowerCamelCase=768,__lowerCamelCase=12,__lowerCamelCase=12,__lowerCamelCase=3072,__lowerCamelCase="gelu",__lowerCamelCase=0.1,__lowerCamelCase=0.1,__lowerCamelCase=0.1,__lowerCamelCase=0.0,__lowerCamelCase=0.0,__lowerCamelCase=0.1,__lowerCamelCase=0.1,__lowerCamelCase=0.02,__lowerCamelCase=1E-5,__lowerCamelCase="group",__lowerCamelCase="gelu",__lowerCamelCase=(512, 512, 512, 512, 512, 512, 512),__lowerCamelCase=(5, 2, 2, 2, 2, 2, 2),__lowerCamelCase=(10, 3, 3, 3, 3, 2, 2),__lowerCamelCase=False,__lowerCamelCase=128,__lowerCamelCase=16,__lowerCamelCase=False,__lowerCamelCase=True,__lowerCamelCase=0.05,__lowerCamelCase=10,__lowerCamelCase=2,__lowerCamelCase=0.0,__lowerCamelCase=10,__lowerCamelCase=0,__lowerCamelCase=320,__lowerCamelCase=2,__lowerCamelCase=0.1,__lowerCamelCase=100,__lowerCamelCase=256,__lowerCamelCase=256,__lowerCamelCase=0.1,__lowerCamelCase="mean",__lowerCamelCase=False,__lowerCamelCase=False,__lowerCamelCase=256,__lowerCamelCase=80,__lowerCamelCase=0,__lowerCamelCase=1,__lowerCamelCase=2,__lowerCamelCase=0.5,**__lowerCamelCase,): super().__init__(**__lowerCamelCase,pad_token_id=__lowerCamelCase,bos_token_id=__lowerCamelCase,eos_token_id=__lowerCamelCase ) A__ = hidden_size A__ = feat_extract_norm A__ = feat_extract_activation A__ = list(__lowerCamelCase ) A__ = list(__lowerCamelCase ) A__ = list(__lowerCamelCase ) A__ = conv_bias A__ = num_conv_pos_embeddings A__ = num_conv_pos_embedding_groups A__ = len(self.conv_dim ) A__ = num_hidden_layers A__ = intermediate_size A__ = hidden_act A__ = num_attention_heads A__ = hidden_dropout A__ = attention_dropout A__ = activation_dropout A__ = feat_proj_dropout A__ = final_dropout A__ = layerdrop A__ = layer_norm_eps A__ = initializer_range A__ = num_ctc_classes A__ = vocab_size A__ = do_stable_layer_norm A__ = use_weighted_layer_sum A__ = classifier_proj_size if ( (len(self.conv_stride ) != self.num_feat_extract_layers) or (len(self.conv_kernel ) != self.num_feat_extract_layers) or (len(self.conv_dim ) != self.num_feat_extract_layers) ): raise ValueError( '''Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` ==''' ''' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) =''' f" {len(self.conv_dim )}`, `len(config.conv_stride) = {len(self.conv_stride )}`," f" `len(config.conv_kernel) = {len(self.conv_kernel )}`." ) # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779 A__ = apply_spec_augment A__ = mask_time_prob A__ = mask_time_length A__ = mask_time_min_masks A__ = mask_feature_prob A__ = mask_feature_length A__ = mask_feature_min_masks # parameters for pretraining with codevector quantized representations A__ = num_codevectors_per_group A__ = num_codevector_groups A__ = contrastive_logits_temperature A__ = feat_quantizer_dropout A__ = num_negatives A__ = codevector_dim A__ = proj_codevector_dim A__ = diversity_loss_weight # ctc loss A__ = ctc_loss_reduction A__ = ctc_zero_infinity # pretraining loss A__ = replace_prob @property def UpperCamelCase ( self ): return functools.reduce(operator.mul,self.conv_stride,1 )
39
1
import json import os import tempfile import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ImageGPTImageProcessor class __A ( unittest.TestCase ): '''simple docstring''' def __init__( self , __lowerCAmelCase , __lowerCAmelCase=7 , __lowerCAmelCase=3 , __lowerCAmelCase=1_8 , __lowerCAmelCase=3_0 , __lowerCAmelCase=4_0_0 , __lowerCAmelCase=True , __lowerCAmelCase=None , __lowerCAmelCase=True , ): '''simple docstring''' lowerCamelCase__ = size if size is not None else {'height': 1_8, 'width': 1_8} lowerCamelCase__ = parent lowerCamelCase__ = batch_size lowerCamelCase__ = num_channels lowerCamelCase__ = image_size lowerCamelCase__ = min_resolution lowerCamelCase__ = max_resolution lowerCamelCase__ = do_resize lowerCamelCase__ = size lowerCamelCase__ = do_normalize def __lowerCamelCase ( self ): '''simple docstring''' return { # here we create 2 clusters for the sake of simplicity "clusters": np.asarray( [ [0.8866_4436_3403_3203, 0.6618_8293_6954_4983, 0.3891_7464_0178_6804], [-0.6042_5591_4688_1104, -0.0_2295_0088_6052_8469, 0.5423_7973_6900_3296], ] ), "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, } @require_torch @require_vision class __A ( _a , unittest.TestCase ): '''simple docstring''' lowerCAmelCase_ = ImageGPTImageProcessor if is_vision_available() else None def __lowerCamelCase ( self ): '''simple docstring''' lowerCamelCase__ = ImageGPTImageProcessingTester(self ) @property def __lowerCamelCase ( self ): '''simple docstring''' return self.image_processor_tester.prepare_image_processor_dict() def __lowerCamelCase ( self ): '''simple docstring''' lowerCamelCase__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__lowerCAmelCase , '''clusters''' ) ) self.assertTrue(hasattr(__lowerCAmelCase , '''do_resize''' ) ) self.assertTrue(hasattr(__lowerCAmelCase , '''size''' ) ) self.assertTrue(hasattr(__lowerCAmelCase , '''do_normalize''' ) ) def __lowerCamelCase ( self ): '''simple docstring''' lowerCamelCase__ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''height''': 1_8, '''width''': 1_8} ) lowerCamelCase__ = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 ) self.assertEqual(image_processor.size , {'''height''': 4_2, '''width''': 4_2} ) def __lowerCamelCase ( self ): '''simple docstring''' lowerCamelCase__ = self.image_processing_class(**self.image_processor_dict ) lowerCamelCase__ = json.loads(image_processor.to_json_string() ) for key, value in self.image_processor_dict.items(): if key == "clusters": self.assertTrue(np.array_equal(__lowerCAmelCase , obj[key] ) ) else: self.assertEqual(obj[key] , __lowerCAmelCase ) def __lowerCamelCase ( self ): '''simple docstring''' lowerCamelCase__ = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: lowerCamelCase__ = os.path.join(__lowerCAmelCase , '''image_processor.json''' ) image_processor_first.to_json_file(__lowerCAmelCase ) lowerCamelCase__ = self.image_processing_class.from_json_file(__lowerCAmelCase ).to_dict() lowerCamelCase__ = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(__lowerCAmelCase , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , __lowerCAmelCase ) def __lowerCamelCase ( self ): '''simple docstring''' lowerCamelCase__ = self.image_processing_class(**self.image_processor_dict ) with tempfile.TemporaryDirectory() as tmpdirname: image_processor_first.save_pretrained(__lowerCAmelCase ) lowerCamelCase__ = self.image_processing_class.from_pretrained(__lowerCAmelCase ).to_dict() lowerCamelCase__ = image_processor_first.to_dict() for key, value in image_processor_first.items(): if key == "clusters": self.assertTrue(np.array_equal(__lowerCAmelCase , image_processor_second[key] ) ) else: self.assertEqual(image_processor_first[key] , __lowerCAmelCase ) @unittest.skip('''ImageGPT requires clusters at initialization''' ) def __lowerCamelCase ( self ): '''simple docstring''' pass def lowerCAmelCase__() -> Tuple: '''simple docstring''' lowerCamelCase__ = load_dataset('''hf-internal-testing/fixtures_image_utils''' ,split='''test''' ) lowerCamelCase__ = Image.open(dataset[4]['''file'''] ) lowerCamelCase__ = Image.open(dataset[5]['''file'''] ) lowerCamelCase__ = [imagea, imagea] return images @require_vision @require_torch class __A ( unittest.TestCase ): '''simple docstring''' @slow def __lowerCamelCase ( self ): '''simple docstring''' lowerCamelCase__ = ImageGPTImageProcessor.from_pretrained('''openai/imagegpt-small''' ) lowerCamelCase__ = prepare_images() # test non-batched lowerCamelCase__ = image_processing(images[0] , return_tensors='''pt''' ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (1, 1_0_2_4) ) lowerCamelCase__ = [3_0_6, 1_9_1, 1_9_1] self.assertEqual(encoding.input_ids[0, :3].tolist() , __lowerCAmelCase ) # test batched lowerCamelCase__ = image_processing(__lowerCAmelCase , return_tensors='''pt''' ) self.assertIsInstance(encoding.input_ids , torch.LongTensor ) self.assertEqual(encoding.input_ids.shape , (2, 1_0_2_4) ) lowerCamelCase__ = [3_0_3, 1_3, 1_3] self.assertEqual(encoding.input_ids[1, -3:].tolist() , __lowerCAmelCase )
209
import unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class _lowerCamelCase( _a ): def __init__( self, lowerCamelCase, lowerCamelCase=13, lowerCamelCase=7, lowerCamelCase=True, lowerCamelCase=True, lowerCamelCase=False, lowerCamelCase=True, lowerCamelCase=99, lowerCamelCase=32, lowerCamelCase=5, lowerCamelCase=4, lowerCamelCase=64, lowerCamelCase="gelu", lowerCamelCase=0.1, lowerCamelCase=0.1, lowerCamelCase=5_12, lowerCamelCase=16, lowerCamelCase=2, lowerCamelCase=0.0_2, lowerCamelCase=3, lowerCamelCase=4, lowerCamelCase=None, lowerCamelCase=2, lowerCamelCase=2, lowerCamelCase=2, lowerCamelCase=2, lowerCamelCase=4, lowerCamelCase=1, ) -> Union[str, Any]: """simple docstring""" _lowercase : Dict = parent _lowercase : Optional[Any] = batch_size _lowercase : Any = seq_length _lowercase : Optional[Any] = is_training _lowercase : Optional[Any] = use_input_mask _lowercase : List[Any] = use_token_type_ids _lowercase : List[str] = use_labels _lowercase : str = vocab_size _lowercase : List[str] = hidden_size _lowercase : Dict = num_hidden_layers _lowercase : List[str] = num_attention_heads _lowercase : int = intermediate_size _lowercase : Union[str, Any] = hidden_act _lowercase : int = hidden_dropout_prob _lowercase : List[Any] = attention_probs_dropout_prob _lowercase : Dict = max_position_embeddings _lowercase : Union[str, Any] = type_vocab_size _lowercase : List[Any] = type_sequence_label_size _lowercase : Any = initializer_range _lowercase : List[str] = num_labels _lowercase : Any = num_choices _lowercase : Tuple = scope _lowercase : Optional[Any] = q_groups _lowercase : List[str] = k_groups _lowercase : Optional[int] = v_groups _lowercase : List[str] = post_attention_groups _lowercase : Union[str, Any] = intermediate_groups _lowercase : int = output_groups def UpperCamelCase ( self) -> Optional[int]: """simple docstring""" _lowercase : int = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) _lowercase : Any = None if self.use_input_mask: _lowercase : Tuple = random_attention_mask([self.batch_size, self.seq_length]) _lowercase : Dict = None _lowercase : int = None _lowercase : List[Any] = None if self.use_labels: _lowercase : List[Any] = ids_tensor([self.batch_size], self.type_sequence_label_size) _lowercase : int = ids_tensor([self.batch_size, self.seq_length], self.num_labels) _lowercase : Dict = ids_tensor([self.batch_size], self.num_choices) _lowercase : Optional[Any] = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase ( self) -> Optional[int]: """simple docstring""" 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 UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase) -> Union[str, Any]: """simple docstring""" _lowercase : List[str] = SqueezeBertModel(config=lowerCamelCase) model.to(lowerCamelCase) model.eval() _lowercase : Dict = model(lowerCamelCase, lowerCamelCase) _lowercase : Any = model(lowerCamelCase) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase) -> int: """simple docstring""" _lowercase : Dict = SqueezeBertForMaskedLM(config=lowerCamelCase) model.to(lowerCamelCase) model.eval() _lowercase : Optional[Any] = model(lowerCamelCase, attention_mask=lowerCamelCase, labels=lowerCamelCase) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase) -> Union[str, Any]: """simple docstring""" _lowercase : Union[str, Any] = SqueezeBertForQuestionAnswering(config=lowerCamelCase) model.to(lowerCamelCase) model.eval() _lowercase : List[Any] = model( lowerCamelCase, attention_mask=lowerCamelCase, start_positions=lowerCamelCase, end_positions=lowerCamelCase) self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase) -> str: """simple docstring""" _lowercase : Optional[Any] = self.num_labels _lowercase : int = SqueezeBertForSequenceClassification(lowerCamelCase) model.to(lowerCamelCase) model.eval() _lowercase : Any = model(lowerCamelCase, attention_mask=lowerCamelCase, labels=lowerCamelCase) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase) -> List[Any]: """simple docstring""" _lowercase : Union[str, Any] = self.num_labels _lowercase : List[str] = SqueezeBertForTokenClassification(config=lowerCamelCase) model.to(lowerCamelCase) model.eval() _lowercase : Union[str, Any] = model(lowerCamelCase, attention_mask=lowerCamelCase, labels=lowerCamelCase) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase) -> Dict: """simple docstring""" _lowercase : str = self.num_choices _lowercase : str = SqueezeBertForMultipleChoice(config=lowerCamelCase) model.to(lowerCamelCase) model.eval() _lowercase : Dict = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() _lowercase : int = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() _lowercase : Optional[Any] = model( lowerCamelCase, attention_mask=lowerCamelCase, labels=lowerCamelCase, ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) def UpperCamelCase ( self) -> List[str]: """simple docstring""" _lowercase : Optional[int] = self.prepare_config_and_inputs() ((_lowercase) , (_lowercase) , (_lowercase) , (_lowercase) , (_lowercase) , (_lowercase)) : Dict = config_and_inputs _lowercase : Tuple = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class _lowerCamelCase( _a, _a, unittest.TestCase ): lowercase_ : Union[str, Any] = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) lowercase_ : Optional[int] = ( { """feature-extraction""": SqueezeBertModel, """fill-mask""": SqueezeBertForMaskedLM, """question-answering""": SqueezeBertForQuestionAnswering, """text-classification""": SqueezeBertForSequenceClassification, """token-classification""": SqueezeBertForTokenClassification, """zero-shot""": SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) lowercase_ : Tuple = False lowercase_ : List[str] = True lowercase_ : int = False def UpperCamelCase ( self) -> int: """simple docstring""" _lowercase : str = SqueezeBertModelTester(self) _lowercase : Dict = ConfigTester(self, config_class=lowerCamelCase, dim=37) def UpperCamelCase ( self) -> List[str]: """simple docstring""" self.config_tester.run_common_tests() def UpperCamelCase ( self) -> Tuple: """simple docstring""" _lowercase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*lowerCamelCase) def UpperCamelCase ( self) -> List[str]: """simple docstring""" _lowercase : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*lowerCamelCase) def UpperCamelCase ( self) -> Any: """simple docstring""" _lowercase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*lowerCamelCase) def UpperCamelCase ( self) -> Union[str, Any]: """simple docstring""" _lowercase : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*lowerCamelCase) def UpperCamelCase ( self) -> Any: """simple docstring""" _lowercase : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*lowerCamelCase) def UpperCamelCase ( self) -> Optional[int]: """simple docstring""" _lowercase : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*lowerCamelCase) @slow def UpperCamelCase ( self) -> Dict: """simple docstring""" for model_name in SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: _lowercase : List[Any] = SqueezeBertModel.from_pretrained(lowerCamelCase) self.assertIsNotNone(lowerCamelCase) @require_sentencepiece @require_tokenizers @require_torch class _lowerCamelCase( unittest.TestCase ): @slow def UpperCamelCase ( self) -> Optional[Any]: """simple docstring""" _lowercase : Union[str, Any] = SqueezeBertForSequenceClassification.from_pretrained('squeezebert/squeezebert-mnli') _lowercase : Optional[int] = torch.tensor([[1, 2_94_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69, 13, 15_88, 2]]) _lowercase : List[str] = model(lowerCamelCase)[0] _lowercase : Union[str, Any] = torch.Size((1, 3)) self.assertEqual(output.shape, lowerCamelCase) _lowercase : Tuple = torch.tensor([[0.6_4_0_1, -0.0_3_4_9, -0.6_0_4_1]]) self.assertTrue(torch.allclose(lowerCamelCase, lowerCamelCase, atol=1E-4))
21
0
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging a : Any = logging.get_logger(__name__) a : List[Any] = {"""vocab_file""": """sentencepiece.bpe.model"""} a : Optional[Any] = { """vocab_file""": { """moussaKam/mbarthez""": """https://huggingface.co/moussaKam/mbarthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez""": """https://huggingface.co/moussaKam/barthez/resolve/main/sentencepiece.bpe.model""", """moussaKam/barthez-orangesum-title""": ( """https://huggingface.co/moussaKam/barthez-orangesum-title/resolve/main/sentencepiece.bpe.model""" ), }, } a : str = { """moussaKam/mbarthez""": 1024, """moussaKam/barthez""": 1024, """moussaKam/barthez-orangesum-title""": 1024, } a : Union[str, Any] = """▁""" class a ( __A ): snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = ['input_ids', 'attention_mask'] def __init__( self : int , lowercase_ : List[str] , lowercase_ : List[str]="<s>" , lowercase_ : Union[str, Any]="</s>" , lowercase_ : str="</s>" , lowercase_ : List[str]="<s>" , lowercase_ : Dict="<unk>" , lowercase_ : Optional[int]="<pad>" , lowercase_ : List[str]="<mask>" , lowercase_ : str = None , **lowercase_ : Any , ): # Mask token behave like a normal word, i.e. include the space before it snake_case_ = AddedToken(__lowercase , lstrip=__lowercase , rstrip=__lowercase ) if isinstance(__lowercase , __lowercase ) else mask_token snake_case_ = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=__lowercase , eos_token=__lowercase , unk_token=__lowercase , sep_token=__lowercase , cls_token=__lowercase , pad_token=__lowercase , mask_token=__lowercase , sp_model_kwargs=self.sp_model_kwargs , **__lowercase , ) snake_case_ = vocab_file snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(__lowercase ) ) snake_case_ = {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3} snake_case_ = len(self.sp_model ) - 1 snake_case_ = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def A_ ( self : Dict , lowercase_ : Any , lowercase_ : int = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] snake_case_ = [self.cls_token_id] snake_case_ = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def A_ ( self : Optional[Any] , lowercase_ : Union[str, Any] , lowercase_ : List[Any] = None , lowercase_ : Any = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__lowercase , token_ids_a=__lowercase , already_has_special_tokens=__lowercase ) if token_ids_a is None: return [1] + ([0] * len(__lowercase )) + [1] return [1] + ([0] * len(__lowercase )) + [1, 1] + ([0] * len(__lowercase )) + [1] def A_ ( self : Any , lowercase_ : int , lowercase_ : Any = None ): snake_case_ = [self.sep_token_id] snake_case_ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def A_ ( self : Optional[Any] ): return len(self.sp_model ) def A_ ( self : int ): snake_case_ = {self.convert_ids_to_tokens(__lowercase ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def A_ ( self : Optional[int] , lowercase_ : List[Any] ): return self.sp_model.encode(__lowercase , out_type=__lowercase ) def A_ ( self : Optional[int] , lowercase_ : int ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] snake_case_ = self.sp_model.PieceToId(__lowercase ) return spm_id if spm_id else self.unk_token_id def A_ ( self : Dict , lowercase_ : str ): if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(__lowercase ) def A_ ( self : Optional[int] , lowercase_ : Optional[Any] ): snake_case_ = [] snake_case_ = '''''' snake_case_ = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(__lowercase ) + token snake_case_ = True snake_case_ = [] else: current_sub_tokens.append(__lowercase ) snake_case_ = False out_string += self.sp_model.decode(__lowercase ) return out_string.strip() def __getstate__( self : int ): snake_case_ = self.__dict__.copy() snake_case_ = None return state def __setstate__( self : int , lowercase_ : Dict ): snake_case_ = d # for backward compatibility if not hasattr(self , '''sp_model_kwargs''' ): snake_case_ = {} snake_case_ = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def A_ ( self : List[str] , lowercase_ : Dict , lowercase_ : Optional[Any] = None ): if not os.path.isdir(__lowercase ): logger.error(F"Vocabulary path ({save_directory}) should be a directory" ) return snake_case_ = os.path.join( __lowercase , (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowercase ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __lowercase ) elif not os.path.isfile(self.vocab_file ): with open(__lowercase , '''wb''' ) as fi: snake_case_ = self.sp_model.serialized_model_proto() fi.write(__lowercase ) return (out_vocab_file,)
359
'''simple docstring''' import json import multiprocessing import os import re from collections import defaultdict import torch from accelerate import Accelerator from accelerate.utils import set_seed from arguments import HumanEvalArguments from datasets import load_dataset, load_metric from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from tqdm import tqdm import transformers from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, StoppingCriteria, StoppingCriteriaList a : str = ['\nclass', '\ndef', '\n#', '\n@', '\nprint', '\nif'] class a ( _lowerCamelCase ): def __init__( self : List[Any] , lowercase_ : Union[str, Any] , lowercase_ : Dict , lowercase_ : Optional[int]=None , lowercase_ : str=1 ): snake_case_ = tokenizer snake_case_ = dataset snake_case_ = len(lowercase_ ) if n_tasks is None else n_tasks snake_case_ = n_copies def __iter__( self : Optional[Any] ): snake_case_ = [] for task in range(self.n_tasks ): # without strip, the model generate commented codes ... prompts.append(self.tokenizer.eos_token + self.dataset[task]['''prompt'''].strip() ) snake_case_ = self.tokenizer(lowercase_ , padding=lowercase_ , return_tensors='''pt''' ) for task in range(self.n_tasks ): for _ in range(self.n_copies ): yield { "ids": outputs.input_ids[task], "task_id": task, "input_len": outputs.attention_mask[task].sum(), } class a ( _lowerCamelCase ): def __init__( self : str , lowercase_ : Tuple , lowercase_ : Optional[int] , lowercase_ : int ): snake_case_ = start_length snake_case_ = eof_strings snake_case_ = tokenizer def __call__( self : List[Any] , lowercase_ : str , lowercase_ : Optional[int] , **lowercase_ : List[str] ): snake_case_ = self.tokenizer.batch_decode(input_ids[:, self.start_length :] ) snake_case_ = [] for decoded_generation in decoded_generations: done.append(any(stop_string in decoded_generation for stop_string in self.eof_strings ) ) return all(lowercase_ ) def __magic_name__ ( __UpperCAmelCase ) -> Any: '''simple docstring''' snake_case_ = re.split('''(%s)''' % '''|'''.join(__UpperCAmelCase ), __UpperCAmelCase ) # last string should be "" return "".join(string_list[:-2] ) def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase=20, **__UpperCAmelCase ) -> str: '''simple docstring''' snake_case_ = defaultdict(__UpperCAmelCase ) # dict of list of generated tokens for step, batch in tqdm(enumerate(__UpperCAmelCase ) ): with torch.no_grad(): snake_case_ = batch['''ids'''].shape[-1] snake_case_ = accelerator.unwrap_model(__UpperCAmelCase ).generate( input_ids=batch['''ids'''][:, : batch['''input_len''']], num_return_sequences=__UpperCAmelCase, **__UpperCAmelCase ) # each task is generated batch_size times snake_case_ = batch['''task_id'''].repeat(__UpperCAmelCase ) snake_case_ = accelerator.pad_across_processes( __UpperCAmelCase, dim=1, pad_index=tokenizer.pad_token_id ) snake_case_ ,snake_case_ = accelerator.gather((generated_tokens, generated_tasks) ) snake_case_ = generated_tokens.cpu().numpy() snake_case_ = generated_tasks.cpu().numpy() for task, generated_tokens in zip(__UpperCAmelCase, __UpperCAmelCase ): gen_token_dict[task].append(__UpperCAmelCase ) snake_case_ = [[] for _ in range(__UpperCAmelCase )] for task, generated_tokens in gen_token_dict.items(): for s in generated_tokens: snake_case_ = tokenizer.decode(__UpperCAmelCase, skip_special_tokens=__UpperCAmelCase, clean_up_tokenization_spaces=__UpperCAmelCase ) code_gens[task].append(remove_last_block(__UpperCAmelCase ) ) return code_gens def __magic_name__ ( ) -> Tuple: '''simple docstring''' snake_case_ = HfArgumentParser(__UpperCAmelCase ) snake_case_ = parser.parse_args() transformers.logging.set_verbosity_error() # enables code execution in code_eval metric snake_case_ = args.HF_ALLOW_CODE_EVAL # make sure tokenizer plays nice with multiprocessing snake_case_ = '''false''' if args.num_workers is None: snake_case_ = multiprocessing.cpu_count() # Use dataset load to feed to accelerate snake_case_ = Accelerator() set_seed(args.seed, device_specific=__UpperCAmelCase ) # Load model and tokenizer snake_case_ = AutoTokenizer.from_pretrained(args.model_ckpt ) snake_case_ = tokenizer.eos_token snake_case_ = AutoModelForCausalLM.from_pretrained(args.model_ckpt ) # Generation settings snake_case_ = { '''do_sample''': args.do_sample, '''temperature''': args.temperature, '''max_new_tokens''': args.max_new_tokens, '''top_p''': args.top_p, '''top_k''': args.top_k, '''stopping_criteria''': StoppingCriteriaList([EndOfFunctionCriteria(0, __UpperCAmelCase, __UpperCAmelCase )] ), } # Load evaluation dataset and metric snake_case_ = load_dataset('''openai_humaneval''' ) snake_case_ = load_metric('''code_eval''' ) snake_case_ = args.num_tasks if args.num_tasks is not None else len(human_eval['''test'''] ) snake_case_ = args.n_samples // args.batch_size snake_case_ = TokenizedDataset(__UpperCAmelCase, human_eval['''test'''], n_copies=__UpperCAmelCase, n_tasks=__UpperCAmelCase ) # do not confuse args.batch_size, which is actually the num_return_sequences snake_case_ = DataLoader(__UpperCAmelCase, batch_size=1 ) # Run a quick test to see if code evaluation is enabled try: snake_case_ = code_eval_metric.compute(references=[''''''], predictions=[['''''']] ) except ValueError as exception: print( '''Code evaluation not enabled. Read the warning below carefully and then use `--HF_ALLOW_CODE_EVAL="1"`''' ''' flag to enable code evaluation.''' ) raise exception snake_case_ ,snake_case_ = accelerator.prepare(__UpperCAmelCase, __UpperCAmelCase ) snake_case_ = complete_code( __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, __UpperCAmelCase, n_tasks=__UpperCAmelCase, batch_size=args.batch_size, **__UpperCAmelCase, ) if accelerator.is_main_process: snake_case_ = [] for task in tqdm(range(__UpperCAmelCase ) ): snake_case_ = human_eval['''test'''][task]['''test'''] snake_case_ = F"check({human_eval['test'][task]['entry_point']})" references.append('''\n''' + test_func + '''\n''' + entry_point ) # Evaluate completions with "code_eval" metric snake_case_ ,snake_case_ = code_eval_metric.compute( references=__UpperCAmelCase, predictions=__UpperCAmelCase, num_workers=args.num_workers ) print(F"Results: {pass_at_k}" ) # Save results to json file with open(args.output_file, '''w''' ) as fp: json.dump(__UpperCAmelCase, __UpperCAmelCase ) # For some reason the folliwng seems to be necessary sometimes for code_eval to work nice with multiprocessing # https://stackoverflow.com/questions/60804599/python-multiprocessing-keeps-spawning-the-whole-script if __name__ == "__main__": main()
72
0
'''simple docstring''' from __future__ import annotations from PIL import Image # Define glider example a : Optional[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 a : List[Any] = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] def __magic_name__ ( __UpperCAmelCase ) -> list[list[int]]: '''simple docstring''' snake_case_ = [] for i in range(len(__UpperCAmelCase ) ): snake_case_ = [] for j in range(len(cells[i] ) ): # Get the number of live neighbours snake_case_ = 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(__UpperCAmelCase ) - 1 and j > 0: neighbour_count += cells[i + 1][j - 1] if i < len(__UpperCAmelCase ) - 1: neighbour_count += cells[i + 1][j] if i < len(__UpperCAmelCase ) - 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. snake_case_ = 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(__UpperCAmelCase ) return next_generation def __magic_name__ ( __UpperCAmelCase, __UpperCAmelCase ) -> list[Image.Image]: '''simple docstring''' snake_case_ = [] for _ in range(__UpperCAmelCase ): # Create output image snake_case_ = Image.new('''RGB''', (len(cells[0] ), len(__UpperCAmelCase )) ) snake_case_ = img.load() # Save cells to image for x in range(len(__UpperCAmelCase ) ): for y in range(len(cells[0] ) ): snake_case_ = 255 - cells[y][x] * 255 snake_case_ = (colour, colour, colour) # Save image images.append(__UpperCAmelCase ) snake_case_ = new_generation(__UpperCAmelCase ) return images if __name__ == "__main__": a : Dict = generate_images(GLIDER, 16) images[0].save('out.gif', save_all=True, append_images=images[1:])
56
import requests def UpperCAmelCase ( lowercase , lowercase ): """simple docstring""" __lowercase = {'''Content-Type''': '''application/json'''} __lowercase = requests.post(lowercase , json={'''text''': message_body} , headers=lowercase ) if response.status_code != 200: __lowercase = ( '''Request to slack returned an error ''' F"{response.status_code}, the response is:\n{response.text}" ) raise ValueError(lowercase ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message("""<YOUR MESSAGE BODY>""", """<SLACK CHANNEL URL>""")
210
0
import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class _snake_case ( unittest.TestCase ): def SCREAMING_SNAKE_CASE__ ( self) -> List[Any]: SCREAMING_SNAKE_CASE = inspect.getfile(accelerate.test_utils) SCREAMING_SNAKE_CASE = os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ['scripts', 'test_script.py']) SCREAMING_SNAKE_CASE = os.path.sep.join( mod_file.split(os.path.sep)[:-1] + ['scripts', 'test_distributed_data_loop.py']) SCREAMING_SNAKE_CASE = os.path.sep.join(mod_file.split(os.path.sep)[:-1] + ['scripts', 'test_ops.py']) @require_multi_gpu def SCREAMING_SNAKE_CASE__ ( self) -> Union[str, Any]: print(f'''Found {torch.cuda.device_count()} devices.''') SCREAMING_SNAKE_CASE = ['torchrun', f'''--nproc_per_node={torch.cuda.device_count()}''', self.test_file_path] with patch_environment(omp_num_threads=1): execute_subprocess_async(A__ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: print(f'''Found {torch.cuda.device_count()} devices.''') SCREAMING_SNAKE_CASE = ['torchrun', f'''--nproc_per_node={torch.cuda.device_count()}''', self.operation_file_path] print(f'''Command: {cmd}''') with patch_environment(omp_num_threads=1): execute_subprocess_async(A__ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE__ ( self) -> Optional[Any]: SCREAMING_SNAKE_CASE = ['torchrun', f'''--nproc_per_node={torch.cuda.device_count()}''', inspect.getfile(self.__class__)] with patch_environment(omp_num_threads=1): execute_subprocess_async(A__ , env=os.environ.copy()) @require_multi_gpu def SCREAMING_SNAKE_CASE__ ( self) -> List[str]: print(f'''Found {torch.cuda.device_count()} devices, using 2 devices only''') SCREAMING_SNAKE_CASE = ['torchrun', f'''--nproc_per_node={torch.cuda.device_count()}''', self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices='0,1'): execute_subprocess_async(A__ , env=os.environ.copy()) if __name__ == "__main__": a_ : Union[str, Any] = Accelerator() a_ : int = (accelerator.state.process_index + 2, 10) a_ : Any = torch.randint(0, 10, shape).to(accelerator.device) a_ : str = "" a_ : List[str] = accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." a_ : List[Any] = accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." a_ : int = accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
359
import logging import os import quant_trainer import torch from torch.utils.data import DataLoader from transformers import Trainer, is_torch_tpu_available from transformers.trainer_utils import PredictionOutput a_ : Dict = logging.getLogger(__name__) if is_torch_tpu_available(check_device=False): import torch_xla.core.xla_model as xm import torch_xla.debug.metrics as met class _snake_case ( A__ ): def __init__( self , *a , a=None , a=None , a=None , **a) -> List[Any]: super().__init__(*a , **a) SCREAMING_SNAKE_CASE = eval_examples SCREAMING_SNAKE_CASE = post_process_function SCREAMING_SNAKE_CASE = quant_trainer_args SCREAMING_SNAKE_CASE = 128 # default number of calibration samples def SCREAMING_SNAKE_CASE__ ( self , a=None) -> Union[str, Any]: if calib_dataset is None and self.calib_dataset is None: raise ValueError('Trainer: calibration requires an calib_dataset.') SCREAMING_SNAKE_CASE = calib_dataset if calib_dataset is not None else self.calib_dataset SCREAMING_SNAKE_CASE = self._remove_unused_columns(a , description='Calibration') return DataLoader( a , batch_size=self.args.eval_batch_size , collate_fn=self.data_collator , drop_last=self.args.dataloader_drop_last , num_workers=self.args.dataloader_num_workers , pin_memory=self.args.dataloader_pin_memory , shuffle=a , ) def SCREAMING_SNAKE_CASE__ ( self , a=None) -> Optional[Any]: SCREAMING_SNAKE_CASE = self.train_dataset if calib_dataset is None else calib_dataset SCREAMING_SNAKE_CASE = self.get_calib_dataloader(a) SCREAMING_SNAKE_CASE = self.model quant_trainer.configure_model(a , self.quant_trainer_args , calib=a) model.eval() quant_trainer.enable_calibration(a) logger.info('***** Running calibration *****') logger.info(f''' Num examples = {self.calib_num}''') logger.info(f''' Batch size = {calib_dataloader.batch_size}''') for step, inputs in enumerate(a): # Prediction step SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = self.prediction_step(a , a , prediction_loss_only=a) if (step + 1) * calib_dataloader.batch_size >= self.calib_num: break quant_trainer.finish_calibration(a , self.quant_trainer_args) SCREAMING_SNAKE_CASE = model def SCREAMING_SNAKE_CASE__ ( self , a=None , a=None , a=None , a = "eval") -> str: SCREAMING_SNAKE_CASE = self.eval_dataset if eval_dataset is None else eval_dataset SCREAMING_SNAKE_CASE = self.get_eval_dataloader(a) SCREAMING_SNAKE_CASE = self.eval_examples if eval_examples is None else eval_examples # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE = self.compute_metrics SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE = eval_loop( a , description='Evaluation' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=a , ) finally: SCREAMING_SNAKE_CASE = compute_metrics if self.post_process_function is not None and self.compute_metrics is not None: SCREAMING_SNAKE_CASE = self.post_process_function(a , a , output.predictions) SCREAMING_SNAKE_CASE = self.compute_metrics(a) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys()): if not key.startswith(f'''{metric_key_prefix}_'''): SCREAMING_SNAKE_CASE = metrics.pop(a) self.log(a) else: SCREAMING_SNAKE_CASE = {} if self.args.tpu_metrics_debug or self.args.debug: # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) xm.master_print(met.metrics_report()) SCREAMING_SNAKE_CASE = self.callback_handler.on_evaluate(self.args , self.state , self.control , a) return metrics def SCREAMING_SNAKE_CASE__ ( self , a , a , a=None , a = "test") -> Optional[Any]: SCREAMING_SNAKE_CASE = self.get_test_dataloader(a) # Temporarily disable metric computation, we will do it in the loop here. SCREAMING_SNAKE_CASE = self.compute_metrics SCREAMING_SNAKE_CASE = None SCREAMING_SNAKE_CASE = self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop try: SCREAMING_SNAKE_CASE = eval_loop( a , description='Prediction' , prediction_loss_only=True if compute_metrics is None else None , ignore_keys=a , ) finally: SCREAMING_SNAKE_CASE = compute_metrics if self.post_process_function is None or self.compute_metrics is None: return output SCREAMING_SNAKE_CASE = self.post_process_function(a , a , output.predictions , 'predict') SCREAMING_SNAKE_CASE = self.compute_metrics(a) # Prefix all keys with metric_key_prefix + '_' for key in list(metrics.keys()): if not key.startswith(f'''{metric_key_prefix}_'''): SCREAMING_SNAKE_CASE = metrics.pop(a) return PredictionOutput(predictions=predictions.predictions , label_ids=predictions.label_ids , metrics=a) def SCREAMING_SNAKE_CASE__ ( self , a="./") -> List[Any]: SCREAMING_SNAKE_CASE = self.eval_dataset SCREAMING_SNAKE_CASE = self.get_eval_dataloader(a) SCREAMING_SNAKE_CASE = next(iter(a)) # saving device - to make it consistent SCREAMING_SNAKE_CASE = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # convert to tuple SCREAMING_SNAKE_CASE = tuple(v.to(a) for k, v in batch.items()) logger.info('Converting model to be onnx compatible') from pytorch_quantization.nn import TensorQuantizer SCREAMING_SNAKE_CASE = True SCREAMING_SNAKE_CASE = self.model.to(a) model.eval() model.float() SCREAMING_SNAKE_CASE = model.module if hasattr(a , 'module') else model quant_trainer.configure_model(a , self.quant_trainer_args) SCREAMING_SNAKE_CASE = os.path.join(a , 'model.onnx') logger.info(f'''exporting model to {output_model_file}''') SCREAMING_SNAKE_CASE = {0: 'batch_size', 1: 'seq_len'} torch.onnx.export( a , a , a , export_params=a , opset_version=13 , do_constant_folding=a , input_names=['input_ids', 'attention_mask', 'token_type_ids'] , output_names=['output_start_logits', 'output_end_logits'] , dynamic_axes={ 'input_ids': axes, 'attention_mask': axes, 'token_type_ids': axes, 'output_start_logits': axes, 'output_end_logits': axes, } , verbose=a , ) logger.info('onnx export finished')
327
0
from collections import OrderedDict from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import TensorType, logging if TYPE_CHECKING: from ...onnx.config import PatchingSpec from ...tokenization_utils_base import PreTrainedTokenizerBase lowerCAmelCase__ : Optional[Any] =logging.get_logger(__name__) lowerCAmelCase__ : Tuple ={ '''allenai/longformer-base-4096''': '''https://huggingface.co/allenai/longformer-base-4096/resolve/main/config.json''', '''allenai/longformer-large-4096''': '''https://huggingface.co/allenai/longformer-large-4096/resolve/main/config.json''', '''allenai/longformer-large-4096-finetuned-triviaqa''': ( '''https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/config.json''' ), '''allenai/longformer-base-4096-extra.pos.embd.only''': ( '''https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/config.json''' ), '''allenai/longformer-large-4096-extra.pos.embd.only''': ( '''https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/config.json''' ), } class UpperCAmelCase_ ( UpperCamelCase_ ): '''simple docstring''' UpperCamelCase__ : Optional[int] = "longformer" def __init__( self , _A = 512 , _A = 2 , _A = 1 , _A = 0 , _A = 2 , _A = 30_522 , _A = 768 , _A = 12 , _A = 12 , _A = 3_072 , _A = "gelu" , _A = 0.1 , _A = 0.1 , _A = 512 , _A = 2 , _A = 0.0_2 , _A = 1e-12 , _A = False , **_A , ): '''simple docstring''' super().__init__(pad_token_id=snake_case__ , **snake_case__ ) __SCREAMING_SNAKE_CASE = attention_window __SCREAMING_SNAKE_CASE = sep_token_id __SCREAMING_SNAKE_CASE = bos_token_id __SCREAMING_SNAKE_CASE = eos_token_id __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_hidden_layers __SCREAMING_SNAKE_CASE = num_attention_heads __SCREAMING_SNAKE_CASE = hidden_act __SCREAMING_SNAKE_CASE = intermediate_size __SCREAMING_SNAKE_CASE = hidden_dropout_prob __SCREAMING_SNAKE_CASE = attention_probs_dropout_prob __SCREAMING_SNAKE_CASE = max_position_embeddings __SCREAMING_SNAKE_CASE = type_vocab_size __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = layer_norm_eps __SCREAMING_SNAKE_CASE = onnx_export class UpperCAmelCase_ ( UpperCamelCase_ ): '''simple docstring''' def __init__( self , _A , _A = "default" , _A = None ): '''simple docstring''' super().__init__(snake_case__ , snake_case__ , snake_case__ ) __SCREAMING_SNAKE_CASE = True @property def _A ( self ): '''simple docstring''' if self.task == "multiple-choice": __SCREAMING_SNAKE_CASE = {0: "batch", 1: "choice", 2: "sequence"} else: __SCREAMING_SNAKE_CASE = {0: "batch", 1: "sequence"} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ('global_attention_mask', dynamic_axis), ] ) @property def _A ( self ): '''simple docstring''' __SCREAMING_SNAKE_CASE = super().outputs if self.task == "default": __SCREAMING_SNAKE_CASE = {0: "batch"} return outputs @property def _A ( self ): '''simple docstring''' return 1e-4 @property def _A ( self ): '''simple docstring''' return max(super().default_onnx_opset , 14 ) def _A ( self , _A , _A = -1 , _A = -1 , _A = False , _A = None , ): '''simple docstring''' __SCREAMING_SNAKE_CASE = super().generate_dummy_inputs( preprocessor=snake_case__ , batch_size=snake_case__ , seq_length=snake_case__ , is_pair=snake_case__ , framework=snake_case__ ) import torch # for some reason, replacing this code by inputs["global_attention_mask"] = torch.randint(2, inputs["input_ids"].shape, dtype=torch.int64) # makes the export fail randomly __SCREAMING_SNAKE_CASE = torch.zeros_like(inputs['input_ids'] ) # make every second token global __SCREAMING_SNAKE_CASE = 1 return inputs
257
"""simple docstring""" from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class SCREAMING_SNAKE_CASE__ : """simple docstring""" a : int a : TreeNode | None =None a : TreeNode | None =None lowerCAmelCase__ = namedtuple('''CoinsDistribResult''', '''moves excess''') def a__ ( SCREAMING_SNAKE_CASE : TreeNode | None ): '''simple docstring''' if root is None: return 0 # Validation def count_nodes(SCREAMING_SNAKE_CASE : TreeNode | None ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(SCREAMING_SNAKE_CASE : TreeNode | None ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(SCREAMING_SNAKE_CASE ) != count_coins(SCREAMING_SNAKE_CASE ): raise ValueError("The nodes number should be same as the number of coins" ) # Main calculation def get_distrib(SCREAMING_SNAKE_CASE : TreeNode | None ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) lowerCAmelCase , lowerCAmelCase : List[str] = get_distrib(node.left ) lowerCAmelCase , lowerCAmelCase : List[str] = get_distrib(node.right ) lowerCAmelCase : Union[str, Any] = 1 - left_distrib_excess lowerCAmelCase : List[Any] = 1 - right_distrib_excess lowerCAmelCase : int = ( left_distrib_moves + right_distrib_moves + abs(SCREAMING_SNAKE_CASE ) + abs(SCREAMING_SNAKE_CASE ) ) lowerCAmelCase : int = node.data - coins_to_left - coins_to_right return CoinsDistribResult(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) return get_distrib(SCREAMING_SNAKE_CASE )[0] if __name__ == "__main__": import doctest doctest.testmod()
108
0
import unittest import numpy as np from transformers.testing_utils import is_flaky, require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import DonutImageProcessor class _snake_case ( unittest.TestCase ): def __init__( self , _a , _a=7 , _a=3 , _a=18 , _a=30 , _a=400 , _a=True , _a=None , _a=True , _a=False , _a=True , _a=True , _a=[0.5, 0.5, 0.5] , _a=[0.5, 0.5, 0.5] , ): __magic_name__ : Optional[Any] = parent __magic_name__ : Optional[Any] = batch_size __magic_name__ : Any = num_channels __magic_name__ : List[str] = image_size __magic_name__ : List[str] = min_resolution __magic_name__ : Optional[Any] = max_resolution __magic_name__ : Optional[int] = do_resize __magic_name__ : Union[str, Any] = size if size is not None else {"height": 18, "width": 20} __magic_name__ : int = do_thumbnail __magic_name__ : Dict = do_align_axis __magic_name__ : Any = do_pad __magic_name__ : Any = do_normalize __magic_name__ : str = image_mean __magic_name__ : Union[str, Any] = image_std def SCREAMING_SNAKE_CASE ( self ): return { "do_resize": self.do_resize, "size": self.size, "do_thumbnail": self.do_thumbnail, "do_align_long_axis": self.do_align_axis, "do_pad": self.do_pad, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, } @require_torch @require_vision class _snake_case ( snake_case , unittest.TestCase ): UpperCamelCase__ = DonutImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[str] = DonutImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE ( self ): return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_a , "do_resize" ) ) self.assertTrue(hasattr(_a , "size" ) ) self.assertTrue(hasattr(_a , "do_thumbnail" ) ) self.assertTrue(hasattr(_a , "do_align_long_axis" ) ) self.assertTrue(hasattr(_a , "do_pad" ) ) self.assertTrue(hasattr(_a , "do_normalize" ) ) self.assertTrue(hasattr(_a , "image_mean" ) ) self.assertTrue(hasattr(_a , "image_std" ) ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : int = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"height": 18, "width": 20} ) __magic_name__ : Dict = self.image_processing_class.from_dict(self.image_processor_dict , size=42 ) self.assertEqual(image_processor.size , {"height": 42, "width": 42} ) # Previous config had dimensions in (width, height) order __magic_name__ : List[str] = self.image_processing_class.from_dict(self.image_processor_dict , size=(42, 84) ) self.assertEqual(image_processor.size , {"height": 84, "width": 42} ) def SCREAMING_SNAKE_CASE ( self ): pass @is_flaky() def SCREAMING_SNAKE_CASE ( self ): # Initialize image_processing __magic_name__ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images __magic_name__ : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a ) for image in image_inputs: self.assertIsInstance(_a , Image.Image ) # Test not batched input __magic_name__ : str = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched __magic_name__ : List[Any] = image_processing(_a , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) @is_flaky() def SCREAMING_SNAKE_CASE ( self ): # Initialize image_processing __magic_name__ : Dict = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors __magic_name__ : Tuple = prepare_image_inputs(self.image_processor_tester , equal_resolution=_a , numpify=_a ) for image in image_inputs: self.assertIsInstance(_a , np.ndarray ) # Test not batched input __magic_name__ : Dict = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched __magic_name__ : int = image_processing(_a , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) @is_flaky() def SCREAMING_SNAKE_CASE ( self ): # Initialize image_processing __magic_name__ : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors __magic_name__ : Optional[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 __magic_name__ : List[Any] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , ) # Test batched __magic_name__ : Dict = image_processing(_a , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.size["height"], self.image_processor_tester.size["width"], ) , )
41
import numpy class _snake_case : def __init__( self , _a , _a ): __magic_name__ : Optional[Any] = input_array # Random initial weights are assigned where first argument is the # number of nodes in previous layer and second argument is the # number of nodes in the next layer. # Random initial weights are assigned. # self.input_array.shape[1] is used to represent number of nodes in input layer. # First hidden layer consists of 4 nodes. __magic_name__ : Any = numpy.random.rand( self.input_array.shape[1] , 4 ) # Random initial values for the first hidden layer. # First hidden layer has 4 nodes. # Second hidden layer has 3 nodes. __magic_name__ : List[str] = numpy.random.rand( 4 , 3 ) # Random initial values for the second hidden layer. # Second hidden layer has 3 nodes. # Output layer has 1 node. __magic_name__ : Any = numpy.random.rand(3 , 1 ) # Real output values provided. __magic_name__ : Dict = output_array # Predicted output values by the neural network. # Predicted_output array initially consists of zeroes. __magic_name__ : Tuple = numpy.zeros(output_array.shape ) def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : List[str] = sigmoid( numpy.dot(self.input_array , self.input_layer_and_first_hidden_layer_weights ) ) # layer_between_first_hidden_layer_and_second_hidden_layer is the layer # connecting the first hidden set of nodes with the second hidden set of nodes. __magic_name__ : int = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) ) # layer_between_second_hidden_layer_and_output is the layer connecting # second hidden layer with the output node. __magic_name__ : Tuple = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) ) return self.layer_between_second_hidden_layer_and_output def SCREAMING_SNAKE_CASE ( self ): __magic_name__ : Optional[int] = numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer.T , 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , ) __magic_name__ : Optional[int] = numpy.dot( self.layer_between_input_and_first_hidden_layer.T , numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ) , ) __magic_name__ : int = numpy.dot( self.input_array.T , numpy.dot( numpy.dot( 2 * (self.output_array - self.predicted_output) * sigmoid_derivative(self.predicted_output ) , self.second_hidden_layer_and_output_layer_weights.T , ) * sigmoid_derivative( self.layer_between_first_hidden_layer_and_second_hidden_layer ) , self.first_hidden_layer_and_second_hidden_layer_weights.T , ) * sigmoid_derivative(self.layer_between_input_and_first_hidden_layer ) , ) self.input_layer_and_first_hidden_layer_weights += ( updated_input_layer_and_first_hidden_layer_weights ) self.first_hidden_layer_and_second_hidden_layer_weights += ( updated_first_hidden_layer_and_second_hidden_layer_weights ) self.second_hidden_layer_and_output_layer_weights += ( updated_second_hidden_layer_and_output_layer_weights ) def SCREAMING_SNAKE_CASE ( self , _a , _a , _a ): for iteration in range(1 , iterations + 1 ): __magic_name__ : Any = self.feedforward() self.back_propagation() if give_loss: __magic_name__ : int = numpy.mean(numpy.square(output - self.feedforward() ) ) print(f'''Iteration {iteration} Loss: {loss}''' ) def SCREAMING_SNAKE_CASE ( self , _a ): __magic_name__ : str = input_arr __magic_name__ : Optional[Any] = sigmoid( numpy.dot(self.array , self.input_layer_and_first_hidden_layer_weights ) ) __magic_name__ : Union[str, Any] = sigmoid( numpy.dot( self.layer_between_input_and_first_hidden_layer , self.first_hidden_layer_and_second_hidden_layer_weights , ) ) __magic_name__ : Optional[Any] = sigmoid( numpy.dot( self.layer_between_first_hidden_layer_and_second_hidden_layer , self.second_hidden_layer_and_output_layer_weights , ) ) return int(self.layer_between_second_hidden_layer_and_output > 0.6 ) def lowerCAmelCase_ ( _snake_case : numpy.ndarray ) -> numpy.ndarray: '''simple docstring''' return 1 / (1 + numpy.exp(-value )) def lowerCAmelCase_ ( _snake_case : numpy.ndarray ) -> numpy.ndarray: '''simple docstring''' return (value) * (1 - (value)) def lowerCAmelCase_ ( ) -> int: '''simple docstring''' __magic_name__ : Tuple = numpy.array( ( [0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1], ) , dtype=numpy.floataa , ) # True output values for the given input values. __magic_name__ : List[str] = numpy.array(([0], [1], [1], [0], [1], [0], [0], [1]) , dtype=numpy.floataa ) # Calling neural network class. __magic_name__ : List[Any] = TwoHiddenLayerNeuralNetwork( input_array=_snake_case , output_array=_snake_case ) # Calling training function. # Set give_loss to True if you want to see loss in every iteration. neural_network.train(output=_snake_case , iterations=10 , give_loss=_snake_case ) return neural_network.predict(numpy.array(([1, 1, 1]) , dtype=numpy.floataa ) ) if __name__ == "__main__": example()
41
1
def lowerCamelCase__ ( A__ : Any , A__ : Any ): '''simple docstring''' __lowerCamelCase = int(_lowerCAmelCase ) # Initialize Result __lowerCamelCase = [] # Traverse through all denomination for denomination in reversed(_lowerCAmelCase ): # Find denominations while int(_lowerCAmelCase ) >= int(_lowerCAmelCase ): total_value -= int(_lowerCAmelCase ) answer.append(_lowerCAmelCase ) # Append the "answers" array return answer # Driver Code if __name__ == "__main__": UpperCAmelCase_ = [] UpperCAmelCase_ = '0' if ( input('Do you want to enter your denominations ? (yY/n): ').strip().lower() == "y" ): UpperCAmelCase_ = int(input('Enter the number of denominations you want to add: ').strip()) for i in range(0, n): denominations.append(int(input(f"""Denomination {i}: """).strip())) UpperCAmelCase_ = input('Enter the change you want to make in Indian Currency: ').strip() else: # All denominations of Indian Currency if user does not enter UpperCAmelCase_ = [1, 2, 5, 10, 20, 50, 100, 500, 2_000] UpperCAmelCase_ = input('Enter the change you want to make: ').strip() if int(value) == 0 or int(value) < 0: print('The total value cannot be zero or negative.') else: print(f"""Following is minimal change for {value}: """) UpperCAmelCase_ = find_minimum_change(denominations, value) # Print result for i in range(len(answer)): print(answer[i], end=' ')
12
"""simple docstring""" import os from distutils.util import strtobool def lowercase (_lowerCAmelCase , _lowerCAmelCase ): for e in env_keys: __lowerCAmelCase = int(os.environ.get(_lowerCAmelCase , -1 ) ) if val >= 0: return val return default def lowercase (_lowerCAmelCase , _lowerCAmelCase=False ): __lowerCAmelCase = os.environ.get(_lowerCAmelCase , str(_lowerCAmelCase ) ) return strtobool(_lowerCAmelCase ) == 1 # As its name indicates `strtobool` actually returns an int... def lowercase (_lowerCAmelCase , _lowerCAmelCase="no" ): __lowerCAmelCase = os.environ.get(_lowerCAmelCase , str(_lowerCAmelCase ) ) return value
301
0
"""simple docstring""" from arguments import InitializationArguments from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, HfArgumentParser # Configuration UpperCAmelCase : Tuple = HfArgumentParser(InitializationArguments) UpperCAmelCase : str = parser.parse_args() # Load codeparrot tokenizer trained for Python code tokenization UpperCAmelCase : Optional[Any] = AutoTokenizer.from_pretrained(args.tokenizer_name) # Config: "scale_attn_by_layer_idx" and "reorder_and_upcast_attn" are Mistral stability tweaks UpperCAmelCase : int = { "vocab_size": len(tokenizer), "scale_attn_by_inverse_layer_idx": True, "reorder_and_upcast_attn": True, } # Load model config (GPT-2 large in this case) UpperCAmelCase : Tuple = AutoConfig.from_pretrained(args.config_name, **config_kwargs) # Initialize new model with config UpperCAmelCase : List[str] = AutoModelForCausalLM.from_config(config) # Save model to the hub model.save_pretrained(args.model_name, push_to_hub=args.push_to_hub)
365
"""simple docstring""" import argparse import json import os import numpy as np import PIL import requests import tensorflow.keras.applications.efficientnet as efficientnet import torch from huggingface_hub import hf_hub_download from PIL import Image from tensorflow.keras.preprocessing import image from transformers import ( EfficientNetConfig, EfficientNetForImageClassification, EfficientNetImageProcessor, ) from transformers.utils import logging logging.set_verbosity_info() UpperCAmelCase : List[str] = logging.get_logger(__name__) UpperCAmelCase : List[str] = { 'b0': efficientnet.EfficientNetBa, 'b1': efficientnet.EfficientNetBa, 'b2': efficientnet.EfficientNetBa, 'b3': efficientnet.EfficientNetBa, 'b4': efficientnet.EfficientNetBa, 'b5': efficientnet.EfficientNetBa, 'b6': efficientnet.EfficientNetBa, 'b7': efficientnet.EfficientNetBa, } UpperCAmelCase : List[str] = { 'b0': { 'hidden_dim': 1280, 'width_coef': 1.0, 'depth_coef': 1.0, 'image_size': 224, 'dropout_rate': 0.2, 'dw_padding': [], }, 'b1': { 'hidden_dim': 1280, 'width_coef': 1.0, 'depth_coef': 1.1, 'image_size': 240, 'dropout_rate': 0.2, 'dw_padding': [16], }, 'b2': { 'hidden_dim': 1408, 'width_coef': 1.1, 'depth_coef': 1.2, 'image_size': 260, 'dropout_rate': 0.3, 'dw_padding': [5, 8, 16], }, 'b3': { 'hidden_dim': 1536, 'width_coef': 1.2, 'depth_coef': 1.4, 'image_size': 300, 'dropout_rate': 0.3, 'dw_padding': [5, 18], }, 'b4': { 'hidden_dim': 1792, 'width_coef': 1.4, 'depth_coef': 1.8, 'image_size': 380, 'dropout_rate': 0.4, 'dw_padding': [6], }, 'b5': { 'hidden_dim': 2048, 'width_coef': 1.6, 'depth_coef': 2.2, 'image_size': 456, 'dropout_rate': 0.4, 'dw_padding': [13, 27], }, 'b6': { 'hidden_dim': 2304, 'width_coef': 1.8, 'depth_coef': 2.6, 'image_size': 528, 'dropout_rate': 0.5, 'dw_padding': [31], }, 'b7': { 'hidden_dim': 2560, 'width_coef': 2.0, 'depth_coef': 3.1, 'image_size': 600, 'dropout_rate': 0.5, 'dw_padding': [18], }, } def lowerCamelCase ( _UpperCamelCase : List[Any] ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : List[Any] = EfficientNetConfig() __UpperCAmelCase : Dict = CONFIG_MAP[model_name]["""hidden_dim"""] __UpperCAmelCase : Dict = CONFIG_MAP[model_name]["""width_coef"""] __UpperCAmelCase : str = CONFIG_MAP[model_name]["""depth_coef"""] __UpperCAmelCase : Dict = CONFIG_MAP[model_name]["""image_size"""] __UpperCAmelCase : Dict = CONFIG_MAP[model_name]["""dropout_rate"""] __UpperCAmelCase : Union[str, Any] = CONFIG_MAP[model_name]["""dw_padding"""] __UpperCAmelCase : int = """huggingface/label-files""" __UpperCAmelCase : Optional[int] = """imagenet-1k-id2label.json""" __UpperCAmelCase : str = 1_0_0_0 __UpperCAmelCase : Dict = json.load(open(hf_hub_download(_UpperCamelCase , _UpperCamelCase , repo_type="""dataset""" ) , """r""" ) ) __UpperCAmelCase : int = {int(_UpperCamelCase ): v for k, v in idalabel.items()} __UpperCAmelCase : Dict = idalabel __UpperCAmelCase : Tuple = {v: k for k, v in idalabel.items()} return config def lowerCamelCase ( ) -> Union[str, Any]: '''simple docstring''' __UpperCAmelCase : Dict = """http://images.cocodataset.org/val2017/000000039769.jpg""" __UpperCAmelCase : Optional[Any] = Image.open(requests.get(_UpperCamelCase , stream=_UpperCamelCase ).raw ) return im def lowerCamelCase ( _UpperCamelCase : Any ) -> str: '''simple docstring''' __UpperCAmelCase : Tuple = CONFIG_MAP[model_name]["""image_size"""] __UpperCAmelCase : List[str] = EfficientNetImageProcessor( size={"""height""": size, """width""": size} , image_mean=[0.485, 0.456, 0.406] , image_std=[0.47_853_944, 0.4_732_864, 0.47_434_163] , do_center_crop=_UpperCamelCase , ) return preprocessor def lowerCamelCase ( _UpperCamelCase : Dict ) -> Optional[int]: '''simple docstring''' __UpperCAmelCase : Union[str, Any] = [v.split("""_""" )[0].split("""block""" )[1] for v in original_param_names if v.startswith("""block""" )] __UpperCAmelCase : str = sorted(set(_UpperCamelCase ) ) __UpperCAmelCase : Optional[int] = len(_UpperCamelCase ) __UpperCAmelCase : Any = {b: str(_UpperCamelCase ) for b, i in zip(_UpperCamelCase , range(_UpperCamelCase ) )} __UpperCAmelCase : Any = [] rename_keys.append(("""stem_conv/kernel:0""", """embeddings.convolution.weight""") ) rename_keys.append(("""stem_bn/gamma:0""", """embeddings.batchnorm.weight""") ) rename_keys.append(("""stem_bn/beta:0""", """embeddings.batchnorm.bias""") ) rename_keys.append(("""stem_bn/moving_mean:0""", """embeddings.batchnorm.running_mean""") ) rename_keys.append(("""stem_bn/moving_variance:0""", """embeddings.batchnorm.running_var""") ) for b in block_names: __UpperCAmelCase : List[str] = block_name_mapping[b] rename_keys.append((f'''block{b}_expand_conv/kernel:0''', f'''encoder.blocks.{hf_b}.expansion.expand_conv.weight''') ) rename_keys.append((f'''block{b}_expand_bn/gamma:0''', f'''encoder.blocks.{hf_b}.expansion.expand_bn.weight''') ) rename_keys.append((f'''block{b}_expand_bn/beta:0''', f'''encoder.blocks.{hf_b}.expansion.expand_bn.bias''') ) rename_keys.append( (f'''block{b}_expand_bn/moving_mean:0''', f'''encoder.blocks.{hf_b}.expansion.expand_bn.running_mean''') ) rename_keys.append( (f'''block{b}_expand_bn/moving_variance:0''', f'''encoder.blocks.{hf_b}.expansion.expand_bn.running_var''') ) rename_keys.append( (f'''block{b}_dwconv/depthwise_kernel:0''', f'''encoder.blocks.{hf_b}.depthwise_conv.depthwise_conv.weight''') ) rename_keys.append((f'''block{b}_bn/gamma:0''', f'''encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.weight''') ) rename_keys.append((f'''block{b}_bn/beta:0''', f'''encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.bias''') ) rename_keys.append( (f'''block{b}_bn/moving_mean:0''', f'''encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_mean''') ) rename_keys.append( (f'''block{b}_bn/moving_variance:0''', f'''encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_var''') ) rename_keys.append((f'''block{b}_se_reduce/kernel:0''', f'''encoder.blocks.{hf_b}.squeeze_excite.reduce.weight''') ) rename_keys.append((f'''block{b}_se_reduce/bias:0''', f'''encoder.blocks.{hf_b}.squeeze_excite.reduce.bias''') ) rename_keys.append((f'''block{b}_se_expand/kernel:0''', f'''encoder.blocks.{hf_b}.squeeze_excite.expand.weight''') ) rename_keys.append((f'''block{b}_se_expand/bias:0''', f'''encoder.blocks.{hf_b}.squeeze_excite.expand.bias''') ) rename_keys.append( (f'''block{b}_project_conv/kernel:0''', f'''encoder.blocks.{hf_b}.projection.project_conv.weight''') ) rename_keys.append((f'''block{b}_project_bn/gamma:0''', f'''encoder.blocks.{hf_b}.projection.project_bn.weight''') ) rename_keys.append((f'''block{b}_project_bn/beta:0''', f'''encoder.blocks.{hf_b}.projection.project_bn.bias''') ) rename_keys.append( (f'''block{b}_project_bn/moving_mean:0''', f'''encoder.blocks.{hf_b}.projection.project_bn.running_mean''') ) rename_keys.append( (f'''block{b}_project_bn/moving_variance:0''', f'''encoder.blocks.{hf_b}.projection.project_bn.running_var''') ) rename_keys.append(("""top_conv/kernel:0""", """encoder.top_conv.weight""") ) rename_keys.append(("""top_bn/gamma:0""", """encoder.top_bn.weight""") ) rename_keys.append(("""top_bn/beta:0""", """encoder.top_bn.bias""") ) rename_keys.append(("""top_bn/moving_mean:0""", """encoder.top_bn.running_mean""") ) rename_keys.append(("""top_bn/moving_variance:0""", """encoder.top_bn.running_var""") ) __UpperCAmelCase : Optional[int] = {} for item in rename_keys: if item[0] in original_param_names: __UpperCAmelCase : Optional[Any] = """efficientnet.""" + item[1] __UpperCAmelCase : Tuple = """classifier.weight""" __UpperCAmelCase : Optional[int] = """classifier.bias""" return key_mapping def lowerCamelCase ( _UpperCamelCase : Any , _UpperCamelCase : Dict , _UpperCamelCase : int ) -> Tuple: '''simple docstring''' for key, value in tf_params.items(): if "normalization" in key: continue __UpperCAmelCase : List[Any] = key_mapping[key] if "_conv" in key and "kernel" in key: __UpperCAmelCase : int = torch.from_numpy(_UpperCamelCase ).permute(3 , 2 , 0 , 1 ) elif "depthwise_kernel" in key: __UpperCAmelCase : Optional[Any] = torch.from_numpy(_UpperCamelCase ).permute(2 , 3 , 0 , 1 ) elif "kernel" in key: __UpperCAmelCase : List[str] = torch.from_numpy(np.transpose(_UpperCamelCase ) ) else: __UpperCAmelCase : Tuple = torch.from_numpy(_UpperCamelCase ) # Replace HF parameters with original TF model parameters assert hf_params[hf_key].shape == new_hf_value.shape hf_params[hf_key].copy_(_UpperCamelCase ) @torch.no_grad() def lowerCamelCase ( _UpperCamelCase : Optional[int] , _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Union[str, Any] , _UpperCamelCase : List[str] ) -> Tuple: '''simple docstring''' __UpperCAmelCase : int = model_classes[model_name]( include_top=_UpperCamelCase , weights="""imagenet""" , input_tensor=_UpperCamelCase , input_shape=_UpperCamelCase , pooling=_UpperCamelCase , classes=1_0_0_0 , classifier_activation="""softmax""" , ) __UpperCAmelCase : List[str] = original_model.trainable_variables __UpperCAmelCase : List[Any] = original_model.non_trainable_variables __UpperCAmelCase : Union[str, Any] = {param.name: param.numpy() for param in tf_params} for param in tf_non_train_params: __UpperCAmelCase : int = param.numpy() __UpperCAmelCase : Dict = list(tf_params.keys() ) # Load HuggingFace model __UpperCAmelCase : Optional[Any] = get_efficientnet_config(_UpperCamelCase ) __UpperCAmelCase : Optional[Any] = EfficientNetForImageClassification(_UpperCamelCase ).eval() __UpperCAmelCase : Any = hf_model.state_dict() # Create src-to-dst parameter name mapping dictionary print("""Converting parameters...""" ) __UpperCAmelCase : Tuple = rename_keys(_UpperCamelCase ) replace_params(_UpperCamelCase , _UpperCamelCase , _UpperCamelCase ) # Initialize preprocessor and preprocess input image __UpperCAmelCase : List[Any] = convert_image_processor(_UpperCamelCase ) __UpperCAmelCase : Union[str, Any] = preprocessor(images=prepare_img() , return_tensors="""pt""" ) # HF model inference hf_model.eval() with torch.no_grad(): __UpperCAmelCase : Optional[int] = hf_model(**_UpperCamelCase ) __UpperCAmelCase : Any = outputs.logits.detach().numpy() # Original model inference __UpperCAmelCase : Union[str, Any] = False __UpperCAmelCase : Dict = CONFIG_MAP[model_name]["""image_size"""] __UpperCAmelCase : str = prepare_img().resize((image_size, image_size) , resample=PIL.Image.NEAREST ) __UpperCAmelCase : Optional[Any] = image.img_to_array(_UpperCamelCase ) __UpperCAmelCase : Tuple = np.expand_dims(_UpperCamelCase , axis=0 ) __UpperCAmelCase : str = original_model.predict(_UpperCamelCase ) # Check whether original and HF model outputs match -> np.allclose assert np.allclose(_UpperCamelCase , _UpperCamelCase , atol=1E-3 ), "The predicted logits are not the same." print("""Model outputs match!""" ) if save_model: # Create folder to save model if not os.path.isdir(_UpperCamelCase ): os.mkdir(_UpperCamelCase ) # Save converted model and image processor hf_model.save_pretrained(_UpperCamelCase ) preprocessor.save_pretrained(_UpperCamelCase ) if push_to_hub: # Push model and image processor to hub print(f'''Pushing converted {model_name} to the hub...''' ) __UpperCAmelCase : List[str] = f'''efficientnet-{model_name}''' preprocessor.push_to_hub(_UpperCamelCase ) hf_model.push_to_hub(_UpperCamelCase ) if __name__ == "__main__": UpperCAmelCase : Any = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='b0', type=str, help='Version name of the EfficientNet model you want to convert, select from [b0, b1, b2, b3, b4, b5, b6, b7].', ) parser.add_argument( '--pytorch_dump_folder_path', default='hf_model', type=str, help='Path to the output PyTorch model directory.', ) parser.add_argument('--save_model', action='store_true', help='Save model to local') parser.add_argument('--push_to_hub', action='store_true', help='Push model and image processor to the hub') UpperCAmelCase : Any = parser.parse_args() convert_efficientnet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.save_model, args.push_to_hub)
320
0
import unittest from parameterized import parameterized from transformers import OpenLlamaConfig, is_torch_available, set_seed from transformers.testing_utils import require_torch, 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 OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel class UpperCAmelCase__ : """simple docstring""" def __init__( self , A_ , A_=13 , A_=7 , A_=True , A_=True , A_=False , A_=True , A_=99 , A_=32 , A_=5 , A_=4 , A_=37 , A_="gelu" , A_=0.1 , A_=0.1 , A_=512 , A_=16 , A_=2 , A_=0.02 , A_=3 , A_=4 , A_=None , ) -> int: __UpperCamelCase =parent __UpperCamelCase =batch_size __UpperCamelCase =seq_length __UpperCamelCase =is_training __UpperCamelCase =use_input_mask __UpperCamelCase =use_token_type_ids __UpperCamelCase =use_labels __UpperCamelCase =vocab_size __UpperCamelCase =hidden_size __UpperCamelCase =num_hidden_layers __UpperCamelCase =num_attention_heads __UpperCamelCase =intermediate_size __UpperCamelCase =hidden_act __UpperCamelCase =hidden_dropout_prob __UpperCamelCase =attention_probs_dropout_prob __UpperCamelCase =max_position_embeddings __UpperCamelCase =type_vocab_size __UpperCamelCase =type_sequence_label_size __UpperCamelCase =initializer_range __UpperCamelCase =num_labels __UpperCamelCase =num_choices __UpperCamelCase =scope def _a ( self ) -> Dict: __UpperCamelCase =ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) __UpperCamelCase =None if self.use_input_mask: __UpperCamelCase =random_attention_mask([self.batch_size, self.seq_length] ) __UpperCamelCase =None if self.use_token_type_ids: __UpperCamelCase =ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) __UpperCamelCase =None __UpperCamelCase =None __UpperCamelCase =None if self.use_labels: __UpperCamelCase =ids_tensor([self.batch_size] , self.type_sequence_label_size ) __UpperCamelCase =ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) __UpperCamelCase =ids_tensor([self.batch_size] , self.num_choices ) __UpperCamelCase =self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _a ( self ) -> int: return OpenLlamaConfig( 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 , use_stable_embedding=A_ , ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ ) -> Dict: __UpperCamelCase =OpenLlamaModel(config=A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ , attention_mask=A_ ) __UpperCamelCase =model(A_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ) -> Optional[int]: __UpperCamelCase =True __UpperCamelCase =OpenLlamaModel(A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model( A_ , attention_mask=A_ , encoder_hidden_states=A_ , encoder_attention_mask=A_ , ) __UpperCamelCase =model( A_ , attention_mask=A_ , encoder_hidden_states=A_ , ) __UpperCamelCase =model(A_ , attention_mask=A_ ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ) -> Union[str, Any]: __UpperCamelCase =OpenLlamaForCausalLM(config=A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ , attention_mask=A_ , labels=A_ ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _a ( self , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , A_ , ) -> List[Any]: __UpperCamelCase =True __UpperCamelCase =True __UpperCamelCase =OpenLlamaForCausalLM(config=A_ ) model.to(A_ ) model.eval() # first forward pass __UpperCamelCase =model( A_ , attention_mask=A_ , encoder_hidden_states=A_ , encoder_attention_mask=A_ , use_cache=A_ , ) __UpperCamelCase =outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids __UpperCamelCase =ids_tensor((self.batch_size, 3) , config.vocab_size ) __UpperCamelCase =ids_tensor((self.batch_size, 3) , vocab_size=2 ) # append to next input_ids and __UpperCamelCase =torch.cat([input_ids, next_tokens] , dim=-1 ) __UpperCamelCase =torch.cat([input_mask, next_mask] , dim=-1 ) __UpperCamelCase =model( A_ , attention_mask=A_ , encoder_hidden_states=A_ , encoder_attention_mask=A_ , output_hidden_states=A_ , )['hidden_states'][0] __UpperCamelCase =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 __UpperCamelCase =ids_tensor((1,) , output_from_past.shape[-1] ).item() __UpperCamelCase =output_from_no_past[:, -3:, random_slice_idx].detach() __UpperCamelCase =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 _a ( self ) -> List[str]: __UpperCamelCase =self.prepare_config_and_inputs() ( ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ) =config_and_inputs __UpperCamelCase ={'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class UpperCAmelCase__ ( A_ , A_ , A_ , unittest.TestCase ): """simple docstring""" UpperCAmelCase__ : Optional[int] = ( (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else () ) UpperCAmelCase__ : List[Any] = (OpenLlamaForCausalLM,) if is_torch_available() else () UpperCAmelCase__ : str = ( { "feature-extraction": OpenLlamaModel, "text-classification": OpenLlamaForSequenceClassification, "text-generation": OpenLlamaForCausalLM, "zero-shot": OpenLlamaForSequenceClassification, } if is_torch_available() else {} ) UpperCAmelCase__ : Optional[Any] = False UpperCAmelCase__ : Optional[int] = False def _a ( self ) -> List[str]: __UpperCamelCase =OpenLlamaModelTester(self ) __UpperCamelCase =ConfigTester(self , config_class=A_ , hidden_size=37 ) def _a ( self ) -> Tuple: self.config_tester.run_common_tests() def _a ( self ) -> Any: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A_ ) def _a ( self ) -> str: __UpperCamelCase =self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: __UpperCamelCase =type self.model_tester.create_and_check_model(*A_ ) def _a ( self ) -> Dict: __UpperCamelCase , __UpperCamelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCamelCase =3 __UpperCamelCase =input_dict['input_ids'] __UpperCamelCase =input_ids.ne(1 ).to(A_ ) __UpperCamelCase =ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __UpperCamelCase =OpenLlamaForSequenceClassification(A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ , attention_mask=A_ , labels=A_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _a ( self ) -> Tuple: __UpperCamelCase , __UpperCamelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCamelCase =3 __UpperCamelCase ='single_label_classification' __UpperCamelCase =input_dict['input_ids'] __UpperCamelCase =input_ids.ne(1 ).to(A_ ) __UpperCamelCase =ids_tensor([self.model_tester.batch_size] , self.model_tester.type_sequence_label_size ) __UpperCamelCase =OpenLlamaForSequenceClassification(A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ , attention_mask=A_ , labels=A_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) def _a ( self ) -> Tuple: __UpperCamelCase , __UpperCamelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCamelCase =3 __UpperCamelCase ='multi_label_classification' __UpperCamelCase =input_dict['input_ids'] __UpperCamelCase =input_ids.ne(1 ).to(A_ ) __UpperCamelCase =ids_tensor( [self.model_tester.batch_size, config.num_labels] , self.model_tester.type_sequence_label_size ).to(torch.float ) __UpperCamelCase =OpenLlamaForSequenceClassification(A_ ) model.to(A_ ) model.eval() __UpperCamelCase =model(A_ , attention_mask=A_ , labels=A_ ) self.assertEqual(result.logits.shape , (self.model_tester.batch_size, self.model_tester.num_labels) ) @unittest.skip('Open-Llama buffers include complex numbers, which breaks this test' ) def _a ( self ) -> List[Any]: pass @parameterized.expand([('linear',), ('dynamic',)] ) def _a ( self , A_ ) -> Tuple: __UpperCamelCase , __UpperCamelCase =self.model_tester.prepare_config_and_inputs_for_common() __UpperCamelCase =ids_tensor([1, 10] , config.vocab_size ) __UpperCamelCase =ids_tensor([1, int(config.max_position_embeddings * 1.5 )] , config.vocab_size ) set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __UpperCamelCase =OpenLlamaModel(A_ ) original_model.to(A_ ) original_model.eval() __UpperCamelCase =original_model(A_ ).last_hidden_state __UpperCamelCase =original_model(A_ ).last_hidden_state set_seed(42 ) # Fixed seed at init time so the two models get the same random weights __UpperCamelCase ={'type': scaling_type, 'factor': 10.0} __UpperCamelCase =OpenLlamaModel(A_ ) scaled_model.to(A_ ) scaled_model.eval() __UpperCamelCase =scaled_model(A_ ).last_hidden_state __UpperCamelCase =scaled_model(A_ ).last_hidden_state # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original # maximum sequence length, so the outputs for the short input should match. if scaling_type == "dynamic": self.assertTrue(torch.allclose(A_ , A_ , atol=1E-5 ) ) else: self.assertFalse(torch.allclose(A_ , A_ , atol=1E-5 ) ) # The output should be different for long inputs self.assertFalse(torch.allclose(A_ , A_ , atol=1E-5 ) )
62
def UpperCAmelCase__ (UpperCamelCase_ = 4_00_00_00 ): """simple docstring""" snake_case = [0, 1] snake_case = 0 while fib[i] <= n: fib.append(fib[i] + fib[i + 1] ) if fib[i + 2] > n: break i += 1 snake_case = 0 for j in range(len(UpperCamelCase_ ) - 1 ): if fib[j] % 2 == 0: total += fib[j] return total if __name__ == "__main__": print(f'''{solution() = }''')
127
0
from typing import List import numpy as np def lowerCamelCase_ ( lowerCamelCase__ ): lowerCamelCase_ = {key: len(lowerCamelCase__ ) for key, value in gen_kwargs.items() if isinstance(lowerCamelCase__ , lowerCamelCase__ )} if len(set(lists_lengths.values() ) ) > 1: raise RuntimeError( ( "Sharding is ambiguous for this dataset: " + "we found several data sources lists of different lengths, and we don't know over which list we should parallelize:\n" + "\n".join(F'\t- key {key} has length {length}' for key, length in lists_lengths.items() ) + "\nTo fix this, check the 'gen_kwargs' and make sure to use lists only for data sources, " + "and use tuples otherwise. In the end there should only be one single list, or several lists with the same length." ) ) lowerCamelCase_ = max(lists_lengths.values() , default=0 ) return max(1 , lowerCamelCase__ ) def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ ): lowerCamelCase_ = [] for group_idx in range(lowerCamelCase__ ): lowerCamelCase_ = num_shards // max_num_jobs + (group_idx < (num_shards % max_num_jobs)) if num_shards_to_add == 0: break lowerCamelCase_ = shards_indices_per_group[-1].stop if shards_indices_per_group else 0 lowerCamelCase_ = range(lowerCamelCase__ , start + num_shards_to_add ) shards_indices_per_group.append(lowerCamelCase__ ) return shards_indices_per_group def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ ): lowerCamelCase_ = _number_of_shards_in_gen_kwargs(lowerCamelCase__ ) if num_shards == 1: return [dict(lowerCamelCase__ )] else: lowerCamelCase_ = _distribute_shards(num_shards=lowerCamelCase__ , max_num_jobs=lowerCamelCase__ ) return [ { key: [value[shard_idx] for shard_idx in shard_indices_per_group[group_idx]] if isinstance(lowerCamelCase__ , lowerCamelCase__ ) else value for key, value in gen_kwargs.items() } for group_idx in range(len(lowerCamelCase__ ) ) ] def lowerCamelCase_ ( lowerCamelCase__ ): return { key: [value for gen_kwargs in gen_kwargs_list for value in gen_kwargs[key]] if isinstance(gen_kwargs_list[0][key] , lowerCamelCase__ ) else gen_kwargs_list[0][key] for key in gen_kwargs_list[0] } def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ ): lowerCamelCase_ = {len(lowerCamelCase__ ) for value in gen_kwargs.values() if isinstance(lowerCamelCase__ , lowerCamelCase__ )} lowerCamelCase_ = {} for size in list_sizes: lowerCamelCase_ = list(range(lowerCamelCase__ ) ) rng.shuffle(indices_per_size[size] ) # Now let's copy the gen_kwargs and shuffle the lists based on their sizes lowerCamelCase_ = dict(lowerCamelCase__ ) for key, value in shuffled_kwargs.items(): if isinstance(lowerCamelCase__ , lowerCamelCase__ ): lowerCamelCase_ = [value[i] for i in indices_per_size[len(lowerCamelCase__ )]] return shuffled_kwargs
353
import numpy as np from cva import destroyAllWindows, imread, imshow, waitKey class _SCREAMING_SNAKE_CASE : def __init__( self , lowercase , lowercase , lowercase ) -> List[Any]: if dst_width < 0 or dst_height < 0: raise ValueError("Destination width/height should be > 0" ) lowerCamelCase_ = img lowerCamelCase_ = img.shape[1] lowerCamelCase_ = img.shape[0] lowerCamelCase_ = dst_width lowerCamelCase_ = dst_height lowerCamelCase_ = self.src_w / self.dst_w lowerCamelCase_ = self.src_h / self.dst_h lowerCamelCase_ = lowerCamelCase_ = ( np.ones((self.dst_h, self.dst_w, 3) , np.uinta ) * 255 ) def SCREAMING_SNAKE_CASE_( self ) -> Optional[int]: for i in range(self.dst_h ): for j in range(self.dst_w ): lowerCamelCase_ = self.img[self.get_y(lowercase )][self.get_x(lowercase )] def SCREAMING_SNAKE_CASE_( self , lowercase ) -> int: return int(self.ratio_x * x ) def SCREAMING_SNAKE_CASE_( self , lowercase ) -> int: return int(self.ratio_y * y ) if __name__ == "__main__": __A, __A =8_0_0, 6_0_0 __A =imread('''image_data/lena.jpg''', 1) __A =NearestNeighbour(im, dst_w, dst_h) n.process() imshow( F"""Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}""", n.output ) waitKey(0) destroyAllWindows()
47
0
"""simple docstring""" import math def _snake_case ( lowercase__ , lowercase__ ): _lowerCamelCase : List[Any] = len(lowercase__ ) _lowerCamelCase : Optional[Any] = int(math.floor(math.sqrt(lowercase__ ) ) ) _lowerCamelCase : Optional[int] = 0 while arr[min(lowercase__ , lowercase__ ) - 1] < x: _lowerCamelCase : Tuple = step step += int(math.floor(math.sqrt(lowercase__ ) ) ) if prev >= n: return -1 while arr[prev] < x: _lowerCamelCase : str = prev + 1 if prev == min(lowercase__ , lowercase__ ): return -1 if arr[prev] == x: return prev return -1 if __name__ == "__main__": lowercase__ = input("""Enter numbers separated by a comma:\n""").strip() lowercase__ = [int(item) for item in user_input.split(""",""")] lowercase__ = int(input("""Enter the number to be searched:\n""")) lowercase__ = jump_search(arr, x) if res == -1: print("""Number not found!""") else: print(F"Number {x} is at index {res}")
96
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__ : """simple docstring""" def __init__( self : Tuple, _snake_case : Any, _snake_case : int=1_3, _snake_case : Optional[int]=3_2, _snake_case : Tuple=2, _snake_case : Any=3, _snake_case : Tuple=1_6, _snake_case : Tuple=[1, 2, 1], _snake_case : Dict=[2, 2, 4], _snake_case : str=2, _snake_case : Union[str, Any]=2.0, _snake_case : Dict=True, _snake_case : Dict=0.0, _snake_case : str=0.0, _snake_case : str=0.1, _snake_case : List[str]="gelu", _snake_case : int=False, _snake_case : Optional[Any]=True, _snake_case : List[Any]=0.0_2, _snake_case : Union[str, Any]=1e-5, _snake_case : Union[str, Any]=True, _snake_case : List[Any]=None, _snake_case : Any=True, _snake_case : List[Any]=1_0, _snake_case : str=8, ) ->Union[str, Any]: snake_case__ : Any = parent snake_case__ : Tuple = batch_size snake_case__ : Tuple = image_size snake_case__ : Any = patch_size snake_case__ : Optional[int] = num_channels snake_case__ : Tuple = embed_dim snake_case__ : Any = depths snake_case__ : Any = num_heads snake_case__ : List[str] = window_size snake_case__ : Dict = mlp_ratio snake_case__ : Optional[int] = qkv_bias snake_case__ : Optional[Any] = hidden_dropout_prob snake_case__ : List[str] = attention_probs_dropout_prob snake_case__ : Union[str, Any] = drop_path_rate snake_case__ : str = hidden_act snake_case__ : Union[str, Any] = use_absolute_embeddings snake_case__ : Union[str, Any] = patch_norm snake_case__ : Any = layer_norm_eps snake_case__ : Tuple = initializer_range snake_case__ : Dict = is_training snake_case__ : Any = scope snake_case__ : Optional[Any] = use_labels snake_case__ : str = type_sequence_label_size snake_case__ : List[Any] = encoder_stride def lowercase_ ( self : Tuple ) ->str: snake_case__ : Tuple = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) snake_case__ : List[Any] = None if self.use_labels: snake_case__ : Optional[Any] = ids_tensor([self.batch_size], self.type_sequence_label_size ) snake_case__ : Any = self.get_config() return config, pixel_values, labels def lowercase_ ( self : Optional[int] ) ->Optional[int]: 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 : Optional[int], _snake_case : str, _snake_case : List[str], _snake_case : int ) ->Dict: snake_case__ : List[Any] = SwinvaModel(config=_snake_case ) model.to(_snake_case ) model.eval() snake_case__ : Optional[int] = model(_snake_case ) snake_case__ : List[Any] = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1)) snake_case__ : List[Any] = int(config.embed_dim * 2 ** (len(config.depths ) - 1) ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, expected_seq_len, expected_dim) ) def lowercase_ ( self : Optional[Any], _snake_case : Any, _snake_case : List[str], _snake_case : Dict ) ->List[Any]: snake_case__ : List[str] = SwinvaForMaskedImageModeling(config=_snake_case ) model.to(_snake_case ) model.eval() snake_case__ : Union[str, Any] = model(_snake_case ) self.parent.assertEqual( result.logits.shape, (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images snake_case__ : Optional[Any] = 1 snake_case__ : Optional[int] = SwinvaForMaskedImageModeling(_snake_case ) model.to(_snake_case ) model.eval() snake_case__ : Tuple = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) snake_case__ : Any = model(_snake_case ) self.parent.assertEqual(result.logits.shape, (self.batch_size, 1, self.image_size, self.image_size) ) def lowercase_ ( self : List[str], _snake_case : int, _snake_case : List[Any], _snake_case : Optional[int] ) ->Any: snake_case__ : Tuple = self.type_sequence_label_size snake_case__ : int = SwinvaForImageClassification(_snake_case ) model.to(_snake_case ) model.eval() snake_case__ : Tuple = model(_snake_case, labels=_snake_case ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size) ) def lowercase_ ( self : Any ) ->Dict: snake_case__ : str = self.prepare_config_and_inputs() snake_case__ , snake_case__ , snake_case__ : List[str] = config_and_inputs snake_case__ : Union[str, Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class snake_case__ ( lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase ): """simple docstring""" _SCREAMING_SNAKE_CASE = ( (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else () ) _SCREAMING_SNAKE_CASE = ( {"""feature-extraction""": SwinvaModel, """image-classification""": SwinvaForImageClassification} if is_torch_available() else {} ) _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False _SCREAMING_SNAKE_CASE = False def lowercase_ ( self : Union[str, Any] ) ->Dict: snake_case__ : Optional[int] = SwinvaModelTester(self ) snake_case__ : int = ConfigTester(self, config_class=_snake_case, embed_dim=3_7 ) def lowercase_ ( self : Tuple ) ->int: 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 : Any ) ->str: snake_case__ : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*_snake_case ) @unittest.skip(reason='Got `CUDA error: misaligned address` with PyTorch 2.0.0.' ) def lowercase_ ( self : Any ) ->Union[str, Any]: pass @unittest.skip(reason='Swinv2 does not use inputs_embeds' ) def lowercase_ ( self : str ) ->Union[str, Any]: pass def lowercase_ ( self : Optional[Any] ) ->Union[str, Any]: snake_case__ , snake_case__ : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : Union[str, Any] = model_class(_snake_case ) self.assertIsInstance(model.get_input_embeddings(), (nn.Module) ) snake_case__ : Union[str, Any] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(_snake_case, nn.Linear ) ) def lowercase_ ( self : List[str] ) ->Optional[int]: snake_case__ , snake_case__ : Any = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: snake_case__ : Any = model_class(_snake_case ) snake_case__ : Dict = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic snake_case__ : Optional[Any] = [*signature.parameters.keys()] snake_case__ : List[Any] = ['pixel_values'] self.assertListEqual(arg_names[:1], _snake_case ) def lowercase_ ( self : str ) ->Union[str, Any]: snake_case__ , snake_case__ : Any = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : int = True for model_class in self.all_model_classes: snake_case__ : str = True snake_case__ : Union[str, Any] = False snake_case__ : Tuple = True snake_case__ : int = model_class(_snake_case ) model.to(_snake_case ) model.eval() with torch.no_grad(): snake_case__ : Optional[int] = model(**self._prepare_for_class(_snake_case, _snake_case ) ) snake_case__ : List[str] = outputs.attentions snake_case__ : List[Any] = len(self.model_tester.depths ) self.assertEqual(len(_snake_case ), _snake_case ) # check that output_attentions also work using config del inputs_dict["output_attentions"] snake_case__ : str = True snake_case__ : Tuple = config.window_size**2 snake_case__ : Optional[int] = model_class(_snake_case ) model.to(_snake_case ) model.eval() with torch.no_grad(): snake_case__ : str = model(**self._prepare_for_class(_snake_case, _snake_case ) ) snake_case__ : Tuple = outputs.attentions self.assertEqual(len(_snake_case ), _snake_case ) self.assertListEqual( list(attentions[0].shape[-3:] ), [self.model_tester.num_heads[0], window_size_squared, window_size_squared], ) snake_case__ : Optional[Any] = len(_snake_case ) # Check attention is always last and order is fine snake_case__ : Optional[int] = True snake_case__ : Dict = True snake_case__ : List[Any] = model_class(_snake_case ) model.to(_snake_case ) model.eval() with torch.no_grad(): snake_case__ : Optional[int] = model(**self._prepare_for_class(_snake_case, _snake_case ) ) if hasattr(self.model_tester, 'num_hidden_states_types' ): snake_case__ : str = self.model_tester.num_hidden_states_types else: # also another +1 for reshaped_hidden_states snake_case__ : Dict = 2 self.assertEqual(out_len + added_hidden_states, len(_snake_case ) ) snake_case__ : Any = outputs.attentions self.assertEqual(len(_snake_case ), _snake_case ) self.assertListEqual( list(self_attentions[0].shape[-3:] ), [self.model_tester.num_heads[0], window_size_squared, window_size_squared], ) def lowercase_ ( self : Dict, _snake_case : Tuple, _snake_case : Any, _snake_case : int, _snake_case : Optional[int] ) ->str: snake_case__ : Dict = model_class(_snake_case ) model.to(_snake_case ) model.eval() with torch.no_grad(): snake_case__ : List[Any] = model(**self._prepare_for_class(_snake_case, _snake_case ) ) snake_case__ : Dict = outputs.hidden_states snake_case__ : int = getattr( self.model_tester, 'expected_num_hidden_layers', len(self.model_tester.depths ) + 1 ) self.assertEqual(len(_snake_case ), _snake_case ) # Swinv2 has a different seq_length snake_case__ : int = ( config.patch_size if isinstance(config.patch_size, collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) snake_case__ : Optional[Any] = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.assertListEqual( list(hidden_states[0].shape[-2:] ), [num_patches, self.model_tester.embed_dim], ) snake_case__ : Union[str, Any] = outputs.reshaped_hidden_states self.assertEqual(len(_snake_case ), _snake_case ) snake_case__ , snake_case__ , snake_case__ , snake_case__ : str = reshaped_hidden_states[0].shape snake_case__ : Any = ( reshaped_hidden_states[0].view(_snake_case, _snake_case, height * width ).permute(0, 2, 1 ) ) self.assertListEqual( list(reshaped_hidden_states.shape[-2:] ), [num_patches, self.model_tester.embed_dim], ) def lowercase_ ( self : str ) ->List[Any]: snake_case__ , snake_case__ : Any = self.model_tester.prepare_config_and_inputs_for_common() 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: snake_case__ : Optional[int] = True self.check_hidden_states_output(_snake_case, _snake_case, _snake_case, _snake_case ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case__ : Dict = True self.check_hidden_states_output(_snake_case, _snake_case, _snake_case, _snake_case ) def lowercase_ ( self : List[str] ) ->str: snake_case__ , snake_case__ : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : List[str] = 3 snake_case__ : Union[str, 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) ) snake_case__ : str = ( config.patch_size if isinstance(config.patch_size, collections.abc.Iterable ) else (config.patch_size, config.patch_size) ) snake_case__ : Tuple = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) snake_case__ : Optional[Any] = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) for model_class in self.all_model_classes: snake_case__ : int = True self.check_hidden_states_output(_snake_case, _snake_case, _snake_case, (padded_height, padded_width) ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] snake_case__ : List[str] = True self.check_hidden_states_output(_snake_case, _snake_case, _snake_case, (padded_height, padded_width) ) def lowercase_ ( self : List[str] ) ->Optional[int]: snake_case__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*_snake_case ) def lowercase_ ( self : List[Any] ) ->str: snake_case__ : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*_snake_case ) @slow def lowercase_ ( self : str ) ->Union[str, Any]: for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: snake_case__ : Dict = SwinvaModel.from_pretrained(_snake_case ) self.assertIsNotNone(_snake_case ) def lowercase_ ( self : Optional[int] ) ->List[str]: snake_case__ , snake_case__ : Any = self.model_tester.prepare_config_and_inputs_for_common() snake_case__ : List[Any] = _config_zero_init(_snake_case ) for model_class in self.all_model_classes: snake_case__ : List[str] = model_class(config=_snake_case ) 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 ): """simple docstring""" @cached_property def lowercase_ ( self : Union[str, Any] ) ->List[str]: return ( AutoImageProcessor.from_pretrained('microsoft/swinv2-tiny-patch4-window8-256' ) if is_vision_available() else None ) @slow def lowercase_ ( self : int ) ->List[Any]: snake_case__ : Any = SwinvaForImageClassification.from_pretrained('microsoft/swinv2-tiny-patch4-window8-256' ).to( _snake_case ) snake_case__ : int = self.default_image_processor snake_case__ : Union[str, Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) snake_case__ : Optional[Any] = image_processor(images=_snake_case, return_tensors='pt' ).to(_snake_case ) # forward pass with torch.no_grad(): snake_case__ : List[str] = model(**_snake_case ) # verify the logits snake_case__ : int = torch.Size((1, 1_0_0_0) ) self.assertEqual(outputs.logits.shape, _snake_case ) snake_case__ : Optional[int] = torch.tensor([-0.3_9_4_7, -0.4_3_0_6, 0.0_0_2_6] ).to(_snake_case ) self.assertTrue(torch.allclose(outputs.logits[0, :3], _snake_case, atol=1e-4 ) )
277
0
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging lowerCAmelCase :Tuple = logging.get_logger(__name__) class _lowerCamelCase ( lowercase__ ): '''simple docstring''' A_ : int = ["""pixel_values"""] def __init__( self : Any , _A : bool = True , _A : Optional[Dict[str, int]] = None , _A : PILImageResampling = PILImageResampling.BILINEAR , _A : bool = True , _A : Dict[str, int] = None , _A : bool = True , _A : Union[int, float] = 1 / 255 , _A : bool = True , _A : Optional[Union[float, List[float]]] = None , _A : Optional[Union[float, List[float]]] = None , **_A : Optional[Any] , ) -> None: super().__init__(**_A ) __magic_name__ : List[str] = size if size is not None else {'shortest_edge': 256} __magic_name__ : str = get_size_dict(_A , default_to_square=_A ) __magic_name__ : List[str] = crop_size if crop_size is not None else {'height': 224, 'width': 224} __magic_name__ : Optional[int] = get_size_dict(_A ) __magic_name__ : Union[str, Any] = do_resize __magic_name__ : List[Any] = size __magic_name__ : List[str] = resample __magic_name__ : Dict = do_center_crop __magic_name__ : List[str] = crop_size __magic_name__ : int = do_rescale __magic_name__ : Tuple = rescale_factor __magic_name__ : List[str] = do_normalize __magic_name__ : Union[str, Any] = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN __magic_name__ : Dict = image_std if image_std is not None else IMAGENET_STANDARD_STD def __lowerCAmelCase ( self : Optional[Any] , _A : np.ndarray , _A : Dict[str, int] , _A : PILImageResampling = PILImageResampling.BICUBIC , _A : Optional[Union[str, ChannelDimension]] = None , **_A : List[str] , ) -> np.ndarray: __magic_name__ : Optional[Any] = get_size_dict(_A , default_to_square=_A ) if "shortest_edge" not in size: raise ValueError(F'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}' ) __magic_name__ : Dict = 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 __lowerCAmelCase ( self : Dict , _A : np.ndarray , _A : Dict[str, int] , _A : Optional[Union[str, ChannelDimension]] = None , **_A : Optional[int] , ) -> np.ndarray: __magic_name__ : int = get_size_dict(_A ) return center_crop(_A , size=(size['height'], size['width']) , data_format=_A , **_A ) def __lowerCAmelCase ( self : List[str] , _A : np.ndarray , _A : float , _A : Optional[Union[str, ChannelDimension]] = None , **_A : Tuple ) -> np.ndarray: return rescale(_A , scale=_A , data_format=_A , **_A ) def __lowerCAmelCase ( self : str , _A : np.ndarray , _A : Union[float, List[float]] , _A : Union[float, List[float]] , _A : Optional[Union[str, ChannelDimension]] = None , **_A : int , ) -> np.ndarray: return normalize(_A , mean=_A , std=_A , data_format=_A , **_A ) def __lowerCAmelCase ( self : List[str] , _A : ImageInput , _A : Optional[bool] = None , _A : Dict[str, int] = None , _A : PILImageResampling = None , _A : bool = None , _A : Dict[str, int] = None , _A : Optional[bool] = None , _A : Optional[float] = None , _A : Optional[bool] = None , _A : Optional[Union[float, List[float]]] = None , _A : Optional[Union[float, List[float]]] = None , _A : Optional[Union[str, TensorType]] = None , _A : Union[str, ChannelDimension] = ChannelDimension.FIRST , **_A : List[Any] , ) -> List[str]: __magic_name__ : int = do_resize if do_resize is not None else self.do_resize __magic_name__ : Tuple = size if size is not None else self.size __magic_name__ : Optional[Any] = get_size_dict(_A , default_to_square=_A ) __magic_name__ : Dict = resample if resample is not None else self.resample __magic_name__ : Optional[Any] = do_center_crop if do_center_crop is not None else self.do_center_crop __magic_name__ : Dict = crop_size if crop_size is not None else self.crop_size __magic_name__ : List[str] = get_size_dict(_A ) __magic_name__ : Union[str, Any] = do_rescale if do_rescale is not None else self.do_rescale __magic_name__ : str = rescale_factor if rescale_factor is not None else self.rescale_factor __magic_name__ : Any = do_normalize if do_normalize is not None else self.do_normalize __magic_name__ : Tuple = image_mean if image_mean is not None else self.image_mean __magic_name__ : Union[str, Any] = image_std if image_std is not None else self.image_std __magic_name__ : int = 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_center_crop and crop_size is None: raise ValueError('Crop size must be specified if do_center_crop is True.' ) if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.' ) if do_normalize and (image_mean is None or image_std is None): raise ValueError('Image mean and std must be specified if do_normalize is True.' ) # All transformations expect numpy arrays. __magic_name__ : List[Any] = [to_numpy_array(_A ) for image in images] if do_resize: __magic_name__ : Union[str, Any] = [self.resize(image=_A , size=_A , resample=_A ) for image in images] if do_center_crop: __magic_name__ : Union[str, Any] = [self.center_crop(image=_A , size=_A ) for image in images] if do_rescale: __magic_name__ : List[Any] = [self.rescale(image=_A , scale=_A ) for image in images] if do_normalize: __magic_name__ : Optional[Any] = [self.normalize(image=_A , mean=_A , std=_A ) for image in images] __magic_name__ : Union[str, Any] = [to_channel_dimension_format(_A , _A ) for image in images] __magic_name__ : List[str] = {'pixel_values': images} return BatchFeature(data=_A , tensor_type=_A )
275
'''simple docstring''' from __future__ import annotations from sys import maxsize from typing import Generic, TypeVar lowerCAmelCase :Any = TypeVar('''T''') def lowerCamelCase ( lowerCAmelCase : int ): """simple docstring""" return (position - 1) // 2 def lowerCamelCase ( lowerCAmelCase : int ): """simple docstring""" return (2 * position) + 1 def lowerCamelCase ( lowerCAmelCase : int ): """simple docstring""" return (2 * position) + 2 class _lowerCamelCase ( Generic[T] ): '''simple docstring''' def __init__( self : Union[str, Any] ) -> None: __magic_name__ : list[tuple[T, int]] = [] __magic_name__ : dict[T, int] = {} __magic_name__ : int = 0 def __len__( self : Optional[int] ) -> int: return self.elements def __repr__( self : Optional[Any] ) -> str: return str(self.heap ) def __lowerCAmelCase ( self : List[Any] ) -> bool: # Check if the priority queue is empty return self.elements == 0 def __lowerCAmelCase ( self : Dict , _A : T , _A : int ) -> None: # Add an element with given priority to the queue self.heap.append((elem, weight) ) __magic_name__ : List[str] = self.elements self.elements += 1 self._bubble_up(_A ) def __lowerCAmelCase ( self : List[Any] ) -> T: # Remove and return the element with lowest weight (highest priority) if self.elements > 1: self._swap_nodes(0 , self.elements - 1 ) __magic_name__ , __magic_name__ : Optional[Any] = self.heap.pop() del self.position_map[elem] self.elements -= 1 if self.elements > 0: __magic_name__ , __magic_name__ : Tuple = self.heap[0] self._bubble_down(_A ) return elem def __lowerCAmelCase ( self : Dict , _A : T , _A : int ) -> None: # Update the weight of the given key __magic_name__ : Optional[Any] = self.position_map[elem] __magic_name__ : Any = (elem, weight) if position > 0: __magic_name__ : Optional[int] = get_parent_position(_A ) __magic_name__ , __magic_name__ : Any = self.heap[parent_position] if parent_weight > weight: self._bubble_up(_A ) else: self._bubble_down(_A ) else: self._bubble_down(_A ) def __lowerCAmelCase ( self : Optional[int] , _A : T ) -> None: # Place a node at the proper position (upward movement) [to be used internally # only] __magic_name__ : Union[str, Any] = self.position_map[elem] if curr_pos == 0: return None __magic_name__ : Optional[Any] = get_parent_position(_A ) __magic_name__ , __magic_name__ : Any = self.heap[curr_pos] __magic_name__ , __magic_name__ : int = self.heap[parent_position] if parent_weight > weight: self._swap_nodes(_A , _A ) return self._bubble_up(_A ) return None def __lowerCAmelCase ( self : int , _A : T ) -> None: # Place a node at the proper position (downward movement) [to be used # internally only] __magic_name__ : Dict = self.position_map[elem] __magic_name__ , __magic_name__ : List[str] = self.heap[curr_pos] __magic_name__ : str = get_child_left_position(_A ) __magic_name__ : List[str] = get_child_right_position(_A ) if child_left_position < self.elements and child_right_position < self.elements: __magic_name__ , __magic_name__ : int = self.heap[child_left_position] __magic_name__ , __magic_name__ : int = self.heap[child_right_position] if child_right_weight < child_left_weight and child_right_weight < weight: self._swap_nodes(_A , _A ) return self._bubble_down(_A ) if child_left_position < self.elements: __magic_name__ , __magic_name__ : Any = self.heap[child_left_position] if child_left_weight < weight: self._swap_nodes(_A , _A ) return self._bubble_down(_A ) else: return None if child_right_position < self.elements: __magic_name__ , __magic_name__ : str = self.heap[child_right_position] if child_right_weight < weight: self._swap_nodes(_A , _A ) return self._bubble_down(_A ) return None def __lowerCAmelCase ( self : int , _A : int , _A : int ) -> None: # Swap the nodes at the given positions __magic_name__ : List[Any] = self.heap[nodea_pos][0] __magic_name__ : Union[str, Any] = self.heap[nodea_pos][0] __magic_name__ , __magic_name__ : Optional[Any] = ( self.heap[nodea_pos], self.heap[nodea_pos], ) __magic_name__ : Optional[Any] = nodea_pos __magic_name__ : Optional[Any] = nodea_pos class _lowerCamelCase ( Generic[T] ): '''simple docstring''' def __init__( self : Union[str, Any] ) -> None: __magic_name__ : dict[T, dict[T, int]] = {} __magic_name__ : int = 0 def __repr__( self : str ) -> str: return str(self.connections ) def __len__( self : Union[str, Any] ) -> int: return self.nodes def __lowerCAmelCase ( self : Dict , _A : T ) -> None: # Add a node in the graph if it is not in the graph if node not in self.connections: __magic_name__ : str = {} self.nodes += 1 def __lowerCAmelCase ( self : List[str] , _A : T , _A : T , _A : int ) -> None: # Add an edge between 2 nodes in the graph self.add_node(_A ) self.add_node(_A ) __magic_name__ : Any = weight __magic_name__ : Dict = weight def lowerCamelCase ( lowerCAmelCase : GraphUndirectedWeighted[T] , ): """simple docstring""" __magic_name__ : dict[T, int] = {node: maxsize for node in graph.connections} __magic_name__ : dict[T, T | None] = {node: None for node in graph.connections} __magic_name__ : MinPriorityQueue[T] = MinPriorityQueue() for node, weight in dist.items(): priority_queue.push(lowerCAmelCase , lowerCAmelCase ) if priority_queue.is_empty(): return dist, parent # initialization __magic_name__ : Any = priority_queue.extract_min() __magic_name__ : List[str] = 0 for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __magic_name__ : Any = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(lowerCAmelCase , dist[neighbour] ) __magic_name__ : Tuple = node # running prim's algorithm while not priority_queue.is_empty(): __magic_name__ : Tuple = priority_queue.extract_min() for neighbour in graph.connections[node]: if dist[neighbour] > dist[node] + graph.connections[node][neighbour]: __magic_name__ : int = dist[node] + graph.connections[node][neighbour] priority_queue.update_key(lowerCAmelCase , dist[neighbour] ) __magic_name__ : Union[str, Any] = node return dist, parent
275
1
'''simple docstring''' from itertools import product from cva import COLOR_BGR2GRAY, cvtColor, imread, imshow, waitKey from numpy import dot, exp, mgrid, pi, ravel, square, uinta, zeros def lowercase ( __magic_name__ , __magic_name__ ): '''simple docstring''' UpperCAmelCase : Any = k_size // 2 UpperCAmelCase , UpperCAmelCase : List[str] = mgrid[0 - center : k_size - center, 0 - center : k_size - center] UpperCAmelCase : List[str] = 1 / (2 * pi * sigma) * exp(-(square(__magic_name__ ) + square(__magic_name__ )) / (2 * square(__magic_name__ )) ) return g def lowercase ( __magic_name__ , __magic_name__ , __magic_name__ ): '''simple docstring''' UpperCAmelCase , UpperCAmelCase : Union[str, Any] = image.shape[0], image.shape[1] # dst image height and width UpperCAmelCase : Any = height - k_size + 1 UpperCAmelCase : str = width - k_size + 1 # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows UpperCAmelCase : Tuple = zeros((dst_height * dst_width, k_size * k_size) ) UpperCAmelCase : str = 0 for i, j in product(range(__magic_name__ ) , range(__magic_name__ ) ): UpperCAmelCase : List[Any] = ravel(image[i : i + k_size, j : j + k_size] ) UpperCAmelCase : List[str] = window row += 1 # turn the kernel into shape(k*k, 1) UpperCAmelCase : Dict = gen_gaussian_kernel(__magic_name__ , __magic_name__ ) UpperCAmelCase : str = ravel(__magic_name__ ) # reshape and get the dst image UpperCAmelCase : Any = dot(__magic_name__ , __magic_name__ ).reshape(__magic_name__ , __magic_name__ ).astype(__magic_name__ ) return dst if __name__ == "__main__": # read original image a : Any = imread(R"../image_data/lena.jpg") # turn image in gray scale value a : Dict = cvtColor(img, COLOR_BGR2GRAY) # get values with two different mask size a : Dict = gaussian_filter(gray, 3, sigma=1) a : Optional[Any] = gaussian_filter(gray, 5, sigma=0.8) # show result images imshow("gaussian filter with 3x3 mask", gaussianaxa) imshow("gaussian filter with 5x5 mask", gaussianaxa) waitKey()
311
'''simple docstring''' import argparse from pathlib import Path from typing import Dict, OrderedDict, Tuple import torch from audiocraft.models import MusicGen from transformers import ( AutoFeatureExtractor, AutoTokenizer, EncodecModel, MusicgenDecoderConfig, MusicgenForConditionalGeneration, MusicgenProcessor, TaEncoderModel, ) from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM from transformers.utils import logging logging.set_verbosity_info() a : List[str] = logging.get_logger(__name__) a : Optional[Any] = ["model.decoder.embed_positions.weights"] def lowercase ( __magic_name__ ): '''simple docstring''' if "emb" in name: UpperCAmelCase : str = name.replace("emb" , "model.decoder.embed_tokens" ) if "transformer" in name: UpperCAmelCase : List[str] = name.replace("transformer" , "model.decoder" ) if "cross_attention" in name: UpperCAmelCase : int = name.replace("cross_attention" , "encoder_attn" ) if "linear1" in name: UpperCAmelCase : List[Any] = name.replace("linear1" , "fc1" ) if "linear2" in name: UpperCAmelCase : int = name.replace("linear2" , "fc2" ) if "norm1" in name: UpperCAmelCase : Dict = name.replace("norm1" , "self_attn_layer_norm" ) if "norm_cross" in name: UpperCAmelCase : Any = name.replace("norm_cross" , "encoder_attn_layer_norm" ) if "norm2" in name: UpperCAmelCase : Union[str, Any] = name.replace("norm2" , "final_layer_norm" ) if "out_norm" in name: UpperCAmelCase : Dict = name.replace("out_norm" , "model.decoder.layer_norm" ) if "linears" in name: UpperCAmelCase : List[Any] = name.replace("linears" , "lm_heads" ) if "condition_provider.conditioners.description.output_proj" in name: UpperCAmelCase : Any = name.replace("condition_provider.conditioners.description.output_proj" , "enc_to_dec_proj" ) return name def lowercase ( __magic_name__ , __magic_name__ ): '''simple docstring''' UpperCAmelCase : Any = list(state_dict.keys() ) UpperCAmelCase : List[Any] = {} for key in keys: UpperCAmelCase : Any = state_dict.pop(__magic_name__ ) UpperCAmelCase : str = rename_keys(__magic_name__ ) if "in_proj_weight" in key: # split fused qkv proj UpperCAmelCase : Optional[int] = val[:hidden_size, :] UpperCAmelCase : Optional[Any] = val[hidden_size : 2 * hidden_size, :] UpperCAmelCase : Optional[Any] = val[-hidden_size:, :] elif "enc_to_dec_proj" in key: UpperCAmelCase : str = val else: UpperCAmelCase : int = val return state_dict, enc_dec_proj_state_dict def lowercase ( __magic_name__ ): '''simple docstring''' if checkpoint == "small": # default config values UpperCAmelCase : List[Any] = 1024 UpperCAmelCase : Tuple = 24 UpperCAmelCase : Union[str, Any] = 16 elif checkpoint == "medium": UpperCAmelCase : List[Any] = 1536 UpperCAmelCase : Optional[Any] = 48 UpperCAmelCase : List[str] = 24 elif checkpoint == "large": UpperCAmelCase : List[Any] = 2048 UpperCAmelCase : str = 48 UpperCAmelCase : Optional[Any] = 32 else: raise ValueError(F"Checkpoint should be one of `['small', 'medium', 'large']`, got {checkpoint}." ) UpperCAmelCase : Tuple = MusicgenDecoderConfig( hidden_size=__magic_name__ , ffn_dim=hidden_size * 4 , num_hidden_layers=__magic_name__ , num_attention_heads=__magic_name__ , ) return config @torch.no_grad() def lowercase ( __magic_name__ , __magic_name__=None , __magic_name__=None , __magic_name__="cpu" ): '''simple docstring''' UpperCAmelCase : Union[str, Any] = MusicGen.get_pretrained(__magic_name__ , device=__magic_name__ ) UpperCAmelCase : List[str] = decoder_config_from_checkpoint(__magic_name__ ) UpperCAmelCase : Dict = fairseq_model.lm.state_dict() UpperCAmelCase , UpperCAmelCase : List[str] = rename_state_dict( __magic_name__ , hidden_size=decoder_config.hidden_size ) UpperCAmelCase : Any = TaEncoderModel.from_pretrained("t5-base" ) UpperCAmelCase : Any = EncodecModel.from_pretrained("facebook/encodec_32khz" ) UpperCAmelCase : int = MusicgenForCausalLM(__magic_name__ ).eval() # load all decoder weights - expect that we'll be missing embeddings and enc-dec projection UpperCAmelCase , UpperCAmelCase : Optional[int] = decoder.load_state_dict(__magic_name__ , strict=__magic_name__ ) for key in missing_keys.copy(): if key.startswith(("text_encoder", "audio_encoder") ) or key in EXPECTED_MISSING_KEYS: missing_keys.remove(__magic_name__ ) if len(__magic_name__ ) > 0: raise ValueError(F"Missing key(s) in state_dict: {missing_keys}" ) if len(__magic_name__ ) > 0: raise ValueError(F"Unexpected key(s) in state_dict: {unexpected_keys}" ) # init the composite model UpperCAmelCase : List[Any] = MusicgenForConditionalGeneration(text_encoder=__magic_name__ , audio_encoder=__magic_name__ , decoder=__magic_name__ ) # load the pre-trained enc-dec projection (from the decoder state dict) model.enc_to_dec_proj.load_state_dict(__magic_name__ ) # check we can do a forward pass UpperCAmelCase : Union[str, Any] = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 ) UpperCAmelCase : Optional[Any] = input_ids.reshape(2 * 4 , -1 ) with torch.no_grad(): UpperCAmelCase : str = model(input_ids=__magic_name__ , decoder_input_ids=__magic_name__ ).logits if logits.shape != (8, 1, 2048): raise ValueError("Incorrect shape for logits" ) # now construct the processor UpperCAmelCase : Dict = AutoTokenizer.from_pretrained("t5-base" ) UpperCAmelCase : List[str] = AutoFeatureExtractor.from_pretrained("facebook/encodec_32khz" , padding_side="left" ) UpperCAmelCase : Dict = MusicgenProcessor(feature_extractor=__magic_name__ , tokenizer=__magic_name__ ) # set the appropriate bos/pad token ids UpperCAmelCase : List[Any] = 2048 UpperCAmelCase : Tuple = 2048 # set other default generation config params UpperCAmelCase : Tuple = int(30 * audio_encoder.config.frame_rate ) UpperCAmelCase : str = True UpperCAmelCase : Tuple = 3.0 if pytorch_dump_folder is not None: Path(__magic_name__ ).mkdir(exist_ok=__magic_name__ ) logger.info(F"Saving model {checkpoint} to {pytorch_dump_folder}" ) model.save_pretrained(__magic_name__ ) processor.save_pretrained(__magic_name__ ) if repo_id: logger.info(F"Pushing model {checkpoint} to {repo_id}" ) model.push_to_hub(__magic_name__ ) processor.push_to_hub(__magic_name__ ) if __name__ == "__main__": a : Tuple = argparse.ArgumentParser() # Required parameters parser.add_argument( "--checkpoint", default="small", type=str, help="Checkpoint size of the MusicGen model you'd like to convert. Can be one of: `['small', 'medium', 'large']`.", ) parser.add_argument( "--pytorch_dump_folder", required=True, default=None, type=str, help="Path to the output PyTorch model directory.", ) parser.add_argument( "--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub." ) parser.add_argument( "--device", default="cpu", type=str, help="Torch device to run the conversion, either cpu or cuda." ) a : int = parser.parse_args() convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
311
1
'''simple docstring''' from __future__ import annotations import unittest from transformers import DebertaVaConfig, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import ( TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, TFDebertaVaModel, ) class _a : '''simple docstring''' def __init__( self, A, A=13, A=7, A=True, A=True, A=True, A=True, A=99, A=32, A=2, A=4, A=37, A="gelu", A=0.1, A=0.1, A=512, A=16, A=2, A=0.02, A=False, A=True, A="None", A=3, A=4, A=None, ): '''simple docstring''' SCREAMING_SNAKE_CASE : Tuple = parent SCREAMING_SNAKE_CASE : Any = batch_size SCREAMING_SNAKE_CASE : int = seq_length SCREAMING_SNAKE_CASE : Dict = is_training SCREAMING_SNAKE_CASE : Union[str, Any] = use_input_mask SCREAMING_SNAKE_CASE : List[Any] = use_token_type_ids SCREAMING_SNAKE_CASE : Optional[Any] = use_labels SCREAMING_SNAKE_CASE : List[str] = vocab_size SCREAMING_SNAKE_CASE : List[str] = hidden_size SCREAMING_SNAKE_CASE : Tuple = num_hidden_layers SCREAMING_SNAKE_CASE : Tuple = num_attention_heads SCREAMING_SNAKE_CASE : Optional[Any] = intermediate_size SCREAMING_SNAKE_CASE : str = hidden_act SCREAMING_SNAKE_CASE : Optional[int] = hidden_dropout_prob SCREAMING_SNAKE_CASE : Dict = attention_probs_dropout_prob SCREAMING_SNAKE_CASE : Union[str, Any] = max_position_embeddings SCREAMING_SNAKE_CASE : List[str] = type_vocab_size SCREAMING_SNAKE_CASE : Optional[int] = type_sequence_label_size SCREAMING_SNAKE_CASE : Dict = initializer_range SCREAMING_SNAKE_CASE : Tuple = num_labels SCREAMING_SNAKE_CASE : Dict = num_choices SCREAMING_SNAKE_CASE : str = relative_attention SCREAMING_SNAKE_CASE : List[str] = position_biased_input SCREAMING_SNAKE_CASE : Optional[Any] = pos_att_type SCREAMING_SNAKE_CASE : List[str] = scope def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = ids_tensor([self.batch_size, self.seq_length], self.vocab_size ) SCREAMING_SNAKE_CASE : List[str] = None if self.use_input_mask: SCREAMING_SNAKE_CASE : Union[str, Any] = random_attention_mask([self.batch_size, self.seq_length] ) SCREAMING_SNAKE_CASE : Dict = None if self.use_token_type_ids: SCREAMING_SNAKE_CASE : Dict = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size ) SCREAMING_SNAKE_CASE : Optional[int] = None SCREAMING_SNAKE_CASE : str = None SCREAMING_SNAKE_CASE : Any = None if self.use_labels: SCREAMING_SNAKE_CASE : str = ids_tensor([self.batch_size], self.type_sequence_label_size ) SCREAMING_SNAKE_CASE : Dict = ids_tensor([self.batch_size, self.seq_length], self.num_labels ) SCREAMING_SNAKE_CASE : int = DebertaVaConfig( 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, relative_attention=self.relative_attention, position_biased_input=self.position_biased_input, initializer_range=self.initializer_range, return_dict=A, ) return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def UpperCamelCase_ ( self, A, A, A, A, A, A, A ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = TFDebertaVaModel(config=A ) SCREAMING_SNAKE_CASE : Dict = {'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids} SCREAMING_SNAKE_CASE : Any = [input_ids, input_mask] SCREAMING_SNAKE_CASE : Tuple = model(A ) SCREAMING_SNAKE_CASE : int = model(A ) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size) ) def UpperCamelCase_ ( self, A, A, A, A, A, A, A ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = TFDebertaVaForMaskedLM(config=A ) SCREAMING_SNAKE_CASE : str = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } SCREAMING_SNAKE_CASE : List[Any] = model(A ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size) ) def UpperCamelCase_ ( self, A, A, A, A, A, A, A ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self.num_labels SCREAMING_SNAKE_CASE : Dict = TFDebertaVaForSequenceClassification(config=A ) SCREAMING_SNAKE_CASE : Dict = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } SCREAMING_SNAKE_CASE : Optional[int] = model(A ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self, A, A, A, A, A, A, A ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.num_labels SCREAMING_SNAKE_CASE : List[str] = TFDebertaVaForTokenClassification(config=A ) SCREAMING_SNAKE_CASE : Union[str, Any] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } SCREAMING_SNAKE_CASE : Optional[int] = model(A ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels) ) def UpperCamelCase_ ( self, A, A, A, A, A, A, A ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = TFDebertaVaForQuestionAnswering(config=A ) SCREAMING_SNAKE_CASE : List[Any] = { 'input_ids': input_ids, 'attention_mask': input_mask, 'token_type_ids': token_type_ids, } SCREAMING_SNAKE_CASE : Optional[int] = model(A ) self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length) ) def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : Dict = 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 ) , ) : str = config_and_inputs SCREAMING_SNAKE_CASE : Dict = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_tf class _a ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' A : int = ( ( TFDebertaVaModel, TFDebertaVaForMaskedLM, TFDebertaVaForQuestionAnswering, TFDebertaVaForSequenceClassification, TFDebertaVaForTokenClassification, ) if is_tf_available() else () ) A : Optional[Any] = ( { '''feature-extraction''': TFDebertaVaModel, '''fill-mask''': TFDebertaVaForMaskedLM, '''question-answering''': TFDebertaVaForQuestionAnswering, '''text-classification''': TFDebertaVaForSequenceClassification, '''token-classification''': TFDebertaVaForTokenClassification, '''zero-shot''': TFDebertaVaForSequenceClassification, } if is_tf_available() else {} ) A : Any = False A : List[Any] = False def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = TFDebertaVaModelTester(self ) SCREAMING_SNAKE_CASE : str = ConfigTester(self, config_class=A, hidden_size=37 ) def UpperCamelCase_ ( self ): '''simple docstring''' self.config_tester.run_common_tests() def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*A ) def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*A ) def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*A ) def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*A ) @slow def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : Any = TFDebertaVaModel.from_pretrained('kamalkraj/deberta-v2-xlarge' ) self.assertIsNotNone(A ) @require_tf class _a ( unittest.TestCase ): '''simple docstring''' @unittest.skip(reason='Model not available yet' ) def UpperCamelCase_ ( self ): '''simple docstring''' pass @slow def UpperCamelCase_ ( self ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = TFDebertaVaModel.from_pretrained('kamalkraj/deberta-v2-xlarge' ) SCREAMING_SNAKE_CASE : Dict = tf.constant([[0, 31_414, 232, 328, 740, 1_140, 12_695, 69, 46_078, 1_588, 2]] ) SCREAMING_SNAKE_CASE : str = tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) SCREAMING_SNAKE_CASE : Any = model(A, attention_mask=A )[0] SCREAMING_SNAKE_CASE : Union[str, Any] = tf.constant( [[[0.23_56, 0.19_48, 0.03_69], [-0.10_63, 0.35_86, -0.51_52], [-0.63_99, -0.02_59, -0.25_25]]] ) tf.debugging.assert_near(output[:, 1:4, 1:4], A, atol=1E-4 )
246
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from tokenizers import processors from ...tokenization_utils import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_nllb import NllbTokenizer else: UpperCamelCase_ = None UpperCamelCase_ = logging.get_logger(__name__) UpperCamelCase_ = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"} UpperCamelCase_ = { "vocab_file": { "facebook/nllb-200-distilled-600M": ( "https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model" ), }, "tokenizer_file": { "facebook/nllb-200-distilled-600M": ( "https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json" ), }, } UpperCamelCase_ = { "facebook/nllb-large-en-ro": 1_0_2_4, "facebook/nllb-200-distilled-600M": 1_0_2_4, } # fmt: off UpperCamelCase_ = ["ace_Arab", "ace_Latn", "acm_Arab", "acq_Arab", "aeb_Arab", "afr_Latn", "ajp_Arab", "aka_Latn", "amh_Ethi", "apc_Arab", "arb_Arab", "ars_Arab", "ary_Arab", "arz_Arab", "asm_Beng", "ast_Latn", "awa_Deva", "ayr_Latn", "azb_Arab", "azj_Latn", "bak_Cyrl", "bam_Latn", "ban_Latn", "bel_Cyrl", "bem_Latn", "ben_Beng", "bho_Deva", "bjn_Arab", "bjn_Latn", "bod_Tibt", "bos_Latn", "bug_Latn", "bul_Cyrl", "cat_Latn", "ceb_Latn", "ces_Latn", "cjk_Latn", "ckb_Arab", "crh_Latn", "cym_Latn", "dan_Latn", "deu_Latn", "dik_Latn", "dyu_Latn", "dzo_Tibt", "ell_Grek", "eng_Latn", "epo_Latn", "est_Latn", "eus_Latn", "ewe_Latn", "fao_Latn", "pes_Arab", "fij_Latn", "fin_Latn", "fon_Latn", "fra_Latn", "fur_Latn", "fuv_Latn", "gla_Latn", "gle_Latn", "glg_Latn", "grn_Latn", "guj_Gujr", "hat_Latn", "hau_Latn", "heb_Hebr", "hin_Deva", "hne_Deva", "hrv_Latn", "hun_Latn", "hye_Armn", "ibo_Latn", "ilo_Latn", "ind_Latn", "isl_Latn", "ita_Latn", "jav_Latn", "jpn_Jpan", "kab_Latn", "kac_Latn", "kam_Latn", "kan_Knda", "kas_Arab", "kas_Deva", "kat_Geor", "knc_Arab", "knc_Latn", "kaz_Cyrl", "kbp_Latn", "kea_Latn", "khm_Khmr", "kik_Latn", "kin_Latn", "kir_Cyrl", "kmb_Latn", "kon_Latn", "kor_Hang", "kmr_Latn", "lao_Laoo", "lvs_Latn", "lij_Latn", "lim_Latn", "lin_Latn", "lit_Latn", "lmo_Latn", "ltg_Latn", "ltz_Latn", "lua_Latn", "lug_Latn", "luo_Latn", "lus_Latn", "mag_Deva", "mai_Deva", "mal_Mlym", "mar_Deva", "min_Latn", "mkd_Cyrl", "plt_Latn", "mlt_Latn", "mni_Beng", "khk_Cyrl", "mos_Latn", "mri_Latn", "zsm_Latn", "mya_Mymr", "nld_Latn", "nno_Latn", "nob_Latn", "npi_Deva", "nso_Latn", "nus_Latn", "nya_Latn", "oci_Latn", "gaz_Latn", "ory_Orya", "pag_Latn", "pan_Guru", "pap_Latn", "pol_Latn", "por_Latn", "prs_Arab", "pbt_Arab", "quy_Latn", "ron_Latn", "run_Latn", "rus_Cyrl", "sag_Latn", "san_Deva", "sat_Beng", "scn_Latn", "shn_Mymr", "sin_Sinh", "slk_Latn", "slv_Latn", "smo_Latn", "sna_Latn", "snd_Arab", "som_Latn", "sot_Latn", "spa_Latn", "als_Latn", "srd_Latn", "srp_Cyrl", "ssw_Latn", "sun_Latn", "swe_Latn", "swh_Latn", "szl_Latn", "tam_Taml", "tat_Cyrl", "tel_Telu", "tgk_Cyrl", "tgl_Latn", "tha_Thai", "tir_Ethi", "taq_Latn", "taq_Tfng", "tpi_Latn", "tsn_Latn", "tso_Latn", "tuk_Latn", "tum_Latn", "tur_Latn", "twi_Latn", "tzm_Tfng", "uig_Arab", "ukr_Cyrl", "umb_Latn", "urd_Arab", "uzn_Latn", "vec_Latn", "vie_Latn", "war_Latn", "wol_Latn", "xho_Latn", "ydd_Hebr", "yor_Latn", "yue_Hant", "zho_Hans", "zho_Hant", "zul_Latn"] class _a ( SCREAMING_SNAKE_CASE ): '''simple docstring''' A : Optional[Any] = VOCAB_FILES_NAMES A : Dict = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A : Dict = PRETRAINED_VOCAB_FILES_MAP A : Any = ['''input_ids''', '''attention_mask'''] A : Dict = NllbTokenizer A : List[int] = [] A : List[int] = [] def __init__( self, A=None, A=None, A="<s>", A="</s>", A="</s>", A="<s>", A="<unk>", A="<pad>", A="<mask>", A=None, A=None, A=None, A=False, **A, ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = AddedToken(A, lstrip=A, rstrip=A ) if isinstance(A, A ) else mask_token SCREAMING_SNAKE_CASE : Tuple = legacy_behaviour super().__init__( vocab_file=A, tokenizer_file=A, bos_token=A, eos_token=A, sep_token=A, cls_token=A, unk_token=A, pad_token=A, mask_token=A, src_lang=A, tgt_lang=A, additional_special_tokens=A, legacy_behaviour=A, **A, ) SCREAMING_SNAKE_CASE : Any = vocab_file SCREAMING_SNAKE_CASE : Optional[int] = False if not self.vocab_file else True SCREAMING_SNAKE_CASE : List[str] = FAIRSEQ_LANGUAGE_CODES.copy() if additional_special_tokens is not None: # Only add those special tokens if they are not already there. _additional_special_tokens.extend( [t for t in additional_special_tokens if t not in _additional_special_tokens] ) self.add_special_tokens({'additional_special_tokens': _additional_special_tokens} ) SCREAMING_SNAKE_CASE : Optional[Any] = { lang_code: self.convert_tokens_to_ids(A ) for lang_code in FAIRSEQ_LANGUAGE_CODES } SCREAMING_SNAKE_CASE : Dict = src_lang if src_lang is not None else 'eng_Latn' SCREAMING_SNAKE_CASE : Optional[Any] = self.convert_tokens_to_ids(self._src_lang ) SCREAMING_SNAKE_CASE : List[str] = tgt_lang self.set_src_lang_special_tokens(self._src_lang ) @property def UpperCamelCase_ ( self ): '''simple docstring''' return self._src_lang @src_lang.setter def UpperCamelCase_ ( self, A ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[str] = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def UpperCamelCase_ ( self, A, A = None ): '''simple docstring''' if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def UpperCamelCase_ ( self, A, A = None ): '''simple docstring''' SCREAMING_SNAKE_CASE : List[Any] = [self.sep_token_id] SCREAMING_SNAKE_CASE : Dict = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def UpperCamelCase_ ( self, A, A, A, A, **A ): '''simple docstring''' if src_lang is None or tgt_lang is None: raise ValueError('Translation requires a `src_lang` and a `tgt_lang` for this model' ) SCREAMING_SNAKE_CASE : Union[str, Any] = src_lang SCREAMING_SNAKE_CASE : List[Any] = self(A, add_special_tokens=A, return_tensors=A, **A ) SCREAMING_SNAKE_CASE : Any = self.convert_tokens_to_ids(A ) SCREAMING_SNAKE_CASE : int = tgt_lang_id return inputs def UpperCamelCase_ ( self, A, A = "eng_Latn", A = None, A = "fra_Latn", **A, ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = src_lang SCREAMING_SNAKE_CASE : List[Any] = tgt_lang return super().prepare_seqaseq_batch(A, A, **A ) def UpperCamelCase_ ( self ): '''simple docstring''' return self.set_src_lang_special_tokens(self.src_lang ) def UpperCamelCase_ ( self ): '''simple docstring''' return self.set_tgt_lang_special_tokens(self.tgt_lang ) def UpperCamelCase_ ( self, A ): '''simple docstring''' SCREAMING_SNAKE_CASE : int = self.convert_tokens_to_ids(A ) if self.legacy_behaviour: SCREAMING_SNAKE_CASE : str = [] SCREAMING_SNAKE_CASE : List[Any] = [self.eos_token_id, self.cur_lang_code] else: SCREAMING_SNAKE_CASE : Tuple = [self.cur_lang_code] SCREAMING_SNAKE_CASE : List[Any] = [self.eos_token_id] SCREAMING_SNAKE_CASE : Tuple = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE : int = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE : Tuple = processors.TemplateProcessing( single=prefix_tokens_str + ['$A'] + suffix_tokens_str, pair=prefix_tokens_str + ['$A', '$B'] + suffix_tokens_str, special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str, self.prefix_tokens + self.suffix_tokens ) ), ) def UpperCamelCase_ ( self, A ): '''simple docstring''' SCREAMING_SNAKE_CASE : Union[str, Any] = self.convert_tokens_to_ids(A ) if self.legacy_behaviour: SCREAMING_SNAKE_CASE : List[Any] = [] SCREAMING_SNAKE_CASE : List[str] = [self.eos_token_id, self.cur_lang_code] else: SCREAMING_SNAKE_CASE : Dict = [self.cur_lang_code] SCREAMING_SNAKE_CASE : str = [self.eos_token_id] SCREAMING_SNAKE_CASE : Optional[int] = self.convert_ids_to_tokens(self.prefix_tokens ) SCREAMING_SNAKE_CASE : List[str] = self.convert_ids_to_tokens(self.suffix_tokens ) SCREAMING_SNAKE_CASE : Union[str, Any] = processors.TemplateProcessing( single=prefix_tokens_str + ['$A'] + suffix_tokens_str, pair=prefix_tokens_str + ['$A', '$B'] + suffix_tokens_str, special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str, self.prefix_tokens + self.suffix_tokens ) ), ) def UpperCamelCase_ ( self, A, A = None ): '''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 : int = 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,)
246
1
"""simple docstring""" from __future__ import annotations import random # Maximum size of the population. Bigger could be faster but is more memory expensive. _lowerCamelCase : Optional[int] = 200 # Number of elements selected in every generation of evolution. The selection takes # place from best to worst of that generation and must be smaller than N_POPULATION. _lowerCamelCase : str = 50 # Probability that an element of a generation can mutate, changing one of its genes. # This will guarantee that all genes will be used during evolution. _lowerCamelCase : Any = 0.4 # Just a seed to improve randomness required by the algorithm. random.seed(random.randint(0, 1000)) def lowercase_ ( _UpperCAmelCase , _UpperCAmelCase ): """simple docstring""" A_ : Union[str, Any] = len([g for position, g in enumerate(_UpperCAmelCase ) if g == main_target[position]] ) return (item, float(_UpperCAmelCase )) def lowercase_ ( _UpperCAmelCase , _UpperCAmelCase ): """simple docstring""" A_ : str = random.randint(0 , len(_UpperCAmelCase ) - 1 ) A_ : Tuple = parent_a[:random_slice] + parent_a[random_slice:] A_ : Tuple = parent_a[:random_slice] + parent_a[random_slice:] return (child_a, child_a) def lowercase_ ( _UpperCAmelCase , _UpperCAmelCase ): """simple docstring""" A_ : Tuple = list(_UpperCAmelCase ) if random.uniform(0 , 1 ) < MUTATION_PROBABILITY: A_ : Tuple = random.choice(_UpperCAmelCase ) return "".join(_UpperCAmelCase ) def lowercase_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , ): """simple docstring""" A_ : Any = [] # Generate more children proportionally to the fitness score. A_ : int = int(parent_a[1] * 100 ) + 1 A_ : Tuple = 10 if child_n >= 10 else child_n for _ in range(_UpperCAmelCase ): A_ : List[Any] = population_score[random.randint(0 , _UpperCAmelCase )][0] A_ , A_ : Any = crossover(parent_a[0] , _UpperCAmelCase ) # Append new string to the population list. pop.append(mutate(_UpperCAmelCase , _UpperCAmelCase ) ) pop.append(mutate(_UpperCAmelCase , _UpperCAmelCase ) ) return pop def lowercase_ ( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = True ): """simple docstring""" if N_POPULATION < N_SELECTED: A_ : Union[str, Any] = f"""{N_POPULATION} must be bigger than {N_SELECTED}""" raise ValueError(_UpperCAmelCase ) # Verify that the target contains no genes besides the ones inside genes variable. A_ : Tuple = sorted({c for c in target if c not in genes} ) if not_in_genes_list: A_ : int = f"""{not_in_genes_list} is not in genes list, evolution cannot converge""" raise ValueError(_UpperCAmelCase ) # Generate random starting population. A_ : List[Any] = [] for _ in range(_UpperCAmelCase ): population.append(''''''.join([random.choice(_UpperCAmelCase ) for i in range(len(_UpperCAmelCase ) )] ) ) # Just some logs to know what the algorithms is doing. A_ , A_ : str = 0, 0 # This loop will end when we find a perfect match for our target. while True: generation += 1 total_population += len(_UpperCAmelCase ) # Random population created. Now it's time to evaluate. # Adding a bit of concurrency can make everything faster, # # import concurrent.futures # population_score: list[tuple[str, float]] = [] # with concurrent.futures.ThreadPoolExecutor( # max_workers=NUM_WORKERS) as executor: # futures = {executor.submit(evaluate, item) for item in population} # concurrent.futures.wait(futures) # population_score = [item.result() for item in futures] # # but with a simple algorithm like this, it will probably be slower. # We just need to call evaluate for every item inside the population. A_ : Union[str, Any] = [evaluate(_UpperCAmelCase , _UpperCAmelCase ) for item in population] # Check if there is a matching evolution. A_ : List[Any] = sorted(_UpperCAmelCase , key=lambda _UpperCAmelCase : x[1] , reverse=_UpperCAmelCase ) if population_score[0][0] == target: return (generation, total_population, population_score[0][0]) # Print the best result every 10 generation. # Just to know that the algorithm is working. if debug and generation % 10 == 0: print( f"""\nGeneration: {generation}""" f"""\nTotal Population:{total_population}""" f"""\nBest score: {population_score[0][1]}""" f"""\nBest string: {population_score[0][0]}""" ) # Flush the old population, keeping some of the best evolutions. # Keeping this avoid regression of evolution. A_ : Optional[Any] = population[: int(N_POPULATION / 3 )] population.clear() population.extend(_UpperCAmelCase ) # Normalize population score to be between 0 and 1. A_ : Tuple = [ (item, score / len(_UpperCAmelCase )) for item, score in population_score ] # This is selection for i in range(_UpperCAmelCase ): population.extend(select(population_score[int(_UpperCAmelCase )] , _UpperCAmelCase , _UpperCAmelCase ) ) # Check if the population has already reached the maximum value and if so, # break the cycle. If this check is disabled, the algorithm will take # forever to compute large strings, but will also calculate small strings in # a far fewer generations. if len(_UpperCAmelCase ) > N_POPULATION: break if __name__ == "__main__": _lowerCamelCase : Optional[Any] = ( 'This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!' ) _lowerCamelCase : List[str] = list( ' ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm' 'nopqrstuvwxyz.,;!?+-*#@^\'èéòà€ù=)(&%$£/\\' ) _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : List[Any] = basic(target_str, genes_list) print( f'\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}' )
167
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available _lowerCamelCase : Any = { 'configuration_git': ['GIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'GitConfig', 'GitVisionConfig'], 'processing_git': ['GitProcessor'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _lowerCamelCase : Dict = [ 'GIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'GitForCausalLM', 'GitModel', 'GitPreTrainedModel', 'GitVisionModel', ] if TYPE_CHECKING: from .configuration_git import GIT_PRETRAINED_CONFIG_ARCHIVE_MAP, GitConfig, GitVisionConfig from .processing_git import GitProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_git import ( GIT_PRETRAINED_MODEL_ARCHIVE_LIST, GitForCausalLM, GitModel, GitPreTrainedModel, GitVisionModel, ) else: import sys _lowerCamelCase : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
167
1
"""simple docstring""" import math from typing import Optional import numpy as np from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : Optional[int] = logging.get_logger(__name__) a__ : Optional[Any] = { '''facebook/encodec_24khz''': '''https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json''', '''facebook/encodec_48khz''': '''https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json''', } class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Optional[Any] = "encodec" def __init__( self : Optional[int] , UpperCAmelCase__ : str=[1.5, 3.0, 6.0, 12.0, 24.0] , UpperCAmelCase__ : Tuple=2_4_0_0_0 , UpperCAmelCase__ : List[str]=1 , UpperCAmelCase__ : Dict=False , UpperCAmelCase__ : List[Any]=None , UpperCAmelCase__ : Tuple=None , UpperCAmelCase__ : List[str]=1_2_8 , UpperCAmelCase__ : Any=3_2 , UpperCAmelCase__ : Optional[int]=1 , UpperCAmelCase__ : Optional[Any]=[8, 5, 4, 2] , UpperCAmelCase__ : Any="weight_norm" , UpperCAmelCase__ : List[str]=7 , UpperCAmelCase__ : str=7 , UpperCAmelCase__ : int=3 , UpperCAmelCase__ : int=2 , UpperCAmelCase__ : Any=True , UpperCAmelCase__ : Optional[int]="reflect" , UpperCAmelCase__ : Optional[Any]=2 , UpperCAmelCase__ : Dict=2 , UpperCAmelCase__ : Dict=1.0 , UpperCAmelCase__ : Union[str, Any]=1_0_2_4 , UpperCAmelCase__ : Dict=None , UpperCAmelCase__ : Any=True , **UpperCAmelCase__ : str , ) -> Dict: __SCREAMING_SNAKE_CASE = target_bandwidths __SCREAMING_SNAKE_CASE = sampling_rate __SCREAMING_SNAKE_CASE = audio_channels __SCREAMING_SNAKE_CASE = normalize __SCREAMING_SNAKE_CASE = chunk_length_s __SCREAMING_SNAKE_CASE = overlap __SCREAMING_SNAKE_CASE = hidden_size __SCREAMING_SNAKE_CASE = num_filters __SCREAMING_SNAKE_CASE = num_residual_layers __SCREAMING_SNAKE_CASE = upsampling_ratios __SCREAMING_SNAKE_CASE = norm_type __SCREAMING_SNAKE_CASE = kernel_size __SCREAMING_SNAKE_CASE = last_kernel_size __SCREAMING_SNAKE_CASE = residual_kernel_size __SCREAMING_SNAKE_CASE = dilation_growth_rate __SCREAMING_SNAKE_CASE = use_causal_conv __SCREAMING_SNAKE_CASE = pad_mode __SCREAMING_SNAKE_CASE = compress __SCREAMING_SNAKE_CASE = num_lstm_layers __SCREAMING_SNAKE_CASE = trim_right_ratio __SCREAMING_SNAKE_CASE = codebook_size __SCREAMING_SNAKE_CASE = codebook_dim if codebook_dim is not None else hidden_size __SCREAMING_SNAKE_CASE = use_conv_shortcut if self.norm_type not in ["weight_norm", "time_group_norm"]: raise ValueError( F"""self.norm_type must be one of `\"weight_norm\"`, `\"time_group_norm\"`), got {self.norm_type}""" ) super().__init__(**UpperCAmelCase__ ) @property def UpperCAmelCase_ ( self : Optional[int] ) -> Optional[int]: if self.chunk_length_s is None: return None else: return int(self.chunk_length_s * self.sampling_rate ) @property def UpperCAmelCase_ ( self : Tuple ) -> Optional[int]: if self.chunk_length_s is None or self.overlap is None: return None else: return max(1 , int((1.0 - self.overlap) * self.chunk_length ) ) @property def UpperCAmelCase_ ( self : Any ) -> int: __SCREAMING_SNAKE_CASE = np.prod(self.upsampling_ratios ) return math.ceil(self.sampling_rate / hop_length ) @property def UpperCAmelCase_ ( self : Optional[Any] ) -> int: return int(1_0_0_0 * self.target_bandwidths[-1] // (self.frame_rate * 1_0) )
195
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : int = logging.get_logger(__name__) a__ : Tuple = {'''ctrl''': '''https://huggingface.co/ctrl/resolve/main/config.json'''} class UpperCamelCase_ ( UpperCamelCase): """simple docstring""" snake_case__ : Dict = "ctrl" snake_case__ : int = ["past_key_values"] snake_case__ : Tuple = { "max_position_embeddings": "n_positions", "hidden_size": "n_embd", "num_attention_heads": "n_head", "num_hidden_layers": "n_layer", } def __init__( self : List[Any] , UpperCAmelCase__ : Any=2_4_6_5_3_4 , UpperCAmelCase__ : List[Any]=2_5_6 , UpperCAmelCase__ : Optional[int]=1_2_8_0 , UpperCAmelCase__ : Optional[Any]=8_1_9_2 , UpperCAmelCase__ : int=4_8 , UpperCAmelCase__ : Optional[int]=1_6 , UpperCAmelCase__ : Tuple=0.1 , UpperCAmelCase__ : Optional[Any]=0.1 , UpperCAmelCase__ : Any=1E-6 , UpperCAmelCase__ : List[str]=0.02 , UpperCAmelCase__ : Union[str, Any]=True , **UpperCAmelCase__ : Tuple , ) -> str: __SCREAMING_SNAKE_CASE = vocab_size __SCREAMING_SNAKE_CASE = n_positions __SCREAMING_SNAKE_CASE = n_embd __SCREAMING_SNAKE_CASE = n_layer __SCREAMING_SNAKE_CASE = n_head __SCREAMING_SNAKE_CASE = dff __SCREAMING_SNAKE_CASE = resid_pdrop __SCREAMING_SNAKE_CASE = embd_pdrop __SCREAMING_SNAKE_CASE = layer_norm_epsilon __SCREAMING_SNAKE_CASE = initializer_range __SCREAMING_SNAKE_CASE = use_cache super().__init__(**UpperCAmelCase__ )
195
1
from __future__ import annotations from decimal import Decimal from numpy import array def lowercase_ ( _lowerCamelCase : list[list[float]]): lowercase__ : Tuple = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(_lowerCamelCase) == 2 and len(matrix[0]) == 2 and len(matrix[1]) == 2: # Calculate the determinant of the matrix lowercase__ : str = float( d(matrix[0][0]) * d(matrix[1][1]) - d(matrix[1][0]) * d(matrix[0][1])) if determinant == 0: raise ValueError("This matrix has no inverse.") # Creates a copy of the matrix with swapped positions of the elements lowercase__ : Dict = [[0.0, 0.0], [0.0, 0.0]] lowercase__ , lowercase__ : Union[str, Any] = matrix[1][1], matrix[0][0] lowercase__ , lowercase__ : int = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(_lowerCamelCase)) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(_lowerCamelCase) == 3 and len(matrix[0]) == 3 and len(matrix[1]) == 3 and len(matrix[2]) == 3 ): # Calculate the determinant of the matrix using Sarrus rule lowercase__ : Any = float( ( (d(matrix[0][0]) * d(matrix[1][1]) * d(matrix[2][2])) + (d(matrix[0][1]) * d(matrix[1][2]) * d(matrix[2][0])) + (d(matrix[0][2]) * d(matrix[1][0]) * d(matrix[2][1])) ) - ( (d(matrix[0][2]) * d(matrix[1][1]) * d(matrix[2][0])) + (d(matrix[0][1]) * d(matrix[1][0]) * d(matrix[2][2])) + (d(matrix[0][0]) * d(matrix[1][2]) * d(matrix[2][1])) )) if determinant == 0: raise ValueError("This matrix has no inverse.") # Creating cofactor matrix lowercase__ : Optional[Any] = [ [d(0.0), d(0.0), d(0.0)], [d(0.0), d(0.0), d(0.0)], [d(0.0), d(0.0), d(0.0)], ] lowercase__ : Optional[int] = (d(matrix[1][1]) * d(matrix[2][2])) - ( d(matrix[1][2]) * d(matrix[2][1]) ) lowercase__ : List[Any] = -( (d(matrix[1][0]) * d(matrix[2][2])) - (d(matrix[1][2]) * d(matrix[2][0])) ) lowercase__ : List[Any] = (d(matrix[1][0]) * d(matrix[2][1])) - ( d(matrix[1][1]) * d(matrix[2][0]) ) lowercase__ : Optional[Any] = -( (d(matrix[0][1]) * d(matrix[2][2])) - (d(matrix[0][2]) * d(matrix[2][1])) ) lowercase__ : Optional[int] = (d(matrix[0][0]) * d(matrix[2][2])) - ( d(matrix[0][2]) * d(matrix[2][0]) ) lowercase__ : int = -( (d(matrix[0][0]) * d(matrix[2][1])) - (d(matrix[0][1]) * d(matrix[2][0])) ) lowercase__ : int = (d(matrix[0][1]) * d(matrix[1][2])) - ( d(matrix[0][2]) * d(matrix[1][1]) ) lowercase__ : Any = -( (d(matrix[0][0]) * d(matrix[1][2])) - (d(matrix[0][2]) * d(matrix[1][0])) ) lowercase__ : List[Any] = (d(matrix[0][0]) * d(matrix[1][1])) - ( d(matrix[0][1]) * d(matrix[1][0]) ) # Transpose the cofactor matrix (Adjoint matrix) lowercase__ : List[Any] = array(_lowerCamelCase) for i in range(3): for j in range(3): lowercase__ : int = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix lowercase__ : List[Any] = array(_lowerCamelCase) for i in range(3): for j in range(3): inverse_matrix[i][j] /= d(_lowerCamelCase) # Calculate the inverse of the matrix return [[float(d(_lowerCamelCase)) or 0.0 for n in row] for row in inverse_matrix] raise ValueError("Please provide a matrix of size 2x2 or 3x3.")
87
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import cached_download, hf_hub_url from PIL import Image from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor from transformers.utils import logging logging.set_verbosity_info() _UpperCamelCase = logging.get_logger(__name__) def a_ ( _lowerCAmelCase ) -> Tuple: __lowerCamelCase : Optional[int] = DPTConfig() if "large" in checkpoint_url: __lowerCamelCase : List[Any] = 1024 __lowerCamelCase : Union[str, Any] = 4096 __lowerCamelCase : Any = 24 __lowerCamelCase : List[str] = 16 __lowerCamelCase : int = [5, 11, 17, 23] __lowerCamelCase : List[Any] = [256, 512, 1024, 1024] __lowerCamelCase : Tuple = (1, 384, 384) if "ade" in checkpoint_url: __lowerCamelCase : Tuple = True __lowerCamelCase : Union[str, Any] = 150 __lowerCamelCase : Any = 'huggingface/label-files' __lowerCamelCase : Dict = 'ade20k-id2label.json' __lowerCamelCase : Tuple = json.load(open(cached_download(hf_hub_url(_lowerCAmelCase ,_lowerCAmelCase ,repo_type='dataset' ) ) ,'r' ) ) __lowerCamelCase : List[Any] = {int(_lowerCAmelCase ): v for k, v in idalabel.items()} __lowerCamelCase : List[Any] = idalabel __lowerCamelCase : List[str] = {v: k for k, v in idalabel.items()} __lowerCamelCase : Optional[int] = [1, 150, 480, 480] return config, expected_shape def a_ ( _lowerCAmelCase ) -> Tuple: __lowerCamelCase : Optional[int] = ['pretrained.model.head.weight', 'pretrained.model.head.bias'] for k in ignore_keys: state_dict.pop(_lowerCAmelCase ,_lowerCAmelCase ) def a_ ( _lowerCAmelCase ) -> Dict: if ( "pretrained.model" in name and "cls_token" not in name and "pos_embed" not in name and "patch_embed" not in name ): __lowerCamelCase : str = name.replace('pretrained.model' ,'dpt.encoder' ) if "pretrained.model" in name: __lowerCamelCase : Union[str, Any] = name.replace('pretrained.model' ,'dpt.embeddings' ) if "patch_embed" in name: __lowerCamelCase : int = name.replace('patch_embed' ,'patch_embeddings' ) if "pos_embed" in name: __lowerCamelCase : Optional[Any] = name.replace('pos_embed' ,'position_embeddings' ) if "attn.proj" in name: __lowerCamelCase : Union[str, Any] = name.replace('attn.proj' ,'attention.output.dense' ) if "proj" in name and "project" not in name: __lowerCamelCase : List[str] = name.replace('proj' ,'projection' ) if "blocks" in name: __lowerCamelCase : Optional[int] = name.replace('blocks' ,'layer' ) if "mlp.fc1" in name: __lowerCamelCase : Dict = name.replace('mlp.fc1' ,'intermediate.dense' ) if "mlp.fc2" in name: __lowerCamelCase : int = name.replace('mlp.fc2' ,'output.dense' ) if "norm1" in name: __lowerCamelCase : Optional[int] = name.replace('norm1' ,'layernorm_before' ) if "norm2" in name: __lowerCamelCase : str = name.replace('norm2' ,'layernorm_after' ) if "scratch.output_conv" in name: __lowerCamelCase : int = name.replace('scratch.output_conv' ,'head' ) if "scratch" in name: __lowerCamelCase : Any = name.replace('scratch' ,'neck' ) if "layer1_rn" in name: __lowerCamelCase : List[str] = name.replace('layer1_rn' ,'convs.0' ) if "layer2_rn" in name: __lowerCamelCase : str = name.replace('layer2_rn' ,'convs.1' ) if "layer3_rn" in name: __lowerCamelCase : List[Any] = name.replace('layer3_rn' ,'convs.2' ) if "layer4_rn" in name: __lowerCamelCase : Optional[Any] = name.replace('layer4_rn' ,'convs.3' ) if "refinenet" in name: __lowerCamelCase : Any = int(name[len('neck.refinenet' ) : len('neck.refinenet' ) + 1] ) # tricky here: we need to map 4 to 0, 3 to 1, 2 to 2 and 1 to 3 __lowerCamelCase : Tuple = name.replace(F'refinenet{layer_idx}' ,F'fusion_stage.layers.{abs(layer_idx-4 )}' ) if "out_conv" in name: __lowerCamelCase : Any = name.replace('out_conv' ,'projection' ) if "resConfUnit1" in name: __lowerCamelCase : Optional[Any] = name.replace('resConfUnit1' ,'residual_layer1' ) if "resConfUnit2" in name: __lowerCamelCase : List[str] = name.replace('resConfUnit2' ,'residual_layer2' ) if "conv1" in name: __lowerCamelCase : Any = name.replace('conv1' ,'convolution1' ) if "conv2" in name: __lowerCamelCase : Optional[Any] = name.replace('conv2' ,'convolution2' ) # readout blocks if "pretrained.act_postprocess1.0.project.0" in name: __lowerCamelCase : str = name.replace('pretrained.act_postprocess1.0.project.0' ,'neck.reassemble_stage.readout_projects.0.0' ) if "pretrained.act_postprocess2.0.project.0" in name: __lowerCamelCase : List[Any] = name.replace('pretrained.act_postprocess2.0.project.0' ,'neck.reassemble_stage.readout_projects.1.0' ) if "pretrained.act_postprocess3.0.project.0" in name: __lowerCamelCase : Tuple = name.replace('pretrained.act_postprocess3.0.project.0' ,'neck.reassemble_stage.readout_projects.2.0' ) if "pretrained.act_postprocess4.0.project.0" in name: __lowerCamelCase : List[Any] = name.replace('pretrained.act_postprocess4.0.project.0' ,'neck.reassemble_stage.readout_projects.3.0' ) # resize blocks if "pretrained.act_postprocess1.3" in name: __lowerCamelCase : Optional[int] = name.replace('pretrained.act_postprocess1.3' ,'neck.reassemble_stage.layers.0.projection' ) if "pretrained.act_postprocess1.4" in name: __lowerCamelCase : Dict = name.replace('pretrained.act_postprocess1.4' ,'neck.reassemble_stage.layers.0.resize' ) if "pretrained.act_postprocess2.3" in name: __lowerCamelCase : Dict = name.replace('pretrained.act_postprocess2.3' ,'neck.reassemble_stage.layers.1.projection' ) if "pretrained.act_postprocess2.4" in name: __lowerCamelCase : Any = name.replace('pretrained.act_postprocess2.4' ,'neck.reassemble_stage.layers.1.resize' ) if "pretrained.act_postprocess3.3" in name: __lowerCamelCase : Tuple = name.replace('pretrained.act_postprocess3.3' ,'neck.reassemble_stage.layers.2.projection' ) if "pretrained.act_postprocess4.3" in name: __lowerCamelCase : List[Any] = name.replace('pretrained.act_postprocess4.3' ,'neck.reassemble_stage.layers.3.projection' ) if "pretrained.act_postprocess4.4" in name: __lowerCamelCase : Optional[int] = name.replace('pretrained.act_postprocess4.4' ,'neck.reassemble_stage.layers.3.resize' ) if "pretrained" in name: __lowerCamelCase : Union[str, Any] = name.replace('pretrained' ,'dpt' ) if "bn" in name: __lowerCamelCase : Union[str, Any] = name.replace('bn' ,'batch_norm' ) if "head" in name: __lowerCamelCase : Dict = name.replace('head' ,'head.head' ) if "encoder.norm" in name: __lowerCamelCase : str = name.replace('encoder.norm' ,'layernorm' ) if "auxlayer" in name: __lowerCamelCase : int = name.replace('auxlayer' ,'auxiliary_head.head' ) return name def a_ ( _lowerCAmelCase ,_lowerCAmelCase ) -> Optional[Any]: for i in range(config.num_hidden_layers ): # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) __lowerCamelCase : Union[str, Any] = state_dict.pop(F'dpt.encoder.layer.{i}.attn.qkv.weight' ) __lowerCamelCase : Optional[Any] = state_dict.pop(F'dpt.encoder.layer.{i}.attn.qkv.bias' ) # next, add query, keys and values (in that order) to the state dict __lowerCamelCase : Union[str, Any] = in_proj_weight[: config.hidden_size, :] __lowerCamelCase : List[Any] = in_proj_bias[: config.hidden_size] __lowerCamelCase : Union[str, Any] = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] __lowerCamelCase : Any = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] __lowerCamelCase : Any = in_proj_weight[ -config.hidden_size :, : ] __lowerCamelCase : Optional[Any] = in_proj_bias[-config.hidden_size :] def a_ ( ) -> Optional[int]: __lowerCamelCase : int = 'http://images.cocodataset.org/val2017/000000039769.jpg' __lowerCamelCase : Dict = Image.open(requests.get(_lowerCAmelCase ,stream=_lowerCAmelCase ).raw ) return im @torch.no_grad() def a_ ( _lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase ) -> List[Any]: __lowerCamelCase ,__lowerCamelCase : List[Any] = get_dpt_config(_lowerCAmelCase ) # load original state_dict from URL __lowerCamelCase : str = torch.hub.load_state_dict_from_url(_lowerCAmelCase ,map_location='cpu' ) # remove certain keys remove_ignore_keys_(_lowerCAmelCase ) # rename keys for key in state_dict.copy().keys(): __lowerCamelCase : int = state_dict.pop(_lowerCAmelCase ) __lowerCamelCase : List[str] = val # read in qkv matrices read_in_q_k_v(_lowerCAmelCase ,_lowerCAmelCase ) # load HuggingFace model __lowerCamelCase : Tuple = DPTForSemanticSegmentation(_lowerCAmelCase ) if 'ade' in checkpoint_url else DPTForDepthEstimation(_lowerCAmelCase ) model.load_state_dict(_lowerCAmelCase ) model.eval() # Check outputs on an image __lowerCamelCase : Dict = 480 if 'ade' in checkpoint_url else 384 __lowerCamelCase : Dict = DPTImageProcessor(size=_lowerCAmelCase ) __lowerCamelCase : Optional[int] = prepare_img() __lowerCamelCase : Optional[int] = image_processor(_lowerCAmelCase ,return_tensors='pt' ) # forward pass __lowerCamelCase : List[Any] = model(**_lowerCAmelCase ).logits if 'ade' in checkpoint_url else model(**_lowerCAmelCase ).predicted_depth # Assert logits __lowerCamelCase : Optional[int] = torch.tensor([[6.3199, 6.3629, 6.4148], [6.3850, 6.3615, 6.4166], [6.3519, 6.3176, 6.3575]] ) if "ade" in checkpoint_url: __lowerCamelCase : List[str] = torch.tensor([[4.0480, 4.2420, 4.4360], [4.3124, 4.5693, 4.8261], [4.5768, 4.8965, 5.2163]] ) assert outputs.shape == torch.Size(_lowerCAmelCase ) assert ( torch.allclose(outputs[0, 0, :3, :3] ,_lowerCAmelCase ,atol=1E-4 ) if "ade" in checkpoint_url else torch.allclose(outputs[0, :3, :3] ,_lowerCAmelCase ) ) Path(_lowerCAmelCase ).mkdir(exist_ok=_lowerCAmelCase ) print(F'Saving model to {pytorch_dump_folder_path}' ) model.save_pretrained(_lowerCAmelCase ) print(F'Saving image processor to {pytorch_dump_folder_path}' ) image_processor.save_pretrained(_lowerCAmelCase ) if push_to_hub: print('Pushing model to hub...' ) model.push_to_hub( repo_path_or_name=Path(_lowerCAmelCase ,_lowerCAmelCase ) ,organization='nielsr' ,commit_message='Add model' ,use_temp_dir=_lowerCAmelCase ,) image_processor.push_to_hub( repo_path_or_name=Path(_lowerCAmelCase ,_lowerCAmelCase ) ,organization='nielsr' ,commit_message='Add image processor' ,use_temp_dir=_lowerCAmelCase ,) if __name__ == "__main__": _UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '--checkpoint_url', default='https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt', type=str, help='URL of the original DPT checkpoint you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model directory.', ) parser.add_argument( '--push_to_hub', action='store_true', ) parser.add_argument( '--model_name', default='dpt-large', type=str, help='Name of the model, in case you\'re pushing to the hub.', ) _UpperCamelCase = parser.parse_args() convert_dpt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name)
208
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 lowerCamelCase_ ( unittest.TestCase ): '''simple docstring''' def lowerCAmelCase_ ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE_ = tempfile.mkdtemp() SCREAMING_SNAKE_CASE_ = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', '的', '价', '格', '是', '15', '便', 'alex', '##andra', ',', '。', '-', 't', 'shirt', ] SCREAMING_SNAKE_CASE_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file , 'w' , encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) SCREAMING_SNAKE_CASE_ = { '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_ = os.path.join(self.tmpdirname , _lowerCAmelCase ) with open(self.image_processor_file , 'w' , encoding='utf-8' ) as fp: json.dump(_lowerCAmelCase , _lowerCAmelCase ) def lowerCAmelCase_ ( self : Optional[Any] , **_lowerCAmelCase : str ): return BertTokenizer.from_pretrained(self.tmpdirname , **_lowerCAmelCase ) def lowerCAmelCase_ ( self : Dict , **_lowerCAmelCase : Optional[int] ): return BertTokenizerFast.from_pretrained(self.tmpdirname , **_lowerCAmelCase ) def lowerCAmelCase_ ( self : Optional[int] , **_lowerCAmelCase : List[Any] ): return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname , **_lowerCAmelCase ) def lowerCAmelCase_ ( self : Optional[Any] ): shutil.rmtree(self.tmpdirname ) def lowerCAmelCase_ ( self : str ): SCREAMING_SNAKE_CASE_ = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )] SCREAMING_SNAKE_CASE_ = [Image.fromarray(np.moveaxis(_lowerCAmelCase , 0 , -1 ) ) for x in image_inputs] return image_inputs def lowerCAmelCase_ ( self : Any ): SCREAMING_SNAKE_CASE_ = self.get_tokenizer() SCREAMING_SNAKE_CASE_ = self.get_rust_tokenizer() SCREAMING_SNAKE_CASE_ = self.get_image_processor() SCREAMING_SNAKE_CASE_ = ChineseCLIPProcessor(tokenizer=_lowerCAmelCase , image_processor=_lowerCAmelCase ) processor_slow.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE_ = ChineseCLIPProcessor.from_pretrained(self.tmpdirname , use_fast=_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = ChineseCLIPProcessor(tokenizer=_lowerCAmelCase , image_processor=_lowerCAmelCase ) processor_fast.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE_ = 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 , _lowerCAmelCase ) self.assertIsInstance(processor_fast.tokenizer , _lowerCAmelCase ) 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 , _lowerCAmelCase ) self.assertIsInstance(processor_fast.image_processor , _lowerCAmelCase ) def lowerCAmelCase_ ( self : Optional[int] ): SCREAMING_SNAKE_CASE_ = ChineseCLIPProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() ) processor.save_pretrained(self.tmpdirname ) SCREAMING_SNAKE_CASE_ = self.get_tokenizer(cls_token='(CLS)' , sep_token='(SEP)' ) SCREAMING_SNAKE_CASE_ = self.get_image_processor(do_normalize=_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = ChineseCLIPProcessor.from_pretrained( self.tmpdirname , cls_token='(CLS)' , sep_token='(SEP)' , do_normalize=_lowerCAmelCase ) self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() ) self.assertIsInstance(processor.tokenizer , _lowerCAmelCase ) self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() ) self.assertIsInstance(processor.image_processor , _lowerCAmelCase ) def lowerCAmelCase_ ( self : Optional[int] ): SCREAMING_SNAKE_CASE_ = self.get_image_processor() SCREAMING_SNAKE_CASE_ = self.get_tokenizer() SCREAMING_SNAKE_CASE_ = ChineseCLIPProcessor(tokenizer=_lowerCAmelCase , image_processor=_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = self.prepare_image_inputs() SCREAMING_SNAKE_CASE_ = image_processor(_lowerCAmelCase , return_tensors='np' ) SCREAMING_SNAKE_CASE_ = processor(images=_lowerCAmelCase , return_tensors='np' ) for key in input_feat_extract.keys(): self.assertAlmostEqual(input_feat_extract[key].sum() , input_processor[key].sum() , delta=1E-2 ) def lowerCAmelCase_ ( self : Union[str, Any] ): SCREAMING_SNAKE_CASE_ = self.get_image_processor() SCREAMING_SNAKE_CASE_ = self.get_tokenizer() SCREAMING_SNAKE_CASE_ = ChineseCLIPProcessor(tokenizer=_lowerCAmelCase , image_processor=_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = 'Alexandra,T-shirt的价格是15便士。' SCREAMING_SNAKE_CASE_ = processor(text=_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = tokenizer(_lowerCAmelCase ) for key in encoded_tok.keys(): self.assertListEqual(encoded_tok[key] , encoded_processor[key] ) def lowerCAmelCase_ ( self : Tuple ): SCREAMING_SNAKE_CASE_ = self.get_image_processor() SCREAMING_SNAKE_CASE_ = self.get_tokenizer() SCREAMING_SNAKE_CASE_ = ChineseCLIPProcessor(tokenizer=_lowerCAmelCase , image_processor=_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = 'Alexandra,T-shirt的价格是15便士。' SCREAMING_SNAKE_CASE_ = self.prepare_image_inputs() SCREAMING_SNAKE_CASE_ = processor(text=_lowerCAmelCase , images=_lowerCAmelCase ) self.assertListEqual(list(inputs.keys() ) , ['input_ids', 'token_type_ids', 'attention_mask', 'pixel_values'] ) # test if it raises when no input is passed with pytest.raises(_lowerCAmelCase ): processor() def lowerCAmelCase_ ( self : Optional[int] ): SCREAMING_SNAKE_CASE_ = self.get_image_processor() SCREAMING_SNAKE_CASE_ = self.get_tokenizer() SCREAMING_SNAKE_CASE_ = ChineseCLIPProcessor(tokenizer=_lowerCAmelCase , image_processor=_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]] SCREAMING_SNAKE_CASE_ = processor.batch_decode(_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = tokenizer.batch_decode(_lowerCAmelCase ) self.assertListEqual(_lowerCAmelCase , _lowerCAmelCase ) def lowerCAmelCase_ ( self : str ): SCREAMING_SNAKE_CASE_ = self.get_image_processor() SCREAMING_SNAKE_CASE_ = self.get_tokenizer() SCREAMING_SNAKE_CASE_ = ChineseCLIPProcessor(tokenizer=_lowerCAmelCase , image_processor=_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = 'Alexandra,T-shirt的价格是15便士。' SCREAMING_SNAKE_CASE_ = self.prepare_image_inputs() SCREAMING_SNAKE_CASE_ = processor(text=_lowerCAmelCase , images=_lowerCAmelCase ) self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
363
import cva import numpy as np class lowerCamelCase_ : '''simple docstring''' def __init__( self : Optional[Any] , _lowerCAmelCase : float , _lowerCAmelCase : int ): if k in (0.04, 0.06): SCREAMING_SNAKE_CASE_ = k SCREAMING_SNAKE_CASE_ = window_size else: raise ValueError('invalid k value' ) def __str__( self : Tuple ): return str(self.k ) def lowerCAmelCase_ ( self : int , _lowerCAmelCase : str ): SCREAMING_SNAKE_CASE_ = cva.imread(_lowerCAmelCase , 0 ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = img.shape SCREAMING_SNAKE_CASE_ = [] SCREAMING_SNAKE_CASE_ = img.copy() SCREAMING_SNAKE_CASE_ = cva.cvtColor(_lowerCAmelCase , cva.COLOR_GRAY2RGB ) SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = np.gradient(_lowerCAmelCase ) SCREAMING_SNAKE_CASE_ = dx**2 SCREAMING_SNAKE_CASE_ = dy**2 SCREAMING_SNAKE_CASE_ = dx * dy SCREAMING_SNAKE_CASE_ = 0.04 SCREAMING_SNAKE_CASE_ = self.window_size // 2 for y in range(_lowerCAmelCase , h - offset ): for x in range(_lowerCAmelCase , w - offset ): SCREAMING_SNAKE_CASE_ = ixx[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() SCREAMING_SNAKE_CASE_ = iyy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() SCREAMING_SNAKE_CASE_ = ixy[ y - offset : y + offset + 1, x - offset : x + offset + 1 ].sum() SCREAMING_SNAKE_CASE_ = (wxx * wyy) - (wxy**2) SCREAMING_SNAKE_CASE_ = wxx + wyy SCREAMING_SNAKE_CASE_ = det - k * (trace**2) # Can change the value if r > 0.5: corner_list.append([x, y, r] ) color_img.itemset((y, x, 0) , 0 ) color_img.itemset((y, x, 1) , 0 ) color_img.itemset((y, x, 2) , 255 ) return color_img, corner_list if __name__ == "__main__": lowerCamelCase__ : Optional[int] = HarrisCorner(0.04, 3) lowerCamelCase__ , lowerCamelCase__ : str = edge_detect.detect('path_to_image') cva.imwrite('detect.png', color_img)
210
0
'''simple docstring''' import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def lowerCamelCase ( __lowerCamelCase : Tuple , __lowerCamelCase : Union[str, Any]=0.999 , __lowerCamelCase : Dict="cosine" , ) ->Tuple: if alpha_transform_type == "cosine": def alpha_bar_fn(__lowerCamelCase : int ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(__lowerCamelCase : List[str] ): return math.exp(t * -12.0 ) else: raise ValueError(F'Unsupported alpha_tranform_type: {alpha_transform_type}' ) _SCREAMING_SNAKE_CASE = [] for i in range(__lowerCamelCase ): _SCREAMING_SNAKE_CASE = i / num_diffusion_timesteps _SCREAMING_SNAKE_CASE = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(__lowerCamelCase ) / alpha_bar_fn(__lowerCamelCase ) , __lowerCamelCase ) ) return torch.tensor(__lowerCamelCase , dtype=torch.floataa ) class a_ ( snake_case_ , snake_case_ ): '''simple docstring''' UpperCamelCase = [e.name for e in KarrasDiffusionSchedulers] UpperCamelCase = 2 @register_to_config def __init__( self , A = 1000 , A = 0.0_0085 , A = 0.012 , A = "linear" , A = None , A = "epsilon" , A = "linspace" , A = 0 , ) -> Dict: if trained_betas is not None: _SCREAMING_SNAKE_CASE = torch.tensor(A , dtype=torch.floataa ) elif beta_schedule == "linear": _SCREAMING_SNAKE_CASE = torch.linspace(A , A , A , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. _SCREAMING_SNAKE_CASE = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , A , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule _SCREAMING_SNAKE_CASE = betas_for_alpha_bar(A ) else: raise NotImplementedError(f'{beta_schedule} does is not implemented for {self.__class__}' ) _SCREAMING_SNAKE_CASE = 1.0 - self.betas _SCREAMING_SNAKE_CASE = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(A , A , A ) def snake_case_( self , A , A=None ) -> Union[str, Any]: if schedule_timesteps is None: _SCREAMING_SNAKE_CASE = self.timesteps _SCREAMING_SNAKE_CASE = (schedule_timesteps == timestep).nonzero() # The sigma index that is taken for the **very** first `step` # is always the second index (or the last index if there is only 1) # This way we can ensure we don't accidentally skip a sigma in # case we start in the middle of the denoising schedule (e.g. for image-to-image) if len(self._index_counter ) == 0: _SCREAMING_SNAKE_CASE = 1 if len(A ) > 1 else 0 else: _SCREAMING_SNAKE_CASE = timestep.cpu().item() if torch.is_tensor(A ) else timestep _SCREAMING_SNAKE_CASE = self._index_counter[timestep_int] return indices[pos].item() @property def snake_case_( self ) -> Tuple: # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def snake_case_( self , A , A , ) -> torch.FloatTensor: _SCREAMING_SNAKE_CASE = self.index_for_timestep(A ) if self.state_in_first_order: _SCREAMING_SNAKE_CASE = self.sigmas[step_index] else: _SCREAMING_SNAKE_CASE = self.sigmas_interpol[step_index] _SCREAMING_SNAKE_CASE = sample / ((sigma**2 + 1) ** 0.5) return sample def snake_case_( self , A , A = None , A = None , ) -> Optional[Any]: _SCREAMING_SNAKE_CASE = num_inference_steps _SCREAMING_SNAKE_CASE = num_train_timesteps or self.config.num_train_timesteps # "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891 if self.config.timestep_spacing == "linspace": _SCREAMING_SNAKE_CASE = np.linspace(0 , num_train_timesteps - 1 , A , dtype=A )[::-1].copy() elif self.config.timestep_spacing == "leading": _SCREAMING_SNAKE_CASE = num_train_timesteps // self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 _SCREAMING_SNAKE_CASE = (np.arange(0 , A ) * step_ratio).round()[::-1].copy().astype(A ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": _SCREAMING_SNAKE_CASE = num_train_timesteps / self.num_inference_steps # creates integer timesteps by multiplying by ratio # casting to int to avoid issues when num_inference_step is power of 3 _SCREAMING_SNAKE_CASE = (np.arange(A , 0 , -step_ratio )).round().copy().astype(A ) timesteps -= 1 else: raise ValueError( f'{self.config.timestep_spacing} is not supported. Please make sure to choose one of \'linspace\', \'leading\' or \'trailing\'.' ) _SCREAMING_SNAKE_CASE = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) _SCREAMING_SNAKE_CASE = torch.from_numpy(np.log(A ) ).to(A ) _SCREAMING_SNAKE_CASE = np.interp(A , np.arange(0 , len(A ) ) , A ) _SCREAMING_SNAKE_CASE = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) _SCREAMING_SNAKE_CASE = torch.from_numpy(A ).to(device=A ) # interpolate sigmas _SCREAMING_SNAKE_CASE = sigmas.log().lerp(sigmas.roll(1 ).log() , 0.5 ).exp() _SCREAMING_SNAKE_CASE = torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2 ), sigmas[-1:]] ) _SCREAMING_SNAKE_CASE = torch.cat( [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2 ), sigmas_interpol[-1:]] ) if str(A ).startswith("""mps""" ): # mps does not support float64 _SCREAMING_SNAKE_CASE = torch.from_numpy(A ).to(A , dtype=torch.floataa ) else: _SCREAMING_SNAKE_CASE = torch.from_numpy(A ).to(A ) # interpolate timesteps _SCREAMING_SNAKE_CASE = self.sigma_to_t(A ).to(A , dtype=timesteps.dtype ) _SCREAMING_SNAKE_CASE = torch.stack((timesteps_interpol[1:-1, None], timesteps[1:, None]) , dim=-1 ).flatten() _SCREAMING_SNAKE_CASE = torch.cat([timesteps[:1], interleaved_timesteps] ) _SCREAMING_SNAKE_CASE = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter _SCREAMING_SNAKE_CASE = defaultdict(A ) def snake_case_( self , A ) -> Optional[Any]: # get log sigma _SCREAMING_SNAKE_CASE = sigma.log() # get distribution _SCREAMING_SNAKE_CASE = log_sigma - self.log_sigmas[:, None] # get sigmas range _SCREAMING_SNAKE_CASE = dists.ge(0 ).cumsum(dim=0 ).argmax(dim=0 ).clamp(max=self.log_sigmas.shape[0] - 2 ) _SCREAMING_SNAKE_CASE = low_idx + 1 _SCREAMING_SNAKE_CASE = self.log_sigmas[low_idx] _SCREAMING_SNAKE_CASE = self.log_sigmas[high_idx] # interpolate sigmas _SCREAMING_SNAKE_CASE = (low - log_sigma) / (low - high) _SCREAMING_SNAKE_CASE = w.clamp(0 , 1 ) # transform interpolation to time range _SCREAMING_SNAKE_CASE = (1 - w) * low_idx + w * high_idx _SCREAMING_SNAKE_CASE = t.view(sigma.shape ) return t @property def snake_case_( self ) -> int: return self.sample is None def snake_case_( self , A , A , A , A = True , ) -> Union[SchedulerOutput, Tuple]: _SCREAMING_SNAKE_CASE = self.index_for_timestep(A ) # advance index counter by 1 _SCREAMING_SNAKE_CASE = timestep.cpu().item() if torch.is_tensor(A ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: _SCREAMING_SNAKE_CASE = self.sigmas[step_index] _SCREAMING_SNAKE_CASE = self.sigmas_interpol[step_index + 1] _SCREAMING_SNAKE_CASE = self.sigmas[step_index + 1] else: # 2nd order / KDPM2's method _SCREAMING_SNAKE_CASE = self.sigmas[step_index - 1] _SCREAMING_SNAKE_CASE = self.sigmas_interpol[step_index] _SCREAMING_SNAKE_CASE = self.sigmas[step_index] # currently only gamma=0 is supported. This usually works best anyways. # We can support gamma in the future but then need to scale the timestep before # passing it to the model which requires a change in API _SCREAMING_SNAKE_CASE = 0 _SCREAMING_SNAKE_CASE = sigma * (gamma + 1) # Note: sigma_hat == sigma for now # 1. compute predicted original sample (x_0) from sigma-scaled predicted noise if self.config.prediction_type == "epsilon": _SCREAMING_SNAKE_CASE = sigma_hat if self.state_in_first_order else sigma_interpol _SCREAMING_SNAKE_CASE = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": _SCREAMING_SNAKE_CASE = sigma_hat if self.state_in_first_order else sigma_interpol _SCREAMING_SNAKE_CASE = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": raise NotImplementedError("""prediction_type not implemented yet: sample""" ) else: raise ValueError( f'prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`' ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order _SCREAMING_SNAKE_CASE = (sample - pred_original_sample) / sigma_hat # 3. delta timestep _SCREAMING_SNAKE_CASE = sigma_interpol - sigma_hat # store for 2nd order step _SCREAMING_SNAKE_CASE = sample else: # DPM-Solver-2 # 2. Convert to an ODE derivative for 2nd order _SCREAMING_SNAKE_CASE = (sample - pred_original_sample) / sigma_interpol # 3. delta timestep _SCREAMING_SNAKE_CASE = sigma_next - sigma_hat _SCREAMING_SNAKE_CASE = self.sample _SCREAMING_SNAKE_CASE = None _SCREAMING_SNAKE_CASE = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=A ) def snake_case_( self , A , A , A , ) -> torch.FloatTensor: # Make sure sigmas and timesteps have the same device and dtype as original_samples _SCREAMING_SNAKE_CASE = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(A ): # mps does not support float64 _SCREAMING_SNAKE_CASE = self.timesteps.to(original_samples.device , dtype=torch.floataa ) _SCREAMING_SNAKE_CASE = timesteps.to(original_samples.device , dtype=torch.floataa ) else: _SCREAMING_SNAKE_CASE = self.timesteps.to(original_samples.device ) _SCREAMING_SNAKE_CASE = timesteps.to(original_samples.device ) _SCREAMING_SNAKE_CASE = [self.index_for_timestep(A , A ) for t in timesteps] _SCREAMING_SNAKE_CASE = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): _SCREAMING_SNAKE_CASE = sigma.unsqueeze(-1 ) _SCREAMING_SNAKE_CASE = original_samples + noise * sigma return noisy_samples def __len__( self ) -> str: return self.config.num_train_timesteps
58
from typing import List, Optional, Union import numpy as np import PIL.Image from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, PILImageResampling, get_image_size, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, logging __snake_case = logging.get_logger(__name__) class lowercase__ ( _UpperCAmelCase ): A__ : List[str] =["""pixel_values"""] def __init__( self : Dict , UpperCAmelCase_ : bool = True , UpperCAmelCase_ : int = 32 , UpperCAmelCase_ : int=PILImageResampling.BILINEAR , UpperCAmelCase_ : bool = True , **UpperCAmelCase_ : Any , ): SCREAMING_SNAKE_CASE__ = do_resize SCREAMING_SNAKE_CASE__ = do_rescale SCREAMING_SNAKE_CASE__ = size_divisor SCREAMING_SNAKE_CASE__ = resample super().__init__(**UpperCAmelCase_ ) def A_ ( self : Optional[int] , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : int , UpperCAmelCase_ : Dict , UpperCAmelCase_ : Optional[ChannelDimension] = None , **UpperCAmelCase_ : Dict ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = get_image_size(UpperCAmelCase_ ) # Rounds the height and width down to the closest multiple of size_divisor SCREAMING_SNAKE_CASE__ = height // size_divisor * size_divisor SCREAMING_SNAKE_CASE__ = width // size_divisor * size_divisor SCREAMING_SNAKE_CASE__ = resize(UpperCAmelCase_ , (new_h, new_w) , resample=UpperCAmelCase_ , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) return image def A_ ( self : Any , UpperCAmelCase_ : np.ndarray , UpperCAmelCase_ : float , UpperCAmelCase_ : Optional[ChannelDimension] = None , **UpperCAmelCase_ : List[str] ): return rescale(image=UpperCAmelCase_ , scale=UpperCAmelCase_ , data_format=UpperCAmelCase_ , **UpperCAmelCase_ ) def A_ ( self : Dict , UpperCAmelCase_ : Union["PIL.Image.Image", TensorType, List["PIL.Image.Image"], List[TensorType]] , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[int] = None , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : Optional[bool] = None , UpperCAmelCase_ : Optional[Union[TensorType, str]] = None , UpperCAmelCase_ : ChannelDimension = ChannelDimension.FIRST , **UpperCAmelCase_ : List[Any] , ): SCREAMING_SNAKE_CASE__ = do_resize if do_resize is not None else self.do_resize SCREAMING_SNAKE_CASE__ = do_rescale if do_rescale is not None else self.do_rescale SCREAMING_SNAKE_CASE__ = size_divisor if size_divisor is not None else self.size_divisor SCREAMING_SNAKE_CASE__ = resample if resample is not None else self.resample if do_resize and size_divisor is None: raise ValueError('size_divisor is required for resizing' ) SCREAMING_SNAKE_CASE__ = make_list_of_images(UpperCAmelCase_ ) if not valid_images(UpperCAmelCase_ ): raise ValueError('Invalid image(s)' ) # All transformations expect numpy arrays. SCREAMING_SNAKE_CASE__ = [to_numpy_array(UpperCAmelCase_ ) for img in images] if do_resize: SCREAMING_SNAKE_CASE__ = [self.resize(UpperCAmelCase_ , size_divisor=UpperCAmelCase_ , resample=UpperCAmelCase_ ) for image in images] if do_rescale: SCREAMING_SNAKE_CASE__ = [self.rescale(UpperCAmelCase_ , scale=1 / 255 ) for image in images] SCREAMING_SNAKE_CASE__ = [to_channel_dimension_format(UpperCAmelCase_ , UpperCAmelCase_ ) for image in images] SCREAMING_SNAKE_CASE__ = {'pixel_values': images} return BatchFeature(data=UpperCAmelCase_ , tensor_type=UpperCAmelCase_ )
176
0
"""simple docstring""" def snake_case__ ( __lowerCamelCase : str ): """simple docstring""" lowerCamelCase__ : str =[] lowerCamelCase__ : Optional[int] =[] lowerCamelCase__ : Dict ={ '''^''': 3, '''*''': 2, '''/''': 2, '''%''': 2, '''+''': 1, '''-''': 1, } # Priority of each operator lowerCamelCase__ : List[Any] =len(__A ) if (len(__A ) > 7) else 7 # Print table header for output print( '''Symbol'''.center(8 ) , '''Stack'''.center(__A ) , '''Postfix'''.center(__A ) , sep=''' | ''' , ) print('''-''' * (print_width * 3 + 7) ) for x in infix: if x.isalpha() or x.isdigit(): post_fix.append(__A ) # if x is Alphabet / Digit, add it to Postfix elif x == "(": stack.append(__A ) # if x is "(" push to Stack elif x == ")": # if x is ")" pop stack until "(" is encountered while stack[-1] != "(": post_fix.append(stack.pop() ) # Pop stack & add the content to Postfix stack.pop() else: if len(__A ) == 0: stack.append(__A ) # If stack is empty, push x to stack else: # while priority of x is not > priority of element in the stack while len(__A ) > 0 and priority[x] <= priority[stack[-1]]: post_fix.append(stack.pop() ) # pop stack & add to Postfix stack.append(__A ) # push x to stack print( x.center(8 ) , (''''''.join(__A )).ljust(__A ) , (''''''.join(__A )).ljust(__A ) , sep=''' | ''' , ) # Output in tabular format while len(__A ) > 0: # while stack is not empty post_fix.append(stack.pop() ) # pop stack & add to Postfix print( ''' '''.center(8 ) , (''''''.join(__A )).ljust(__A ) , (''''''.join(__A )).ljust(__A ) , sep=''' | ''' , ) # Output in tabular format return "".join(__A ) # return Postfix as str def snake_case__ ( __lowerCamelCase : List[Any] ): """simple docstring""" lowerCamelCase__ : Dict =list(infix[::-1] ) # reverse the infix equation for i in range(len(__A ) ): if infix[i] == "(": lowerCamelCase__ : List[str] =''')''' # change "(" to ")" elif infix[i] == ")": lowerCamelCase__ : Optional[Any] ='''(''' # change ")" to "(" return (infix_2_postfix(''''''.join(__A ) ))[ ::-1 ] # call infix_2_postfix on Infix, return reverse of Postfix if __name__ == "__main__": _lowercase : int = input("\nEnter an Infix Equation = ") # Input an Infix equation _lowercase : str = "".join(Infix.split()) # Remove spaces from the input print("\n\t", Infix, "(Infix) -> ", infix_2_prefix(Infix), "(Prefix)")
357
"""simple docstring""" def snake_case__ ( __lowerCamelCase : int , __lowerCamelCase : int ): """simple docstring""" return int((input_a, input_a).count(0 ) != 0 ) def snake_case__ ( ): """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))
272
0
"""simple docstring""" from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging __UpperCamelCase = logging.get_logger(__name__) class UpperCamelCase ( __a ): SCREAMING_SNAKE_CASE_ = ["""pixel_values"""] def __init__( self, lowerCAmelCase__ = True, lowerCAmelCase__ = 1 / 255, lowerCAmelCase__ = True, lowerCAmelCase__ = 8, **lowerCAmelCase__, ) -> str: super().__init__(**lowerCAmelCase__) snake_case_ = do_rescale snake_case_ = rescale_factor snake_case_ = do_pad snake_case_ = pad_size def a_ ( self, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__ = None, **lowerCAmelCase__) -> Any: return rescale(lowerCAmelCase__, scale=lowerCAmelCase__, data_format=lowerCAmelCase__, **lowerCAmelCase__) def a_ ( self, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__ = None) -> Optional[Any]: snake_case_ , snake_case_ = get_image_size(lowerCAmelCase__) snake_case_ = (old_height // size + 1) * size - old_height snake_case_ = (old_width // size + 1) * size - old_width return pad(lowerCAmelCase__, ((0, pad_height), (0, pad_width)), mode='symmetric', data_format=lowerCAmelCase__) def a_ ( self, lowerCAmelCase__, lowerCAmelCase__ = None, lowerCAmelCase__ = None, lowerCAmelCase__ = None, lowerCAmelCase__ = None, lowerCAmelCase__ = None, lowerCAmelCase__ = ChannelDimension.FIRST, **lowerCAmelCase__, ) -> List[Any]: snake_case_ = do_rescale if do_rescale is not None else self.do_rescale snake_case_ = rescale_factor if rescale_factor is not None else self.rescale_factor snake_case_ = do_pad if do_pad is not None else self.do_pad snake_case_ = pad_size if pad_size is not None else self.pad_size snake_case_ = make_list_of_images(lowerCAmelCase__) if not valid_images(lowerCAmelCase__): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.') if do_rescale and rescale_factor is None: raise ValueError('Rescale factor must be specified if do_rescale is True.') # All transformations expect numpy arrays. snake_case_ = [to_numpy_array(lowerCAmelCase__) for image in images] if do_rescale: snake_case_ = [self.rescale(image=lowerCAmelCase__, scale=lowerCAmelCase__) for image in images] if do_pad: snake_case_ = [self.pad(lowerCAmelCase__, size=lowerCAmelCase__) for image in images] snake_case_ = [to_channel_dimension_format(lowerCAmelCase__, lowerCAmelCase__) for image in images] snake_case_ = {'pixel_values': images} return BatchFeature(data=lowerCAmelCase__, tensor_type=lowerCAmelCase__)
69
'''simple docstring''' from typing import List, Optional, TypeVar from .arrow_dataset import Dataset, _concatenate_map_style_datasets, _interleave_map_style_datasets from .dataset_dict import DatasetDict, IterableDatasetDict from .info import DatasetInfo from .iterable_dataset import IterableDataset, _concatenate_iterable_datasets, _interleave_iterable_datasets from .splits import NamedSplit from .utils import logging from .utils.py_utils import Literal A =logging.get_logger(__name__) A =TypeVar('DatasetType', Dataset, IterableDataset) def snake_case_ (_a : List[DatasetType] , _a : Optional[List[float]] = None , _a : Optional[int] = None , _a : Optional[DatasetInfo] = None , _a : Optional[NamedSplit] = None , _a : Literal["first_exhausted", "all_exhausted"] = "first_exhausted" , ): from .arrow_dataset import Dataset from .iterable_dataset import IterableDataset if not datasets: raise ValueError('''Unable to interleave an empty list of datasets.''' ) for i, dataset in enumerate(_a ): if not isinstance(_a , (Dataset, IterableDataset) ): if isinstance(_a , (DatasetDict, IterableDatasetDict) ): if not dataset: raise ValueError( F"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} " '''is an empty dataset dictionary.''' ) raise ValueError( F"Dataset at position {i} has at least one split: {list(_a )}\n" F"Please pick one to interleave with the other datasets, for example: dataset['{next(iter(_a ) )}']" ) raise ValueError( F"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(_a ).__name__}." ) if i == 0: UpperCAmelCase , UpperCAmelCase = ( (Dataset, IterableDataset) if isinstance(_a , _a ) else (IterableDataset, Dataset) ) elif not isinstance(_a , _a ): raise ValueError( F"Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects." ) if stopping_strategy not in ["first_exhausted", "all_exhausted"]: raise ValueError(F"{stopping_strategy} is not supported. Please enter a valid stopping_strategy." ) if dataset_type is Dataset: return _interleave_map_style_datasets( _a , _a , _a , info=_a , split=_a , stopping_strategy=_a ) else: return _interleave_iterable_datasets( _a , _a , _a , info=_a , split=_a , stopping_strategy=_a ) def snake_case_ (_a : List[DatasetType] , _a : Optional[DatasetInfo] = None , _a : Optional[NamedSplit] = None , _a : int = 0 , ): if not dsets: raise ValueError('''Unable to concatenate an empty list of datasets.''' ) for i, dataset in enumerate(_a ): if not isinstance(_a , (Dataset, IterableDataset) ): if isinstance(_a , (DatasetDict, IterableDatasetDict) ): if not dataset: raise ValueError( F"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} " '''is an empty dataset dictionary.''' ) raise ValueError( F"Dataset at position {i} has at least one split: {list(_a )}\n" F"Please pick one to interleave with the other datasets, for example: dataset['{next(iter(_a ) )}']" ) raise ValueError( F"Expected a list of Dataset objects or a list of IterableDataset objects, but element at position {i} is a {type(_a ).__name__}." ) if i == 0: UpperCAmelCase , UpperCAmelCase = ( (Dataset, IterableDataset) if isinstance(_a , _a ) else (IterableDataset, Dataset) ) elif not isinstance(_a , _a ): raise ValueError( F"Unable to interleave a {dataset_type.__name__} (at position 0) with a {other_type.__name__} (at position {i}). Expected a list of Dataset objects or a list of IterableDataset objects." ) if dataset_type is Dataset: return _concatenate_map_style_datasets(_a , info=_a , split=_a , axis=_a ) else: return _concatenate_iterable_datasets(_a , info=_a , split=_a , axis=_a )
34
0
"""simple docstring""" import argparse import json import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification def lowerCAmelCase__ ( _UpperCamelCase : List[str] ) -> int: """simple docstring""" snake_case = SwinConfig() snake_case = swin_name.split('_' ) snake_case = name_split[1] snake_case = int(name_split[4] ) snake_case = int(name_split[3][-1] ) if model_size == "tiny": snake_case = 9_6 snake_case = (2, 2, 6, 2) snake_case = (3, 6, 1_2, 2_4) elif model_size == "small": snake_case = 9_6 snake_case = (2, 2, 1_8, 2) snake_case = (3, 6, 1_2, 2_4) elif model_size == "base": snake_case = 1_2_8 snake_case = (2, 2, 1_8, 2) snake_case = (4, 8, 1_6, 3_2) else: snake_case = 1_9_2 snake_case = (2, 2, 1_8, 2) snake_case = (6, 1_2, 2_4, 4_8) if "in22k" in swin_name: snake_case = 2_1_8_4_1 else: snake_case = 1_0_0_0 snake_case = 'huggingface/label-files' snake_case = 'imagenet-1k-id2label.json' snake_case = json.load(open(hf_hub_download(_UpperCamelCase , _UpperCamelCase , repo_type='dataset' ) , 'r' ) ) snake_case = {int(_UpperCamelCase ): v for k, v in idalabel.items()} snake_case = idalabel snake_case = {v: k for k, v in idalabel.items()} snake_case = img_size snake_case = num_classes snake_case = embed_dim snake_case = depths snake_case = num_heads snake_case = window_size return config def lowerCAmelCase__ ( _UpperCamelCase : int ) -> int: """simple docstring""" if "patch_embed.proj" in name: snake_case = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: snake_case = name.replace('patch_embed.norm' , 'embeddings.norm' ) if "layers" in name: snake_case = 'encoder.' + name if "attn.proj" in name: snake_case = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: snake_case = name.replace('attn' , 'attention.self' ) if "norm1" in name: snake_case = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: snake_case = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: snake_case = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: snake_case = name.replace('mlp.fc2' , 'output.dense' ) if name == "norm.weight": snake_case = 'layernorm.weight' if name == "norm.bias": snake_case = 'layernorm.bias' if "head" in name: snake_case = name.replace('head' , 'classifier' ) else: snake_case = 'swin.' + name return name def lowerCAmelCase__ ( _UpperCamelCase : Union[str, Any] , _UpperCamelCase : Dict ) -> str: """simple docstring""" for key in orig_state_dict.copy().keys(): snake_case = orig_state_dict.pop(_UpperCamelCase ) if "mask" in key: continue elif "qkv" in key: snake_case = key.split('.' ) snake_case = int(key_split[1] ) snake_case = int(key_split[3] ) snake_case = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: snake_case = val[:dim, :] snake_case = val[ dim : dim * 2, : ] snake_case = val[-dim:, :] else: snake_case = val[ :dim ] snake_case = val[ dim : dim * 2 ] snake_case = val[ -dim: ] else: snake_case = val return orig_state_dict def lowerCAmelCase__ ( _UpperCamelCase : int , _UpperCamelCase : Optional[int] ) -> List[str]: """simple docstring""" snake_case = timm.create_model(_UpperCamelCase , pretrained=_UpperCamelCase ) timm_model.eval() snake_case = get_swin_config(_UpperCamelCase ) snake_case = SwinForImageClassification(_UpperCamelCase ) model.eval() snake_case = convert_state_dict(timm_model.state_dict() , _UpperCamelCase ) model.load_state_dict(_UpperCamelCase ) snake_case = 'http://images.cocodataset.org/val2017/000000039769.jpg' snake_case = AutoImageProcessor.from_pretrained('microsoft/{}'.format(swin_name.replace('_' , '-' ) ) ) snake_case = Image.open(requests.get(_UpperCamelCase , stream=_UpperCamelCase ).raw ) snake_case = image_processor(images=_UpperCamelCase , return_tensors='pt' ) snake_case = timm_model(inputs['pixel_values'] ) snake_case = model(**_UpperCamelCase ).logits assert torch.allclose(_UpperCamelCase , _UpperCamelCase , atol=1e-3 ) print(f"""Saving model {swin_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_UpperCamelCase ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_UpperCamelCase ) if __name__ == "__main__": SCREAMING_SNAKE_CASE__ = argparse.ArgumentParser() # Required parameters parser.add_argument( "--swin_name", default="swin_tiny_patch4_window7_224", type=str, help="Name of the Swin timm model you'd like to convert.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to the output PyTorch model directory." ) SCREAMING_SNAKE_CASE__ = parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
366
"""simple docstring""" import os def lowerCAmelCase__ ( _UpperCamelCase : str = "matrix.txt" ) -> int: """simple docstring""" with open(os.path.join(os.path.dirname(_UpperCamelCase ) , _UpperCamelCase ) ) as in_file: snake_case = in_file.read() snake_case = [[int(_UpperCamelCase ) for cell in row.split(',' )] for row in data.strip().splitlines()] snake_case = [[0 for cell in row] for row in grid] snake_case = len(grid[0] ) snake_case = [[0 for i in range(_UpperCamelCase )] for j in range(_UpperCamelCase )] snake_case = grid[0][0] for i in range(1 , _UpperCamelCase ): snake_case = grid[0][i] + dp[0][i - 1] for i in range(1 , _UpperCamelCase ): snake_case = grid[i][0] + dp[i - 1][0] for i in range(1 , _UpperCamelCase ): for j in range(1 , _UpperCamelCase ): snake_case = grid[i][j] + min(dp[i - 1][j] , dp[i][j - 1] ) return dp[-1][-1] if __name__ == "__main__": print(f"""{solution() = }""")
149
0
'''simple docstring''' import qiskit def lowercase__ ( __lowercase : int , __lowercase : int ) -> qiskit.result.counts.Counts: """simple docstring""" __UpperCamelCase = qiskit.Aer.get_backend('aer_simulator' ) # Create a Quantum Circuit acting on the q register __UpperCamelCase = qiskit.QuantumCircuit(__lowercase , __lowercase ) # Apply X (NOT) Gate to Qubits 0 & 1 circuit.x(0 ) circuit.x(1 ) # Map the quantum measurement to the classical bits circuit.measure([0, 1] , [0, 1] ) # Execute the circuit on the qasm simulator __UpperCamelCase = qiskit.execute(__lowercase , __lowercase , shots=1000 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(__lowercase ) if __name__ == "__main__": a__ : Tuple =single_qubit_measure(2, 2) print(f'Total count for various states are: {counts}')
53
'''simple docstring''' import copy import os from typing import Union from ...configuration_utils import PretrainedConfig from ...utils import logging a__ : List[Any] =logging.get_logger(__name__) a__ : List[Any] ={ '''BAAI/AltCLIP''': '''https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json''', # See all AltCLIP models at https://huggingface.co/models?filter=altclip } class snake_case ( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple ="altclip_text_model" def __init__( self : str , __A : List[Any]=2_5_0_0_0_2 , __A : Any=1_0_2_4 , __A : int=2_4 , __A : Dict=1_6 , __A : Optional[Any]=4_0_9_6 , __A : Union[str, Any]="gelu" , __A : Dict=0.1 , __A : Dict=0.1 , __A : List[str]=5_1_4 , __A : Optional[int]=1 , __A : int=0.02 , __A : Optional[Any]=0.02 , __A : Optional[Any]=1e-05 , __A : Dict=1 , __A : List[Any]=0 , __A : int=2 , __A : Tuple="absolute" , __A : Optional[Any]=True , __A : Optional[int]=7_6_8 , **__A : List[str] , ): super().__init__(pad_token_id=__A , bos_token_id=__A , eos_token_id=__A , **__A ) __UpperCamelCase = vocab_size __UpperCamelCase = hidden_size __UpperCamelCase = num_hidden_layers __UpperCamelCase = num_attention_heads __UpperCamelCase = hidden_act __UpperCamelCase = intermediate_size __UpperCamelCase = hidden_dropout_prob __UpperCamelCase = attention_probs_dropout_prob __UpperCamelCase = max_position_embeddings __UpperCamelCase = type_vocab_size __UpperCamelCase = initializer_range __UpperCamelCase = initializer_factor __UpperCamelCase = layer_norm_eps __UpperCamelCase = position_embedding_type __UpperCamelCase = use_cache __UpperCamelCase = project_dim class snake_case ( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Tuple ="altclip_vision_model" def __init__( self : List[Any] , __A : Union[str, Any]=7_6_8 , __A : Optional[int]=3_0_7_2 , __A : Optional[Any]=5_1_2 , __A : Tuple=1_2 , __A : Union[str, Any]=1_2 , __A : Optional[int]=3 , __A : Dict=2_2_4 , __A : Tuple=3_2 , __A : str="quick_gelu" , __A : Dict=1e-5 , __A : Optional[int]=0.0 , __A : List[Any]=0.02 , __A : int=1.0 , **__A : Optional[int] , ): super().__init__(**__A ) __UpperCamelCase = hidden_size __UpperCamelCase = intermediate_size __UpperCamelCase = projection_dim __UpperCamelCase = num_hidden_layers __UpperCamelCase = num_attention_heads __UpperCamelCase = num_channels __UpperCamelCase = patch_size __UpperCamelCase = image_size __UpperCamelCase = initializer_range __UpperCamelCase = initializer_factor __UpperCamelCase = attention_dropout __UpperCamelCase = layer_norm_eps __UpperCamelCase = hidden_act @classmethod def _lowerCamelCase ( cls : Optional[Any] , __A : Union[str, os.PathLike] , **__A : Optional[Any] ): cls._set_token_in_kwargs(__A ) __UpperCamelCase , __UpperCamelCase = cls.get_config_dict(__A , **__A ) # get the vision config dict if we are loading from AltCLIPConfig if config_dict.get('model_type' ) == "altclip": __UpperCamelCase = config_dict['vision_config'] if "model_type" in config_dict and hasattr(cls , 'model_type' ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(__A , **__A ) class snake_case ( __lowerCamelCase ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] ="altclip" SCREAMING_SNAKE_CASE_ : Optional[int] =True def __init__( self : Any , __A : List[str]=None , __A : List[Any]=None , __A : List[str]=7_6_8 , __A : List[str]=2.6592 , **__A : Dict ): # If `_config_dict` exist, we use them for the backward compatibility. # We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot # of confusion!). __UpperCamelCase = kwargs.pop('text_config_dict' , __A ) __UpperCamelCase = kwargs.pop('vision_config_dict' , __A ) super().__init__(**__A ) # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`. if text_config_dict is not None: if text_config is None: __UpperCamelCase = {} # This is the complete result when using `text_config_dict`. __UpperCamelCase = AltCLIPTextConfig(**__A ).to_dict() # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different. for key, value in _text_config_dict.items(): if key in text_config and value != text_config[key] and key not in ["transformers_version"]: # If specified in `text_config_dict` if key in text_config_dict: __UpperCamelCase = ( f'''`{key}` is found in both `text_config_dict` and `text_config` but with different values. ''' f'''The value `text_config_dict["{key}"]` will be used instead.''' ) # If inferred from default argument values (just to be super careful) else: __UpperCamelCase = ( f'''`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The ''' f'''value `text_config["{key}"]` will be overriden.''' ) logger.warning(__A ) # Update all values in `text_config` with the ones in `_text_config_dict`. text_config.update(_text_config_dict ) if vision_config_dict is not None: if vision_config is None: __UpperCamelCase = {} # This is the complete result when using `vision_config_dict`. __UpperCamelCase = AltCLIPVisionConfig(**__A ).to_dict() # convert keys to string instead of integer if "id2label" in _vision_config_dict: __UpperCamelCase = { str(__A ): value for key, value in _vision_config_dict['id2label'].items() } # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different. for key, value in _vision_config_dict.items(): if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]: # If specified in `vision_config_dict` if key in vision_config_dict: __UpperCamelCase = ( f'''`{key}` is found in both `vision_config_dict` and `vision_config` but with different ''' f'''values. The value `vision_config_dict["{key}"]` will be used instead.''' ) # If inferred from default argument values (just to be super careful) else: __UpperCamelCase = ( f'''`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. ''' f'''The value `vision_config["{key}"]` will be overriden.''' ) logger.warning(__A ) # Update all values in `vision_config` with the ones in `_vision_config_dict`. vision_config.update(_vision_config_dict ) if text_config is None: __UpperCamelCase = {} logger.info('`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values.' ) if vision_config is None: __UpperCamelCase = {} logger.info('`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values.' ) __UpperCamelCase = AltCLIPTextConfig(**__A ) __UpperCamelCase = AltCLIPVisionConfig(**__A ) __UpperCamelCase = projection_dim __UpperCamelCase = logit_scale_init_value __UpperCamelCase = 1.0 @classmethod def _lowerCamelCase ( cls : Union[str, Any] , __A : AltCLIPTextConfig , __A : AltCLIPVisionConfig , **__A : Optional[Any] ): return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__A ) def _lowerCamelCase ( self : List[Any] ): __UpperCamelCase = copy.deepcopy(self.__dict__ ) __UpperCamelCase = self.text_config.to_dict() __UpperCamelCase = self.vision_config.to_dict() __UpperCamelCase = self.__class__.model_type return output
53
1
'''simple docstring''' import math def lowerCamelCase__ ( _A ): a : Union[str, Any] = [True] * n a : int = False a : List[str] = False a : List[Any] = True for i in range(3 , int(n**0.5 + 1 ) , 2 ): a : Any = i * 2 while index < n: a : Any = False a : Optional[Any] = index + i a : str = [2] for i in range(3 , _A , 2 ): if is_prime[i]: primes.append(_A ) return primes def lowerCamelCase__ ( _A = 9999_6666_3333 ): a : Optional[int] = math.floor(math.sqrt(_A ) ) + 100 a : Dict = prime_sieve(_A ) a : List[Any] = 0 a : Tuple = 0 a : int = primes[prime_index] while (last_prime**2) <= limit: a : Tuple = primes[prime_index + 1] a : Union[str, Any] = last_prime**2 a : Optional[int] = next_prime**2 # Get numbers divisible by lps(current) a : List[str] = lower_bound + last_prime while upper_bound > current <= limit: matches_sum += current current += last_prime # Reset the upper_bound while (upper_bound - next_prime) > limit: upper_bound -= next_prime # Add the numbers divisible by ups(current) a : Optional[Any] = upper_bound - next_prime while current > lower_bound: matches_sum += current current -= next_prime # Remove the numbers divisible by both ups and lps a : str = 0 while upper_bound > current <= limit: if current <= lower_bound: # Increment the current number current += last_prime * next_prime continue if current > limit: break # Remove twice since it was added by both ups and lps matches_sum -= current * 2 # Increment the current number current += last_prime * next_prime # Setup for next pair a : List[str] = next_prime prime_index += 1 return matches_sum if __name__ == "__main__": print(solution())
96
'''simple docstring''' import unittest from transformers import MraConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask if is_torch_available(): import torch from transformers import ( MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, MraModel, ) from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST class a__: def __init__( self : Union[str, Any] , __snake_case : Optional[int] , __snake_case : Optional[int]=2 , __snake_case : Union[str, Any]=8 , __snake_case : List[str]=True , __snake_case : Dict=True , __snake_case : Optional[Any]=True , __snake_case : List[str]=True , __snake_case : Tuple=99 , __snake_case : int=16 , __snake_case : Optional[int]=5 , __snake_case : int=2 , __snake_case : Tuple=36 , __snake_case : Optional[Any]="gelu" , __snake_case : str=0.0 , __snake_case : Optional[int]=0.0 , __snake_case : Tuple=5_12 , __snake_case : str=16 , __snake_case : str=2 , __snake_case : int=0.02 , __snake_case : Optional[int]=3 , __snake_case : List[Any]=4 , __snake_case : Any=None , ): a : int = parent a : Any = batch_size a : Optional[int] = seq_length a : List[str] = is_training a : Dict = use_input_mask a : Union[str, Any] = use_token_type_ids a : Tuple = use_labels a : Dict = vocab_size a : Optional[int] = hidden_size a : List[Any] = num_hidden_layers a : Optional[Any] = num_attention_heads a : str = intermediate_size a : Dict = hidden_act a : str = hidden_dropout_prob a : Tuple = attention_probs_dropout_prob a : Optional[Any] = max_position_embeddings a : Tuple = type_vocab_size a : int = type_sequence_label_size a : List[Any] = initializer_range a : List[str] = num_labels a : List[str] = num_choices a : Optional[Any] = scope def lowercase_ ( self : Union[str, Any] ): a : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a : Optional[Any] = None if self.use_input_mask: a : List[Any] = random_attention_mask([self.batch_size, self.seq_length] ) a : Tuple = None if self.use_token_type_ids: a : Optional[Any] = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) a : str = None a : int = None a : Any = None if self.use_labels: a : int = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a : List[str] = ids_tensor([self.batch_size] , self.num_choices ) a : Dict = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def lowercase_ ( self : Union[str, Any] ): return MraConfig( vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , is_decoder=__snake_case , initializer_range=self.initializer_range , ) def lowercase_ ( self : List[str] ): a : List[Any] = self.get_config() a : Optional[Any] = 3_00 return config def lowercase_ ( self : Union[str, Any] ): ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) : Optional[Any] = self.prepare_config_and_inputs() a : Union[str, Any] = True a : Tuple = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] ) a : Dict = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 ) return ( config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask, ) def lowercase_ ( self : int , __snake_case : int , __snake_case : List[Any] , __snake_case : Union[str, Any] , __snake_case : List[Any] , __snake_case : Union[str, Any] , __snake_case : Dict , __snake_case : Any ): a : Dict = MraModel(config=__snake_case ) model.to(__snake_case ) model.eval() a : str = model(__snake_case , attention_mask=__snake_case , token_type_ids=__snake_case ) a : List[str] = model(__snake_case , token_type_ids=__snake_case ) a : Union[str, Any] = model(__snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowercase_ ( self : List[str] , __snake_case : Tuple , __snake_case : List[str] , __snake_case : str , __snake_case : Optional[Any] , __snake_case : Union[str, Any] , __snake_case : Any , __snake_case : Optional[Any] , __snake_case : Optional[int] , __snake_case : List[Any] , ): a : Optional[Any] = True a : Optional[int] = MraModel(__snake_case ) model.to(__snake_case ) model.eval() a : List[Any] = model( __snake_case , attention_mask=__snake_case , token_type_ids=__snake_case , encoder_hidden_states=__snake_case , encoder_attention_mask=__snake_case , ) a : Any = model( __snake_case , attention_mask=__snake_case , token_type_ids=__snake_case , encoder_hidden_states=__snake_case , ) a : Optional[int] = model(__snake_case , attention_mask=__snake_case , token_type_ids=__snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowercase_ ( self : Optional[Any] , __snake_case : int , __snake_case : List[Any] , __snake_case : Optional[int] , __snake_case : Optional[Any] , __snake_case : List[Any] , __snake_case : Dict , __snake_case : Optional[Any] ): a : Union[str, Any] = MraForMaskedLM(config=__snake_case ) model.to(__snake_case ) model.eval() a : List[str] = model(__snake_case , attention_mask=__snake_case , token_type_ids=__snake_case , labels=__snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def lowercase_ ( self : Tuple , __snake_case : Union[str, Any] , __snake_case : str , __snake_case : Tuple , __snake_case : str , __snake_case : Tuple , __snake_case : Optional[int] , __snake_case : int ): a : Optional[int] = MraForQuestionAnswering(config=__snake_case ) model.to(__snake_case ) model.eval() a : Optional[int] = model( __snake_case , attention_mask=__snake_case , token_type_ids=__snake_case , start_positions=__snake_case , end_positions=__snake_case , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def lowercase_ ( self : Dict , __snake_case : Tuple , __snake_case : List[Any] , __snake_case : List[Any] , __snake_case : Optional[Any] , __snake_case : Any , __snake_case : List[str] , __snake_case : str ): a : Tuple = self.num_labels a : Dict = MraForSequenceClassification(__snake_case ) model.to(__snake_case ) model.eval() a : Any = model(__snake_case , attention_mask=__snake_case , token_type_ids=__snake_case , labels=__snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def lowercase_ ( self : str , __snake_case : Dict , __snake_case : Optional[Any] , __snake_case : int , __snake_case : List[Any] , __snake_case : Any , __snake_case : List[Any] , __snake_case : int ): a : Tuple = self.num_labels a : Tuple = MraForTokenClassification(config=__snake_case ) model.to(__snake_case ) model.eval() a : List[Any] = model(__snake_case , attention_mask=__snake_case , token_type_ids=__snake_case , labels=__snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def lowercase_ ( self : Any , __snake_case : Any , __snake_case : str , __snake_case : Dict , __snake_case : List[Any] , __snake_case : Any , __snake_case : Any , __snake_case : str ): a : Optional[int] = self.num_choices a : int = MraForMultipleChoice(config=__snake_case ) model.to(__snake_case ) model.eval() a : Tuple = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a : Optional[int] = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a : Optional[Any] = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() a : int = model( __snake_case , attention_mask=__snake_case , token_type_ids=__snake_case , labels=__snake_case , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def lowercase_ ( self : Optional[Any] ): a : Union[str, Any] = self.prepare_config_and_inputs() ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) : Union[str, Any] = config_and_inputs a : List[str] = {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class a__( lowerCamelCase__ , unittest.TestCase ): lowercase__ = ( ( MraModel, MraForMaskedLM, MraForMultipleChoice, MraForQuestionAnswering, MraForSequenceClassification, MraForTokenClassification, ) if is_torch_available() else () ) lowercase__ = False lowercase__ = False lowercase__ = False lowercase__ = False lowercase__ = () def lowercase_ ( self : Any ): a : Tuple = MraModelTester(self ) a : str = ConfigTester(self , config_class=__snake_case , hidden_size=37 ) def lowercase_ ( self : List[str] ): self.config_tester.run_common_tests() def lowercase_ ( self : List[str] ): a : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__snake_case ) def lowercase_ ( self : Any ): a : Union[str, Any] = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: a : Dict = type self.model_tester.create_and_check_model(*__snake_case ) def lowercase_ ( self : List[Any] ): a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__snake_case ) def lowercase_ ( self : Optional[Any] ): a : List[str] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__snake_case ) def lowercase_ ( self : List[Any] ): a : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__snake_case ) def lowercase_ ( self : Tuple ): a : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__snake_case ) def lowercase_ ( self : Optional[Any] ): a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_token_classification(*__snake_case ) @slow def lowercase_ ( self : int ): for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : Dict = MraModel.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) @unittest.skip(reason='MRA does not output attentions' ) def lowercase_ ( self : Union[str, Any] ): return @require_torch class a__( unittest.TestCase ): @slow def lowercase_ ( self : Union[str, Any] ): a : Union[str, Any] = MraModel.from_pretrained('uw-madison/mra-base-512-4' ) a : List[str] = torch.arange(2_56 ).unsqueeze(0 ) with torch.no_grad(): a : Optional[int] = model(__snake_case )[0] a : Any = torch.Size((1, 2_56, 7_68) ) self.assertEqual(output.shape , __snake_case ) a : str = torch.tensor( [[[-0.0140, 0.0830, -0.0381], [0.1546, 0.1402, 0.0220], [0.1162, 0.0851, 0.0165]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __snake_case , atol=1e-4 ) ) @slow def lowercase_ ( self : Optional[int] ): a : Dict = MraForMaskedLM.from_pretrained('uw-madison/mra-base-512-4' ) a : Optional[int] = torch.arange(2_56 ).unsqueeze(0 ) with torch.no_grad(): a : Dict = model(__snake_case )[0] a : Union[str, Any] = 5_02_65 a : Dict = torch.Size((1, 2_56, vocab_size) ) self.assertEqual(output.shape , __snake_case ) a : Dict = torch.tensor( [[[9.2595, -3.6038, 11.8819], [9.3869, -3.2693, 11.0956], [11.8524, -3.4938, 13.1210]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __snake_case , atol=1e-4 ) ) @slow def lowercase_ ( self : Any ): a : Dict = MraForMaskedLM.from_pretrained('uw-madison/mra-base-4096-8-d3' ) a : Optional[int] = torch.arange(40_96 ).unsqueeze(0 ) with torch.no_grad(): a : Tuple = model(__snake_case )[0] a : List[Any] = 5_02_65 a : str = torch.Size((1, 40_96, vocab_size) ) self.assertEqual(output.shape , __snake_case ) a : int = torch.tensor( [[[5.4789, -2.3564, 7.5064], [7.9067, -1.3369, 9.9668], [9.0712, -1.8106, 7.0380]]] ) self.assertTrue(torch.allclose(output[:, :3, :3] , __snake_case , atol=1e-4 ) )
96
1
'''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 typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class __magic_name__ ( _UpperCamelCase ): lowerCAmelCase : Tuple = 'Salesforce/blip-image-captioning-base' lowerCAmelCase : Tuple = ( 'This is a tool that generates a description of an image. It takes an input named `image` which should be the ' 'image to caption, and returns a text that contains the description in English.' ) lowerCAmelCase : Optional[int] = 'image_captioner' lowerCAmelCase : List[str] = AutoModelForVisionaSeq lowerCAmelCase : Tuple = ['image'] lowerCAmelCase : Optional[Any] = ['text'] def __init__( self : Dict ,*_UpperCAmelCase : List[Any] ,**_UpperCAmelCase : str ): requires_backends(self ,['vision'] ) super().__init__(*_UpperCAmelCase ,**_UpperCAmelCase ) def __lowercase ( self : Optional[int] ,_UpperCAmelCase : "Image" ): return self.pre_processor(images=_UpperCAmelCase ,return_tensors='pt' ) def __lowercase ( self : List[str] ,_UpperCAmelCase : int ): return self.model.generate(**_UpperCAmelCase ) def __lowercase ( self : int ,_UpperCAmelCase : Dict ): return self.pre_processor.batch_decode(_UpperCAmelCase ,skip_special_tokens=_UpperCAmelCase )[0].strip()
89
'''simple docstring''' import unittest import numpy as np from datasets import load_dataset from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import BeitImageProcessor class snake_case__ ( unittest.TestCase): def __init__( self : int , _A : List[str] , _A : Dict=7 , _A : List[str]=3 , _A : List[str]=18 , _A : Dict=30 , _A : Union[str, Any]=4_00 , _A : List[str]=True , _A : List[str]=None , _A : int=True , _A : Tuple=None , _A : Union[str, Any]=True , _A : Tuple=[0.5, 0.5, 0.5] , _A : Union[str, Any]=[0.5, 0.5, 0.5] , _A : Tuple=False , ) -> List[Any]: UpperCAmelCase_ : Union[str, Any] = size if size is not None else {'''height''': 20, '''width''': 20} UpperCAmelCase_ : List[Any] = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18} UpperCAmelCase_ : Tuple = parent UpperCAmelCase_ : Optional[int] = batch_size UpperCAmelCase_ : Any = num_channels UpperCAmelCase_ : Optional[Any] = image_size UpperCAmelCase_ : Tuple = min_resolution UpperCAmelCase_ : Tuple = max_resolution UpperCAmelCase_ : Optional[int] = do_resize UpperCAmelCase_ : Tuple = size UpperCAmelCase_ : Optional[Any] = do_center_crop UpperCAmelCase_ : Optional[int] = crop_size UpperCAmelCase_ : Tuple = do_normalize UpperCAmelCase_ : Optional[Any] = image_mean UpperCAmelCase_ : int = image_std UpperCAmelCase_ : List[Any] = do_reduce_labels def A ( self : Union[str, Any] ) -> str: return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_reduce_labels": self.do_reduce_labels, } def __UpperCAmelCase ( ) -> Optional[Any]: UpperCAmelCase_ : Union[str, Any] = load_dataset('''hf-internal-testing/fixtures_ade20k''' , split='''test''' ) UpperCAmelCase_ : Optional[Any] = Image.open(dataset[0]['''file'''] ) UpperCAmelCase_ : str = Image.open(dataset[1]['''file'''] ) return image, map def __UpperCAmelCase ( ) -> Any: UpperCAmelCase_ : int = load_dataset('''hf-internal-testing/fixtures_ade20k''' , split='''test''' ) UpperCAmelCase_ : int = Image.open(ds[0]['''file'''] ) UpperCAmelCase_ : Optional[Any] = Image.open(ds[1]['''file'''] ) UpperCAmelCase_ : Dict = Image.open(ds[2]['''file'''] ) UpperCAmelCase_ : List[str] = Image.open(ds[3]['''file'''] ) return [imagea, imagea], [mapa, mapa] @require_torch @require_vision class snake_case__ ( UpperCamelCase , unittest.TestCase): a_ = BeitImageProcessor if is_vision_available() else None def A ( self : Optional[Any] ) -> Union[str, Any]: UpperCAmelCase_ : Tuple = BeitImageProcessingTester(self ) @property def A ( self : List[Any] ) -> Tuple: return self.image_processor_tester.prepare_image_processor_dict() def A ( self : List[Any] ) -> Optional[Any]: UpperCAmelCase_ : Dict = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(_A , '''do_resize''' ) ) self.assertTrue(hasattr(_A , '''size''' ) ) self.assertTrue(hasattr(_A , '''do_center_crop''' ) ) self.assertTrue(hasattr(_A , '''center_crop''' ) ) self.assertTrue(hasattr(_A , '''do_normalize''' ) ) self.assertTrue(hasattr(_A , '''image_mean''' ) ) self.assertTrue(hasattr(_A , '''image_std''' ) ) def A ( self : List[str] ) -> Optional[int]: UpperCAmelCase_ : List[str] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'''height''': 20, '''width''': 20} ) self.assertEqual(image_processor.crop_size , {'''height''': 18, '''width''': 18} ) self.assertEqual(image_processor.do_reduce_labels , _A ) UpperCAmelCase_ : Union[str, Any] = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , crop_size=84 , reduce_labels=_A ) self.assertEqual(image_processor.size , {'''height''': 42, '''width''': 42} ) self.assertEqual(image_processor.crop_size , {'''height''': 84, '''width''': 84} ) self.assertEqual(image_processor.do_reduce_labels , _A ) def A ( self : Optional[Any] ) -> Any: pass def A ( self : List[str] ) -> Optional[int]: # Initialize image_processing UpperCAmelCase_ : List[str] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCAmelCase_ : 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 UpperCAmelCase_ : Tuple = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched UpperCAmelCase_ : Any = image_processing(_A , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def A ( self : Union[str, Any] ) -> Union[str, Any]: # Initialize image_processing UpperCAmelCase_ : Any = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCAmelCase_ : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , numpify=_A ) for image in image_inputs: self.assertIsInstance(_A , np.ndarray ) # Test not batched input UpperCAmelCase_ : List[Any] = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched UpperCAmelCase_ : int = image_processing(_A , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def A ( self : Optional[int] ) -> str: # Initialize image_processing UpperCAmelCase_ : List[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCAmelCase_ : Optional[int] = 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 UpperCAmelCase_ : Any = image_processing(image_inputs[0] , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) # Test batched UpperCAmelCase_ : int = image_processing(_A , return_tensors='''pt''' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) def A ( self : Any ) -> Optional[Any]: # Initialize image_processing UpperCAmelCase_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCAmelCase_ : Dict = prepare_image_inputs(self.image_processor_tester , equal_resolution=_A , torchify=_A ) UpperCAmelCase_ : Union[str, Any] = [] for image in image_inputs: self.assertIsInstance(_A , torch.Tensor ) maps.append(torch.zeros(image.shape[-2:] ).long() ) # Test not batched input UpperCAmelCase_ : str = image_processing(image_inputs[0] , maps[0] , return_tensors='''pt''' ) self.assertEqual( encoding['''pixel_values'''].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( 1, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 2_55 ) # Test batched UpperCAmelCase_ : List[Any] = image_processing(_A , _A , return_tensors='''pt''' ) self.assertEqual( encoding['''pixel_values'''].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 2_55 ) # Test not batched input (PIL images) UpperCAmelCase_ , UpperCAmelCase_ : Any = prepare_semantic_single_inputs() UpperCAmelCase_ : List[str] = image_processing(_A , _A , return_tensors='''pt''' ) self.assertEqual( encoding['''pixel_values'''].shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( 1, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 2_55 ) # Test batched input (PIL images) UpperCAmelCase_ , UpperCAmelCase_ : List[str] = prepare_semantic_batch_inputs() UpperCAmelCase_ : int = image_processing(_A , _A , return_tensors='''pt''' ) self.assertEqual( encoding['''pixel_values'''].shape , ( 2, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual( encoding['''labels'''].shape , ( 2, self.image_processor_tester.crop_size['''height'''], self.image_processor_tester.crop_size['''width'''], ) , ) self.assertEqual(encoding['''labels'''].dtype , torch.long ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 2_55 ) def A ( self : List[Any] ) -> Union[str, Any]: # Initialize image_processing UpperCAmelCase_ : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150 UpperCAmelCase_ , UpperCAmelCase_ : Any = prepare_semantic_single_inputs() UpperCAmelCase_ : Dict = image_processing(_A , _A , return_tensors='''pt''' ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 1_50 ) UpperCAmelCase_ : int = True UpperCAmelCase_ : Dict = image_processing(_A , _A , return_tensors='''pt''' ) self.assertTrue(encoding['''labels'''].min().item() >= 0 ) self.assertTrue(encoding['''labels'''].max().item() <= 2_55 )
304
0
from __future__ import annotations from typing import Dict from ...configuration_utils import PretrainedConfig lowercase__ :List[Any] = { "susnato/ernie-m-base_pytorch": "https://huggingface.co/susnato/ernie-m-base_pytorch/blob/main/config.json", "susnato/ernie-m-large_pytorch": "https://huggingface.co/susnato/ernie-m-large_pytorch/blob/main/config.json", } class lowercase ( SCREAMING_SNAKE_CASE__ ): lowercase_ : List[Any] ='''ernie_m''' lowercase_ : Dict[str, str] ={"dropout": "classifier_dropout", "num_classes": "num_labels"} def __init__( self ,A__ = 2_5_0_0_0_2 ,A__ = 7_6_8 ,A__ = 1_2 ,A__ = 1_2 ,A__ = 3_0_7_2 ,A__ = "gelu" ,A__ = 0.1 ,A__ = 0.1 ,A__ = 5_1_4 ,A__ = 0.02 ,A__ = 1 ,A__ = 1E-05 ,A__=None ,A__=False ,A__=0.0 ,**A__ ,): super().__init__(pad_token_id=A__ ,**A__) lowercase = vocab_size lowercase = hidden_size lowercase = num_hidden_layers lowercase = num_attention_heads lowercase = intermediate_size lowercase = hidden_act lowercase = hidden_dropout_prob lowercase = attention_probs_dropout_prob lowercase = max_position_embeddings lowercase = initializer_range lowercase = layer_norm_eps lowercase = classifier_dropout lowercase = is_decoder lowercase = act_dropout
97
from __future__ import annotations import unittest from transformers import is_tf_available from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow if is_tf_available(): import numpy as np import tensorflow as tf from transformers import TFXLMRobertaModel @require_tf @require_sentencepiece @require_tokenizers class lowercase ( unittest.TestCase ): @slow def A__ ( self): lowercase = TFXLMRobertaModel.from_pretrained('''jplu/tf-xlm-roberta-base''') lowercase = { '''input_ids''': tf.convert_to_tensor([[0, 2_6_4_6, 1_0_2_6_9, 8_3, 9_9_9_4_2, 2]] ,dtype=tf.intaa), # "My dog is cute" '''attention_mask''': tf.convert_to_tensor([[1, 1, 1, 1, 1, 1]] ,dtype=tf.intaa), } lowercase = model(A__)['''last_hidden_state'''] lowercase = tf.TensorShape((1, 6, 7_6_8)) self.assertEqual(output.shape ,A__) # compare the actual values for a slice. lowercase = tf.convert_to_tensor( [ [ [0.0681762, 0.10894451, 0.06772504], [-0.06423668, 0.02366615, 0.04329344], [-0.06057295, 0.09974135, -0.00070584], ] ] ,dtype=tf.floataa ,) self.assertTrue(np.allclose(output[:, :3, :3].numpy() ,expected_slice.numpy() ,atol=1E-4))
97
1
import json import os from datetime import date from pathlib import Path from tabulate import DataRow, TableFormat, tabulate lowercase : int = TableFormat( lineabove=None, linebelowheader=None, linebetweenrows=None, linebelow=None, headerrow=DataRow('', '|', '|'), datarow=DataRow('', '|', '|'), padding=1, with_header_hide=None, ) lowercase : Optional[int] = [] lowercase : int = [] lowercase : Any = {'type': 'section', 'text': {'type': 'plain_text', 'text': 'No failed tests! 🤗', 'emoji': True}} lowercase : List[str] = [ { 'type': 'header', 'text': { 'type': 'plain_text', 'text': f"🤗 Accelerate nightly {os.environ.get('TEST_TYPE', '')} test results", 'emoji': True, }, } ] lowercase : Union[str, Any] = 0 for log in Path().glob('*.log'): lowercase : Optional[int] = 0 with open(log, 'r') as f: for line in f: lowercase : Dict = json.loads(line) if line.get('nodeid', '') != "": lowercase : List[str] = line['nodeid'] if line.get('duration', None) is not None: lowercase : List[str] = f"{line['duration']:.4f}" if line.get('outcome', '') == "failed": section_num_failed += 1 failed.append([test, duration, log.name.split('_')[0]]) total_num_failed += 1 group_info.append([str(log), section_num_failed, failed]) lowercase : Union[str, Any] = [] log.unlink() lowercase : Optional[Any] = '' lowercase : Any = [] if total_num_failed > 0: for name, num_failed, failed_tests in group_info: if num_failed > 0: if num_failed == 1: message += f"*{name[1:]}: {num_failed} failed test*\n" else: message += f"*{name[1:]}: {num_failed} failed tests*\n" lowercase : List[str] = [] lowercase : Optional[int] = {} for test in failed_tests: lowercase : Any = test[0].split('::') lowercase : List[str] = data[0].split('/')[-1] if data[0] not in filesafailed: lowercase : Optional[Any] = [data[1:]] else: filesafailed[data[0]] += [data[1:]] failed_table.append(data) lowercase : Tuple = [test[0] for test in failed_table] lowercase : Any = list(set(files)) # Count number of instances in failed_tests lowercase : Union[str, Any] = [] for file in individual_files: table.append([file, len(filesafailed[file])]) lowercase : List[str] = tabulate( table, headers=['Test Location', 'Num Failed'], tablefmt=hf_table_format, stralign='right', ) message += f"\n```\n{failed_table}\n```" all_filesafailed.append(filesafailed) if len(message) > 3000: lowercase : Optional[Any] = 'Too many failed tests, please see the full report in the Action results.' lowercase : List[str] = len(err) + 10 lowercase : Dict = message[: 3000 - offset] + f"\n...\n```\n{err}" print(f"### {message}") else: lowercase : Union[str, Any] = 'No failed tests! 🤗' print(f"## {message}") payload.append(no_error_payload) if os.environ.get('TEST_TYPE', '') != "": from slack_sdk import WebClient lowercase : Union[str, Any] = WebClient(token=os.environ['SLACK_API_TOKEN']) if message != "No failed tests! 🤗": lowercase : Any = { 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': message, }, } payload.append(md_report) lowercase : List[Any] = { 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': '*For more details:*', }, 'accessory': { 'type': 'button', 'text': { 'type': 'plain_text', 'text': 'Check Action results', 'emoji': True, }, 'url': f"https://github.com/{os.environ['GITHUB_REPOSITORY']}/actions/runs/{os.environ['GITHUB_RUN_ID']}", }, } payload.append(action_button) lowercase : Union[str, Any] = { 'type': 'context', 'elements': [ { 'type': 'plain_text', 'text': f"Nightly {os.environ.get('TEST_TYPE')} test results for {date.today()}", } ], } payload.append(date_report) lowercase : int = client.chat_postMessage(channel='#accelerate-ci-daily', text=message, blocks=payload) lowercase : Dict = response.data['ts'] for failed_file in all_filesafailed: for test_location, test_failures in failed_file.items(): # Keep only the first instance of the test name lowercase : Tuple = '' for i, row in enumerate(test_failures): if row[0] != test_class: lowercase : Dict = row[0] else: lowercase : Dict = '' lowercase : Dict = { 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': f"Test location: {test_location}\n```\n{tabulate(test_failures, headers=['Class', 'Test'], tablefmt=hf_table_format, stralign='right')}\n```", }, } client.chat_postMessage( channel='#accelerate-ci-daily', thread_ts=ts, blocks=[payload], )
232
from operator import delitem, getitem, setitem import pytest from data_structures.hashing.hash_map import HashMap def lowercase ( SCREAMING_SNAKE_CASE__ : Optional[int] ) -> int: return getitem, k def lowercase ( SCREAMING_SNAKE_CASE__ : Tuple , SCREAMING_SNAKE_CASE__ : Optional[int] ) -> str: return setitem, k, v def lowercase ( SCREAMING_SNAKE_CASE__ : Tuple ) -> Optional[Any]: return delitem, k def lowercase ( SCREAMING_SNAKE_CASE__ : Dict , SCREAMING_SNAKE_CASE__ : str , *SCREAMING_SNAKE_CASE__ : int ) -> Optional[int]: try: return fun(SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ), None except Exception as e: return None, e a__ = ( _set("""key_a""", """val_a"""), _set("""key_b""", """val_b"""), ) a__ = [ _set("""key_a""", """val_a"""), _set("""key_a""", """val_b"""), ] a__ = [ _set("""key_a""", """val_a"""), _set("""key_b""", """val_b"""), _del("""key_a"""), _del("""key_b"""), _set("""key_a""", """val_a"""), _del("""key_a"""), ] a__ = [ _get("""key_a"""), _del("""key_a"""), _set("""key_a""", """val_a"""), _del("""key_a"""), _del("""key_a"""), _get("""key_a"""), ] a__ = [ *[_set(x, x) for x in range(5)], # guaranteed upsize ] a__ = [ *[_set(x, x) for x in range(5)], # guaranteed upsize *[_del(x) for x in range(5)], _set("""key_a""", """val_b"""), ] @pytest.mark.parametrize( """operations""" , ( pytest.param(_add_items , id="""add items""" ), pytest.param(_overwrite_items , id="""overwrite items""" ), pytest.param(_delete_items , id="""delete items""" ), pytest.param(_access_absent_items , id="""access absent items""" ), pytest.param(_add_with_resize_up , id="""add with resize up""" ), pytest.param(_add_with_resize_down , id="""add with resize down""" ), ) , ) def lowercase ( SCREAMING_SNAKE_CASE__ : str ) -> Tuple: _snake_case : List[Any] = HashMap(initial_block_size=4 ) _snake_case : int = {} for _, (fun, *args) in enumerate(SCREAMING_SNAKE_CASE__ ): _snake_case , _snake_case : Tuple = _run_operation(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ) _snake_case , _snake_case : int = _run_operation(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , *SCREAMING_SNAKE_CASE__ ) assert my_res == py_res assert str(SCREAMING_SNAKE_CASE__ ) == str(SCREAMING_SNAKE_CASE__ ) assert set(SCREAMING_SNAKE_CASE__ ) == set(SCREAMING_SNAKE_CASE__ ) assert len(SCREAMING_SNAKE_CASE__ ) == len(SCREAMING_SNAKE_CASE__ ) assert set(my.items() ) == set(py.items() ) def lowercase ( ) -> Optional[int]: def is_public(SCREAMING_SNAKE_CASE__ : str ) -> bool: return not name.startswith("""_""" ) _snake_case : Tuple = {name for name in dir({} ) if is_public(SCREAMING_SNAKE_CASE__ )} _snake_case : Optional[Any] = {name for name in dir(HashMap() ) if is_public(SCREAMING_SNAKE_CASE__ )} assert dict_public_names > hash_public_names
317
0
class __lowercase : """simple docstring""" def __init__( self , A ) -> None: snake_case : List[Any] = set_counts snake_case : Tuple = max(A ) snake_case : Union[str, Any] = len(A ) snake_case : int = [1] * num_sets snake_case : int = list(range(A ) ) def UpperCAmelCase ( self , A , A ) -> bool: snake_case : List[str] = self.get_parent(A ) snake_case : List[Any] = self.get_parent(A ) if src_parent == dst_parent: return False if self.ranks[dst_parent] >= self.ranks[src_parent]: self.set_counts[dst_parent] += self.set_counts[src_parent] snake_case : List[Any] = 0 snake_case : Union[str, Any] = dst_parent if self.ranks[dst_parent] == self.ranks[src_parent]: self.ranks[dst_parent] += 1 snake_case : Dict = self.set_counts[dst_parent] else: self.set_counts[src_parent] += self.set_counts[dst_parent] snake_case : str = 0 snake_case : str = src_parent snake_case : Any = self.set_counts[src_parent] snake_case : Tuple = max(self.max_set , A ) return True def UpperCAmelCase ( self , A ) -> int: if self.parents[disj_set] == disj_set: return disj_set snake_case : int = self.get_parent(self.parents[disj_set] ) return self.parents[disj_set]
176
import argparse import json import pickle from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import MaskFormerConfig, MaskFormerForInstanceSegmentation, MaskFormerImageProcessor, SwinConfig from transformers.utils import logging logging.set_verbosity_info() lowerCamelCase : List[Any] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE__ ( lowercase ) -> int: snake_case : Dict = SwinConfig.from_pretrained( """microsoft/swin-tiny-patch4-window7-224""" ,out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] ) snake_case : List[str] = MaskFormerConfig(backbone_config=lowercase ) snake_case : List[Any] = """huggingface/label-files""" if "ade20k-full" in model_name: # this should be ok snake_case : Dict = 847 snake_case : List[str] = """maskformer-ade20k-full-id2label.json""" elif "ade" in model_name: # this should be ok snake_case : Union[str, Any] = 150 snake_case : List[Any] = """ade20k-id2label.json""" elif "coco-stuff" in model_name: # this should be ok snake_case : Union[str, Any] = 171 snake_case : int = """maskformer-coco-stuff-id2label.json""" elif "coco" in model_name: # TODO snake_case : Optional[Any] = 133 snake_case : Optional[Any] = """coco-panoptic-id2label.json""" elif "cityscapes" in model_name: # this should be ok snake_case : Tuple = 19 snake_case : int = """cityscapes-id2label.json""" elif "vistas" in model_name: # this should be ok snake_case : int = 65 snake_case : Any = """mapillary-vistas-id2label.json""" snake_case : Optional[Any] = json.load(open(hf_hub_download(lowercase ,lowercase ,repo_type="""dataset""" ) ,"""r""" ) ) snake_case : List[Any] = {int(lowercase ): v for k, v in idalabel.items()} return config def SCREAMING_SNAKE_CASE__ ( lowercase ) -> List[str]: snake_case : Union[str, Any] = [] # stem # fmt: off rename_keys.append(("""backbone.patch_embed.proj.weight""", """model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.weight""") ) rename_keys.append(("""backbone.patch_embed.proj.bias""", """model.pixel_level_module.encoder.model.embeddings.patch_embeddings.projection.bias""") ) rename_keys.append(("""backbone.patch_embed.norm.weight""", """model.pixel_level_module.encoder.model.embeddings.norm.weight""") ) rename_keys.append(("""backbone.patch_embed.norm.bias""", """model.pixel_level_module.encoder.model.embeddings.norm.bias""") ) # stages for i in range(len(config.backbone_config.depths ) ): for j in range(config.backbone_config.depths[i] ): rename_keys.append((f"""backbone.layers.{i}.blocks.{j}.norm1.weight""", f"""model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.weight""") ) rename_keys.append((f"""backbone.layers.{i}.blocks.{j}.norm1.bias""", f"""model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_before.bias""") ) rename_keys.append((f"""backbone.layers.{i}.blocks.{j}.attn.relative_position_bias_table""", f"""model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_bias_table""") ) rename_keys.append((f"""backbone.layers.{i}.blocks.{j}.attn.relative_position_index""", f"""model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.self.relative_position_index""") ) rename_keys.append((f"""backbone.layers.{i}.blocks.{j}.attn.proj.weight""", f"""model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight""") ) rename_keys.append((f"""backbone.layers.{i}.blocks.{j}.attn.proj.bias""", f"""model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias""") ) rename_keys.append((f"""backbone.layers.{i}.blocks.{j}.norm2.weight""", f"""model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.weight""") ) rename_keys.append((f"""backbone.layers.{i}.blocks.{j}.norm2.bias""", f"""model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.layernorm_after.bias""") ) rename_keys.append((f"""backbone.layers.{i}.blocks.{j}.mlp.fc1.weight""", f"""model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight""") ) rename_keys.append((f"""backbone.layers.{i}.blocks.{j}.mlp.fc1.bias""", f"""model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias""") ) rename_keys.append((f"""backbone.layers.{i}.blocks.{j}.mlp.fc2.weight""", f"""model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.weight""") ) rename_keys.append((f"""backbone.layers.{i}.blocks.{j}.mlp.fc2.bias""", f"""model.pixel_level_module.encoder.model.encoder.layers.{i}.blocks.{j}.output.dense.bias""") ) if i < 3: rename_keys.append((f"""backbone.layers.{i}.downsample.reduction.weight""", f"""model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.reduction.weight""") ) rename_keys.append((f"""backbone.layers.{i}.downsample.norm.weight""", f"""model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.weight""") ) rename_keys.append((f"""backbone.layers.{i}.downsample.norm.bias""", f"""model.pixel_level_module.encoder.model.encoder.layers.{i}.downsample.norm.bias""") ) rename_keys.append((f"""backbone.norm{i}.weight""", f"""model.pixel_level_module.encoder.hidden_states_norms.{i}.weight""") ) rename_keys.append((f"""backbone.norm{i}.bias""", f"""model.pixel_level_module.encoder.hidden_states_norms.{i}.bias""") ) # FPN rename_keys.append(("""sem_seg_head.layer_4.weight""", """model.pixel_level_module.decoder.fpn.stem.0.weight""") ) rename_keys.append(("""sem_seg_head.layer_4.norm.weight""", """model.pixel_level_module.decoder.fpn.stem.1.weight""") ) rename_keys.append(("""sem_seg_head.layer_4.norm.bias""", """model.pixel_level_module.decoder.fpn.stem.1.bias""") ) for source_index, target_index in zip(range(3 ,0 ,-1 ) ,range(0 ,3 ) ): rename_keys.append((f"""sem_seg_head.adapter_{source_index}.weight""", f"""model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.0.weight""") ) rename_keys.append((f"""sem_seg_head.adapter_{source_index}.norm.weight""", f"""model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.weight""") ) rename_keys.append((f"""sem_seg_head.adapter_{source_index}.norm.bias""", f"""model.pixel_level_module.decoder.fpn.layers.{target_index}.proj.1.bias""") ) rename_keys.append((f"""sem_seg_head.layer_{source_index}.weight""", f"""model.pixel_level_module.decoder.fpn.layers.{target_index}.block.0.weight""") ) rename_keys.append((f"""sem_seg_head.layer_{source_index}.norm.weight""", f"""model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.weight""") ) rename_keys.append((f"""sem_seg_head.layer_{source_index}.norm.bias""", f"""model.pixel_level_module.decoder.fpn.layers.{target_index}.block.1.bias""") ) rename_keys.append(("""sem_seg_head.mask_features.weight""", """model.pixel_level_module.decoder.mask_projection.weight""") ) rename_keys.append(("""sem_seg_head.mask_features.bias""", """model.pixel_level_module.decoder.mask_projection.bias""") ) # Transformer decoder for idx in range(config.decoder_config.decoder_layers ): # self-attention out projection rename_keys.append((f"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.weight""", f"""model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.weight""") ) rename_keys.append((f"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.out_proj.bias""", f"""model.transformer_module.decoder.layers.{idx}.self_attn.out_proj.bias""") ) # cross-attention out projection rename_keys.append((f"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.weight""", f"""model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.weight""") ) rename_keys.append((f"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.out_proj.bias""", f"""model.transformer_module.decoder.layers.{idx}.encoder_attn.out_proj.bias""") ) # MLP 1 rename_keys.append((f"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.weight""", f"""model.transformer_module.decoder.layers.{idx}.fc1.weight""") ) rename_keys.append((f"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear1.bias""", f"""model.transformer_module.decoder.layers.{idx}.fc1.bias""") ) # MLP 2 rename_keys.append((f"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.weight""", f"""model.transformer_module.decoder.layers.{idx}.fc2.weight""") ) rename_keys.append((f"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.linear2.bias""", f"""model.transformer_module.decoder.layers.{idx}.fc2.bias""") ) # layernorm 1 (self-attention layernorm) rename_keys.append((f"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.weight""", f"""model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.weight""") ) rename_keys.append((f"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm1.bias""", f"""model.transformer_module.decoder.layers.{idx}.self_attn_layer_norm.bias""") ) # layernorm 2 (cross-attention layernorm) rename_keys.append((f"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.weight""", f"""model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.weight""") ) rename_keys.append((f"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm2.bias""", f"""model.transformer_module.decoder.layers.{idx}.encoder_attn_layer_norm.bias""") ) # layernorm 3 (final layernorm) rename_keys.append((f"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.weight""", f"""model.transformer_module.decoder.layers.{idx}.final_layer_norm.weight""") ) rename_keys.append((f"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.norm3.bias""", f"""model.transformer_module.decoder.layers.{idx}.final_layer_norm.bias""") ) rename_keys.append(("""sem_seg_head.predictor.transformer.decoder.norm.weight""", """model.transformer_module.decoder.layernorm.weight""") ) rename_keys.append(("""sem_seg_head.predictor.transformer.decoder.norm.bias""", """model.transformer_module.decoder.layernorm.bias""") ) # heads on top rename_keys.append(("""sem_seg_head.predictor.query_embed.weight""", """model.transformer_module.queries_embedder.weight""") ) rename_keys.append(("""sem_seg_head.predictor.input_proj.weight""", """model.transformer_module.input_projection.weight""") ) rename_keys.append(("""sem_seg_head.predictor.input_proj.bias""", """model.transformer_module.input_projection.bias""") ) rename_keys.append(("""sem_seg_head.predictor.class_embed.weight""", """class_predictor.weight""") ) rename_keys.append(("""sem_seg_head.predictor.class_embed.bias""", """class_predictor.bias""") ) for i in range(3 ): rename_keys.append((f"""sem_seg_head.predictor.mask_embed.layers.{i}.weight""", f"""mask_embedder.{i}.0.weight""") ) rename_keys.append((f"""sem_seg_head.predictor.mask_embed.layers.{i}.bias""", f"""mask_embedder.{i}.0.bias""") ) # fmt: on return rename_keys def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ,lowercase ) -> str: snake_case : Tuple = dct.pop(lowercase ) snake_case : int = val def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ) -> int: snake_case : List[str] = [int(backbone_config.embed_dim * 2**i ) for i in range(len(backbone_config.depths ) )] for i in range(len(backbone_config.depths ) ): snake_case : Optional[Any] = num_features[i] for j in range(backbone_config.depths[i] ): # fmt: off # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias) snake_case : Tuple = state_dict.pop(f"""backbone.layers.{i}.blocks.{j}.attn.qkv.weight""" ) snake_case : Optional[Any] = state_dict.pop(f"""backbone.layers.{i}.blocks.{j}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict snake_case : Optional[Any] = in_proj_weight[:dim, :] snake_case : Optional[int] = in_proj_bias[: dim] snake_case : Union[str, Any] = in_proj_weight[ dim : dim * 2, : ] snake_case : Tuple = in_proj_bias[ dim : dim * 2 ] snake_case : List[Any] = in_proj_weight[ -dim :, : ] snake_case : Any = in_proj_bias[-dim :] # fmt: on def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ) -> Any: # fmt: off snake_case : int = config.decoder_config.hidden_size for idx in range(config.decoder_config.decoder_layers ): # read in weights + bias of self-attention input projection layer (in the original implementation, this is a single matrix + bias) snake_case : Any = state_dict.pop(f"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_weight""" ) snake_case : Tuple = state_dict.pop(f"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.self_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) to the state dict snake_case : Optional[int] = in_proj_weight[: hidden_size, :] snake_case : Any = in_proj_bias[:config.hidden_size] snake_case : Any = in_proj_weight[hidden_size : hidden_size * 2, :] snake_case : int = in_proj_bias[hidden_size : hidden_size * 2] snake_case : Any = in_proj_weight[-hidden_size :, :] snake_case : Union[str, Any] = in_proj_bias[-hidden_size :] # read in weights + bias of cross-attention input projection layer (in the original implementation, this is a single matrix + bias) snake_case : Dict = state_dict.pop(f"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_weight""" ) snake_case : str = state_dict.pop(f"""sem_seg_head.predictor.transformer.decoder.layers.{idx}.multihead_attn.in_proj_bias""" ) # next, add query, keys and values (in that order) to the state dict snake_case : Dict = in_proj_weight[: hidden_size, :] snake_case : Dict = in_proj_bias[:config.hidden_size] snake_case : List[Any] = in_proj_weight[hidden_size : hidden_size * 2, :] snake_case : Optional[Any] = in_proj_bias[hidden_size : hidden_size * 2] snake_case : Tuple = in_proj_weight[-hidden_size :, :] snake_case : str = in_proj_bias[-hidden_size :] # fmt: on def SCREAMING_SNAKE_CASE__ ( ) -> torch.Tensor: snake_case : Any = """http://images.cocodataset.org/val2017/000000039769.jpg""" snake_case : Any = Image.open(requests.get(lowercase ,stream=lowercase ).raw ) return im @torch.no_grad() def SCREAMING_SNAKE_CASE__ ( lowercase ,lowercase ,lowercase ,lowercase = False ) -> Dict: snake_case : List[str] = get_maskformer_config(lowercase ) # load original state_dict with open(lowercase ,"""rb""" ) as f: snake_case : Optional[Any] = pickle.load(lowercase ) snake_case : Optional[Any] = data["""model"""] # for name, param in state_dict.items(): # print(name, param.shape) # rename keys snake_case : str = create_rename_keys(lowercase ) for src, dest in rename_keys: rename_key(lowercase ,lowercase ,lowercase ) read_in_swin_q_k_v(lowercase ,config.backbone_config ) read_in_decoder_q_k_v(lowercase ,lowercase ) # update to torch tensors for key, value in state_dict.items(): snake_case : List[Any] = torch.from_numpy(lowercase ) # load 🤗 model snake_case : int = MaskFormerForInstanceSegmentation(lowercase ) model.eval() for name, param in model.named_parameters(): print(lowercase ,param.shape ) snake_case , snake_case : Optional[int] = model.load_state_dict(lowercase ,strict=lowercase ) assert missing_keys == [ "model.pixel_level_module.encoder.model.layernorm.weight", "model.pixel_level_module.encoder.model.layernorm.bias", ] assert len(lowercase ) == 0, f"""Unexpected keys: {unexpected_keys}""" # verify results snake_case : List[str] = prepare_img() if "vistas" in model_name: snake_case : Optional[int] = 65 elif "cityscapes" in model_name: snake_case : int = 65535 else: snake_case : List[str] = 255 snake_case : List[Any] = True if """ade""" in model_name else False snake_case : Optional[int] = MaskFormerImageProcessor(ignore_index=lowercase ,reduce_labels=lowercase ) snake_case : Tuple = image_processor(lowercase ,return_tensors="""pt""" ) snake_case : str = model(**lowercase ) print("""Logits:""" ,outputs.class_queries_logits[0, :3, :3] ) if model_name == "maskformer-swin-tiny-ade": snake_case : Union[str, Any] = torch.tensor( [[3.6353, -4.4770, -2.6065], [0.5081, -4.2394, -3.5343], [2.1909, -5.0353, -1.9323]] ) assert torch.allclose(outputs.class_queries_logits[0, :3, :3] ,lowercase ,atol=1E-4 ) print("""Looks ok!""" ) if pytorch_dump_folder_path is not None: print(f"""Saving model and image processor to {pytorch_dump_folder_path}""" ) Path(lowercase ).mkdir(exist_ok=lowercase ) model.save_pretrained(lowercase ) image_processor.save_pretrained(lowercase ) if push_to_hub: print("""Pushing model and image processor to the hub...""" ) model.push_to_hub(f"""nielsr/{model_name}""" ) image_processor.push_to_hub(f"""nielsr/{model_name}""" ) if __name__ == "__main__": lowerCamelCase : Optional[Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='maskformer-swin-tiny-ade', type=str, help=('Name of the MaskFormer model you\'d like to convert',), ) parser.add_argument( '--checkpoint_path', default='/Users/nielsrogge/Documents/MaskFormer_checkpoints/MaskFormer-Swin-tiny-ADE20k/model.pkl', type=str, help='Path to the original state dict (.pth file).', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.' ) lowerCamelCase : List[str] = parser.parse_args() convert_maskformer_checkpoint( args.model_name, args.checkpoint_path, args.pytorch_dump_folder_path, args.push_to_hub )
176
1
import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() a_ = logging.get_logger(__name__) a_ = 'https://openaipublic.azureedge.net/jukebox/models/' a_ = { 'jukebox-1b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '1b_lyrics/prior_level_2.pth.tar', ], 'jukebox-5b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '5b_lyrics/prior_level_2.pth.tar', ], } def lowerCamelCase__ ( _a): if key.endswith(".model.1.bias") and len(key.split(".")) > 10: SCREAMING_SNAKE_CASE : Any = key.replace(".model.1.bias" , ".conv1d_1.bias") elif key.endswith(".model.1.weight") and len(key.split(".")) > 10: SCREAMING_SNAKE_CASE : Optional[Any] = key.replace(".model.1.weight" , ".conv1d_1.weight") elif key.endswith(".model.3.bias") and len(key.split(".")) > 10: SCREAMING_SNAKE_CASE : Union[str, Any] = key.replace(".model.3.bias" , ".conv1d_2.bias") elif key.endswith(".model.3.weight") and len(key.split(".")) > 10: SCREAMING_SNAKE_CASE : int = key.replace(".model.3.weight" , ".conv1d_2.weight") if "conditioner_blocks.0." in key: SCREAMING_SNAKE_CASE : List[str] = key.replace("conditioner_blocks.0" , "conditioner_blocks") if "prime_prior" in key: SCREAMING_SNAKE_CASE : Optional[Any] = key.replace("prime_prior" , "encoder") if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: SCREAMING_SNAKE_CASE : Union[str, Any] = key.replace(".emb." , ".") if key.endswith("k"): # replace vqvae.X.k with vqvae.X.codebook return key.replace(".k" , ".codebook") if "y_emb." in key: return key.replace("y_emb." , "metadata_embedding.") if "x_emb.emb." in key: SCREAMING_SNAKE_CASE : Dict = key.replace("0.x_emb.emb" , "embed_tokens") if "prime_state_ln" in key: return key.replace("prime_state_ln" , "encoder.final_layer_norm") if ".ln" in key: return key.replace(".ln" , ".layer_norm") if "_ln" in key: return key.replace("_ln" , "_layer_norm") if "prime_state_proj" in key: return key.replace("prime_state_proj" , "encoder.proj_in") if "prime_x_out" in key: return key.replace("prime_x_out" , "encoder.lm_head") if "prior.x_out" in key: return key.replace("x_out" , "fc_proj_out") if "x_emb" in key: return key.replace("x_emb" , "embed_tokens") return key def lowerCamelCase__ ( _a , _a , _a , _a): SCREAMING_SNAKE_CASE : Tuple = {} import re SCREAMING_SNAKE_CASE : Optional[int] = re.compile(r"encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)") SCREAMING_SNAKE_CASE : Any = re.compile( r"encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)") SCREAMING_SNAKE_CASE : List[str] = re.compile(r"encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)") SCREAMING_SNAKE_CASE : int = re.compile(r"decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)") SCREAMING_SNAKE_CASE : Dict = re.compile( r"decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)") SCREAMING_SNAKE_CASE : Optional[int] = re.compile(r"decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)") SCREAMING_SNAKE_CASE : Dict = re.compile(r"conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)") SCREAMING_SNAKE_CASE : List[Any] = re.compile( r"conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)") SCREAMING_SNAKE_CASE : Optional[Any] = re.compile(r"conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)") for original_key, value in state_dict.items(): # rename vqvae.encoder keys if re_encoder_block_conv_in.fullmatch(_a): SCREAMING_SNAKE_CASE : str = re_encoder_block_conv_in.match(_a) SCREAMING_SNAKE_CASE : List[Any] = regex_match.groups() SCREAMING_SNAKE_CASE : List[str] = int(groups[2]) * 2 + int(groups[3]) SCREAMING_SNAKE_CASE : Any = f"encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}" SCREAMING_SNAKE_CASE : int = re_encoder_block_conv_in.sub(_a , _a) elif re_encoder_block_resnet.fullmatch(_a): SCREAMING_SNAKE_CASE : Optional[int] = re_encoder_block_resnet.match(_a) SCREAMING_SNAKE_CASE : Dict = regex_match.groups() SCREAMING_SNAKE_CASE : List[Any] = int(groups[2]) * 2 + int(groups[3]) SCREAMING_SNAKE_CASE : Optional[Any] = {"1": 1, "3": 2}[groups[-2]] SCREAMING_SNAKE_CASE : List[Any] = f"encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}." SCREAMING_SNAKE_CASE : Optional[Any] = f"resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}" SCREAMING_SNAKE_CASE : Dict = prefix + resnet_block SCREAMING_SNAKE_CASE : Tuple = re_encoder_block_resnet.sub(_a , _a) elif re_encoder_block_proj_out.fullmatch(_a): SCREAMING_SNAKE_CASE : Optional[Any] = re_encoder_block_proj_out.match(_a) SCREAMING_SNAKE_CASE : List[str] = regex_match.groups() SCREAMING_SNAKE_CASE : Union[str, Any] = f"encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}" SCREAMING_SNAKE_CASE : Optional[int] = re_encoder_block_proj_out.sub(_a , _a) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(_a): SCREAMING_SNAKE_CASE : Optional[Any] = re_decoder_block_conv_out.match(_a) SCREAMING_SNAKE_CASE : Any = regex_match.groups() SCREAMING_SNAKE_CASE : List[Any] = int(groups[2]) * 2 + int(groups[3]) - 2 SCREAMING_SNAKE_CASE : str = f"decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}" SCREAMING_SNAKE_CASE : int = re_decoder_block_conv_out.sub(_a , _a) elif re_decoder_block_resnet.fullmatch(_a): SCREAMING_SNAKE_CASE : int = re_decoder_block_resnet.match(_a) SCREAMING_SNAKE_CASE : str = regex_match.groups() SCREAMING_SNAKE_CASE : List[str] = int(groups[2]) * 2 + int(groups[3]) - 2 SCREAMING_SNAKE_CASE : List[Any] = {"1": 1, "3": 2}[groups[-2]] SCREAMING_SNAKE_CASE : Tuple = f"decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}." SCREAMING_SNAKE_CASE : str = f"resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}" SCREAMING_SNAKE_CASE : Union[str, Any] = prefix + resnet_block SCREAMING_SNAKE_CASE : Optional[Any] = re_decoder_block_resnet.sub(_a , _a) elif re_decoder_block_proj_in.fullmatch(_a): SCREAMING_SNAKE_CASE : List[str] = re_decoder_block_proj_in.match(_a) SCREAMING_SNAKE_CASE : Any = regex_match.groups() SCREAMING_SNAKE_CASE : List[str] = f"decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}" SCREAMING_SNAKE_CASE : Union[str, Any] = re_decoder_block_proj_in.sub(_a , _a) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(_a): SCREAMING_SNAKE_CASE : Optional[int] = re_prior_cond_conv_out.match(_a) SCREAMING_SNAKE_CASE : int = regex_match.groups() SCREAMING_SNAKE_CASE : Optional[int] = int(groups[1]) * 2 + int(groups[2]) - 2 SCREAMING_SNAKE_CASE : Optional[Any] = f"conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}" SCREAMING_SNAKE_CASE : Any = re_prior_cond_conv_out.sub(_a , _a) elif re_prior_cond_resnet.fullmatch(_a): SCREAMING_SNAKE_CASE : List[Any] = re_prior_cond_resnet.match(_a) SCREAMING_SNAKE_CASE : int = regex_match.groups() SCREAMING_SNAKE_CASE : Tuple = int(groups[1]) * 2 + int(groups[2]) - 2 SCREAMING_SNAKE_CASE : Dict = {"1": 1, "3": 2}[groups[-2]] SCREAMING_SNAKE_CASE : Tuple = f"conditioner_blocks.upsampler.upsample_block.{block_index}." SCREAMING_SNAKE_CASE : Any = f"resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}" SCREAMING_SNAKE_CASE : Optional[Any] = prefix + resnet_block SCREAMING_SNAKE_CASE : List[Any] = re_prior_cond_resnet.sub(_a , _a) elif re_prior_cond_proj_in.fullmatch(_a): SCREAMING_SNAKE_CASE : Optional[int] = re_prior_cond_proj_in.match(_a) SCREAMING_SNAKE_CASE : Optional[int] = regex_match.groups() SCREAMING_SNAKE_CASE : Any = f"conditioner_blocks.upsampler.proj_in.{groups[-1]}" SCREAMING_SNAKE_CASE : Dict = re_prior_cond_proj_in.sub(_a , _a) # keep original key else: SCREAMING_SNAKE_CASE : List[Any] = original_key SCREAMING_SNAKE_CASE : Optional[int] = replace_key(_a) if f"{key_prefix}.{key}" not in model_state_dict or key is None: print(f"failed converting {original_key} to {key}, does not match") # handle missmatched shape elif value.shape != model_state_dict[f"{key_prefix}.{key}"].shape: SCREAMING_SNAKE_CASE : Tuple = model_state_dict[f"{key_prefix}.{key}"] print(f"{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match") SCREAMING_SNAKE_CASE : List[Any] = original_key SCREAMING_SNAKE_CASE : str = original_key SCREAMING_SNAKE_CASE : List[str] = value return new_dict @torch.no_grad() def lowerCamelCase__ ( _a=None , _a=None): for file in MODEL_MAPPING[model_name]: if not os.path.isfile(f"{pytorch_dump_folder_path}/{file.split('/')[-1]}"): SCREAMING_SNAKE_CASE : List[Any] = requests.get(f"{PREFIX}{file}" , allow_redirects=_a) os.makedirs(f"{pytorch_dump_folder_path}/" , exist_ok=_a) open(f"{pytorch_dump_folder_path}/{file.split('/')[-1]}" , "wb").write(r.content) SCREAMING_SNAKE_CASE : Tuple = MODEL_MAPPING[model_name.split("/")[-1]] SCREAMING_SNAKE_CASE : Union[str, Any] = JukeboxConfig.from_pretrained(_a) SCREAMING_SNAKE_CASE : Any = JukeboxModel(_a) SCREAMING_SNAKE_CASE : Tuple = [] SCREAMING_SNAKE_CASE : Tuple = {} for i, dict_name in enumerate(_a): SCREAMING_SNAKE_CASE : Union[str, Any] = torch.load(f"{pytorch_dump_folder_path}/{dict_name.split('/')[-1]}")["model"] SCREAMING_SNAKE_CASE : str = {} for k in old_dic.keys(): if k.endswith(".b"): SCREAMING_SNAKE_CASE : List[str] = old_dic[k] elif k.endswith(".w"): SCREAMING_SNAKE_CASE : Optional[Any] = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: SCREAMING_SNAKE_CASE : List[Any] = old_dic[k] else: SCREAMING_SNAKE_CASE : Union[str, Any] = old_dic[k] SCREAMING_SNAKE_CASE : Tuple = "vqvae" if i == 0 else f"priors.{3 - i}" SCREAMING_SNAKE_CASE : int = fix_jukebox_keys(_a , model.state_dict() , _a , _a) weight_dict.append(_a) SCREAMING_SNAKE_CASE : Tuple = weight_dict.pop(0) model.vqvae.load_state_dict(_a) for i in range(len(_a)): model.priors[i].load_state_dict(weight_dict[2 - i]) Path(_a).mkdir(exist_ok=_a) with open(f"{pytorch_dump_folder_path}/mapping.json" , "w") as txtfile: json.dump(_a , _a) print(f"Saving model {model_name} to {pytorch_dump_folder_path}") model.save_pretrained(_a) return weight_dict if __name__ == "__main__": a_ = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='jukebox-5b-lyrics', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='jukebox-5b-lyrics-converted', type=str, help='Path to the output PyTorch model directory.', ) a_ = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
76
import math class _UpperCamelCase : def __init__( self :Union[str, Any] , lowerCamelCase :Union[str, Any]=0 ) -> Tuple: # a graph with Node 0,1,...,N-1 UpperCAmelCase__ = n UpperCAmelCase__ = [ [math.inf for j in range(0 , lowerCamelCase )] for i in range(0 , lowerCamelCase ) ] # adjacency matrix for weight UpperCAmelCase__ = [ [math.inf for j in range(0 , lowerCamelCase )] for i in range(0 , lowerCamelCase ) ] # dp[i][j] stores minimum distance from i to j def UpperCAmelCase_ ( self :Tuple , lowerCamelCase :List[Any] , lowerCamelCase :Optional[Any] , lowerCamelCase :int ) -> List[Any]: UpperCAmelCase__ = w def UpperCAmelCase_ ( self :Optional[int] ) -> Optional[Any]: for k in range(0 , self.n ): for i in range(0 , self.n ): for j in range(0 , self.n ): UpperCAmelCase__ = min(self.dp[i][j] , self.dp[i][k] + self.dp[k][j] ) def UpperCAmelCase_ ( self :int , lowerCamelCase :List[Any] , lowerCamelCase :Dict ) -> List[str]: return self.dp[u][v] if __name__ == "__main__": _lowerCAmelCase : Optional[int] = Graph(5) graph.add_edge(0, 2, 9) graph.add_edge(0, 4, 1_0) graph.add_edge(1, 3, 5) graph.add_edge(2, 3, 7) graph.add_edge(3, 0, 1_0) graph.add_edge(3, 1, 2) graph.add_edge(3, 2, 1) graph.add_edge(3, 4, 6) graph.add_edge(4, 1, 3) graph.add_edge(4, 2, 4) graph.add_edge(4, 3, 9) graph.floyd_warshall() graph.show_min(1, 4) graph.show_min(0, 3)
169
0
"""simple docstring""" from random import randint from tempfile import TemporaryFile import numpy as np def snake_case (A_ :str , A_ :List[str] , A_ :List[Any] ): '''simple docstring''' a : Tuple = 0 if start < end: a : Optional[Any] = randint(A_ , A_ ) a : Optional[Any] = a[end] a : Union[str, Any] = a[pivot] a : str = temp a, a : str = _in_place_partition(A_ , A_ , A_ ) count += _in_place_quick_sort(A_ , A_ , p - 1 ) count += _in_place_quick_sort(A_ , p + 1 , A_ ) return count def snake_case (A_ :List[str] , A_ :Optional[int] , A_ :List[str] ): '''simple docstring''' a : Union[str, Any] = 0 a : Optional[Any] = randint(A_ , A_ ) a : Optional[int] = a[end] a : Dict = a[pivot] a : Dict = temp a : Dict = start - 1 for index in range(A_ , A_ ): count += 1 if a[index] < a[end]: # check if current val is less than pivot value a : Optional[Any] = new_pivot_index + 1 a : int = a[new_pivot_index] a : List[str] = a[index] a : Union[str, Any] = temp a : Optional[int] = a[new_pivot_index + 1] a : int = a[end] a : Optional[Any] = temp return new_pivot_index + 1, count _UpperCamelCase : Any = TemporaryFile() _UpperCamelCase : Optional[int] = 100 # 1000 elements are to be sorted _UpperCamelCase , _UpperCamelCase : int = 0, 1 # mean and standard deviation _UpperCamelCase : str = np.random.normal(mu, sigma, p) np.save(outfile, X) print('The array is') print(X) outfile.seek(0) # using the same array _UpperCamelCase : Dict = np.load(outfile) _UpperCamelCase : str = len(M) - 1 _UpperCamelCase : List[str] = _in_place_quick_sort(M, 0, r) print( 'No of Comparisons for 100 elements selected from a standard normal distribution' 'is :' ) print(z)
186
"""simple docstring""" import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin _UpperCamelCase : List[str] = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class snake_case ( UpperCAmelCase , unittest.TestCase ): __magic_name__ = XLNetTokenizer __magic_name__ = XLNetTokenizerFast __magic_name__ = True __magic_name__ = True def lowerCamelCase__ ( self : List[Any] ): '''simple docstring''' super().setUp() # We have a SentencePiece fixture for testing a : Tuple = XLNetTokenizer(A , keep_accents=A ) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname ) def lowerCamelCase__ ( self : Optional[int] ): '''simple docstring''' a : Optional[int] = '<s>' a : int = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(A ) , A ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(A ) , A ) def lowerCamelCase__ ( self : Tuple ): '''simple docstring''' a : str = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<unk>' ) self.assertEqual(vocab_keys[1] , '<s>' ) self.assertEqual(vocab_keys[-1] , '<eod>' ) self.assertEqual(len(A ) , 1_0_0_6 ) def lowerCamelCase__ ( self : Any ): '''simple docstring''' self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_0 ) def lowerCamelCase__ ( self : Optional[int] ): '''simple docstring''' a : Optional[Any] = XLNetTokenizer(A , keep_accents=A ) a : List[str] = tokenizer.tokenize('This is a test' ) self.assertListEqual(A , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(A ) , [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2] ) a : List[str] = 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', 'é', '.', ] , ) a : Union[str, Any] = tokenizer.convert_tokens_to_ids(A ) self.assertListEqual(A , [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 0, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 0, 4] ) a : Tuple = 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 lowerCamelCase__ ( self : Union[str, Any] ): '''simple docstring''' a : Optional[int] = XLNetTokenizer(A , do_lower_case=A ) a : Any = 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', 'se', '.', ] , ) self.assertListEqual(tokenizer.tokenize('H\u00E9llo' ) , ['▁he', 'll', 'o'] ) def lowerCamelCase__ ( self : int ): '''simple docstring''' a : str = XLNetTokenizer(A , do_lower_case=A ) a : List[Any] = 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', 'se', '.', ] , ) @slow def lowerCamelCase__ ( self : Optional[int] ): '''simple docstring''' a : Dict = XLNetTokenizer.from_pretrained('xlnet-base-cased' ) a : int = tokenizer.encode('sequence builders' , add_special_tokens=A ) a : List[Any] = tokenizer.encode('multi-sequence build' , add_special_tokens=A ) a : Optional[int] = tokenizer.build_inputs_with_special_tokens(A ) a : Optional[Any] = tokenizer.build_inputs_with_special_tokens(A , A ) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def lowerCamelCase__ ( self : Any ): '''simple docstring''' a : Union[str, Any] = {'input_ids': [[1_7, 2_1_4_4_2, 2_7_0, 1_7, 1_0, 1_4_6_4_5, 3_1_8, 3_4, 1_7, 4_5_4_6, 3_1_4_5, 7_8_7, 1_3, 7_7_5_2, 2_2_0_1_8, 2_3, 2_1, 1_7, 4_5_4_6, 3_1_4_5, 7_8_7, 1_3, 3_3_5_2, 1_4_4_3_1, 1_3, 5_5_0_0, 1_1, 1_1_7_6, 5_8_0, 1_3, 1_6_8_1_9, 4_7_9_7, 2_3, 1_7, 1_0, 1_7_1_3_5, 6_5_8, 1_9, 4_5_7, 7_9_3_2, 1_3, 1_8_4, 1_9, 3_1_5_4, 1_7_1_3_5, 6_4_6_8, 1_9, 1_4_0_4, 1_2_2_6_9, 1_9, 4_2_2_9, 5_3_5_6, 1_6_2_6_4, 4_6, 1_9, 1_7, 2_0_5_4_5, 1_0_3_9_5, 9, 9, 9, 1_1, 2_8, 6_4_2_1, 9_5_3_1, 2_0_7_2_9, 1_7, 1_0, 3_5_3, 1_7_0_2_2, 1_1, 2_1, 6_4_2_1, 9_5_3_1, 1_6_9_4_9, 1_7, 1_0, 1_1_5_0_9, 7_5_3, 1_1, 3_3, 9_5, 2_4_2_1, 7_3_8_5, 9_5_6, 1_4_4_3_1, 2_6_2_6, 2_5, 8_4_2, 7_3_8_5, 4_8_3_6, 2_1, 1_4_2_9, 2_2_7_2, 9_8_5_5, 3_1_2_0, 1_6_1, 2_4_7_3_8, 1_9, 1_3_2_0_3, 6_5_8, 2_1_8, 7_8_7, 2_1, 4_3_0, 1_8_4_8_2, 8_4_7, 2_6_3_7, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 3_2_2, 2_2_1_7_8, 2_7, 1_0_6_4, 2_2, 9_5_6, 1_3, 1_1_1_0_1, 1_4_2_9, 5_8_5_4, 2_4_3_1_3, 1_8_9_5_3, 4_0, 4_2_2, 2_4_3_6_6, 6_8, 1_7_5_8, 3_7, 1_0_4_8_3, 1_4_2_5_7, 3_1, 2_0_7, 2_6_3, 2_1, 2_0_3, 3_7_7_3, 2_5, 7_1, 9_7_3_5, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 3_2, 2_0_4_9, 3_4_4_2, 1_7, 1_3_8_9_4, 3_3_8_0, 2_3, 9_5, 1_8, 1_7_6_3_4, 2_2_8_8, 9, 4, 3]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=A , model_name='xlnet-base-cased' , revision='c841166438c31ec7ca9a106dee7bb312b73ae511' , )
186
1
'''simple docstring''' from math import ceil, sqrt def lowerCAmelCase_ ( _lowerCamelCase: int = 1_00_00_00 ): __SCREAMING_SNAKE_CASE : Union[str, Any] = 0 for outer_width in range(3 , (limit // 4) + 2 ): if outer_width**2 > limit: __SCREAMING_SNAKE_CASE : Union[str, Any] = max(ceil(sqrt(outer_width**2 - limit ) ) , 1 ) else: __SCREAMING_SNAKE_CASE : Union[str, Any] = 1 if (outer_width - hole_width_lower_bound) % 2: hole_width_lower_bound += 1 answer += (outer_width - hole_width_lower_bound - 2) // 2 + 1 return answer if __name__ == "__main__": print(f"{solution() = }")
112
'''simple docstring''' from collections.abc import Iterable from typing import Any class _UpperCamelCase : '''simple docstring''' def __init__( self : Optional[int] , lowerCAmelCase__ : int | None = None ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = value __SCREAMING_SNAKE_CASE : Node | None = None # Added in order to delete a node easier __SCREAMING_SNAKE_CASE : Node | None = None __SCREAMING_SNAKE_CASE : Node | None = None def __repr__( self : Optional[Any] ): """simple docstring""" from pprint import pformat if self.left is None and self.right is None: return str(self.value ) return pformat({F"{self.value}": (self.left, self.right)} , indent=1 ) class _UpperCamelCase : '''simple docstring''' def __init__( self : Optional[int] , lowerCAmelCase__ : Node | None = None ): """simple docstring""" __SCREAMING_SNAKE_CASE : str = root def __str__( self : Union[str, Any] ): """simple docstring""" return str(self.root ) def UpperCamelCase__ ( self : Dict , lowerCAmelCase__ : Node , lowerCAmelCase__ : Node | None ): """simple docstring""" if new_children is not None: # reset its kids __SCREAMING_SNAKE_CASE : List[str] = node.parent if node.parent is not None: # reset its parent if self.is_right(lowerCAmelCase__ ): # If it is the right children __SCREAMING_SNAKE_CASE : Any = new_children else: __SCREAMING_SNAKE_CASE : int = new_children else: __SCREAMING_SNAKE_CASE : int = new_children def UpperCamelCase__ ( self : str , lowerCAmelCase__ : Node ): """simple docstring""" if node.parent and node.parent.right: return node == node.parent.right return False def UpperCamelCase__ ( self : List[Any] ): """simple docstring""" return self.root is None def UpperCamelCase__ ( self : Optional[Any] , lowerCAmelCase__ : str ): """simple docstring""" __SCREAMING_SNAKE_CASE : Union[str, Any] = Node(lowerCAmelCase__ ) # create a new Node if self.empty(): # if Tree is empty __SCREAMING_SNAKE_CASE : Optional[int] = new_node # set its root else: # Tree is not empty __SCREAMING_SNAKE_CASE : Optional[int] = self.root # from root if parent_node is None: return while True: # While we don't get to a leaf if value < parent_node.value: # We go left if parent_node.left is None: __SCREAMING_SNAKE_CASE : List[str] = new_node # We insert the new node in a leaf break else: __SCREAMING_SNAKE_CASE : Any = parent_node.left else: if parent_node.right is None: __SCREAMING_SNAKE_CASE : Tuple = new_node break else: __SCREAMING_SNAKE_CASE : List[str] = parent_node.right __SCREAMING_SNAKE_CASE : Tuple = parent_node def UpperCamelCase__ ( self : str , *lowerCAmelCase__ : List[Any] ): """simple docstring""" for value in values: self.__insert(lowerCAmelCase__ ) def UpperCamelCase__ ( self : List[str] , lowerCAmelCase__ : Union[str, Any] ): """simple docstring""" if self.empty(): raise IndexError("""Warning: Tree is empty! please use another.""" ) else: __SCREAMING_SNAKE_CASE : List[Any] = self.root # use lazy evaluation here to avoid NoneType Attribute error while node is not None and node.value is not value: __SCREAMING_SNAKE_CASE : Any = node.left if value < node.value else node.right return node def UpperCamelCase__ ( self : List[Any] , lowerCAmelCase__ : Node | None = None ): """simple docstring""" if node is None: if self.root is None: return None __SCREAMING_SNAKE_CASE : Optional[Any] = self.root if not self.empty(): while node.right is not None: __SCREAMING_SNAKE_CASE : Tuple = node.right return node def UpperCamelCase__ ( self : Dict , lowerCAmelCase__ : Node | None = None ): """simple docstring""" if node is None: __SCREAMING_SNAKE_CASE : Union[str, Any] = self.root if self.root is None: return None if not self.empty(): __SCREAMING_SNAKE_CASE : Optional[Any] = self.root while node.left is not None: __SCREAMING_SNAKE_CASE : Any = node.left return node def UpperCamelCase__ ( self : str , lowerCAmelCase__ : int ): """simple docstring""" __SCREAMING_SNAKE_CASE : List[str] = self.search(lowerCAmelCase__ ) # Look for the node with that label if node is not None: if node.left is None and node.right is None: # If it has no children self.__reassign_nodes(lowerCAmelCase__ , lowerCAmelCase__ ) elif node.left is None: # Has only right children self.__reassign_nodes(lowerCAmelCase__ , node.right ) elif node.right is None: # Has only left children self.__reassign_nodes(lowerCAmelCase__ , node.left ) else: __SCREAMING_SNAKE_CASE : Tuple = self.get_max( node.left ) # Gets the max value of the left branch self.remove(tmp_node.value ) # type: ignore __SCREAMING_SNAKE_CASE : Optional[Any] = ( tmp_node.value # type: ignore ) # Assigns the value to the node to delete and keep tree structure def UpperCamelCase__ ( self : Tuple , lowerCAmelCase__ : Node | None ): """simple docstring""" if node is not None: yield node # Preorder Traversal yield from self.preorder_traverse(node.left ) yield from self.preorder_traverse(node.right ) def UpperCamelCase__ ( self : Optional[int] , lowerCAmelCase__ : Optional[Any]=None ): """simple docstring""" if traversal_function is None: return self.preorder_traverse(self.root ) else: return traversal_function(self.root ) def UpperCamelCase__ ( self : str , lowerCAmelCase__ : list , lowerCAmelCase__ : Node | None ): """simple docstring""" if node: self.inorder(lowerCAmelCase__ , node.left ) arr.append(node.value ) self.inorder(lowerCAmelCase__ , node.right ) def UpperCamelCase__ ( self : int , lowerCAmelCase__ : int , lowerCAmelCase__ : Node ): """simple docstring""" __SCREAMING_SNAKE_CASE : list[int] = [] self.inorder(lowerCAmelCase__ , lowerCAmelCase__ ) # append all values to list using inorder traversal return arr[k - 1] def lowerCAmelCase_ ( _lowerCamelCase: Node | None ): __SCREAMING_SNAKE_CASE : Optional[Any] = [] if curr_node is not None: __SCREAMING_SNAKE_CASE : Optional[int] = postorder(curr_node.left ) + postorder(curr_node.right ) + [curr_node] return node_list def lowerCAmelCase_ ( ): __SCREAMING_SNAKE_CASE : str = (8, 3, 6, 1, 10, 14, 13, 4, 7) __SCREAMING_SNAKE_CASE : Dict = BinarySearchTree() for i in testlist: t.insert(_lowerCamelCase ) # Prints all the elements of the list in order traversal print(_lowerCamelCase ) if t.search(6 ) is not None: print("""The value 6 exists""" ) else: print("""The value 6 doesn't exist""" ) if t.search(-1 ) is not None: print("""The value -1 exists""" ) else: print("""The value -1 doesn't exist""" ) if not t.empty(): print("""Max Value: """ , t.get_max().value ) # type: ignore print("""Min Value: """ , t.get_min().value ) # type: ignore for i in testlist: t.remove(_lowerCamelCase ) print(_lowerCamelCase ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
112
1
'''simple docstring''' import unittest from transformers import SPIECE_UNDERLINE, XLNetTokenizer, XLNetTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin _lowercase : Dict = get_tests_dir("""fixtures/test_sentencepiece.model""") @require_sentencepiece @require_tokenizers class UpperCamelCase__( lowerCAmelCase , unittest.TestCase ): __magic_name__ : Tuple = XLNetTokenizer __magic_name__ : Any = XLNetTokenizerFast __magic_name__ : Optional[int] = True __magic_name__ : Union[str, Any] = True def a__( self : List[Any] )-> List[Any]: """simple docstring""" super().setUp() # We have a SentencePiece fixture for testing UpperCAmelCase = XLNetTokenizer(lowerCAmelCase , keep_accents=lowerCAmelCase ) tokenizer.sanitize_special_tokens() tokenizer.save_pretrained(self.tmpdirname ) def a__( self : List[str] )-> Optional[Any]: """simple docstring""" UpperCAmelCase = '''<s>''' UpperCAmelCase = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowerCAmelCase ) , lowerCAmelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowerCAmelCase ) , lowerCAmelCase ) def a__( self : Optional[int] )-> Union[str, Any]: """simple docstring""" UpperCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<unk>''' ) self.assertEqual(vocab_keys[1] , '''<s>''' ) self.assertEqual(vocab_keys[-1] , '''<eod>''' ) self.assertEqual(len(lowerCAmelCase ) , 1006 ) def a__( self : int )-> str: """simple docstring""" self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def a__( self : int )-> Tuple: """simple docstring""" UpperCAmelCase = XLNetTokenizer(lowerCAmelCase , keep_accents=lowerCAmelCase ) UpperCAmelCase = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(lowerCAmelCase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(lowerCAmelCase ) , [285, 46, 10, 170, 382] ) UpperCAmelCase = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( lowerCAmelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) UpperCAmelCase = tokenizer.convert_tokens_to_ids(lowerCAmelCase ) self.assertListEqual(lowerCAmelCase , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] ) UpperCAmelCase = tokenizer.convert_ids_to_tokens(lowerCAmelCase ) self.assertListEqual( lowerCAmelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) def a__( self : Optional[Any] )-> Optional[int]: """simple docstring""" UpperCAmelCase = XLNetTokenizer(lowerCAmelCase , do_lower_case=lowerCAmelCase ) UpperCAmelCase = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( lowerCAmelCase , [ SPIECE_UNDERLINE + '''''', '''i''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''se''', '''.''', ] , ) self.assertListEqual(tokenizer.tokenize('''H\u00E9llo''' ) , ['''▁he''', '''ll''', '''o'''] ) def a__( self : Any )-> Dict: """simple docstring""" UpperCAmelCase = XLNetTokenizer(lowerCAmelCase , do_lower_case=lowerCAmelCase ) UpperCAmelCase = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( lowerCAmelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''se''', '''.''', ] , ) @slow def a__( self : Optional[Any] )-> str: """simple docstring""" UpperCAmelCase = XLNetTokenizer.from_pretrained('''xlnet-base-cased''' ) UpperCAmelCase = tokenizer.encode('''sequence builders''' , add_special_tokens=lowerCAmelCase ) UpperCAmelCase = tokenizer.encode('''multi-sequence build''' , add_special_tokens=lowerCAmelCase ) UpperCAmelCase = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase ) UpperCAmelCase = tokenizer.build_inputs_with_special_tokens(lowerCAmelCase , lowerCAmelCase ) assert encoded_sentence == text + [4, 3] assert encoded_pair == text + [4] + text_a + [4, 3] @slow def a__( self : List[str] )-> Tuple: """simple docstring""" UpperCAmelCase = {'''input_ids''': [[17, 21442, 270, 17, 10, 14645, 318, 34, 17, 4546, 3145, 787, 13, 7752, 22018, 23, 21, 17, 4546, 3145, 787, 13, 3352, 14431, 13, 5500, 11, 1176, 580, 13, 16819, 4797, 23, 17, 10, 17135, 658, 19, 457, 7932, 13, 184, 19, 3154, 17135, 6468, 19, 1404, 12269, 19, 4229, 5356, 16264, 46, 19, 17, 20545, 10395, 9, 9, 9, 11, 28, 6421, 9531, 20729, 17, 10, 353, 17022, 11, 21, 6421, 9531, 16949, 17, 10, 11509, 753, 11, 33, 95, 2421, 7385, 956, 14431, 2626, 25, 842, 7385, 4836, 21, 1429, 2272, 9855, 3120, 161, 24738, 19, 13203, 658, 218, 787, 21, 430, 18482, 847, 2637, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 322, 22178, 27, 1064, 22, 956, 13, 11101, 1429, 5854, 24313, 18953, 40, 422, 24366, 68, 1758, 37, 10483, 14257, 31, 207, 263, 21, 203, 3773, 25, 71, 9735, 9, 4, 3], [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 32, 2049, 3442, 17, 13894, 3380, 23, 95, 18, 17634, 2288, 9, 4, 3]], '''token_type_ids''': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowerCAmelCase , model_name='''xlnet-base-cased''' , revision='''c841166438c31ec7ca9a106dee7bb312b73ae511''' , )
364
'''simple docstring''' import numpy as np from cva import COLOR_BGR2GRAY, CV_8UC3, cvtColor, filteraD, imread, imshow, waitKey def lowerCamelCase__ ( A : int , A : int , A : int , A : int , A : int , A : int ): '''simple docstring''' if (ksize % 2) == 0: UpperCAmelCase = ksize + 1 UpperCAmelCase = np.zeros((ksize, ksize) , dtype=np.floataa ) # each value for y in range(A ): for x in range(A ): # distance from center UpperCAmelCase = x - ksize // 2 UpperCAmelCase = y - ksize // 2 # degree to radiant UpperCAmelCase = theta / 1_80 * np.pi UpperCAmelCase = np.cos(_theta ) UpperCAmelCase = np.sin(_theta ) # get kernel x UpperCAmelCase = cos_theta * px + sin_theta * py # get kernel y UpperCAmelCase = -sin_theta * px + cos_theta * py # fill kernel UpperCAmelCase = np.exp( -(_x**2 + gamma**2 * _y**2) / (2 * sigma**2) ) * np.cos(2 * np.pi * _x / lambd + psi ) return gabor if __name__ == "__main__": import doctest doctest.testmod() # read original image _lowercase : Tuple = imread("""../image_data/lena.jpg""") # turn image in gray scale value _lowercase : int = cvtColor(img, COLOR_BGR2GRAY) # Apply multiple Kernel to detect edges _lowercase : List[str] = np.zeros(gray.shape[:2]) for theta in [0, 30, 60, 90, 120, 150]: _lowercase : List[Any] = gabor_filter_kernel(10, 8, theta, 10, 0, 0) out += filteraD(gray, CV_8UC3, kernel_aa) _lowercase : Optional[int] = out / out.max() * 255 _lowercase : Optional[int] = out.astype(np.uinta) imshow("""Original""", gray) imshow("""Gabor filter with 20x20 mask and 6 directions""", out) waitKey(0)
91
0
"""simple docstring""" import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import ConditionalDetrImageProcessor class lowerCamelCase (unittest.TestCase ): def __init__( self : str , __UpperCAmelCase : Any , __UpperCAmelCase : str=7 , __UpperCAmelCase : Optional[int]=3 , __UpperCAmelCase : List[Any]=3_0 , __UpperCAmelCase : Tuple=4_0_0 , __UpperCAmelCase : Tuple=True , __UpperCAmelCase : List[str]=None , __UpperCAmelCase : Any=True , __UpperCAmelCase : Optional[Any]=[0.5, 0.5, 0.5] , __UpperCAmelCase : Dict=[0.5, 0.5, 0.5] , __UpperCAmelCase : Union[str, Any]=True , __UpperCAmelCase : Dict=1 / 2_5_5 , __UpperCAmelCase : int=True , ) -> Optional[Any]: # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p SCREAMING_SNAKE_CASE__ = size if size is not None else {"""shortest_edge""": 1_8, """longest_edge""": 1_3_3_3} SCREAMING_SNAKE_CASE__ = parent SCREAMING_SNAKE_CASE__ = batch_size SCREAMING_SNAKE_CASE__ = num_channels SCREAMING_SNAKE_CASE__ = min_resolution SCREAMING_SNAKE_CASE__ = max_resolution SCREAMING_SNAKE_CASE__ = do_resize SCREAMING_SNAKE_CASE__ = size SCREAMING_SNAKE_CASE__ = do_normalize SCREAMING_SNAKE_CASE__ = image_mean SCREAMING_SNAKE_CASE__ = image_std SCREAMING_SNAKE_CASE__ = do_rescale SCREAMING_SNAKE_CASE__ = rescale_factor SCREAMING_SNAKE_CASE__ = do_pad def SCREAMING_SNAKE_CASE ( self : Tuple ) -> str: return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def SCREAMING_SNAKE_CASE ( self : Tuple , __UpperCAmelCase : Tuple , __UpperCAmelCase : Dict=False ) -> Dict: if not batched: SCREAMING_SNAKE_CASE__ = image_inputs[0] if isinstance(__UpperCAmelCase , Image.Image ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = image.size else: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = image.shape[1], image.shape[2] if w < h: SCREAMING_SNAKE_CASE__ = int(self.size["""shortest_edge"""] * h / w ) SCREAMING_SNAKE_CASE__ = self.size["""shortest_edge"""] elif w > h: SCREAMING_SNAKE_CASE__ = self.size["""shortest_edge"""] SCREAMING_SNAKE_CASE__ = int(self.size["""shortest_edge"""] * w / h ) else: SCREAMING_SNAKE_CASE__ = self.size["""shortest_edge"""] SCREAMING_SNAKE_CASE__ = self.size["""shortest_edge"""] else: SCREAMING_SNAKE_CASE__ = [] for image in image_inputs: SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) SCREAMING_SNAKE_CASE__ = max(__UpperCAmelCase , key=lambda __UpperCAmelCase : item[0] )[0] SCREAMING_SNAKE_CASE__ = max(__UpperCAmelCase , key=lambda __UpperCAmelCase : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class lowerCamelCase (A__ ,unittest.TestCase ): lowerCamelCase__ : Optional[Any] = ConditionalDetrImageProcessor if is_vision_available() else None def SCREAMING_SNAKE_CASE ( self : Dict ) -> Union[str, Any]: SCREAMING_SNAKE_CASE__ = ConditionalDetrImageProcessingTester(self ) @property def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Tuple: return self.image_processor_tester.prepare_image_processor_dict() def SCREAMING_SNAKE_CASE ( self : str ) -> Dict: SCREAMING_SNAKE_CASE__ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__UpperCAmelCase , """image_mean""" ) ) self.assertTrue(hasattr(__UpperCAmelCase , """image_std""" ) ) self.assertTrue(hasattr(__UpperCAmelCase , """do_normalize""" ) ) self.assertTrue(hasattr(__UpperCAmelCase , """do_resize""" ) ) self.assertTrue(hasattr(__UpperCAmelCase , """size""" ) ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Dict: SCREAMING_SNAKE_CASE__ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"""shortest_edge""": 1_8, """longest_edge""": 1_3_3_3} ) self.assertEqual(image_processor.do_pad , __UpperCAmelCase ) SCREAMING_SNAKE_CASE__ = self.image_processing_class.from_dict( self.image_processor_dict , size=4_2 , max_size=8_4 , pad_and_return_pixel_mask=__UpperCAmelCase ) self.assertEqual(image_processor.size , {"""shortest_edge""": 4_2, """longest_edge""": 8_4} ) self.assertEqual(image_processor.do_pad , __UpperCAmelCase ) def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Tuple: pass def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> str: # Initialize image_processing SCREAMING_SNAKE_CASE__ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images SCREAMING_SNAKE_CASE__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , Image.Image ) # Test not batched input SCREAMING_SNAKE_CASE__ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.image_processor_tester.get_expected_values(__UpperCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.image_processor_tester.get_expected_values(__UpperCAmelCase , batched=__UpperCAmelCase ) SCREAMING_SNAKE_CASE__ = image_processing(__UpperCAmelCase , return_tensors="""pt""" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE ( self : List[Any] ) -> int: # Initialize image_processing SCREAMING_SNAKE_CASE__ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors SCREAMING_SNAKE_CASE__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , numpify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , np.ndarray ) # Test not batched input SCREAMING_SNAKE_CASE__ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.image_processor_tester.get_expected_values(__UpperCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE__ = image_processing(__UpperCAmelCase , return_tensors="""pt""" ).pixel_values SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.image_processor_tester.get_expected_values(__UpperCAmelCase , batched=__UpperCAmelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]: # Initialize image_processing SCREAMING_SNAKE_CASE__ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors SCREAMING_SNAKE_CASE__ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__UpperCAmelCase , torchify=__UpperCAmelCase ) for image in image_inputs: self.assertIsInstance(__UpperCAmelCase , torch.Tensor ) # Test not batched input SCREAMING_SNAKE_CASE__ = image_processing(image_inputs[0] , return_tensors="""pt""" ).pixel_values SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.image_processor_tester.get_expected_values(__UpperCAmelCase ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched SCREAMING_SNAKE_CASE__ = image_processing(__UpperCAmelCase , return_tensors="""pt""" ).pixel_values SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = self.image_processor_tester.get_expected_values(__UpperCAmelCase , batched=__UpperCAmelCase ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) @slow def SCREAMING_SNAKE_CASE ( self : List[str] ) -> Union[str, Any]: # prepare image and target SCREAMING_SNAKE_CASE__ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) with open("""./tests/fixtures/tests_samples/COCO/coco_annotations.txt""" , """r""" ) as f: SCREAMING_SNAKE_CASE__ = json.loads(f.read() ) SCREAMING_SNAKE_CASE__ = {"""image_id""": 3_9_7_6_9, """annotations""": target} # encode them SCREAMING_SNAKE_CASE__ = ConditionalDetrImageProcessor.from_pretrained("""microsoft/conditional-detr-resnet-50""" ) SCREAMING_SNAKE_CASE__ = image_processing(images=__UpperCAmelCase , annotations=__UpperCAmelCase , return_tensors="""pt""" ) # verify pixel values SCREAMING_SNAKE_CASE__ = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding["""pixel_values"""].shape , __UpperCAmelCase ) SCREAMING_SNAKE_CASE__ = torch.tensor([0.2_796, 0.3_138, 0.3_481] ) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , __UpperCAmelCase , atol=1e-4 ) ) # verify area SCREAMING_SNAKE_CASE__ = torch.tensor([5_887.9_600, 11_250.2_061, 489_353.8_438, 837_122.7_500, 147_967.5_156, 165_732.3_438] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , __UpperCAmelCase ) ) # verify boxes SCREAMING_SNAKE_CASE__ = torch.Size([6, 4] ) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , __UpperCAmelCase ) SCREAMING_SNAKE_CASE__ = torch.tensor([0.5_503, 0.2_765, 0.0_604, 0.2_215] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , __UpperCAmelCase , atol=1e-3 ) ) # verify image_id SCREAMING_SNAKE_CASE__ = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , __UpperCAmelCase ) ) # verify is_crowd SCREAMING_SNAKE_CASE__ = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , __UpperCAmelCase ) ) # verify class_labels SCREAMING_SNAKE_CASE__ = torch.tensor([7_5, 7_5, 6_3, 6_5, 1_7, 1_7] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , __UpperCAmelCase ) ) # verify orig_size SCREAMING_SNAKE_CASE__ = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , __UpperCAmelCase ) ) # verify size SCREAMING_SNAKE_CASE__ = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , __UpperCAmelCase ) ) @slow def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Any: # prepare image, target and masks_path SCREAMING_SNAKE_CASE__ = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) with open("""./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt""" , """r""" ) as f: SCREAMING_SNAKE_CASE__ = json.loads(f.read() ) SCREAMING_SNAKE_CASE__ = {"""file_name""": """000000039769.png""", """image_id""": 3_9_7_6_9, """segments_info""": target} SCREAMING_SNAKE_CASE__ = pathlib.Path("""./tests/fixtures/tests_samples/COCO/coco_panoptic""" ) # encode them SCREAMING_SNAKE_CASE__ = ConditionalDetrImageProcessor(format="""coco_panoptic""" ) SCREAMING_SNAKE_CASE__ = image_processing(images=__UpperCAmelCase , annotations=__UpperCAmelCase , masks_path=__UpperCAmelCase , return_tensors="""pt""" ) # verify pixel values SCREAMING_SNAKE_CASE__ = torch.Size([1, 3, 8_0_0, 1_0_6_6] ) self.assertEqual(encoding["""pixel_values"""].shape , __UpperCAmelCase ) SCREAMING_SNAKE_CASE__ = torch.tensor([0.2_796, 0.3_138, 0.3_481] ) self.assertTrue(torch.allclose(encoding["""pixel_values"""][0, 0, 0, :3] , __UpperCAmelCase , atol=1e-4 ) ) # verify area SCREAMING_SNAKE_CASE__ = torch.tensor([147_979.6_875, 165_527.0_469, 484_638.5_938, 11_292.9_375, 5_879.6_562, 7_634.1_147] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""area"""] , __UpperCAmelCase ) ) # verify boxes SCREAMING_SNAKE_CASE__ = torch.Size([6, 4] ) self.assertEqual(encoding["""labels"""][0]["""boxes"""].shape , __UpperCAmelCase ) SCREAMING_SNAKE_CASE__ = torch.tensor([0.2_625, 0.5_437, 0.4_688, 0.8_625] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""boxes"""][0] , __UpperCAmelCase , atol=1e-3 ) ) # verify image_id SCREAMING_SNAKE_CASE__ = torch.tensor([3_9_7_6_9] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""image_id"""] , __UpperCAmelCase ) ) # verify is_crowd SCREAMING_SNAKE_CASE__ = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""iscrowd"""] , __UpperCAmelCase ) ) # verify class_labels SCREAMING_SNAKE_CASE__ = torch.tensor([1_7, 1_7, 6_3, 7_5, 7_5, 9_3] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""class_labels"""] , __UpperCAmelCase ) ) # verify masks SCREAMING_SNAKE_CASE__ = 8_2_2_8_7_3 self.assertEqual(encoding["""labels"""][0]["""masks"""].sum().item() , __UpperCAmelCase ) # verify orig_size SCREAMING_SNAKE_CASE__ = torch.tensor([4_8_0, 6_4_0] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""orig_size"""] , __UpperCAmelCase ) ) # verify size SCREAMING_SNAKE_CASE__ = torch.tensor([8_0_0, 1_0_6_6] ) self.assertTrue(torch.allclose(encoding["""labels"""][0]["""size"""] , __UpperCAmelCase ) )
165
"""simple docstring""" import argparse import json import os import torch from transformers import LukeConfig, LukeModel, LukeTokenizer, RobertaTokenizer from transformers.tokenization_utils_base import AddedToken @torch.no_grad() def A ( snake_case__ , snake_case__ , snake_case__ , snake_case__ , snake_case__ ): '''simple docstring''' with open(snake_case__ ) as metadata_file: SCREAMING_SNAKE_CASE__ = json.load(snake_case__ ) SCREAMING_SNAKE_CASE__ = LukeConfig(use_entity_aware_attention=snake_case__ , **metadata["""model_config"""] ) # Load in the weights from the checkpoint_path SCREAMING_SNAKE_CASE__ = torch.load(snake_case__ , map_location="""cpu""" ) # Load the entity vocab file SCREAMING_SNAKE_CASE__ = load_entity_vocab(snake_case__ ) SCREAMING_SNAKE_CASE__ = RobertaTokenizer.from_pretrained(metadata["""model_config"""]["""bert_model_name"""] ) # Add special tokens to the token vocabulary for downstream tasks SCREAMING_SNAKE_CASE__ = AddedToken("""<ent>""" , lstrip=snake_case__ , rstrip=snake_case__ ) SCREAMING_SNAKE_CASE__ = AddedToken("""<ent2>""" , lstrip=snake_case__ , rstrip=snake_case__ ) tokenizer.add_special_tokens({"""additional_special_tokens""": [entity_token_a, entity_token_a]} ) config.vocab_size += 2 print(f"""Saving tokenizer to {pytorch_dump_folder_path}""" ) tokenizer.save_pretrained(snake_case__ ) with open(os.path.join(snake_case__ , LukeTokenizer.vocab_files_names["""entity_vocab_file"""] ) , """w""" ) as f: json.dump(snake_case__ , snake_case__ ) SCREAMING_SNAKE_CASE__ = LukeTokenizer.from_pretrained(snake_case__ ) # Initialize the embeddings of the special tokens SCREAMING_SNAKE_CASE__ = state_dict["""embeddings.word_embeddings.weight"""] SCREAMING_SNAKE_CASE__ = word_emb[tokenizer.convert_tokens_to_ids(["""@"""] )[0]].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ = word_emb[tokenizer.convert_tokens_to_ids(["""#"""] )[0]].unsqueeze(0 ) SCREAMING_SNAKE_CASE__ = torch.cat([word_emb, ent_emb, enta_emb] ) # Initialize the query layers of the entity-aware self-attention mechanism for layer_index in range(config.num_hidden_layers ): for matrix_name in ["query.weight", "query.bias"]: SCREAMING_SNAKE_CASE__ = f"""encoder.layer.{layer_index}.attention.self.""" SCREAMING_SNAKE_CASE__ = state_dict[prefix + matrix_name] SCREAMING_SNAKE_CASE__ = state_dict[prefix + matrix_name] SCREAMING_SNAKE_CASE__ = state_dict[prefix + matrix_name] # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks SCREAMING_SNAKE_CASE__ = state_dict["""entity_embeddings.entity_embeddings.weight"""] SCREAMING_SNAKE_CASE__ = entity_emb[entity_vocab["""[MASK]"""]] SCREAMING_SNAKE_CASE__ = LukeModel(config=snake_case__ ).eval() SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = model.load_state_dict(snake_case__ , strict=snake_case__ ) if not (len(snake_case__ ) == 1 and missing_keys[0] == "embeddings.position_ids"): raise ValueError(f"""Missing keys {", ".join(snake_case__ )}. Expected only missing embeddings.position_ids""" ) if not (all(key.startswith("""entity_predictions""" ) or key.startswith("""lm_head""" ) for key in unexpected_keys )): raise ValueError( """Unexpected keys""" f""" {", ".join([key for key in unexpected_keys if not (key.startswith("entity_predictions" ) or key.startswith("lm_head" ))] )}""" ) # Check outputs SCREAMING_SNAKE_CASE__ = LukeTokenizer.from_pretrained(snake_case__ , task="""entity_classification""" ) SCREAMING_SNAKE_CASE__ = ( """Top seed Ana Ivanovic said on Thursday she could hardly believe her luck as a fortuitous netcord helped the""" """ new world number one avoid a humiliating second- round exit at Wimbledon .""" ) SCREAMING_SNAKE_CASE__ = (39, 42) SCREAMING_SNAKE_CASE__ = tokenizer(snake_case__ , entity_spans=[span] , add_prefix_space=snake_case__ , return_tensors="""pt""" ) SCREAMING_SNAKE_CASE__ = model(**snake_case__ ) # Verify word hidden states if model_size == "large": SCREAMING_SNAKE_CASE__ = torch.Size((1, 42, 10_24) ) SCREAMING_SNAKE_CASE__ = torch.tensor( [[0.01_33, 0.08_65, 0.00_95], [0.30_93, -0.25_76, -0.74_18], [-0.17_20, -0.21_17, -0.28_69]] ) else: # base SCREAMING_SNAKE_CASE__ = torch.Size((1, 42, 7_68) ) SCREAMING_SNAKE_CASE__ = torch.tensor([[0.00_37, 0.13_68, -0.00_91], [0.10_99, 0.33_29, -0.10_95], [0.07_65, 0.53_35, 0.11_79]] ) if not (outputs.last_hidden_state.shape == expected_shape): raise ValueError( f"""Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}""" ) if not torch.allclose(outputs.last_hidden_state[0, :3, :3] , snake_case__ , atol=1e-4 ): raise ValueError # Verify entity hidden states if model_size == "large": SCREAMING_SNAKE_CASE__ = torch.Size((1, 1, 10_24) ) SCREAMING_SNAKE_CASE__ = torch.tensor([[0.04_66, -0.01_06, -0.01_79]] ) else: # base SCREAMING_SNAKE_CASE__ = torch.Size((1, 1, 7_68) ) SCREAMING_SNAKE_CASE__ = torch.tensor([[0.14_57, 0.10_44, 0.01_74]] ) if not (outputs.entity_last_hidden_state.shape != expected_shape): raise ValueError( f"""Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is""" f""" {expected_shape}""" ) if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3] , snake_case__ , atol=1e-4 ): raise ValueError # Finally, save our PyTorch model and tokenizer print("""Saving PyTorch model to {}""".format(snake_case__ ) ) model.save_pretrained(snake_case__ ) def A ( snake_case__ ): '''simple docstring''' SCREAMING_SNAKE_CASE__ = {} with open(snake_case__ , """r""" , encoding="""utf-8""" ) as f: for index, line in enumerate(snake_case__ ): SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = line.rstrip().split("""\t""" ) SCREAMING_SNAKE_CASE__ = index return entity_vocab if __name__ == "__main__": A_ : str = argparse.ArgumentParser() # Required parameters parser.add_argument("--checkpoint_path", type=str, help="Path to a pytorch_model.bin file.") parser.add_argument( "--metadata_path", default=None, type=str, help="Path to a metadata.json file, defining the configuration." ) parser.add_argument( "--entity_vocab_path", default=None, type=str, help="Path to an entity_vocab.tsv file, containing the entity vocabulary.", ) parser.add_argument( "--pytorch_dump_folder_path", default=None, type=str, help="Path to where to dump the output PyTorch model." ) parser.add_argument( "--model_size", default="base", type=str, choices=["base", "large"], help="Size of the model to be converted." ) A_ : Optional[Any] = parser.parse_args() convert_luke_checkpoint( args.checkpoint_path, args.metadata_path, args.entity_vocab_path, args.pytorch_dump_folder_path, args.model_size, )
165
1
"""simple docstring""" import math import os from copy import deepcopy import datasets import evaluate import torch import transformers from datasets import load_dataset from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer from accelerate import Accelerator from accelerate.test_utils import RegressionDataset, RegressionModel from accelerate.utils import is_tpu_available, set_seed __UpperCamelCase = '''true''' def lowercase (SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Tuple=82 , SCREAMING_SNAKE_CASE_ : List[Any]=16 ) -> Union[str, Any]: set_seed(42 ) SCREAMING_SNAKE_CASE = RegressionModel() SCREAMING_SNAKE_CASE = deepcopy(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = RegressionDataset(length=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = DataLoader(SCREAMING_SNAKE_CASE_ , batch_size=SCREAMING_SNAKE_CASE_ ) model.to(accelerator.device ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return model, ddp_model, dataloader def lowercase (SCREAMING_SNAKE_CASE_ : Accelerator , SCREAMING_SNAKE_CASE_ : Union[str, Any]=False ) -> Union[str, Any]: SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained('hf-internal-testing/mrpc-bert-base-cased' ) SCREAMING_SNAKE_CASE = load_dataset('glue' , 'mrpc' , split='validation' ) def tokenize_function(SCREAMING_SNAKE_CASE_ : List[str] ): SCREAMING_SNAKE_CASE = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=SCREAMING_SNAKE_CASE_ , max_length=SCREAMING_SNAKE_CASE_ ) return outputs with accelerator.main_process_first(): SCREAMING_SNAKE_CASE = dataset.map( SCREAMING_SNAKE_CASE_ , batched=SCREAMING_SNAKE_CASE_ , remove_columns=['idx', 'sentence1', 'sentence2'] , ) SCREAMING_SNAKE_CASE = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(SCREAMING_SNAKE_CASE_ : Optional[int] ): if use_longest: return tokenizer.pad(SCREAMING_SNAKE_CASE_ , padding='longest' , return_tensors='pt' ) return tokenizer.pad(SCREAMING_SNAKE_CASE_ , padding='max_length' , max_length=1_28 , return_tensors='pt' ) return DataLoader(SCREAMING_SNAKE_CASE_ , shuffle=SCREAMING_SNAKE_CASE_ , collate_fn=SCREAMING_SNAKE_CASE_ , batch_size=16 ) def lowercase (SCREAMING_SNAKE_CASE_ : List[Any] , SCREAMING_SNAKE_CASE_ : Any ) -> Dict: SCREAMING_SNAKE_CASE = Accelerator(dispatch_batches=SCREAMING_SNAKE_CASE_ , split_batches=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = get_dataloader(SCREAMING_SNAKE_CASE_ , not dispatch_batches ) SCREAMING_SNAKE_CASE = AutoModelForSequenceClassification.from_pretrained( 'hf-internal-testing/mrpc-bert-base-cased' , return_dict=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.prepare(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) return {"ddp": [ddp_model, ddp_dataloader, "cuda:0"], "no": [model, dataloader, accelerator.device]}, accelerator def lowercase (SCREAMING_SNAKE_CASE_ : Dict , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : Dict ) -> Dict: SCREAMING_SNAKE_CASE = [] for batch in dataloader: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = batch.values() with torch.no_grad(): SCREAMING_SNAKE_CASE = model(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((logit, target) ) logits_and_targets.append((logit, target) ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = [], [] for logit, targ in logits_and_targets: logits.append(SCREAMING_SNAKE_CASE_ ) targs.append(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = torch.cat(SCREAMING_SNAKE_CASE_ ), torch.cat(SCREAMING_SNAKE_CASE_ ) return logits, targs def lowercase (SCREAMING_SNAKE_CASE_ : Accelerator , SCREAMING_SNAKE_CASE_ : Optional[Any]=82 , SCREAMING_SNAKE_CASE_ : int=False , SCREAMING_SNAKE_CASE_ : List[Any]=False , SCREAMING_SNAKE_CASE_ : Union[str, Any]=16 ) -> List[str]: SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_basic_setup(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = generate_predictions(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) assert ( len(SCREAMING_SNAKE_CASE_ ) == num_samples ), F'Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(SCREAMING_SNAKE_CASE_ )}' def lowercase (SCREAMING_SNAKE_CASE_ : bool = False , SCREAMING_SNAKE_CASE_ : bool = False ) -> Optional[int]: SCREAMING_SNAKE_CASE = evaluate.load('glue' , 'mrpc' ) SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = get_mrpc_setup(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) # First do baseline SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['no'] model.to(SCREAMING_SNAKE_CASE_ ) model.eval() for batch in dataloader: batch.to(SCREAMING_SNAKE_CASE_ ) with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1 ) metric.add_batch(predictions=SCREAMING_SNAKE_CASE_ , references=batch['labels'] ) SCREAMING_SNAKE_CASE = metric.compute() # Then do distributed SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = setup['ddp'] model.eval() for batch in dataloader: with torch.inference_mode(): SCREAMING_SNAKE_CASE = model(**SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = outputs.logits.argmax(dim=-1 ) SCREAMING_SNAKE_CASE = batch['labels'] SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = accelerator.gather_for_metrics((preds, references) ) metric.add_batch(predictions=SCREAMING_SNAKE_CASE_ , references=SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = metric.compute() for key in "accuracy f1".split(): assert math.isclose( baseline[key] , distributed[key] ), F'Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n' def lowercase () -> Dict: SCREAMING_SNAKE_CASE = Accelerator(split_batches=SCREAMING_SNAKE_CASE_ , dispatch_batches=SCREAMING_SNAKE_CASE_ ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_warning() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() # These are a bit slower so they should only be ran on the GPU or TPU if torch.cuda.is_available() or is_tpu_available(): if accelerator.is_local_main_process: print('**Testing gather_for_metrics**' ) for split_batches in [True, False]: for dispatch_batches in [True, False]: if accelerator.is_local_main_process: print(F'With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`' ) test_mrpc(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test torch metrics**' ) for split_batches in [True, False]: for dispatch_batches in [True, False]: SCREAMING_SNAKE_CASE = Accelerator(split_batches=SCREAMING_SNAKE_CASE_ , dispatch_batches=SCREAMING_SNAKE_CASE_ ) if accelerator.is_local_main_process: print(F'With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99' ) test_torch_metrics(SCREAMING_SNAKE_CASE_ , 99 ) accelerator.state._reset_state() if accelerator.is_local_main_process: print('**Test last batch is not dropped when perfectly divisible**' ) SCREAMING_SNAKE_CASE = Accelerator() test_torch_metrics(SCREAMING_SNAKE_CASE_ , 5_12 ) accelerator.state._reset_state() def lowercase (SCREAMING_SNAKE_CASE_ : int ) -> Union[str, Any]: # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
38
"""simple docstring""" import argparse from pathlib import Path import torch from transformers import OPTConfig, OPTModel from transformers.utils import logging logging.set_verbosity_info() __UpperCamelCase = logging.get_logger(__name__) def lowercase (SCREAMING_SNAKE_CASE_ : List[str] ) -> Optional[Any]: SCREAMING_SNAKE_CASE = torch.load(SCREAMING_SNAKE_CASE_ , map_location='cpu' ) if "model" in sd.keys(): SCREAMING_SNAKE_CASE = torch.load(SCREAMING_SNAKE_CASE_ , map_location='cpu' )['model'] # pop unnecessary weights SCREAMING_SNAKE_CASE = [ 'decoder.version', 'decoder.output_projection.weight', ] for key in keys_to_delete: if key in sd: sd.pop(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = { 'decoder.project_in_dim.weight': 'decoder.project_in.weight', 'decoder.project_out_dim.weight': 'decoder.project_out.weight', 'decoder.layer_norm.weight': 'decoder.final_layer_norm.weight', 'decoder.layer_norm.bias': 'decoder.final_layer_norm.bias', } for old_key, new_key in keys_to_rename.items(): if old_key in sd: SCREAMING_SNAKE_CASE = sd.pop(SCREAMING_SNAKE_CASE_ ) SCREAMING_SNAKE_CASE = list(sd.keys() ) for key in keys: if ".qkv_proj." in key: SCREAMING_SNAKE_CASE = sd[key] # We split QKV in separate Q,K,V SCREAMING_SNAKE_CASE = key.replace('.qkv_proj.' , '.q_proj.' ) SCREAMING_SNAKE_CASE = key.replace('.qkv_proj.' , '.k_proj.' ) SCREAMING_SNAKE_CASE = key.replace('.qkv_proj.' , '.v_proj.' ) SCREAMING_SNAKE_CASE = value.shape[0] assert depth % 3 == 0 # `SequeuceParallelTransformerBlock` has QKV weight is separated in K,V,Q despite the naming: # https://cs.github.com/facebookresearch/metaseq/blob/51871bd73cd04c038f239ea2a26db1d7f6b37927/metaseq/modules/sequence_parallel_transformer_layer.py#L97 SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = torch.split(SCREAMING_SNAKE_CASE_ , depth // 3 , dim=0 ) SCREAMING_SNAKE_CASE = q SCREAMING_SNAKE_CASE = k SCREAMING_SNAKE_CASE = v del sd[key] return sd @torch.no_grad() def lowercase (SCREAMING_SNAKE_CASE_ : str , SCREAMING_SNAKE_CASE_ : Tuple , SCREAMING_SNAKE_CASE_ : Optional[int]=None ) -> List[Any]: SCREAMING_SNAKE_CASE = load_checkpoint(SCREAMING_SNAKE_CASE_ ) if config is not None: SCREAMING_SNAKE_CASE = OPTConfig.from_pretrained(SCREAMING_SNAKE_CASE_ ) else: SCREAMING_SNAKE_CASE = OPTConfig() SCREAMING_SNAKE_CASE = OPTModel(SCREAMING_SNAKE_CASE_ ).half().eval() model.load_state_dict(SCREAMING_SNAKE_CASE_ ) # Check results Path(SCREAMING_SNAKE_CASE_ ).mkdir(exist_ok=SCREAMING_SNAKE_CASE_ ) model.save_pretrained(SCREAMING_SNAKE_CASE_ ) if __name__ == "__main__": __UpperCamelCase = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--fairseq_path''', type=str, help=( '''path to fairseq checkpoint in correct format. You can find all checkpoints in the correct format here:''' ''' https://huggingface.co/models?other=opt_metasq''' ), ) parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument('''--hf_config''', default=None, type=str, help='''Define HF config.''') __UpperCamelCase = parser.parse_args() convert_opt_checkpoint(args.fairseq_path, args.pytorch_dump_folder_path, config=args.hf_config)
38
1
'''simple docstring''' from ....configuration_utils import PretrainedConfig from ....utils import logging __snake_case = logging.get_logger(__name__) __snake_case = { '''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 lowercase ( A__ ): """simple docstring""" _a = 'trajectory_transformer' _a = ['past_key_values'] _a = { 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer', } def __init__( self , UpperCamelCase_=100 , UpperCamelCase_=5 , UpperCamelCase_=1 , UpperCamelCase_=1 , UpperCamelCase_=249 , UpperCamelCase_=6 , UpperCamelCase_=17 , UpperCamelCase_=25 , UpperCamelCase_=4 , UpperCamelCase_=4 , UpperCamelCase_=128 , UpperCamelCase_=0.1 , UpperCamelCase_=0.1 , UpperCamelCase_=0.1 , UpperCamelCase_=0.0006 , UpperCamelCase_=512 , UpperCamelCase_=0.02 , UpperCamelCase_=1e-12 , UpperCamelCase_=1 , UpperCamelCase_=True , UpperCamelCase_=1 , UpperCamelCase_=50256 , UpperCamelCase_=50256 , **UpperCamelCase_ , ): '''simple docstring''' UpperCamelCase__ :int = vocab_size UpperCamelCase__ :str = action_weight UpperCamelCase__ :Dict = reward_weight UpperCamelCase__ :Optional[int] = value_weight UpperCamelCase__ :List[Any] = max_position_embeddings UpperCamelCase__ :int = block_size UpperCamelCase__ :Optional[Any] = action_dim UpperCamelCase__ :Union[str, Any] = observation_dim UpperCamelCase__ :int = transition_dim UpperCamelCase__ :int = learning_rate UpperCamelCase__ :int = n_layer UpperCamelCase__ :int = n_head UpperCamelCase__ :List[Any] = n_embd UpperCamelCase__ :Optional[int] = embd_pdrop UpperCamelCase__ :Dict = attn_pdrop UpperCamelCase__ :List[str] = resid_pdrop UpperCamelCase__ :Optional[Any] = initializer_range UpperCamelCase__ :Any = layer_norm_eps UpperCamelCase__ :Optional[int] = kaiming_initializer_range UpperCamelCase__ :Dict = use_cache super().__init__(pad_token_id=UpperCamelCase_ , bos_token_id=UpperCamelCase_ , eos_token_id=UpperCamelCase_ , **UpperCamelCase_ )
97
'''simple docstring''' import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : int = logging.get_logger(__name__) lowercase : Union[str, Any] = { "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/config.json", "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/config.json", } class __UpperCAmelCase ( _lowerCamelCase ): __lowercase = """xlnet""" __lowercase = ["""mems"""] __lowercase = { """n_token""": """vocab_size""", # Backward compatibility """hidden_size""": """d_model""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self , lowerCAmelCase_=3_20_00 , lowerCAmelCase_=10_24 , lowerCAmelCase_=24 , lowerCAmelCase_=16 , lowerCAmelCase_=40_96 , lowerCAmelCase_="gelu" , lowerCAmelCase_=True , lowerCAmelCase_="bi" , lowerCAmelCase_=0.02 , lowerCAmelCase_=1E-12 , lowerCAmelCase_=0.1 , lowerCAmelCase_=5_12 , lowerCAmelCase_=None , lowerCAmelCase_=True , lowerCAmelCase_=False , lowerCAmelCase_=False , lowerCAmelCase_=-1 , lowerCAmelCase_=False , lowerCAmelCase_="last" , lowerCAmelCase_=True , lowerCAmelCase_="tanh" , lowerCAmelCase_=0.1 , lowerCAmelCase_=5 , lowerCAmelCase_=5 , lowerCAmelCase_=5 , lowerCAmelCase_=1 , lowerCAmelCase_=2 , **lowerCAmelCase_ , ): """simple docstring""" _snake_case = vocab_size _snake_case = d_model _snake_case = n_layer _snake_case = n_head if d_model % n_head != 0: raise ValueError(F'\'d_model % n_head\' ({d_model % n_head}) should be equal to 0' ) if "d_head" in kwargs: if kwargs["d_head"] != d_model // n_head: raise ValueError( F'`d_head` ({kwargs["d_head"]}) should be equal to `d_model // n_head` ({d_model // n_head})' ) _snake_case = d_model // n_head _snake_case = ff_activation _snake_case = d_inner _snake_case = untie_r _snake_case = attn_type _snake_case = initializer_range _snake_case = layer_norm_eps _snake_case = dropout _snake_case = mem_len _snake_case = reuse_len _snake_case = bi_data _snake_case = clamp_len _snake_case = same_length _snake_case = summary_type _snake_case = summary_use_proj _snake_case = summary_activation _snake_case = summary_last_dropout _snake_case = start_n_top _snake_case = end_n_top _snake_case = bos_token_id _snake_case = pad_token_id _snake_case = eos_token_id if "use_cache" in kwargs: warnings.warn( 'The `use_cache` argument is deprecated and will be removed in a future version, use `use_mems_eval`' ' instead.' , lowerCAmelCase_ , ) _snake_case = kwargs['use_cache'] _snake_case = use_mems_eval _snake_case = use_mems_train super().__init__(pad_token_id=lowerCAmelCase_ , bos_token_id=lowerCAmelCase_ , eos_token_id=lowerCAmelCase_ , **lowerCAmelCase_ ) @property def lowerCamelCase ( self ): """simple docstring""" logger.info(F'The model {self.model_type} is one of the few models that has no sequence length limit.' ) return -1 @max_position_embeddings.setter def lowerCamelCase ( self , lowerCAmelCase_ ): """simple docstring""" raise NotImplementedError( F'The model {self.model_type} is one of the few models that has no sequence length limit.' )
42
0
"""simple docstring""" # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import doctest import sys import warnings from os.path import abspath, dirname, join import _pytest from transformers.testing_utils import HfDoctestModule, HfDocTestParser # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. __UpperCamelCase : Optional[Any] = abspath(join(dirname(__file__), '''src''')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='''ignore''', category=FutureWarning) def __SCREAMING_SNAKE_CASE ( A_ ): config.addinivalue_line( '''markers''' , '''is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested''' ) config.addinivalue_line( '''markers''' , '''is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested''' ) config.addinivalue_line('''markers''' , '''is_pipeline_test: mark test to run only when pipelines are tested''' ) config.addinivalue_line('''markers''' , '''is_staging_test: mark test to run only in the staging environment''' ) config.addinivalue_line('''markers''' , '''accelerate_tests: mark test that require accelerate''' ) config.addinivalue_line('''markers''' , '''tool_tests: mark the tool tests that are run on their specific schedule''' ) def __SCREAMING_SNAKE_CASE ( A_ ): from transformers.testing_utils import pytest_addoption_shared pytest_addoption_shared(A_ ) def __SCREAMING_SNAKE_CASE ( A_ ): from transformers.testing_utils import pytest_terminal_summary_main lowerCAmelCase__ : Optional[int] = terminalreporter.config.getoption('''--make-reports''' ) if make_reports: pytest_terminal_summary_main(A_ , id=A_ ) def __SCREAMING_SNAKE_CASE ( A_ , A_ ): # If no tests are collected, pytest exists with code 5, which makes the CI fail. if exitstatus == 5: lowerCAmelCase__ : List[Any] = 0 # Doctest custom flag to ignore output. __UpperCamelCase : Any = doctest.register_optionflag('''IGNORE_RESULT''') __UpperCamelCase : List[Any] = doctest.OutputChecker class SCREAMING_SNAKE_CASE ( a_ ): """simple docstring""" def __lowerCAmelCase ( self : Dict ,lowercase_ : List[Any] ,lowercase_ : Dict ,lowercase_ : str ): if IGNORE_RESULT & optionflags: return True return OutputChecker.check_output(self ,lowercase_ ,lowercase_ ,lowercase_ ) __UpperCamelCase : int = CustomOutputChecker __UpperCamelCase : Union[str, Any] = HfDoctestModule __UpperCamelCase : int = HfDocTestParser
74
"""simple docstring""" from __future__ import annotations import math __UpperCamelCase : Dict = '''2020.9.26''' __UpperCamelCase : Tuple = '''xcodz-dot, cclaus, dhruvmanila''' def __SCREAMING_SNAKE_CASE ( A_ , A_ , A_ , A_ , A_ ): if not all(isinstance(A_ , (float, int) ) for val in locals().values() ): lowerCAmelCase__ : Optional[Any] = f'Input values must either be float or int: {list(locals().values() )}' raise TypeError(A_ ) lowerCAmelCase__ : Optional[Any] = ((x * distance) / (z + distance)) * scale lowerCAmelCase__ : Optional[int] = ((y * distance) / (z + distance)) * scale return projected_x, projected_y def __SCREAMING_SNAKE_CASE ( A_ , A_ , A_ , A_ , A_ ): if not isinstance(A_ , A_ ): raise TypeError('''Axis must be a str''' ) lowerCAmelCase__ : str = locals() del input_variables["axis"] if not all(isinstance(A_ , (float, int) ) for val in input_variables.values() ): lowerCAmelCase__ : int = ( '''Input values except axis must either be float or int: ''' f'{list(input_variables.values() )}' ) raise TypeError(A_ ) lowerCAmelCase__ : Any = (angle % 3_60) / 4_50 * 1_80 / math.pi if axis == "z": lowerCAmelCase__ : Tuple = x * math.cos(A_ ) - y * math.sin(A_ ) lowerCAmelCase__ : List[str] = y * math.cos(A_ ) + x * math.sin(A_ ) lowerCAmelCase__ : Optional[Any] = z elif axis == "x": lowerCAmelCase__ : List[str] = y * math.cos(A_ ) - z * math.sin(A_ ) lowerCAmelCase__ : str = z * math.cos(A_ ) + y * math.sin(A_ ) lowerCAmelCase__ : Union[str, Any] = x elif axis == "y": lowerCAmelCase__ : Optional[int] = x * math.cos(A_ ) - z * math.sin(A_ ) lowerCAmelCase__ : Tuple = z * math.cos(A_ ) + x * math.sin(A_ ) lowerCAmelCase__ : Optional[int] = y else: raise ValueError('''not a valid axis, choose one of \'x\', \'y\', \'z\'''' ) return new_x, new_y, new_z if __name__ == "__main__": import doctest doctest.testmod() print(F'''{convert_to_ad(1.0, 2.0, 3.0, 1_0.0, 1_0.0) = }''') print(F'''{rotate(1.0, 2.0, 3.0, 'y', 9_0.0) = }''')
74
1
import numpy as np from cva import destroyAllWindows, imread, imshow, waitKey class lowercase__ : def __init__( self : str , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : int , UpperCAmelCase_ : int ): if dst_width < 0 or dst_height < 0: raise ValueError('Destination width/height should be > 0' ) SCREAMING_SNAKE_CASE__ = img SCREAMING_SNAKE_CASE__ = img.shape[1] SCREAMING_SNAKE_CASE__ = img.shape[0] SCREAMING_SNAKE_CASE__ = dst_width SCREAMING_SNAKE_CASE__ = dst_height SCREAMING_SNAKE_CASE__ = self.src_w / self.dst_w SCREAMING_SNAKE_CASE__ = self.src_h / self.dst_h SCREAMING_SNAKE_CASE__ = SCREAMING_SNAKE_CASE__ = ( np.ones((self.dst_h, self.dst_w, 3) , np.uinta ) * 255 ) def A_ ( self : int ): for i in range(self.dst_h ): for j in range(self.dst_w ): SCREAMING_SNAKE_CASE__ = self.img[self.get_y(UpperCAmelCase_ )][self.get_x(UpperCAmelCase_ )] def A_ ( self : Tuple , UpperCAmelCase_ : int ): return int(self.ratio_x * x ) def A_ ( self : List[str] , UpperCAmelCase_ : int ): return int(self.ratio_y * y ) if __name__ == "__main__": __snake_case ,__snake_case = 8_00, 6_00 __snake_case = imread("""image_data/lena.jpg""", 1) __snake_case = NearestNeighbour(im, dst_w, dst_h) n.process() imshow( F"""Image resized from: {im.shape[1]}x{im.shape[0]} to {dst_w}x{dst_h}""", n.output ) waitKey(0) destroyAllWindows()
176
import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_bart import BartTokenizer __snake_case = logging.get_logger(__name__) __snake_case = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""} # See all BART models at https://huggingface.co/models?filter=bart __snake_case = { """vocab_file""": { """facebook/bart-base""": """https://huggingface.co/facebook/bart-base/resolve/main/vocab.json""", """facebook/bart-large""": """https://huggingface.co/facebook/bart-large/resolve/main/vocab.json""", """facebook/bart-large-mnli""": """https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json""", """facebook/bart-large-cnn""": """https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json""", """facebook/bart-large-xsum""": """https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json""", """yjernite/bart_eli5""": """https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json""", }, """merges_file""": { """facebook/bart-base""": """https://huggingface.co/facebook/bart-base/resolve/main/merges.txt""", """facebook/bart-large""": """https://huggingface.co/facebook/bart-large/resolve/main/merges.txt""", """facebook/bart-large-mnli""": """https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt""", """facebook/bart-large-cnn""": """https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt""", """facebook/bart-large-xsum""": """https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt""", """yjernite/bart_eli5""": """https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt""", }, """tokenizer_file""": { """facebook/bart-base""": """https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json""", """facebook/bart-large""": """https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json""", """facebook/bart-large-mnli""": """https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json""", """facebook/bart-large-cnn""": """https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json""", """facebook/bart-large-xsum""": """https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json""", """yjernite/bart_eli5""": """https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json""", }, } __snake_case = { """facebook/bart-base""": 10_24, """facebook/bart-large""": 10_24, """facebook/bart-large-mnli""": 10_24, """facebook/bart-large-cnn""": 10_24, """facebook/bart-large-xsum""": 10_24, """yjernite/bart_eli5""": 10_24, } class lowercase__ ( _UpperCAmelCase ): A__ : Tuple =VOCAB_FILES_NAMES A__ : Any =PRETRAINED_VOCAB_FILES_MAP A__ : str =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES A__ : Tuple =["""input_ids""", """attention_mask"""] A__ : Optional[int] =BartTokenizer def __init__( self : str , UpperCAmelCase_ : Optional[Any]=None , UpperCAmelCase_ : int=None , UpperCAmelCase_ : str=None , UpperCAmelCase_ : Optional[Any]="replace" , UpperCAmelCase_ : int="<s>" , UpperCAmelCase_ : List[Any]="</s>" , UpperCAmelCase_ : int="</s>" , UpperCAmelCase_ : Tuple="<s>" , UpperCAmelCase_ : Any="<unk>" , UpperCAmelCase_ : Any="<pad>" , UpperCAmelCase_ : Optional[Any]="<mask>" , UpperCAmelCase_ : Optional[int]=False , UpperCAmelCase_ : List[str]=True , **UpperCAmelCase_ : List[Any] , ): super().__init__( UpperCAmelCase_ , UpperCAmelCase_ , tokenizer_file=UpperCAmelCase_ , errors=UpperCAmelCase_ , bos_token=UpperCAmelCase_ , eos_token=UpperCAmelCase_ , sep_token=UpperCAmelCase_ , cls_token=UpperCAmelCase_ , unk_token=UpperCAmelCase_ , pad_token=UpperCAmelCase_ , mask_token=UpperCAmelCase_ , add_prefix_space=UpperCAmelCase_ , trim_offsets=UpperCAmelCase_ , **UpperCAmelCase_ , ) SCREAMING_SNAKE_CASE__ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('add_prefix_space' , UpperCAmelCase_ ) != add_prefix_space: SCREAMING_SNAKE_CASE__ = getattr(UpperCAmelCase_ , pre_tok_state.pop('type' ) ) SCREAMING_SNAKE_CASE__ = add_prefix_space SCREAMING_SNAKE_CASE__ = pre_tok_class(**UpperCAmelCase_ ) SCREAMING_SNAKE_CASE__ = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` SCREAMING_SNAKE_CASE__ = 'post_processor' SCREAMING_SNAKE_CASE__ = getattr(self.backend_tokenizer , UpperCAmelCase_ , UpperCAmelCase_ ) if tokenizer_component_instance: SCREAMING_SNAKE_CASE__ = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: SCREAMING_SNAKE_CASE__ = tuple(state['sep'] ) if "cls" in state: SCREAMING_SNAKE_CASE__ = tuple(state['cls'] ) SCREAMING_SNAKE_CASE__ = False if state.get('add_prefix_space' , UpperCAmelCase_ ) != add_prefix_space: SCREAMING_SNAKE_CASE__ = add_prefix_space SCREAMING_SNAKE_CASE__ = True if state.get('trim_offsets' , UpperCAmelCase_ ) != trim_offsets: SCREAMING_SNAKE_CASE__ = trim_offsets SCREAMING_SNAKE_CASE__ = True if changes_to_apply: SCREAMING_SNAKE_CASE__ = getattr(UpperCAmelCase_ , state.pop('type' ) ) SCREAMING_SNAKE_CASE__ = component_class(**UpperCAmelCase_ ) setattr(self.backend_tokenizer , UpperCAmelCase_ , UpperCAmelCase_ ) @property def A_ ( self : Tuple ): if self._mask_token is None: if self.verbose: logger.error('Using mask_token, but it is not set yet.' ) return None return str(self._mask_token ) @mask_token.setter def A_ ( self : Any , UpperCAmelCase_ : List[Any] ): SCREAMING_SNAKE_CASE__ = AddedToken(UpperCAmelCase_ , lstrip=UpperCAmelCase_ , rstrip=UpperCAmelCase_ ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_ ) else value SCREAMING_SNAKE_CASE__ = value def A_ ( self : List[str] , *UpperCAmelCase_ : Tuple , **UpperCAmelCase_ : str ): SCREAMING_SNAKE_CASE__ = kwargs.get('is_split_into_words' , UpperCAmelCase_ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' 'to use it with pretokenized inputs.' ) return super()._batch_encode_plus(*UpperCAmelCase_ , **UpperCAmelCase_ ) def A_ ( self : List[str] , *UpperCAmelCase_ : Dict , **UpperCAmelCase_ : int ): SCREAMING_SNAKE_CASE__ = kwargs.get('is_split_into_words' , UpperCAmelCase_ ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F'You need to instantiate {self.__class__.__name__} with add_prefix_space=True ' 'to use it with pretokenized inputs.' ) return super()._encode_plus(*UpperCAmelCase_ , **UpperCAmelCase_ ) def A_ ( self : List[str] , UpperCAmelCase_ : str , UpperCAmelCase_ : Optional[str] = None ): SCREAMING_SNAKE_CASE__ = self._tokenizer.model.save(UpperCAmelCase_ , name=UpperCAmelCase_ ) return tuple(UpperCAmelCase_ ) def A_ ( self : Optional[Any] , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Union[str, Any]=None ): SCREAMING_SNAKE_CASE__ = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def A_ ( self : str , UpperCAmelCase_ : List[int] , UpperCAmelCase_ : Optional[List[int]] = None ): SCREAMING_SNAKE_CASE__ = [self.sep_token_id] SCREAMING_SNAKE_CASE__ = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
176
1
"""simple docstring""" import argparse import dataclasses import json import logging import os import shutil from typing import List, Optional import datasets from accelerate import Accelerator from datasets import load_dataset from finetuning import finetune from tqdm.auto import tqdm import transformers from transformers import AutoConfig, set_seed from transformers.trainer_utils import IntervalStrategy UpperCamelCase_ = logging.getLogger(__name__) UpperCamelCase_ = 'pytorch_model.bin' @dataclasses.dataclass class snake_case : a_ : str = dataclasses.field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models."""} ) a_ : Optional[str] = dataclasses.field( default=SCREAMING_SNAKE_CASE_ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co."""} , ) @dataclasses.dataclass class snake_case : a_ : str = dataclasses.field(metadata={"""help""": """A csv or a json file containing the training data."""} ) a_ : str = dataclasses.field(metadata={"""help""": """A csv or a json file containing the data to predict on."""} ) a_ : Optional[str] = dataclasses.field( default=SCREAMING_SNAKE_CASE_ , metadata={"""help""": """A csv or a json file containing the validation data."""} ) a_ : Optional[str] = dataclasses.field( default=SCREAMING_SNAKE_CASE_ , metadata={"""help""": """The name of the task to train on."""} , ) a_ : Optional[List[str]] = dataclasses.field( default=SCREAMING_SNAKE_CASE_ , metadata={"""help""": """The list of labels for the task."""} ) @dataclasses.dataclass class snake_case : a_ : str = dataclasses.field( metadata={"""help""": """The output directory where the model predictions and checkpoints will be written."""} ) a_ : Optional[str] = dataclasses.field( default="""accuracy""" , metadata={"""help""": """The evaluation metric used for the task."""} ) a_ : Optional[str] = dataclasses.field( default="""no""" , metadata={ """help""": """The evaluation strategy to adopt during training. Possible values are: [\"no\", \"step\", \"epoch]""" } , ) a_ : Optional[int] = dataclasses.field( default=10 , metadata={"""help""": """Number of evaluation calls with no improvement after which training will be stopped."""} , ) a_ : Optional[float] = dataclasses.field( default=0.0 , metadata={ """help""": """How much the specified evaluation metric must improve to satisfy early stopping conditions.""" } , ) a_ : Optional[bool] = dataclasses.field( default=SCREAMING_SNAKE_CASE_ , metadata={"""help""": """Whether to filter the pseudo-labeled data based on the confidence score."""} , ) a_ : Optional[bool] = dataclasses.field( default=SCREAMING_SNAKE_CASE_ , metadata={"""help""": """Whether to filter the pseudo-labeled data based on the validation performance."""} , ) a_ : Optional[bool] = dataclasses.field( default=SCREAMING_SNAKE_CASE_ , metadata={"""help""": """Whether to fine-tune on labeled data after pseudo training."""} , ) a_ : Optional[float] = dataclasses.field( default=0.0 , metadata={"""help""": """Confidence threshold for pseudo-labeled data filtering."""} , ) a_ : Optional[int] = dataclasses.field( default=100 , metadata={"""help""": """Number of evaluation calls with no improvement after which training will be stopped."""} , ) a_ : Optional[int] = dataclasses.field( default=SCREAMING_SNAKE_CASE_ , metadata={"""help""": """Random seed for initialization."""} , ) def UpperCamelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) ->Dict: """simple docstring""" a_ = datasets.concatenate_datasets([infer_input, infer_output] , axis=1 ) if args.do_filter_by_confidence: a_ = dataset.filter(lambda UpperCAmelCase : example["probability"] > args.confidence_threshold ) if args.do_filter_by_val_performance: assert eval_result >= 0.0 and eval_result <= 1.0 a_ = int(eval_result * len(UpperCAmelCase ) ) print(UpperCAmelCase ) a_ = dataset.sort("probability" , reverse=UpperCAmelCase ) a_ = dataset.select(range(UpperCAmelCase ) ) a_ = dataset.remove_columns(["label", "probability"] ) a_ = dataset.rename_column("prediction" , "label" ) a_ = dataset.map(lambda UpperCAmelCase : {"label": idalabel[example["label"]]} ) a_ = dataset.shuffle(seed=args.seed ) a_ = os.path.join(UpperCAmelCase , F'''train_pseudo.{args.data_file_extension}''' ) if args.data_file_extension == "csv": dataset.to_csv(UpperCAmelCase , index=UpperCAmelCase ) else: dataset.to_json(UpperCAmelCase ) def UpperCamelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , **UpperCAmelCase ) ->List[Any]: """simple docstring""" a_ = Accelerator() # Make one log on every process with the configuration for debugging. logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO , ) logger.info(accelerator.state ) # Setup logging, we only want one process per machine to log things on the # screen. accelerator.is_local_main_process is only True for one process per # machine. logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR ) if accelerator.is_local_main_process: datasets.utils.logging.set_verbosity_warning() transformers.utils.logging.set_verbosity_info() else: datasets.utils.logging.set_verbosity_error() transformers.utils.logging.set_verbosity_error() a_ = STModelArguments(model_name_or_path=UpperCAmelCase ) a_ = STDataArguments(train_file=UpperCAmelCase , infer_file=UpperCAmelCase ) a_ = STTrainingArguments(output_dir=UpperCAmelCase ) a_ = argparse.Namespace() for arg_class in (model_args, data_args, training_args): for key, value in vars(UpperCAmelCase ).items(): setattr(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) for key, value in kwargs.items(): if hasattr(UpperCAmelCase , UpperCAmelCase ): setattr(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) # Sanity checks a_ = {} a_ = None # You need to provide the training data and the data to predict on assert args.train_file is not None assert args.infer_file is not None a_ = args.train_file a_ = args.infer_file if args.evaluation_strategy != IntervalStrategy.NO.value: assert args.eval_file is not None a_ = args.eval_file for key in data_files: a_ = data_files[key].split("." )[-1] assert extension in ["csv", "json"], F'''`{key}_file` should be a csv or a json file.''' if args.data_file_extension is None: a_ = extension else: assert extension == args.data_file_extension, F'''`{key}_file` should be a {args.data_file_extension} file`.''' assert ( args.eval_metric in datasets.list_metrics() ), F'''{args.eval_metric} not in the list of supported metrics {datasets.list_metrics()}.''' # If passed along, set the training seed now. if args.seed is not None: set_seed(args.seed ) logger.info("Creating the initial data directory for self-training..." ) a_ = F'''{args.output_dir}/self-train_iter-{{}}'''.format a_ = data_dir_format(0 ) if accelerator.is_main_process: if args.output_dir is not None: os.makedirs(args.output_dir , exist_ok=UpperCAmelCase ) os.makedirs(UpperCAmelCase , exist_ok=UpperCAmelCase ) accelerator.wait_for_everyone() a_ = None a_ = None a_ = 0 a_ = False # Show the progress bar a_ = tqdm(range(args.max_selftrain_iterations ) , disable=not accelerator.is_local_main_process ) # Self-train for iteration in range(0 , int(args.max_selftrain_iterations ) ): a_ = data_dir_format(UpperCAmelCase ) assert os.path.exists(UpperCAmelCase ) # Stage 1: initial fine-tuning for iteration = 0 or pseudo-training for # iteration > 0 a_ = os.path.join(UpperCAmelCase , "stage-1" ) a_ = { "accelerator": accelerator, "model_name_or_path": args.model_name_or_path, "cache_dir": args.cache_dir, "do_train": True, "train_file": data_files["train"] if iteration == 0 else data_files["train_pseudo"], "do_eval": True if args.eval_file is not None else False, "eval_file": data_files["eval"], "do_predict": True, "infer_file": data_files["infer"], "task_name": args.task_name, "label_list": args.label_list, "output_dir": current_output_dir, "eval_metric": args.eval_metric, "evaluation_strategy": args.evaluation_strategy, "early_stopping_patience": args.early_stopping_patience, "early_stopping_threshold": args.early_stopping_threshold, "seed": args.seed, } # Add additional training arguments for key, value in kwargs.items(): if key not in arguments_dict and not hasattr(UpperCAmelCase , UpperCAmelCase ): arguments_dict.update({key: value} ) a_ = os.path.join(UpperCAmelCase , "best-checkpoint" , UpperCAmelCase ) if os.path.exists(UpperCAmelCase ): logger.info( "Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 1." , UpperCAmelCase , UpperCAmelCase , ) else: logger.info("***** Running self-training: iteration: %d, stage: 1 *****" , UpperCAmelCase ) finetune(**UpperCAmelCase ) accelerator.wait_for_everyone() assert os.path.exists(UpperCAmelCase ) logger.info("Self-training job completed: iteration: %d, stage: 1." , UpperCAmelCase ) if iteration > 0 and args.finetune_on_labeled_data: # Stage 2 (optional): fine-tuning on the original labeled data a_ = os.path.join(UpperCAmelCase , "best-checkpoint" ) a_ = os.path.join(UpperCAmelCase , "stage-2" ) # Update arguments_dict a_ = model_path a_ = data_files["train"] a_ = current_output_dir a_ = os.path.join(UpperCAmelCase , "best-checkpoint" , UpperCAmelCase ) if os.path.exists(UpperCAmelCase ): logger.info( "Found existing model checkpoint at %s. Skipping self-training: iteration: %d, stage: 2." , UpperCAmelCase , UpperCAmelCase , ) else: logger.info("***** Running self-training: iteration: %d, stage: 2 *****" , UpperCAmelCase ) finetune(**UpperCAmelCase ) accelerator.wait_for_everyone() assert os.path.exists(UpperCAmelCase ) logger.info("Self-training job completed: iteration: %d, stage: 2." , UpperCAmelCase ) a_ = iteration a_ = data_dir_format(iteration + 1 ) a_ = AutoConfig.from_pretrained(os.path.join(UpperCAmelCase , "best-checkpoint" ) ) a_ = config.idalabel a_ = os.path.join(UpperCAmelCase , "eval_results_best-checkpoint.json" ) a_ = os.path.join(UpperCAmelCase , "test_results_best-checkpoint.json" ) assert os.path.exists(UpperCAmelCase ) with open(UpperCAmelCase , "r" ) as f: a_ = float(json.load(UpperCAmelCase )[args.eval_metric] ) a_ = os.path.join(UpperCAmelCase , "infer_output_best-checkpoint.csv" ) assert os.path.exists(UpperCAmelCase ) # Loading the dataset from local csv or json files. a_ = load_dataset(args.data_file_extension , data_files={"data": data_files["infer"]} )["data"] a_ = load_dataset("csv" , data_files={"data": infer_output_file} )["data"] if accelerator.is_main_process: os.makedirs(UpperCAmelCase , exist_ok=UpperCAmelCase ) shutil.copy(UpperCAmelCase , os.path.join(UpperCAmelCase , F'''eval_results_iter-{iteration}.json''' ) ) if os.path.exists(UpperCAmelCase ): shutil.copy(UpperCAmelCase , os.path.join(UpperCAmelCase , F'''test_results_iter-{iteration}.json''' ) ) create_pseudo_labeled_data(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) accelerator.wait_for_everyone() a_ = os.path.join(UpperCAmelCase , F'''train_pseudo.{args.data_file_extension}''' ) if args.evaluation_strategy != IntervalStrategy.NO.value: a_ = eval_result if best_iteration is None: a_ = new_iteration a_ = new_eval_result else: if new_eval_result - best_eval_result > args.early_stopping_threshold: a_ = new_iteration a_ = new_eval_result a_ = 0 else: if new_eval_result == best_eval_result: a_ = new_iteration a_ = new_eval_result early_stopping_patience_counter += 1 if early_stopping_patience_counter >= args.early_stopping_patience: a_ = True progress_bar.update(1 ) if should_training_stop: break if best_iteration is not None: # Save the best iteration logger.info("Best iteration: %d" , UpperCAmelCase ) logger.info("Best evaluation result: %s = %f" , args.eval_metric , UpperCAmelCase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(UpperCAmelCase , F'''eval_results_iter-{iteration}.json''' ) , os.path.join(UpperCAmelCase , "eval_results_best-iteration.json" ) , ) else: # Assume that the last iteration is the best logger.info("Best iteration: %d" , args.max_selftrain_iterations - 1 ) logger.info("Best evaluation result: %s = %f" , args.eval_metric , UpperCAmelCase ) accelerator.wait_for_everyone() if accelerator.is_main_process: shutil.copy( os.path.join(UpperCAmelCase , F'''eval_results_iter-{args.max_selftrain_iterations - 1}.json''' ) , os.path.join(UpperCAmelCase , "eval_results_best-iteration.json" ) , )
303
"""simple docstring""" import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DetrConfig, DetrForObjectDetection, DetrForSegmentation, DetrImageProcessor, ResNetConfig from transformers.utils import logging logging.set_verbosity_info() UpperCamelCase_ = logging.get_logger(__name__) def UpperCamelCase ( UpperCAmelCase ) ->Union[str, Any]: """simple docstring""" if "resnet-50" in model_name: a_ = ResNetConfig.from_pretrained("microsoft/resnet-50" ) elif "resnet-101" in model_name: a_ = ResNetConfig.from_pretrained("microsoft/resnet-101" ) else: raise ValueError("Model name should include either resnet50 or resnet101" ) a_ = DetrConfig(use_timm_backbone=UpperCAmelCase , backbone_config=UpperCAmelCase ) # set label attributes a_ = "panoptic" in model_name if is_panoptic: a_ = 250 else: a_ = 91 a_ = "huggingface/label-files" a_ = "coco-detection-id2label.json" a_ = json.load(open(hf_hub_download(UpperCAmelCase , UpperCAmelCase , repo_type="dataset" ) , "r" ) ) a_ = {int(UpperCAmelCase ): v for k, v in idalabel.items()} a_ = idalabel a_ = {v: k for k, v in idalabel.items()} return config, is_panoptic def UpperCamelCase ( UpperCAmelCase ) ->List[str]: """simple docstring""" a_ = [] # stem # fmt: off rename_keys.append(("backbone.0.body.conv1.weight", "backbone.conv_encoder.model.embedder.embedder.convolution.weight") ) rename_keys.append(("backbone.0.body.bn1.weight", "backbone.conv_encoder.model.embedder.embedder.normalization.weight") ) rename_keys.append(("backbone.0.body.bn1.bias", "backbone.conv_encoder.model.embedder.embedder.normalization.bias") ) rename_keys.append(("backbone.0.body.bn1.running_mean", "backbone.conv_encoder.model.embedder.embedder.normalization.running_mean") ) rename_keys.append(("backbone.0.body.bn1.running_var", "backbone.conv_encoder.model.embedder.embedder.normalization.running_var") ) # stages for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): # shortcut if layer_idx == 0: rename_keys.append( ( F'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.0.weight''', F'''backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.convolution.weight''', ) ) rename_keys.append( ( F'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.weight''', F'''backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.weight''', ) ) rename_keys.append( ( F'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.bias''', F'''backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.bias''', ) ) rename_keys.append( ( F'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_mean''', F'''backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_mean''', ) ) rename_keys.append( ( F'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.downsample.1.running_var''', F'''backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.shortcut.normalization.running_var''', ) ) # 3 convs for i in range(3 ): rename_keys.append( ( F'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.conv{i+1}.weight''', F'''backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.convolution.weight''', ) ) rename_keys.append( ( F'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.weight''', F'''backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.weight''', ) ) rename_keys.append( ( F'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.bias''', F'''backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.bias''', ) ) rename_keys.append( ( F'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_mean''', F'''backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_mean''', ) ) rename_keys.append( ( F'''backbone.0.body.layer{stage_idx + 1}.{layer_idx}.bn{i+1}.running_var''', F'''backbone.conv_encoder.model.encoder.stages.{stage_idx}.layers.{layer_idx}.layer.{i}.normalization.running_var''', ) ) # fmt: on for i in range(config.encoder_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append( ( F'''transformer.encoder.layers.{i}.self_attn.out_proj.weight''', F'''encoder.layers.{i}.self_attn.out_proj.weight''', ) ) rename_keys.append( (F'''transformer.encoder.layers.{i}.self_attn.out_proj.bias''', F'''encoder.layers.{i}.self_attn.out_proj.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.linear1.weight''', F'''encoder.layers.{i}.fc1.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.linear1.bias''', F'''encoder.layers.{i}.fc1.bias''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.linear2.weight''', F'''encoder.layers.{i}.fc2.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.linear2.bias''', F'''encoder.layers.{i}.fc2.bias''') ) rename_keys.append( (F'''transformer.encoder.layers.{i}.norm1.weight''', F'''encoder.layers.{i}.self_attn_layer_norm.weight''') ) rename_keys.append( (F'''transformer.encoder.layers.{i}.norm1.bias''', F'''encoder.layers.{i}.self_attn_layer_norm.bias''') ) rename_keys.append( (F'''transformer.encoder.layers.{i}.norm2.weight''', F'''encoder.layers.{i}.final_layer_norm.weight''') ) rename_keys.append((F'''transformer.encoder.layers.{i}.norm2.bias''', F'''encoder.layers.{i}.final_layer_norm.bias''') ) # decoder layers: 2 times output projection, 2 feedforward neural networks and 3 layernorms rename_keys.append( ( F'''transformer.decoder.layers.{i}.self_attn.out_proj.weight''', F'''decoder.layers.{i}.self_attn.out_proj.weight''', ) ) rename_keys.append( (F'''transformer.decoder.layers.{i}.self_attn.out_proj.bias''', F'''decoder.layers.{i}.self_attn.out_proj.bias''') ) rename_keys.append( ( F'''transformer.decoder.layers.{i}.multihead_attn.out_proj.weight''', F'''decoder.layers.{i}.encoder_attn.out_proj.weight''', ) ) rename_keys.append( ( F'''transformer.decoder.layers.{i}.multihead_attn.out_proj.bias''', F'''decoder.layers.{i}.encoder_attn.out_proj.bias''', ) ) rename_keys.append((F'''transformer.decoder.layers.{i}.linear1.weight''', F'''decoder.layers.{i}.fc1.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.linear1.bias''', F'''decoder.layers.{i}.fc1.bias''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.linear2.weight''', F'''decoder.layers.{i}.fc2.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.linear2.bias''', F'''decoder.layers.{i}.fc2.bias''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.norm1.weight''', F'''decoder.layers.{i}.self_attn_layer_norm.weight''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.norm1.bias''', F'''decoder.layers.{i}.self_attn_layer_norm.bias''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.norm2.weight''', F'''decoder.layers.{i}.encoder_attn_layer_norm.weight''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.norm2.bias''', F'''decoder.layers.{i}.encoder_attn_layer_norm.bias''') ) rename_keys.append( (F'''transformer.decoder.layers.{i}.norm3.weight''', F'''decoder.layers.{i}.final_layer_norm.weight''') ) rename_keys.append((F'''transformer.decoder.layers.{i}.norm3.bias''', F'''decoder.layers.{i}.final_layer_norm.bias''') ) # convolutional projection + query embeddings + layernorm of decoder + class and bounding box heads rename_keys.extend( [ ("input_proj.weight", "input_projection.weight"), ("input_proj.bias", "input_projection.bias"), ("query_embed.weight", "query_position_embeddings.weight"), ("transformer.decoder.norm.weight", "decoder.layernorm.weight"), ("transformer.decoder.norm.bias", "decoder.layernorm.bias"), ("class_embed.weight", "class_labels_classifier.weight"), ("class_embed.bias", "class_labels_classifier.bias"), ("bbox_embed.layers.0.weight", "bbox_predictor.layers.0.weight"), ("bbox_embed.layers.0.bias", "bbox_predictor.layers.0.bias"), ("bbox_embed.layers.1.weight", "bbox_predictor.layers.1.weight"), ("bbox_embed.layers.1.bias", "bbox_predictor.layers.1.bias"), ("bbox_embed.layers.2.weight", "bbox_predictor.layers.2.weight"), ("bbox_embed.layers.2.bias", "bbox_predictor.layers.2.bias"), ] ) return rename_keys def UpperCamelCase ( UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) ->Union[str, Any]: """simple docstring""" a_ = state_dict.pop(UpperCAmelCase ) a_ = val def UpperCamelCase ( UpperCAmelCase , UpperCAmelCase=False ) ->Optional[Any]: """simple docstring""" a_ = "" if is_panoptic: a_ = "detr." # first: transformer encoder for i in range(6 ): # read in weights + bias of input projection layer (in PyTorch's MultiHeadAttention, this is a single matrix + bias) a_ = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight''' ) a_ = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict a_ = in_proj_weight[:256, :] a_ = in_proj_bias[:256] a_ = in_proj_weight[256:512, :] a_ = in_proj_bias[256:512] a_ = in_proj_weight[-256:, :] a_ = in_proj_bias[-256:] # next: transformer decoder (which is a bit more complex because it also includes cross-attention) for i in range(6 ): # read in weights + bias of input projection layer of self-attention a_ = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight''' ) a_ = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) to the state dict a_ = in_proj_weight[:256, :] a_ = in_proj_bias[:256] a_ = in_proj_weight[256:512, :] a_ = in_proj_bias[256:512] a_ = in_proj_weight[-256:, :] a_ = in_proj_bias[-256:] # read in weights + bias of input projection layer of cross-attention a_ = state_dict.pop( F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight''' ) a_ = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_bias''' ) # next, add query, keys and values (in that order) of cross-attention to the state dict a_ = in_proj_weight_cross_attn[:256, :] a_ = in_proj_bias_cross_attn[:256] a_ = in_proj_weight_cross_attn[256:512, :] a_ = in_proj_bias_cross_attn[256:512] a_ = in_proj_weight_cross_attn[-256:, :] a_ = in_proj_bias_cross_attn[-256:] def UpperCamelCase ( ) ->Dict: """simple docstring""" a_ = "http://images.cocodataset.org/val2017/000000039769.jpg" a_ = Image.open(requests.get(UpperCAmelCase , stream=UpperCAmelCase ).raw ) return im @torch.no_grad() def UpperCamelCase ( UpperCAmelCase , UpperCAmelCase=None , UpperCAmelCase=False ) ->List[str]: """simple docstring""" a_ , a_ = get_detr_config(UpperCAmelCase ) # load original model from torch hub a_ = { "detr-resnet-50": "detr_resnet50", "detr-resnet-101": "detr_resnet101", } logger.info(F'''Converting model {model_name}...''' ) a_ = torch.hub.load("facebookresearch/detr" , model_name_to_original_name[model_name] , pretrained=UpperCAmelCase ).eval() a_ = detr.state_dict() # rename keys for src, dest in create_rename_keys(UpperCAmelCase ): if is_panoptic: a_ = "detr." + src rename_key(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) # query, key and value matrices need special treatment read_in_q_k_v(UpperCAmelCase , is_panoptic=UpperCAmelCase ) # important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them a_ = "detr.model." if is_panoptic else "model." for key in state_dict.copy().keys(): if is_panoptic: if ( key.startswith("detr" ) and not key.startswith("class_labels_classifier" ) and not key.startswith("bbox_predictor" ) ): a_ = state_dict.pop(UpperCAmelCase ) a_ = val elif "class_labels_classifier" in key or "bbox_predictor" in key: a_ = state_dict.pop(UpperCAmelCase ) a_ = val elif key.startswith("bbox_attention" ) or key.startswith("mask_head" ): continue else: a_ = state_dict.pop(UpperCAmelCase ) a_ = val else: if not key.startswith("class_labels_classifier" ) and not key.startswith("bbox_predictor" ): a_ = state_dict.pop(UpperCAmelCase ) a_ = val # finally, create HuggingFace model and load state dict a_ = DetrForSegmentation(UpperCAmelCase ) if is_panoptic else DetrForObjectDetection(UpperCAmelCase ) model.load_state_dict(UpperCAmelCase ) model.eval() # verify our conversion on an image a_ = "coco_panoptic" if is_panoptic else "coco_detection" a_ = DetrImageProcessor(format=UpperCAmelCase ) a_ = processor(images=prepare_img() , return_tensors="pt" ) a_ = encoding["pixel_values"] a_ = detr(UpperCAmelCase ) a_ = model(UpperCAmelCase ) assert torch.allclose(outputs.logits , original_outputs["pred_logits"] , atol=1E-3 ) assert torch.allclose(outputs.pred_boxes , original_outputs["pred_boxes"] , atol=1E-3 ) if is_panoptic: assert torch.allclose(outputs.pred_masks , original_outputs["pred_masks"] , atol=1E-4 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: # Save model and image processor logger.info(F'''Saving PyTorch model and image processor to {pytorch_dump_folder_path}...''' ) Path(UpperCAmelCase ).mkdir(exist_ok=UpperCAmelCase ) model.save_pretrained(UpperCAmelCase ) processor.save_pretrained(UpperCAmelCase ) if push_to_hub: # Upload model and image processor to the hub logger.info("Uploading PyTorch model and image processor to the hub..." ) model.push_to_hub(F'''nielsr/{model_name}''' ) processor.push_to_hub(F'''nielsr/{model_name}''' ) if __name__ == "__main__": UpperCamelCase_ = argparse.ArgumentParser() parser.add_argument( '--model_name', default='detr-resnet-50', type=str, choices=['detr-resnet-50', 'detr-resnet-101'], help='Name of the DETR model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the folder to output PyTorch model.' ) parser.add_argument('--push_to_hub', action='store_true', help='Whether to push the model to the hub or not.') UpperCamelCase_ = parser.parse_args() convert_detr_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
303
1
import random import unittest import numpy as np from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionImgaImgPipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class _A( snake_case__ , unittest.TestCase ): """simple docstring""" UpperCamelCase : Tuple = '''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline''' def UpperCAmelCase_ ( self , _A=0 ): __A : Dict = floats_tensor((1, 3, 128, 128) , rng=random.Random(_A ) ) __A : List[Any] = np.random.RandomState(_A ) __A : str = { 'prompt': 'A painting of a squirrel eating a burger', 'image': image, 'generator': generator, 'num_inference_steps': 3, 'strength': 0.7_5, 'guidance_scale': 7.5, 'output_type': 'numpy', } return inputs def UpperCAmelCase_ ( self ): __A : Dict = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) pipe.set_progress_bar_config(disable=_A ) __A : int = self.get_dummy_inputs() __A : List[Any] = pipe(**_A ).images __A : Optional[Any] = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 128, 128, 3) __A : Dict = np.array([0.6_9_6_4_3, 0.5_8_4_8_4, 0.5_0_3_1_4, 0.5_8_7_6_0, 0.5_5_3_6_8, 0.5_9_6_4_3, 0.5_1_5_2_9, 0.4_1_2_1_7, 0.4_9_0_8_7] ) assert np.abs(image_slice - expected_slice ).max() < 1e-1 def UpperCAmelCase_ ( self ): __A : int = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) __A : List[str] = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=_A ) pipe.set_progress_bar_config(disable=_A ) __A : List[str] = self.get_dummy_inputs() __A : Optional[Any] = pipe(**_A ).images __A : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __A : Union[str, Any] = np.array([0.6_1_7_3_7, 0.5_4_6_4_2, 0.5_3_1_8_3, 0.5_4_4_6_5, 0.5_2_7_4_2, 0.6_0_5_2_5, 0.4_9_9_6_9, 0.4_0_6_5_5, 0.4_8_1_5_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def UpperCAmelCase_ ( self ): __A : Any = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) __A : Optional[Any] = LMSDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=_A ) # warmup pass to apply optimizations __A : Tuple = pipe(**self.get_dummy_inputs() ) __A : Any = self.get_dummy_inputs() __A : Dict = pipe(**_A ).images __A : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __A : int = np.array([0.5_2_7_6_1, 0.5_9_9_7_7, 0.4_9_0_3_3, 0.4_9_6_1_9, 0.5_4_2_8_2, 0.5_0_3_1_1, 0.4_7_6_0_0, 0.4_0_9_1_8, 0.4_5_2_0_3] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def UpperCAmelCase_ ( self ): __A : Optional[int] = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) __A : Any = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=_A ) __A : Optional[Any] = self.get_dummy_inputs() __A : List[Any] = pipe(**_A ).images __A : Union[str, Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __A : Optional[Any] = np.array([0.5_2_9_1_1, 0.6_0_0_0_4, 0.4_9_2_2_9, 0.4_9_8_0_5, 0.5_4_5_0_2, 0.5_0_6_8_0, 0.4_7_7_7_7, 0.4_1_0_2_8, 0.4_5_3_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def UpperCAmelCase_ ( self ): __A : Any = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) __A : Optional[int] = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=_A ) __A : List[Any] = self.get_dummy_inputs() __A : Tuple = pipe(**_A ).images __A : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __A : Any = np.array([0.5_2_9_1_1, 0.6_0_0_0_4, 0.4_9_2_2_9, 0.4_9_8_0_5, 0.5_4_5_0_2, 0.5_0_6_8_0, 0.4_7_7_7_7, 0.4_1_0_2_8, 0.4_5_3_0_4] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def UpperCAmelCase_ ( self ): __A : Any = OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint , provider='CPUExecutionProvider' ) __A : str = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=_A ) __A : int = self.get_dummy_inputs() __A : Dict = pipe(**_A ).images __A : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 128, 128, 3) __A : List[str] = np.array([0.6_5_3_3_1, 0.5_8_2_7_7, 0.4_8_2_0_4, 0.5_6_0_5_9, 0.5_3_6_6_5, 0.5_6_2_3_5, 0.5_0_9_6_9, 0.4_0_0_0_9, 0.4_6_5_5_2] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class _A( unittest.TestCase ): """simple docstring""" @property def UpperCAmelCase_ ( self ): return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def UpperCAmelCase_ ( self ): __A : List[str] = ort.SessionOptions() __A : List[str] = False return options def UpperCAmelCase_ ( self ): __A : Optional[int] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) __A : Any = init_image.resize((768, 512) ) # using the PNDM scheduler by default __A : Any = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'CompVis/stable-diffusion-v1-4' , revision='onnx' , safety_checker=_A , feature_extractor=_A , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_A ) __A : Optional[int] = 'A fantasy landscape, trending on artstation' __A : Any = np.random.RandomState(0 ) __A : Optional[Any] = pipe( prompt=_A , image=_A , strength=0.7_5 , guidance_scale=7.5 , num_inference_steps=10 , generator=_A , output_type='np' , ) __A : Optional[int] = output.images __A : Any = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) __A : Tuple = np.array([0.4_9_0_9, 0.5_0_5_9, 0.5_3_7_2, 0.4_6_2_3, 0.4_8_7_6, 0.5_0_4_9, 0.4_8_2_0, 0.4_9_5_6, 0.5_0_1_9] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def UpperCAmelCase_ ( self ): __A : Optional[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/img2img/sketch-mountains-input.jpg' ) __A : List[str] = init_image.resize((768, 512) ) __A : Union[str, Any] = LMSDiscreteScheduler.from_pretrained( 'runwayml/stable-diffusion-v1-5' , subfolder='scheduler' , revision='onnx' ) __A : int = OnnxStableDiffusionImgaImgPipeline.from_pretrained( 'runwayml/stable-diffusion-v1-5' , revision='onnx' , scheduler=_A , safety_checker=_A , feature_extractor=_A , provider=self.gpu_provider , sess_options=self.gpu_options , ) pipe.set_progress_bar_config(disable=_A ) __A : List[Any] = 'A fantasy landscape, trending on artstation' __A : Optional[Any] = np.random.RandomState(0 ) __A : List[Any] = pipe( prompt=_A , image=_A , strength=0.7_5 , guidance_scale=7.5 , num_inference_steps=20 , generator=_A , output_type='np' , ) __A : str = output.images __A : Union[str, Any] = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 768, 3) __A : str = np.array([0.8_0_4_3, 0.9_2_6, 0.9_5_8_1, 0.8_1_1_9, 0.8_9_5_4, 0.9_1_3, 0.7_2_0_9, 0.7_4_6_3, 0.7_4_3_1] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
280
import argparse import os import gluonnlp as nlp import mxnet as mx import numpy as np import torch from gluonnlp.base import get_home_dir from gluonnlp.model.bert import BERTEncoder from gluonnlp.model.utils import _load_vocab from gluonnlp.vocab import Vocab from packaging import version from torch import nn from transformers import BertConfig, BertForMaskedLM, BertModel, RobertaTokenizer from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.utils import logging if version.parse(nlp.__version__) != version.parse('''0.8.3'''): raise Exception('''requires gluonnlp == 0.8.3''') if version.parse(mx.__version__) != version.parse('''1.5.0'''): raise Exception('''requires mxnet == 1.5.0''') logging.set_verbosity_info() UpperCAmelCase : List[Any] = logging.get_logger(__name__) UpperCAmelCase : Optional[Any] = '''The Nymphenburg Palace is a beautiful palace in Munich!''' def _SCREAMING_SNAKE_CASE ( a , a ) -> Optional[Any]: __A : Any = { 'attention_cell': 'multi_head', 'num_layers': 4, 'units': 10_24, 'hidden_size': 7_68, 'max_length': 5_12, 'num_heads': 8, 'scaled': True, 'dropout': 0.1, 'use_residual': True, 'embed_size': 10_24, 'embed_dropout': 0.1, 'word_embed': None, 'layer_norm_eps': 1e-5, 'token_type_vocab_size': 2, } __A : str = bort_4_8_768_1024_hparams # Let's construct the original Bort model here # Taken from official BERT implementation, see: # https://github.com/alexa/bort/blob/master/bort/bort.py __A : Optional[int] = BERTEncoder( attention_cell=predefined_args['attention_cell'] , num_layers=predefined_args['num_layers'] , units=predefined_args['units'] , hidden_size=predefined_args['hidden_size'] , max_length=predefined_args['max_length'] , num_heads=predefined_args['num_heads'] , scaled=predefined_args['scaled'] , dropout=predefined_args['dropout'] , output_attention=a , output_all_encodings=a , use_residual=predefined_args['use_residual'] , activation=predefined_args.get('activation' , 'gelu' ) , layer_norm_eps=predefined_args.get('layer_norm_eps' , a ) , ) # Vocab information needs to be fetched first # It's the same as RoBERTa, so RobertaTokenizer can be used later __A : Union[str, Any] = 'openwebtext_ccnews_stories_books_cased' # Specify download folder to Gluonnlp's vocab __A : Any = os.path.join(get_home_dir() , 'models' ) __A : List[Any] = _load_vocab(a , a , a , cls=a ) __A : Dict = nlp.model.BERTModel( a , len(a ) , units=predefined_args['units'] , embed_size=predefined_args['embed_size'] , embed_dropout=predefined_args['embed_dropout'] , word_embed=predefined_args['word_embed'] , use_pooler=a , use_token_type_embed=a , token_type_vocab_size=predefined_args['token_type_vocab_size'] , use_classifier=a , use_decoder=a , ) original_bort.load_parameters(a , cast_dtype=a , ignore_extra=a ) __A : Union[str, Any] = original_bort._collect_params_with_prefix() # Build our config 🤗 __A : Any = { 'architectures': ['BertForMaskedLM'], 'attention_probs_dropout_prob': predefined_args['dropout'], 'hidden_act': 'gelu', 'hidden_dropout_prob': predefined_args['dropout'], 'hidden_size': predefined_args['embed_size'], 'initializer_range': 0.02, 'intermediate_size': predefined_args['hidden_size'], 'layer_norm_eps': predefined_args['layer_norm_eps'], 'max_position_embeddings': predefined_args['max_length'], 'model_type': 'bort', 'num_attention_heads': predefined_args['num_heads'], 'num_hidden_layers': predefined_args['num_layers'], 'pad_token_id': 1, # 2 = BERT, 1 = RoBERTa 'type_vocab_size': 1, # 2 = BERT, 1 = RoBERTa 'vocab_size': len(a ), } __A : int = BertConfig.from_dict(a ) __A : Union[str, Any] = BertForMaskedLM(a ) hf_bort_model.eval() # Parameter mapping table (Gluonnlp to Transformers) # * denotes layer index # # | Gluon Parameter | Transformers Parameter # | -------------------------------------------------------------- | ---------------------- # | `encoder.layer_norm.beta` | `bert.embeddings.LayerNorm.bias` # | `encoder.layer_norm.gamma` | `bert.embeddings.LayerNorm.weight` # | `encoder.position_weight` | `bert.embeddings.position_embeddings.weight` # | `word_embed.0.weight` | `bert.embeddings.word_embeddings.weight` # | `encoder.transformer_cells.*.attention_cell.proj_key.bias` | `bert.encoder.layer.*.attention.self.key.bias` # | `encoder.transformer_cells.*.attention_cell.proj_key.weight` | `bert.encoder.layer.*.attention.self.key.weight` # | `encoder.transformer_cells.*.attention_cell.proj_query.bias` | `bert.encoder.layer.*.attention.self.query.bias` # | `encoder.transformer_cells.*.attention_cell.proj_query.weight` | `bert.encoder.layer.*.attention.self.query.weight` # | `encoder.transformer_cells.*.attention_cell.proj_value.bias` | `bert.encoder.layer.*.attention.self.value.bias` # | `encoder.transformer_cells.*.attention_cell.proj_value.weight` | `bert.encoder.layer.*.attention.self.value.weight` # | `encoder.transformer_cells.*.ffn.ffn_2.bias` | `bert.encoder.layer.*.attention.output.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_2.weight` | `bert.encoder.layer.*.attention.output.dense.weight` # | `encoder.transformer_cells.*.layer_norm.beta` | `bert.encoder.layer.*.attention.output.LayerNorm.bias` # | `encoder.transformer_cells.*.layer_norm.gamma` | `bert.encoder.layer.*.attention.output.LayerNorm.weight` # | `encoder.transformer_cells.*.ffn.ffn_1.bias` | `bert.encoder.layer.*.intermediate.dense.bias` # | `encoder.transformer_cells.*.ffn.ffn_1.weight` | `bert.encoder.layer.*.intermediate.dense.weight` # | `encoder.transformer_cells.*.ffn.layer_norm.beta` | `bert.encoder.layer.*.output.LayerNorm.bias` # | `encoder.transformer_cells.*.ffn.layer_norm.gamma` | `bert.encoder.layer.*.output.LayerNorm.weight` # | `encoder.transformer_cells.*.proj.bias` | `bert.encoder.layer.*.output.dense.bias` # | `encoder.transformer_cells.*.proj.weight` | `bert.encoder.layer.*.output.dense.weight` # Helper function to convert MXNET Arrays to PyTorch def to_torch(a ) -> nn.Parameter: return nn.Parameter(torch.FloatTensor(mx_array.data().asnumpy() ) ) # Check param shapes and map new HF param back def check_and_map_params(a , a ): __A : Tuple = hf_param.shape __A : str = to_torch(params[gluon_param] ) __A : Union[str, Any] = gluon_param.shape assert ( shape_hf == shape_gluon ), F"""The gluon parameter {gluon_param} has shape {shape_gluon}, but expects shape {shape_hf} for Transformers""" return gluon_param __A : str = check_and_map_params( hf_bort_model.bert.embeddings.word_embeddings.weight , 'word_embed.0.weight' ) __A : Tuple = check_and_map_params( hf_bort_model.bert.embeddings.position_embeddings.weight , 'encoder.position_weight' ) __A : List[str] = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.bias , 'encoder.layer_norm.beta' ) __A : Tuple = check_and_map_params( hf_bort_model.bert.embeddings.LayerNorm.weight , 'encoder.layer_norm.gamma' ) # Inspired by RoBERTa conversion script, we just zero them out (Bort does not use them) __A : Tuple = torch.zeros_like( hf_bort_model.bert.embeddings.token_type_embeddings.weight.data ) for i in range(hf_bort_config.num_hidden_layers ): __A : BertLayer = hf_bort_model.bert.encoder.layer[i] # self attention __A : BertSelfAttention = layer.attention.self __A : Optional[Any] = check_and_map_params( self_attn.key.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_key.bias""" ) __A : Optional[int] = check_and_map_params( self_attn.key.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_key.weight""" ) __A : Union[str, Any] = check_and_map_params( self_attn.query.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_query.bias""" ) __A : Optional[Any] = check_and_map_params( self_attn.query.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_query.weight""" ) __A : Union[str, Any] = check_and_map_params( self_attn.value.bias.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_value.bias""" ) __A : Optional[int] = check_and_map_params( self_attn.value.weight.data , F"""encoder.transformer_cells.{i}.attention_cell.proj_value.weight""" ) # self attention output __A : BertSelfOutput = layer.attention.output __A : Tuple = check_and_map_params( self_output.dense.bias , F"""encoder.transformer_cells.{i}.proj.bias""" ) __A : int = check_and_map_params( self_output.dense.weight , F"""encoder.transformer_cells.{i}.proj.weight""" ) __A : List[Any] = check_and_map_params( self_output.LayerNorm.bias , F"""encoder.transformer_cells.{i}.layer_norm.beta""" ) __A : str = check_and_map_params( self_output.LayerNorm.weight , F"""encoder.transformer_cells.{i}.layer_norm.gamma""" ) # intermediate __A : BertIntermediate = layer.intermediate __A : int = check_and_map_params( intermediate.dense.bias , F"""encoder.transformer_cells.{i}.ffn.ffn_1.bias""" ) __A : List[Any] = check_and_map_params( intermediate.dense.weight , F"""encoder.transformer_cells.{i}.ffn.ffn_1.weight""" ) # output __A : BertOutput = layer.output __A : List[Any] = check_and_map_params( bert_output.dense.bias , F"""encoder.transformer_cells.{i}.ffn.ffn_2.bias""" ) __A : Dict = check_and_map_params( bert_output.dense.weight , F"""encoder.transformer_cells.{i}.ffn.ffn_2.weight""" ) __A : Optional[int] = check_and_map_params( bert_output.LayerNorm.bias , F"""encoder.transformer_cells.{i}.ffn.layer_norm.beta""" ) __A : Dict = check_and_map_params( bert_output.LayerNorm.weight , F"""encoder.transformer_cells.{i}.ffn.layer_norm.gamma""" ) # Save space and energy 🎄 hf_bort_model.half() # Compare output of both models __A : Any = RobertaTokenizer.from_pretrained('roberta-base' ) __A : List[str] = tokenizer.encode_plus(a )['input_ids'] # Get gluon output __A : List[str] = mx.nd.array([input_ids] ) __A : Union[str, Any] = original_bort(inputs=a , token_types=[] ) # Get Transformer output (save and reload model again) hf_bort_model.save_pretrained(a ) __A : Optional[Any] = BertModel.from_pretrained(a ) hf_bort_model.eval() __A : Tuple = tokenizer.encode_plus(a , return_tensors='pt' ) __A : Any = hf_bort_model(**a )[0] __A : Union[str, Any] = output_gluon[0].asnumpy() __A : Tuple = output_hf[0].detach().numpy() __A : int = np.max(np.abs(hf_layer - gluon_layer ) ).item() __A : int = np.allclose(a , a , atol=1e-3 ) if success: print('✔️ Both model do output the same tensors' ) else: print('❌ Both model do **NOT** output the same tensors' ) print('Absolute difference is:' , a ) if __name__ == "__main__": UpperCAmelCase : int = argparse.ArgumentParser() # Required parameters parser.add_argument( '''--bort_checkpoint_path''', default=None, type=str, required=True, help='''Path the official Bort params file.''' ) parser.add_argument( '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.''' ) UpperCAmelCase : Dict = parser.parse_args() convert_bort_checkpoint_to_pytorch(args.bort_checkpoint_path, args.pytorch_dump_folder_path)
280
1
"""simple docstring""" __SCREAMING_SNAKE_CASE : Optional[Any] = 256 # Modulus to hash a string __SCREAMING_SNAKE_CASE : Optional[int] = 1_000_003 def _a ( _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> bool: snake_case_ = len(_SCREAMING_SNAKE_CASE ) snake_case_ = len(_SCREAMING_SNAKE_CASE ) if p_len > t_len: return False snake_case_ = 0 snake_case_ = 0 snake_case_ = 1 # Calculating the hash of pattern and substring of text for i in range(_SCREAMING_SNAKE_CASE ): snake_case_ = (ord(pattern[i] ) + p_hash * alphabet_size) % modulus snake_case_ = (ord(text[i] ) + text_hash * alphabet_size) % modulus if i == p_len - 1: continue snake_case_ = (modulus_power * alphabet_size) % modulus for i in range(0 , t_len - p_len + 1 ): if text_hash == p_hash and text[i : i + p_len] == pattern: return True if i == t_len - p_len: continue # Calculate the https://en.wikipedia.org/wiki/Rolling_hash snake_case_ = ( (text_hash - ord(text[i] ) * modulus_power) * alphabet_size + ord(text[i + p_len] ) ) % modulus return False def _a ( ) -> None: snake_case_ = """abc1abc12""" snake_case_ = """alskfjaldsabc1abc1abc12k23adsfabcabc""" snake_case_ = """alskfjaldsk23adsfabcabc""" assert rabin_karp(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) and not rabin_karp(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Test 2) snake_case_ = """ABABX""" snake_case_ = """ABABZABABYABABX""" assert rabin_karp(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Test 3) snake_case_ = """AAAB""" snake_case_ = """ABAAAAAB""" assert rabin_karp(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Test 4) snake_case_ = """abcdabcy""" snake_case_ = """abcxabcdabxabcdabcdabcy""" assert rabin_karp(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) # Test 5) snake_case_ = """Lü""" snake_case_ = """Lüsai""" assert rabin_karp(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) snake_case_ = """Lue""" assert not rabin_karp(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) print("""Success.""" ) if __name__ == "__main__": test_rabin_karp()
369
"""simple docstring""" def _a ( _SCREAMING_SNAKE_CASE ) -> list: if len(_SCREAMING_SNAKE_CASE ) <= 1: return [tuple(_SCREAMING_SNAKE_CASE )] snake_case_ = [] def generate(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , _SCREAMING_SNAKE_CASE ) for i in range(k - 1 ): if k % 2 == 0: # k is even snake_case_ , snake_case_ = arr[k - 1], arr[i] else: # k is odd snake_case_ , snake_case_ = arr[k - 1], arr[0] generate(k - 1 , _SCREAMING_SNAKE_CASE ) generate(len(_SCREAMING_SNAKE_CASE ) , _SCREAMING_SNAKE_CASE ) return res if __name__ == "__main__": __SCREAMING_SNAKE_CASE : List[Any] = input('Enter numbers separated by a comma:\n').strip() __SCREAMING_SNAKE_CASE : str = [int(item) for item in user_input.split(',')] print(heaps(arr))
233
0
"""simple docstring""" def lowercase (snake_case__ : list[int] ) -> int: '''simple docstring''' if not numbers: return 0 if not isinstance(snake_case__ , (list, tuple) ) or not all( isinstance(snake_case__ , snake_case__ ) for number in numbers ): raise ValueError("""numbers must be an iterable of integers""" ) lowerCAmelCase = lowerCAmelCase = lowerCAmelCase = numbers[0] for i in range(1 , len(snake_case__ ) ): # update the maximum and minimum subarray products lowerCAmelCase = numbers[i] if number < 0: lowerCAmelCase , lowerCAmelCase = min_till_now, max_till_now lowerCAmelCase = max(snake_case__ , max_till_now * number ) lowerCAmelCase = min(snake_case__ , min_till_now * number ) # update the maximum product found till now lowerCAmelCase = max(snake_case__ , snake_case__ ) return max_prod
155
"""simple docstring""" from __future__ import annotations from collections.abc import Generator import requests from bsa import BeautifulSoup a = 'https://www.indeed.co.in/jobs?q=mobile+app+development&l=' def lowercase (snake_case__ : str = "mumbai" ) -> Generator[tuple[str, str], None, None]: '''simple docstring''' lowerCAmelCase = BeautifulSoup(requests.get(url + location ).content , """html.parser""" ) # This attribute finds out all the specifics listed in a job for job in soup.find_all("""div""" , attrs={"""data-tn-component""": """organicJob"""} ): lowerCAmelCase = job.find("""a""" , attrs={"""data-tn-element""": """jobTitle"""} ).text.strip() lowerCAmelCase = job.find("""span""" , {"""class""": """company"""} ).text.strip() yield job_title, company_name if __name__ == "__main__": for i, job in enumerate(fetch_jobs('Bangalore'), 1): print(f"""Job {i:>2} is {job[0]} at {job[1]}""")
155
1
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import normalizers from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_distilbert import DistilBertTokenizer __snake_case = logging.get_logger(__name__) __snake_case = {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''} __snake_case = { '''vocab_file''': { '''distilbert-base-uncased''': '''https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt''', '''distilbert-base-uncased-distilled-squad''': ( '''https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt''' ), '''distilbert-base-cased''': '''https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt''', '''distilbert-base-cased-distilled-squad''': ( '''https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt''' ), '''distilbert-base-german-cased''': '''https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt''', '''distilbert-base-multilingual-cased''': ( '''https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt''' ), }, '''tokenizer_file''': { '''distilbert-base-uncased''': '''https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json''', '''distilbert-base-uncased-distilled-squad''': ( '''https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json''' ), '''distilbert-base-cased''': '''https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json''', '''distilbert-base-cased-distilled-squad''': ( '''https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json''' ), '''distilbert-base-german-cased''': ( '''https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json''' ), '''distilbert-base-multilingual-cased''': ( '''https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json''' ), }, } __snake_case = { '''distilbert-base-uncased''': 512, '''distilbert-base-uncased-distilled-squad''': 512, '''distilbert-base-cased''': 512, '''distilbert-base-cased-distilled-squad''': 512, '''distilbert-base-german-cased''': 512, '''distilbert-base-multilingual-cased''': 512, } __snake_case = { '''distilbert-base-uncased''': {'''do_lower_case''': True}, '''distilbert-base-uncased-distilled-squad''': {'''do_lower_case''': True}, '''distilbert-base-cased''': {'''do_lower_case''': False}, '''distilbert-base-cased-distilled-squad''': {'''do_lower_case''': False}, '''distilbert-base-german-cased''': {'''do_lower_case''': False}, '''distilbert-base-multilingual-cased''': {'''do_lower_case''': False}, } class lowercase ( A__ ): """simple docstring""" _a = VOCAB_FILES_NAMES _a = PRETRAINED_VOCAB_FILES_MAP _a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES _a = PRETRAINED_INIT_CONFIGURATION _a = ['input_ids', 'attention_mask'] _a = DistilBertTokenizer def __init__( self , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=True , UpperCamelCase_="[UNK]" , UpperCamelCase_="[SEP]" , UpperCamelCase_="[PAD]" , UpperCamelCase_="[CLS]" , UpperCamelCase_="[MASK]" , UpperCamelCase_=True , UpperCamelCase_=None , **UpperCamelCase_ , ): '''simple docstring''' super().__init__( UpperCamelCase_ , tokenizer_file=UpperCamelCase_ , do_lower_case=UpperCamelCase_ , unk_token=UpperCamelCase_ , sep_token=UpperCamelCase_ , pad_token=UpperCamelCase_ , cls_token=UpperCamelCase_ , mask_token=UpperCamelCase_ , tokenize_chinese_chars=UpperCamelCase_ , strip_accents=UpperCamelCase_ , **UpperCamelCase_ , ) UpperCamelCase__ :int = json.loads(self.backend_tokenizer.normalizer.__getstate__() ) if ( normalizer_state.get('''lowercase''' , UpperCamelCase_ ) != do_lower_case or normalizer_state.get('''strip_accents''' , UpperCamelCase_ ) != strip_accents or normalizer_state.get('''handle_chinese_chars''' , UpperCamelCase_ ) != tokenize_chinese_chars ): UpperCamelCase__ :int = getattr(UpperCamelCase_ , normalizer_state.pop('''type''' ) ) UpperCamelCase__ :Optional[Any] = do_lower_case UpperCamelCase__ :Optional[Any] = strip_accents UpperCamelCase__ :List[Any] = tokenize_chinese_chars UpperCamelCase__ :Any = normalizer_class(**UpperCamelCase_ ) UpperCamelCase__ :int = do_lower_case def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_=None ): '''simple docstring''' UpperCamelCase__ :Tuple = [self.cls_token_id] + token_ids_a + [self.sep_token_id] if token_ids_a: output += token_ids_a + [self.sep_token_id] return output def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ = None ): '''simple docstring''' UpperCamelCase__ :List[str] = [self.sep_token_id] UpperCamelCase__ :List[str] = [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 , UpperCamelCase_ , UpperCamelCase_ = None ): '''simple docstring''' UpperCamelCase__ :str = self._tokenizer.model.save(UpperCamelCase_ , name=UpperCamelCase_ ) return tuple(UpperCamelCase_ )
219
'''simple docstring''' # Copyright 2021 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 argparse from .config import config_command_parser from .config_args import default_config_file, load_config_from_file # noqa: F401 from .default import default_command_parser from .update import update_command_parser def a ( __a=None ) -> List[str]: '''simple docstring''' UpperCamelCase__ :Optional[Any] = argparse.ArgumentParser(add_help=__a , allow_abbrev=__a ) # The main config parser UpperCamelCase__ :str = config_command_parser(__a ) # The subparser to add commands to UpperCamelCase__ :Union[str, Any] = config_parser.add_subparsers(title='''subcommands''' , dest='''subcommand''' ) # Then add other parsers with the parent parser default_command_parser(__a , parents=[parent_parser] ) update_command_parser(__a , parents=[parent_parser] ) return config_parser def a ( ) -> Any: '''simple docstring''' UpperCamelCase__ :int = get_config_parser() UpperCamelCase__ :List[Any] = config_parser.parse_args() if not hasattr(__a , '''func''' ): config_parser.print_help() exit(1 ) # Run args.func(__a ) if __name__ == "__main__": main()
219
1
from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class SCREAMING_SNAKE_CASE__ : A_ : int A_ : TreeNode | None = None A_ : TreeNode | None = None snake_case_ = namedtuple('CoinsDistribResult', 'moves excess') def lowerCamelCase__ ( snake_case_ : TreeNode | None ) -> int: if root is None: return 0 # Validation def count_nodes(snake_case_ : TreeNode | None ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(snake_case_ : TreeNode | None ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(snake_case_ ) != count_coins(snake_case_ ): raise ValueError('''The nodes number should be same as the number of coins''' ) # Main calculation def get_distrib(snake_case_ : TreeNode | None ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) __snake_case , __snake_case = get_distrib(node.left ) __snake_case , __snake_case = get_distrib(node.right ) __snake_case = 1 - left_distrib_excess __snake_case = 1 - right_distrib_excess __snake_case = ( left_distrib_moves + right_distrib_moves + abs(snake_case_ ) + abs(snake_case_ ) ) __snake_case = node.data - coins_to_left - coins_to_right return CoinsDistribResult(snake_case_ , snake_case_ ) return get_distrib(snake_case_ )[0] if __name__ == "__main__": import doctest doctest.testmod()
24
'''simple docstring''' def SCREAMING_SNAKE_CASE__ ( __A = 1_000_000 ) -> int: _snake_case = limit + 1 _snake_case = [0] * limit for first_term in range(1 , __A ): for n in range(__A , __A , __A ): _snake_case = first_term + n / first_term if common_difference % 4: # d must be divisble by 4 continue else: common_difference /= 4 if ( first_term > common_difference and first_term < 4 * common_difference ): # since x,y,z are positive integers frequency[n] += 1 # so z>0 and a>d ,also 4d<a _snake_case = sum(1 for x in frequency[1:limit] if x == 10 ) return count if __name__ == "__main__": print(F'''{solution() = }''')
42
0
from __future__ import annotations from collections.abc import Sequence from typing import Literal def lowercase__( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str ): lowercase_ : List[str] = list(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = list(__SCREAMING_SNAKE_CASE ) lowercase_ : Dict = 0 for i in range(len(__SCREAMING_SNAKE_CASE ) ): if lista[i] != lista[i]: count += 1 lowercase_ : List[Any] = '_' if count > 1: return False else: return "".join(__SCREAMING_SNAKE_CASE ) def lowercase__( __SCREAMING_SNAKE_CASE : list[str] ): lowercase_ : List[Any] = [] while True: lowercase_ : Optional[Any] = ['$'] * len(__SCREAMING_SNAKE_CASE ) lowercase_ : int = [] for i in range(len(__SCREAMING_SNAKE_CASE ) ): for j in range(i + 1 , len(__SCREAMING_SNAKE_CASE ) ): lowercase_ : Tuple = compare_string(binary[i] , binary[j] ) if k is False: lowercase_ : List[str] = '*' lowercase_ : Optional[Any] = '*' temp.append('X' ) for i in range(len(__SCREAMING_SNAKE_CASE ) ): if checka[i] == "$": pi.append(binary[i] ) if len(__SCREAMING_SNAKE_CASE ) == 0: return pi lowercase_ : Optional[Any] = list(set(__SCREAMING_SNAKE_CASE ) ) def lowercase__( __SCREAMING_SNAKE_CASE : int , __SCREAMING_SNAKE_CASE : Sequence[float] ): lowercase_ : Any = [] for minterm in minterms: lowercase_ : Union[str, Any] = '' for _ in range(__SCREAMING_SNAKE_CASE ): lowercase_ : Dict = str(minterm % 2 ) + string minterm //= 2 temp.append(__SCREAMING_SNAKE_CASE ) return temp def lowercase__( __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : str , __SCREAMING_SNAKE_CASE : int ): lowercase_ : Dict = list(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = list(__SCREAMING_SNAKE_CASE ) lowercase_ : str = 0 for i in range(len(__SCREAMING_SNAKE_CASE ) ): if lista[i] != lista[i]: count_n += 1 return count_n == count def lowercase__( __SCREAMING_SNAKE_CASE : list[list[int]] , __SCREAMING_SNAKE_CASE : list[str] ): lowercase_ : Tuple = [] lowercase_ : Optional[Any] = [0] * len(__SCREAMING_SNAKE_CASE ) for i in range(len(chart[0] ) ): lowercase_ : int = 0 lowercase_ : Dict = -1 for j in range(len(__SCREAMING_SNAKE_CASE ) ): if chart[j][i] == 1: count += 1 lowercase_ : Union[str, Any] = j if count == 1: lowercase_ : Dict = 1 for i in range(len(__SCREAMING_SNAKE_CASE ) ): if select[i] == 1: for j in range(len(chart[0] ) ): if chart[i][j] == 1: for k in range(len(__SCREAMING_SNAKE_CASE ) ): lowercase_ : List[str] = 0 temp.append(prime_implicants[i] ) while True: lowercase_ : Optional[Any] = 0 lowercase_ : str = -1 lowercase_ : Any = 0 for i in range(len(__SCREAMING_SNAKE_CASE ) ): lowercase_ : Dict = chart[i].count(1 ) if count_n > max_n: lowercase_ : List[str] = count_n lowercase_ : str = i if max_n == 0: return temp temp.append(prime_implicants[rem] ) for i in range(len(chart[0] ) ): if chart[rem][i] == 1: for j in range(len(__SCREAMING_SNAKE_CASE ) ): lowercase_ : List[Any] = 0 def lowercase__( __SCREAMING_SNAKE_CASE : list[str] , __SCREAMING_SNAKE_CASE : list[str] ): lowercase_ : int = [[0 for x in range(len(__SCREAMING_SNAKE_CASE ) )] for x in range(len(__SCREAMING_SNAKE_CASE ) )] for i in range(len(__SCREAMING_SNAKE_CASE ) ): lowercase_ : str = prime_implicants[i].count('_' ) for j in range(len(__SCREAMING_SNAKE_CASE ) ): if is_for_table(prime_implicants[i] , binary[j] , __SCREAMING_SNAKE_CASE ): lowercase_ : Union[str, Any] = 1 return chart def lowercase__( ): lowercase_ : List[Any] = int(input('Enter the no. of variables\n' ) ) lowercase_ : Optional[Any] = [ float(__SCREAMING_SNAKE_CASE ) for x in input( 'Enter the decimal representation of Minterms \'Spaces Separated\'\n' ).split() ] lowercase_ : Optional[int] = decimal_to_binary(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Union[str, Any] = check(__SCREAMING_SNAKE_CASE ) print('Prime Implicants are:' ) print(__SCREAMING_SNAKE_CASE ) lowercase_ : Optional[int] = prime_implicant_chart(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) lowercase_ : Optional[Any] = selection(__SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ) print('Essential Prime Implicants are:' ) print(__SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod() main()
362
"""simple docstring""" class UpperCamelCase : def __init__( self ,__UpperCamelCase ,__UpperCamelCase ) -> int: '''simple docstring''' lowercase_ : List[Any] = name lowercase_ : int = val def __str__( self ) -> Tuple: '''simple docstring''' return f'''{self.__class__.__name__}({self.name}, {self.val})''' def __lt__( self ,__UpperCamelCase ) -> Tuple: '''simple docstring''' return self.val < other.val class UpperCamelCase : def __init__( self ,__UpperCamelCase ) -> Dict: '''simple docstring''' lowercase_ : Optional[int] = {} lowercase_ : Tuple = {} lowercase_ : Union[str, Any] = self.build_heap(__UpperCamelCase ) def __getitem__( self ,__UpperCamelCase ) -> int: '''simple docstring''' return self.get_value(__UpperCamelCase ) def _UpperCAmelCase ( self ,__UpperCamelCase ) -> List[str]: '''simple docstring''' return (idx - 1) // 2 def _UpperCAmelCase ( self ,__UpperCamelCase ) -> Optional[Any]: '''simple docstring''' return idx * 2 + 1 def _UpperCAmelCase ( self ,__UpperCamelCase ) -> Tuple: '''simple docstring''' return idx * 2 + 2 def _UpperCAmelCase ( self ,__UpperCamelCase ) -> List[Any]: '''simple docstring''' return self.heap_dict[key] def _UpperCAmelCase ( self ,__UpperCamelCase ) -> List[str]: '''simple docstring''' lowercase_ : Optional[int] = len(__UpperCamelCase ) - 1 lowercase_ : Optional[int] = self.get_parent_idx(__UpperCamelCase ) for idx, i in enumerate(__UpperCamelCase ): lowercase_ : Any = idx lowercase_ : str = i.val for i in range(__UpperCamelCase ,-1 ,-1 ): self.sift_down(__UpperCamelCase ,__UpperCamelCase ) return array def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ) -> Tuple: '''simple docstring''' while True: lowercase_ : List[str] = self.get_left_child_idx(__UpperCamelCase ) # noqa: E741 lowercase_ : List[str] = self.get_right_child_idx(__UpperCamelCase ) lowercase_ : List[str] = idx if l < len(__UpperCamelCase ) and array[l] < array[idx]: lowercase_ : List[str] = l if r < len(__UpperCamelCase ) and array[r] < array[smallest]: lowercase_ : Dict = r if smallest != idx: lowercase_ , lowercase_ : Union[str, Any] = array[smallest], array[idx] ( ( lowercase_ ) , ( lowercase_ ) , ) : str = ( self.idx_of_element[array[smallest]], self.idx_of_element[array[idx]], ) lowercase_ : Any = smallest else: break def _UpperCAmelCase ( self ,__UpperCamelCase ) -> int: '''simple docstring''' lowercase_ : Dict = self.get_parent_idx(__UpperCamelCase ) while p >= 0 and self.heap[p] > self.heap[idx]: lowercase_ , lowercase_ : Any = self.heap[idx], self.heap[p] lowercase_ , lowercase_ : Tuple = ( self.idx_of_element[self.heap[idx]], self.idx_of_element[self.heap[p]], ) lowercase_ : int = p lowercase_ : str = self.get_parent_idx(__UpperCamelCase ) def _UpperCAmelCase ( self ) -> str: '''simple docstring''' return self.heap[0] def _UpperCAmelCase ( self ) -> Optional[int]: '''simple docstring''' lowercase_ , lowercase_ : Optional[Any] = self.heap[-1], self.heap[0] lowercase_ , lowercase_ : Tuple = ( self.idx_of_element[self.heap[-1]], self.idx_of_element[self.heap[0]], ) lowercase_ : Tuple = self.heap.pop() del self.idx_of_element[x] self.sift_down(0 ,self.heap ) return x def _UpperCAmelCase ( self ,__UpperCamelCase ) -> Dict: '''simple docstring''' self.heap.append(__UpperCamelCase ) lowercase_ : Tuple = len(self.heap ) - 1 lowercase_ : Optional[int] = node.val self.sift_up(len(self.heap ) - 1 ) def _UpperCAmelCase ( self ) -> Optional[Any]: '''simple docstring''' return len(self.heap ) == 0 def _UpperCAmelCase ( self ,__UpperCamelCase ,__UpperCamelCase ) -> List[Any]: '''simple docstring''' assert ( self.heap[self.idx_of_element[node]].val > new_value ), "newValue must be less that current value" lowercase_ : Any = new_value lowercase_ : List[str] = new_value self.sift_up(self.idx_of_element[node] ) __SCREAMING_SNAKE_CASE =Node("R", -1) __SCREAMING_SNAKE_CASE =Node("B", 6) __SCREAMING_SNAKE_CASE =Node("A", 3) __SCREAMING_SNAKE_CASE =Node("X", 1) __SCREAMING_SNAKE_CASE =Node("E", 4) # Use one of these two ways to generate Min-Heap # Generating Min-Heap from array __SCREAMING_SNAKE_CASE =MinHeap([r, b, a, x, e]) # Generating Min-Heap by Insert method # myMinHeap.insert(a) # myMinHeap.insert(b) # myMinHeap.insert(x) # myMinHeap.insert(r) # myMinHeap.insert(e) # Before print("Min Heap - before decrease key") for i in my_min_heap.heap: print(i) print("Min Heap - After decrease key of node [B -> -17]") my_min_heap.decrease_key(b, -17) # After for i in my_min_heap.heap: print(i) if __name__ == "__main__": import doctest doctest.testmod()
321
0
'''simple docstring''' import math import sys def __lowerCAmelCase ( UpperCamelCase__ ) -> str: __lowerCamelCase = '''''' try: with open(UpperCamelCase__ , '''rb''' ) as binary_file: __lowerCamelCase = binary_file.read() for dat in data: __lowerCamelCase = f"""{dat:08b}""" result += curr_byte return result except OSError: print('''File not accessible''' ) sys.exit() def __lowerCAmelCase ( UpperCamelCase__ ) -> str: __lowerCamelCase = {'''0''': '''0''', '''1''': '''1'''} __lowerCamelCase , __lowerCamelCase = '''''', '''''' __lowerCamelCase = len(UpperCamelCase__ ) for i in range(len(UpperCamelCase__ ) ): curr_string += data_bits[i] if curr_string not in lexicon: continue __lowerCamelCase = lexicon[curr_string] result += last_match_id __lowerCamelCase = last_match_id + '''0''' if math.loga(UpperCamelCase__ ).is_integer(): __lowerCamelCase = {} for curr_key in list(UpperCamelCase__ ): __lowerCamelCase = lexicon.pop(UpperCamelCase__ ) __lowerCamelCase = new_lex __lowerCamelCase = last_match_id + '''1''' index += 1 __lowerCamelCase = '''''' return result def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> None: __lowerCamelCase = 8 try: with open(UpperCamelCase__ , '''wb''' ) as opened_file: __lowerCamelCase = [ to_write[i : i + byte_length] for i in range(0 , len(UpperCamelCase__ ) , UpperCamelCase__ ) ] 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(UpperCamelCase__ , 2 ).to_bytes(1 , byteorder='''big''' ) ) except OSError: print('''File not accessible''' ) sys.exit() def __lowerCAmelCase ( UpperCamelCase__ ) -> str: __lowerCamelCase = 0 for letter in data_bits: if letter == "1": break counter += 1 __lowerCamelCase = data_bits[counter:] __lowerCamelCase = data_bits[counter + 1 :] return data_bits def __lowerCAmelCase ( UpperCamelCase__ , UpperCamelCase__ ) -> None: __lowerCamelCase = read_file_binary(UpperCamelCase__ ) __lowerCamelCase = remove_prefix(UpperCamelCase__ ) __lowerCamelCase = decompress_data(UpperCamelCase__ ) write_file_binary(UpperCamelCase__ , UpperCamelCase__ ) if __name__ == "__main__": compress(sys.argv[1], sys.argv[2])
67
import argparse import json import os import time import zipfile from get_ci_error_statistics import download_artifact, get_artifacts_links from transformers import logging _UpperCAmelCase : Optional[int] = logging.get_logger(__name__) def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase ) -> Dict: lowerCamelCase__ : str = set() lowerCamelCase__ : Any = [] def parse_line(_UpperCAmelCase ): for line in fp: if isinstance(_UpperCAmelCase , _UpperCAmelCase ): lowerCamelCase__ : Any = line.decode('UTF-8' ) if "warnings summary (final)" in line: continue # This means we are outside the body of a warning elif not line.startswith(' ' ): # process a single warning and move it to `selected_warnings`. if len(_UpperCAmelCase ) > 0: lowerCamelCase__ : str = '\n'.join(_UpperCAmelCase ) # Only keep the warnings specified in `targets` if any(F""": {x}: """ in warning for x in targets ): selected_warnings.add(_UpperCAmelCase ) buffer.clear() continue else: lowerCamelCase__ : List[str] = line.strip() buffer.append(_UpperCAmelCase ) if from_gh: for filename in os.listdir(_UpperCAmelCase ): lowerCamelCase__ : Dict = os.path.join(_UpperCAmelCase , _UpperCAmelCase ) if not os.path.isdir(_UpperCAmelCase ): # read the file if filename != "warnings.txt": continue with open(_UpperCAmelCase ) as fp: parse_line(_UpperCAmelCase ) else: try: with zipfile.ZipFile(_UpperCAmelCase ) as z: for filename in z.namelist(): if not os.path.isdir(_UpperCAmelCase ): # read the file if filename != "warnings.txt": continue with z.open(_UpperCAmelCase ) as fp: parse_line(_UpperCAmelCase ) except Exception: logger.warning( F"""{artifact_path} is either an invalid zip file or something else wrong. This file is skipped.""" ) return selected_warnings def SCREAMING_SNAKE_CASE ( _UpperCAmelCase , _UpperCAmelCase ) -> Union[str, Any]: lowerCamelCase__ : Tuple = set() lowerCamelCase__ : Optional[int] = [os.path.join(_UpperCAmelCase , _UpperCAmelCase ) for p in os.listdir(_UpperCAmelCase ) if (p.endswith('.zip' ) or from_gh)] for p in paths: selected_warnings.update(extract_warnings_from_single_artifact(_UpperCAmelCase , _UpperCAmelCase ) ) return selected_warnings if __name__ == "__main__": def SCREAMING_SNAKE_CASE ( _UpperCAmelCase ) -> Tuple: return values.split(',' ) _UpperCAmelCase : List[str] = argparse.ArgumentParser() # Required parameters parser.add_argument("""--workflow_run_id""", type=str, required=True, help="""A GitHub Actions workflow run id.""") parser.add_argument( """--output_dir""", type=str, required=True, help="""Where to store the downloaded artifacts and other result files.""", ) parser.add_argument("""--token""", default=None, type=str, help="""A token that has actions:read permission.""") # optional parameters parser.add_argument( """--targets""", default="""DeprecationWarning,UserWarning,FutureWarning""", type=list_str, help="""Comma-separated list of target warning(s) which we want to extract.""", ) parser.add_argument( """--from_gh""", action="""store_true""", help="""If running from a GitHub action workflow and collecting warnings from its artifacts.""", ) _UpperCAmelCase : Union[str, Any] = parser.parse_args() _UpperCAmelCase : Dict = args.from_gh if from_gh: # The artifacts have to be downloaded using `actions/download-artifact@v3` pass else: os.makedirs(args.output_dir, exist_ok=True) # get download links _UpperCAmelCase : Union[str, Any] = get_artifacts_links(args.workflow_run_id, token=args.token) with open(os.path.join(args.output_dir, """artifacts.json"""), """w""", encoding="""UTF-8""") as fp: json.dump(artifacts, fp, ensure_ascii=False, indent=4) # download artifacts for idx, (name, url) in enumerate(artifacts.items()): print(name) print(url) print("""=""" * 80) download_artifact(name, url, args.output_dir, args.token) # Be gentle to GitHub time.sleep(1) # extract warnings from artifacts _UpperCAmelCase : Dict = extract_warnings(args.output_dir, args.targets) _UpperCAmelCase : Optional[Any] = sorted(selected_warnings) with open(os.path.join(args.output_dir, """selected_warnings.json"""), """w""", encoding="""UTF-8""") as fp: json.dump(selected_warnings, fp, ensure_ascii=False, indent=4)
50
0
'''simple docstring''' import copy from typing import Dict, List, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING UpperCAmelCase = { 'facebook/mask2former-swin-small-coco-instance': ( 'https://huggingface.co/facebook/mask2former-swin-small-coco-instance/blob/main/config.json' ) # See all Mask2Former models at https://huggingface.co/models?filter=mask2former } UpperCAmelCase = logging.get_logger(__name__) class __snake_case( _lowerCAmelCase ): '''simple docstring''' UpperCAmelCase : Dict = "mask2former" UpperCAmelCase : Union[str, Any] = ["swin"] UpperCAmelCase : Optional[Any] = {"hidden_size": "hidden_dim"} def __init__( self , A_ = None , A_ = 256 , A_ = 256 , A_ = 256 , A_ = 1024 , A_ = "relu" , A_ = 6 , A_ = 10 , A_ = 8 , A_ = 0.0 , A_ = 2048 , A_ = False , A_ = False , A_ = 4 , A_ = 255 , A_ = 100 , A_ = 0.1 , A_ = 2.0 , A_ = 5.0 , A_ = 5.0 , A_ = 1_2544 , A_ = 3.0 , A_ = 0.7_5 , A_ = 0.0_2 , A_ = 1.0 , A_ = True , A_ = [4, 8, 16, 32] , A_ = None , **A_ , ) -> List[Any]: if backbone_config is None: logger.info("""`backbone_config` is `None`. Initializing the config with the default `Swin` backbone.""" ) lowerCAmelCase = CONFIG_MAPPING["""swin"""]( image_size=224 , in_channels=3 , patch_size=4 , embed_dim=96 , depths=[2, 2, 18, 2] , num_heads=[3, 6, 12, 24] , window_size=7 , drop_path_rate=0.3 , use_absolute_embeddings=A_ , out_features=["""stage1""", """stage2""", """stage3""", """stage4"""] , ) if isinstance(A_ , A_ ): lowerCAmelCase = backbone_config.pop("""model_type""" ) lowerCAmelCase = CONFIG_MAPPING[backbone_model_type] lowerCAmelCase = config_class.from_dict(A_ ) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( f'Backbone {backbone_config.model_type} is not a supported model and may not be compatible with Mask2Former. ' f'Supported model types: {",".join(self.backbones_supported )}' ) lowerCAmelCase = backbone_config lowerCAmelCase = feature_size lowerCAmelCase = mask_feature_size lowerCAmelCase = hidden_dim lowerCAmelCase = encoder_feedforward_dim lowerCAmelCase = activation_function lowerCAmelCase = encoder_layers lowerCAmelCase = decoder_layers lowerCAmelCase = num_attention_heads lowerCAmelCase = dropout lowerCAmelCase = dim_feedforward lowerCAmelCase = pre_norm lowerCAmelCase = enforce_input_projection lowerCAmelCase = common_stride lowerCAmelCase = ignore_value lowerCAmelCase = num_queries lowerCAmelCase = no_object_weight lowerCAmelCase = class_weight lowerCAmelCase = mask_weight lowerCAmelCase = dice_weight lowerCAmelCase = train_num_points lowerCAmelCase = oversample_ratio lowerCAmelCase = importance_sample_ratio lowerCAmelCase = init_std lowerCAmelCase = init_xavier_std lowerCAmelCase = use_auxiliary_loss lowerCAmelCase = feature_strides lowerCAmelCase = output_auxiliary_logits lowerCAmelCase = decoder_layers super().__init__(**A_ ) @classmethod def __snake_case ( cls , A_ , **A_ ) -> Tuple: return cls( backbone_config=A_ , **A_ , ) def __snake_case ( self ) -> Dict[str, any]: lowerCAmelCase = copy.deepcopy(self.__dict__ ) lowerCAmelCase = self.backbone_config.to_dict() lowerCAmelCase = self.__class__.model_type return output
187
'''simple docstring''' from __future__ import annotations import pandas as pd def _snake_case ( _SCREAMING_SNAKE_CASE : list[int] , _SCREAMING_SNAKE_CASE : list[int] , _SCREAMING_SNAKE_CASE : int ) -> list[int]: """simple docstring""" lowerCAmelCase = [0] * no_of_processes lowerCAmelCase = [0] * no_of_processes # Copy the burst time into remaining_time[] for i in range(_SCREAMING_SNAKE_CASE ): lowerCAmelCase = burst_time[i] lowerCAmelCase = 0 lowerCAmelCase = 0 lowerCAmelCase = 999_999_999 lowerCAmelCase = 0 lowerCAmelCase = False # Process until all processes are completed while complete != no_of_processes: for j in range(_SCREAMING_SNAKE_CASE ): if arrival_time[j] <= increment_time and remaining_time[j] > 0: if remaining_time[j] < minm: lowerCAmelCase = remaining_time[j] lowerCAmelCase = j lowerCAmelCase = True if not check: increment_time += 1 continue remaining_time[short] -= 1 lowerCAmelCase = remaining_time[short] if minm == 0: lowerCAmelCase = 999_999_999 if remaining_time[short] == 0: complete += 1 lowerCAmelCase = False # Find finish time of current process lowerCAmelCase = increment_time + 1 # Calculate waiting time lowerCAmelCase = finish_time - arrival_time[short] lowerCAmelCase = finar - burst_time[short] if waiting_time[short] < 0: lowerCAmelCase = 0 # Increment time increment_time += 1 return waiting_time def _snake_case ( _SCREAMING_SNAKE_CASE : list[int] , _SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : list[int] ) -> list[int]: """simple docstring""" lowerCAmelCase = [0] * no_of_processes for i in range(_SCREAMING_SNAKE_CASE ): lowerCAmelCase = burst_time[i] + waiting_time[i] return turn_around_time def _snake_case ( _SCREAMING_SNAKE_CASE : list[int] , _SCREAMING_SNAKE_CASE : list[int] , _SCREAMING_SNAKE_CASE : int ) -> None: """simple docstring""" lowerCAmelCase = 0 lowerCAmelCase = 0 for i in range(_SCREAMING_SNAKE_CASE ): lowerCAmelCase = total_waiting_time + waiting_time[i] lowerCAmelCase = total_turn_around_time + turn_around_time[i] print(f'Average waiting time = {total_waiting_time / no_of_processes:.5f}' ) print("""Average turn around time =""" , total_turn_around_time / no_of_processes ) if __name__ == "__main__": print('Enter how many process you want to analyze') UpperCAmelCase = int(input()) UpperCAmelCase = [0] * no_of_processes UpperCAmelCase = [0] * no_of_processes UpperCAmelCase = list(range(1, no_of_processes + 1)) for i in range(no_of_processes): print('Enter the arrival time and burst time for process:--' + str(i + 1)) UpperCAmelCase , UpperCAmelCase = map(int, input().split()) UpperCAmelCase = calculate_waitingtime(arrival_time, burst_time, no_of_processes) UpperCAmelCase = burst_time UpperCAmelCase = no_of_processes UpperCAmelCase = waiting_time UpperCAmelCase = calculate_turnaroundtime(bt, n, wt) calculate_average_times(waiting_time, turn_around_time, no_of_processes) UpperCAmelCase = pd.DataFrame( list(zip(processes, burst_time, arrival_time, waiting_time, turn_around_time)), columns=[ 'Process', 'BurstTime', 'ArrivalTime', 'WaitingTime', 'TurnAroundTime', ], ) # Printing the dataFrame pd.set_option('display.max_rows', fcfs.shape[0] + 1) print(fcfs)
187
1
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCamelCase : Optional[int] = {"""configuration_mmbt""": ["""MMBTConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : List[Any] = ["""MMBTForClassification""", """MMBTModel""", """ModalEmbeddings"""] if TYPE_CHECKING: from .configuration_mmbt import MMBTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings else: import sys __lowerCamelCase : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
52
import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class A ( _UpperCAmelCase ): """simple docstring""" lowerCamelCase = (DPMSolverSinglestepScheduler,) lowerCamelCase = (('num_inference_steps', 25),) def snake_case__ ( self : Tuple,**lowercase_ : Dict )-> Optional[int]: '''simple docstring''' A__ = { 'num_train_timesteps': 1_0_0_0, 'beta_start': 0.0_001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'solver_order': 2, 'prediction_type': 'epsilon', 'thresholding': False, 'sample_max_value': 1.0, 'algorithm_type': 'dpmsolver++', 'solver_type': 'midpoint', 'lambda_min_clipped': -float('inf' ), 'variance_type': None, } config.update(**lowercase_ ) return config def snake_case__ ( self : str,lowercase_ : Optional[Any]=0,**lowercase_ : Any )-> List[Any]: '''simple docstring''' A__ = dict(self.forward_default_kwargs ) A__ = kwargs.pop('num_inference_steps',lowercase_ ) A__ = self.dummy_sample A__ = 0.1 * sample A__ = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: A__ = self.get_scheduler_config(**lowercase_ ) A__ = scheduler_class(**lowercase_ ) scheduler.set_timesteps(lowercase_ ) # copy over dummy past residuals A__ = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowercase_ ) A__ = scheduler_class.from_pretrained(lowercase_ ) new_scheduler.set_timesteps(lowercase_ ) # copy over dummy past residuals A__ = dummy_past_residuals[: new_scheduler.config.solver_order] A__ , A__ = sample, sample for t in range(lowercase_,time_step + scheduler.config.solver_order + 1 ): A__ = scheduler.step(lowercase_,lowercase_,lowercase_,**lowercase_ ).prev_sample A__ = new_scheduler.step(lowercase_,lowercase_,lowercase_,**lowercase_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def snake_case__ ( self : List[str] )-> List[Any]: '''simple docstring''' pass def snake_case__ ( self : Tuple,lowercase_ : Union[str, Any]=0,**lowercase_ : Union[str, Any] )-> Union[str, Any]: '''simple docstring''' A__ = dict(self.forward_default_kwargs ) A__ = kwargs.pop('num_inference_steps',lowercase_ ) A__ = self.dummy_sample A__ = 0.1 * sample A__ = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: A__ = self.get_scheduler_config() A__ = scheduler_class(**lowercase_ ) scheduler.set_timesteps(lowercase_ ) # copy over dummy past residuals (must be after setting timesteps) A__ = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(lowercase_ ) A__ = scheduler_class.from_pretrained(lowercase_ ) # copy over dummy past residuals new_scheduler.set_timesteps(lowercase_ ) # copy over dummy past residual (must be after setting timesteps) A__ = dummy_past_residuals[: new_scheduler.config.solver_order] A__ = scheduler.step(lowercase_,lowercase_,lowercase_,**lowercase_ ).prev_sample A__ = new_scheduler.step(lowercase_,lowercase_,lowercase_,**lowercase_ ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1E-5, "Scheduler outputs are not identical" def snake_case__ ( self : Optional[Any],lowercase_ : Optional[int]=None,**lowercase_ : int )-> int: '''simple docstring''' if scheduler is None: A__ = self.scheduler_classes[0] A__ = self.get_scheduler_config(**lowercase_ ) A__ = scheduler_class(**lowercase_ ) A__ = self.scheduler_classes[0] A__ = self.get_scheduler_config(**lowercase_ ) A__ = scheduler_class(**lowercase_ ) A__ = 1_0 A__ = self.dummy_model() A__ = self.dummy_sample_deter scheduler.set_timesteps(lowercase_ ) for i, t in enumerate(scheduler.timesteps ): A__ = model(lowercase_,lowercase_ ) A__ = scheduler.step(lowercase_,lowercase_,lowercase_ ).prev_sample return sample def snake_case__ ( self : Any )-> str: '''simple docstring''' A__ = DPMSolverSinglestepScheduler(**self.get_scheduler_config() ) A__ = 5_0 A__ = self.dummy_model() A__ = self.dummy_sample_deter scheduler.set_timesteps(lowercase_ ) # make sure that the first t is uneven for i, t in enumerate(scheduler.timesteps[3:] ): A__ = model(lowercase_,lowercase_ ) A__ = scheduler.step(lowercase_,lowercase_,lowercase_ ).prev_sample A__ = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_mean.item() - 0.2_574 ) < 1E-3 def snake_case__ ( self : Optional[Any] )-> List[Any]: '''simple docstring''' for timesteps in [2_5, 5_0, 1_0_0, 9_9_9, 1_0_0_0]: self.check_over_configs(num_train_timesteps=lowercase_ ) def snake_case__ ( self : int )-> Optional[Any]: '''simple docstring''' A__ = DPMSolverSinglestepScheduler(**self.get_scheduler_config() ) A__ = self.full_loop(scheduler=lowercase_ ) A__ = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_mean.item() - 0.2_791 ) < 1E-3 A__ = DEISMultistepScheduler.from_config(scheduler.config ) A__ = DPMSolverMultistepScheduler.from_config(scheduler.config ) A__ = UniPCMultistepScheduler.from_config(scheduler.config ) A__ = DPMSolverSinglestepScheduler.from_config(scheduler.config ) A__ = self.full_loop(scheduler=lowercase_ ) A__ = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_mean.item() - 0.2_791 ) < 1E-3 def snake_case__ ( self : Tuple )-> Any: '''simple docstring''' self.check_over_configs(thresholding=lowercase_ ) for order in [1, 2, 3]: for solver_type in ["midpoint", "heun"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=lowercase_,prediction_type=lowercase_,sample_max_value=lowercase_,algorithm_type='dpmsolver++',solver_order=lowercase_,solver_type=lowercase_,) def snake_case__ ( self : List[Any] )-> int: '''simple docstring''' for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=lowercase_ ) def snake_case__ ( self : Dict )-> List[Any]: '''simple docstring''' for algorithm_type in ["dpmsolver", "dpmsolver++"]: for solver_type in ["midpoint", "heun"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=lowercase_,solver_type=lowercase_,prediction_type=lowercase_,algorithm_type=lowercase_,) A__ = self.full_loop( solver_order=lowercase_,solver_type=lowercase_,prediction_type=lowercase_,algorithm_type=lowercase_,) assert not torch.isnan(lowercase_ ).any(), "Samples have nan numbers" def snake_case__ ( self : Optional[int] )-> Tuple: '''simple docstring''' self.check_over_configs(lower_order_final=lowercase_ ) self.check_over_configs(lower_order_final=lowercase_ ) def snake_case__ ( self : Tuple )-> Optional[int]: '''simple docstring''' self.check_over_configs(lambda_min_clipped=-float('inf' ) ) self.check_over_configs(lambda_min_clipped=-5.1 ) def snake_case__ ( self : Optional[Any] )-> Tuple: '''simple docstring''' self.check_over_configs(variance_type=lowercase_ ) self.check_over_configs(variance_type='learned_range' ) def snake_case__ ( self : str )-> Any: '''simple docstring''' for num_inference_steps in [1, 2, 3, 5, 1_0, 5_0, 1_0_0, 9_9_9, 1_0_0_0]: self.check_over_forward(num_inference_steps=lowercase_,time_step=0 ) def snake_case__ ( self : Tuple )-> Tuple: '''simple docstring''' A__ = self.full_loop() A__ = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_mean.item() - 0.2_791 ) < 1E-3 def snake_case__ ( self : Any )-> Union[str, Any]: '''simple docstring''' A__ = self.full_loop(use_karras_sigmas=lowercase_ ) A__ = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_mean.item() - 0.2_248 ) < 1E-3 def snake_case__ ( self : Union[str, Any] )-> Tuple: '''simple docstring''' A__ = self.full_loop(prediction_type='v_prediction' ) A__ = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_mean.item() - 0.1_453 ) < 1E-3 def snake_case__ ( self : Tuple )-> int: '''simple docstring''' A__ = self.full_loop(prediction_type='v_prediction',use_karras_sigmas=lowercase_ ) A__ = torch.mean(torch.abs(lowercase_ ) ) assert abs(result_mean.item() - 0.0_649 ) < 1E-3 def snake_case__ ( self : List[Any] )-> int: '''simple docstring''' A__ = self.scheduler_classes[0] A__ = self.get_scheduler_config(thresholding=lowercase_,dynamic_thresholding_ratio=0 ) A__ = scheduler_class(**lowercase_ ) A__ = 1_0 A__ = self.dummy_model() A__ = self.dummy_sample_deter.half() scheduler.set_timesteps(lowercase_ ) for i, t in enumerate(scheduler.timesteps ): A__ = model(lowercase_,lowercase_ ) A__ = scheduler.step(lowercase_,lowercase_,lowercase_ ).prev_sample assert sample.dtype == torch.floataa
7
0
import importlib import inspect import os import re # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py lowerCamelCase_ = '''src/transformers''' # This is to make sure the transformers module imported is the one in the repo. lowerCamelCase_ = importlib.util.spec_from_file_location( '''transformers''', os.path.join(PATH_TO_TRANSFORMERS, '''__init__.py'''), submodule_search_locations=[PATH_TO_TRANSFORMERS], ) lowerCamelCase_ = spec.loader.load_module() lowerCamelCase_ = transformers.models.auto.configuration_auto.CONFIG_MAPPING # Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`. # For example, `[bert-base-uncased](https://huggingface.co/bert-base-uncased)` lowerCamelCase_ = re.compile('''\[(.+?)\]\((https://huggingface\.co/.+?)\)''') lowerCamelCase_ = { '''CLIPConfigMixin''', '''DecisionTransformerConfigMixin''', '''EncoderDecoderConfigMixin''', '''RagConfigMixin''', '''SpeechEncoderDecoderConfigMixin''', '''VisionEncoderDecoderConfigMixin''', '''VisionTextDualEncoderConfigMixin''', } def __magic_name__ ( ): '''simple docstring''' UpperCamelCase__ = [] for config_class in list(CONFIG_MAPPING.values() ): UpperCamelCase__ = False # source code of `config_class` UpperCamelCase__ = inspect.getsource(__a ) UpperCamelCase__ = _re_checkpoint.findall(__a ) for checkpoint in checkpoints: # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. # For example, `('bert-base-uncased', 'https://huggingface.co/bert-base-uncased')` UpperCamelCase__ , UpperCamelCase__ = checkpoint # verify the checkpoint name corresponds to the checkpoint link UpperCamelCase__ = f"https://huggingface.co/{ckpt_name}" if ckpt_link == ckpt_link_from_name: UpperCamelCase__ = True break UpperCamelCase__ = config_class.__name__ if not checkpoint_found and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: configs_without_checkpoint.append(__a ) if len(__a ) > 0: UpperCamelCase__ = """\n""".join(sorted(__a ) ) raise ValueError(f"The following configurations don't contain any valid checkpoint:\n{message}" ) if __name__ == "__main__": check_config_docstrings_have_checkpoints()
358
import argparse from collections import defaultdict import yaml lowerCamelCase_ = '''docs/source/en/_toctree.yml''' def __magic_name__ ( __a : Union[str, Any] ): '''simple docstring''' UpperCamelCase__ = defaultdict(__a ) for doc in model_doc: counts[doc["local"]] += 1 UpperCamelCase__ = [key for key, value in counts.items() if value > 1] UpperCamelCase__ = [] for duplicate_key in duplicates: UpperCamelCase__ = list({doc["""title"""] for doc in model_doc if doc["""local"""] == duplicate_key} ) if len(__a ) > 1: raise ValueError( f"{duplicate_key} is present several times in the documentation table of content at " """`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the """ """others.""" ) # Only add this once new_doc.append({"""local""": duplicate_key, """title""": titles[0]} ) # Add none duplicate-keys new_doc.extend([doc for doc in model_doc if counts[doc["""local"""]] == 1] ) # Sort return sorted(__a , key=lambda __a : s["title"].lower() ) def __magic_name__ ( __a : int=False ): '''simple docstring''' with open(__a , encoding="""utf-8""" ) as f: UpperCamelCase__ = yaml.safe_load(f.read() ) # Get to the API doc UpperCamelCase__ = 0 while content[api_idx]["title"] != "API": api_idx += 1 UpperCamelCase__ = content[api_idx]["""sections"""] # Then to the model doc UpperCamelCase__ = 0 while api_doc[model_idx]["title"] != "Models": model_idx += 1 UpperCamelCase__ = api_doc[model_idx]["""sections"""] UpperCamelCase__ = [(idx, section) for idx, section in enumerate(__a ) if """sections""" in section] UpperCamelCase__ = False for idx, modality_doc in modalities_docs: UpperCamelCase__ = modality_doc["""sections"""] UpperCamelCase__ = clean_model_doc_toc(__a ) if old_modality_doc != new_modality_doc: UpperCamelCase__ = True if overwrite: UpperCamelCase__ = new_modality_doc if diff: if overwrite: UpperCamelCase__ = model_doc UpperCamelCase__ = api_doc with open(__a , """w""" , encoding="""utf-8""" ) as f: f.write(yaml.dump(__a , allow_unicode=__a ) ) else: raise ValueError( """The model doc part of the table of content is not properly sorted, run `make style` to fix this.""" ) if __name__ == "__main__": lowerCamelCase_ = argparse.ArgumentParser() parser.add_argument('''--fix_and_overwrite''', action='''store_true''', help='''Whether to fix inconsistencies.''') lowerCamelCase_ = parser.parse_args() check_model_doc(args.fix_and_overwrite)
178
0
'''simple docstring''' def snake_case_ ( SCREAMING_SNAKE_CASE__ ): """simple docstring""" _SCREAMING_SNAKE_CASE : Union[str, Any] = len(SCREAMING_SNAKE_CASE__ ) for i in range(SCREAMING_SNAKE_CASE__ ): for j in range(i + 1 , SCREAMING_SNAKE_CASE__ ): if numbers[j] < numbers[i]: _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[str] = numbers[j], numbers[i] return numbers if __name__ == "__main__": UpperCAmelCase_ : Any = input('Enter numbers separated by a comma:\n').strip() UpperCAmelCase_ : Dict = [int(item) for item in user_input.split(',')] print(exchange_sort(unsorted))
200
'''simple docstring''' import inspect import unittest from transformers import RegNetConfig, is_flax_available from transformers.testing_utils import require_flax, slow from transformers.utils import cached_property, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor if is_flax_available(): import jax import jax.numpy as jnp from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class lowercase__ ( unittest.TestCase ): '''simple docstring''' def __init__( self , __snake_case , __snake_case=3 , __snake_case=32 , __snake_case=3 , __snake_case=10 , __snake_case=[10, 20, 30, 40] , __snake_case=[1, 1, 2, 1] , __snake_case=True , __snake_case=True , __snake_case="relu" , __snake_case=3 , __snake_case=None , ): _SCREAMING_SNAKE_CASE : Union[str, Any] = parent _SCREAMING_SNAKE_CASE : Dict = batch_size _SCREAMING_SNAKE_CASE : int = image_size _SCREAMING_SNAKE_CASE : Any = num_channels _SCREAMING_SNAKE_CASE : Optional[int] = embeddings_size _SCREAMING_SNAKE_CASE : Tuple = hidden_sizes _SCREAMING_SNAKE_CASE : str = depths _SCREAMING_SNAKE_CASE : str = is_training _SCREAMING_SNAKE_CASE : Any = use_labels _SCREAMING_SNAKE_CASE : Dict = hidden_act _SCREAMING_SNAKE_CASE : int = num_labels _SCREAMING_SNAKE_CASE : str = scope _SCREAMING_SNAKE_CASE : Any = len(__snake_case ) def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : List[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) _SCREAMING_SNAKE_CASE : Any = self.get_config() return config, pixel_values def UpperCAmelCase_ ( self ): return RegNetConfig( num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , image_size=self.image_size , ) def UpperCAmelCase_ ( self , __snake_case , __snake_case ): _SCREAMING_SNAKE_CASE : List[str] = FlaxRegNetModel(config=__snake_case ) _SCREAMING_SNAKE_CASE : Optional[int] = model(__snake_case ) # Output shape (b, c, h, w) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , ) def UpperCAmelCase_ ( self , __snake_case , __snake_case ): _SCREAMING_SNAKE_CASE : Tuple = self.num_labels _SCREAMING_SNAKE_CASE : List[Any] = FlaxRegNetForImageClassification(config=__snake_case ) _SCREAMING_SNAKE_CASE : Tuple = model(__snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : List[Any] = self.prepare_config_and_inputs() _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : List[Any] = config_and_inputs _SCREAMING_SNAKE_CASE : Dict = {"""pixel_values""": pixel_values} return config, inputs_dict @require_flax class lowercase__ ( _snake_case , unittest.TestCase ): '''simple docstring''' A_ : Dict = (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else () A_ : Union[str, Any] = False A_ : List[str] = False A_ : str = False def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : str = FlaxRegNetModelTester(self ) _SCREAMING_SNAKE_CASE : Any = ConfigTester(self , config_class=__snake_case , has_text_modality=__snake_case ) def UpperCAmelCase_ ( self ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCAmelCase_ ( self ): return def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : int = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__snake_case ) def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : Tuple = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__snake_case ) @unittest.skip(reason="""RegNet does not use inputs_embeds""" ) def UpperCAmelCase_ ( self ): pass @unittest.skip(reason="""RegNet does not support input and output embeddings""" ) def UpperCAmelCase_ ( self ): pass def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Optional[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(__snake_case ) _SCREAMING_SNAKE_CASE : Union[str, Any] = inspect.signature(model.__call__ ) # signature.parameters is an OrderedDict => so arg_names order is deterministic _SCREAMING_SNAKE_CASE : int = [*signature.parameters.keys()] _SCREAMING_SNAKE_CASE : Tuple = ["""pixel_values"""] self.assertListEqual(arg_names[:1] , __snake_case ) def UpperCAmelCase_ ( self ): def check_hidden_states_output(__snake_case , __snake_case , __snake_case ): _SCREAMING_SNAKE_CASE : Any = model_class(__snake_case ) _SCREAMING_SNAKE_CASE : int = model(**self._prepare_for_class(__snake_case , __snake_case ) ) _SCREAMING_SNAKE_CASE : Dict = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states _SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.num_stages self.assertEqual(len(__snake_case ) , expected_num_stages + 1 ) _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: _SCREAMING_SNAKE_CASE : Optional[int] = True check_hidden_states_output(__snake_case , __snake_case , __snake_case ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] _SCREAMING_SNAKE_CASE : Union[str, Any] = True check_hidden_states_output(__snake_case , __snake_case , __snake_case ) def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): _SCREAMING_SNAKE_CASE : List[Any] = self._prepare_for_class(__snake_case , __snake_case ) _SCREAMING_SNAKE_CASE : str = model_class(__snake_case ) @jax.jit def model_jitted(__snake_case , **__snake_case ): return model(pixel_values=__snake_case , **__snake_case ) with self.subTest("""JIT Enabled""" ): _SCREAMING_SNAKE_CASE : Any = model_jitted(**__snake_case ).to_tuple() with self.subTest("""JIT Disabled""" ): with jax.disable_jit(): _SCREAMING_SNAKE_CASE : Optional[int] = model_jitted(**__snake_case ).to_tuple() self.assertEqual(len(__snake_case ) , len(__snake_case ) ) for jitted_output, output in zip(__snake_case , __snake_case ): self.assertEqual(jitted_output.shape , output.shape ) def snake_case_ ( ): """simple docstring""" _SCREAMING_SNAKE_CASE : List[str] = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" ) return image @require_flax class lowercase__ ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCAmelCase_ ( self ): return AutoImageProcessor.from_pretrained("""facebook/regnet-y-040""" ) if is_vision_available() else None @slow def UpperCAmelCase_ ( self ): _SCREAMING_SNAKE_CASE : Any = FlaxRegNetForImageClassification.from_pretrained("""facebook/regnet-y-040""" ) _SCREAMING_SNAKE_CASE : List[Any] = self.default_image_processor _SCREAMING_SNAKE_CASE : Optional[Any] = prepare_img() _SCREAMING_SNAKE_CASE : Tuple = image_processor(images=__snake_case , return_tensors="""np""" ) _SCREAMING_SNAKE_CASE : str = model(**__snake_case ) # verify the logits _SCREAMING_SNAKE_CASE : Tuple = (1, 1000) self.assertEqual(outputs.logits.shape , __snake_case ) _SCREAMING_SNAKE_CASE : List[Any] = jnp.array([-0.4180, -1.5051, -3.4836] ) self.assertTrue(jnp.allclose(outputs.logits[0, :3] , __snake_case , atol=1e-4 ) )
200
1
'''simple docstring''' import colorsys from PIL import Image # type: ignore def a ( __a , __a , __a ) -> float: '''simple docstring''' UpperCamelCase__ :Dict = x UpperCamelCase__ :str = y for step in range(__a ): # noqa: B007 UpperCamelCase__ :List[Any] = a * a - b * b + x UpperCamelCase__ :Any = 2 * a * b + y UpperCamelCase__ :Optional[Any] = a_new # divergence happens for all complex number with an absolute value # greater than 4 if a * a + b * b > 4: break return step / (max_step - 1) def a ( __a ) -> tuple: '''simple docstring''' if distance == 1: return (0, 0, 0) else: return (255, 255, 255) def a ( __a ) -> tuple: '''simple docstring''' if distance == 1: return (0, 0, 0) else: return tuple(round(i * 255 ) for i in colorsys.hsv_to_rgb(__a , 1 , 1 ) ) def a ( __a = 800 , __a = 600 , __a = -0.6 , __a = 0 , __a = 3.2 , __a = 50 , __a = True , ) -> Image.Image: '''simple docstring''' UpperCamelCase__ :List[Any] = Image.new('''RGB''' , (image_width, image_height) ) UpperCamelCase__ :str = img.load() # loop through the image-coordinates for image_x in range(__a ): for image_y in range(__a ): # determine the figure-coordinates based on the image-coordinates UpperCamelCase__ :Union[str, Any] = figure_width / image_width * image_height UpperCamelCase__ :Any = figure_center_x + (image_x / image_width - 0.5) * figure_width UpperCamelCase__ :int = figure_center_y + (image_y / image_height - 0.5) * figure_height UpperCamelCase__ :Dict = get_distance(__a , __a , __a ) # color the corresponding pixel based on the selected coloring-function if use_distance_color_coding: UpperCamelCase__ :Dict = get_color_coded_rgb(__a ) else: UpperCamelCase__ :Dict = get_black_and_white_rgb(__a ) return img if __name__ == "__main__": import doctest doctest.testmod() # colored version, full figure __snake_case = get_image() # uncomment for colored version, different section, zoomed in # img = get_image(figure_center_x = -0.6, figure_center_y = -0.4, # figure_width = 0.8) # uncomment for black and white version, full figure # img = get_image(use_distance_color_coding = False) # uncomment to save the image # img.save("mandelbrot.png") img.show()
360
'''simple docstring''' # tests directory-specific settings - this file is run automatically # by pytest before any tests are run import sys import warnings from os.path import abspath, dirname, join # allow having multiple repository checkouts and not needing to remember to rerun # 'pip install -e .[dev]' when switching between checkouts and running tests. __snake_case = abspath(join(dirname(dirname(__file__)), '''src''')) sys.path.insert(1, git_repo_path) # silence FutureWarning warnings in tests since often we can't act on them until # they become normal warnings - i.e. the tests still need to test the current functionality warnings.simplefilter(action='''ignore''', category=FutureWarning) def a ( __a ) -> Optional[int]: '''simple docstring''' from diffusers.utils.testing_utils import pytest_addoption_shared pytest_addoption_shared(__a ) def a ( __a ) -> str: '''simple docstring''' from diffusers.utils.testing_utils import pytest_terminal_summary_main UpperCamelCase__ :Union[str, Any] = terminalreporter.config.getoption('''--make-reports''' ) if make_reports: pytest_terminal_summary_main(__a , id=__a )
219
0